import AppKit import PlakServices import PlakUI @MainActor final class AppDelegate: NSObject, NSApplicationDelegate { private var store: PageStore? private var windowController: PageWindowController? private var shortcut: GlobalShortcut? private var statusMenu: StatusMenu? func applicationDidFinishLaunching(_ notification: Notification) { FontRegistry.registerBundledFonts() NSApp.mainMenu = MainMenu.make() let store: PageStore do { store = try PageStore() } catch { // No store means nothing can flush over the unreadable page file on quit. showUnreadable(error) NSApp.terminate(nil) return } self.store = store let controller = PageWindowController(store: store) windowController = controller controller.onHide = { [weak self] in self?.hidePlak() } open(atEnd: true) shortcut = GlobalShortcut { [weak self] in self?.togglePlak() } statusMenu = StatusMenu( show: { [weak self] in self?.showPlak() }, hide: { [weak self] in self?.hidePlak() } ) } func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { open(atEnd: true) return true } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false } func applicationWillResignActive(_ notification: Notification) { windowController?.page.closeEditor() store?.flush() } func applicationWillTerminate(_ notification: Notification) { windowController?.page.closeEditor() store?.flush() } private func togglePlak() { if NSApp.isActive, let window = windowController?.window, window.isVisible, window.isKeyWindow { hidePlak() } else { showPlak() } } private func showPlak() { open(atEnd: false) } /// Only hiding the app gives focus back to the previous app; an ordered-out window leaves Plak active. private func hidePlak() { windowController?.page.closeEditor() NSApp.hide(nil) } private func open(atEnd: Bool) { if NSApp.isHidden { NSApp.unhideWithoutActivation() } // NSApp.activate() is cooperative since macOS 14 and loses to the app in front on ⌘P. (NSApp as ForcedActivation).activate(ignoringOtherApps: true) if atEnd { windowController?.showAtEnd() } else { windowController?.reveal() } } private func showUnreadable(_ error: Error) { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = "Plak cannot read the page file" var path = PageStore.defaultURL.path if case let .unreadable(unreadable)? = error as? PageStoreError { path = unreadable } alert.informativeText = "\(path) is not readable as text. Plak quits and leaves the file as it is." alert.addButton(withTitle: "Quit") NSApp.activate() alert.runModal() } } /// Calls the deprecated activate(ignoringOtherApps:) without the deprecation warning. @MainActor private protocol ForcedActivation { func activate(ignoringOtherApps flag: Bool) } extension NSApplication: ForcedActivation {}