Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions WrangURL/App/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {

guard !Self.isRunningTests else { return }

router.startTrackingClicks()

#if DEBUG
// Launch with `-DebugAppearance <light|dark>` to override the system appearance, e.g. for screenshots.
switch UserDefaults.standard.string(forKey: "DebugAppearance") {
Expand Down
35 changes: 35 additions & 0 deletions WrangURL/Core/ClickModifierTracker.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
23 changes: 23 additions & 0 deletions WrangURL/Core/ModifierKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
13 changes: 12 additions & 1 deletion WrangURL/Core/URLRouter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)?
Expand All @@ -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
Expand All @@ -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")
Expand Down
22 changes: 22 additions & 0 deletions WrangURLTests/RoutePlannerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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])
}
}