Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/System/DeepLinkRouter.swift3// Description: Takes the app where a notification tap, a widget, an App Intent, Spotlight, Handoff or a URL points: the exact conversation,4// a new message, the inbox, a search. Links wait while the app launches or is locked (cold start, background) and are delivered to the5// right window: the one that already shows the conversation, else the last active one. Scene hooks (URL, user activities, Handoff6// advertising) are attached to each window by `systemScene`.7import CoreSpotlight8import SPMailCore9import SPMailSystem10import SwiftUI11#if os(macOS)12import AppKit13#endif1415@MainActor @Observable16final class DeepLinkRouter {17 @ObservationIgnored unowned let app: AppModel18 @ObservationIgnored private var pending: [DeepLink] = []19 @ObservationIgnored private var flushing = false20 /// The window that was active last (iPad multi-window, macOS): links open there.21 @ObservationIgnored weak var activeScene: MailScene?22 #if os(macOS)23 @ObservationIgnored var openWindow: OpenWindowAction?24 #endif25 #if DEBUG26 /// Self-test: the last link delivered to a window.27 @ObservationIgnored private(set) var lastDelivered: DeepLink?28 #endif2930 init(app: AppModel) { self.app = app }31 func reset() { pending = [] }3233 // MARK: entry points3435 @discardableResult36 func handle(url: URL) -> Bool {37 // `mailto:` keeps its existing path through the window that received it (MainView); everything else is ours38 guard url.scheme?.lowercased() != "mailto", let link = DeepLink(url: url) else { return false }39 deliver(link)40 return true41 }42 func handle(activity: NSUserActivity) {43 if activity.activityType == CSSearchableItemActionType, let id = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String, let (account, email) = Spotlight.parse(identifier: id) {44 deliver(.conversation(mailboxId: account, emailId: email, threadId: nil))45 } else if activity.activityType == Handoff.activityType, let link = Handoff.link(from: activity.userInfo) {46 deliver(link)47 }48 }49 func deliver(_ link: DeepLink) {50 pending.append(link)51 Task { await flush() }52 }5354 /// Delivers what is waiting once the session is up and the app unlocked. Called on launch, unlock and return to the foreground.55 func flush() async {56 guard app.phase == .ready, !flushing, !pending.isEmpty else { return }57 flushing = true58 defer { flushing = false }59 while !pending.isEmpty, app.phase == .ready {60 let link = pending.removeFirst()61 await open(link)62 #if DEBUG63 lastDelivered = link64 #endif65 }66 }6768 // MARK: destinations6970 private func scene(showing mailbox: String? = nil, thread: String? = nil) -> MailScene {71 let windows = app.scenes.filter { !$0.isDetached }72 if let mailbox, let thread, let s = windows.first(where: { $0.activeAccount == mailbox && $0.reader.conversation.contains { $0.threadId == thread } }) { return s }73 if let s = activeScene, windows.contains(where: { $0 === s }) { return s }74 return app.main75 }7677 private func bringForward() {78 #if os(macOS)79 NSApp?.activate(ignoringOtherApps: true)80 if !(NSApp?.windows.contains { $0.identifier?.rawValue.hasPrefix("main") == true && $0.isVisible } ?? false) { openWindow?(id: "main") }81 #endif82 }8384 private func open(_ link: DeepLink) async {85 switch link {86 case .conversation(let mb, let email, let thread): await showConversation(mailbox: mb, emailId: email, threadId: thread)87 case .inbox(let mb): bringForward(); await showInbox(mb, in: scene())88 case .compose(let mailto):89 let s = scene()90 guard let account = s.currentAccount ?? app.accounts.first?.id, let id = await app.makeComposer(mailto.map { .mailto($0.url) } ?? .new, account: account) else { return }91 present(composer: id, in: s)92 case .search(let text):93 bringForward()94 let s = scene()95 await showInbox(nil, in: s)96 s.search.text = text97 if text.isEmpty { s.focusSearchToken += 1 } else { await s.runSearch() }98 case .reminders:99 // the follow-up list is a screen of the productivity pass; until it registers itself here, the inbox is the closest place100 bringForward(); await showInbox(nil, in: scene())101 case .shareQueue: await app.system.shared.importSharedDrafts()102 }103 }104105 /// Opens a composer that already exists (`AppModel.composers`): a window on macOS, the sheet of the target window on iOS / iPadOS.106 func present(composer id: String, in target: MailScene? = nil) {107 #if os(macOS)108 NSApp?.activate(ignoringOtherApps: true)109 if let openWindow { openWindow(id: "compose", value: id) } else { (target ?? scene()).composeRequest = id }110 #else111 (target ?? scene()).composeRequest = id112 #endif113 }114115 private func showInbox(_ mailbox: String?, in s: MailScene) async {116 if let mailbox, mailbox != s.currentAccount, app.engines[mailbox] != nil { await s.switchAccount(mailbox) }117 guard let inbox = s.mailbox(.inbox) else { return }118 if s.selection != .mailbox(inbox.id) || s.search.isActive { s.selection = .mailbox(inbox.id); s.didSelectSidebar() }119 }120121 private func showConversation(mailbox mb: String, emailId: String, threadId: String?) async {122 guard let engine = app.engines[mb], let store = app.store else {123 app.toast = Toast(message: L("Ce message n’est plus disponible."), kind: .warning)124 return125 }126 // a notification can be tapped before the message was synced: fetch its header first127 try? await engine.ensureCached(ids: [emailId])128 guard let head = (try? await store.email(mb, id: emailId)) ?? nil else {129 bringForward()130 app.toast = Toast(message: L("Ce message n’est plus disponible."), kind: .warning)131 return132 }133 let s = scene(showing: mb, thread: head.threadId)134 bringForward()135 if s.activeAccount == mb, s.reader.conversation.contains(where: { $0.id == emailId }) { await s.focus(emailId); s.detailRequest += 1; return }136 await showInbox(mb, in: s)137 await s.reloadThreads()138 if let row = s.rows.first(where: { $0.id == emailId }) ?? s.rows.first(where: { $0.threadId == head.threadId }) {139 s.list.selectedIds = [row.id]140 await s.open(emailId: row.id)141 if row.id != emailId, s.reader.conversation.contains(where: { $0.id == emailId }) { await s.focus(emailId) }142 s.detailRequest += 1143 return144 }145 // not in the inbox list (filed by a rule, archived meanwhile): read it on its own146 #if os(macOS)147 if let openWindow { openWindow(id: "message", value: MessageRef(account: mb, emailId: emailId, conversation: app.settings.threaded)); return }148 #endif149 s.list.selectedIds = []150 if s.reader.account != mb { s.reader.clearBodies() }151 s.reader.account = mb152 let thread = app.settings.threaded ? ((try? await store.threadEmails(mb, threadId: head.threadId)) ?? []).filter { !$0.isDraft } : []153 s.reader.conversation = thread.contains { $0.id == head.id } ? thread : [head]154 s.reader.focusedEmailId = head.id155 await s.loadBody(head.id)156 if app.settings.markReadOnOpen, !head.isSeen { await engine.markSeen(true, ids: [head.id]) }157 s.detailRequest += 1158 }159}160161// MARK: - Handoff162163/// The open conversation is advertised to the person's other devices (same iCloud account) as opaque identifiers: no subject, no sender.164enum Handoff {165 static let activityType = "ai.spboucher.spmail.conversation"166 static func userInfo(mailboxId: String, emailId: String, threadId: String) -> [String: String] { ["mb": mailboxId, "email": emailId, "thread": threadId] }167 static func link(from info: [AnyHashable: Any]?) -> DeepLink? {168 guard let mb = info?["mb"] as? String, let email = info?["email"] as? String else { return nil }169 return DeepLink(url: DeepLink.conversation(mailboxId: mb, emailId: email, threadId: info?["thread"] as? String).url())170 }171}172173// MARK: - per-window hooks174175/// Attached to the root of each main window by the app entry points: URLs, Spotlight and Handoff continuation, Handoff advertising of the176/// open conversation, and delivery of waiting links when the app unlocks.177struct SystemSceneHooks: ViewModifier {178 let app: AppModel179 let scene: MailScene?180 @Environment(\.scenePhase) private var scenePhase181 #if os(macOS)182 @Environment(\.openWindow) private var openWindow183 #endif184185 private var handoffEmail: EmailSummary? { app.phase == .ready ? scene?.reader.focusedEmail : nil }186187 func body(content: Content) -> some View {188 let router = app.system.router189 content190 .onAppear {191 #if os(macOS)192 router.openWindow = openWindow193 #endif194 if let scene, router.activeScene == nil { router.activeScene = scene }195 }196 .onChange(of: scenePhase) { _, phase in if phase == .active, let scene { router.activeScene = scene } }197 .onOpenURL { router.handle(url: $0) }198 .onContinueUserActivity(CSSearchableItemActionType) { router.handle(activity: $0) }199 .onContinueUserActivity(Handoff.activityType) { router.handle(activity: $0) }200 .userActivity(Handoff.activityType, isActive: handoffEmail != nil) { activity in201 guard let e = handoffEmail, let account = scene?.activeAccount else { return }202 activity.title = "SP Mail"203 activity.isEligibleForHandoff = true204 activity.isEligibleForSearch = false205 activity.userInfo = Handoff.userInfo(mailboxId: account, emailId: e.id, threadId: e.threadId)206 activity.requiredUserInfoKeys = ["mb", "email"]207 }208 .onChange(of: app.phase) { old, phase in209 app.system.shared.writeState()210 guard phase == .ready else { return }211 Task {212 await router.flush()213 if old == .locked { await app.system.notifications.unlocked(); await app.system.shared.importSharedDrafts() }214 }215 }216 #if DEBUG && os(iOS)217 .task(id: scene?.id) {218 // `-spmOpenSettings YES` (simulator captures): the Settings sheet opens once the session is up219 guard UserDefaults.standard.bool(forKey: "spmOpenSettings"), let scene else { return }220 for _ in 0..<150 where app.phase != .ready { try? await Task.sleep(for: .milliseconds(200)) }221 if app.phase == .ready { scene.showSettings = true }222 }223 #endif224 .onChange(of: app.settings.lockEnabled) { _, _ in app.system.notifications.registerCategories(); app.system.shared.writeState() }225 .onChange(of: app.settings.lockAfterMinutes) { _, _ in app.system.shared.writeState() }226 .onChange(of: app.settings.hideNotificationContent) { _, hidden in227 app.system.shared.writeState(); app.system.shared.scheduleSnapshot()228 if hidden { Spotlight.removeAll() }229 }230 }231}232233extension View {234 /// The system hooks of a main window (see `SystemSceneHooks`).235 func systemScene(_ app: AppModel, _ scene: MailScene?) -> some View { modifier(SystemSceneHooks(app: app, scene: scene)) }236}237