SPB Git

Repository Public License

SatelliteHostApp.swift 5.1 KB 114 lines swift

1import AppKit2import PrismComponentCatalog3import PrismCore4import PrismDataRuntime5import PrismRenderer6import PrismSatellitePublisher7import SwiftUI89/// The prebuilt host of every desktop satellite. It embeds the PRISM renderer and runtime, reads the manifest and10/// blueprint from its own Resources, and keeps the app's data in the app's own Application Support folder.11@MainActor12final class HostModel: ObservableObject {13    let title: String14    let runtime: AppRuntime?15    let failure: String?16    let manifest: SatelliteManifest?17    private let dialogs = AppKitDialogs()1819    init() {20        let resources = Bundle.main.resourceURL ?? Bundle.main.bundleURL21        do {22            let loaded = try SatelliteLoader.load(resources: resources, registry: Catalog.registry)23            let base = ProcessInfo.processInfo.environment["PRISM_SATELLITE_DATA_DIR"].map { URL(fileURLWithPath: $0) }24            let directory = SatelliteLoader.dataDirectory(appId: loaded.manifest.appId, base: base)25            let store = try AppDataStore(url: directory.appendingPathComponent("data.sqlite"))26            let runtime = try AppRuntime(blueprint: loaded.blueprint, store: store, registry: Catalog.registry)27            runtime.dialogs = dialogs28            self.runtime = runtime29            manifest = loaded.manifest30            title = loaded.manifest.displayName31            failure = nil32        } catch {33            runtime = nil34            manifest = nil35            title = (Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String) ?? "PRISM App"36            failure = error.localizedDescription37        }38    }3940    /// When PRISM verifies a freshly published app it asks for a small report, then the app quits by itself.41    func reportIfAsked() {42        let env = ProcessInfo.processInfo.environment43        guard let path = env["PRISM_SATELLITE_REPORT"] else { return }44        var tables: [String: JSONValue] = [:]45        if let runtime { for t in runtime.blueprint.tables { tables[t.id] = .int((try? runtime.store.count(t.id)) ?? -1) } }46        let report: JSONValue = [47            "bundleId": .string(Bundle.main.bundleIdentifier ?? ""), "displayName": .string(title), "version": .string(manifest?.version ?? ""),48            "runtime": .string(PrismRuntimeInfo.version), "pid": .int(Int(ProcessInfo.processInfo.processIdentifier)),49            "loaded": .bool(runtime != nil), "failure": failure.map(JSONValue.string) ?? .null,50            "visibleWindows": .int(NSApp.windows.filter { $0.isVisible && $0.contentView != nil }.count),51            "activationPolicy": .string(NSApp.activationPolicy() == .regular ? "regular" : "other"),52            "hasDockIcon": .bool(NSApp.applicationIconImage != nil && NSApp.activationPolicy() == .regular),53            "tables": .object(tables), "state": .object(runtime?.state ?? [:]),54        ]55        try? AtomicFile.write(Data(report.prettyString().utf8), to: URL(fileURLWithPath: path))56        if env["PRISM_SATELLITE_QUIT"] == "1" {57            runtime?.persistStateNow()58            NSApp.terminate(nil)59        }60    }61}6263final class HostDelegate: NSObject, NSApplicationDelegate {64    var onTerminate: (() -> Void)?65    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }66    func applicationWillTerminate(_ notification: Notification) { onTerminate?() }67}6869@main70struct SatelliteHostApp: App {71    @NSApplicationDelegateAdaptor(HostDelegate.self) private var delegate72    @StateObject private var model = HostModel()7374    var body: some Scene {75        WindowGroup(model.title) {76            Group {77                if let runtime = model.runtime {78                    AppView(runtime: runtime)79                } else {80                    ContentUnavailableView {81                        Label("This app cannot open", systemImage: "exclamationmark.triangle")82                    } description: {83                        Text(model.failure ?? "Unknown problem.")84                    } actions: {85                        Button("Quit") { NSApp.terminate(nil) }86                    }87                    .padding(40)88                }89            }90            .frame(minWidth: 720, minHeight: 480)91            .onAppear {92                let runtime = model.runtime93                delegate.onTerminate = { MainActor.assumeIsolated { runtime?.persistStateNow() } }94                Task { @MainActor in95                    try? await Task.sleep(for: .milliseconds(600))96                    model.reportIfAsked()97                }98            }99        }100        .defaultSize(width: 1100, height: 720)101        .commands {102            CommandGroup(replacing: .newItem) {}103            CommandGroup(replacing: .appInfo) {104                Button("About \(model.title)") {105                    NSApp.orderFrontStandardAboutPanel(options: [106                        .applicationName: model.title, .applicationVersion: model.manifest?.version ?? "",107                        .credits: NSAttributedString(string: "Built with PRISM. Runtime \(PrismRuntimeInfo.version), embedded in this app."),108                    ])109                }110            }111        }112    }113}114
Files main
Menu

Theme