From 64dc323a4f842f26812168f8827a286c955340f3 Mon Sep 17 00:00:00 2001 From: Warrick Bayman Date: Mon, 28 Sep 2026 17:46:41 +0200 Subject: [PATCH] Count the keys held for the click that opened a link. Some apps pass links on slowly, so the user has often let go of the modifier keys by the time a link reaches WrangURL, and the picker didn't appear. ClickModifierTracker watches left clicks in every app with a global mouse monitor, which needs no extra permission, and remembers the keys held for the last one. A link that arrives within 2 seconds of a click with keys held uses that click's keys; otherwise the keys held on arrival count, as before. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- WrangURL/App/AppDelegate.swift | 2 ++ WrangURL/Core/ClickModifierTracker.swift | 35 ++++++++++++++++++++++++ WrangURL/Core/ModifierKeys.swift | 23 ++++++++++++++++ WrangURL/Core/URLRouter.swift | 13 ++++++++- WrangURLTests/RoutePlannerTests.swift | 22 +++++++++++++++ 6 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 WrangURL/Core/ClickModifierTracker.swift diff --git a/CLAUDE.md b/CLAUDE.md index 7b48eea..8ef1c2f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,7 +28,7 @@ App logs use subsystem `com.thepublicgood.wrangurl`. In zsh, `log` is a shell bu **URL flow.** macOS delivers URLs to `AppDelegate.application(_:open:)` → `URLRouter.handle`. The router queues URLs until `markReady()` in `applicationDidFinishLaunching`, because a cold launch can deliver them early. `URLRouter.preview(_:)` does the decision part: 1. `RuleMatcher` finds the first enabled rule matching the URL and its source app (`SourceApp`, read from the Apple Event's sender in `application(_:open:)`). It is compiled once per rules array and cached in the router. -2. `RoutePlanner` decides `.open(browserID)`, `.pick(browserIDs)` or `.noBrowserAvailable`. It applies the fallback browser (configured browser, then Safari, then the first installed one), the unmatched-URL behaviour, removal of uninstalled browsers, and "file URLs go to the fallback". Holding exactly `AppSettings.pickerModifiers` (default ⌥⌘) forces `.pick` with every browser; `URLRouter.handle` reads `NSEvent.modifierFlags` on arrival, before any queueing. +2. `RoutePlanner` decides `.open(browserID)`, `.pick(browserIDs)` or `.noBrowserAvailable`. It applies the fallback browser (configured browser, then Safari, then the first installed one), the unmatched-URL behaviour, removal of uninstalled browsers, and "file URLs go to the fallback". Holding exactly `AppSettings.pickerModifiers` (default ⌥⌘) forces `.pick` with every browser; `URLRouter.handle` works out the keys on arrival, before any queueing: those of a left click in the last 2 seconds (`ClickModifierTracker`, a global mouse monitor, since apps often deliver links after the keys are released), else `NSEvent.modifierFlags`. The router then either opens the URL via `NSWorkspace` or shows `BrowserPickerController`. The URL testers in Settings call `preview(_:)`, so they can't diverge from real routing. `RoutePlanner`, `RuleMatcher`/`SimplePattern`, `PickerAction` and the `Config` import helpers are deliberately AppKit-free and pure; keep new routing logic there so it stays unit-testable. diff --git a/WrangURL/App/AppDelegate.swift b/WrangURL/App/AppDelegate.swift index 82ccedf..78140b2 100644 --- a/WrangURL/App/AppDelegate.swift +++ b/WrangURL/App/AppDelegate.swift @@ -59,6 +59,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { guard !Self.isRunningTests else { return } + router.startTrackingClicks() + #if DEBUG // Launch with `-DebugAppearance ` to override the system appearance, e.g. for screenshots. switch UserDefaults.standard.string(forKey: "DebugAppearance") { diff --git a/WrangURL/Core/ClickModifierTracker.swift b/WrangURL/Core/ClickModifierTracker.swift new file mode 100644 index 0000000..d8bb4d4 --- /dev/null +++ b/WrangURL/Core/ClickModifierTracker.swift @@ -0,0 +1,35 @@ +import AppKit + +/// Remembers the modifier keys held for the last left click in any app, so a link that +/// arrives after the keys were released still counts as modifier-clicked. +/// +/// A global monitor sees mouse events without Accessibility or Input Monitoring permission; +/// only keyboard events need those. It doesn't see clicks in WrangURL's own windows, but links +/// opened from there are handled straight away, while the keys are still held. +@MainActor +final class ClickModifierTracker { + private(set) var lastClick: ModifierClick? + private var monitor: Any? + + func start() { + guard monitor == nil else { return } + monitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .leftMouseUp]) { [weak self] event in + let type = event.type + let keys = ModifierKeys(event.modifierFlags) + let time = event.timestamp + MainActor.assumeIsolated { + self?.record(type: type, keys: keys, time: time) + } + } + } + + private func record(type: NSEvent.EventType, keys: ModifierKeys, time: TimeInterval) { + // Apps open links on mouse down or mouse up. Keep the keys from both halves of the click, + // in case some were released in between. + if type == .leftMouseUp, let down = lastClick { + lastClick = ModifierClick(keys: down.keys.union(keys), time: time) + } else { + lastClick = ModifierClick(keys: keys, time: time) + } + } +} diff --git a/WrangURL/Core/ModifierKeys.swift b/WrangURL/Core/ModifierKeys.swift index 38355e1..0975802 100644 --- a/WrangURL/Core/ModifierKeys.swift +++ b/WrangURL/Core/ModifierKeys.swift @@ -47,3 +47,26 @@ extension ModifierKeys: Codable { try container.encode(Self.keys.filter { contains($0.key) }.map(\.name)) } } + +/// A mouse click somewhere on the system, and the modifier keys held for it. +struct ModifierClick: Equatable, Sendable { + var keys: ModifierKeys + /// Seconds since the Mac started, like `NSEvent.timestamp` and `ProcessInfo.systemUptime`. + var time: TimeInterval +} + +extension ModifierKeys { + /// How long after a click a link can arrive and still count as coming from it. + static let clickWindow: TimeInterval = 2 + + /// The keys that count for a link arriving at `now`. Some apps pass links on slowly, and + /// the user has often let go of the keys by the time one arrives, so the keys held for a + /// recent click win. Otherwise, such as for a link opened from the keyboard, the keys held + /// now count. + static func forLink(heldNow: ModifierKeys, lastClick: ModifierClick?, now: TimeInterval) -> ModifierKeys { + if let click = lastClick, !click.keys.isEmpty, (0...clickWindow).contains(now - click.time) { + return click.keys + } + return heldNow + } +} diff --git a/WrangURL/Core/URLRouter.swift b/WrangURL/Core/URLRouter.swift index adac3b7..ab7d71e 100644 --- a/WrangURL/Core/URLRouter.swift +++ b/WrangURL/Core/URLRouter.swift @@ -27,6 +27,7 @@ final class URLRouter { @ObservationIgnored private let browsers: BrowserRegistry @ObservationIgnored private let history: HistoryStore @ObservationIgnored private let picker = BrowserPickerController() + @ObservationIgnored private let clicks = ClickModifierTracker() @ObservationIgnored private var pending: [PendingURL] = [] @ObservationIgnored private var isReady = false @ObservationIgnored private var matcherCache: (rules: [Rule], matcher: RuleMatcher)? @@ -40,6 +41,11 @@ final class URLRouter { self.history = history } + /// Starts remembering the modifier keys of clicks in other apps. Not called when hosting tests. + func startTrackingClicks() { + clicks.start() + } + func markReady() { isReady = true let queued = pending @@ -52,7 +58,12 @@ final class URLRouter { /// Routes URLs clicked in `source`, the app they came from, if known. func handle(_ urls: [URL], from source: SourceApp? = nil) { // Read the keys now: by the time a queued URL is routed, the user may have let go. - let modifiers = ModifierKeys(NSEvent.modifierFlags) + let heldNow = ModifierKeys(NSEvent.modifierFlags) + let modifiers = ModifierKeys.forLink(heldNow: heldNow, lastClick: clicks.lastClick, now: ProcessInfo.processInfo.systemUptime) + if modifiers != heldNow, let click = clicks.lastClick { + let age = ProcessInfo.processInfo.systemUptime - click.time + Self.logger.info("Using \(modifiers.symbols, privacy: .public) from a click \(age, format: .fixed(precision: 2))s before the link arrived; held now: \(heldNow.symbols, privacy: .public)") + } guard isReady else { pending.append(contentsOf: urls.map { PendingURL(url: $0, source: source, modifiers: modifiers) }) Self.logger.info("Queued \(urls.count) URL(s) until launch finishes") diff --git a/WrangURLTests/RoutePlannerTests.swift b/WrangURLTests/RoutePlannerTests.swift index 84c1a8c..3d36c7c 100644 --- a/WrangURLTests/RoutePlannerTests.swift +++ b/WrangURLTests/RoutePlannerTests.swift @@ -127,4 +127,26 @@ struct RoutePlannerTests { let unknown = try JSONDecoder().decode(AppSettings.self, from: Data(#"{"pickerModifiers": ["option", "hyper"]}"#.utf8)) #expect(unknown.pickerModifiers == [.option]) } + + // MARK: Keys held for the click that opened a link + + @Test func recentClickKeysCountAfterRelease() { + let click = ModifierClick(keys: [.option, .command], time: 100) + #expect(ModifierKeys.forLink(heldNow: [], lastClick: click, now: 101.5) == [.option, .command]) + } + + @Test func staleClickIsIgnored() { + let click = ModifierClick(keys: [.option, .command], time: 100) + #expect(ModifierKeys.forLink(heldNow: [], lastClick: click, now: 102.5) == []) + } + + @Test func plainClickLeavesHeldKeys() { + // A link opened from the keyboard just after an ordinary click. + let click = ModifierClick(keys: [], time: 100) + #expect(ModifierKeys.forLink(heldNow: [.option, .command], lastClick: click, now: 100.5) == [.option, .command]) + } + + @Test func heldKeysCountWithoutAClick() { + #expect(ModifierKeys.forLink(heldNow: [.shift], lastClick: nil, now: 100) == [.shift]) + } }