Cotton code
329 lines · 13.8 KB · SwiftRaw
// The two backends, and the OS behind them.//// There is no native module standing in front of AlarmKit any more: this app// IS Swift, so the framework is called directly and the bridge stops existing.//// **Three gates stand in front of AlarmKit and all three fail CLOSED** — the// caller falls back to a notification, never to silence-that-looks-armed://// 1. `#if canImport(AlarmKit)` — built by an Xcode whose SDK predates iOS 26.// 2. `if #available(iOS 26.0, *)` — running on an older OS.// 3. the authorization state — the person said no, or has not been asked.//// AlarmKit needs NO entitlement, only the `NSAlarmKitUsageDescription` string.// The much-repeated `com.apple.developer.alarmkit` does not exist — Apple's own// staff have called it an invention that breaks device builds — so do not add// it when a signing error tempts you to.//// **Honesty, not loudness**, on the fallback: `timeSensitive` is the loudest// interruption level available without the critical-alerts entitlement, and it// still respects the silent switch. So a fallback alarm is a REMINDER, and// every surface that can be in this state has to say so. Promising a ring this// path cannot deliver is the one failure mode worth more than the feature.//// The row id IS the AlarmKit id: `cotton_alarms.id` is a uuid and `Alarm.ID` is// a `UUID`, so the reconciler's desired set diffs against the live list with no// side table to keep in step.import CottonKitimport Foundationimport UserNotifications#if canImport(AlarmKit)    import AlarmKit    import SwiftUI#endif/// What one alarm asks the device for. The COPY travels down (`title`,/// `stopLabel`) because every user-facing word in this app comes from/// `CottonStrings`, and this file must never hardcode one the sweep cannot see.public struct AlarmSchedule: Equatable, Sendable {    public let id: String    /// The lock-screen headline: the person's label, or the app's word for an    /// alarm they never named.    public let title: String    public let label: String    public let stopLabel: String    public let hour: Int    public let minute: Int    /// ISO weekdays 1–7. Empty = one-shot at the next occurrence.    public let repeatDays: [Int]    /// Does it make a noise (schema v24)? Honoured on the FALLBACK only: an    /// AlarmKit alarm is a ringing alarm by construction — that is what the    /// framework is for — and its own alert sound wants an API this file does    /// not call. The sheet says so under the switch rather than drawing a    /// control that quietly does nothing on the loud path.    public let sound: Bool    public init(        id: String,        title: String,        label: String,        stopLabel: String,        hour: Int,        minute: Int,        repeatDays: [Int],        sound: Bool    ) {        self.id = id        self.title = title        self.label = label        self.stopLabel = stopLabel        self.hour = hour        self.minute = minute        self.repeatDays = repeatDays        self.sound = sound    }}/// Everything the reconciler does to the device, behind one protocol so the/// pass is drivable in a test without a simulator, a permission or a clock.public protocol AlarmDevice: Sendable {    /// The ids AlarmKit currently holds — the "actual" set. `nil` means    /// UNKNOWN (no framework, or the read threw), which is NOT "none": diffing    /// against an empty set would cancel nothing and reschedule everything.    func alarmKitIds() async -> [String]?    /// Schedule (or REPLACE — scheduling a live id overwrites it, which is what    /// makes the reconciler's "changed" case a plain re-schedule). `false` =    /// the caller must not record it as done.    func scheduleAlarmKit(_ schedule: AlarmSchedule) async -> Bool    /// Idempotent: cancelling an id AlarmKit does not hold still succeeds.    func cancelAlarmKit(id: String) async -> Bool    /// Every pending notification identifier — ours AND the rest of the app's.    /// The reconciler needs the whole list so it can tell "my key is missing"    /// from "my key is there"; it filters to ours before cancelling anything.    func notificationKeys() async -> [String]?    func scheduleFallback(_ schedule: AlarmSchedule, now: Date) async -> Bool    func cancelFallback(keys: [String]) async}/// The real device./// `@unchecked Sendable`: the stored `UNUserNotificationCenter` is documented/// thread-safe but is not marked `Sendable`.public struct SystemAlarmDevice: AlarmDevice, AlarmAuthorizer, @unchecked Sendable {    private let centre: UNUserNotificationCenter    private let calendar: Calendar    public init(centre: UNUserNotificationCenter = .current(), calendar: Calendar = .current) {        self.centre = centre        self.calendar = calendar    }    // ── AlarmKit ────────────────────────────────────────────────────────────    public func alarmKitAvailable() -> Bool {        #if canImport(AlarmKit)            if #available(iOS 26.0, *) { return true }            return false        #else            return false        #endif    }    public func alarmKitAuthorization() async -> AlarmAuthorization {        #if canImport(AlarmKit)            if #available(iOS 26.0, *) {                switch AlarmManager.shared.authorizationState {                case .authorized: return .authorized                case .denied: return .denied                case .notDetermined: return .notDetermined                @unknown default: return .notDetermined                }            }        #endif        return .unavailable    }    /// Presents the system prompt when undetermined; a no-op read once decided.    public func requestAlarmKitAuthorization() async -> AlarmAuthorization {        #if canImport(AlarmKit)            if #available(iOS 26.0, *) {                guard let state = try? await AlarmManager.shared.requestAuthorization() else {                    return .unavailable                }                switch state {                case .authorized: return .authorized                case .denied: return .denied                case .notDetermined: return .notDetermined                @unknown default: return .notDetermined                }            }        #endif        return .unavailable    }    public func alarmKitIds() async -> [String]? {        #if canImport(AlarmKit)            if #available(iOS 26.0, *) {                guard let live = try? AlarmManager.shared.alarms else { return nil }                // Lowercased, because AlarmKit uppercases a uuid and the row's                // id is stored the way the file wrote it.                return live.map { $0.id.uuidString.lowercased() }            }        #endif        return nil    }    public func scheduleAlarmKit(_ schedule: AlarmSchedule) async -> Bool {        #if canImport(AlarmKit)            if #available(iOS 26.0, *) {                guard let uuid = UUID(uuidString: schedule.id) else { return false }                guard AlarmManager.shared.authorizationState == .authorized else { return false }                let stop = AlarmButton(                    text: LocalizedStringResource(stringLiteral: schedule.stopLabel),                    textColor: .white,                    systemImageName: "alarm"                )                let alert = AlarmPresentation.Alert(                    title: LocalizedStringResource(stringLiteral: schedule.title),                    stopButton: stop                )                let attributes = AlarmAttributes<CottonAlarmMetadata>(                    presentation: AlarmPresentation(alert: alert),                    metadata: CottonAlarmMetadata(label: schedule.label),                    tintColor: .white                )                let time = AlarmKit.Alarm.Schedule.Relative.Time(hour: schedule.hour, minute: schedule.minute)                // Empty repeatDays = a one-shot at the next occurrence, which                // `.never` is exactly: a relative schedule with no recurrence                // still fires once, at the next wall-clock match.                let weekdays = schedule.repeatDays.compactMap(alarmKitWeekday(fromISO:))                let repeats: AlarmKit.Alarm.Schedule.Relative.Recurrence =                    weekdays.isEmpty ? .never : .weekly(weekdays)                let configuration = AlarmManager.AlarmConfiguration.alarm(                    schedule: .relative(AlarmKit.Alarm.Schedule.Relative(time: time, repeats: repeats)),                    attributes: attributes                )                guard (try? await AlarmManager.shared.schedule(id: uuid, configuration: configuration)) != nil                else { return false }                return true            }        #endif        return false    }    public func cancelAlarmKit(id: String) async -> Bool {        #if canImport(AlarmKit)            if #available(iOS 26.0, *) {                guard let uuid = UUID(uuidString: id) else { return false }                let live = (try? AlarmManager.shared.alarms) ?? []                guard live.contains(where: { $0.id == uuid }) else { return true }                guard (try? AlarmManager.shared.cancel(id: uuid)) != nil else { return false }                return true            }        #endif        return false    }    // ── The notification fallback ───────────────────────────────────────────    public func notificationAuthorization() async -> AlarmAuthorization {        let settings = await centre.notificationSettings()        switch settings.authorizationStatus {        case .authorized, .provisional, .ephemeral: return .authorized        case .denied: return .denied        case .notDetermined: return .notDetermined        @unknown default: return .notDetermined        }    }    public func notificationKeys() async -> [String]? {        await centre.pendingNotificationRequests().map(\.identifier)    }    public func scheduleFallback(_ schedule: AlarmSchedule, now: Date) async -> Bool {        let content = UNMutableNotificationContent()        content.title = schedule.title        // The person's own switch (schema v24). A silent alarm still arrives,        // it still breaks Focus and it still lights the screen — it just does        // not make a noise, which is the whole request behind "wake me without        // waking the room".        content.sound = schedule.sound ? .default : nil        // The loudest honest level: breaks through Focus, NOT the silent switch.        content.interruptionLevel = .timeSensitive        content.userInfo = ["kind": alarmNotificationKind, "id": schedule.id]        do {            if schedule.repeatDays.isEmpty {                let at = nextOneShotAt(                    hour: schedule.hour,                    minute: schedule.minute,                    now: now,                    calendar: calendar                )                let parts = calendar.dateComponents(                    [.year, .month, .day, .hour, .minute],                    from: at                )                try await centre.add(                    UNNotificationRequest(                        identifier: "\(alarmKeyPrefix)\(schedule.id)",                        content: content,                        trigger: UNCalendarNotificationTrigger(dateMatching: parts, repeats: false)                    )                )                return true            }            // iOS repeats a calendar trigger on ONE weekday, so a Mon/Wed alarm            // is two standing requests. Their identifiers carry the ISO day,            // which is what makes the diff in `reconcileAlarms` line up.            for iso in schedule.repeatDays {                var parts = DateComponents()                parts.weekday = isoToAppleWeekday(iso)                parts.hour = schedule.hour                parts.minute = schedule.minute                try await centre.add(                    UNNotificationRequest(                        identifier: "\(alarmKeyPrefix)\(schedule.id):\(iso)",                        content: content,                        trigger: UNCalendarNotificationTrigger(dateMatching: parts, repeats: true)                    )                )            }            return true        } catch {            // Leave the ledger unwritten and try again next pass, rather than            // record a request the centre refused as done.            return false        }    }    /// Cancel by identifier. Only `cotton:alarm:` keys are honoured — a guard,    /// not an optimisation: this is handed a diff, and a bug upstream must not    /// be able to wipe reminders another part of the app scheduled.    public func cancelFallback(keys: [String]) async {        let ours = keys.filter(isAlarmKey)        guard !ours.isEmpty else { return }        centre.removePendingNotificationRequests(withIdentifiers: ours)    }}/// Marks an alarm notification's payload so a tap can route to the screen.public let alarmNotificationKind = "alarm"#if canImport(AlarmKit)    @available(iOS 26.0, *)    struct CottonAlarmMetadata: AlarmMetadata {        let label: String    }    /// ISO 1–7 (Mon–Sun) → `Locale.Weekday`. Anything else is DROPPED rather    /// than guessed: the tool has already refused an out-of-range day, so a    /// survivor here would be a bug, not somebody's data.    @available(iOS 26.0, *)    func alarmKitWeekday(fromISO day: Int) -> Locale.Weekday? {        switch day {        case 1: return .monday        case 2: return .tuesday        case 3: return .wednesday        case 4: return .thursday        case 5: return .friday        case 6: return .saturday        case 7: return .sunday        default: return nil        }    }#endif