Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Model/AppServices.swift3// Description: App-wide services extracted from AppModel: the sync status shown by the quiet indicator (fed by the core's SyncEngine.activity),4// the app lock / activity tracker (idle timer, « on leaving the app », notification privacy) and the hooks a later pass implements (snooze).5import SPMailCore6import SwiftUI7#if os(macOS)8import AppKit9#else10import UIKit11#endif1213/// Whether the app is frontmost (new-mail notifications are only posted when it is not). False until the tracker has read the real state:14/// a cold launch in the background (push, background refresh) must not count as « active ».15@MainActor16enum AppActivity {17 static var isActive = false18}1920// MARK: - sync status2122/// What the quiet sync indicator shows, across mailboxes. Fed by the core's `SyncEngine.activity` (`SyncStatus` of each engine) — the real23/// engine state, never a guess, never a blocking spinner.24@MainActor @Observable25final class SyncStatusModel {26 enum Display: Equatable { case synced, syncing, offline(pending: Int), error(String) }2728 /// Reachability as the engines' connectivity events report it (also read by the composer and the settings panes).29 var isOnline = true30 private(set) var statuses: [String: SyncStatus] = [:]31 /// « Synchronisation » is only shown once it has lasted more than 600 ms.32 private(set) var showsSyncing = false33 /// A failure reported by the interface itself (a manual refresh), until the next successful pass.34 var lastError: String?35 @ObservationIgnored private var debounce: Task<Void, Never>?3637 var isSyncing: Bool { statuses.values.contains(.syncing) }38 /// Changes waiting on this device (flag / move / delete operations and queued messages), as counted by the engines.39 var pending: Int { statuses.values.reduce(0) { if case .offline(let n) = $1 { return $0 + n } else { return $0 } } }40 var display: Display {41 if !isOnline || statuses.values.contains(where: { if case .offline = $0 { return true } else { return false } }) { return .offline(pending: pending) }42 for s in statuses.values { if case .error(let message, _) = s { return .error(message) } }43 if let lastError { return .error(lastError) }44 return showsSyncing ? .syncing : .synced45 }4647 func set(_ status: SyncStatus, account: String) {48 statuses[account] = status49 if status == .syncing || status == .idle { lastError = nil }50 guard isSyncing else { debounce?.cancel(); debounce = nil; showsSyncing = false; return }51 guard debounce == nil, !showsSyncing else { return }52 debounce = Task { [weak self] in53 try? await Task.sleep(for: .milliseconds(600))54 guard let self, !Task.isCancelled else { return }55 self.debounce = nil56 if self.isSyncing { self.showsSyncing = true }57 }58 }59 func forget(account: String) { statuses[account] = nil; if !isSyncing { debounce?.cancel(); debounce = nil; showsSyncing = false } }60 func reset() { debounce?.cancel(); debounce = nil; statuses = [:]; showsSyncing = false; lastError = nil; isOnline = true }61}6263// MARK: - lock and activity6465/// The app lock: idle timer, « as soon as the app is left » (application-level notifications on both platforms, so that one iPad scene going66/// to the background or one Mac window closing never counts as leaving), and what notifications may reveal.67@MainActor @Observable68final class LockController {69 @ObservationIgnored weak var app: AppModel?70 @ObservationIgnored var lastActivity = Date()71 @ObservationIgnored private(set) var leftAt: Date?72 @ObservationIgnored private var started = false73 @ObservationIgnored private var isAuthenticating = false74 @ObservationIgnored private var observers: [NSObjectProtocol] = []75 #if os(macOS)76 @ObservationIgnored private var eventMonitor: Any?77 #endif78 @ObservationIgnored private var idleTimer: Timer?7980 /// Installs the observers once for the life of the app.81 func start() {82 guard !started else { return }83 started = true84 let center = NotificationCenter.default85 func on(_ name: Notification.Name, _ body: @escaping @MainActor (LockController) -> Void) {86 observers.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { if let self { body(self) } } })87 }88 #if os(macOS)89 AppActivity.isActive = NSApp?.isActive ?? false90 on(NSApplication.didBecomeActiveNotification) { $0.appDidReturn() }91 on(NSApplication.didResignActiveNotification) { $0.appDidLeave() }92 on(NSApplication.didHideNotification) { $0.appDidLeave() }93 // one local monitor for the life of the app (it used to be added again at every appearance of the main view)94 eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown, .scrollWheel]) { [weak self] e in95 MainActor.assumeIsolated { self?.lastActivity = Date() }96 return e97 }98 #else99 AppActivity.isActive = UIApplication.shared.applicationState == .active100 on(UIApplication.didBecomeActiveNotification) { $0.appDidReturn() }101 on(UIApplication.willResignActiveNotification) { _ in AppActivity.isActive = false }102 on(UIApplication.didEnterBackgroundNotification) { $0.appDidLeave() }103 #endif104 idleTimer = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.lockIfNeeded() } }105 }106107 func noteActivity() { lastActivity = Date() }108109 /// The app is no longer in front. With « Dès la sortie de l’app » the lock is immediate, so nothing readable is left for the return.110 func appDidLeave() {111 AppActivity.isActive = false112 guard let app, app.phase == .ready, !isAuthenticating else { return }113 if app.settings.lockEnabled, app.settings.lockAfterMinutes == 0 { app.phase = .locked; leftAt = nil } else if leftAt == nil { leftAt = Date() }114 }115116 func appDidReturn() {117 AppActivity.isActive = true118 guard let app else { return }119 if let since = leftAt {120 leftAt = nil121 if app.settings.lockEnabled, app.phase == .ready, Date().timeIntervalSince(since) > Double(app.settings.lockAfterMinutes) * 60 { app.phase = .locked }122 }123 lastActivity = Date()124 Task { if app.phase == .ready { await app.refreshAll() } }125 }126127 func lockIfNeeded(force: Bool = false) {128 guard let app, app.settings.lockEnabled, app.phase == .ready else { return }129 let idle = Date().timeIntervalSince(lastActivity)130 if force || (app.settings.lockAfterMinutes > 0 && idle > Double(app.settings.lockAfterMinutes) * 60) { app.phase = .locked }131 }132133 func unlock() async {134 guard let app, app.phase == .locked, !isAuthenticating else { return }135 isAuthenticating = true136 let ok = await AppLock.unlock(reason: L("Déverrouiller SP Mail"))137 // the system sheet made the app resign active: only now may « leaving » lock again138 try? await Task.sleep(for: .milliseconds(400))139 isAuthenticating = false140 if ok, app.phase == .locked { app.phase = .ready; lastActivity = Date(); leftAt = nil }141 }142143 /// True when a notification or the menu bar must not show senders or subjects: the app is locked, or would be if it were opened now.144 var concealsContent: Bool {145 guard let app else { return true }146 if app.phase == .locked { return true }147 guard app.settings.lockEnabled, !AppActivity.isActive else { return false }148 if app.settings.lockAfterMinutes == 0 { return true }149 return leftAt.map { Date().timeIntervalSince($0) > Double(app.settings.lockAfterMinutes) * 60 } ?? false150 }151152 #if DEBUG153 /// Self-test: simulates leaving and coming back without the system notifications.154 func simulateLeave() { appDidLeave() }155 #endif156}157158// MARK: - hooks for later passes159160/// Entry points wired in the interface now and implemented by a later pass.161@MainActor162struct MailHooks {163 /// Snooze the messages `ids` of mailbox `account` (swipe action, context menu). Nil until the snooze pass lands.164 var snooze: ((_ ids: [String], _ account: String) async -> Void)?165}166