Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/macOS/SPMailApp.swift3// Description: SP Mail for macOS — main window (3-column split view with inspector), message windows and composer windows (value-based, restored after4// a relaunch), template studio window, Settings scene, menu bar extra, menu commands. The application delegate wires the system layer5// (Sources/Shared/System): push registration and remote notifications, Services menu, Dock menu. Every secondary window is lock-gated.6import AppKit7import SPMailCore8import SPMailSystem9import SwiftUI1011@MainActor12final class AppDelegate: NSObject, NSApplicationDelegate {13 /// The one model of the process: a push or a notification action can start the app before any window exists.14 var model: AppModel? { AppRuntime.model }15 func applicationWillFinishLaunching(_ notification: Notification) {16 // before the launch finishes: the notification delegate must be in place for a tap that started the app17 AppRuntime.model.system.install()18 }19 func applicationDidFinishLaunching(_ notification: Notification) {20 AppModel.purgeTemporaryFiles()21 NSApp.servicesProvider = ServicesProvider.shared22 NSUpdateDynamicServices()23 }24 func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {25 DockMenu.make(AppRuntime.model, target: self, compose: #selector(dockCompose), open: #selector(dockOpenInbox))26 }27 @objc private func dockCompose() { AppRuntime.model.system.router.deliver(.compose(nil)) }28 @objc private func dockOpenInbox() { AppRuntime.model.system.router.deliver(.inbox(mailboxId: nil)) }29 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }30 /// A template with unsaved changes is not lost silently when the app quits.31 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {32 guard let editor = model?.studio.current, editor.isDirty else { return .terminateNow }33 let alert = NSAlert()34 alert.messageText = String(localized: "Ce modèle a des modifications non enregistrées.")35 alert.informativeText = editor.name36 alert.addButton(withTitle: String(localized: "Enregistrer"))37 alert.addButton(withTitle: String(localized: "Annuler"))38 alert.addButton(withTitle: String(localized: "Abandonner les modifications"))39 switch alert.runModal() {40 case .alertFirstButtonReturn:41 Task { let ok = await editor.save(); sender.reply(toApplicationShouldTerminate: ok) }42 return .terminateLater43 case .alertThirdButtonReturn: return .terminateNow44 default: return .terminateCancel45 }46 }47 func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {48 Task { await model?.didRegisterForPush(deviceToken) }49 }50 func application(_ application: NSApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {51 model?.didFailToRegisterForPush(error)52 }53 func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String: Any]) {54 // a push delivered to the running app (silent badge update, or an alert while it runs): sync, then put the badge right55 guard let payload = NotificationPayload(userInfo: userInfo) else { return }56 Task { _ = await AppRuntime.model.system.notifications.handleRemote(payload) }57 }58}5960@main61struct SPMailApp: App {62 @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate63 @State private var model = AppRuntime.model6465 var body: some Scene {66 Window("SP Mail", id: "main") {67 RootView(app: model, scene: model.main)68 .frame(minWidth: 940, minHeight: 580)69 .systemScene(model, model.main)70 #if DEBUG71 .task { if AppConfig.selfTest { await SelfTest.run(model) } else { await DemoFixtures.runIfRequested(model) } }72 #endif73 }74 .defaultSize(width: 1280, height: 800)75 .windowResizability(.contentMinSize)76 .commands { MailCommands(app: model); SystemCommands(app: model) }7778 // a message or a conversation in its own window; the value is Codable, so the system restores these windows after a relaunch79 WindowGroup("Message", id: "message", for: MessageRef.self) { $ref in80 MessageWindow(app: model, ref: ref)81 }82 .defaultSize(width: 760, height: 720)83 .windowResizability(.contentMinSize)8485 // composer windows are keyed by the id of their draft in the local outbox: a restored window reads its draft back86 WindowGroup("Nouveau message", id: "compose", for: String.self) { $id in87 ComposeWindow(app: model, id: id)88 }89 .defaultSize(width: 760, height: 780)90 .windowResizability(.contentMinSize)9192 Window("Modèles", id: "studio") {93 StudioWindow(app: model)94 }95 .defaultSize(width: 1400, height: 860)96 // no scene shortcut: « Modèles › Studio de modèles » (⇧⌘M) opens it — ⌥⌘M is the system's « Minimize All »9798 Settings { LockGate(app: model, requiresSession: false) { SettingsView(model: model) } }99100 MenuBarExtra(isInserted: Binding(get: { model.settings.showMenuBarExtra }, set: { model.settings.showMenuBarExtra = $0 })) {101 MenuBarContent(app: model)102 } label: {103 MenuBarLabel(app: model)104 }105 .menuBarExtraStyle(.menu)106 }107}108109/// A compose window. Closing it keeps the draft (saved on the device and, when online, in the server Drafts mailbox).110/// Restored after a relaunch: the draft is read back from the local outbox.111struct ComposeWindow: View {112 let app: AppModel113 let id: String?114 @State private var restoring = true115 @Environment(\.dismiss) private var dismiss116117 var body: some View {118 LockGate(app: app, keepsContentAlive: true) {119 if let id, let composer = app.composers[id] {120 ComposeView(model: composer) { dismiss() }121 .navigationTitle(composer.subject.isEmpty ? L("Nouveau message") : composer.subject)122 .onDisappear { Task { await composer.close() } }123 .onPasteCommand(of: [.fileURL]) { providers in124 for p in providers { _ = p.loadObject(ofClass: URL.self) { url, _ in if let url { Task { @MainActor in composer.addAttachment(url: url) } } } }125 }126 } else if restoring {127 ProgressView().controlSize(.small).frame(maxWidth: .infinity, maxHeight: .infinity)128 } else {129 SPEmptyState(icon: "doc", title: L("Ce brouillon n’est plus ouvert")).onAppear { dismiss() }130 }131 }132 .frame(minWidth: 560, minHeight: 460)133 .task(id: app.phase == .ready) {134 guard app.phase == .ready, let id else { return }135 if app.composers[id] == nil { _ = await app.restoreComposer(id: id) }136 restoring = false137 }138 }139}140141/// A message (or its conversation) in its own window, with its own navigation state on the shared session.142struct MessageWindow: View {143 let app: AppModel144 let ref: MessageRef?145 @State private var scene: MailScene?146 @State private var missing = false147 @Environment(\.dismiss) private var dismiss148 @Environment(\.openWindow) private var openWindow149150 var body: some View {151 LockGate(app: app) {152 if let scene, !scene.reader.isEmpty {153 ReaderView(scene: scene)154 .toastHost(app)155 .composeUndoHost(app)156 .focusedSceneValue(scene)157 .navigationTitle(scene.reader.conversation.last?.subject.isEmpty == false ? scene.reader.conversation.last!.subject : L("(sans objet)"))158 .onChange(of: scene.composeRequest) { _, id in if let id { openWindow(id: "compose", value: id); scene.composeRequest = nil } }159 .onChange(of: scene.studioRequest) { _, _ in openWindow(id: "studio") }160 // archived, deleted or moved from this window: nothing left to show161 .onChange(of: scene.reader.isEmpty) { _, empty in if empty { dismiss() } }162 } else if missing {163 SPEmptyState(icon: "envelope.open", title: L("Ce message n’est plus disponible."))164 } else {165 ProgressView().controlSize(.small).frame(maxWidth: .infinity, maxHeight: .infinity)166 }167 }168 .frame(minWidth: 520, minHeight: 420)169 .background(SPColor.surface)170 .task(id: app.phase == .ready) {171 guard app.phase == .ready, let ref, scene == nil else { return }172 let s = MailScene(app: app, detached: true)173 if await s.openDetached(ref) { scene = s } else { missing = true }174 }175 }176}177178/// The template studio window. Closing it keeps the open template and its unsaved draft in memory: reopening shows them again.179struct StudioWindow: View {180 let app: AppModel181 var body: some View {182 LockGate(app: app, keepsContentAlive: true) { StudioRoot(studio: app.studio) }183 .frame(minWidth: 980, minHeight: 620)184 }185}186