fenilsonani / menu-browser / Sources/ BrowserManager.swift

import AppKit
import CoreServices
import os

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

extension String {
    /// Case-insensitive equality — replaces the `caseInsensitiveCompare(_:) == .orderedSame` chant.
    func equalsIgnoringCase(_ other: String) -> Bool {
        caseInsensitiveCompare(other) == .orderedSame
    }
}

struct BrowserInfo: Identifiable {
    var id: String { bundleIdentifier }
    let bundleIdentifier: String
    let name: String
    let icon: NSImage
    let appURL: URL
}

struct BrowserProfile: Identifiable {
    var id: String { "\(browserBundleID)|\(directory)" }
    let name: String
    let directory: String       // e.g. "Default", "Profile 1"
    let browserBundleID: String
}

class BrowserManager {

    private static let menuIconSize = NSSize(width: 18, height: 18)
    static let selfBundleID = Bundle.main.bundleIdentifier ?? "com.fenilsonani.MenuBrowser"
    private static let probeURL = URL(string: "https://example.com")!

    /// URL schemes MenuBrowser registers itself for when promoted to system default.
    private static let handledURLSchemes = ["http", "https"]

    /// LaunchServices applies a default-handler change asynchronously with no completion
    /// signal we can trust, so re-probe after a short settle delay.
    private static let defaultHandlerSettleDelay: TimeInterval = 1.5

    // Cached browser list and fast lookup by bundle ID
    private var cachedBrowsers: [BrowserInfo]?
    private var browserByID: [String: BrowserInfo] = [:]  // lowercased bundle ID → BrowserInfo

    func installedBrowsers() -> [BrowserInfo] {
        if let cached = cachedBrowsers { return cached }
        return reloadBrowsers()
    }

    @discardableResult
    func reloadBrowsers() -> [BrowserInfo] {
        let appURLs = NSWorkspace.shared.urlsForApplications(toOpen: Self.probeURL)
        var browsers: [BrowserInfo] = []
        browsers.reserveCapacity(appURLs.count)

        for appURL in appURLs {
            guard let bundle = Bundle(url: appURL),
                  let bundleID = bundle.bundleIdentifier,
                  !bundleID.equalsIgnoringCase(Self.selfBundleID)
            else { continue }

            let name = bundle.object(forInfoDictionaryKey: "CFBundleName") as? String
                ?? bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
                ?? appURL.deletingPathExtension().lastPathComponent

            browsers.append(BrowserInfo(
                bundleIdentifier: bundleID,
                name: name,
                icon: Self.renderAppIcon(at: appURL, size: Self.menuIconSize),
                appURL: appURL
            ))
        }

        browsers.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }

        browserByID.removeAll(keepingCapacity: true)
        for b in browsers {
            browserByID[b.bundleIdentifier.lowercased()] = b
        }

