fenilsonani / menu-browser / Sources/ AppDelegate.swift

import AppKit
import SwiftUI
import ServiceManagement
import Combine
import os
import QuartzCore

private let log = Logger(subsystem: "com.fenilsonani.MenuBrowser", category: "AppDelegate")

/// Typed payload for browser menu items (clipboard, private mode).
private struct BrowserURLAction {
    let url: URL
    let browser: BrowserInfo
}

private let webSchemes: Set<String> = ["http", "https"]

class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate, NSSearchFieldDelegate {

    private var statusItem: NSStatusItem!
    private let menu = NSMenu()
    private let browserManager = BrowserManager()
    private let preferencesState = PreferencesState()
    let urlRuleManager = URLRuleManager()
    private var preferencesWindow: NSWindow?
    private var onboardingWindow: NSWindow?
    private var helpWindow: NSWindow?

    private lazy var searchField: NSSearchField = {
        let search = NSSearchField(frame: .zero)
        search.placeholderString = "Filter browsers\u{2026}"
        search.font = .systemFont(ofSize: 13)
        search.delegate = self
        search.sendsSearchStringImmediately = true
        search.sendsWholeSearchString = false
        search.focusRingType = .none
        return search
    }()
    private static let searchHorizontalInset: CGFloat = 14
    private static let searchInitialWidth: CGFloat = 260
    private static let searchHeight: CGFloat = 32

    private lazy var searchContainer: NSView = {
        let container = NSView(frame: NSRect(x: 0, y: 0, width: Self.searchInitialWidth, height: Self.searchHeight))
        container.autoresizingMask = [.width]
        let fieldWidth = Self.searchInitialWidth - Self.searchHorizontalInset * 2
        searchField.frame = NSRect(x: Self.searchHorizontalInset, y: 4, width: fieldWidth, height: 24)
        searchField.autoresizingMask = [.width]
        container.addSubview(searchField)
        return container
    }()
    private lazy var searchMenuItem: NSMenuItem = {
        let item = NSMenuItem()
        item.view = searchContainer
        return item
    }()

    private var allMenuBrowsers: [BrowserInfo] = []
    private var fallbackChangeCancellable: AnyCancellable?

    func applicationWillFinishLaunching(_ notification: Notification) {
        // URL handlers must be registered *before* didFinishLaunching, otherwise a kAEGetURL
        // event delivered as part of the launch (e.g. user clicks a link with MenuBrowser as
        // default while MenuBrowser is not running) arrives before our handler exists and is
        // silently dropped — which presents as "rules don't work on the first click."
        NSAppleEventManager.shared().setEventHandler(
            self,
            andSelector: #selector(handleURLEvent(_:withReply:)),
            forEventClass: AEEventClass(kInternetEventClass),
            andEventID: AEEventID(kAEGetURL)
        )
    }

    func application(_ application: NSApplication, open urls: [URL]) {
        // Modern AppKit URL entrypoint — fires on macOS 11+ as a peer to the kAEGetURL Apple
        // Event. Some clients (especially command-line `open` and certain SwiftUI helpers)
        // hit this path instead of the legacy one, so we route both through the same logic.
        for url in urls { route(url: url) }
    }

    func applicationDidFinishLaunching(_ notification: Notification) {
        log.info("MenuBrowser launched")

        // LaunchServices binds the default-browser handler to the bundle's path. Running from
        // ~/Downloads or a build folder makes the "Set as Default" flow flaky, and macOS will
        // sometimes refuse to dispatch URLs to a bundle outside /Applications. Offer to move
        // ourselves before continuing.
        if offerMoveToApplicationsIfNeeded() { return }

        browserManager.reloadBrowsers() // pre-cache for fast URL routing
        ensureFallbackBrowserSelected()
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)

        updateStatusBarIcon()

        menu.delegate = self
        statusItem.menu = menu

        setupHotkey()
        preferencesState.onShortcutChanged = { [weak self] in
            self?.setupHotkey()
        }

