From 6805b182e40e556c9fb4f2fcbe7c8151dc3ad9fc Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Sun, 14 Dec 2025 15:07:20 -0800 Subject: [PATCH 01/22] feat: add visual keyboard layout editor and cheatsheet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a visual keyboard interface for both editing and viewing shortcuts: - Keyboard Editor: A new Settings tab that displays a full QWERTY keyboard. Click any key to add or edit actions and groups directly on the layout. - Keyboard Cheatsheet: An alternative to the list-style cheatsheet that shows your bindings overlaid on a keyboard. Toggle between styles in preferences. Technical Details: - New KeyboardLayout module: KeyboardLayoutModel, KeyboardLayoutView, KeyView - KeyboardCheatsheetView for overlay display of bindings - KeyboardPane settings tab with unified editor for actions and groups - Modifier key monitoring in Controller for real-time shift state - Cheatsheet style preference stored in UserDefaults - Extracted reusable components: KeyBadge, CheatsheetRows πŸ€– Generated with assistance from [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- Leader Key.xcodeproj/project.pbxproj | 44 + Leader Key/AppDelegate.swift | 7 + Leader Key/Cheatsheet.swift | 240 ++--- Leader Key/Cheatsheet/CheatsheetRows.swift | 84 ++ Leader Key/Cheatsheet/KeyBadge.swift | 16 + Leader Key/Controller.swift | 142 ++- Leader Key/Defaults.swift | 7 + Leader Key/KeyboardLayout/KeyView.swift | 163 ++++ .../KeyboardCheatsheetView.swift | 73 ++ .../KeyboardLayout/KeyboardLayoutModel.swift | 174 ++++ .../KeyboardLayout/KeyboardLayoutView.swift | 67 ++ Leader Key/Settings.swift | 1 + Leader Key/Settings/AdvancedPane.swift | 21 + Leader Key/Settings/KeyboardPane.swift | 845 ++++++++++++++++++ Leader Key/Themes/Cheater.swift | 2 +- Leader Key/URLSchemeHandler.swift | 4 +- Leader Key/UserConfig.swift | 37 + Leader Key/UserState.swift | 10 + 18 files changed, 1756 insertions(+), 181 deletions(-) create mode 100644 Leader Key/Cheatsheet/CheatsheetRows.swift create mode 100644 Leader Key/Cheatsheet/KeyBadge.swift create mode 100644 Leader Key/KeyboardLayout/KeyView.swift create mode 100644 Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift create mode 100644 Leader Key/KeyboardLayout/KeyboardLayoutModel.swift create mode 100644 Leader Key/KeyboardLayout/KeyboardLayoutView.swift create mode 100644 Leader Key/Settings/KeyboardPane.swift diff --git a/Leader Key.xcodeproj/project.pbxproj b/Leader Key.xcodeproj/project.pbxproj index 141cebf6..7128397d 100644 --- a/Leader Key.xcodeproj/project.pbxproj +++ b/Leader Key.xcodeproj/project.pbxproj @@ -41,6 +41,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 */; }; @@ -102,6 +109,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 = ""; }; @@ -158,10 +172,31 @@ children = ( 427C18242BD31E2E00955B98 /* GeneralPane.swift */, 42FDC3192D51687B004F5C5C /* AdvancedPane.swift */, + 428483532E813219009D7EEF /* KeyboardPane.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 = ""; + }; 427C17DE2BD311B400955B98 = { isa = PBXGroup; children = ( @@ -205,6 +240,8 @@ 427C182E2BD3206200955B98 /* UserState.swift */, 427C184F2BD6652500955B98 /* Util.swift */, 427C17EE2BD311B500955B98 /* Assets.xcassets */, + 4284835C2E813222009D7EEF /* Cheatsheet */, + 428483552E81321B009D7EEF /* KeyboardLayout */, 423632242D68CC5D00878D92 /* Settings */, 427C18362BD3243C00955B98 /* Support */, 423632232D68CB0F00878D92 /* Themes */, @@ -443,6 +480,13 @@ 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 */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Leader Key/AppDelegate.swift b/Leader Key/AppDelegate.swift index 36411839..4b2a40c4 100644 --- a/Leader Key/AppDelegate.swift +++ b/Leader Key/AppDelegate.swift @@ -35,6 +35,13 @@ 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) + }), ], style: .segmentedControl, ) diff --git a/Leader Key/Cheatsheet.swift b/Leader Key/Cheatsheet.swift index 1dc54bda..c04e0b6b 100644 --- a/Leader Key/Cheatsheet.swift +++ b/Leader Key/Cheatsheet.swift @@ -3,195 +3,111 @@ 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) + 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( + VisualEffectView(material: .hudWindow, blendingMode: .behindWindow) + ) + .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..() @@ -56,6 +58,7 @@ class Controller { func show() { Events.send(.willActivate) + startModifierMonitoring() let screen = Defaults[.screen].getNSScreen() ?? NSScreen() window.show(on: screen) { @@ -77,6 +80,12 @@ class Controller { func hide(afterClose: (() -> Void)? = nil) { Events.send(.willDeactivate) + stopModifierMonitoring() + + // Reset centered mode state + window.alphaValue = 1 + isCheatsheetCentered = false + userState.cheatsheetCentered = 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 } @@ -168,7 +187,6 @@ class Controller { } } } - // If execute is false, just stay visible showing the matched action case .group(let group): if execute, let mods = modifiers, shouldRunGroupSequenceWithModifiers(mods) { hide { @@ -182,9 +200,11 @@ class Controller { 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 +212,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 +248,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 +293,80 @@ class Controller { mainWindow.cheatsheetOrigin(cheatsheetSize: cheatsheet.frame.size)) } - private func showCheatsheet() { + private func centerCheatsheetWindow() { + guard let cheatsheet = cheatsheetWindow, + let screen = cheatsheetDisplayScreen() + else { + return + } + + let screenFrame = screen.visibleFrame + let cheatsheetFrame = cheatsheet.frame + + let x = screenFrame.origin.x + (screenFrame.width - cheatsheetFrame.width) / 2 + let y = screenFrame.origin.y + (screenFrame.height - cheatsheetFrame.height) / 2 + + 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() + + if centered { + // Hide the main window visually but keep it as key window for input + window.alphaValue = 0 + isCheatsheetCentered = true + userState.cheatsheetCentered = true + sizeCheatsheetWindowToFitContent() + centerCheatsheetWindow() + } else { + cheatsheetWindow?.setContentSize( + NSSize(width: CheatsheetView.preferredWidth, height: 640) + ) + positionCheatsheetWindow() + } cheatsheetWindow?.orderFront(nil) + + if centered { + DispatchQueue.main.async { [weak self] in + self?.sizeCheatsheetWindowToFitContent() + self?.centerCheatsheetWindow() + } + } + } + + private func exitCenteredMode() { + if isCheatsheetCentered { + window.alphaValue = 1 + isCheatsheetCentered = false + userState.cheatsheetCentered = false + cheatsheetWindow?.orderOut(nil) + } } private func scheduleCheatsheet() { @@ -284,7 +375,9 @@ 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) } } @@ -360,6 +453,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..dc737238 --- /dev/null +++ b/Leader Key/KeyboardLayout/KeyView.swift @@ -0,0 +1,163 @@ +import AppKit +import SwiftUI + +struct KeyView: View { + let keyDef: KeyDefinition + let binding: ActionOrGroup? + let isEditable: Bool + let shiftHeld: Bool + var scale: CGFloat = 1.0 + var onSelect: (() -> Void)? = nil + + @State private var isHovered = false + @State private var isCursorPushed = false + + private var iconSize: NSSize { + NSSize(width: 20 * scale, height: 20 * scale) + } + + var body: some View { + let width = + keyDef.width * KeyboardLayout.scaledKeySize(scale) + (keyDef.width - 1) + * KeyboardLayout.scaledKeySpacing(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: false) + } + .overlay { + if isHovered, 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)) + } + } + } + + // 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)) + } + } + .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?() + } + } + .zIndex(isHovered ? 1 : 0) + } + + private var displayLabel: String { + if shiftHeld && !keyDef.isModifier { + let shiftedKey = KeyboardLayout.shiftedKey(for: keyDef.key) + return KeyMaps.glyph(for: shiftedKey) ?? shiftedKey.uppercased() + } + + let displayKey: String + if keyDef.key.hasSuffix("_r") { + displayKey = String(keyDef.key.dropLast(2)) + } else { + displayKey = keyDef.key + } + + return KeyMaps.glyph(for: displayKey) ?? keyDef.label + } + + 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 + } + } +} diff --git a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift new file mode 100644 index 00000000..53ade487 --- /dev/null +++ b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift @@ -0,0 +1,73 @@ +import SwiftUI + +struct KeyboardCheatsheetView: View { + @EnvironmentObject var userState: UserState + + var scale: CGFloat { + userState.cheatsheetCentered ? KeyboardLayout.centeredScale : 1.0 + } + + var bindings: [String: ActionOrGroup] { + var result: [String: ActionOrGroup] = [:] + + let actions = + (userState.currentGroup != nil) + ? userState.currentGroup!.actions + : userState.userConfig.root.actions + + for item in actions { + switch item { + case .action(let action): + if let key = action.key { + result[key] = item + } + case .group(let group): + if let key = group.key { + result[key] = item + } + } + } + + return result + } + + var body: some View { + VStack(alignment: .leading, spacing: 8 * scale) { + // Fixed height header area - always present to maintain layout + HStack { + if let group = userState.currentGroup { + Text(group.displayName) + .font(.system(size: 12 * scale, weight: .semibold)) + .foregroundColor(.white) + .padding(.horizontal, 8 * scale) + .padding(.vertical, 4 * scale) + .background(Color.accentColor.opacity(0.8)) + .clipShape(RoundedRectangle(cornerRadius: 6 * scale, style: .continuous)) + } + Spacer() + } + .frame(height: 28 * scale) + + // Keyboard layout + KeyboardLayoutView( + bindings: bindings, + isEditable: false, + shiftHeld: userState.shiftHeld, + scale: scale + ) + } + .padding(16 * scale) + .background( + VisualEffectView(material: .hudWindow, blendingMode: .behindWindow) + ) + } +} + +#Preview { + let config = UserConfig() + let state = UserState(userConfig: config) + + return KeyboardCheatsheetView() + .environmentObject(state) + .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..0ce96dfc --- /dev/null +++ b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift @@ -0,0 +1,174 @@ +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 // Config key for binding lookup ("q", "tab", "space") + 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, width: CGFloat = 1.0, isModifier: Bool = false) { + self.label = label + self.key = key + self.width = width + self.isModifier = isModifier + } +} + +/// 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 + } + + /// Calculate total keyboard width based on widest row + static var totalWidth: CGFloat { + let widestRow = rows.max(by: { rowWidth($0) < rowWidth($1) }) ?? [] + return rowWidth(widestRow) + } + + /// Calculate width of a row + static func rowWidth(_ row: [KeyDefinition]) -> CGFloat { + let totalUnits = row.reduce(0) { $0 + $1.width } + return totalUnits * keySize + (totalUnits - 1) * keySpacing + } + + /// 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: "`"), + KeyDefinition(label: "1", key: "1"), + KeyDefinition(label: "2", key: "2"), + KeyDefinition(label: "3", key: "3"), + KeyDefinition(label: "4", key: "4"), + KeyDefinition(label: "5", key: "5"), + KeyDefinition(label: "6", key: "6"), + KeyDefinition(label: "7", key: "7"), + KeyDefinition(label: "8", key: "8"), + KeyDefinition(label: "9", key: "9"), + KeyDefinition(label: "0", key: "0"), + KeyDefinition(label: "-", key: "-"), + KeyDefinition(label: "=", key: "="), + KeyDefinition(label: "⌫", key: "backspace", 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", width: 1.5), + KeyDefinition(label: "Q", key: "q"), + KeyDefinition(label: "W", key: "w"), + KeyDefinition(label: "E", key: "e"), + KeyDefinition(label: "R", key: "r"), + KeyDefinition(label: "T", key: "t"), + KeyDefinition(label: "Y", key: "y"), + KeyDefinition(label: "U", key: "u"), + KeyDefinition(label: "I", key: "i"), + KeyDefinition(label: "O", key: "o"), + KeyDefinition(label: "P", key: "p"), + KeyDefinition(label: "[", key: "["), + KeyDefinition(label: "]", key: "]"), + KeyDefinition(label: "\\", key: "\\", 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", width: 1.75, isModifier: true), + KeyDefinition(label: "A", key: "a"), + KeyDefinition(label: "S", key: "s"), + KeyDefinition(label: "D", key: "d"), + KeyDefinition(label: "F", key: "f"), + KeyDefinition(label: "G", key: "g"), + KeyDefinition(label: "H", key: "h"), + KeyDefinition(label: "J", key: "j"), + KeyDefinition(label: "K", key: "k"), + KeyDefinition(label: "L", key: "l"), + KeyDefinition(label: ";", key: ";"), + KeyDefinition(label: "'", key: "'"), + KeyDefinition(label: "⏎", key: "enter", width: 2.25), + ] + + // Row 3: Shift Z X C V B N M , . / Shift (total: 15u) + static let row3: [KeyDefinition] = [ + KeyDefinition(label: "⇧", key: "shift", width: 2.25, isModifier: true), + KeyDefinition(label: "Z", key: "z"), + KeyDefinition(label: "X", key: "x"), + KeyDefinition(label: "C", key: "c"), + KeyDefinition(label: "V", key: "v"), + KeyDefinition(label: "B", key: "b"), + KeyDefinition(label: "N", key: "n"), + KeyDefinition(label: "M", key: "m"), + KeyDefinition(label: ",", key: ","), + KeyDefinition(label: ".", key: "."), + KeyDefinition(label: "/", key: "/"), + KeyDefinition(label: "⇧", key: "shift_r", width: 2.75, isModifier: true), + ] + + // Row 4: Ctrl Opt Cmd Space Cmd Opt (total: 15u) + static let row4: [KeyDefinition] = [ + KeyDefinition(label: "βŒƒ", key: "ctrl", width: 1.5, isModifier: true), + KeyDefinition(label: "βŒ₯", key: "opt", width: 1.25, isModifier: true), + KeyDefinition(label: "⌘", key: "cmd", width: 1.5, isModifier: true), + KeyDefinition(label: "", key: "space", width: 6.5), + KeyDefinition(label: "⌘", key: "cmd_r", width: 1.5, isModifier: true), + KeyDefinition(label: "βŒ₯", key: "opt_r", width: 1.25, isModifier: true), + KeyDefinition(label: "βŒƒ", key: "ctrl_r", width: 1.5, isModifier: true), + ] +} diff --git a/Leader Key/KeyboardLayout/KeyboardLayoutView.swift b/Leader Key/KeyboardLayout/KeyboardLayoutView.swift new file mode 100644 index 00000000..1994f353 --- /dev/null +++ b/Leader Key/KeyboardLayout/KeyboardLayoutView.swift @@ -0,0 +1,67 @@ +import AppKit +import SwiftUI + +struct KeyboardLayoutView: View { + let bindings: [String: ActionOrGroup] + let isEditable: Bool + let shiftHeld: Bool + var scale: CGFloat = 1.0 + var onKeySelected: ((String) -> Void)? = nil + + 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), + isEditable: isEditable, + shiftHeld: shiftHeld, + scale: scale, + onSelect: { + onKeySelected?(keyDef.key) + } + ) + } + } + .fixedSize() + } + } + .fixedSize() + } + + private func getBinding(for keyDef: KeyDefinition) -> ActionOrGroup? { + if shiftHeld { + let shiftedKey = KeyboardLayout.shiftedKey(for: keyDef.key) + return bindings[shiftedKey] + } + return bindings[keyDef.key] + } +} + +#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, + isEditable: false, + shiftHeld: false + ) + .frame(width: 700, height: 300) + .padding() +} diff --git a/Leader Key/Settings.swift b/Leader Key/Settings.swift index 1eb1af27..96f5ecd3 100644 --- a/Leader Key/Settings.swift +++ b/Leader Key/Settings.swift @@ -3,4 +3,5 @@ import Settings extension Settings.PaneIdentifier { static let general = Self("general") static let advanced = Self("advanced") + static let keyboard = Self("keyboard") } 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..f34aca00 --- /dev/null +++ b/Leader Key/Settings/KeyboardPane.swift @@ -0,0 +1,845 @@ +import AppKit +import Defaults +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 + + @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 + VStack(spacing: 16) { + if case .group = item { + Button { + let updated = getUpdatedItem() + item = updated + onSave(updated) + onOpenLayout(updated) + } label: { + HStack { + Image(systemName: "square.grid.3x3") + Text("Edit Group Layout") + } + .frame(maxWidth: .infinity) + .padding(.vertical, 4) + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + + Text("Assign actions to keys within this group.") + .font(.caption) + .foregroundColor(.secondary) + .multilineTextAlignment(.center) + } + } + .padding(.top, 10) + } + } + .padding(.horizontal, 24) + + Spacer() + + // Footer + HStack { + if !isNew { + Button(role: .destructive) { + onDelete(item) + } label: { + Image(systemName: "trash") + .font(.system(size: 16)) + .foregroundColor(.secondary) + } + .buttonStyle(.plain) + .help("Delete Item") + } + + Spacer() + + Button("Done") { + let updated = getUpdatedItem() + item = updated + onSave(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 + @Default(.cheatsheetStyle) var cheatsheetStyle + + @State private var editingItem: EditorWrapper? + @State private var editingGroupWrapper: GroupWrapper? + @State private var currentGroupPath: [UUID] = [] + @State private var keyboardScale: CGFloat = 1.4 + @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[key] = item + } + case .group(let group): + if let key = group.key { + result[key] = item + } + } + } + + return result + } + + var body: some View { + Settings.Container(contentWidth: contentWidth) { + Settings.Section(title: "", bottomDivider: true) { + VStack(alignment: .leading, spacing: 12) { + // Breadcrumbs & Header + HStack(spacing: 4) { + if !currentGroupPath.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 4) { + // Root breadcrumb + Button { + currentGroupPath.removeAll() + } label: { + Text("Root") + } + .buttonStyle(.bordered) + + // 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) + } + .buttonStyle(.bordered) + } + } + } + } + + 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: { + Text("Root") + } + .buttonStyle(.bordered) + .opacity(0) + .disabled(true) + + Spacer() + } + } + .frame(height: 24) + + HStack(spacing: 0) { + Spacer() + KeyboardLayoutView( + bindings: bindings, + isEditable: false, + 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 + } + + // If shift is held, use the shifted key for lookup and creation + let lookupKey = + isShiftActive ? KeyboardLayout.shiftedKey(for: key) : key + + 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 + ) + } + } + ) + Spacer() + } + + Text("Click any key to configure") + .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 { + deleteGroup(group) + // If we deleted the current group, pop back + if !currentGroupPath.isEmpty { + currentGroupPath.removeLast() + } + } + editingGroupWrapper = nil + }, + onOpenLayout: { + editingGroupWrapper = nil + } + ) + } + .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 var keyboardMaxHeight: CGFloat { + let rows = CGFloat(KeyboardLayout.rows.count) + let scaledKeySize = KeyboardLayout.keySize * maxKeyboardScale + let scaledRowSpacing = KeyboardLayout.rowSpacing * maxKeyboardScale + let keyboardHeight = (scaledKeySize * rows) + (scaledRowSpacing * (rows - 1)) + // Add padding (8px for .padding(.vertical, 4)) + 32px for the overlapping text + return ceil(keyboardHeight) + 40 + } + + 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) + } + + 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) { + if currentGroupPath.isEmpty { + config.root = modifiedGroup + } else { + 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/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/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..0ca62e76 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.. Bool { + if navigationPath.isEmpty { + return false + } + navigationPath.removeLast() + return true + } } From 2f8c72901a1c3b45b35d27f661cba75ea5254750 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 15 Dec 2025 13:50:21 -0800 Subject: [PATCH 02/22] style(cheatsheet): improve background visibility on light backgrounds Change material from hudWindow to popover and add semi-transparent window background overlay (70% opacity) for better contrast while maintaining blur effect. --- Leader Key/Cheatsheet.swift | 5 ++++- Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Leader Key/Cheatsheet.swift b/Leader Key/Cheatsheet.swift index c04e0b6b..832205b5 100644 --- a/Leader Key/Cheatsheet.swift +++ b/Leader Key/Cheatsheet.swift @@ -90,7 +90,10 @@ struct CheatsheetView: SwiftUI.View { .frame(width: CheatsheetView.preferredWidth) .frame(height: min(contentHeight, maxHeight)) .background( - VisualEffectView(material: .hudWindow, blendingMode: .behindWindow) + ZStack { + VisualEffectView(material: .popover, blendingMode: .behindWindow) + Color(NSColor.windowBackgroundColor).opacity(0.7) + } ) .onPreferenceChange(HeightPreferenceKey.self) { height in self.contentHeight = height diff --git a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift index 53ade487..699aee49 100644 --- a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift +++ b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift @@ -58,7 +58,10 @@ struct KeyboardCheatsheetView: View { } .padding(16 * scale) .background( - VisualEffectView(material: .hudWindow, blendingMode: .behindWindow) + ZStack { + VisualEffectView(material: .popover, blendingMode: .behindWindow) + Color(NSColor.windowBackgroundColor).opacity(0.7) + } ) } } From 799d3afb70783da57464d6e1ac1f3b52e34ccef4 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 15 Dec 2025 17:26:31 -0800 Subject: [PATCH 03/22] fix(cheatsheet): center keyboard cheatsheet to match theme window position MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update the keyboard cheatsheet centering logic to align with the main theme window positioning. Both windows now share the same vertical offset (slightly above true center) for consistent visual alignment. Changes: - Modified centerCheatsheetWindow to use theme-matching vertical offset - Added multiple centering passes to handle SwiftUI layout timing - Improved showCheatsheet timing to ensure proper sizing before display πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 --- Leader Key/Controller.swift | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/Leader Key/Controller.swift b/Leader Key/Controller.swift index 17205ac7..51b3eca5 100644 --- a/Leader Key/Controller.swift +++ b/Leader Key/Controller.swift @@ -300,11 +300,15 @@ class Controller { return } - let screenFrame = screen.visibleFrame + let screenCenter = screen.center() let cheatsheetFrame = cheatsheet.frame - let x = screenFrame.origin.x + (screenFrame.width - cheatsheetFrame.width) / 2 - let y = screenFrame.origin.y + (screenFrame.height - cheatsheetFrame.height) / 2 + // 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)) } @@ -344,19 +348,25 @@ class Controller { userState.cheatsheetCentered = true sizeCheatsheetWindowToFitContent() centerCheatsheetWindow() - } else { - cheatsheetWindow?.setContentSize( - NSSize(width: CheatsheetView.preferredWidth, height: 640) - ) - positionCheatsheetWindow() - } - cheatsheetWindow?.orderFront(nil) + cheatsheetWindow?.orderFront(nil) - if centered { + // 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) } } From 0a57a87bc1c2af45b3f8aabce8b7db27bf94fce8 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 15 Dec 2025 17:33:21 -0800 Subject: [PATCH 04/22] refactor(settings): streamline group editor UI with improved action flow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Simplified the group editing interface by removing redundant elements and improving the action flow with clearer button labels. Changes: - Removed "Edit Group Layout" button from group editor body - Removed helper text "Assign actions to keys within this group" - Changed "Done" button to "Assign Actions" for groups - Added "Cancel" button for groups to dismiss without saving - "Assign Actions" button now saves and opens keyboard layout in one step πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 --- Leader Key/Settings/KeyboardPane.swift | 43 ++++++++++---------------- 1 file changed, 16 insertions(+), 27 deletions(-) diff --git a/Leader Key/Settings/KeyboardPane.swift b/Leader Key/Settings/KeyboardPane.swift index f34aca00..2560e521 100644 --- a/Leader Key/Settings/KeyboardPane.swift +++ b/Leader Key/Settings/KeyboardPane.swift @@ -19,6 +19,7 @@ struct UnifiedEditorView: View { 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 @@ -188,31 +189,7 @@ struct UnifiedEditorView: View { } } else { // Group Mode - VStack(spacing: 16) { - if case .group = item { - Button { - let updated = getUpdatedItem() - item = updated - onSave(updated) - onOpenLayout(updated) - } label: { - HStack { - Image(systemName: "square.grid.3x3") - Text("Edit Group Layout") - } - .frame(maxWidth: .infinity) - .padding(.vertical, 4) - } - .buttonStyle(.borderedProminent) - .controlSize(.large) - - Text("Assign actions to keys within this group.") - .font(.caption) - .foregroundColor(.secondary) - .multilineTextAlignment(.center) - } - } - .padding(.top, 10) + Spacer() } } .padding(.horizontal, 24) @@ -221,7 +198,16 @@ struct UnifiedEditorView: View { // Footer HStack { - if !isNew { + 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: { @@ -235,10 +221,13 @@ struct UnifiedEditorView: View { Spacer() - Button("Done") { + Button(selectedType == .group ? "Assign Actions" : "Done") { let updated = getUpdatedItem() item = updated onSave(updated) + if selectedType == .group { + onOpenLayout(updated) + } } .keyboardShortcut(.defaultAction) .buttonStyle(.borderedProminent) From fd708c00aaa400c7d614c066d0aeeefe53d94632 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 15 Dec 2025 18:10:44 -0800 Subject: [PATCH 05/22] refactor(keyboard): improve breadcrumb navigation with icon-only home button MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace "Root" text with house icon for cleaner UI - Use default macOS button styling for breadcrumb buttons - Adjust breadcrumb alignment to match keyboard layout edges - Add balanced left/right spacing for proper visual alignment πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 --- Leader Key/Settings/KeyboardPane.swift | 117 ++++++++++++++----------- 1 file changed, 64 insertions(+), 53 deletions(-) diff --git a/Leader Key/Settings/KeyboardPane.swift b/Leader Key/Settings/KeyboardPane.swift index 2560e521..63f0c0fc 100644 --- a/Leader Key/Settings/KeyboardPane.swift +++ b/Leader Key/Settings/KeyboardPane.swift @@ -546,68 +546,79 @@ struct KeyboardPane: View { Settings.Section(title: "", bottomDivider: true) { VStack(alignment: .leading, spacing: 12) { // Breadcrumbs & Header - HStack(spacing: 4) { - if !currentGroupPath.isEmpty { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 4) { - // Root breadcrumb - Button { - currentGroupPath.removeAll() - } label: { - Text("Root") - } - .buttonStyle(.bordered) - - // 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: { + HStack(spacing: 0) { + // Calculate keyboard left offset to align breadcrumbs with ` key + let keyboardWidth = KeyboardLayout.totalWidth * maxKeyboardScale + let centerOffset = (contentWidth - keyboardWidth) / 2 + let leftOffset = max(0, centerOffset - 4) + let rightOffset = max(0, centerOffset - 4) + + Spacer() + .frame(width: leftOffset) + + 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) + } } - .buttonStyle(.bordered) } } } - } - Spacer() + 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: { - Text("Root") - } - .buttonStyle(.bordered) - .opacity(0) - .disabled(true) + // 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() + Spacer() + } } + + Spacer() + .frame(width: rightOffset) } .frame(height: 24) From 5ac3f34df827fbf19aeaee7e50f13feeebdf8eac Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 15 Dec 2025 18:21:10 -0800 Subject: [PATCH 06/22] fix(keyboard): align spacebar and bottom row with standard layout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Align spacebar left edge with C key and right edge with comma key - Adjust spacebar width from 6.5u to 6.0u for accurate alignment - Balance right Cmd (1.5u) and Opt (1.5u) keys to meet under slash key - Maintain total bottom row width at 15 units πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 --- Leader Key/KeyboardLayout/KeyboardLayoutModel.swift | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift index 0ce96dfc..efd54e8b 100644 --- a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift +++ b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift @@ -161,14 +161,16 @@ enum KeyboardLayout { KeyDefinition(label: "⇧", key: "shift_r", width: 2.75, isModifier: true), ] - // Row 4: Ctrl Opt Cmd Space Cmd Opt (total: 15u) + // 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", width: 1.5, isModifier: true), KeyDefinition(label: "βŒ₯", key: "opt", width: 1.25, isModifier: true), KeyDefinition(label: "⌘", key: "cmd", width: 1.5, isModifier: true), - KeyDefinition(label: "", key: "space", width: 6.5), + KeyDefinition(label: "", key: "space", width: 6.0), KeyDefinition(label: "⌘", key: "cmd_r", width: 1.5, isModifier: true), - KeyDefinition(label: "βŒ₯", key: "opt_r", width: 1.25, isModifier: true), - KeyDefinition(label: "βŒƒ", key: "ctrl_r", width: 1.5, isModifier: true), + KeyDefinition(label: "βŒ₯", key: "opt_r", width: 1.5, isModifier: true), + KeyDefinition(label: "βŒƒ", key: "ctrl_r", width: 1.75, isModifier: true), ] } From 4a2b79e10065ff392a8f7e76f76f07f887adf361 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Tue, 16 Dec 2025 04:31:18 -0800 Subject: [PATCH 07/22] feat(cheatsheet): add breadcrumb navigation to keyboard cheatsheet Replace single group label with full breadcrumb path showing navigation hierarchy. Breadcrumbs are read-only (non-interactive) for display purposes only. --- .../KeyboardCheatsheetView.swift | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift index 699aee49..d2a1ef45 100644 --- a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift +++ b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift @@ -33,16 +33,27 @@ struct KeyboardCheatsheetView: View { var body: some View { VStack(alignment: .leading, spacing: 8 * scale) { - // Fixed height header area - always present to maintain layout - HStack { - if let group = userState.currentGroup { - Text(group.displayName) - .font(.system(size: 12 * scale, weight: .semibold)) - .foregroundColor(.white) - .padding(.horizontal, 8 * scale) - .padding(.vertical, 4 * scale) - .background(Color.accentColor.opacity(0.8)) - .clipShape(RoundedRectangle(cornerRadius: 6 * scale, style: .continuous)) + // 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() } From ebf992e0e6193704d19300be87e0a724c584d51e Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Tue, 16 Dec 2025 04:50:59 -0800 Subject: [PATCH 08/22] feat(favicon): improve favicon display with larger size and rounded corners MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enhanced favicon presentation in keyboard layout and cheatsheet views: - Enabled favicon loading in keyboard layout (was previously disabled) - Removed padding to display favicons at full icon size - Added rounded corners (20% radius) to match app icon styling - Maintained aspect ratio with .fit content mode for better appearance Favicons now match the visual style of native app icons throughout the UI. πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 --- Leader Key/KeyboardLayout/KeyView.swift | 2 +- Leader Key/Views/ActionIcon.swift | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Leader Key/KeyboardLayout/KeyView.swift b/Leader Key/KeyboardLayout/KeyView.swift index dc737238..977fa2c8 100644 --- a/Leader Key/KeyboardLayout/KeyView.swift +++ b/Leader Key/KeyboardLayout/KeyView.swift @@ -48,7 +48,7 @@ struct KeyView: View { // Binding icon (centered) if let binding = binding { VStack { - actionIcon(item: binding, iconSize: iconSize, loadFavicons: false) + actionIcon(item: binding, iconSize: iconSize, loadFavicons: true) } .overlay { if isHovered, let label = bindingLabel { diff --git a/Leader Key/Views/ActionIcon.swift b/Leader Key/Views/ActionIcon.swift index 74d37e9a..95182988 100644 --- a/Leader Key/Views/ActionIcon.swift +++ b/Leader Key/Views/ActionIcon.swift @@ -124,8 +124,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 } From 629865e218795005c6b0b1a8d6cfbd406b0c859a Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Sun, 14 Dec 2025 12:45:45 -0800 Subject: [PATCH 09/22] feat: add usage statistics tracking with SQLite storage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a new Stats tab in settings to help users identify their most-used actions and optimize their keyboard shortcut configurations. Features: - Track every action execution with timestamps and key paths - Store stats in SQLite database using GRDB.swift - Display grouped stats by parent group with usage counts - Show keyboard shortcuts inline with action names - Clear all stats with confirmation dialog Implementation: - StatsDatabase.swift: Define ActionExecution and ActionStats models with GRDB migrations and indexes - StatsManager.swift: Singleton for recording executions and querying aggregated statistics - StatsPane.swift: SwiftUI settings pane with grouped display showing [key] Action Name (count) format - Hook stats recording into Controller.runAction() with full key path Database stored at ~/Library/Application Support/Leader Key/stats.db πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- Leader Key.xcodeproj/project.pbxproj | 16 + .../xcshareddata/swiftpm/Package.resolved | 2 +- Leader Key/AppDelegate.swift | 7 + Leader Key/Controller.swift | 83 ++- Leader Key/Settings.swift | 1 + Leader Key/Settings/StatsPane.swift | 494 ++++++++++++++++++ Leader Key/Stats/StatsManager.swift | 349 +++++++++++++ 7 files changed, 928 insertions(+), 24 deletions(-) create mode 100644 Leader Key/Settings/StatsPane.swift create mode 100644 Leader Key/Stats/StatsManager.swift diff --git a/Leader Key.xcodeproj/project.pbxproj b/Leader Key.xcodeproj/project.pbxproj index 141cebf6..902b9674 100644 --- a/Leader Key.xcodeproj/project.pbxproj +++ b/Leader Key.xcodeproj/project.pbxproj @@ -55,6 +55,8 @@ 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 */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -114,6 +116,8 @@ 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 = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -158,10 +162,19 @@ children = ( 427C18242BD31E2E00955B98 /* GeneralPane.swift */, 42FDC3192D51687B004F5C5C /* AdvancedPane.swift */, + CC0000012E9A000000000009 /* StatsPane.swift */, ); path = Settings; sourceTree = ""; }; + CC0000012E9A000000000004 /* Stats */ = { + isa = PBXGroup; + children = ( + CC0000012E9A000000000007 /* StatsManager.swift */, + ); + path = Stats; + sourceTree = ""; + }; 427C17DE2BD311B400955B98 = { isa = PBXGroup; children = ( @@ -206,6 +219,7 @@ 427C184F2BD6652500955B98 /* Util.swift */, 427C17EE2BD311B500955B98 /* Assets.xcassets */, 423632242D68CC5D00878D92 /* Settings */, + CC0000012E9A000000000004 /* Stats */, 427C18362BD3243C00955B98 /* Support */, 423632232D68CB0F00878D92 /* Themes */, 427C18392BD3268000955B98 /* Views */, @@ -443,6 +457,8 @@ 42F4CDCD2D45B13600D0DD76 /* KeyButton.swift in Sources */, 606C56EF2DAB875A00198B9F /* Cheater.swift in Sources */, 427C181C2BD314B500955B98 /* Constants.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..43ae1159 100644 --- a/Leader Key/AppDelegate.swift +++ b/Leader Key/AppDelegate.swift @@ -35,6 +35,13 @@ class AppDelegate: NSObject, NSApplicationDelegate, contentView: { AdvancedPane().environmentObject(self.config) }), + Settings.Pane( + identifier: .stats, title: "Stats", + toolbarIcon: NSImage( + systemSymbolName: "chart.bar.fill", accessibilityDescription: "Stats")!, + contentView: { + StatsPane().environmentObject(self.config) + }), ], style: .segmentedControl, ) diff --git a/Leader Key/Controller.swift b/Leader Key/Controller.swift index 37c0eecd..854ba505 100644 --- a/Leader Key/Controller.swift +++ b/Leader Key/Controller.swift @@ -160,24 +160,34 @@ 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) { - hide { - self.runGroup(group) - } - } else { - userState.display = group.key - userState.navigateToGroup(group) - } + case .group(let group): + if execute, let mods = modifiers, shouldRunGroupSequenceWithModifiers(mods) { + // Capture keyPath BEFORE hiding + let parentPath = statsKeyPath(leafKey: nil) + hide { + self.runGroup(group, parentPath: parentPath) + } + } else { + // Record group navigation for stats + if let keyPath = statsKeyPath(leafKey: group.key) { + StatsManager.shared.recordGroupNavigation(group: group, keyPath: keyPath) + } + + userState.display = group.key + userState.navigateToGroup(group) + } case .none: window.notFound() } @@ -288,20 +298,47 @@ class Controller { } } - 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()) diff --git a/Leader Key/Settings.swift b/Leader Key/Settings.swift index 1eb1af27..d63194d8 100644 --- a/Leader Key/Settings.swift +++ b/Leader Key/Settings.swift @@ -3,4 +3,5 @@ import Settings extension Settings.PaneIdentifier { static let general = Self("general") static let advanced = Self("advanced") + static let stats = Self("stats") } diff --git a/Leader Key/Settings/StatsPane.swift b/Leader Key/Settings/StatsPane.swift new file mode 100644 index 00000000..f50e27b7 --- /dev/null +++ b/Leader Key/Settings/StatsPane.swift @@ -0,0 +1,494 @@ +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(.system(size: 20, weight: .medium)) + Spacer() + Text("\(totalExecutions) total") + .foregroundColor(.secondary) + .font(.body) + } + .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: 20) + + // Key badge + KeyBadgeView(key: group.groupKey) + .padding(.leading, 8) + + // 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, 16) + + // 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(.vertical, 8) + .padding(.horizontal, 12) + .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) + 20) + + // Key badge + if let lastKey = stat.pathComponents.last { + KeyBadgeView(key: lastKey) + .padding(.leading, 8) + } + + // 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, 16) + + // 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(.vertical, 8) + .padding(.horizontal, 12) + .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 +} From c129d049472d1a91925dd3043329081d7a0f2fa8 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Wed, 17 Dec 2025 21:47:50 -0800 Subject: [PATCH 10/22] fix(stats): correct Settings.Section usage in StatsPane Update StatsPane to properly wrap content in Settings.Section components with required title parameter, fixing build errors after Settings library update. --- Leader Key/Settings/StatsPane.swift | 39 ++++++++++++++++------------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/Leader Key/Settings/StatsPane.swift b/Leader Key/Settings/StatsPane.swift index f50e27b7..1e8a9c8b 100644 --- a/Leader Key/Settings/StatsPane.swift +++ b/Leader Key/Settings/StatsPane.swift @@ -19,11 +19,13 @@ struct StatsPane: View { // Header HStack(alignment: .center) { Text("Usage Stats") - .font(.system(size: 20, weight: .medium)) + .font(.headline) Spacer() Text("\(totalExecutions) total") - .foregroundColor(.secondary) - .font(.body) + .foregroundColor(.primary) + .font(.system(.body, design: .rounded)) + .fontWeight(.medium) + .monospacedDigit() } .padding(.bottom, 8) @@ -264,11 +266,11 @@ private struct GroupStatsRow: View { .foregroundColor(.secondary) .rotationEffect(.degrees(isExpanded ? 90 : 0)) .animation(.easeInOut(duration: 0.2), value: isExpanded) - .frame(width: 20) + .frame(width: 14) // Key badge KeyBadgeView(key: group.groupKey) - .padding(.leading, 8) + .padding(.leading, 4) // Group name Text(group.groupLabel) @@ -282,7 +284,7 @@ private struct GroupStatsRow: View { HStack(spacing: 0) { // Progress bar ProgressBarView(value: group.totalCount, max: maxCount) - .padding(.trailing, 16) + .padding(.trailing, 20) // Folder icon Image(systemName: "folder") @@ -296,14 +298,14 @@ private struct GroupStatsRow: View { .foregroundColor(.primary) .font(.system(.body, design: .rounded)) .fontWeight(.medium) - .monospacedDigit() - .frame(width: 36, alignment: .trailing) - } - } - .padding(.vertical, 8) - .padding(.horizontal, 12) - .background( - RoundedRectangle(cornerRadius: 8) + .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()) @@ -362,12 +364,12 @@ private struct ActionStatsRow: View { HStack(alignment: .center, spacing: 0) { // Indent spacer (add extra indent since no chevron) Spacer() - .frame(width: indentPerLevel * CGFloat(depth) + 20) + .frame(width: indentPerLevel * CGFloat(depth) + 14) // Key badge if let lastKey = stat.pathComponents.last { KeyBadgeView(key: lastKey) - .padding(.leading, 8) + .padding(.leading, 4) } // Action name @@ -383,7 +385,7 @@ private struct ActionStatsRow: View { HStack(spacing: 0) { // Progress bar ProgressBarView(value: stat.action.executionCount, max: maxCount) - .padding(.trailing, 16) + .padding(.trailing, 20) // Icon ActionIconView(actionType: stat.action.actionType, actionValue: stat.action.actionValue) @@ -397,8 +399,9 @@ private struct ActionStatsRow: View { .frame(width: 36, alignment: .trailing) } } + .padding(.trailing, 18) .padding(.vertical, 8) - .padding(.horizontal, 12) + .padding(.horizontal, 8) .contentShape(Rectangle()) } From a409514f9a84b149a625f91b75e33544def48115 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Wed, 17 Dec 2025 21:51:43 -0800 Subject: [PATCH 11/22] fix(keyboard): correct row width calculation and simplify centering - Fix rowWidth calculation to properly count gaps between keys instead of using total width units - Simplify keyboard centering in KeyboardPane by using center alignment and frame width instead of manual spacer calculations - Remove complex left/right offset logic for cleaner layout code This fixes spacing issues where keyboard rows were misaligned. --- .../KeyboardLayout/KeyboardLayoutModel.swift | 3 +- Leader Key/Settings/KeyboardPane.swift | 29 +++++-------------- 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift index efd54e8b..c57fc887 100644 --- a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift +++ b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift @@ -84,7 +84,8 @@ enum KeyboardLayout { /// Calculate width of a row static func rowWidth(_ row: [KeyDefinition]) -> CGFloat { let totalUnits = row.reduce(0) { $0 + $1.width } - return totalUnits * keySize + (totalUnits - 1) * keySpacing + let totalGaps = CGFloat(max(0, row.count - 1)) + return totalUnits * keySize + totalGaps * keySpacing } /// All keyboard rows diff --git a/Leader Key/Settings/KeyboardPane.swift b/Leader Key/Settings/KeyboardPane.swift index 63f0c0fc..add9602e 100644 --- a/Leader Key/Settings/KeyboardPane.swift +++ b/Leader Key/Settings/KeyboardPane.swift @@ -544,17 +544,10 @@ struct KeyboardPane: View { var body: some View { Settings.Container(contentWidth: contentWidth) { Settings.Section(title: "", bottomDivider: true) { - VStack(alignment: .leading, spacing: 12) { + VStack(alignment: .center, spacing: 12) { // Breadcrumbs & Header HStack(spacing: 0) { - // Calculate keyboard left offset to align breadcrumbs with ` key let keyboardWidth = KeyboardLayout.totalWidth * maxKeyboardScale - let centerOffset = (contentWidth - keyboardWidth) / 2 - let leftOffset = max(0, centerOffset - 4) - let rightOffset = max(0, centerOffset - 4) - - Spacer() - .frame(width: leftOffset) HStack(spacing: 4) { if !currentGroupPath.isEmpty { @@ -616,20 +609,16 @@ struct KeyboardPane: View { Spacer() } } - - Spacer() - .frame(width: rightOffset) + .frame(width: keyboardWidth) } .frame(height: 24) - HStack(spacing: 0) { - Spacer() - KeyboardLayoutView( - bindings: bindings, - isEditable: false, - shiftHeld: shiftHeld || stickyShiftMode, - scale: maxKeyboardScale, - onKeySelected: { key in + KeyboardLayoutView( + bindings: bindings, + isEditable: false, + shiftHeld: shiftHeld || stickyShiftMode, + scale: maxKeyboardScale, + onKeySelected: { key in if key == "shift" || key == "shift_r" { stickyShiftMode.toggle() return @@ -671,8 +660,6 @@ struct KeyboardPane: View { } } ) - Spacer() - } Text("Click any key to configure") .font(.body) From 019dba30037ae047ad0ce828ad170673d8e4a786 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Wed, 17 Dec 2025 21:51:43 -0800 Subject: [PATCH 12/22] fix(keyboard): correct row width calculation and simplify centering - Fix rowWidth calculation to properly count gaps between keys instead of using total width units - Simplify keyboard centering in KeyboardPane by using center alignment and frame width instead of manual spacer calculations - Remove complex left/right offset logic for cleaner layout code This fixes spacing issues where keyboard rows were misaligned. --- .../KeyboardLayout/KeyboardLayoutModel.swift | 3 +- Leader Key/Settings/KeyboardPane.swift | 29 +++++-------------- 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift index efd54e8b..c57fc887 100644 --- a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift +++ b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift @@ -84,7 +84,8 @@ enum KeyboardLayout { /// Calculate width of a row static func rowWidth(_ row: [KeyDefinition]) -> CGFloat { let totalUnits = row.reduce(0) { $0 + $1.width } - return totalUnits * keySize + (totalUnits - 1) * keySpacing + let totalGaps = CGFloat(max(0, row.count - 1)) + return totalUnits * keySize + totalGaps * keySpacing } /// All keyboard rows diff --git a/Leader Key/Settings/KeyboardPane.swift b/Leader Key/Settings/KeyboardPane.swift index 63f0c0fc..add9602e 100644 --- a/Leader Key/Settings/KeyboardPane.swift +++ b/Leader Key/Settings/KeyboardPane.swift @@ -544,17 +544,10 @@ struct KeyboardPane: View { var body: some View { Settings.Container(contentWidth: contentWidth) { Settings.Section(title: "", bottomDivider: true) { - VStack(alignment: .leading, spacing: 12) { + VStack(alignment: .center, spacing: 12) { // Breadcrumbs & Header HStack(spacing: 0) { - // Calculate keyboard left offset to align breadcrumbs with ` key let keyboardWidth = KeyboardLayout.totalWidth * maxKeyboardScale - let centerOffset = (contentWidth - keyboardWidth) / 2 - let leftOffset = max(0, centerOffset - 4) - let rightOffset = max(0, centerOffset - 4) - - Spacer() - .frame(width: leftOffset) HStack(spacing: 4) { if !currentGroupPath.isEmpty { @@ -616,20 +609,16 @@ struct KeyboardPane: View { Spacer() } } - - Spacer() - .frame(width: rightOffset) + .frame(width: keyboardWidth) } .frame(height: 24) - HStack(spacing: 0) { - Spacer() - KeyboardLayoutView( - bindings: bindings, - isEditable: false, - shiftHeld: shiftHeld || stickyShiftMode, - scale: maxKeyboardScale, - onKeySelected: { key in + KeyboardLayoutView( + bindings: bindings, + isEditable: false, + shiftHeld: shiftHeld || stickyShiftMode, + scale: maxKeyboardScale, + onKeySelected: { key in if key == "shift" || key == "shift_r" { stickyShiftMode.toggle() return @@ -671,8 +660,6 @@ struct KeyboardPane: View { } } ) - Spacer() - } Text("Click any key to configure") .font(.body) From 79b610d156a7c7cbafd716f51ca5e581277b0746 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Sat, 20 Dec 2025 14:39:31 -0800 Subject: [PATCH 13/22] feat: add custom PNG/JPEG/ICNS icon support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add support for custom image files as icons alongside existing app icons. Users can now select PNG, JPEG, or ICNS files from the "Custom Icon..." menu option. Changes: - Add CustomIconImage SwiftUI view for rendering custom icons - Add "Custom Icon..." option to icon picker menu - Add file picker handlers for Actions and Groups - Apply proper sizing and rounded corners to match app bundle icons - Add validation to ensure selected files are valid images πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- Leader Key.xcodeproj/project.pbxproj | 12 ++-- Leader Key/Views/ActionIcon.swift | 30 +++++++++ Leader Key/Views/ConfigEditorShared.swift | 35 ++++++++++- .../Views/ConfigOutlineEditorView.swift | 62 +++++++++++++++++++ Leader Key/Views/CustomIconRenderer.swift | 57 +++++++++++++++++ 5 files changed, 190 insertions(+), 6 deletions(-) create mode 100644 Leader Key/Views/CustomIconRenderer.swift diff --git a/Leader Key.xcodeproj/project.pbxproj b/Leader Key.xcodeproj/project.pbxproj index 141cebf6..8ed03ae3 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 */; }; @@ -55,6 +54,8 @@ 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 */; }; + 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 +69,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 +78,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 +89,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 = ""; }; @@ -114,6 +114,8 @@ 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 = ""; }; + 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 */ @@ -247,6 +249,7 @@ 427C18392BD3268000955B98 /* Views */ = { isa = PBXGroup; children = ( + 0A27E0A12EF7616100731753 /* CustomIconRenderer.swift */, 605385A22D523CAD00BEDB4B /* Pulsate.swift */, 6D9B9C002DBA000000000001 /* ConfigOutlineEditorView.swift */, 427C18372BD3262100955B98 /* VisualEffectBackground.swift */, @@ -414,6 +417,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 */, diff --git a/Leader Key/Views/ActionIcon.swift b/Leader Key/Views/ActionIcon.swift index 74d37e9a..898e9502 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) @@ -103,6 +106,33 @@ 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? { + CustomIconRenderer.renderCustomIcon(from: path, size: size) + } +} + struct FavIconImage: View { let url: String let icon: String 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..77ff97d1 --- /dev/null +++ b/Leader Key/Views/CustomIconRenderer.swift @@ -0,0 +1,57 @@ +import AppKit + +enum CustomIconRenderer { + static let cornerRadiusFactor: CGFloat = 0.2237 + + 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() } + + let destRect = NSRect(origin: .zero, size: targetSize) + let cornerRadius = min(size.width, size.height) * 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) + } +} From 80705d7d618167b0cd384ed3e3879291ffb84610 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Sat, 20 Dec 2025 14:39:31 -0800 Subject: [PATCH 14/22] feat: add custom PNG/JPEG/ICNS icon support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add support for custom image files as icons alongside existing app icons. Users can now select PNG, JPEG, or ICNS files from the "Custom Icon..." menu option. Changes: - Add CustomIconImage SwiftUI view for rendering custom icons - Add "Custom Icon..." option to icon picker menu - Add file picker handlers for Actions and Groups - Apply proper sizing and rounded corners to match app bundle icons - Add validation to ensure selected files are valid images πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- Leader Key/Views/CustomIconRenderer.swift | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Leader Key/Views/CustomIconRenderer.swift b/Leader Key/Views/CustomIconRenderer.swift index 77ff97d1..d104bb98 100644 --- a/Leader Key/Views/CustomIconRenderer.swift +++ b/Leader Key/Views/CustomIconRenderer.swift @@ -2,6 +2,7 @@ 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 @@ -24,8 +25,13 @@ enum CustomIconRenderer { outputImage.lockFocus() defer { outputImage.unlockFocus() } - let destRect = NSRect(origin: .zero, size: targetSize) - let cornerRadius = min(size.width, size.height) * cornerRadiusFactor + // 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() From 4b96f48d0975564df0af0de748c926ae96aa543a Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 29 Dec 2025 09:59:30 -0800 Subject: [PATCH 15/22] fix(cheatsheet): prevent hint popup from showing when keyboard cheatsheet is visible Skip updating userState.display in centered cheatsheet mode since the keyboard cheatsheet already shows navigation state via breadcrumbs. --- Leader Key/Controller.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Leader Key/Controller.swift b/Leader Key/Controller.swift index fde22279..4f471a3b 100644 --- a/Leader Key/Controller.swift +++ b/Leader Key/Controller.swift @@ -203,7 +203,11 @@ class Controller { StatsManager.shared.recordGroupNavigation(group: group, keyPath: keyPath) } - userState.display = group.key + // 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: From 886c619498fb3ba81853c2c36ade603a7178587a Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 9 Nov 2026 19:44:31 -0800 Subject: [PATCH 16/22] fix(settings): stop pane titles repeating under the tab bar Co-Authored-By: Claude Fable 5.2 --- Leader Key/AppDelegate.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Leader Key/AppDelegate.swift b/Leader Key/AppDelegate.swift index f9ff759d..13518e2f 100644 --- a/Leader Key/AppDelegate.swift +++ b/Leader Key/AppDelegate.swift @@ -285,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 From 7ad948240d213d7331e696c0fe4671e76259c512 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 9 Nov 2026 19:44:31 -0800 Subject: [PATCH 17/22] fix(cheatsheet): center keyboard cheatsheet when set to always show Co-Authored-By: Claude Fable 5.2 --- Leader Key/Controller.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Leader Key/Controller.swift b/Leader Key/Controller.swift index 4f471a3b..d259d6da 100644 --- a/Leader Key/Controller.swift +++ b/Leader Key/Controller.swift @@ -71,7 +71,7 @@ class Controller { switch Defaults[.autoOpenCheatsheet] { case .always: - showCheatsheet() + showCheatsheet(centered: Defaults[.cheatsheetStyle] == .keyboard) case .delay: scheduleCheatsheet() default: break From 20d98ce937f4144616dcc734a4cd8c6b73e5d913 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 9 Nov 2026 19:44:31 -0800 Subject: [PATCH 18/22] feat(keyboard): drag bindings to rearrange, follow the active layout - Drag a bound key onto another key to move or swap bindings; root group shortcuts follow the moved binding - Resolve key labels and binding keys from the active input source unless Force English is on - Show binding names in the keyboard cheatsheet - Share one key-width calculation so rowWidth matches what is drawn - Size favicons like other key icons - Remove unused keyboard pane state and the isEditable parameter - Add model tests for row widths, shifted keys and layout resolution Co-Authored-By: Claude Fable 5.2 --- Leader Key/KeyboardLayout/KeyView.swift | 123 ++++++++- .../KeyboardCheatsheetView.swift | 8 +- .../KeyboardLayout/KeyboardLayoutModel.swift | 234 ++++++++++++------ .../KeyboardLayout/KeyboardLayoutView.swift | 56 ++++- Leader Key/Settings/KeyboardPane.swift | 73 ++++-- Leader Key/UserConfig.swift | 11 + Leader Key/Views/ActionIcon.swift | 2 +- Leader KeyTests/KeyboardLayoutTests.swift | 163 ++++++++++++ 8 files changed, 561 insertions(+), 109 deletions(-) diff --git a/Leader Key/KeyboardLayout/KeyView.swift b/Leader Key/KeyboardLayout/KeyView.swift index 977fa2c8..32d96b95 100644 --- a/Leader Key/KeyboardLayout/KeyView.swift +++ b/Leader Key/KeyboardLayout/KeyView.swift @@ -1,25 +1,29 @@ import AppKit import SwiftUI +import UniformTypeIdentifiers struct KeyView: View { let keyDef: KeyDefinition let binding: ActionOrGroup? - let isEditable: Bool 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 @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 = - keyDef.width * KeyboardLayout.scaledKeySize(scale) + (keyDef.width - 1) - * KeyboardLayout.scaledKeySpacing(scale) + let width = KeyboardLayout.keyWidth(for: keyDef, scale: scale) let height = KeyboardLayout.scaledKeySize(scale) let cornerRadius = 6 * scale @@ -50,8 +54,9 @@ struct KeyView: View { VStack { actionIcon(item: binding, iconSize: iconSize, loadFavicons: true) } + .offset(y: showLabels ? -4 * scale : 0) .overlay { - if isHovered, let label = bindingLabel { + if isHovered, !showLabels, let label = bindingLabel { Text(label) .font(.system(size: 9 * scale)) .lineLimit(1) @@ -66,6 +71,22 @@ struct KeyView: View { } } + // 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 { @@ -87,6 +108,12 @@ struct KeyView: View { 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()) @@ -115,12 +142,23 @@ struct KeyView: View { onSelect?() } } + .modifier( + KeyDragDrop( + onDragStart: binding == nil ? nil : onDragStart, + dropDelegate: dropDelegate, + isDropTargeted: $isDropTargeted + ) { + if let binding = binding { + actionIcon(item: binding, iconSize: iconSize, loadFavicons: true) + } + } + ) .zIndex(isHovered ? 1 : 0) } private var displayLabel: String { if shiftHeld && !keyDef.isModifier { - let shiftedKey = KeyboardLayout.shiftedKey(for: keyDef.key) + let shiftedKey = KeyboardLayout.bindingKey(for: keyDef, shifted: true) return KeyMaps.glyph(for: shiftedKey) ?? shiftedKey.uppercased() } @@ -128,12 +166,17 @@ struct KeyView: View { if keyDef.key.hasSuffix("_r") { displayKey = String(keyDef.key.dropLast(2)) } else { - displayKey = keyDef.key + 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" } @@ -161,3 +204,69 @@ struct KeyView: View { } } } + +/// 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 index d2a1ef45..9ea59cd5 100644 --- a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift +++ b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift @@ -19,11 +19,11 @@ struct KeyboardCheatsheetView: View { switch item { case .action(let action): if let key = action.key { - result[key] = item + result[KeyMaps.text(for: key) ?? key] = item } case .group(let group): if let key = group.key { - result[key] = item + result[KeyMaps.text(for: key) ?? key] = item } } } @@ -62,9 +62,9 @@ struct KeyboardCheatsheetView: View { // Keyboard layout KeyboardLayoutView( bindings: bindings, - isEditable: false, shiftHeld: userState.shiftHeld, - scale: scale + scale: scale, + showLabels: true ) } .padding(16 * scale) diff --git a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift index c57fc887..454036a6 100644 --- a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift +++ b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift @@ -1,19 +1,29 @@ +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 // Config key for binding lookup ("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, width: CGFloat = 1.0, isModifier: Bool = false) { + 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 @@ -75,17 +85,102 @@ enum KeyboardLayout { 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 { - let widestRow = rows.max(by: { rowWidth($0) < rowWidth($1) }) ?? [] - return rowWidth(widestRow) + rows.map { rowWidth($0) }.max() ?? 0 } - /// Calculate width of a row - static func rowWidth(_ row: [KeyDefinition]) -> CGFloat { - let totalUnits = row.reduce(0) { $0 + $1.width } - let totalGaps = CGFloat(max(0, row.count - 1)) - return totalUnits * keySize + totalGaps * keySpacing + /// 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 @@ -95,83 +190,84 @@ enum KeyboardLayout { // Row 0: ` 1 2 3 4 5 6 7 8 9 0 - = Backspace (total: 15u) static let row0: [KeyDefinition] = [ - KeyDefinition(label: "`", key: "`"), - KeyDefinition(label: "1", key: "1"), - KeyDefinition(label: "2", key: "2"), - KeyDefinition(label: "3", key: "3"), - KeyDefinition(label: "4", key: "4"), - KeyDefinition(label: "5", key: "5"), - KeyDefinition(label: "6", key: "6"), - KeyDefinition(label: "7", key: "7"), - KeyDefinition(label: "8", key: "8"), - KeyDefinition(label: "9", key: "9"), - KeyDefinition(label: "0", key: "0"), - KeyDefinition(label: "-", key: "-"), - KeyDefinition(label: "=", key: "="), - KeyDefinition(label: "⌫", key: "backspace", width: 2.0, isModifier: true), + 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", width: 1.5), - KeyDefinition(label: "Q", key: "q"), - KeyDefinition(label: "W", key: "w"), - KeyDefinition(label: "E", key: "e"), - KeyDefinition(label: "R", key: "r"), - KeyDefinition(label: "T", key: "t"), - KeyDefinition(label: "Y", key: "y"), - KeyDefinition(label: "U", key: "u"), - KeyDefinition(label: "I", key: "i"), - KeyDefinition(label: "O", key: "o"), - KeyDefinition(label: "P", key: "p"), - KeyDefinition(label: "[", key: "["), - KeyDefinition(label: "]", key: "]"), - KeyDefinition(label: "\\", key: "\\", width: 1.5), + 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", width: 1.75, isModifier: true), - KeyDefinition(label: "A", key: "a"), - KeyDefinition(label: "S", key: "s"), - KeyDefinition(label: "D", key: "d"), - KeyDefinition(label: "F", key: "f"), - KeyDefinition(label: "G", key: "g"), - KeyDefinition(label: "H", key: "h"), - KeyDefinition(label: "J", key: "j"), - KeyDefinition(label: "K", key: "k"), - KeyDefinition(label: "L", key: "l"), - KeyDefinition(label: ";", key: ";"), - KeyDefinition(label: "'", key: "'"), - KeyDefinition(label: "⏎", key: "enter", width: 2.25), + 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", width: 2.25, isModifier: true), - KeyDefinition(label: "Z", key: "z"), - KeyDefinition(label: "X", key: "x"), - KeyDefinition(label: "C", key: "c"), - KeyDefinition(label: "V", key: "v"), - KeyDefinition(label: "B", key: "b"), - KeyDefinition(label: "N", key: "n"), - KeyDefinition(label: "M", key: "m"), - KeyDefinition(label: ",", key: ","), - KeyDefinition(label: ".", key: "."), - KeyDefinition(label: "/", key: "/"), - KeyDefinition(label: "⇧", key: "shift_r", width: 2.75, isModifier: true), + 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", width: 1.5, isModifier: true), - KeyDefinition(label: "βŒ₯", key: "opt", width: 1.25, isModifier: true), - KeyDefinition(label: "⌘", key: "cmd", width: 1.5, isModifier: true), - KeyDefinition(label: "", key: "space", width: 6.0), - KeyDefinition(label: "⌘", key: "cmd_r", width: 1.5, isModifier: true), - KeyDefinition(label: "βŒ₯", key: "opt_r", width: 1.5, isModifier: true), - KeyDefinition(label: "βŒƒ", key: "ctrl_r", width: 1.75, isModifier: true), + 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 index 1994f353..a1722b7d 100644 --- a/Leader Key/KeyboardLayout/KeyboardLayoutView.swift +++ b/Leader Key/KeyboardLayout/KeyboardLayoutView.swift @@ -1,12 +1,22 @@ import AppKit +import Carbon.HIToolbox +import Defaults import SwiftUI struct KeyboardLayoutView: View { let bindings: [String: ActionOrGroup] - let isEditable: Bool 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 + + @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)) { @@ -16,12 +26,15 @@ struct KeyboardLayoutView: View { KeyView( keyDef: keyDef, binding: getBinding(for: keyDef), - isEditable: isEditable, 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 ) } } @@ -29,14 +42,40 @@ struct KeyboardLayoutView: View { } } .fixedSize() + .id("\(forceEnglishKeyboardLayout)-\(inputSourceRevision)") + .onReceive( + DistributedNotificationCenter.default().publisher( + for: Notification.Name(kTISNotifySelectedKeyboardInputSourceChanged as String)) + ) { _ in + inputSourceRevision += 1 + } } private func getBinding(for keyDef: KeyDefinition) -> ActionOrGroup? { - if shiftHeld { - let shiftedKey = KeyboardLayout.shiftedKey(for: keyDef.key) - return bindings[shiftedKey] - } - return bindings[keyDef.key] + bindings[bindingKey(for: keyDef)] + } + + private func bindingKey(for keyDef: KeyDefinition) -> String { + KeyboardLayout.bindingKey(for: keyDef, shifted: shiftHeld) + } + + 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) + } + ) } } @@ -59,7 +98,6 @@ struct KeyboardLayoutView: View { KeyboardLayoutView( bindings: sampleBindings, - isEditable: false, shiftHeld: false ) .frame(width: 700, height: 300) diff --git a/Leader Key/Settings/KeyboardPane.swift b/Leader Key/Settings/KeyboardPane.swift index add9602e..1641e1f3 100644 --- a/Leader Key/Settings/KeyboardPane.swift +++ b/Leader Key/Settings/KeyboardPane.swift @@ -1,5 +1,6 @@ import AppKit import Defaults +import KeyboardShortcuts import Settings import SwiftUI import UniformTypeIdentifiers @@ -505,12 +506,10 @@ struct KeyboardPane: View { private let contentWidth = 950.0 private let maxKeyboardScale: CGFloat = 1.4 @EnvironmentObject private var config: UserConfig - @Default(.cheatsheetStyle) var cheatsheetStyle @State private var editingItem: EditorWrapper? @State private var editingGroupWrapper: GroupWrapper? @State private var currentGroupPath: [UUID] = [] - @State private var keyboardScale: CGFloat = 1.4 @State private var shiftHeld = false @State private var stickyShiftMode = false // Persists after editing capital letter keys @State private var monitor: Any? @@ -529,11 +528,11 @@ struct KeyboardPane: View { switch item { case .action(let action): if let key = action.key { - result[key] = item + result[KeyMaps.text(for: key) ?? key] = item } case .group(let group): if let key = group.key { - result[key] = item + result[KeyMaps.text(for: key) ?? key] = item } } } @@ -615,7 +614,6 @@ struct KeyboardPane: View { KeyboardLayoutView( bindings: bindings, - isEditable: false, shiftHeld: shiftHeld || stickyShiftMode, scale: maxKeyboardScale, onKeySelected: { key in @@ -632,9 +630,9 @@ struct KeyboardPane: View { stickyShiftMode = true } - // If shift is held, use the shifted key for lookup and creation - let lookupKey = - isShiftActive ? KeyboardLayout.shiftedKey(for: key) : key + // 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 { @@ -658,10 +656,13 @@ struct KeyboardPane: View { isNew: true ) } - } + }, + onBindingMoved: { sourceKey, targetKey in + moveBinding(from: sourceKey, to: targetKey) + } ) - Text("Click any key to configure") + Text("Click a key to configure, drag a binding to move or swap it") .font(.body) .foregroundColor(.secondary) .frame(maxWidth: .infinity, alignment: .center) @@ -757,15 +758,6 @@ struct KeyboardPane: View { } } - private var keyboardMaxHeight: CGFloat { - let rows = CGFloat(KeyboardLayout.rows.count) - let scaledKeySize = KeyboardLayout.keySize * maxKeyboardScale - let scaledRowSpacing = KeyboardLayout.rowSpacing * maxKeyboardScale - let keyboardHeight = (scaledKeySize * rows) + (scaledRowSpacing * (rows - 1)) - // Add padding (8px for .padding(.vertical, 4)) + 32px for the overlapping text - return ceil(keyboardHeight) + 40 - } - private func saveItem(_ item: ActionOrGroup) { var group = currentGroup let newActions = group.actions.filter { existing in @@ -787,6 +779,49 @@ struct KeyboardPane: View { updateConfig(with: group) } + /// 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) } diff --git a/Leader Key/UserConfig.swift b/Leader Key/UserConfig.swift index 0ca62e76..bd8560b0 100644 --- a/Leader Key/UserConfig.swift +++ b/Leader Key/UserConfig.swift @@ -602,6 +602,17 @@ enum ActionOrGroup: Codable, Equatable { } } + func withKey(_ key: String?) -> 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/Views/ActionIcon.swift b/Leader Key/Views/ActionIcon.swift index 077e6dc2..f614b867 100644 --- a/Leader Key/Views/ActionIcon.swift +++ b/Leader Key/Views/ActionIcon.swift @@ -35,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") 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) + } + } +} From 43adaa097ef1d810639a678a93de72eef378c0e0 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 9 Nov 2026 20:18:39 -0800 Subject: [PATCH 19/22] feat(mystery-box): show the group's icon in the hint Co-Authored-By: Claude Fable 5.2 --- Leader Key/Themes/MysteryBox.swift | 9 +++++++++ 1 file changed, 9 insertions(+) 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 } From 21ce2f9ec89d27896fb9beebee7e9139d918312b Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 9 Nov 2026 20:18:39 -0800 Subject: [PATCH 20/22] perf(cheatsheet): keep the keyboard cheatsheet at one scale The keyboard switched between 1.0x and 1.4x on every open and hide, which rebuilt all 60 keys and reloaded every icon each time. It is only ever shown centered, so the scale is now fixed. Drawing on open drops from a median of 55 ms to 10 ms (Release, 30 opens per side in a VM). The view now observes UserConfig directly, since the scale flip was also what made config edits appear on the next open. Co-Authored-By: Claude Fable 5.2 --- Leader Key/Cheatsheet.swift | 4 +++- Leader Key/Controller.swift | 3 --- .../KeyboardLayout/KeyboardCheatsheetView.swift | 11 +++++++---- Leader Key/UserState.swift | 1 - 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Leader Key/Cheatsheet.swift b/Leader Key/Cheatsheet.swift index 832205b5..9205c5d3 100644 --- a/Leader Key/Cheatsheet.swift +++ b/Leader Key/Cheatsheet.swift @@ -4,7 +4,9 @@ import SwiftUI enum Cheatsheet { static func createWindow(for userState: UserState) -> NSWindow { - let view = CheatsheetView().environmentObject(userState) + let view = CheatsheetView() + .environmentObject(userState) + .environmentObject(userState.userConfig as UserConfig) let controller = NSHostingController(rootView: view) controller.sizingOptions = .preferredContentSize let cheatsheet = PanelWindow( diff --git a/Leader Key/Controller.swift b/Leader Key/Controller.swift index d259d6da..9e8a8f75 100644 --- a/Leader Key/Controller.swift +++ b/Leader Key/Controller.swift @@ -85,7 +85,6 @@ class Controller { // Reset centered mode state window.alphaValue = 1 isCheatsheetCentered = false - userState.cheatsheetCentered = false window.hide { self.clear() @@ -359,7 +358,6 @@ class Controller { // Hide the main window visually but keep it as key window for input window.alphaValue = 0 isCheatsheetCentered = true - userState.cheatsheetCentered = true sizeCheatsheetWindowToFitContent() centerCheatsheetWindow() cheatsheetWindow?.orderFront(nil) @@ -388,7 +386,6 @@ class Controller { if isCheatsheetCentered { window.alphaValue = 1 isCheatsheetCentered = false - userState.cheatsheetCentered = false cheatsheetWindow?.orderOut(nil) } } diff --git a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift index 9ea59cd5..82674a3c 100644 --- a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift +++ b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift @@ -2,10 +2,12 @@ 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 - var scale: CGFloat { - userState.cheatsheetCentered ? KeyboardLayout.centeredScale : 1.0 - } + // 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] = [:] @@ -13,7 +15,7 @@ struct KeyboardCheatsheetView: View { let actions = (userState.currentGroup != nil) ? userState.currentGroup!.actions - : userState.userConfig.root.actions + : userConfig.root.actions for item in actions { switch item { @@ -83,5 +85,6 @@ struct KeyboardCheatsheetView: View { return KeyboardCheatsheetView() .environmentObject(state) + .environmentObject(config) .frame(width: 700, height: 350) } diff --git a/Leader Key/UserState.swift b/Leader Key/UserState.swift index b44ffa82..148ad2c5 100644 --- a/Leader Key/UserState.swift +++ b/Leader Key/UserState.swift @@ -9,7 +9,6 @@ final class UserState: ObservableObject { @Published var isShowingRefreshState: Bool @Published var navigationPath: [Group] = [] @Published var shiftHeld: Bool = false - @Published var cheatsheetCentered: Bool = false var currentGroup: Group? { return navigationPath.last From 1e2bd76130a9f12d74c1e47f4670a6461609f5b1 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Mon, 9 Nov 2026 20:27:41 -0800 Subject: [PATCH 21/22] perf(icons): cache rendered app and custom icons Entering a group decoded each of its icon files from disk on the main thread every time. Rendered icons are now kept in memory and dropped when the config reloads. Entering a group with 14 icons goes from a median of 34 ms to 15 ms after the first visit (Release, 25 entries per side in a VM). Co-Authored-By: Claude Fable 5.2 --- Leader Key/Controller.swift | 1 + Leader Key/Views/ActionIcon.swift | 28 +++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Leader Key/Controller.swift b/Leader Key/Controller.swift index 9e8a8f75..3723bf78 100644 --- a/Leader Key/Controller.swift +++ b/Leader Key/Controller.swift @@ -41,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() diff --git a/Leader Key/Views/ActionIcon.swift b/Leader Key/Views/ActionIcon.swift index f614b867..8e056574 100644 --- a/Leader Key/Views/ActionIcon.swift +++ b/Leader Key/Views/ActionIcon.swift @@ -69,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 @@ -92,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 } @@ -129,7 +153,9 @@ struct CustomIconImage: View { } private func loadImage(path: String) -> NSImage? { - CustomIconRenderer.renderCustomIcon(from: path, size: size) + IconCache.image(kind: "custom", path: path, size: size) { + CustomIconRenderer.renderCustomIcon(from: path, size: size) + } } } From f01efd90b850e646092b3a046151f8d541c12747 Mon Sep 17 00:00:00 2001 From: Kevin Traver Date: Tue, 10 Nov 2026 08:12:13 -0800 Subject: [PATCH 22/22] feat(keyboard): right-click a key to open, edit or delete its binding Deleting a group that has bindings asks first, and deleting a top-level group also removes its global shortcut. Co-Authored-By: Claude Fable 5.2 --- Leader Key/KeyboardLayout/KeyView.swift | 19 +++++ .../KeyboardLayout/KeyboardLayoutView.swift | 11 ++- Leader Key/Settings/KeyboardPane.swift | 82 ++++++++++++++++--- 3 files changed, 100 insertions(+), 12 deletions(-) diff --git a/Leader Key/KeyboardLayout/KeyView.swift b/Leader Key/KeyboardLayout/KeyView.swift index 32d96b95..7cf15535 100644 --- a/Leader Key/KeyboardLayout/KeyView.swift +++ b/Leader Key/KeyboardLayout/KeyView.swift @@ -13,6 +13,8 @@ struct KeyView: View { 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 @@ -153,6 +155,13 @@ struct KeyView: View { } } ) + .contextMenu { + ForEach(menuItems) { item in + Button(role: item.isDestructive ? .destructive : nil, action: item.action) { + Label(item.title, systemImage: item.systemImage) + } + } + } .zIndex(isHovered ? 1 : 0) } @@ -205,6 +214,16 @@ struct KeyView: View { } } +/// 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. diff --git a/Leader Key/KeyboardLayout/KeyboardLayoutView.swift b/Leader Key/KeyboardLayout/KeyboardLayoutView.swift index a1722b7d..ede8561a 100644 --- a/Leader Key/KeyboardLayout/KeyboardLayoutView.swift +++ b/Leader Key/KeyboardLayout/KeyboardLayoutView.swift @@ -11,6 +11,8 @@ struct KeyboardLayoutView: View { 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? @@ -34,7 +36,8 @@ struct KeyboardLayoutView: View { }, onDragStart: canRearrange(keyDef) ? { draggedBindingKey = bindingKey(for: keyDef) } : nil, - dropDelegate: canRearrange(keyDef) ? dropDelegate(for: keyDef) : nil + dropDelegate: canRearrange(keyDef) ? dropDelegate(for: keyDef) : nil, + menuItems: menuItems(for: keyDef) ) } } @@ -59,6 +62,12 @@ struct KeyboardLayoutView: View { 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 } diff --git a/Leader Key/Settings/KeyboardPane.swift b/Leader Key/Settings/KeyboardPane.swift index 1641e1f3..ddc19fb7 100644 --- a/Leader Key/Settings/KeyboardPane.swift +++ b/Leader Key/Settings/KeyboardPane.swift @@ -509,6 +509,7 @@ struct KeyboardPane: View { @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 @@ -659,10 +660,13 @@ struct KeyboardPane: View { }, 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 a binding to move or swap it") + Text("Click a key to configure, drag to move or swap, right-click for more") .font(.body) .foregroundColor(.secondary) .frame(maxWidth: .infinity, alignment: .center) @@ -718,10 +722,13 @@ struct KeyboardPane: View { }, onDelete: { if let group = editingGroupWrapper?.group { - deleteGroup(group) - // If we deleted the current group, pop back - if !currentGroupPath.isEmpty { + 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 @@ -731,6 +738,20 @@ struct KeyboardPane: View { } ) } + .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 @@ -777,6 +798,48 @@ struct KeyboardPane: View { 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. @@ -842,13 +905,10 @@ struct KeyboardPane: View { } private func updateConfig(with modifiedGroup: KeyGroup) { - if currentGroupPath.isEmpty { - config.root = modifiedGroup - } else { - var root = config.root - if root.update(group: modifiedGroup) { - config.root = root - } + // 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 } }