SPB Git

Repository Public

VQuantApp.swift 22.1 KB 400 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/VQuantApp.swift3// Description: Application entry point: main windows, detached chart windows, Settings, the menu-bar extra, menu commands, and saved window layouts (synced workspaces and layouts of this Mac).4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89@main10struct VQuantApp: App {11    @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate12    @State private var app = AppEnvironment()1314    var body: some Scene {15        WindowGroup("VQuant", id: "main", for: MainSpec.self) { $spec in16            RootView(app: app, spec: spec)17                .preferredColorScheme(app.settings.theme.scheme)18                .frame(minWidth: 940, minHeight: 600)19        } defaultValue: { app.initialSpec() }20        .defaultSize(width: 1320, height: 840)21        .commands { AppCommands(app: app); ResearchLabCommands(app: app) }2223        WindowGroup("Chart", id: "chart", for: ChartSpec.self) { $spec in24            ChartWindow(app: app, spec: spec)25                .preferredColorScheme(app.settings.theme.scheme)26                .frame(minWidth: 520, minHeight: 360)27        }28        .defaultSize(width: 900, height: 600)2930        Settings {31            SettingsView(app: app).preferredColorScheme(app.settings.theme.scheme)32        }3334        MenuBarExtra(isInserted: Binding(get: { app.settings.menuBarExtra }, set: { app.settings.menuBarExtra = $0 })) {35            MenuBarPanel(app: app)36        } label: { MenuBarLabel(app: app) }37        .menuBarExtraStyle(.window)38    }39}4041/// Lets AppKit code (launch guard, Dock reopen) open a main window through SwiftUI's own action.42enum MainWindowOpener { static var open: (() -> Void)? }4344final class AppDelegate: NSObject, NSApplicationDelegate {45    private var hasMainWindow: Bool { NSApp.windows.contains { $0.isVisible && $0.canBecomeMain && !($0 is NSPanel) } }4647    func applicationDidFinishLaunching(_ notification: Notification) {48        NSWindow.allowsAutomaticWindowTabbing = true49        // After a forced quit, a launch may restore no window at all: make sure one is on screen.50        for delay in [0.8, 2.0] { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.ensureMainWindow() } }51    }52    func ensureMainWindow() {53        guard !hasMainWindow else { return }54        MainWindowOpener.open?()55        NSApp.activate(ignoringOtherApps: true)56    }57    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {58        if !hasMainWindow { MainWindowOpener.open?(); return false }59        return true60    }61    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }62    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { true }63}6465/// Decides what a main window shows: launch check, sign-in, lock screen or the workstation.66struct RootView: View {67    let app: AppEnvironment68    /// What the window was opened with. It is never written back: changing a WindowGroup's value re-creates the69    /// window's content. What the window shows afterwards is kept in scene storage, which macOS restores per window.70    let spec: MainSpec71    @State private var model: WindowModel?72    @SceneStorage("vq.section") private var storedSection = ""73    @SceneStorage("vq.symbol") private var storedSymbol = ""74    @SceneStorage("vq.session") private var storedSession = ""75    @SceneStorage("vq.job") private var storedJob = ""76    @SceneStorage("vq.project") private var storedProject = ""77    @SceneStorage("vq.portfolio") private var storedPortfolio = ""78    @SceneStorage("vq.watchlist") private var storedWatchlist = ""79    @Environment(\.openSettings) private var openSettings8081    /// Creates the window's model once. Called from `onAppear` as well as from the task: a window opened right after82    /// the last one was closed (restoring a layout) was observed with its task not run and stayed blank.83    private func setup() {84        guard model == nil else { return }85        do {86            var s = spec87            // a restored window resumes where it was; a new one starts from its spec88            if let sec = AppSection(rawValue: storedSection) { s.section = sec }89            if !storedSymbol.isEmpty { s.symbol = storedSymbol }90            if !storedSession.isEmpty { s.sessionId = storedSession }91            if !storedJob.isEmpty { s.quantJobId = storedJob }92            if !storedProject.isEmpty { s.projectId = storedProject }93            if !storedPortfolio.isEmpty { s.portfolioId = storedPortfolio }94            let m = WindowModel(spec: s)95            if !storedWatchlist.isEmpty { m.watchlistId = storedWatchlist }96            m.launchTab = app.options.tab97            if app.options.palette { m.paletteOpen = true; m.paletteQuery = app.options.paletteQuery ?? "" }98            model = m99            // a window that never navigates must still be restored where it is (launch argument, layout, ⌘N + default)100            if storedSection.isEmpty { storedSection = m.section.rawValue }101            if storedSymbol.isEmpty { storedSymbol = m.symbol }102            // notifications, the menu-bar extra and launch arguments reach this window through the router103            WindowRouter.register(m)104        }105    }106107    var body: some View {108        Group {109            switch app.session.phase {110            case .starting:111                VStack(spacing: 12) { ProgressView(); Text("Contacting VQuant…").foregroundStyle(.secondary) }.frame(maxWidth: .infinity, maxHeight: .infinity)112            case .signedOut: SignInView(app: app)113            case .locked: LockView(app: app)114            case .signedIn:115                if let model { MainWindow(app: app, model: model) } else { Color.clear.onAppear { setup() } }116            }117        }118        .overlay(alignment: .bottom) { ToastOverlay(center: app.toasts).animation(.easeOut(duration: 0.15), value: app.toasts.current).allowsHitTesting(false) }119        .onAppear { setup() }120        .task {121            setup()122            app.wire()123            LaunchActions.runOnce(app: app, openSettings: openSettings)124            await app.session.launch()125        }126        // Scene storage is the window's memory across a relaunch. Its restored values can arrive after the first127        // appearance (seen on macOS 27: restored windows all came back on the default section), so they are applied128        // whenever they change; writing them back from the model below is idempotent.129        .onChange(of: storedSection) { _, v in if let sec = AppSection(rawValue: v), let m = model, m.section != sec { m.section = sec } }130        .onChange(of: storedSymbol) { _, v in if !v.isEmpty, let m = model, m.symbol != v { m.symbol = v } }131        .onChange(of: storedSession) { _, v in if !v.isEmpty, let m = model, m.sessionId != v { m.sessionId = v } }132        .onChange(of: storedJob) { _, v in if !v.isEmpty, let m = model, m.quantJobId != v { m.quantJobId = v } }133        .onChange(of: storedProject) { _, v in if !v.isEmpty, let m = model, m.projectId != v { m.projectId = v } }134        .onChange(of: storedPortfolio) { _, v in if !v.isEmpty, let m = model, m.portfolioId != v { m.portfolioId = v } }135        .onChange(of: model?.section) { _, v in if let v { storedSection = v.rawValue } }136        .onChange(of: model?.symbol) { _, v in if let v { storedSymbol = v } }137        .onChange(of: model?.sessionId) { _, v in storedSession = v ?? "" }138        .onChange(of: model?.quantJobId) { _, v in storedJob = v ?? "" }139        .onChange(of: model?.projectId) { _, v in storedProject = v ?? "" }140        .onChange(of: model?.portfolioId) { _, v in storedPortfolio = v ?? "" }141        .onChange(of: model?.watchlistId) { _, v in storedWatchlist = v ?? "" }142        .vqTheme(app.vqTheme)143        .focusedSceneValue(\.windowModel, model)144        .background(WindowAccessor { w in WorkspaceLayouts.place(w, id: spec.id) })145    }146}147148extension AppEnvironment {149    /// A new main window's content (development launch arguments may pick the section and symbol).150    func initialSpec() -> MainSpec {151        var s = MainSpec()152        if let sec = options.section.flatMap(AppSection.init(rawValue:)) { s.section = sec }153        if let sym = options.symbol { s.symbol = sym }154        s.quantJobId = options.job; s.sessionId = options.conversation155        s.projectId = options.project; s.portfolioId = options.portfolio156        return s157    }158159    /// Connects session changes to the stores (idempotent; called by the first window).160    func wire() {161        guard session.onSignedIn == nil else { return }162Notifier.configure(settings: settings)163        session.onSignedIn = { [unowned self] in self.start(); if self.settings.notifyOnCompletion || self.settings.notifyOnApproval { Notifier.requestAuthorization() } }164        session.onSignedOut = { [unowned self] clear in self.stop(clearCache: clear) }165    }166}167168/// What DEBUG launch arguments ask for once the first window exists: `-VQSettings <pane>` opens the Settings window169/// on that pane, `-VQXNotify approval:<sessionId>|conversation:<sessionId>|quantJob:<id>` behaves as if that170/// notification had been clicked, `-VQXMenuBarPreview 1` shows the menu-bar panel in an ordinary window.171enum LaunchActions {172    private static var done = false173    static func runOnce(app: AppEnvironment, openSettings: OpenSettingsAction) {174        guard !done else { return }175        done = true176        #if DEBUG177        if app.options.settingsPane != nil { DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { NSApp.activate(ignoringOtherApps: true); openSettings() } }178        if let route = app.options.extra["Notify"].flatMap(NotificationRoute.init(argument:)) {179            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { WindowRouter.open(.notification(route)) }180        }181        if app.options.extra["MenuBarPreview"] != nil { DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { MenuBarPreview.show(app: app) } }182        #endif183    }184}185186struct AppCommands: Commands {187    let app: AppEnvironment188    @FocusedValue(\.windowModel) private var model189    @Environment(\.openWindow) private var openWindow190191    var body: some Commands {192        let _ = (MainWindowOpener.open = { [openWindow, app] in openWindow(id: "main", value: app.initialSpec()) })193        CommandGroup(after: .newItem) {194            Button("New Chart Window") { openWindow(id: "chart", value: ChartSpec(symbol: model?.symbol ?? "AAPL")) }.keyboardShortcut(AppShortcuts.newChartWindow)195            Divider()196            // ⇧⌘S: 1.0 used ⌃⌘S, which is the standard "Show/Hide Sidebar" of these windows197            Button("Save Window Layout…") { WorkspaceLayouts.promptAndSave(app: app) }.keyboardShortcut(AppShortcuts.saveLayout)198            Menu("Open Window Layout") { layoutItems }199            Menu("Delete Window Layout") {200                let mine = WorkspaceLayouts.entries(app: app).filter(\.deletable)201                ForEach(mine) { e in Button(e.menuTitle + "…") { WorkspaceLayouts.confirmDelete(e, app: app) } }202                if mine.isEmpty { Text("No saved layout") }203            }204        }205        CommandGroup(after: .sidebar) {206            ForEach(Array(AppSection.allCases.enumerated()), id: \.element) { i, s in207                if i < 9 { Button(s.title) { model?.show(s) }.keyboardShortcut(AppShortcuts.section(i)).disabled(model == nil) }208                else { Button(s.title) { model?.show(s) }.disabled(model == nil) }209            }210            Divider()211        }212        CommandMenu("Data") {213            Button("Command Palette…") { model?.paletteOpen = true }.keyboardShortcut(AppShortcuts.palette).disabled(model == nil)214            Button("Find Symbol…") { model?.searchFocusTick += 1 }.keyboardShortcut(AppShortcuts.findSymbol).disabled(model == nil)215            Button("Sync Now") { Task { await app.sync.syncNow() } }.keyboardShortcut(AppShortcuts.syncNow).disabled(!app.session.isSignedIn)216            Button("Refresh Now") { Task { await app.market.refresh(); await app.workspace.refresh(); await app.quant.refresh(); await app.research.refreshGenerations() } }217                .keyboardShortcut(AppShortcuts.refresh).disabled(!app.session.isSignedIn)218            Divider()219            Button("Chart Current Symbol") { model?.show(.charting) }.keyboardShortcut(AppShortcuts.chartSymbol).disabled(model == nil)220            Button("Detach Chart") { if let m = model { openWindow(id: "chart", value: ChartSpec(symbol: m.symbol)) } }.keyboardShortcut(AppShortcuts.detachChart).disabled(model == nil)221        }222        CommandGroup(after: .appSettings) {223            Button("Lock VQuant") { app.session.lock() }.keyboardShortcut(AppShortcuts.lock).disabled(!app.session.isSignedIn || !app.settings.appLock)224            Button("Sign Out") { Task { await app.session.signOut() } }.disabled(!app.session.isSignedIn)225        }226        // Window menu: the saved layouts, one click away from the window list227        CommandGroup(after: .windowArrangement) {228            Divider()229            Section("Layouts") { layoutItems }230        }231    }232233    /// One item per saved layout: the synced ones first, then those kept on this Mac (labelled).234    @ViewBuilder private var layoutItems: some View {235        let entries = WorkspaceLayouts.entries(app: app)236        ForEach(entries) { e in Button(e.menuTitle) { WorkspaceLayouts.restore(e.windows, openWindow: openWindow) } }237        if entries.isEmpty { Text("No saved layout") }238    }239}240241/// Saved arrangements of windows: which windows were open, what each showed, where it was.242enum WorkspaceLayouts {243    /// Windows register here so a layout can be captured (weak: closing a window removes it).244    static let registry = NSHashTable<WindowRecord>.weakObjects()245246    final class WindowRecord {247        weak var window: NSWindow?248        var describe: () -> SavedWorkspace.Window?249        init(window: NSWindow, describe: @escaping () -> SavedWorkspace.Window?) { self.window = window; self.describe = describe }250    }251252    /// Records are retained by their window (associated object) and referenced weakly here.253    static func register(_ window: NSWindow, describe: @escaping () -> SavedWorkspace.Window?) {254        let r = WindowRecord(window: window, describe: describe)255        objc_setAssociatedObject(window, &recordKey, r, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)256        registry.add(r)257    }258    nonisolated(unsafe) private static var recordKey: UInt8 = 0259260    static func capture(name: String) -> SavedWorkspace {261        let windows: [SavedWorkspace.Window] = registry.allObjects.compactMap { r in262            guard let w = r.window, w.isVisible, var d = r.describe() else { return nil }263            d.frame = [w.frame.origin.x, w.frame.origin.y, w.frame.width, w.frame.height]264            return d265        }266        return SavedWorkspace(name: name, windows: windows)267    }268269    /// A saved layout as the menus list it, whatever keeps it.270    struct Entry: Identifiable {271        enum Source: Hashable {272            /// A `workspace` object of the account (id).273            case synced(String)274            /// A layout the shared model cannot describe, kept in this Mac's `LayoutStore`.275            case local(UUID)276        }277        let source: Source278        let name: String279        let windows: [SavedWorkspace.Window]280        /// A synced workspace made by another client (the web app): it opens here, but is not this app's to delete.281        let foreign: Bool282        var id: String { switch source { case .synced(let id): "synced:\(id)"; case .local(let id): "local:\(id.uuidString)" } }283        var deletable: Bool { !foreign }284        var menuTitle: String {285            switch source {286            case .synced: foreign ? "\(name) — from another device" : name287            case .local: "\(name) — This Mac only"288            }289        }290    }291292    /// Synced workspaces (by name), then the layouts of this Mac (most recent first).293    static func entries(app: AppEnvironment) -> [Entry] {294        let synced: [Entry] = (app.sync.active?.workspaces.items ?? []).compactMap { o in295            let windows = WorkspaceMapping.windows(of: o.data)296            guard !windows.isEmpty else { return nil }297            return Entry(source: .synced(o.id), name: o.data.name.isEmpty ? "Untitled" : o.data.name, windows: windows, foreign: !WorkspaceMapping.isMacLayout(o.data))298        }299        .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }300        return synced + app.layouts.saved.map { Entry(source: .local($0.id), name: $0.name, windows: $0.windows, foreign: false) }301    }302303    static func promptAndSave(app: AppEnvironment) {304        let alert = NSAlert()305        alert.messageText = "Save Window Layout"306        alert.informativeText = "The open windows, what each one shows and where it is on your displays are saved under this name. The layout is kept in your account when every window shows something your other devices can open; otherwise it stays on this Mac."307        let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 24))308        field.stringValue = "Layout \(entries(app: app).filter(\.deletable).count + 1)"309        field.setAccessibilityIdentifier("layout.name")310        alert.accessoryView = field311        alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel")312        alert.window.initialFirstResponder = field313        guard alert.runModal() == .alertFirstButtonReturn else { return }314        let name = field.stringValue.trimmingCharacters(in: .whitespaces)315        save(capture(name: name.isEmpty ? "Layout" : name), app: app)316    }317318    /// Saves into the account (`workspace` object) when the layout maps and someone is signed in, else on this Mac.319    /// A layout of the same name that this app wrote is replaced — edited in place, so keys other clients added stay.320    static func save(_ w: SavedWorkspace, app: AppEnvironment) {321        guard !w.windows.isEmpty else { app.toasts.show("No window to save.", error: true); return }322        let count = "\(w.windows.count) window\(w.windows.count == 1 ? "" : "s")"323        if let session = app.sync.active {324            let previous = session.workspaces.items.first { $0.data.name == w.name && WorkspaceMapping.isMacLayout($0.data) }325            if let ws = WorkspaceMapping.workspace(from: w, existing: previous?.data) {326                let id = previous?.id ?? SyncStore.migratedID(w.id)327                // one name, one layout: a Mac-only layout of that name is superseded328                if let old = app.layouts.saved.first(where: { $0.name == w.name }) { app.layouts.delete(old.id) }329                Task {330                    await session.workspaces.save(ws, id: id)331                    if let e = session.workspaces.lastError { app.toasts.show("Layout “\(w.name)” was not saved: \(e.userMessage)", error: true) }332                    else { app.toasts.show("Layout “\(w.name)” saved to your account (\(count)).") }333                }334                return335            }336        }337        app.layouts.save(w)338        let unmapped = w.windows.filter { WorkspaceMapping.panelType(section: $0.section, kind: $0.kind) == nil }.compactMap { AppSection(rawValue: $0.section)?.title }339        let why = app.sync.active == nil ? "nobody is signed in" : "\(unmapped.isEmpty ? "a window" : unmapped.joined(separator: ", ")) has no equivalent on other devices"340        app.toasts.show("Layout “\(w.name)” saved on this Mac only (\(count)): \(why).")341    }342343    static func delete(_ e: Entry, app: AppEnvironment) {344        switch e.source {345        case .local(let id): app.layouts.delete(id)346        case .synced(let id): if let session = app.sync.active { Task { await session.workspaces.delete(id) } }347        }348    }349350    static func confirmDelete(_ e: Entry, app: AppEnvironment) {351        let alert = NSAlert()352        alert.alertStyle = .warning353        alert.messageText = "Delete the layout “\(e.name)”?"354        if case .synced = e.source { alert.informativeText = "It is removed from your account, on every device. Open windows are not closed." }355        else { alert.informativeText = "It is removed from this Mac. Open windows are not closed." }356        alert.addButton(withTitle: "Delete"); alert.addButton(withTitle: "Cancel")357        alert.buttons.first?.hasDestructiveAction = true358        guard alert.runModal() == .alertFirstButtonReturn else { return }359        delete(e, app: app)360        app.toasts.show("Layout “\(e.name)” deleted.")361    }362363    /// Frames waiting for the windows that `restore` asked SwiftUI to open (keyed by the spec id).364    static var pendingFrames: [UUID: NSRect] = [:]365366    static func restore(_ w: SavedWorkspace, openWindow: OpenWindowAction) { restore(w.windows, openWindow: openWindow) }367368    /// Replaces the open windows by those of a layout (of this Mac or of a synced workspace).369    static func restore(_ windows: [SavedWorkspace.Window], openWindow: OpenWindowAction) {370        guard !windows.isEmpty else { return }371        for r in registry.allObjects { r.window?.close() }372        // the new windows are opened on the next turn of the run loop: opened in the same turn as the closes, the373        // first one came up without content (seen in the layout UI test)374        DispatchQueue.main.async { open(windows, openWindow: openWindow) }375    }376377    private static func open(_ windows: [SavedWorkspace.Window], openWindow: OpenWindowAction) {378        for win in windows {379            let frame: NSRect? = win.frame.flatMap { $0.count == 4 ? NSRect(x: $0[0], y: $0[1], width: $0[2], height: $0[3]) : nil }380            if win.kind == "chart" {381                let spec = ChartSpec(symbol: win.symbol ?? "AAPL")382                pendingFrames[spec.id] = frame383                openWindow(id: "chart", value: spec)384            } else {385                var spec = MainSpec()386                spec.section = AppSection(rawValue: win.section) ?? .overview387                if let s = win.symbol { spec.symbol = s }388                pendingFrames[spec.id] = frame389                openWindow(id: "main", value: spec)390            }391        }392    }393394    /// Applies a pending frame if the display it was saved on is still there; otherwise macOS places the window.395    static func place(_ window: NSWindow, id: UUID) {396        guard let f = pendingFrames.removeValue(forKey: id) else { return }397        if NSScreen.screens.contains(where: { $0.visibleFrame.intersects(f) }) { window.setFrame(f, display: true) }398    }399}400
Files main
Menu

Theme