        // Refresh the menu bar icon whenever the fallback browser changes — covers updates
        // made from Preferences (menu clicks update the icon synchronously in browserSelected).
        // @Published fires in willSet, so we re-read on the next main-queue tick when the
        // property holds the new value.
        fallbackChangeCancellable = urlRuleManager.$fallbackBrowserID
            .removeDuplicates()
            .receive(on: DispatchQueue.main)
            .sink { [weak self] _ in self?.updateStatusBarIcon() }

        // Show onboarding on first launch
        if !UserDefaults.standard.bool(forKey: "onboardingCompleted") {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
                self?.showOnboarding()
            }
        }
    }

    @objc private func handleURLEvent(_ event: NSAppleEventDescriptor, withReply reply: NSAppleEventDescriptor) {
        guard let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
              let url = URL(string: urlString) else { return }
        route(url: url)
    }

    private func route(url: URL) {
        log.info("Routing URL: \(url.absoluteString)")

        // Hot path: rule match with profile support
        if let rule = urlRuleManager.matchingRule(for: url, recordHit: true) {
            log.info("Rule hit: \(rule.pattern) → \(rule.browserBundleID)")
            if let browser = browserManager.browser(forBundleID: rule.browserBundleID) {
                browserManager.openURL(url, in: browser, profile: rule.profileDirectory)
            } else {
                browserManager.openURL(url, inBundleID: rule.browserBundleID)
            }
            DispatchQueue.main.async { self.pulseStatusBarIcon() }
            return
        }

        // Fallback: O(1) dictionary lookup
        if let fallbackID = urlRuleManager.fallbackBrowserID {
            log.info("No rule matched, using fallback: \(fallbackID)")
            browserManager.openURL(url, inBundleID: fallbackID)
            DispatchQueue.main.async { self.pulseStatusBarIcon() }
            return
        }

        // Last resort: open with first cached browser
        if let browser = browserManager.installedBrowsers().first {
            log.info("No fallback, using first installed browser: \(browser.name)")
            browserManager.openURL(url, in: browser)
        } else {
            log.warning("No browser available to route \(url.absoluteString)")
        }
    }

    private func updateStatusBarIcon() {
        statusItem.button?.image = currentStatusBarIcon()
    }

    private func currentStatusBarIcon() -> NSImage {
        // The menu bar icon mirrors the currently-selected fallback browser so the user can
        // see at a glance where unrouted URLs will land.
        if let fallbackID = urlRuleManager.fallbackBrowserID,
           let browser = browserManager.browser(forBundleID: fallbackID) {
            return browser.icon
        }
        return NSImage(systemSymbolName: "globe", accessibilityDescription: "MenuBrowser") ?? NSImage()
    }

    private func pulseStatusBarIcon() {
        // Can be invoked from a URL event during cold launch, before applicationDidFinishLaunching
        // has created the status item — bail out silently rather than trapping on the implicit
        // optional.
        guard let statusItem, let button = statusItem.button else { return }
        button.wantsLayer = true
        let pulse = CAKeyframeAnimation(keyPath: "transform.scale")
        pulse.values = [1.0, 1.3, 1.0]
        pulse.keyTimes = [0, 0.3, 1.0]
        pulse.duration = 0.3
        button.layer?.add(pulse, forKey: "pulse")
    }

    private func setupHotkey() {
        let shortcut = preferencesState.shortcut
        let keyCode = UInt32(shortcut.keyCode)
        let modifiers = carbonModifiers(from: shortcut.modifiers)

        log.info("Registering hotkey: keyCode=\(keyCode), modifiers=\(modifiers)")
        do {
            try HotkeyManager.shared.register(keyCode: keyCode, carbonModifiers: modifiers)
            preferencesState.shortcutError = nil
        } catch let error as HotkeyError {
            log.error("Hotkey registration failed: \(error.message)")
            preferencesState.shortcutError = error.message
        } catch {
            preferencesState.shortcutError = error.localizedDescription
        }

        HotkeyManager.shared.onHotKey = { [weak self] in
            self?.statusItem.button?.performClick(nil)
        }
    }

    // MARK: - NSMenuDelegate

    func menuWillOpen(_ menu: NSMenu) {
        allMenuBrowsers = preferencesState.orderedBrowsers(from: browserManager.installedBrowsers())
        searchField.stringValue = ""
        rebuildEntireMenu(query: "")
    }

    func menuNeedsUpdate(_ menu: NSMenu) {
        // menuWillOpen already rebuilt the menu; this fires on re-displays only.
        if menu.numberOfItems == 0 {
            rebuildEntireMenu(query: "")
        }
    }

    func menuDidClose(_ menu: NSMenu) {
        searchField.stringValue = ""
    }

    // MARK: - Menu Construction

    private func rebuildEntireMenu(query: String) {
        menu.removeAllItems()
        menu.addItem(searchMenuItem)
        menu.addItem(.separator())
        rebuildDynamicMenuContent(query: query)
    }

    private func rebuildDynamicMenuContent(query: String) {
        // Preserve the search field + its separator by tagged identity.
        guard let searchIndex = menu.items.firstIndex(of: searchMenuItem) else {
            rebuildEntireMenu(query: query)
            return
        }
        let firstDynamicIndex = searchIndex + 2  // search item + separator
        while menu.items.count > firstDynamicIndex {
            menu.removeItem(at: firstDynamicIndex)
        }
        appendDynamicMenuSections(query: query)
    }

    private func appendDynamicMenuSections(query: String) {
        if allMenuBrowsers.isEmpty {
            menu.addItem(disabledItem("No browsers detected"))
            appendUtilityItems()
            return
        }

        let fallbackID = urlRuleManager.fallbackBrowserID
        let trimmedQuery = query.trimmingCharacters(in: .whitespaces)

        if !trimmedQuery.isEmpty {
            let filtered = allMenuBrowsers.filter { $0.name.lowercased().contains(trimmedQuery) }
            if filtered.isEmpty {
                menu.addItem(disabledItem("No browsers match"))
            } else {
                appendBrowserSection(
                    title: "Matching Browsers",
                    browsers: filtered,
                    selectedID: fallbackID,
                    showsShortcuts: false
                )
            }
            appendUtilityItems()
            return
        }

        appendDefaultBrowserBanner(selectedID: fallbackID)
        appendRecentBrowsers(selectedID: fallbackID)
        appendBrowserSection(
            title: "Set Default",
            browsers: allMenuBrowsers,
            selectedID: fallbackID,
            showsShortcuts: true
        )
        appendClipboardSection(browsers: allMenuBrowsers)
        appendUtilityItems()
    }

    /// Shows the currently-active default browser at the top of the menu so the user can see
    /// it at a glance — the small checkmark in the "Set Default" section was easy to miss.
    private func appendDefaultBrowserBanner(selectedID: String?) {
        guard let selectedID,
              let browser = allMenuBrowsers.first(where: { $0.bundleIdentifier.equalsIgnoringCase(selectedID) })
        else { return }
        let item = NSMenuItem()
        item.isEnabled = false
        item.image = browser.icon
        item.attributedTitle = NSAttributedString(
            string: "Default: \(browser.name)",
            attributes: [
                .font: NSFont.systemFont(ofSize: 12, weight: .medium),
                .foregroundColor: NSColor.secondaryLabelColor
            ]
        )
        menu.addItem(item)
    }

    private func appendRecentBrowsers(selectedID: String?) {
        let recentBrowsers = preferencesState.recentBrowserIDs.compactMap { id in
            allMenuBrowsers.first { $0.bundleIdentifier.equalsIgnoringCase(id) }
        }
        guard !recentBrowsers.isEmpty else { return }
        appendBrowserSection(
            title: "Recently Used",
            browsers: recentBrowsers,
            selectedID: selectedID,
            showsShortcuts: false
        )
    }

    private func appendBrowserSection(
        title: String,
        browsers: [BrowserInfo],
        selectedID: String?,
        showsShortcuts: Bool
    ) {
        guard !browsers.isEmpty else { return }
        appendSectionHeader(title)

        for (index, browser) in browsers.enumerated() {
            let shortcut = (showsShortcuts && index < 9) ? "\(index + 1)" : ""
            let item = makeMenuItem(
                title: browser.name,
                icon: browser.icon,
                action: #selector(browserSelected(_:)),
                keyEquivalent: shortcut,
                representedObject: browser
            )
            if let selectedID, browser.bundleIdentifier.equalsIgnoringCase(selectedID) {
                item.state = .on
            }
            menu.addItem(item)
        }
    }

    private func appendClipboardSection(browsers: [BrowserInfo]) {
        guard let clipboardURL = clipboardURL() else {
            appendSectionHeader("Clipboard")
            menu.addItem(disabledItem("No URL on clipboard"))
            return
        }

        appendSectionHeader("Clipboard")
        menu.addItem(disabledItem(truncateURL(clipboardURL.absoluteString)))

        for browser in browsers {
            menu.addItem(makeMenuItem(
                title: browser.name,
                icon: browser.icon,
                action: #selector(openClipboardURL(_:)),
                representedObject: BrowserURLAction(url: clipboardURL, browser: browser)
            ))
        }

        let privateItem = NSMenuItem(title: "Open Private", action: nil, keyEquivalent: "")
        let privateSub = NSMenu()
        for browser in browsers {
            privateSub.addItem(makeMenuItem(
                title: browser.name,
                icon: browser.icon,
                action: #selector(openClipboardURLPrivate(_:)),
                representedObject: BrowserURLAction(url: clipboardURL, browser: browser)
            ))
        }
        privateItem.submenu = privateSub
        menu.addItem(privateItem)
    }

    private func appendUtilityItems() {
        menu.addItem(.separator())
        if let shortcutError = preferencesState.shortcutError {
            // Don't advertise a shortcut that never registered.
            let item = disabledItem("\u{26A0}\u{FE0E} \(shortcutError)")
            item.toolTip = shortcutError
            menu.addItem(item)
        } else {
            menu.addItem(disabledItem("\(preferencesState.shortcutDisplay) to open this menu"))
        }
        menu.addItem(.separator())

        menu.addItem(makeActionItem(title: "Preferences\u{2026}", action: #selector(showPreferences), keyEquivalent: ","))
        menu.addItem(makeActionItem(title: "Help", action: #selector(showHelp), keyEquivalent: "?"))
        menu.addItem(makeActionItem(title: "About MenuBrowser", action: #selector(showAbout)))

        menu.addItem(.separator())
        menu.addItem(makeActionItem(title: "Quit MenuBrowser", action: #selector(quitApp), keyEquivalent: "q"))
    }

    // MARK: - Menu Item Builders

    private func makeMenuItem(
        title: String,
        icon: NSImage?,
        action: Selector,
        keyEquivalent: String = "",
        representedObject: Any? = nil
    ) -> NSMenuItem {
        let item = NSMenuItem(title: title, action: action, keyEquivalent: keyEquivalent)
        item.target = self
        item.image = icon
        item.representedObject = representedObject
        return item
    }

    private func makeActionItem(title: String, action: Selector, keyEquivalent: String = "") -> NSMenuItem {
        let item = NSMenuItem(title: title, action: action, keyEquivalent: keyEquivalent)
        item.target = self
        return item
    }

    private func disabledItem(_ text: String) -> NSMenuItem {
        let item = NSMenuItem(title: text, action: nil, keyEquivalent: "")
        item.isEnabled = false
        return item
    }

    /// Adds a section header preceded by a separator, unless it's the first section after the search bar.
    private func appendSectionHeader(_ title: String) {
        if let searchIndex = menu.items.firstIndex(of: searchMenuItem),
           menu.items.count > searchIndex + 2 {
            menu.addItem(.separator())
        }
        menu.addItem(sectionHeader(title))
    }

    private static let sectionHeaderAttributes: [NSAttributedString.Key: Any] = [
        .font: NSFont.systemFont(ofSize: 11, weight: .semibold),
        .foregroundColor: NSColor.secondaryLabelColor
    ]

    private func sectionHeader(_ title: String) -> NSMenuItem {
        let item = NSMenuItem()
        item.isEnabled = false
        item.attributedTitle = NSAttributedString(string: title, attributes: Self.sectionHeaderAttributes)
        return item
    }

    /// Shows "host/path" when possible so users can see what domain they're targeting,
    /// and ellipsizes the middle for long URLs.
    private func truncateURL(_ urlString: String) -> String {
        let display: String
        if let url = URL(string: urlString), let host = url.host {
            let path = url.path.isEmpty ? "" : url.path
            display = host + path
        } else {
            display = urlString
        }

        guard display.count > 45 else { return display }
        let prefix = display.prefix(28)
        let suffix = display.suffix(14)
        return "\(prefix)\u{2026}\(suffix)"
    }

    // MARK: - Actions

    private func clipboardURL() -> URL? {
        guard let string = NSPasteboard.general.string(forType: .string),
              let url = URL(string: string),
              let scheme = url.scheme?.lowercased(),
              webSchemes.contains(scheme)
        else { return nil }
        return url
    }

    func controlTextDidChange(_ notification: Notification) {
        guard let search = notification.object as? NSSearchField, search === searchField else { return }
        rebuildDynamicMenuContent(query: search.stringValue.lowercased())
    }

    @objc private func openClipboardURL(_ sender: NSMenuItem) {
        guard let action = sender.representedObject as? BrowserURLAction else { return }
        browserManager.openURL(action.url, in: action.browser)
    }

    @objc private func openClipboardURLPrivate(_ sender: NSMenuItem) {
        guard let action = sender.representedObject as? BrowserURLAction else { return }
        browserManager.openURLPrivate(action.url, in: action.browser)
    }

    @objc private func browserSelected(_ sender: NSMenuItem) {
        guard let browser = sender.representedObject as? BrowserInfo else { return }
        log.info("Default browser set via menu → \(browser.name)")
        urlRuleManager.fallbackBrowserID = browser.bundleIdentifier
        preferencesState.pushRecent(browserID: browser.bundleIdentifier)
        // Update the status bar icon synchronously so the click feels instant. The Combine
        // subscription would also fire, but it runs deferred + animated and can briefly look
        // like nothing happened.
        statusItem.button?.image = browser.icon
    }

    @objc private func showPreferences() {
        preferencesState.refreshBrowsers(using: browserManager)

        if preferencesWindow == nil {
            let view = PreferencesView(
                state: preferencesState,
                ruleManager: urlRuleManager,
                browserManager: browserManager
            )
            let hostingView = NSHostingView(rootView: view)

            let window = NSWindow(
                contentRect: NSRect(x: 0, y: 0, width: 720, height: 600),
                styleMask: [.titled, .closable, .resizable],
                backing: .buffered,
                defer: false
            )
            window.title = "MenuBrowser Settings"
            window.contentView = hostingView
            window.contentMinSize = NSSize(width: 680, height: 560)
            // Bumped autosave name so the new larger frame is used on first open.
            window.setFrameAutosaveName("MenuBrowserPreferencesV2")
            if !window.setFrameUsingName("MenuBrowserPreferencesV2") {
                window.center()
            }
            window.isReleasedWhenClosed = false

            preferencesWindow = window
        }

        preferencesWindow?.makeKeyAndOrderFront(nil)
        NSApp.activate()
    }

    private func showOnboarding() {
        if onboardingWindow == nil {
            let browsers = browserManager.installedBrowsers()
            let view = OnboardingView(
                browsers: browsers,
                ruleManager: urlRuleManager,
                browserManager: browserManager,
                onComplete: { [weak self] in self?.onboardingWindow?.close() },
                onOpenPreferences: { [weak self] in self?.showPreferences() }
            )
            let hostingView = NSHostingView(rootView: view)

            let window = NSWindow(
                contentRect: NSRect(x: 0, y: 0, width: 520, height: 480),
                styleMask: [.titled, .closable, .fullSizeContentView],
                backing: .buffered,
                defer: false
            )
            window.titlebarAppearsTransparent = true
            window.titleVisibility = .hidden
            window.isMovableByWindowBackground = true
            window.contentView = hostingView
            window.center()
            window.isReleasedWhenClosed = false

            onboardingWindow = window
        }

        onboardingWindow?.makeKeyAndOrderFront(nil)
        NSApp.activate()
    }

    @objc private func showAbout() {
        let credits = NSAttributedString(
            string: "A browser router for macOS.\nMade by Fenil Sonani.",
            attributes: [
                .font: NSFont.systemFont(ofSize: 11),
                .foregroundColor: NSColor.secondaryLabelColor
            ]
        )
        NSApp.orderFrontStandardAboutPanel(options: [
            .credits: credits,
            .applicationName: "MenuBrowser"
        ])
        NSApp.activate()
    }

    @objc private func showHelp() {
        if helpWindow == nil {
            let view = HelpView()
            let hostingView = NSHostingView(rootView: view)

            let window = NSWindow(
                contentRect: NSRect(x: 0, y: 0, width: 480, height: 500),
                styleMask: [.titled, .closable],
                backing: .buffered,
                defer: false
            )
            window.title = "MenuBrowser Help"
            window.contentView = hostingView
            window.center()
            window.isReleasedWhenClosed = false

            helpWindow = window
        }

        helpWindow?.makeKeyAndOrderFront(nil)
        NSApp.activate()
    }

    @objc private func quitApp() {
        NSApp.terminate(nil)
    }

    // MARK: - Fallback Browser Bootstrap

    /// Ensures `URLRuleManager.fallbackBrowserID` always points at a real, installed browser.
    /// On first run we try to use the *current* system default (which is MenuBrowser if the
    /// user already promoted us — in that case we pick the first non-MenuBrowser browser
    /// alphabetically, typically Safari). This makes "no rule matched → fallback browser"
    /// behave deterministically instead of silently selecting a random first-installed app.
    private func ensureFallbackBrowserSelected() {
        let installed = browserManager.installedBrowsers()  // already excludes MenuBrowser
        guard !installed.isEmpty else { return }

        // If a fallback is set and it still resolves to an installed browser, leave it alone.
        if let id = urlRuleManager.fallbackBrowserID,
           installed.contains(where: { $0.bundleIdentifier.equalsIgnoringCase(id) }) {
            return
        }

        // Otherwise pick the first installed browser (Safari sorts to the top on most setups).
        // Users can change this anytime in Preferences → Rules → Defaults.
        let pick = installed.first!.bundleIdentifier
        log.info("No fallback browser configured; auto-selecting \(pick)")
        urlRuleManager.fallbackBrowserID = pick
    }

    // MARK: - Move to /Applications

    /// If the bundle is already inside any `/Applications` directory (system or user),
    /// returns false and lets launch continue. Otherwise prompts the user; on accept
    /// it copies the bundle to /Applications, relaunches from there, and terminates.
    /// Returns true if a relaunch is in progress (caller should bail out).
    private func offerMoveToApplicationsIfNeeded() -> Bool {
        let bundlePath = Bundle.main.bundleURL.resolvingSymlinksInPath().path
        if bundlePath.contains("/Applications/") { return false }
        // Skip the prompt during local development so devs aren't nagged on every rebuild.
        if bundlePath.contains("/DerivedData/") || bundlePath.contains("/build/") {
            log.info("Running from dev build path, skipping move-to-Applications prompt")
            return false
        }

        let alert = NSAlert()
        alert.messageText = "Move MenuBrowser to Applications?"
        alert.informativeText = """
        MenuBrowser is running from \(bundlePath).

        macOS ties Accessibility permissions to the app's location. To make permissions \
        stick and let auto-updates work, move MenuBrowser to your Applications folder.
        """
        alert.addButton(withTitle: "Move to Applications")
        alert.addButton(withTitle: "Don't Move")
        alert.alertStyle = .informational

        guard alert.runModal() == .alertFirstButtonReturn else { return false }

        let destination = URL(fileURLWithPath: "/Applications").appendingPathComponent(Bundle.main.bundleURL.lastPathComponent)
        let fm = FileManager.default

        do {
            if fm.fileExists(atPath: destination.path) {
                try fm.removeItem(at: destination)
            }
            try fm.copyItem(at: Bundle.main.bundleURL, to: destination)
        } catch {
            let failure = NSAlert()
            failure.messageText = "Couldn't move MenuBrowser"
            failure.informativeText = error.localizedDescription
            failure.alertStyle = .warning
            failure.runModal()
            return false
        }

        let config = NSWorkspace.OpenConfiguration()
        config.createsNewApplicationInstance = true
        NSWorkspace.shared.openApplication(at: destination, configuration: config) { _, _ in
            DispatchQueue.main.async { NSApp.terminate(nil) }
        }
        return true
    }
}