#if canImport(RastrilloMacUpdates) import RastrilloMacUpdates #endif import AppKit import BaseKit import KeyboardShortcuts import RastrilloApple import ServiceManagement import SwiftUI extension KeyboardShortcuts.Name { /// Ask Base from anywhere: off until the person records one (P11). static let askBase = Self("askBase") } /// Base for the Mac. One window (B): the sky, a floating sidebar and Ask. /// Ask is also a menu-bar panel (on by default), presented by Base's own /// StatusPanelController so the global shortcut, once the person records /// one, can open it. Settings (⌘,) has General, Account and /// Ask Base; the Colophon is under Help. @main struct BaseMacApp: App { @NSApplicationDelegateAdaptor(BaseMacDelegate.self) private var delegate @AppStorage("showMenuBar") private var showMenuBar = true @AppStorage(OpenPreference.key) private var openIn = OpenPreference.app.rawValue #if canImport(RastrilloMacUpdates) // Quiet, as the other Oficina apps: a scheduled check never opens a // window; an update downloads in the background and installs on quit. @State private var updater = NativeUpdater(policy: .quiet) #endif init() { // Before the first frame, so nothing paints in a fallback face. BaseFonts.register() } private var session: BaseSession { delegate.session } var body: some Scene { Window(BaseText.text("native.sidebar.ask"), id: "main") { MacRoot(session: session, actions: delegate.actions) .onOpenURL { delegate.openURL.handle($0) } .onChange(of: showMenuBar, initial: true) { _, shown in delegate.panel?.itemShown = shown } .modifier(KeepOpenWindow(delegate: delegate)) #if canImport(RastrilloMacUpdates) .safeAreaInset(edge: .bottom) { if updater.canInstallPendingUpdate { NativeUpdateNotice(updater: updater).padding(.bottom, 12) } } #endif } .windowStyle(.hiddenTitleBar) .windowToolbarStyle(.unified(showsTitle: false)) .defaultSize(width: 1280, height: 800) .commands { // First: About, Hide and Quit say "Base", not the Finder name. PlainAppNameCommands() #if canImport(RastrilloMacUpdates) NativeUpdateCommands(updater: updater) #endif // One window: ⌘N opens nothing new. CommandGroup(replacing: .newItem) {} CommandGroup(replacing: .help) { ColophonCommand() } } Settings { MacSettingsRoot(session: session, actions: delegate.actions, showMenuBar: $showMenuBar, openIn: Binding(get: { OpenPreference(rawValue: openIn) ?? .app }, set: { openIn = $0.rawValue })) .onChange(of: showMenuBar) { _, shown in delegate.panel?.itemShown = shown } } Window(ColophonView.title, id: "colophon") { ColophonView() } .windowResizability(.contentMinSize) } } struct ColophonCommand: View { @Environment(\.openWindow) private var openWindow var body: some View { Button(ColophonView.title) { openWindow(id: "colophon") } } } /// The app's session and what its screens do, made once, before the first /// window, and the shortcut's handler. @MainActor final class BaseMacDelegate: NSObject, NSApplicationDelegate { let session = BaseSession.live() lazy var actions = MacActions.make(session: session) private(set) var panel: StatusPanelController? /// The panel's foot shows the shortcut as it is when the panel opens. let panelState = PanelState() /// The window's scene's openWindow, kept from the window's first /// appearance, so Open Base can bring it back after it was closed. var openMain: (() -> Void)? lazy var openURL = BaseOpenURL(showAsk: { [weak self] in self?.showMain() }, openWeb: { [actions] in actions.openWeb($0) }) func applicationDidFinishLaunching(_ notification: Notification) { UserDefaults.standard.register(defaults: ["showMenuBar": true]) let session = self.session, actions = self.actions, state = panelState panel = StatusPanelController(itemShown: UserDefaults.standard.bool(forKey: "showMenuBar"), accessibilityLabel: BaseText.text("native.sidebar.ask")) { MenuPanelRoot(session: session, actions: actions, state: state) { [weak self] in self?.panel?.hide() self?.showMain() } } panel?.onShow = { state.shortcut = KeyboardShortcuts.getShortcut(for: .askBase)?.description } KeyboardShortcuts.onKeyUp(for: .askBase) { [weak self] in self?.panel?.shortcutPressed() } Task { await session.oficina.start() } } /// Open Base: the window, forward (opened again if it was closed). func showMain() { NSApp.activate() if let window = NSApp.windows.first(where: { $0.identifier?.rawValue.hasPrefix("main") == true && $0.isVisible }) { window.makeKeyAndOrderFront(nil) } else { openMain?() } } func applicationDidBecomeActive(_ notification: Notification) { Task { await session.foreground() } } func applicationDidResignActive(_ notification: Notification) {} func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { if !flag { showMain() } return true } } /// Sign-in until there is a session, then the window (B). struct MacRoot: View { let session: BaseSession let actions: BaseActions @SceneStorage("sidebarShown") private var sidebarShown = true @Environment(\.scenePhase) private var phase var body: some View { Group { if let state = session.signedIn { MacMainView(me: session.me, home: session.home, ask: session.ask, transport: session.iconTransport, actions: actions, sidebarShown: $sidebarShown) .overlay(alignment: .top) { NativeOfflineBanner(origin: state.origin, message: BaseText.text("native.offline")).padding(.top, 8) } } else { BaseSignIn(model: session.oficina, openURL: { NSWorkspace.shared.open($0) }) } } .ignoresSafeArea() .frame(minWidth: 860, minHeight: 560) .baseAppearance(session.me?.appearance ?? .system) .onChange(of: phase) { _, now in if now != .active { session.background() } } } } /// The menu-bar panel, from the session. struct MenuPanelRoot: View { let session: BaseSession let actions: BaseActions let state: PanelState let openBase: () -> Void var body: some View { MenuPanel(me: session.me, ask: session.signedIn == nil ? nil : session.ask, shortcut: state.shortcut, openBase: openBase, actions: actions) .baseAppearance(session.me?.appearance ?? .system) } } /// What the panel shows that lives outside the session: the shortcut, /// read again each time the panel opens. @MainActor @Observable final class PanelState { var shortcut: String? = KeyboardShortcuts.getShortcut(for: .askBase)?.description } /// Keeps the window scene's openWindow for the app delegate. struct KeepOpenWindow: ViewModifier { let delegate: BaseMacDelegate @Environment(\.openWindow) private var openWindow func body(content: Content) -> some View { content.onAppear { delegate.openMain = { openWindow(id: "main") } } } } /// Settings, from the session and this Mac. struct MacSettingsRoot: View { let session: BaseSession let actions: BaseActions @Binding var showMenuBar: Bool @Binding var openIn: OpenPreference @State private var openAtLogin = SMAppService.mainApp.status == .enabled var body: some View { MacSettingsView( model: .init(me: session.me, identity: session.signedIn?.identity.label ?? "", askPhase: session.ask?.phase ?? .loading, installed: Opener.installedNames(session.home?.apps ?? [], installed: MacActions.installed), shortcutSet: KeyboardShortcuts.getShortcut(for: .askBase) != nil), showMenuBar: $showMenuBar, openAtLogin: Binding(get: { openAtLogin }, set: { on in do { if on { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() } } catch {} openAtLogin = SMAppService.mainApp.status == .enabled }), openIn: $openIn, setAppearance: { appearance in Task { await session.setAppearance(appearance) } }, disconnect: { Task { await session.disconnectAsk() } }, actions: actions ) { KeyboardShortcuts.Recorder(for: .askBase) } .baseAppearance(session.me?.appearance ?? .system) } }