// 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.importCottonKitimportFoundationimportUserNotifications#if canImport(AlarmKit)importAlarmKitimportSwiftUI#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.publicstructAlarmSchedule: Equatable, Sendable {publiclet id: String/// The lock-screen headline: the person's label, or the app's word for an/// alarm they never named.publiclet title: Stringpubliclet label: Stringpubliclet stopLabel: Stringpubliclet hour: Intpubliclet minute: Int/// ISO weekdays 1–7. Empty = one-shot at the next occurrence.publiclet 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.publiclet sound: Boolpublicinit( id: String, title: String, label: String, stopLabel: String, hour: Int, minute: Int, repeatDays: [Int], sound: Bool ) {self.id = idself.title = titleself.label = labelself.stopLabel = stopLabelself.hour = hourself.minute = minuteself.repeatDays = repeatDaysself.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.publicprotocolAlarmDevice: 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 -> Boolfunc cancelFallback(keys: [String]) async}/// The real device./// `@unchecked Sendable`: the stored `UNUserNotificationCenter` is documented/// thread-safe but is not marked `Sendable`.publicstructSystemAlarmDevice: AlarmDevice, AlarmAuthorizer, @unchecked Sendable {privatelet centre: UNUserNotificationCenterprivatelet calendar: Calendarpublicinit(centre: UNUserNotificationCenter = .current(), calendar: Calendar = .current) {self.centre = centreself.calendar = calendar }// ── AlarmKit ────────────────────────────────────────────────────────────publicfunc alarmKitAvailable() -> Bool { #if canImport(AlarmKit)if #available(iOS 26.0, *) { returntrue }returnfalse #elsereturnfalse #endif }publicfunc alarmKitAuthorization() async -> AlarmAuthorization { #if canImport(AlarmKit)if #available(iOS 26.0, *) {switchAlarmManager.shared.authorizationState {case .authorized: return .authorizedcase .denied: return .deniedcase .notDetermined: return .notDetermined @unknown default: return .notDetermined } } #endifreturn .unavailable }/// Presents the system prompt when undetermined; a no-op read once decided.publicfunc requestAlarmKitAuthorization() async -> AlarmAuthorization { #if canImport(AlarmKit)if #available(iOS 26.0, *) {guardlet state = try? awaitAlarmManager.shared.requestAuthorization() else {return .unavailable }switch state {case .authorized: return .authorizedcase .denied: return .deniedcase .notDetermined: return .notDetermined @unknown default: return .notDetermined } } #endifreturn .unavailable }publicfunc alarmKitIds() async -> [String]? { #if canImport(AlarmKit)if #available(iOS 26.0, *) {guardlet live = try? AlarmManager.shared.alarms else { returnnil }// 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() } } #endifreturnnil }publicfunc scheduleAlarmKit(_ schedule: AlarmSchedule) async -> Bool { #if canImport(AlarmKit)if #available(iOS 26.0, *) {guardlet uuid = UUID(uuidString: schedule.id) else { returnfalse }guardAlarmManager.shared.authorizationState == .authorized else { returnfalse }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? awaitAlarmManager.shared.schedule(id: uuid, configuration: configuration)) != nilelse { returnfalse }returntrue } #endifreturnfalse }publicfunc cancelAlarmKit(id: String) async -> Bool { #if canImport(AlarmKit)if #available(iOS 26.0, *) {guardlet uuid = UUID(uuidString: id) else { returnfalse }let live = (try? AlarmManager.shared.alarms) ?? []guard live.contains(where: { $0.id == uuid }) else { returntrue }guard (try? AlarmManager.shared.cancel(id: uuid)) != nilelse { returnfalse }returntrue } #endifreturnfalse }// ── The notification fallback ───────────────────────────────────────────publicfunc notificationAuthorization() async -> AlarmAuthorization {let settings = await centre.notificationSettings()switch settings.authorizationStatus {case .authorized, .provisional, .ephemeral: return .authorizedcase .denied: return .deniedcase .notDetermined: return .notDetermined @unknown default: return .notDetermined } }publicfunc notificationKeys() async -> [String]? {await centre.pendingNotificationRequests().map(\.identifier) }publicfunc 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 )tryawait centre.add( UNNotificationRequest( identifier: "\(alarmKeyPrefix)\(schedule.id)", content: content, trigger: UNCalendarNotificationTrigger(dateMatching: parts, repeats: false) ) )returntrue }// 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.minutetryawait centre.add( UNNotificationRequest( identifier: "\(alarmKeyPrefix)\(schedule.id):\(iso)", content: content, trigger: UNCalendarNotificationTrigger(dateMatching: parts, repeats: true) ) ) }returntrue } catch {// Leave the ledger unwritten and try again next pass, rather than// record a request the centre refused as done.returnfalse } }/// 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.publicfunc 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.publiclet alarmNotificationKind = "alarm"#if canImport(AlarmKit) @available(iOS 26.0, *)structCottonAlarmMetadata: 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 {case1: return .mondaycase2: return .tuesdaycase3: return .wednesdaycase4: return .thursdaycase5: return .fridaycase6: return .saturdaycase7: return .sundaydefault: returnnil } }#endif