        cachedBrowsers = browsers
        log.info("Detected \(browsers.count) installed browsers")
        return browsers
    }

    /// Loads an app icon and rasterizes it to `size` at Retina density so it
    /// renders crisply in menus and the status bar (full color, never template).
    private static func renderAppIcon(at appURL: URL, size: NSSize) -> NSImage {
        let raw = NSWorkspace.shared.icon(forFile: appURL.path)
        let scale = NSScreen.main?.backingScaleFactor ?? 2.0
        let pixelW = max(1, Int((size.width * scale).rounded()))
        let pixelH = max(1, Int((size.height * scale).rounded()))

        guard let rep = NSBitmapImageRep(
            bitmapDataPlanes: nil,
            pixelsWide: pixelW, pixelsHigh: pixelH,
            bitsPerSample: 8, samplesPerPixel: 4,
            hasAlpha: true, isPlanar: false,
            colorSpaceName: .deviceRGB,
            bytesPerRow: 0, bitsPerPixel: 0
        ) else {
            raw.size = size
            raw.isTemplate = false
            return raw
        }
        rep.size = size

        NSGraphicsContext.saveGraphicsState()
        defer { NSGraphicsContext.restoreGraphicsState() }
        NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
        NSGraphicsContext.current?.imageInterpolation = .high
        raw.draw(in: NSRect(origin: .zero, size: size),
                 from: NSRect(origin: .zero, size: raw.size),
                 operation: .sourceOver, fraction: 1.0)

        let image = NSImage(size: size)
        image.addRepresentation(rep)
        image.isTemplate = false
        return image
    }

    /// O(1) browser lookup by bundle ID — used in the hot URL routing path.
    func browser(forBundleID id: String) -> BrowserInfo? {
        if cachedBrowsers == nil { reloadBrowsers() }
        return browserByID[id.lowercased()]
    }

    func invalidateCache() {
        cachedBrowsers = nil
        browserByID.removeAll()
    }

    // MARK: - System Default Handler

    /// Bundle ID of the app macOS currently routes web URLs to, or nil if none resolves.
    func systemDefaultBrowserBundleID() -> String? {
        NSWorkspace.shared.urlForApplication(toOpen: Self.probeURL)
            .flatMap { Bundle(url: $0)?.bundleIdentifier }
    }

    /// True when MenuBrowser itself is the system handler for web URLs.
    var isSystemDefaultBrowser: Bool {
        systemDefaultBrowserBundleID()?.equalsIgnoringCase(Self.selfBundleID) ?? false
    }

    enum DefaultHandlerResult {
        case success
        /// Carries a user-facing reason; the schemes are claimed independently, so a
        /// partial failure must not read as success.
        case failed(String)
    }

    /// Registers MenuBrowser as the http/https handler, then reports on the main queue
    /// whether the change actually took effect. Both schemes are awaited before the
    /// result is decided, and the live handler is re-probed rather than trusting the
    /// per-scheme callbacks — LaunchServices can report no error and still not switch.
    func promoteSelfToSystemDefault(completion: @escaping (DefaultHandlerResult) -> Void) {
        log.info("Requesting system default browser role")
        let appURL = Bundle.main.bundleURL
        let group = DispatchGroup()
        let lock = NSLock()
        var firstFailure: String?

        for scheme in Self.handledURLSchemes {
            group.enter()
            NSWorkspace.shared.setDefaultApplication(at: appURL, toOpenURLsWithScheme: scheme) { error in
                if let error {
                    log.warning("Failed to claim \(scheme): \(error.localizedDescription)")
                    lock.lock()
                    if firstFailure == nil { firstFailure = error.localizedDescription }
                    lock.unlock()
                }
                group.leave()
            }
        }

        group.notify(queue: .main) {
            DispatchQueue.main.asyncAfter(deadline: .now() + Self.defaultHandlerSettleDelay) { [self] in
                if isSystemDefaultBrowser {
                    completion(.success)
                } else {
                    completion(.failed(firstFailure ?? """
                    macOS didn't apply the change. Set MenuBrowser as the default browser \
                    in System Settings \u{203A} Desktop & Dock.
                    """))
                }
            }
        }
    }

    private let openConfig = NSWorkspace.OpenConfiguration()

    func openURL(_ url: URL, in browser: BrowserInfo) {
        log.info("Opening \(url.absoluteString) in \(browser.name)")
        NSWorkspace.shared.open([url], withApplicationAt: browser.appURL, configuration: openConfig)
    }

    /// Fast path: open URL by bundle ID without a full BrowserInfo lookup.
    func openURL(_ url: URL, inBundleID bundleID: String) {
        if let browser = browser(forBundleID: bundleID) {
            NSWorkspace.shared.open([url], withApplicationAt: browser.appURL, configuration: openConfig)
        }
    }

    // Known private/incognito CLI flags keyed by bundle-ID substring.
    // Safari has no CLI flag → falls through to normal open.
    private static let privateFlags: [(match: String, flag: String)] = [
        ("firefox",  "--private-window"),
        ("chrome",   "--incognito"),
        ("chromium", "--incognito"),
        ("brave",    "--incognito"),
        ("edge",     "--inprivate"),
        ("arc",      "--incognito"),
        ("vivaldi",  "--incognito"),
        ("opera",    "--private"),
    ]

    func openURLPrivate(_ url: URL, in browser: BrowserInfo) {
        log.info("Opening \(url.absoluteString) in \(browser.name) (private)")
        let bid = browser.bundleIdentifier.lowercased()

        if let entry = Self.privateFlags.first(where: { bid.contains($0.match) }),
           let execURL = Bundle(url: browser.appURL)?.executableURL {
            let process = Process()
            process.executableURL = execURL
            process.arguments = [entry.flag, url.absoluteString]
            do {
                try process.run()
                return
            } catch {
                log.warning("Private launch failed for \(browser.name): \(error.localizedDescription)")
            }
        }

        log.info("No private mode flag for \(browser.name), opening normally")
        openURL(url, in: browser)
    }

    // MARK: - Browser Profiles

    /// Returns Chromium profiles for a browser, or empty if not Chromium or only 1 profile.
    func profiles(for browser: BrowserInfo) -> [BrowserProfile] {
        let bid = browser.bundleIdentifier.lowercased()
        let home = FileManager.default.homeDirectoryForCurrentUser.path

        let localStatePath: String
        if bid.contains("com.google.chrome") {
            localStatePath = "\(home)/Library/Application Support/Google/Chrome/Local State"
        } else if bid.contains("com.microsoft.edgemac") || bid.contains("edge") {
            localStatePath = "\(home)/Library/Application Support/Microsoft Edge/Local State"
        } else if bid.contains("com.brave") || bid.contains("brave") {
            localStatePath = "\(home)/Library/Application Support/BraveSoftware/Brave-Browser/Local State"
        } else {
            return []
        }

        guard let data = FileManager.default.contents(atPath: localStatePath),
              let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
              let profileInfo = json["profile"] as? [String: Any],
              let infoCache = profileInfo["info_cache"] as? [String: Any] else {
            return []
        }

        var profiles: [BrowserProfile] = []
        for (dir, value) in infoCache {
            if let info = value as? [String: Any],
               let name = info["name"] as? String {
                profiles.append(BrowserProfile(name: name, directory: dir, browserBundleID: browser.bundleIdentifier))
            }
        }

        profiles.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }

        // Only return if there are 2+ profiles (single profile isn't useful)
        return profiles.count > 1 ? profiles : []
    }

    /// Opens a URL in a specific Chromium profile.
    func openURL(_ url: URL, in browser: BrowserInfo, profile: String?) {
        guard let profileDir = profile else {
            openURL(url, in: browser)
            return
        }

        log.info("Opening \(url.absoluteString) in \(browser.name) profile \(profileDir)")
        guard let execURL = Bundle(url: browser.appURL)?.executableURL else {
            openURL(url, in: browser)
            return
        }

        let process = Process()
        process.executableURL = execURL
        process.arguments = ["--profile-directory=\(profileDir)", url.absoluteString]
        try? process.run()
    }

}