Repository Public
1import AppKit2import SwiftUI34@MainActor5final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {6 private(set) var environment: AppEnvironment!7 private var settingsWindow: NSWindow?8 private var pendingURLs: [URL] = []9 private var didFinishLaunching = false1011 /// Hosted unit tests launch the app only as a container: no windows, no session restore, no user data.12 static var isRunningTests: Bool {13 ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil || NSClassFromString("XCTestCase") != nil14 }1516 func applicationDidFinishLaunching(_ notification: Notification) {17 let root = Self.isRunningTests18 ? FileManager.default.temporaryDirectory.appendingPathComponent("SPBrowserTestHost-\(UUID().uuidString)", isDirectory: true)19 : AppEnvironment.defaultRoot()20 environment = AppEnvironment(root: root, secrets: Self.isRunningTests ? InMemorySecretStore() : KeychainStore())21 NSApp.mainMenu = MainMenuBuilder.build(environment: environment, target: self)22 NotificationCenter.default.addObserver(forName: .spbShortcutsChanged, object: nil, queue: .main) { [weak self] _ in23 Task { @MainActor in24 guard let self else { return }25 NSApp.mainMenu = MainMenuBuilder.build(environment: self.environment, target: self)26 }27 }28 didFinishLaunching = true29 guard !Self.isRunningTests else { return }30 environment.start()3132 let restored = environment.settings.restoreSessionOnLaunch && environment.restoreSession()33 if !restored { environment.openWindow() }34 if let list = UserDefaults.standard.string(forKey: "SPBOpenURLs") {35 // Used by scripts and screenshots: the last address is shown.36 let urls = list.split(separator: ",").compactMap { URL(string: String($0)) }37 for (index, url) in urls.enumerated() { environment.keyState?.newTab(url: url, select: index == urls.count - 1) }38 }39 pendingURLs.forEach(environment.open(url:))40 pendingURLs = []41 if let note = environment.sessionRecoveryNote { environment.keyState?.toast = note }42 if environment.settingsRecoveredFromCorruption {43 environment.keyState?.toast = L("Your settings file was damaged and has been reset. A copy was kept next to it.")44 }45 NSApp.activate(ignoringOtherApps: true)46 if UserDefaults.standard.bool(forKey: "SPBPerfLog") { writeLaunchMetric() }47 // Used by scripts and screenshots: open Settings on a given pane (e.g. -SPBShowSettings account).48 if let pane = UserDefaults.standard.string(forKey: "SPBShowSettings"), let section = SettingsSection(rawValue: pane) { showSettings(section: section) }49 // Used by scripts and screenshots, only with an explicit data folder: show an AURA surface a few seconds after launch50 // (e.g. -SPBAura constellation|flow|canvas|portal|orbit|palette|focus|reader|newtab) and pick an ambient theme (-SPBAmbient cosmos).51 if UserDefaults.standard.string(forKey: "SPBDataDir") != nil {52 if let name = UserDefaults.standard.string(forKey: "SPBAmbient"), let theme = AmbientTheme(rawValue: name) { environment.settings.startPage.ambient = theme }53 if let surface = UserDefaults.standard.string(forKey: "SPBAura") {54 let delay = UserDefaults.standard.double(forKey: "SPBAuraDelay")55 DispatchQueue.main.asyncAfter(deadline: .now() + (delay > 0 ? delay : 6)) { [weak self] in56 guard let state = self?.environment.keyState else { return }57 switch surface {58 case "constellation": state.perform(.showConstellation)59 case "flow": state.perform(.showFlow)60 case "canvas": state.perform(.showCanvas)61 case "portal": state.perform(.showPortal)62 case "orbit": state.perform(.commandOrbit)63 case "palette": state.perform(.commandPalette)64 case "focus": state.perform(.toggleFocusMode)65 case "reader": state.perform(.toggleReader)66 case "newtab": state.perform(.newTab)67 default: break68 }69 }70 }71 }72 }7374 /// Opt-in launch measurement used by scripts/perf.sh: time from process creation to the first window being on screen.75 private func writeLaunchMetric() {76 var info = kinfo_proc()77 var size = MemoryLayout<kinfo_proc>.stride78 var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]79 guard sysctl(&mib, 4, &info, &size, nil, 0) == 0 else { return }80 let start = Double(info.kp_proc.p_starttime.tv_sec) + Double(info.kp_proc.p_starttime.tv_usec) / 1_000_00081 DispatchQueue.main.async { [environment] in82 let elapsed = (Date().timeIntervalSince1970 - start) * 100083 let line = "{\"launchToFirstWindowMs\": \(Int(elapsed))}\n"84 try? line.data(using: .utf8)?.write(to: environment!.root.appendingPathComponent("perf-launch.json"))85 }86 }8788 func applicationDidBecomeActive(_ notification: Notification) {89 guard didFinishLaunching, !Self.isRunningTests else { return }90 environment.applicationBecameActive()91 }9293 func applicationDidResignActive(_ notification: Notification) {94 guard didFinishLaunching, !Self.isRunningTests else { return }95 environment.applicationResignedActive()96 }9798 func application(_ application: NSApplication, open urls: [URL]) {99 let allowed = urls.filter { ["http", "https", "file"].contains($0.scheme?.lowercased() ?? "") }100 guard didFinishLaunching, !Self.isRunningTests else { pendingURLs += allowed; return }101 allowed.forEach(environment.open(url:))102 }103104 func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {105 if !flag, !Self.isRunningTests { environment.openWindow() }106 return true107 }108109 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }110111 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {112 guard !Self.isRunningTests else { return .terminateNow }113 let active = environment.downloads.activeCount114 if active > 0 {115 let alert = NSAlert()116 alert.messageText = L("%d downloads are still in progress", active)117 alert.informativeText = L("Quitting now will stop them.")118 alert.addButton(withTitle: L("Keep Downloading"))119 alert.addButton(withTitle: L("Quit"))120 if alert.runModal() == .alertFirstButtonReturn { return .terminateCancel }121 }122 // Save before windows start closing, otherwise the session would be written empty.123 environment.saveSessionNow()124 environment.isTerminating = true125 return .terminateNow126 }127128 func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { true }129130 func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {131 let menu = NSMenu()132 for command in [CommandID.newWindow, .newPrivateWindow] {133 let item = NSMenuItem(title: command.title, action: #selector(performCommand(_:)), keyEquivalent: "")134 item.target = self135 item.representedObject = command.rawValue136 menu.addItem(item)137 }138 return menu139 }140141 // MARK: Commands142143 @objc func performCommand(_ sender: NSMenuItem) {144 guard let raw = sender.representedObject as? String, let command = CommandID(rawValue: raw) else { return }145 run(command)146 }147148 func run(_ command: CommandID) {149 if let state = environment.keyState {150 state.perform(command)151 return152 }153 // No window is open: only window-independent commands make sense.154 switch command {155 case .newWindow, .newTab: environment.openWindow()156 case .newPrivateWindow: environment.openWindow(isPrivate: true)157 case .openSettings: showSettings()158 case .reopenClosedTab: environment.restoreSession()159 default: NSSound.beep()160 }161 }162163 @objc func selectTabByNumber(_ sender: NSMenuItem) {164 environment.keyState?.selectTab(atVisibleIndex: sender.tag)165 }166167 @objc func showSettingsAction(_ sender: Any?) { showSettings() }168169 @objc func openProfileWindow(_ sender: NSMenuItem) {170 guard let id = sender.representedObject as? String, let profile = environment.profiles.first(where: { $0.id.uuidString == id }) else { return }171 environment.openWindow(profile: profile)172 }173174 func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {175 if menuItem.action == #selector(selectTabByNumber(_:)) { return environment.keyState != nil }176 guard menuItem.action == #selector(performCommand(_:)), let raw = menuItem.representedObject as? String,177 let command = CommandID(rawValue: raw) else { return true }178 guard let state = environment.keyState else {179 return [.newWindow, .newTab, .newPrivateWindow, .openSettings].contains(command)180 }181 switch command {182 case .toggleSidebar: menuItem.state = state.sidebarVisible ? .on : .off183 case .toggleFocusMode: menuItem.state = state.focusMode ? .on : .off184 case .toggleSplitView: menuItem.state = state.splitTabID != nil ? .on : .off185 case .toggleReader: menuItem.state = state.selectedTab?.readerArticle != nil ? .on : .off186 case .pinTab: menuItem.state = state.selectedTab?.isPinned == true ? .on : .off187 default: break188 }189 return state.isEnabled(command)190 }191192 func showSettings(section: SettingsSection? = nil) {193 if let section { environment.settingsSection = section }194 if settingsWindow == nil {195 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 780, height: 560),196 styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)197 window.title = L("Settings")198 window.isReleasedWhenClosed = false199 window.contentMinSize = NSSize(width: 720, height: 480)200 window.contentView = NSHostingView(rootView: SettingsView(environment: environment))201 window.center()202 window.setFrameAutosaveName("SPBrowserSettings")203 settingsWindow = window204 }205 settingsWindow?.makeKeyAndOrderFront(nil)206 NSApp.activate(ignoringOtherApps: true)207 }208}209210/// Builds the menu bar from the command catalogue, so menus, shortcuts and the palette can never drift apart.211@MainActor212enum MainMenuBuilder {213 static func build(environment: AppEnvironment, target: AppDelegate) -> NSMenu {214 let overrides = environment.settings.shortcutOverrides215 let main = NSMenu()216217 func commandItem(_ command: CommandID) -> NSMenuItem {218 let item = NSMenuItem(title: command.title, action: #selector(AppDelegate.performCommand(_:)), keyEquivalent: "")219 item.target = target220 item.representedObject = command.rawValue221 if let combo = command.shortcut(overrides: overrides), combo.isUsable { apply(combo, to: item) }222 return item223 }224225 func submenu(_ title: String, _ build: (NSMenu) -> Void) {226 let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")227 let menu = NSMenu(title: title)228 build(menu)229 item.submenu = menu230 main.addItem(item)231 }232233 func add(_ menu: NSMenu, _ groups: [[CommandID]]) {234 for (index, group) in groups.enumerated() {235 if index > 0 { menu.addItem(.separator()) }236 group.forEach { menu.addItem(commandItem($0)) }237 }238 }239240 submenu("SP Browser") { menu in241 menu.addItem(withTitle: L("About SP Browser"), action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), keyEquivalent: "")242 menu.addItem(.separator())243 menu.addItem(commandItem(.openSettings))244 menu.addItem(.separator())245 let services = NSMenuItem(title: L("Services"), action: nil, keyEquivalent: "")246 services.submenu = NSMenu(title: L("Services"))247 NSApp.servicesMenu = services.submenu248 menu.addItem(services)249 menu.addItem(.separator())250 menu.addItem(withTitle: L("Hide SP Browser"), action: #selector(NSApplication.hide(_:)), keyEquivalent: "h")251 let others = menu.addItem(withTitle: L("Hide Others"), action: #selector(NSApplication.hideOtherApplications(_:)), keyEquivalent: "h")252 others.keyEquivalentModifierMask = [.command, .option]253 menu.addItem(withTitle: L("Show All"), action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: "")254 menu.addItem(.separator())255 menu.addItem(withTitle: L("Quit SP Browser"), action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")256 }257258 submenu(L("File")) { menu in259 add(menu, [[.newTab, .newWindow, .newPrivateWindow], [.openFile, .openLocation], [.closeTab, .closeWindow],260 [.savePageAsPDF, .capturePage, .sharePage], [.printPage]])261 if environment.profiles.count > 1 {262 menu.addItem(.separator())263 let item = NSMenuItem(title: L("New Window with Profile"), action: nil, keyEquivalent: "")264 let profiles = NSMenu()265 for profile in environment.profiles {266 let entry = NSMenuItem(title: profile.name, action: #selector(AppDelegate.openProfileWindow(_:)), keyEquivalent: "")267 entry.target = target268 entry.representedObject = profile.id.uuidString269 profiles.addItem(entry)270 }271 item.submenu = profiles272 menu.addItem(item)273 }274 }275276 submenu(L("Edit")) { menu in277 menu.addItem(withTitle: L("Undo"), action: Selector(("undo:")), keyEquivalent: "z")278 let redo = menu.addItem(withTitle: L("Redo"), action: Selector(("redo:")), keyEquivalent: "z")279 redo.keyEquivalentModifierMask = [.command, .shift]280 menu.addItem(.separator())281 menu.addItem(withTitle: L("Cut"), action: #selector(NSText.cut(_:)), keyEquivalent: "x")282 menu.addItem(withTitle: L("Copy"), action: #selector(NSText.copy(_:)), keyEquivalent: "c")283 menu.addItem(withTitle: L("Paste"), action: #selector(NSText.paste(_:)), keyEquivalent: "v")284 let plain = menu.addItem(withTitle: L("Paste and Match Style"), action: #selector(NSTextView.pasteAsPlainText(_:)), keyEquivalent: "v")285 plain.keyEquivalentModifierMask = [.command, .option, .shift]286 menu.addItem(withTitle: L("Delete"), action: #selector(NSText.delete(_:)), keyEquivalent: "")287 menu.addItem(withTitle: L("Select All"), action: #selector(NSText.selectAll(_:)), keyEquivalent: "a")288 menu.addItem(.separator())289 add(menu, [[.findInPage, .findNext, .findPrevious]])290 }291292 submenu(L("View")) { menu in293 add(menu, [[.reload, .hardReload, .stopLoading], [.zoomIn, .zoomOut, .zoomReset],294 [.toggleSidebar, .toggleTabLayout, .toggleSplitView, .swapSplit], [.toggleReader, .toggleFocusMode, .toggleFullScreen],295 [.commandPalette, .commandOrbit], [.showFlow, .peekLink]])296 }297298 submenu(L("History")) { menu in299 add(menu, [[.goBack, .goForward, .goHome], [.reopenClosedTab, .showOtherDevices, .showPortal], [.showHistory, .clearHistory]])300 }301302 submenu(L("Tabs")) { menu in303 add(menu, [[.nextTab, .previousTab, .searchTabs, .showConstellation], [.duplicateTab, .pinTab, .newTabGroup, .moveTabToNewWindow],304 [.closeOtherTabs, .suspendTab], [.nextWorkspace, .previousWorkspace]])305 menu.addItem(.separator())306 for index in 0..<9 {307 let title = index == 8 ? L("Last Tab") : L("Tab %d", index + 1)308 let item = NSMenuItem(title: title, action: #selector(AppDelegate.selectTabByNumber(_:)), keyEquivalent: "\(index + 1)")309 item.target = target310 item.tag = index311 menu.addItem(item)312 }313 }314315 submenu(L("Bookmarks")) { menu in316 add(menu, [[.addBookmark, .toggleFavorite, .addToReadingList], [.showBookmarks, .showReadingList], [.importBookmarks, .exportBookmarks]])317 }318319 submenu(L("Tools")) { menu in320 add(menu, [[.showDownloads, .showNotes, .showSessions, .saveSession], [.showCanvas, .addToCanvas], [.toggleIntelligence],321 [.pageInfo, .toggleBlockerForSite, .clearSiteData], [.viewSource, .pageMetadata, .changeUserAgent], [.showAccount, .syncNow]])322 }323324 submenu(L("Window")) { menu in325 menu.addItem(withTitle: L("Minimize"), action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m")326 menu.addItem(withTitle: L("Zoom"), action: #selector(NSWindow.performZoom(_:)), keyEquivalent: "")327 menu.addItem(.separator())328 menu.addItem(withTitle: L("Bring All to Front"), action: #selector(NSApplication.arrangeInFront(_:)), keyEquivalent: "")329 NSApp.windowsMenu = menu330 }331332 submenu(L("Help")) { menu in333 menu.addItem(commandItem(.commandPalette))334 NSApp.helpMenu = menu335 }336 return main337 }338339 static func apply(_ combo: KeyCombo, to item: NSMenuItem) {340 let named: [String: Int] = [341 "left": NSLeftArrowFunctionKey, "right": NSRightArrowFunctionKey, "up": NSUpArrowFunctionKey, "down": NSDownArrowFunctionKey,342 "delete": NSBackspaceCharacter, "return": NSCarriageReturnCharacter, "tab": NSTabCharacter, "escape": 0x1B, "space": 0x20,343 ]344 if let code = named[combo.key], let scalar = UnicodeScalar(code) {345 item.keyEquivalent = String(Character(scalar))346 } else {347 item.keyEquivalent = combo.key348 }349 var mask: NSEvent.ModifierFlags = []350 if combo.command { mask.insert(.command) }351 if combo.shift { mask.insert(.shift) }352 if combo.option { mask.insert(.option) }353 if combo.control { mask.insert(.control) }354 item.keyEquivalentModifierMask = mask355 }356}357