// MAY THIS PHONE RING? — the question the alarms feature spent a year not// asking.//// "Which scheduler" reads like the whole question because one of its two// answers is called `notification`. It is not: the notification backend has a// gate of its own that AlarmKit does not — the OS notification permission — and// Cotton deliberately never asks for that at boot, because the prompt is spent// once, for ever. So the ordinary path for somebody whose first serious use of// the app is setting an alarm was: permission undetermined, the request handed// to the notification centre anyway, iOS filing it in a queue it would never// present, and the reconciler recording it as done. The alarm did not ring and// no surface anywhere said why.//// There is a second gate beside it and it was equally unread: the person's own// **Alarms** switch. It wrote a preference, and nothing on earth read it — so// turning alarms off left them ringing and turning them on repaired nothing.//// This is the one place both are resolved, and it answers with a REASON rather// than a boolean, because the screen has to say which of them it is: "allow// notifications" and "your Alarms switch is off" are different problems with// different fixes, and a single "alarms are off" line would send half the// people who read it to the wrong place.importFoundation/// Whether a real alarm is possible at all, and whether the person has agreed./// `unavailable` is a normal state (an older OS), not a failure.publicenumAlarmAuthorization: String, Equatable, Sendable {case unavailablecase notDeterminedcase deniedcase authorized}/// Why nothing will ring. Each one has a different way out.publicenumAlarmSilence: String, Equatable, Sendable {/// The person turned Alarms off. One tap to undo, inside the app.case switchedOff/// Never asked. Cotton may still ask — and the Alarms screen is a fair/// place to do it.case permissionUndetermined/// Asked and refused. iOS never re-prompts; only Settings can undo it.case permissionDenied}publicstructAlarmGate: Equatable, Sendable {/// Which scheduler a pass would use.publicvar backend: AlarmBackend/// May a pass hand anything to it?publicvar canSchedule: Bool/// Why not — `nil` exactly when `canSchedule` is true.publicvar silence: AlarmSilence?publicinit(backend: AlarmBackend, canSchedule: Bool, silence: AlarmSilence?) {self.backend = backendself.canSchedule = canScheduleself.silence = silence }}/// The person's own Alarms switch.////// In the previous app this lived inside one `@cotton:notifprefs` record with the/// other four notification categories. That whole record — the categories, the/// mood hour, the "have we asked yet" stamp — belongs to the notifications/// lane, which has not landed here; this protocol is the ONE half the alarm/// gate needs, so the gate is a real question rather than a hardcoded yes. When/// the prefs record lands, this reader moves onto it and the protocol stays.publicprotocolAlarmPreferences: Sendable {var alarmsEnabled: Bool { get }}/// `@unchecked Sendable`: the only stored property is `UserDefaults`, which is/// documented thread-safe but is not marked `Sendable`.publicstructStoredAlarmPreferences: AlarmPreferences, @unchecked Sendable {privatelet defaults: UserDefaults/// The inherited category name, under this app's key namespace.publicstaticlet key = "cotton.notifications.alarms"publicinit(defaults: UserDefaults = .standard) {self.defaults = defaults }/// Defaults ON, which is not the same as "alarms default on": nothing can/// be scheduled until the OS grants permission, and this app never asks for/// that at boot. The switch describes what a person would want IF they said/// yes.publicvar alarmsEnabled: Bool { defaults.object(forKey: Self.key) as? Bool ?? true }}/// What the OS will tell us, behind a protocol so a test can drive the gate/// without a device and without a prompt.publicprotocolAlarmAuthorizer: Sendable {/// Can this binary, on this OS, schedule a real alarm at all? Says nothing/// about permission.func alarmKitAvailable() -> Boolfunc alarmKitAuthorization() async -> AlarmAuthorization/// Raise AlarmKit's prompt when undetermined; a plain read once decided./// Only `askForAlarmKitIfDue` calls it.func requestAlarmKitAuthorization() async -> AlarmAuthorization/// The notification permission, which is the FALLBACK backend's gate.func notificationAuthorization() async -> AlarmAuthorization}/// Ask for AlarmKit's permission at the first moment it means something.////// Without this nothing ever asked, so AlarmKit stayed `notDetermined` for/// ever and every alarm fell back to a notification that does not ring through/// the silent switch. The prompt is spent once, so it is not raised at boot or/// because a list was looked at, nor by an alarm another device set arriving/// (294 row 4, walker293: the prompt rose at first launch on Me): it is/// raised by the pass after the person sets or switches on an alarm on this/// phone (`setHere`), with their own Alarms switch on. Only `notDetermined`/// asks; a decided answer is never asked again. Answers whether it asked.@discardableResultfunc askForAlarmKitIfDue( _ authorizer: someAlarmAuthorizer, preferences: someAlarmPreferences, alarms: [Alarm], setHere: Bool) async -> Bool {guard setHere, preferences.alarmsEnabled, alarms.contains(where: \.enabled), authorizer.alarmKitAvailable(),await authorizer.alarmKitAuthorization() == .notDeterminedelse { returnfalse } _ = await authorizer.requestAlarmKitAuthorization()returntrue}/// Which backend is live RIGHT NOW.////// Asked once per pass rather than cached, because the answer changes the/// moment the person grants (or revokes) permission in Settings, and a stale/// `alarmkit` would leave real alarms unscheduled behind a screen claiming they/// ring.publicfunc resolveAlarmBackend(_ authorizer: someAlarmAuthorizer) async -> AlarmBackend {guard authorizer.alarmKitAvailable() else { return .notification }returnawait authorizer.alarmKitAuthorization() == .authorized ? .alarmkit : .notification}/// Decide the gate from the preference and the OS.////// The person's own switch is reported FIRST when both are shut. It is their/// decision rather than the platform's, it is the one they can undo without/// leaving the app, and telling somebody to grant a permission they will then/// find changed nothing is the worse of the two wrong answers.publicfunc resolveAlarmGate( preferences: someAlarmPreferences, authorizer: someAlarmAuthorizer) async -> AlarmGate {let backend = await resolveAlarmBackend(authorizer)if !preferences.alarmsEnabled {returnAlarmGate(backend: backend, canSchedule: false, silence: .switchedOff) }// AlarmKit has no second gate: being on this backend at all IS its// authorization having been granted, and a real alarm does not travel// through the notification permission.if backend == .alarmkit {returnAlarmGate(backend: backend, canSchedule: true, silence: nil) }switchawait authorizer.notificationAuthorization() {case .authorized:returnAlarmGate(backend: backend, canSchedule: true, silence: nil)case .denied:returnAlarmGate(backend: backend, canSchedule: false, silence: .permissionDenied)case .notDetermined, .unavailable:returnAlarmGate(backend: backend, canSchedule: false, silence: .permissionUndetermined) }}