From 412e54db09654b484ade6d4801a849cf95883f1b Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Wed, 21 Oct 2026 18:52:25 +0200 Subject: [PATCH 1/8] feat(settings): let alarms and timers choose when they silence themselves A ringing alarm and a finished timer used to stop after a fixed ten minutes. Settings > Alarms and Settings > Timers now each have a "Silence after" row with Google Clock's choices: 1, 5, 10, 15, 20 or 25 minutes, or Never. Ten minutes stays the default, so nothing changes on upgrade. The value is app-wide; a per-alarm override would need a new column, a migration and an editor row, and is left out. "Never" rings for an hour, then stops. The backstop is also what keeps a phone left at home from ringing its battery flat, what bounds the ring services' wake locks, and what stops a reboot hours later from resuming a ring nobody was there for. A truly unbounded ring would give all of that up, so Never maps to a one-hour hard stop, longer than any finite choice, and the settings hint says so. Stored values clamp to 0..60 on read, on write and from a backup. The window is read everywhere the fixed constant was: the resolver's ringing and late-snooze checks (which now take it without a default), the backstop onFire arms, how late a snooze fire may arrive, whether an interrupted ring is resumed after a reboot, upcoming(), the timer ring policy, the lapsed-session check and the timer ring screen. Both ring services' wake-lock timeouts now derive from the hard stop instead of a hard-coded fifteen minutes. When the resolver closes a ring (the window was shortened mid-ring, the clock jumped, the alarm was switched off), the engine now also stops the ring service and cancels the backstop. Before, it only cleared ringingSince and left the sound to a backstop armed for the old window. Both values are backed up as default_alarm_silence_after_minutes and default_timer_silence_after_minutes; a file without them imports as ten minutes. Fixes #17 --- CHANGELOG.md | 4 + .../clockula/alarm/AlarmEngine.kt | 37 ++++-- .../clockula/alarm/ring/AlarmRingService.kt | 9 +- .../clockula/data/backup/BackupCodec.kt | 5 + .../clockula/data/backup/BackupDto.kt | 7 + .../clockula/data/prefs/ClockPrefs.kt | 14 ++ .../clockula/data/prefs/SettingsPrefs.kt | 16 ++- .../clockula/domain/ClockDefaults.kt | 18 ++- .../clockula/domain/alarm/AlarmResolver.kt | 6 +- .../clockula/domain/alarm/AlarmRing.kt | 14 +- .../clockula/domain/ring/SilenceAfter.kt | 44 +++++++ .../clockula/domain/timer/TimerRing.kt | 14 +- .../clockula/domain/timer/TimerRingPolicy.kt | 9 +- .../clockula/timer/TimerEngine.kt | 3 +- .../clockula/timer/service/TimerService.kt | 9 +- .../clockula/ui/alarms/OverridePickers.kt | 30 +++++ .../clockula/ui/ring/TimerRingViewModel.kt | 13 +- .../ui/settings/AlarmDefaultsScreen.kt | 23 +++- .../clockula/ui/settings/SettingsViewModel.kt | 6 + .../ui/settings/TimerDefaultsScreen.kt | 27 +++- app/src/main/res/values/strings.xml | 10 ++ .../clockula/alarm/AlarmEngineInteropTest.kt | 4 +- .../clockula/alarm/AlarmEngineTest.kt | 123 +++++++++++++++++- .../clockula/data/backup/BackupCodecTest.kt | 17 +++ .../clockula/data/prefs/ClockPrefsTest.kt | 22 ++++ .../clockula/data/prefs/SettingsPrefsTest.kt | 10 +- .../domain/alarm/AlarmResolverTest.kt | 56 +++++++- .../clockula/domain/ring/SilenceAfterTest.kt | 50 +++++++ .../domain/timer/TimerRingPolicyTest.kt | 44 ++++++- .../clockula/timer/TimerEngineTest.kt | 23 +++- .../ui/ring/TimerRingViewModelTest.kt | 23 +++- docs/ARCHITECTURE.md | 57 ++++++-- docs/BACKUP.md | 13 +- 33 files changed, 680 insertions(+), 80 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfterTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 76d4d0d..bf9bb46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,10 @@ The first release of Clockula: alarms, timers, a stopwatch and a world clock. with Clockula. A voice-set alarm cleans up after itself once dismissed. - Settings: theme, dynamic colour, language, and the defaults every new alarm and timer inherits. +- Choose how long a ringing alarm or a finished timer keeps going before it + stops on its own: 1, 5, 10, 15, 20 or 25 minutes, or Never, separately for + alarms and timers. Ten minutes stays the default, and Never still stops + after an hour so a phone left at home can't ring its battery flat. - Back up alarms, timers, world clocks and settings to a JSON file, and restore them on this device or another one. - "Why might my alarm not ring?", a self-check that reads your device's real diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt index d9ff0a9..9acaedc 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt @@ -182,7 +182,12 @@ class AlarmEngine @Inject constructor( * emission; a live readout passes a `Ticker`'s flow (M5 D8). */ fun upcoming(refresh: Flow = flowOf(Unit)): Flow> = - combine(alarms.alarms(), states.states(), refresh) { alarms, states, _ -> + combine( + alarms.alarms(), + states.states(), + settings.defaults.map { it.alarmSilenceAfter }.distinctUntilChanged(), + refresh, + ) { alarms, states, silenceAfter, _ -> val now = wallClock.now() val zone = zones.current() val byId = states.associateBy { it.alarmId } @@ -195,6 +200,7 @@ class AlarmEngine @Inject constructor( byId[alarm.id] ?: AlarmRingState.initial(alarm.id), now, zone, + silenceAfter, ) UpcomingAlarm(alarm, resolution.nextFire, resolution.source) } @@ -207,11 +213,12 @@ class AlarmEngine @Inject constructor( private suspend fun rescheduleLocked(): ScheduledFire? { val now = wallClock.now() val zone = zones.current() + val silenceAfter = settings.currentDefaults().alarmSilenceAfter var earliest: Pair? = null for (alarm in alarms.alarms().first()) { val state = states.state(alarm.id) - val resolution = AlarmResolver.resolve(alarm, state, now, zone) + val resolution = AlarmResolver.resolve(alarm, state, now, zone, silenceAfter) persist(alarm, state, resolution) val fireAt = resolution.nextFire ?: continue @@ -236,10 +243,11 @@ class AlarmEngine @Inject constructor( val alarm = alarms.find(alarmId) val state = states.state(alarmId) val isSnoozeFire = state.snoozedUntil != null && state.snoozedUntil == scheduledFor + val silenceAfter = settings.currentDefaults().alarmSilenceAfter // A snooze is kept for as long as the resolver keeps it pending, so one // delivered late (after a reboot, or by Doze) still rings. Rejecting it // here would only re-register the same past instant and fire again. - val lateBy = if (isSnoozeFire) AlarmRing.AUTO_SILENCE_AFTER else AlarmRing.FIRE_GRACE + val lateBy = if (isSnoozeFire) silenceAfter else AlarmRing.FIRE_GRACE // Deleted, switched off, or a PendingIntent so stale the moment has gone: // re-resolve the slot and stay quiet. if (alarm == null || !alarm.enabled || now - scheduledFor > lateBy) { @@ -270,7 +278,7 @@ class AlarmEngine @Inject constructor( states.save(states.state(alarmId).copy(ringingSince = now)) ring.startRinging(alarmId) - scheduler.scheduleAutoSilence(now + AlarmRing.AUTO_SILENCE_AFTER, alarmId) + scheduler.scheduleAutoSilence(now + silenceAfter, alarmId) return FireOutcome.Ringing(alarmId) } @@ -307,20 +315,33 @@ class AlarmEngine @Inject constructor( private suspend fun resumeRingingIfAnyLocked(): Long? { val state = states.ringing() ?: return null val since = state.ringingSince ?: return null + val silenceAfter = settings.currentDefaults().alarmSilenceAfter // Slept through it: leave it to the next resolution to close the cycle. - if (wallClock.now() - since >= AlarmRing.AUTO_SILENCE_AFTER) return null + if (wallClock.now() - since >= silenceAfter) return null val alarm = alarms.find(state.alarmId)?.takeIf { it.enabled } ?: return null ring.startRinging(alarm.id) // The backstop is measured from when the ring started, not from now, so - // a reboot does not buy the alarm another ten minutes. - scheduler.scheduleAutoSilence(since + AlarmRing.AUTO_SILENCE_AFTER, alarm.id) + // a reboot does not buy the alarm a fresh window. + scheduler.scheduleAutoSilence(since + silenceAfter, alarm.id) return alarm.id } - /** Everything the resolver asked to be written, and nothing it did not. */ + /** + * Everything the resolver asked to be written, and nothing it did not — + * plus stopping the sound of a ring it closed, which storage alone cannot do. + */ private suspend fun persist(alarm: Alarm, before: AlarmRingState, resolution: AlarmResolution) { if (resolution.state != before) states.save(resolution.state) + // The resolver closed a ring: its window ran out before the backstop + // fired ("Silence after" was shortened mid-ring, or the clock jumped), + // or the alarm was switched off while ringing. Storage now says it is + // not ringing, so the sound stops with it rather than waiting for a + // backstop registered against the old window. + if (before.ringingSince != null && resolution.state.ringingSince == null) { + ring.stopRinging(alarm.id) + scheduler.cancelAutoSilence() + } if (resolution.clearSkipFlag) alarms.setSkipNextOccurrence(alarm.id, false) // A transient alarm is deleted wherever a permanent one would be // disabled: the cycle has closed either way (M9 D10). diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/ring/AlarmRingService.kt b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/ring/AlarmRingService.kt index 828d27f..11d71a2 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/ring/AlarmRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/ring/AlarmRingService.kt @@ -17,6 +17,7 @@ import de.jeanlucmakiola.clockula.alarm.AlarmIntents import de.jeanlucmakiola.clockula.domain.alarm.RingPresentationPolicy import de.jeanlucmakiola.clockula.domain.alarm.RingSession import de.jeanlucmakiola.clockula.domain.ring.RingFallbackPolicy +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.clockula.ring.RingAudioPlayer import de.jeanlucmakiola.clockula.ring.RingVibrator import kotlinx.coroutines.CoroutineScope @@ -25,6 +26,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch +import kotlin.time.Duration.Companion.minutes import javax.inject.Inject /** @@ -198,8 +200,11 @@ class AlarmRingService : Service() { private const val ACTION_REPOST = AlarmIntents.ACTION_DISMISS + ".SERVICE_REPOST" private const val WAKE_LOCK_TAG = "clockula:alarm-ring" - /** A backstop on the backstop: the ring window is ten minutes. */ - private const val WAKE_LOCK_TIMEOUT_MILLIS = 15L * 60L * 1_000L + /** + * A backstop on the backstop: past the longest ring window any "Silence + * after" choice allows, so a ring is never cut short by its own wake lock. + */ + private val WAKE_LOCK_TIMEOUT_MILLIS = (SilenceAfter.HARD_STOP + 5.minutes).inWholeMilliseconds fun start(context: Context) { context.startForegroundService(Intent(context, AlarmRingService::class.java)) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/data/backup/BackupCodec.kt b/app/src/main/java/de/jeanlucmakiola/clockula/data/backup/BackupCodec.kt index c6daf96..b6fc836 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/data/backup/BackupCodec.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/data/backup/BackupCodec.kt @@ -127,6 +127,8 @@ object BackupCodec { timerRingtoneUri = defaults.timerRingtoneUri, dismissChallenge = defaults.dismissChallenge.name, homeZoneId = defaults.homeZoneId, + alarmSilenceAfterMinutes = defaults.alarmSilenceAfterMinutes, + timerSilenceAfterMinutes = defaults.timerSilenceAfterMinutes, timerPresets = timerPresets.map { it.inWholeMilliseconds }, ) @@ -233,6 +235,9 @@ object BackupCodec { timerRingtoneUri = settingsDto.timerRingtoneUri?.takeIf { it.isNotBlank() }, dismissChallenge = settingsDto.dismissChallenge.toEnum(DismissChallenge.NONE), homeZoneId = settingsDto.homeZoneId?.let(Zones::normalise), + // Clamped on apply, by the preference, like every other default. + alarmSilenceAfterMinutes = settingsDto.alarmSilenceAfterMinutes, + timerSilenceAfterMinutes = settingsDto.timerSilenceAfterMinutes, ), timerPresets = settingsDto.timerPresets?.map { it.milliseconds } ?: TimerPresets.BUILT_IN, ) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/data/backup/BackupDto.kt b/app/src/main/java/de/jeanlucmakiola/clockula/data/backup/BackupDto.kt index 118e99e..a45d071 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/data/backup/BackupDto.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/data/backup/BackupDto.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.clockula.data.backup +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -71,6 +72,12 @@ data class SettingsDto( @SerialName("default_timer_ringtone_uri") val timerRingtoneUri: String? = null, @SerialName("default_dismiss_challenge") val dismissChallenge: String = "NONE", @SerialName("home_zone_id") val homeZoneId: String? = null, + /** + * Minutes, or 0 for "Never". Absent in a file from before the setting + * existed, which is v1's fixed ten minutes. + */ + @SerialName("default_alarm_silence_after_minutes") val alarmSilenceAfterMinutes: Int = SilenceAfter.DEFAULT_MINUTES, + @SerialName("default_timer_silence_after_minutes") val timerSilenceAfterMinutes: Int = SilenceAfter.DEFAULT_MINUTES, /** * Absent is not empty: an empty list is a user who removed every preset, * while a file without the field (an older or hand-written one) keeps the diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefs.kt b/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefs.kt index 0cb43c1..a14e002 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefs.kt @@ -3,6 +3,7 @@ package de.jeanlucmakiola.clockula.data.prefs import de.jeanlucmakiola.clockula.domain.ClockLimits import de.jeanlucmakiola.clockula.domain.DismissChallenge import de.jeanlucmakiola.clockula.domain.Zones +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.floret.prefs.Pref import de.jeanlucmakiola.floret.prefs.booleanPref import de.jeanlucmakiola.floret.prefs.enumPref @@ -31,6 +32,19 @@ object ClockPrefs { val dismissChallenge: Pref = enumPref("default_dismiss_challenge", DismissChallenge.NONE) + /** + * How long a ringing alarm, and a finished timer, keep going before they + * stop on their own (#17): minutes, or [SilenceAfter.NEVER]. An absent key + * reads as v1's fixed ten minutes, so an upgrade changes nothing. + */ + val alarmSilenceAfterMinutes: Pref = + intPref("default_alarm_silence_after_minutes", SilenceAfter.DEFAULT_MINUTES) + .clampedTo(ClockLimits.SILENCE_AFTER_MINUTES) + + val timerSilenceAfterMinutes: Pref = + intPref("default_timer_silence_after_minutes", SilenceAfter.DEFAULT_MINUTES) + .clampedTo(ClockLimits.SILENCE_AFTER_MINUTES) + /** Normalised through [Zones] both ways, so a zone the device dropped reads as absent. */ val homeZoneId: Pref = nullableStringPref("home_zone_id") .map(decode = Zones::normalise, encode = Zones::normalise) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefs.kt index b76785b..e342a1a 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefs.kt @@ -62,14 +62,20 @@ class SettingsPrefs @Inject constructor(private val store: PrefStore) { dismissChallenge = dismissChallenge, ) }, + combine( + store.flow(ClockPrefs.alarmSilenceAfterMinutes), + store.flow(ClockPrefs.timerSilenceAfterMinutes), + ) { alarmMinutes, timerMinutes -> alarmMinutes to timerMinutes }, store.flow(ClockPrefs.alarmRingtoneUri), store.flow(ClockPrefs.timerRingtoneUri), store.flow(ClockPrefs.homeZoneId), - ) { partial, alarmRingtoneUri, timerRingtoneUri, homeZoneId -> + ) { partial, silenceAfter, alarmRingtoneUri, timerRingtoneUri, homeZoneId -> partial.copy( alarmRingtoneUri = alarmRingtoneUri, timerRingtoneUri = timerRingtoneUri, homeZoneId = homeZoneId, + alarmSilenceAfterMinutes = silenceAfter.first, + timerSilenceAfterMinutes = silenceAfter.second, ) }.distinctUntilChanged() @@ -92,6 +98,8 @@ class SettingsPrefs @Inject constructor(private val store: PrefStore) { prefs[ClockPrefs.timerRingtoneUri] = backup.defaults.timerRingtoneUri prefs[ClockPrefs.dismissChallenge] = backup.defaults.dismissChallenge prefs[ClockPrefs.homeZoneId] = backup.defaults.homeZoneId + prefs[ClockPrefs.alarmSilenceAfterMinutes] = backup.defaults.alarmSilenceAfterMinutes + prefs[ClockPrefs.timerSilenceAfterMinutes] = backup.defaults.timerSilenceAfterMinutes prefs[TimerPrefs.presets] = backup.timerPresets } } @@ -111,6 +119,12 @@ class SettingsPrefs @Inject constructor(private val store: PrefStore) { suspend fun setDismissChallenge(challenge: DismissChallenge) = store.set(ClockPrefs.dismissChallenge, challenge) + suspend fun setAlarmSilenceAfterMinutes(minutes: Int) = + store.set(ClockPrefs.alarmSilenceAfterMinutes, minutes) + + suspend fun setTimerSilenceAfterMinutes(minutes: Int) = + store.set(ClockPrefs.timerSilenceAfterMinutes, minutes) + suspend fun setHomeZoneId(zoneId: String?) = store.set(ClockPrefs.homeZoneId, zoneId) // --- timer presets (M6) --- diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ClockDefaults.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ClockDefaults.kt index 73499b3..20b2dd2 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ClockDefaults.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ClockDefaults.kt @@ -1,8 +1,15 @@ package de.jeanlucmakiola.clockula.domain +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter +import kotlin.time.Duration + /** * The app-wide defaults an alarm or timer inherits when it has no override. * Backed by DataStore, edited in M10's settings screen. + * + * The two silence-after values are app-wide only: no alarm or timer overrides + * them (#17). They are stored as [SilenceAfter] minutes; read them as a window + * through [alarmSilenceAfter] and [timerSilenceAfter]. */ data class ClockDefaults( val snoozeMinutes: Int = 10, @@ -13,7 +20,15 @@ data class ClockDefaults( val timerRingtoneUri: String? = null, val dismissChallenge: DismissChallenge = DismissChallenge.NONE, val homeZoneId: String? = null, -) + val alarmSilenceAfterMinutes: Int = SilenceAfter.DEFAULT_MINUTES, + val timerSilenceAfterMinutes: Int = SilenceAfter.DEFAULT_MINUTES, +) { + /** How long a ringing alarm rings before it is silenced as missed. */ + val alarmSilenceAfter: Duration get() = SilenceAfter.window(alarmSilenceAfterMinutes) + + /** How long a finished timer sounds before the noise stops. */ + val timerSilenceAfter: Duration get() = SilenceAfter.window(timerSilenceAfterMinutes) +} /** * The ranges a user can choose from, for the defaults and for an alarm's own @@ -24,4 +39,5 @@ object ClockLimits { val SNOOZE_MINUTES: IntRange = 1..60 val SNOOZE_LIMIT: IntRange = 0..10 val VOLUME_RAMP_SECONDS: IntRange = 0..60 + val SILENCE_AFTER_MINUTES: IntRange = SilenceAfter.MINUTES } diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt index ba6d548..7109ba4 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt @@ -27,6 +27,10 @@ data class AlarmResolution( * * The precedence is fixed and total: disabled, then ringing, then snoozed, then * the natural occurrence. + * + * `autoSilenceAfter` is the "Silence after" setting's window + * (`ClockDefaults.alarmSilenceAfter`). It has no default, so no caller can + * measure a ring against a window the user did not choose. */ object AlarmResolver { fun resolve( @@ -34,7 +38,7 @@ object AlarmResolver { state: AlarmRingState, now: Instant, zone: ZoneId, - autoSilenceAfter: Duration = AlarmRing.AUTO_SILENCE_AFTER, + autoSilenceAfter: Duration, fireGrace: Duration = AlarmRing.FIRE_GRACE, ): AlarmResolution { // 1. Disabled: every volatile field goes, except the dismissal watermark diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt index 96103c0..061b57c 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt @@ -4,17 +4,13 @@ import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes /** - * The alarm ring cycle's constants. They are values rather than settings: v1 - * does not offer them to the user (docs/PLAN.md §4). The audio chain's own - * constants live in `domain/ring/RingAudio`, shared with the timer's ring. + * The alarm ring cycle's constants. They are values rather than settings + * (docs/PLAN.md §4). How long an alarm rings before it is silenced as missed + * became a setting in #17: `ClockDefaults.alarmSilenceAfter`. The audio + * chain's own constants live in `domain/ring/RingAudio`, shared with the + * timer's ring. */ object AlarmRing { - /** - * How long an undismissed alarm rings before it is silenced as missed. - * AOSP DeskClock's default, and the window a resumed ring is measured against. - */ - val AUTO_SILENCE_AFTER: Duration = 10.minutes - /** * How late a fire may arrive and still count. A fire delayed by doze, a slow * boot or a `TIME_SET` nudge still rings; one missed by hours does not. diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt new file mode 100644 index 0000000..5312037 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt @@ -0,0 +1,44 @@ +package de.jeanlucmakiola.clockula.domain.ring + +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes + +/** + * How long a ring keeps going before it stops on its own: the "Silence after" + * setting, one for alarms and one for timers (#17). Stored as whole minutes, + * with [NEVER] for the option that has no user-facing limit. + * + * "Never" is not unbounded. The auto-silence backstop is also what stops a + * phone left at home from ringing until its battery is flat, and what keeps a + * reboot from resuming a ring that started hours ago, so "Never" rings until + * [HARD_STOP] — longer than any finite choice — and then stops as any other + * window would. + */ +object SilenceAfter { + /** The stored value for "Never". Zero, because no window can be zero minutes long. */ + const val NEVER: Int = 0 + + /** + * Everything a stored value is clamped into, on read, on write and from a + * backup. Any value in it means something: [NEVER], or that many minutes. + */ + val MINUTES: IntRange = NEVER..60 + + /** + * The longest a ring ever lasts, and what "Never" means in practice. The + * settings hints say "an hour" in words; change them with it. + */ + val HARD_STOP: Duration = MINUTES.last.minutes + + /** The default, for alarms and timers alike: AOSP DeskClock's, and v1's fixed value. */ + const val DEFAULT_MINUTES: Int = 10 + + /** The choices the pickers offer, in order: Google Clock's, so nothing here surprises. */ + val CHOICES: List = listOf(1, 5, 10, 15, 20, 25, NEVER) + + /** The ring window [minutes] stands for, clamped first so the engines never see an unofferable value. */ + fun window(minutes: Int): Duration { + val clamped = minutes.coerceIn(MINUTES) + return if (clamped == NEVER) HARD_STOP else clamped.minutes + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRing.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRing.kt index 7d0d82e..b620acc 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRing.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRing.kt @@ -5,17 +5,13 @@ import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes /** - * The timer ring's constants. Values rather than settings: v1 does not offer - * them to the user (docs/PLAN.md §5, slice plan D11). + * The timer ring's constants. Values rather than settings (docs/PLAN.md §5, + * slice plan D11). How long an unacknowledged timer sounds before the noise + * stops became a setting in #17, `ClockDefaults.timerSilenceAfter`: its own + * rather than the alarm's, because coupling the two would make one number + * answer two questions. */ object TimerRing { - /** - * How long an unacknowledged timer sounds before the noise stops (D11). - * The same value as the alarm's and its own constant, free to diverge: - * coupling the two would make one number answer two questions. - */ - val AUTO_SILENCE_AFTER: Duration = 10.minutes - /** What "+1 min" grants (D12). */ val ADD_TIME: Duration = 1.minutes diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt index 663c03e..478747d 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt @@ -16,7 +16,7 @@ sealed interface TimerRingDecision { data class Sound( val subjectId: Long, val settings: TimerSettings, - /** When the window closes: the session anchor + [TimerRing.AUTO_SILENCE_AFTER]. */ + /** When the window closes: the session anchor + [ClockDefaults.timerSilenceAfter]. */ val silenceAt: Instant, ) : TimerRingDecision } @@ -49,7 +49,8 @@ object TimerRingPolicy { // Auto-silence before suppression: a window that has run out stays run // out, and an alarm ringing over it must not hand it a fresh one. - if (soundingSince != null && now - soundingSince >= TimerRing.AUTO_SILENCE_AFTER) { + val window = defaults.timerSilenceAfter + if (soundingSince != null && now - soundingSince >= window) { return TimerRingOutcome( TimerRingDecision.AutoSilenced(subject.timer.id), soundingSince = soundingSince, @@ -67,13 +68,13 @@ object TimerRingPolicy { // The anchor is the instant the audio *opened*, so a second timer // expiring mid-session inherits the window rather than buying a fresh - // ten minutes (D10). + // one (D10). val anchor = soundingSince ?: now return TimerRingOutcome( TimerRingDecision.Sound( subjectId = subject.timer.id, settings = subject.timer.resolveSettings(defaults), - silenceAt = anchor + TimerRing.AUTO_SILENCE_AFTER, + silenceAt = anchor + window, ), soundingSince = anchor, ) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/timer/TimerEngine.kt b/app/src/main/java/de/jeanlucmakiola/clockula/timer/TimerEngine.kt index 04b27cc..ea12615 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/timer/TimerEngine.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/timer/TimerEngine.kt @@ -266,7 +266,8 @@ class TimerEngine @Inject constructor( */ private suspend fun dropLapsedSessionLocked() { val anchor = ringState.current() ?: return - if (wall.now() - anchor >= TimerRing.AUTO_SILENCE_AFTER) ringState.set(null) + val window = settings.currentDefaults().timerSilenceAfter + if (wall.now() - anchor >= window) ringState.set(null) } private suspend fun serviceStateLocked(alreadyAlerted: Boolean): TimerServiceState { diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/timer/service/TimerService.kt b/app/src/main/java/de/jeanlucmakiola/clockula/timer/service/TimerService.kt index 5010fbf..0775b6a 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/timer/service/TimerService.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/timer/service/TimerService.kt @@ -14,6 +14,7 @@ import de.jeanlucmakiola.clockula.alarm.AlarmCapabilities import de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs import de.jeanlucmakiola.clockula.data.timers.TimerRepository import de.jeanlucmakiola.clockula.domain.ring.RingFallbackPolicy +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.clockula.domain.timer.TimerNotificationState import de.jeanlucmakiola.clockula.domain.timer.TimerMode import de.jeanlucmakiola.clockula.domain.timer.TimerRingDecision @@ -34,6 +35,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.merge import kotlinx.coroutines.launch +import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant import javax.inject.Inject @@ -363,8 +365,11 @@ class TimerService : Service() { companion object { private const val WAKE_LOCK_TAG = "clockula:timer-ring" - /** A backstop on the backstop: the ring window is ten minutes. */ - private const val WAKE_LOCK_TIMEOUT_MILLIS = 15L * 60L * 1_000L + /** + * A backstop on the backstop: past the longest ring window any "Silence + * after" choice allows, so a ring is never cut short by its own wake lock. + */ + private val WAKE_LOCK_TIMEOUT_MILLIS = (SilenceAfter.HARD_STOP + 5.minutes).inWholeMilliseconds fun start(context: Context) { context.startForegroundService(Intent(context, TimerService::class.java)) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt index 4ba9867..d93d58c 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt @@ -5,6 +5,7 @@ import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import de.jeanlucmakiola.clockula.R import de.jeanlucmakiola.clockula.domain.DismissChallenge +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.floret.components.OptionPicker /** @@ -67,6 +68,35 @@ internal fun challengeText(challenge: DismissChallenge): String = stringResource }, ) +/** [SilenceAfter.NEVER] is "Never" in words, never "0 minutes". */ +@Composable +internal fun silenceAfterText(minutes: Int): String = if (minutes == SilenceAfter.NEVER) { + stringResource(R.string.silence_after_never) +} else { + pluralStringResource(R.plurals.silence_after_minutes, minutes, minutes) +} + +/** + * "Silence after" is app-wide only (#17): no alarm or timer overrides it, so + * this picker never offers "App default". It shares the overrides' shape so + * the settings screens' pickers all look and behave alike. + */ +@Composable +internal fun SilenceAfterPicker( + selected: Int, + onSelect: (Int) -> Unit, + onDismiss: () -> Unit, +) = OverridePicker( + title = stringResource(R.string.settings_silence_after), + options = SilenceAfter.CHOICES, + stored = selected, + default = selected, + text = { silenceAfterText(it) }, + onSelect = { it?.let(onSelect) }, + onDismiss = onDismiss, + includeAppDefault = false, +) + @Composable internal fun VibratePicker( stored: Boolean?, diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/ring/TimerRingViewModel.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/ring/TimerRingViewModel.kt index a5fd38d..d87d70a 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/ring/TimerRingViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/ring/TimerRingViewModel.kt @@ -3,18 +3,19 @@ package de.jeanlucmakiola.clockula.ui.ring import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs import de.jeanlucmakiola.clockula.data.timers.TimerRepository import de.jeanlucmakiola.clockula.data.timers.TimerRingStateStore import de.jeanlucmakiola.clockula.domain.time.ElapsedRealtimeClock import de.jeanlucmakiola.clockula.domain.time.Ticker import de.jeanlucmakiola.clockula.domain.time.WallClock import de.jeanlucmakiola.clockula.domain.timer.TimerReadings -import de.jeanlucmakiola.clockula.domain.timer.TimerRing import de.jeanlucmakiola.clockula.timer.TimerEngine import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlin.time.Duration.Companion.seconds @@ -29,6 +30,7 @@ import javax.inject.Inject class TimerRingViewModel @Inject constructor( timers: TimerRepository, ringState: TimerRingStateStore, + settings: SettingsPrefs, private val engine: TimerEngine, elapsed: ElapsedRealtimeClock, wall: WallClock, @@ -41,7 +43,12 @@ class TimerRingViewModel @Inject constructor( * the auto-silence window ends without anything being written at all. */ val state: StateFlow = - combine(timers.timers(), ringState.soundingSince, ticker.ticks(TICK)) { rows, soundingSince, _ -> + combine( + timers.timers(), + ringState.soundingSince, + settings.defaults.map { it.timerSilenceAfter }.distinctUntilChanged(), + ticker.ticks(TICK), + ) { rows, soundingSince, silenceAfter, _ -> val now = wall.now() val expired = TimerReadings.expired( TimerReadings.active(rows, elapsed.elapsedRealtime(), now), @@ -49,7 +56,7 @@ class TimerRingViewModel @Inject constructor( val subject = expired.firstOrNull() // Auto-silence leaves the rows EXPIRED (D11) but ends the ring, and a // screen held on over a silent timer is only a battery drain. - val silenced = soundingSince != null && now - soundingSince >= TimerRing.AUTO_SILENCE_AFTER + val silenced = soundingSince != null && now - soundingSince >= silenceAfter if (subject == null || silenced) { TimerRingUiState.Finished } else { diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/AlarmDefaultsScreen.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/AlarmDefaultsScreen.kt index 4e4075d..4942a8e 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/AlarmDefaultsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/AlarmDefaultsScreen.kt @@ -12,11 +12,13 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.clockula.R import de.jeanlucmakiola.clockula.ui.alarms.DismissChallengePicker +import de.jeanlucmakiola.clockula.ui.alarms.SilenceAfterPicker import de.jeanlucmakiola.clockula.ui.alarms.SnoozeLengthPicker import de.jeanlucmakiola.clockula.ui.alarms.SnoozeLimitPicker import de.jeanlucmakiola.clockula.ui.alarms.VibratePicker import de.jeanlucmakiola.clockula.ui.alarms.VolumeRampPicker import de.jeanlucmakiola.clockula.ui.alarms.challengeText +import de.jeanlucmakiola.clockula.ui.alarms.silenceAfterText import de.jeanlucmakiola.clockula.ui.alarms.snoozeLimitText import de.jeanlucmakiola.clockula.ui.alarms.snoozeMinutesText import de.jeanlucmakiola.clockula.ui.alarms.vibrateText @@ -26,11 +28,12 @@ import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.Position /** Which of the alarm-default pickers is open. Mirrors [de.jeanlucmakiola.clockula.ui.alarms.AlarmEditorScreen]'s shape. */ -private enum class OpenAlarmPicker { VIBRATE, VOLUME_RAMP, SNOOZE_LENGTH, SNOOZE_LIMIT, CHALLENGE } +private enum class OpenAlarmPicker { VIBRATE, VOLUME_RAMP, SNOOZE_LENGTH, SNOOZE_LIMIT, CHALLENGE, SILENCE_AFTER } /** * What every new alarm starts with: how it sounds, how it snoozes, and how it - * is dismissed. The ringtone picker itself is ViewModel state, drawn by the hub. + * is dismissed; then how long any alarm rings, which no alarm overrides (#17). + * The ringtone picker itself is ViewModel state, drawn by the hub. */ @Composable internal fun AlarmDefaultsScreen( @@ -85,6 +88,17 @@ internal fun AlarmDefaultsScreen( position = Position.Alone, onClick = { openPicker = OpenAlarmPicker.CHALLENGE }, ) + + // Its own group with its own hint: unlike everything above, this one is + // not a default an alarm can change in its editor. + Spacer(Modifier.height(24.dp)) + GroupedRow( + title = stringResource(R.string.settings_silence_after), + summary = silenceAfterText(defaults.alarmSilenceAfterMinutes), + position = Position.Alone, + onClick = { openPicker = OpenAlarmPicker.SILENCE_AFTER }, + ) + SettingsHint(stringResource(R.string.settings_alarm_silence_after_hint)) } when (openPicker) { @@ -124,5 +138,10 @@ internal fun AlarmDefaultsScreen( onSelect = { viewModel.onDismissChallengeChanged(it ?: defaults.dismissChallenge) }, onDismiss = { openPicker = null }, ) + OpenAlarmPicker.SILENCE_AFTER -> SilenceAfterPicker( + selected = defaults.alarmSilenceAfterMinutes, + onSelect = { viewModel.onAlarmSilenceAfterChanged(it) }, + onDismiss = { openPicker = null }, + ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt index 7d90968..224d8b2 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt @@ -142,6 +142,12 @@ class SettingsViewModel @Inject internal constructor( fun onDismissChallengeChanged(value: DismissChallenge) = viewModelScope.launch { settings.setDismissChallenge(value) } + fun onAlarmSilenceAfterChanged(minutes: Int) = + viewModelScope.launch { settings.setAlarmSilenceAfterMinutes(minutes) } + + fun onTimerSilenceAfterChanged(minutes: Int) = + viewModelScope.launch { settings.setTimerSilenceAfterMinutes(minutes) } + // --- the default ringtone pickers --- internal fun onOpenRingtonePicker(kind: DefaultRingtoneKind) { diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/TimerDefaultsScreen.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/TimerDefaultsScreen.kt index cc68b9a..90ffbb2 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/TimerDefaultsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/TimerDefaultsScreen.kt @@ -3,21 +3,29 @@ package de.jeanlucmakiola.clockula.ui.settings import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.clockula.R +import de.jeanlucmakiola.clockula.ui.alarms.SilenceAfterPicker +import de.jeanlucmakiola.clockula.ui.alarms.silenceAfterText import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.Position -/** What a new timer starts with: its sound. */ +/** What a new timer starts with, its sound; then how long any timer sounds (#17). */ @Composable internal fun TimerDefaultsScreen( state: SettingsUiState.Loaded, viewModel: SettingsViewModel, onBack: () -> Unit, ) { + var silenceAfterOpen by rememberSaveable { mutableStateOf(false) } + CollapsingScaffold(title = stringResource(R.string.settings_section_timers), onBack = onBack) { SettingsHint(stringResource(R.string.settings_timer_sound_hint)) Spacer(Modifier.height(8.dp)) @@ -28,5 +36,22 @@ internal fun TimerDefaultsScreen( position = Position.Alone, onClick = { viewModel.onOpenRingtonePicker(DefaultRingtoneKind.TIMER) }, ) + + Spacer(Modifier.height(24.dp)) + GroupedRow( + title = stringResource(R.string.settings_silence_after), + summary = silenceAfterText(state.defaults.timerSilenceAfterMinutes), + position = Position.Alone, + onClick = { silenceAfterOpen = true }, + ) + SettingsHint(stringResource(R.string.settings_timer_silence_after_hint)) + } + + if (silenceAfterOpen) { + SilenceAfterPicker( + selected = state.defaults.timerSilenceAfterMinutes, + onSelect = { viewModel.onTimerSilenceAfterChanged(it) }, + onDismiss = { silenceAfterOpen = false }, + ) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ad0a66c..66cac00 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -164,6 +164,16 @@ Solve a sum Press and hold + + Silence after + Never + + %1$d minute + %1$d minutes + + Applies to every alarm. An alarm nobody stops goes quiet after this long and counts as missed. Never still stops after an hour, so a phone left at home can\'t ring until its battery runs out. + Applies to every timer. A finished timer nobody stops goes quiet after this long but stays finished, so you can still add a minute. Never still stops after an hour. + Alarm sound Silent diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineInteropTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineInteropTest.kt index 9a5a2ab..2687d74 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineInteropTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineInteropTest.kt @@ -2,8 +2,8 @@ package de.jeanlucmakiola.clockula.alarm import app.cash.turbine.test import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.clockula.domain.ClockDefaults import de.jeanlucmakiola.clockula.domain.RepeatDays -import de.jeanlucmakiola.clockula.domain.alarm.AlarmRing import de.jeanlucmakiola.clockula.domain.alarm.DismissOutcome import de.jeanlucmakiola.clockula.domain.alarm.SnoozeOutcome import de.jeanlucmakiola.clockula.testing.BERLIN @@ -246,7 +246,7 @@ class AlarmEngineInteropTest { harness.givenAlarm(id = 1L, hour = 7, deleteAfterUse = true) harness.engine.reschedule() harness.givenRinging(alarmId = 1L, at = sevenToday) - harness.wallClock.instant = sevenToday + AlarmRing.AUTO_SILENCE_AFTER + harness.wallClock.instant = sevenToday + ClockDefaults().alarmSilenceAfter harness.engine.onAutoSilence(1L) diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt index 0a0c53c..bb87cb9 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt @@ -10,15 +10,16 @@ import de.jeanlucmakiola.clockula.data.alarms.AlarmStateRepositoryImpl import de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs import de.jeanlucmakiola.clockula.domain.Alarm import de.jeanlucmakiola.clockula.domain.AlarmDraft +import de.jeanlucmakiola.clockula.domain.ClockDefaults import de.jeanlucmakiola.clockula.domain.RepeatDays import de.jeanlucmakiola.clockula.domain.TimeOfDay -import de.jeanlucmakiola.clockula.domain.alarm.AlarmRing import de.jeanlucmakiola.clockula.domain.alarm.AlarmRingState import de.jeanlucmakiola.clockula.domain.alarm.FireOutcome import de.jeanlucmakiola.clockula.domain.alarm.FireSource import de.jeanlucmakiola.clockula.domain.alarm.ScheduleMode import de.jeanlucmakiola.clockula.domain.alarm.SnoozeOutcome import de.jeanlucmakiola.clockula.domain.resolveSettings +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.clockula.testing.BERLIN import de.jeanlucmakiola.clockula.testing.FakeAlarmDao import de.jeanlucmakiola.clockula.testing.FakeAlarmNotifier @@ -274,7 +275,7 @@ class AlarmEngineTest { assertThat(states.state(1L).ringingSince).isEqualTo(sevenToday) assertThat(states.state(1L).handledOccurrence).isEqualTo(sevenToday) assertThat(scheduler.autoSilence) - .isEqualTo(Registration(sevenToday + AlarmRing.AUTO_SILENCE_AFTER, 1L)) + .isEqualTo(Registration(sevenToday + ClockDefaults().alarmSilenceAfter, 1L)) } @Test @@ -680,7 +681,7 @@ class AlarmEngineTest { assertThat(ring.ringing.value).isEqualTo(1L) assertThat(scheduler.autoSilence) - .isEqualTo(Registration(sevenToday + AlarmRing.AUTO_SILENCE_AFTER, 1L)) + .isEqualTo(Registration(sevenToday + ClockDefaults().alarmSilenceAfter, 1L)) } @Test @@ -692,7 +693,8 @@ class AlarmEngineTest { engine.onBootCompleted() - assertThat(ring.events).isEmpty() + // Closing the stale ring stops whatever might still sound; nothing starts. + assertThat(ring.events).containsExactly(RingEvent.Stopped(1L)) assertThat(states.state(1L).ringingSince).isNull() assertThat(scheduler.next?.fireAt).isEqualTo(sevenTomorrow) } @@ -798,6 +800,117 @@ class AlarmEngineTest { assertThat(scheduler.next).isEqualTo(Registration(sevenToday, 1L)) } + // --- #17: the ring window is the "Silence after" setting --- + + @Test + fun `the backstop is armed at the chosen silence-after, not ten minutes`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val settings = settings(dir) + settings.setAlarmSilenceAfterMinutes(25) + val engine = engineOver(settings) + + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + + assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + 25.minutes, 1L)) + } + + @Test + fun `Never arms the backstop at the hard stop`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val settings = settings(dir) + settings.setAlarmSilenceAfterMinutes(SilenceAfter.NEVER) + val engine = engineOver(settings) + + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + + assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + SilenceAfter.HARD_STOP, 1L)) + } + + @Test + fun `a reschedule inside a longer window keeps the ring going`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val settings = settings(dir) + settings.setAlarmSilenceAfterMinutes(25) + val engine = engineOver(settings) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday + 20.minutes + + engine.reschedule() + + assertThat(ring.ringing.value).isEqualTo(1L) + assertThat(states.state(1L).ringingSince).isEqualTo(sevenToday) + assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + 25.minutes, 1L)) + } + + @Test + fun `shortening silence-after mid-ring stops a ring already past the new window`(@TempDir dir: Path) = + runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val settings = settings(dir) + val engine = engineOver(settings) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday + 5.minutes + + settings.setAlarmSilenceAfterMinutes(1) + engine.reschedule() + + assertThat(ring.ringing.value).isNull() + assertThat(ring.events.last()).isEqualTo(RingEvent.Stopped(1L)) + assertThat(states.state(1L).ringingSince).isNull() + assertThat(scheduler.autoSilence).isNull() + assertThat(scheduler.next?.fireAt).isEqualTo(sevenTomorrow) + } + + @Test + fun `a ring interrupted by a reboot resumes inside a longer window`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + 20.minutes + givenRingingAt(alarmId = 1L, occurrence = sevenToday, since = sevenToday) + val settings = settings(dir) + settings.setAlarmSilenceAfterMinutes(25) + val engine = engineOver(settings) + + engine.onBootCompleted() + + assertThat(ring.ringing.value).isEqualTo(1L) + assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + 25.minutes, 1L)) + } + + @Test + fun `a late snooze is kept for as long as the chosen window`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + val snoozeAt = sevenToday + 9.minutes + states.save( + ringState(snoozedUntil = snoozeAt, snoozeCount = 1, handledOccurrence = sevenToday), + ) + wallClock.instant = snoozeAt + 20.minutes + val settings = settings(dir) + settings.setAlarmSilenceAfterMinutes(25) + val engine = engineOver(settings) + + val outcome = engine.onFire(alarmId = 1L, scheduledFor = snoozeAt) + + assertThat(outcome).isEqualTo(FireOutcome.Ringing(1L)) + } + + @Test + fun `upcoming measures a ring against the chosen window`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + 20.minutes + givenRingingAt(alarmId = 1L, occurrence = sevenToday, since = sevenToday) + val settings = settings(dir) + settings.setAlarmSilenceAfterMinutes(25) + val engine = engineOver(settings) + + val entry = engine.upcoming().first().single() + + assertThat(entry.source).isEqualTo(FireSource.RESUMED_RING) + } + // --- upcoming() --- @Test @@ -886,7 +999,7 @@ class AlarmEngineTest { assertThat(ring.ringing.value).isEqualTo(2L) assertThat(states.state(2L).ringingSince).isEqualTo(eightToday) assertThat(scheduler.autoSilence) - .isEqualTo(Registration(eightToday + AlarmRing.AUTO_SILENCE_AFTER, 2L)) + .isEqualTo(Registration(eightToday + ClockDefaults().alarmSilenceAfter, 2L)) assertThat(states.state(1L).snoozedUntil).isNull() assertThat(notifier.cleared).contains(1L) } diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/data/backup/BackupCodecTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/data/backup/BackupCodecTest.kt index db57734..9b39d5d 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/data/backup/BackupCodecTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/data/backup/BackupCodecTest.kt @@ -10,6 +10,7 @@ import de.jeanlucmakiola.clockula.domain.backup.BackupContent import de.jeanlucmakiola.clockula.domain.backup.BackupSettings import de.jeanlucmakiola.clockula.domain.backup.BackupTimer import de.jeanlucmakiola.clockula.domain.backup.BackupWorldClock +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.clockula.domain.timer.TimerPresets import de.jeanlucmakiola.floret.prefs.ThemeMode import org.junit.jupiter.api.Test @@ -60,6 +61,8 @@ class BackupCodecTest { timerRingtoneUri = "content://media/2", dismissChallenge = DismissChallenge.HOLD, homeZoneId = "America/New_York", + alarmSilenceAfterMinutes = 25, + timerSilenceAfterMinutes = SilenceAfter.NEVER, ), timerPresets = listOf(1.minutes, 2.minutes, 10.minutes), ), @@ -263,6 +266,20 @@ class BackupCodecTest { assertThat(settings.timerPresets).isEqualTo(TimerPresets.BUILT_IN) } + @Test + fun `a file from before silence after keeps the ten minutes it was made with`() { + val defaults = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings.defaults + assertThat(defaults.alarmSilenceAfterMinutes).isEqualTo(10) + assertThat(defaults.timerSilenceAfterMinutes).isEqualTo(10) + } + + @Test + fun `silence after is written under its documented keys`() { + val json = BackupCodec.encode(sampleContent()) + assertThat(json).contains("\"default_alarm_silence_after_minutes\": 25") + assertThat(json).contains("\"default_timer_silence_after_minutes\": 0") + } + @Test fun `an empty preset list is honoured as all removed`() { val json = minimalDocument().replace("\"settings\": {}", "\"settings\": {\"timer_presets\": []}") diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt index 869cca3..bdfe100 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt @@ -9,6 +9,7 @@ import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.clockula.domain.ClockDefaults import de.jeanlucmakiola.clockula.domain.DismissChallenge +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.floret.prefs.PrefStore import de.jeanlucmakiola.floret.prefs.ThemeMode import kotlinx.coroutines.CoroutineScope @@ -53,6 +54,8 @@ class ClockPrefsTest { prefs.setTimerRingtoneUri("content://t") prefs.setDismissChallenge(DismissChallenge.HOLD) prefs.setHomeZoneId("Europe/Berlin") + prefs.setAlarmSilenceAfterMinutes(25) + prefs.setTimerSilenceAfterMinutes(SilenceAfter.NEVER) assertThat(prefs.defaults.first()).isEqualTo( ClockDefaults( @@ -64,6 +67,8 @@ class ClockPrefsTest { timerRingtoneUri = "content://t", dismissChallenge = DismissChallenge.HOLD, homeZoneId = "Europe/Berlin", + alarmSilenceAfterMinutes = 25, + timerSilenceAfterMinutes = SilenceAfter.NEVER, ), ) } @@ -148,4 +153,21 @@ class ClockPrefsTest { cancel() } } + + @Test + fun `silence after clamps on write and on read`(@TempDir tempDir: Path) = runTest { + val dataStore = newDataStore(tempDir) + val prefs = SettingsPrefs(PrefStore(dataStore)) + + prefs.setAlarmSilenceAfterMinutes(999) + prefs.setTimerSilenceAfterMinutes(-3) + assertThat(prefs.defaults.first().alarmSilenceAfterMinutes).isEqualTo(60) + assertThat(prefs.defaults.first().timerSilenceAfterMinutes).isEqualTo(SilenceAfter.NEVER) + + dataStore.updateData { stored -> + stored.toMutablePreferences() + .apply { this[intPreferencesKey("default_alarm_silence_after_minutes")] = 5_000 } + } + assertThat(prefs.defaults.first().alarmSilenceAfter).isEqualTo(SilenceAfter.HARD_STOP) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefsTest.kt index 71ead3e..2abb2d3 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefsTest.kt @@ -74,7 +74,13 @@ class SettingsPrefsTest { BackupSettings( themeMode = ThemeMode.DARK, dynamicColor = false, - defaults = ClockDefaults(snoozeMinutes = 99, volumeRampSeconds = 99, alarmRingtoneUri = " "), + defaults = ClockDefaults( + snoozeMinutes = 99, + volumeRampSeconds = 99, + alarmRingtoneUri = " ", + alarmSilenceAfterMinutes = 25, + timerSilenceAfterMinutes = 999, + ), timerPresets = listOf(5.minutes, 1.minutes, 5.minutes), ), ) @@ -84,6 +90,8 @@ class SettingsPrefsTest { assertThat(prefs.currentDefaults().snoozeMinutes).isEqualTo(60) assertThat(prefs.currentDefaults().volumeRampSeconds).isEqualTo(60) assertThat(prefs.currentDefaults().alarmRingtoneUri).isNull() + assertThat(prefs.currentDefaults().alarmSilenceAfterMinutes).isEqualTo(25) + assertThat(prefs.currentDefaults().timerSilenceAfterMinutes).isEqualTo(60) assertThat(prefs.timerPresets.first()).containsExactly(1.minutes, 5.minutes).inOrder() } diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolverTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolverTest.kt index 960cb2a..e963c99 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolverTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolverTest.kt @@ -2,7 +2,9 @@ package de.jeanlucmakiola.clockula.domain.alarm import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.clockula.domain.Alarm +import de.jeanlucmakiola.clockula.domain.ClockDefaults import de.jeanlucmakiola.clockula.domain.RepeatDays +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.clockula.testing.BERLIN import de.jeanlucmakiola.clockula.testing.alarmAt import de.jeanlucmakiola.clockula.testing.instantAt @@ -28,8 +30,9 @@ class AlarmResolverTest { state: AlarmRingState = ringState(alarmId = alarm.id), now: Instant = morning, fireGrace: Duration = AlarmRing.FIRE_GRACE, + silenceAfter: Duration = ClockDefaults().alarmSilenceAfter, ): AlarmResolution = - AlarmResolver.resolve(alarm, state, now, BERLIN, AlarmRing.AUTO_SILENCE_AFTER, fireGrace) + AlarmResolver.resolve(alarm, state, now, BERLIN, silenceAfter, fireGrace) // --- T32–T34: the disabled and plain cases --- @@ -158,7 +161,7 @@ class AlarmResolverTest { @Test fun `a ring exactly as old as the auto-silence window has timed out`() { val alarm = alarmAt(hour = 7, repeatDays = RepeatDays.EVERY_DAY) - val state = ringState(ringingSince = morning - AlarmRing.AUTO_SILENCE_AFTER) + val state = ringState(ringingSince = morning - ClockDefaults().alarmSilenceAfter) val resolution = resolve(alarm, state) @@ -357,4 +360,53 @@ class AlarmResolverTest { assertThat(resolve(alarm, state)).isEqualTo(first) assertThat(state).isEqualTo(copy) } + + // --- #17: the window is the "Silence after" setting --- + + @Test + fun `a longer window keeps a ring going past the default's ten minutes`() { + val alarm = alarmAt(hour = 7, repeatDays = RepeatDays.EVERY_DAY) + val state = ringState(ringingSince = morning - 20.minutes) + + val resolution = resolve(alarm, state, silenceAfter = SilenceAfter.window(25)) + + assertThat(resolution.source).isEqualTo(FireSource.RESUMED_RING) + assertThat(resolution.state).isEqualTo(state) + } + + @Test + fun `a shorter window closes a ring the default would still keep`() { + val alarm = alarmAt(hour = 7, repeatDays = RepeatDays.EVERY_DAY) + val state = ringState(ringingSince = morning - 2.minutes) + + val resolution = resolve(alarm, state, silenceAfter = SilenceAfter.window(1)) + + assertThat(resolution.source).isEqualTo(FireSource.OCCURRENCE) + assertThat(resolution.state.ringingSince).isNull() + } + + @Test + fun `Never still closes a ring at the hard stop`() { + val alarm = alarmAt(hour = 7, repeatDays = RepeatDays.EVERY_DAY) + val never = SilenceAfter.window(SilenceAfter.NEVER) + + val ringing = resolve(alarm, ringState(ringingSince = morning - 59.minutes), silenceAfter = never) + val stopped = resolve(alarm, ringState(ringingSince = morning - 1.hours), silenceAfter = never) + + assertThat(ringing.source).isEqualTo(FireSource.RESUMED_RING) + assertThat(stopped.state.ringingSince).isNull() + } + + @Test + fun `a late snooze is kept for as long as the window the user chose`() { + val alarm = alarmAt(hour = 7, repeatDays = RepeatDays.EVERY_DAY) + val snoozedUntil = morning - 20.minutes + val state = ringState(snoozedUntil = snoozedUntil, snoozeCount = 1) + + val kept = resolve(alarm, state, silenceAfter = SilenceAfter.window(25)) + val dropped = resolve(alarm, state, silenceAfter = SilenceAfter.window(15)) + + assertThat(kept.nextFire to kept.source).isEqualTo(snoozedUntil to FireSource.SNOOZE) + assertThat(dropped.state.snoozedUntil).isNull() + } } diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfterTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfterTest.kt new file mode 100644 index 0000000..e977bbb --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfterTest.kt @@ -0,0 +1,50 @@ +package de.jeanlucmakiola.clockula.domain.ring + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.clockula.domain.ClockDefaults +import org.junit.jupiter.api.Test +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes + +/** #17: what a stored "Silence after" value means to the two engines. */ +class SilenceAfterTest { + + @Test + fun `the default is v1's fixed ten minutes, for alarms and timers alike`() { + val defaults = ClockDefaults() + + assertThat(defaults.alarmSilenceAfter).isEqualTo(10.minutes) + assertThat(defaults.timerSilenceAfter).isEqualTo(10.minutes) + } + + @Test + fun `a stored value is that many minutes`() { + assertThat(SilenceAfter.window(1)).isEqualTo(1.minutes) + assertThat(SilenceAfter.window(25)).isEqualTo(25.minutes) + } + + @Test + fun `Never is the hard stop, an hour`() { + assertThat(SilenceAfter.window(SilenceAfter.NEVER)).isEqualTo(SilenceAfter.HARD_STOP) + assertThat(SilenceAfter.HARD_STOP).isEqualTo(1.hours) + } + + @Test + fun `no value reaches the engines as a window longer than the hard stop`() { + assertThat(SilenceAfter.window(24 * 60)).isEqualTo(SilenceAfter.HARD_STOP) + // Negative is clamped to Never rather than read as an instant silence. + assertThat(SilenceAfter.window(-5)).isEqualTo(SilenceAfter.HARD_STOP) + } + + @Test + fun `every choice is in range, and the hard stop outlasts every finite one`() { + assertThat(SilenceAfter.CHOICES).contains(SilenceAfter.DEFAULT_MINUTES) + assertThat(SilenceAfter.CHOICES).contains(SilenceAfter.NEVER) + SilenceAfter.CHOICES.forEach { minutes -> + assertThat(minutes).isIn(SilenceAfter.MINUTES) + assertThat(SilenceAfter.window(minutes)).isAtMost(SilenceAfter.HARD_STOP) + } + assertThat(SilenceAfter.CHOICES.filter { it != SilenceAfter.NEVER }.max().minutes) + .isLessThan(SilenceAfter.HARD_STOP) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicyTest.kt index d95ecc1..70f4c8f 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicyTest.kt @@ -3,6 +3,7 @@ package de.jeanlucmakiola.clockula.domain.timer import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.clockula.domain.ClockDefaults import de.jeanlucmakiola.clockula.domain.Ringtones +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.clockula.testing.T0 import de.jeanlucmakiola.clockula.testing.expiredTimer import org.junit.jupiter.api.Test @@ -154,7 +155,7 @@ class TimerRingPolicyTest { TimerRingDecision.Sound( subjectId = 7L, settings = released.sound().settings, - silenceAt = now + TimerRing.AUTO_SILENCE_AFTER, + silenceAt = now + ClockDefaults().timerSilenceAfter, ), soundingSince = now, ), @@ -174,7 +175,7 @@ class TimerRingPolicyTest { /** §5.4 #14 */ @Test fun `a session that has run its window auto-silences`() { - val opened = now - TimerRing.AUTO_SILENCE_AFTER + val opened = now - ClockDefaults().timerSilenceAfter val outcome = decide(soundingSince = opened) @@ -185,7 +186,7 @@ class TimerRingPolicyTest { /** §5.4 #15 */ @Test fun `auto-silence is decided before suppression`() { - val opened = now - TimerRing.AUTO_SILENCE_AFTER + val opened = now - ClockDefaults().timerSilenceAfter val outcome = decide(alarmIsRinging = true, soundingSince = opened) @@ -195,7 +196,7 @@ class TimerRingPolicyTest { /** §5.4 #16 */ @Test fun `an auto-silenced session does not restart a minute later`() { - val opened = now - TimerRing.AUTO_SILENCE_AFTER + val opened = now - ClockDefaults().timerSilenceAfter val outcome = decide(soundingSince = opened, at = now + 1.minutes) @@ -207,7 +208,7 @@ class TimerRingPolicyTest { @Test fun `resetting the last expired timer closes an auto-silenced session`() { val outcome = - decide(expired = emptyList(), soundingSince = now - TimerRing.AUTO_SILENCE_AFTER) + decide(expired = emptyList(), soundingSince = now - ClockDefaults().timerSilenceAfter) assertThat(outcome).isEqualTo(TimerRingOutcome(TimerRingDecision.Silent, soundingSince = null)) } @@ -227,7 +228,7 @@ class TimerRingPolicyTest { fun `the window closes ten minutes after the audio opened`() { val outcome = decide() - assertThat(outcome.sound().silenceAt).isEqualTo(now + TimerRing.AUTO_SILENCE_AFTER) + assertThat(outcome.sound().silenceAt).isEqualTo(now + ClockDefaults().timerSilenceAfter) } /** §5.4 #20 */ @@ -242,4 +243,35 @@ class TimerRingPolicyTest { assertThat(outcome.sound().subjectId).isEqualTo(9L) } + + // --- #17: the window is the timer's own "Silence after" setting --- + + @Test + fun `the window is the timer setting, not the alarm's`() { + val custom = defaults.copy(timerSilenceAfterMinutes = 25, alarmSilenceAfterMinutes = 1) + + val outcome = decide(defaults = custom) + + assertThat(outcome.sound().silenceAt).isEqualTo(now + 25.minutes) + } + + @Test + fun `a shorter window auto-silences a session the default would keep`() { + val custom = defaults.copy(timerSilenceAfterMinutes = 1) + + val outcome = decide(defaults = custom, soundingSince = now - 1.minutes) + + assertThat(outcome.decision).isEqualTo(TimerRingDecision.AutoSilenced(7L)) + } + + @Test + fun `Never sounds up to the hard stop and no further`() { + val never = defaults.copy(timerSilenceAfterMinutes = SilenceAfter.NEVER) + + val sounding = decide(defaults = never, soundingSince = now - 59.minutes) + val silenced = decide(defaults = never, soundingSince = now - SilenceAfter.HARD_STOP) + + assertThat(sounding.sound().silenceAt).isEqualTo(now - 59.minutes + SilenceAfter.HARD_STOP) + assertThat(silenced.decision).isEqualTo(TimerRingDecision.AutoSilenced(7L)) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/timer/TimerEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/timer/TimerEngineTest.kt index 10df056..6f248c5 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/timer/TimerEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/timer/TimerEngineTest.kt @@ -1,10 +1,10 @@ package de.jeanlucmakiola.clockula.timer import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.clockula.domain.ClockDefaults import de.jeanlucmakiola.clockula.domain.TimerState import de.jeanlucmakiola.clockula.domain.time.BootId import de.jeanlucmakiola.clockula.domain.timer.TimerNotificationAction -import de.jeanlucmakiola.clockula.domain.timer.TimerRing import de.jeanlucmakiola.clockula.domain.timer.TimerRingDecision import de.jeanlucmakiola.clockula.testing.T0 import de.jeanlucmakiola.clockula.testing.TimerEngineHarness @@ -497,7 +497,22 @@ class TimerEngineTest { val state = harness.engine.serviceState(alreadyAlerted = false) - assertThat(state.silenceIn).isEqualTo(TimerRing.AUTO_SILENCE_AFTER - 30.seconds) + assertThat(state.silenceIn).isEqualTo(ClockDefaults().timerSilenceAfter - 30.seconds) + } + + /** #17 */ + @Test + fun `the ring session's window is the timer's silence-after setting`( + @TempDir tempDir: Path, + ) = runTest { + val harness = timerEngineHarness(tempDir) + harness.settings.setTimerSilenceAfterMinutes(25) + harness.given(expiredTimer(id = 1L)) + harness.ringState.set(T0 - 30.seconds) + + val state = harness.engine.serviceState(alreadyAlerted = false) + + assertThat(state.silenceIn).isEqualTo(25.minutes - 30.seconds) } /** §5.8 #31 */ @@ -688,7 +703,7 @@ class TimerEngineTest { harness.engine.onExpiryDue() // The first timer sounds, and is then left alone until the window lapses. harness.engine.serviceState(alreadyAlerted = false) - harness.advance(TimerRing.AUTO_SILENCE_AFTER) + harness.advance(ClockDefaults().timerSilenceAfter) val lapsed = harness.engine.serviceState(alreadyAlerted = true) harness.engine.start(2L) @@ -699,7 +714,7 @@ class TimerEngineTest { assertThat(lapsed.ring).isInstanceOf(TimerRingDecision.AutoSilenced::class.java) assertThat(second.ring).isInstanceOf(TimerRingDecision.Sound::class.java) assertThat((second.ring as TimerRingDecision.Sound).silenceAt) - .isEqualTo(harness.wallClock.instant + TimerRing.AUTO_SILENCE_AFTER) + .isEqualTo(harness.wallClock.instant + ClockDefaults().timerSilenceAfter) } /** §5.8 #42 — added with the review fix for finding 2. */ diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/ui/ring/TimerRingViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/ui/ring/TimerRingViewModelTest.kt index 93a42ed..f86301b 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/ui/ring/TimerRingViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/ui/ring/TimerRingViewModelTest.kt @@ -1,8 +1,8 @@ package de.jeanlucmakiola.clockula.ui.ring import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.clockula.domain.ClockDefaults import de.jeanlucmakiola.clockula.domain.TimerState -import de.jeanlucmakiola.clockula.domain.timer.TimerRing import de.jeanlucmakiola.clockula.testing.MainDispatcherExtension import de.jeanlucmakiola.clockula.testing.T0 import de.jeanlucmakiola.clockula.testing.TimerEngineHarness @@ -35,6 +35,7 @@ class TimerRingViewModelTest { private fun TestScope.viewModel(harness: TimerEngineHarness) = TimerRingViewModel( timers = harness.timers, ringState = harness.ringState, + settings = harness.settings, engine = harness.engine, elapsed = harness.elapsed, wall = harness.wallClock, @@ -124,11 +125,29 @@ class TimerRingViewModelTest { advanceUntilIdle() assertThat(viewModel.state.value).isInstanceOf(TimerRingUiState.Ringing::class.java) - harness.wallClock.advance(TimerRing.AUTO_SILENCE_AFTER + 1.seconds) + harness.wallClock.advance(ClockDefaults().timerSilenceAfter + 1.seconds) harness.ticker.tick() advanceUntilIdle() assertThat(harness.stored(1L)!!.state).isEqualTo(TimerState.EXPIRED) assertThat(viewModel.state.value).isEqualTo(TimerRingUiState.Finished) } + + @Test + fun `the screen follows the timer's own silence-after setting`(@TempDir tempDir: Path) = + runTest(main.dispatcher) { + val harness = timerEngineHarness(tempDir) + harness.settings.setTimerSilenceAfterMinutes(1) + harness.given(expiredTimer(id = 1L)) + harness.ringState.set(T0) + val viewModel = viewModel(harness) + advanceUntilIdle() + assertThat(viewModel.state.value).isInstanceOf(TimerRingUiState.Ringing::class.java) + + harness.wallClock.advance(1.minutes + 1.seconds) + harness.ticker.tick() + advanceUntilIdle() + + assertThat(viewModel.state.value).isEqualTo(TimerRingUiState.Finished) + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 97ef4e8..31868fc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1050,14 +1050,14 @@ M10 adds no ``. | Not here | Milestone | |---|---| | Reordering alarms by hand. The list is ordered by time of day (§13) and `alarms` has no `sort_order` column, so this would be a schema change for a preference the time order already answers | not planned for v1 | -| A per-alarm auto-silence duration. Every other per-alarm setting became an override picker in M5; this one is still global and still `AlarmRing.AUTO_SILENCE_AFTER` | not planned for v1 | +| A per-alarm auto-silence duration. Every other per-alarm setting became an override picker in M5; "Silence after" (#17) is an app-wide setting only, because an override would need a new `alarms` column, a migration and an editor row for a value almost nobody sets per alarm | not planned | | Voice-interaction follow-on flows: `Activity.isVoiceInteraction`, `VoiceInteractor.CompleteVoiceRequest` (publishing a deeplink to the alarm just created) and `PickOptionRequest` (disambiguating by voice). `android.intent.category.VOICE` is therefore not declared: advertising it while answering with a touch dialog would be a promise the app does not keep. Clockula *accepts* a `clockula://` deeplink and publishes none | not planned for v1 | | A "most closely matched" time search for `DISMISS_ALARM`. `ALARM_SEARCH_MODE_TIME` matches **exactly**: dismissing an alarm the caller did not name is a missed alarm, and there is no distance at which that becomes a good trade | not planned for v1 | | A toast or any other confirmation on a `SKIP_UI` write. `SKIP_UI` means "bypass any intermediate UI", a voice assistant speaks its own confirmation, and the status-bar alarm icon `setAlarmClock` lights is the platform's own receipt (§17) | not planned for v1 | | Surfacing `delete_after_use` in either editor. It is a property the contract sets, not a setting; an alarm the user edits keeps it, and that consequence is documented (§17) rather than papered over with a checkbox | not planned for v1 | | Carrying `EXTRA_MESSAGE` into the timer setup panel when no length was given. There is no row to carry it on and the panel has no label field | not planned for v1 | | Verifying a ringtone URI at the intent boundary. M5 locked "an unreadable sound is reported, never rewritten"; an unmounted card comes back, and the boundary opens no `ContentResolver` | not planned for v1 | -| A user-configurable auto-silence duration, an unlimited-snooze option, per-alarm auto-silence | not planned for v1 | +| An unlimited-snooze option, per-alarm auto-silence | not planned for v1 | | Reordering timers by hand. `sort_order` and `TimerRepository.reorder` exist and stay caller-less: the list is in storage order, M5 gave the same answer for alarms, and a drag surface would also mean abandoning the `LazyColumn` | not planned for v1 | | Per-timer vibrate, volume-ramp or dismiss-challenge overrides. `timers` has exactly one nullable settings column, its ringtone; four more would be a schema change for settings the roadmap does not ask for | not planned for v1 | | A "stop all" for several expired timers, and undo after a timer delete. Each expired timer is acknowledged on its own, and the delete confirmation asks before rather than after | not planned for v1 | @@ -1142,7 +1142,7 @@ repair, resume and reschedule one by one, so its whole pass is inside the lock. 1. **Disabled** ⇒ clear the snooze, the ring and the skip watermark; keep `handled_occurrence`, because re-enabling must not un-suppress a dismissal. -2. **Ringing** within `AUTO_SILENCE_AFTER` ⇒ `RESUMED_RING`, nothing scheduled: +2. **Ringing** within the "Silence after" window ⇒ `RESUMED_RING`, nothing scheduled: it is not an alarm to come, it is one that is happening. A clock moved *backwards* under a ringing alarm reads as a negative age, which is inside the window, so it keeps ringing. Beyond the window it is auto-dismissed as @@ -1157,8 +1157,32 @@ repair, resume and reschedule one by one, so its whole pass is inside the lock. ### The ring cycle A cycle opens when the alarm fires and closes on dismiss, on the snooze limit -being reached, or on auto-silence after `AUTO_SILENCE_AFTER` = **10 minutes** -(AOSP DeskClock's default; not user-configurable in v1). Snoozing keeps it open. +being reached, or on auto-silence after the **"Silence after"** window. That is +a setting since #17 (Settings › Alarms: 1, 5, 10, 15, 20 or 25 minutes, or +Never), **10 minutes** by default, AOSP DeskClock's default and v1's fixed +value, so an upgrade changes nothing. Snoozing keeps it open. + +The window is read from `ClockDefaults.alarmSilenceAfter` everywhere a ring is +measured: the resolver's ringing and late-snooze checks, the backstop `onFire` +arms, how late a snooze fire may arrive, and whether a ring interrupted by a +reboot is resumed. `AlarmResolver.resolve` takes it without a default, so no +caller can measure against a window the user did not choose. + +**"Never" is an hour.** The backstop is also what stops a phone left at home +from ringing until its battery is flat, what bounds the ring services' wake +locks, and what keeps a reboot hours later from resuming a ring nobody was +there for. So "Never" maps to `SilenceAfter.HARD_STOP` (60 minutes), longer +than any finite choice, and the settings hint says so in words. Stored values +are clamped to 0..60 on read, on write and from a backup, so no value can make +a ring outlast it. + +A ring started under one window keeps the backstop it was armed with. When the +window is shortened mid-ring, the next re-resolution closes the ring once it is +past the new window, and `persist` then stops the ring service and cancels the +backstop with it: storage says nothing rings, so nothing may. The same applies +to any ring the resolver closes (a clock jumped forward, a ringing alarm +switched off), which earlier only cleared `ringingSince` and left the sound to +the backstop. A **non-repeating alarm is disabled when its cycle closes, never when it opens**. Disabling it at the start would clear its own snooze and the alarm would vanish @@ -1284,7 +1308,7 @@ timer too. What the alarm **keeps to itself** is the full-screen intent, the ring activity, the dismiss challenge and the snooze; what the timer parameterises is its own ringtone, a ramp of **zero seconds** (a timer is set by someone awake, and a gentle start is just a quiet start) and its own -auto-silence constant. §14 has the rest, including which of the two wins the +"Silence after" setting. §14 has the rest, including which of the two wins the one audio stream. --- @@ -1433,7 +1457,7 @@ whichever comes first, for every challenge kind, asserted as a parameterised invariant over `DismissChallenge`, not as three happy paths. Three more guarantees hold alongside it. Snooze is never gated: the gate protects -dismissal only. Auto-silence still ends the ring at ten minutes regardless of the +dismissal only. Auto-silence still ends the ring at its "Silence after" window regardless of the gate, because that is the engine's, and the screen only follows the session to `Finished`. And a wrong answer carries no lockout and no penalty timer; it replaces the problem and that is all. @@ -1693,6 +1717,12 @@ the engine's own mutex, so it cannot race the fire it is asking about, and it is deliberately **conditional**: dismissing unconditionally would also drop a merely *snoozed* alarm's pending snooze, which is wrong for a label edit. +Since #17 the engine's `persist` also stops the ring service and cancels the +backstop whenever the resolver closes a ring (§11), so the disabled branch no +longer leaves a ring sounding on its own. The dismiss-first rule stays: it is +what closes the cycle *as a dismissal* (a one-shot alarm disabled, the snooze +notification cleared), and a deleted row never reaches the resolver at all. + ### Immediate apply There is no Save button, no dirty state and no discard dialog: `PLAN.md` §11 @@ -1877,8 +1907,8 @@ sound. - **A session is one window.** It opens when the audio *actually starts sounding* and closes when the expired set returns to empty. A second timer expiring mid-session inherits the session's remaining window rather than - buying a fresh ten minutes. That is the conservative direction, and the same rule as - §11's "a reboot does not buy the alarm another ten minutes". The anchor is the + buying a fresh window. That is the conservative direction, and the same rule as + §11's "a reboot does not buy the alarm a fresh window". The anchor is the instant the audio *opened* rather than the instant of expiry, so a long alarm ring in front of it does not eat the timer's whole window. - **A lapsed window does not silence the next timer.** A window that has run out @@ -1889,9 +1919,12 @@ sound. opens a fresh window with its own heads-up. Inheriting stays the rule for a timer expiring *inside* a live window. -`TimerRing.AUTO_SILENCE_AFTER` is **ten minutes**: its own constant with the -same value as the alarm's, free to diverge, because coupling the two would make -one number answer two questions. Unlike an alarm's, a timer's +The window is the timer's own **"Silence after"** setting +(`ClockDefaults.timerSilenceAfter`, Settings › Timers, #17), ten minutes by +default: the same choices as the alarm's and the same one-hour "Never", but a +separate value, because coupling the two would make one number answer two +questions. `TimerRingPolicy` reads it from the defaults it already takes, so a +change applies on the service's next pass. Unlike an alarm's, a timer's **auto-silence stops the noise and leaves the row `EXPIRED`.** An auto-silenced alarm is a *missed* alarm and its cycle closes; an auto-silenced timer has still finished, and the user coming back must be able to see that and add a minute diff --git a/docs/BACKUP.md b/docs/BACKUP.md index e8536de..670499b 100644 --- a/docs/BACKUP.md +++ b/docs/BACKUP.md @@ -136,6 +136,8 @@ device or after a reboot (`docs/PLAN.md` §5). Every imported timer lands "default_timer_ringtone_uri": null, "default_dismiss_challenge": "NONE", "home_zone_id": null, + "default_alarm_silence_after_minutes": 10, + "default_timer_silence_after_minutes": 10, "timer_presets": [60000, 120000, 180000, 300000, 600000, 900000, 1800000, 3600000] } ``` @@ -143,8 +145,15 @@ device or after a reboot (`docs/PLAN.md` §5). Every imported timer lands Field names mirror `ClockPrefs`'/`SettingsPrefs`' own on-disk keys. Older files may also carry `default_timer_duration_millis`, from a default timer length setting that has since been removed; it is ignored on import like any -other unknown field. Every -numeric/duration value is clamped on *apply* using the same ranges and encoding +other unknown field. + +`default_alarm_silence_after_minutes` and `default_timer_silence_after_minutes` +are how long a ringing alarm or a finished timer keeps going before it stops on +its own: whole minutes, with `0` meaning "Never" (which still stops after an +hour). A file without them, from before the setting existed, imports as `10`, +the value it was made with. Out-of-range values clamp to 0..60. + +Every numeric/duration value is clamped on *apply* using the same ranges and encoding as the existing preference setters, never on parse. ## Ringtone URIs From 1c323d5b4cf62c77ef57816c1af32bca3402aa1f Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Wed, 21 Oct 2026 19:04:08 +0200 Subject: [PATCH 2/8] fix(alarms): apply silence-after mid-ring and close missed one-shots Review fixes for the silence-after setting. Changing the alarm's silence-after now re-measures a ring in progress at once, through AlarmEngine.onSilenceAfterChanged: past the new window it closes as missed, inside it the backstop moves. onAutoSilence also re-arms instead of closing a ring that is still inside the current window, so a backstop armed for a shorter window cannot end a ring early. A cycle the resolver closes as missed (a ring past its window, or a snooze that never fired) now disables a one-shot alarm, as the engine's own close does. A short window made that path much easier to reach, and the alarm was being armed for the same time the next day. A late snooze is kept for the window or ten minutes, whichever is longer, so a short window never makes a promised snooze easier to lose than in v1. A timer that has gone quiet stays quiet when the setting is raised: the lapsed anchor moves back past the hard stop. The timer's heads-up is now keyed to the session anchor rather than the window's end, so editing the setting mid-ring no longer counts as a new session and alerts again. A negative stored value now reads as the default instead of Never. The picker offers a stored value that matches no choice, and the wake-lock timeout is one shared constant. Refs #17 --- .../clockula/alarm/AlarmEngine.kt | 34 +++++++- .../clockula/alarm/ring/AlarmRingService.kt | 8 +- .../clockula/data/prefs/ClockPrefs.kt | 9 ++- .../clockula/domain/ClockDefaults.kt | 1 - .../clockula/domain/alarm/AlarmResolver.kt | 20 ++++- .../clockula/domain/alarm/AlarmRing.kt | 11 +++ .../clockula/domain/ring/SilenceAfter.kt | 48 +++++++---- .../clockula/domain/timer/TimerRingPolicy.kt | 12 ++- .../clockula/timer/service/TimerService.kt | 28 +++---- .../clockula/ui/alarms/AlarmsViewModel.kt | 11 +-- .../clockula/ui/alarms/OverridePickers.kt | 26 +++--- .../clockula/ui/settings/SettingsViewModel.kt | 9 ++- .../clockula/alarm/AlarmEngineTest.kt | 79 +++++++++++++++++++ .../clockula/data/prefs/ClockPrefsTest.kt | 2 +- .../domain/alarm/AlarmResolverTest.kt | 35 ++++++++ .../clockula/domain/ring/SilenceAfterTest.kt | 9 ++- .../domain/timer/TimerRingPolicyTest.kt | 40 ++++++++-- .../ui/settings/SettingsViewModelTest.kt | 56 +++++++++++++ docs/ARCHITECTURE.md | 44 +++++++---- docs/BACKUP.md | 3 +- 20 files changed, 397 insertions(+), 88 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt index 9acaedc..fc09bc8 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt @@ -29,6 +29,7 @@ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant import javax.inject.Inject @@ -80,13 +81,42 @@ class AlarmEngine @Inject constructor( suspend fun onAutoSilence(alarmId: Long): Unit = lock.withLock { val state = states.state(alarmId) - if (state.ringingSince == null) return@withLock + val since = state.ringingSince ?: return@withLock + + // A backstop armed for a shorter window than the one now chosen ("Silence + // after" was raised mid-ring, and the re-arm below has not run yet): the + // ring still has time, so the backstop moves rather than firing early. A + // negative age is a clock moved backwards, and closes as it always did. + val age = wallClock.now() - since + val silenceAfter = settings.currentDefaults().alarmSilenceAfter + if (age >= Duration.ZERO && age < silenceAfter) { + scheduler.scheduleAutoSilence(since + silenceAfter, alarmId) + return@withLock + } // Missed, not snoozed: the ring stops, the cycle closes, the next // occurrence is scheduled. There is no missed-alarm notification in v1. closeCycleLocked(alarmId, state) } + /** + * "Silence after" changed. A ring in progress is measured against the new + * window at once: one already past it closes as missed, exactly as the + * backstop would close it, and one still inside it has its backstop moved + * to the new end. Measured from when the ring started, so changing the + * setting back and forth cannot buy a ring a fresh window. + */ + suspend fun onSilenceAfterChanged(): Unit = lock.withLock { + val state = states.ringing() ?: return@withLock + val since = state.ringingSince ?: return@withLock + val silenceAfter = settings.currentDefaults().alarmSilenceAfter + if (wallClock.now() - since >= silenceAfter) { + closeCycleLocked(state.alarmId, state) + } else { + scheduler.scheduleAutoSilence(since + silenceAfter, state.alarmId) + } + } + /** [minutesOverride] is a one-off, already clamped; it is never persisted anywhere (M9 D15). */ suspend fun snooze(alarmId: Long, minutesOverride: Int? = null): SnoozeOutcome = lock.withLock { snoozeLocked(alarmId, minutesOverride) } @@ -247,7 +277,7 @@ class AlarmEngine @Inject constructor( // A snooze is kept for as long as the resolver keeps it pending, so one // delivered late (after a reboot, or by Doze) still rings. Rejecting it // here would only re-register the same past instant and fire again. - val lateBy = if (isSnoozeFire) silenceAfter else AlarmRing.FIRE_GRACE + val lateBy = if (isSnoozeFire) AlarmRing.snoozeGrace(silenceAfter) else AlarmRing.FIRE_GRACE // Deleted, switched off, or a PendingIntent so stale the moment has gone: // re-resolve the slot and stay quiet. if (alarm == null || !alarm.enabled || now - scheduledFor > lateBy) { diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/ring/AlarmRingService.kt b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/ring/AlarmRingService.kt index 11d71a2..1b18bd8 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/ring/AlarmRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/ring/AlarmRingService.kt @@ -26,7 +26,6 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch -import kotlin.time.Duration.Companion.minutes import javax.inject.Inject /** @@ -200,11 +199,8 @@ class AlarmRingService : Service() { private const val ACTION_REPOST = AlarmIntents.ACTION_DISMISS + ".SERVICE_REPOST" private const val WAKE_LOCK_TAG = "clockula:alarm-ring" - /** - * A backstop on the backstop: past the longest ring window any "Silence - * after" choice allows, so a ring is never cut short by its own wake lock. - */ - private val WAKE_LOCK_TIMEOUT_MILLIS = (SilenceAfter.HARD_STOP + 5.minutes).inWholeMilliseconds + /** A backstop on the backstop, shared with the other ring service. */ + private val WAKE_LOCK_TIMEOUT_MILLIS = SilenceAfter.WAKE_LOCK_TIMEOUT.inWholeMilliseconds fun start(context: Context) { context.startForegroundService(Intent(context, AlarmRingService::class.java)) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefs.kt b/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefs.kt index a14e002..080a367 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefs.kt @@ -34,16 +34,17 @@ object ClockPrefs { /** * How long a ringing alarm, and a finished timer, keep going before they - * stop on their own (#17): minutes, or [SilenceAfter.NEVER]. An absent key - * reads as v1's fixed ten minutes, so an upgrade changes nothing. + * stop on their own (#17): minutes, or [SilenceAfter.NEVER], sanitised both + * ways through [SilenceAfter.sanitise]. An absent key reads as v1's fixed + * ten minutes, so an upgrade changes nothing. */ val alarmSilenceAfterMinutes: Pref = intPref("default_alarm_silence_after_minutes", SilenceAfter.DEFAULT_MINUTES) - .clampedTo(ClockLimits.SILENCE_AFTER_MINUTES) + .map(decode = SilenceAfter::sanitise, encode = SilenceAfter::sanitise) val timerSilenceAfterMinutes: Pref = intPref("default_timer_silence_after_minutes", SilenceAfter.DEFAULT_MINUTES) - .clampedTo(ClockLimits.SILENCE_AFTER_MINUTES) + .map(decode = SilenceAfter::sanitise, encode = SilenceAfter::sanitise) /** Normalised through [Zones] both ways, so a zone the device dropped reads as absent. */ val homeZoneId: Pref = nullableStringPref("home_zone_id") diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ClockDefaults.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ClockDefaults.kt index 20b2dd2..8f37066 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ClockDefaults.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ClockDefaults.kt @@ -39,5 +39,4 @@ object ClockLimits { val SNOOZE_MINUTES: IntRange = 1..60 val SNOOZE_LIMIT: IntRange = 0..10 val VOLUME_RAMP_SECONDS: IntRange = 0..60 - val SILENCE_AFTER_MINUTES: IntRange = SilenceAfter.MINUTES } diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt index 7109ba4..c188d16 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt @@ -72,8 +72,11 @@ object AlarmResolver { // 3. Snooze. A snooze promised before a reboot is kept, even if it came // due while the device was off; one older than the ring window is gone. + // Never sooner than SNOOZE_GRACE, so a short "Silence after" cannot make + // a snooze easier to lose than it was in v1. val snoozedUntil = working.snoozedUntil - val snoozePending = snoozedUntil != null && now - snoozedUntil < autoSilenceAfter + val snoozeGrace = AlarmRing.snoozeGrace(autoSilenceAfter) + val snoozePending = snoozedUntil != null && now - snoozedUntil < snoozeGrace if (snoozedUntil != null && !snoozePending) { working = working.copy(snoozedUntil = null, snoozeCount = 0) } @@ -93,6 +96,21 @@ object AlarmResolver { } } + // A cycle that has just closed as missed (a ring past its window, or a + // snooze that never fired) closes a one-shot alarm for good, exactly as + // the engine's own close does. Falling through would hand it the same + // time tomorrow. + val closedAsMissed = ringingSince != null || snoozedUntil != null + if (closedAsMissed && !alarm.repeatDays.isRepeating) { + return AlarmResolution( + alarmId = alarm.id, + nextFire = null, + source = FireSource.NONE, + state = working.copy(skippedOccurrence = null), + disableAlarm = true, + ) + } + // 4. The natural occurrence, with the skip watermark on top. if (!alarm.skipNextOccurrence) { return AlarmResolution( diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt index 061b57c..6d11d99 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt @@ -16,4 +16,15 @@ object AlarmRing { * boot or a `TIME_SET` nudge still rings; one missed by hours does not. */ val FIRE_GRACE: Duration = 2.minutes + + /** + * The least time a late snooze is still kept: v1's fixed ring window. A + * snooze delayed by a reboot or by Doze is kept for the "Silence after" + * window or this, whichever is longer, so a short window never makes a + * promised snooze easier to lose. + */ + val SNOOZE_GRACE: Duration = 10.minutes + + /** How late a snooze may come due and still ring, given the ring window. */ + fun snoozeGrace(silenceAfter: Duration): Duration = maxOf(silenceAfter, SNOOZE_GRACE) } diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt index 5312037..2982b15 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt @@ -18,27 +18,45 @@ object SilenceAfter { /** The stored value for "Never". Zero, because no window can be zero minutes long. */ const val NEVER: Int = 0 - /** - * Everything a stored value is clamped into, on read, on write and from a - * backup. Any value in it means something: [NEVER], or that many minutes. - */ - val MINUTES: IntRange = NEVER..60 - - /** - * The longest a ring ever lasts, and what "Never" means in practice. The - * settings hints say "an hour" in words; change them with it. - */ - val HARD_STOP: Duration = MINUTES.last.minutes - /** The default, for alarms and timers alike: AOSP DeskClock's, and v1's fixed value. */ const val DEFAULT_MINUTES: Int = 10 + /** + * The longest a ring ever lasts, in minutes, and what "Never" means in + * practice. The settings hints say "an hour" in words; change them with it. + */ + const val HARD_STOP_MINUTES: Int = 60 + + val HARD_STOP: Duration = HARD_STOP_MINUTES.minutes + + /** + * How long the ring services hold their wake locks: a backstop on the + * backstop, past the longest window there is, so a ring is never cut + * short by its own wake lock. + */ + val WAKE_LOCK_TIMEOUT: Duration = HARD_STOP + 5.minutes + + /** Every value [sanitise] lets through: [NEVER], or that many minutes up to the hard stop. */ + val MINUTES: IntRange = NEVER..HARD_STOP_MINUTES + /** The choices the pickers offer, in order: Google Clock's, so nothing here surprises. */ val CHOICES: List = listOf(1, 5, 10, 15, 20, 25, NEVER) - /** The ring window [minutes] stands for, clamped first so the engines never see an unofferable value. */ + /** + * What a stored value is read and written as, from a picker, a hand-edited + * file or a backup. Too long is the hard stop, which is what it would ring + * for anyway. Negative is nothing anyone chose, so it is the default rather + * than the clamp's floor, which would be "Never". + */ + fun sanitise(minutes: Int): Int = when { + minutes < NEVER -> DEFAULT_MINUTES + minutes > HARD_STOP_MINUTES -> HARD_STOP_MINUTES + else -> minutes + } + + /** The ring window [minutes] stands for, sanitised first so the engines never see an unofferable value. */ fun window(minutes: Int): Duration { - val clamped = minutes.coerceIn(MINUTES) - return if (clamped == NEVER) HARD_STOP else clamped.minutes + val sane = sanitise(minutes) + return if (sane == NEVER) HARD_STOP else sane.minutes } } diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt index 478747d..f9bce4f 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.clockula.domain.timer import de.jeanlucmakiola.clockula.domain.ClockDefaults +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import kotlin.time.Instant sealed interface TimerRingDecision { @@ -18,6 +19,11 @@ sealed interface TimerRingDecision { val settings: TimerSettings, /** When the window closes: the session anchor + [ClockDefaults.timerSilenceAfter]. */ val silenceAt: Instant, + /** + * The session anchor: when its audio opened. The session's identity + * (D10), which [silenceAt] is not, since "Silence after" can move it. + */ + val openedAt: Instant, ) : TimerRingDecision } @@ -53,7 +59,10 @@ object TimerRingPolicy { if (soundingSince != null && now - soundingSince >= window) { return TimerRingOutcome( TimerRingDecision.AutoSilenced(subject.timer.id), - soundingSince = soundingSince, + // Stays run out whatever "Silence after" becomes: the anchor is + // moved back past the longest window there is, so raising the + // setting later cannot start a silenced timer ringing again. + soundingSince = minOf(soundingSince, now - SilenceAfter.HARD_STOP), ) } @@ -75,6 +84,7 @@ object TimerRingPolicy { subjectId = subject.timer.id, settings = subject.timer.resolveSettings(defaults), silenceAt = anchor + window, + openedAt = anchor, ), soundingSince = anchor, ) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/timer/service/TimerService.kt b/app/src/main/java/de/jeanlucmakiola/clockula/timer/service/TimerService.kt index 0775b6a..6c666d1 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/timer/service/TimerService.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/timer/service/TimerService.kt @@ -35,7 +35,6 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.merge import kotlinx.coroutines.launch -import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant import javax.inject.Inject @@ -97,11 +96,11 @@ class TimerService : Service() { private var alreadyAlerted: Boolean = false /** - * The auto-silence window the heads-up above was spent inside. A window is - * one ring session (D10), so a *new* session is a new event and gets its - * own one heads-up — even while an earlier timer stays EXPIRED. + * The anchor of the ring session the heads-up above was spent inside. A + * *new* session is a new event and gets its own one heads-up (D10) — even + * while an earlier timer stays EXPIRED. */ - private var alertedWindow: Instant? = null + private var alertedSession: Instant? = null /** * `startForeground` is for going foreground, not for posting: every engine @@ -206,8 +205,10 @@ class TimerService : Service() { } /** - * A ring session's window is its identity (D10), so when the window moves the - * flag that spends the session's one heads-up moves with it. The state is + * A ring session's anchor is its identity (D10), so when a new session opens + * the flag that spends the session's one heads-up moves with it. The anchor + * rather than the window's end, which a "Silence after" edit can move + * mid-session without making it a new one. The state is * asked for again, because it was computed from the answer that has just * changed — a second pass rather than a notification that says the right * thing one trigger too late. @@ -216,9 +217,9 @@ class TimerService : Service() { // Only a sounding decision carries a window; a suppressed or silenced one // must not clear the record, or an alarm ringing across a session would // buy it a second heads-up (D9). - val window = (state.ring as? TimerRingDecision.Sound)?.silenceAt ?: return state - val reopened = alreadyAlerted && window != alertedWindow - alertedWindow = window + val session = (state.ring as? TimerRingDecision.Sound)?.openedAt ?: return state + val reopened = alreadyAlerted && session != alertedSession + alertedSession = session if (!reopened) return state alreadyAlerted = false return engine.serviceState(alreadyAlerted) @@ -365,11 +366,8 @@ class TimerService : Service() { companion object { private const val WAKE_LOCK_TAG = "clockula:timer-ring" - /** - * A backstop on the backstop: past the longest ring window any "Silence - * after" choice allows, so a ring is never cut short by its own wake lock. - */ - private val WAKE_LOCK_TIMEOUT_MILLIS = (SilenceAfter.HARD_STOP + 5.minutes).inWholeMilliseconds + /** A backstop on the backstop, shared with the other ring service. */ + private val WAKE_LOCK_TIMEOUT_MILLIS = SilenceAfter.WAKE_LOCK_TIMEOUT.inWholeMilliseconds fun start(context: Context) { context.startForegroundService(Intent(context, TimerService::class.java)) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/AlarmsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/AlarmsViewModel.kt index d17e9fe..b0f608c 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/AlarmsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/AlarmsViewModel.kt @@ -86,11 +86,12 @@ class AlarmsViewModel @Inject internal constructor( } /** - * The ring service is a single global slot the resolver cannot reach, and - * its auto-silence backstop disarms itself once `ringingSince` is null — so - * switching off a *ringing* alarm has to go through the engine first, or it - * sounds until the wake lock expires. Conditional, because dismissing a - * merely snoozed alarm would drop a snooze it should keep (M5 D11). + * Switching off a *ringing* alarm goes through the engine first, so the ring + * closes as a dismissal: the snooze notification cleared and the cycle + * closed under the engine's lock. (Since #17 the engine would also stop the + * sound when the next resolution sees the alarm disabled, but that is a + * backstop, not the path.) Conditional, because dismissing a merely + * snoozed alarm would drop a snooze it should keep (M5 D11). */ private suspend fun stopRingIfRinging(alarmId: Long) { if (engine.ringSession()?.alarm?.id == alarmId) engine.dismiss(alarmId) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt index d93d58c..6046147 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt @@ -78,24 +78,26 @@ internal fun silenceAfterText(minutes: Int): String = if (minutes == SilenceAfte /** * "Silence after" is app-wide only (#17): no alarm or timer overrides it, so - * this picker never offers "App default". It shares the overrides' shape so - * the settings screens' pickers all look and behave alike. + * this picker has no "App default" rung. A stored value no choice matches (a + * backup can carry any minute up to the hard stop) is offered too, in its + * place, so the picker always shows what is selected and can put it back. */ @Composable internal fun SilenceAfterPicker( selected: Int, onSelect: (Int) -> Unit, onDismiss: () -> Unit, -) = OverridePicker( - title = stringResource(R.string.settings_silence_after), - options = SilenceAfter.CHOICES, - stored = selected, - default = selected, - text = { silenceAfterText(it) }, - onSelect = { it?.let(onSelect) }, - onDismiss = onDismiss, - includeAppDefault = false, -) +) { + val finite = (SilenceAfter.CHOICES + selected).filter { it != SilenceAfter.NEVER }.distinct().sorted() + OptionPicker( + title = stringResource(R.string.settings_silence_after), + options = finite + SilenceAfter.NEVER, + selected = selected, + label = { silenceAfterText(it) }, + onSelect = onSelect, + onDismiss = onDismiss, + ) +} @Composable internal fun VibratePicker( diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt index 224d8b2..213ac9c 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt @@ -3,6 +3,7 @@ package de.jeanlucmakiola.clockula.ui.settings import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.clockula.alarm.AlarmEngine import de.jeanlucmakiola.clockula.alarm.DeviceStateReader import de.jeanlucmakiola.clockula.data.appicon.LauncherIcon import de.jeanlucmakiola.clockula.data.appicon.LauncherIconManager @@ -48,6 +49,7 @@ import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject internal constructor( private val settings: SettingsPrefs, + private val alarmEngine: AlarmEngine, private val ringtones: RingtoneCatalog, private val preview: RingtonePreviewer, private val worldClocks: WorldClockSource, @@ -142,8 +144,11 @@ class SettingsViewModel @Inject internal constructor( fun onDismissChallengeChanged(value: DismissChallenge) = viewModelScope.launch { settings.setDismissChallenge(value) } - fun onAlarmSilenceAfterChanged(minutes: Int) = - viewModelScope.launch { settings.setAlarmSilenceAfterMinutes(minutes) } + /** The engine re-measures a ring in progress against the new window at once. */ + fun onAlarmSilenceAfterChanged(minutes: Int) = viewModelScope.launch { + settings.setAlarmSilenceAfterMinutes(minutes) + alarmEngine.onSilenceAfterChanged() + } fun onTimerSilenceAfterChanged(minutes: Int) = viewModelScope.launch { settings.setTimerSilenceAfterMinutes(minutes) } diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt index bb87cb9..50f13cd 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt @@ -911,6 +911,85 @@ class AlarmEngineTest { assertThat(entry.source).isEqualTo(FireSource.RESUMED_RING) } + @Test + fun `a backstop armed for a shorter window moves rather than firing early`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val settings = settings(dir) + val engine = engineOver(settings) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + settings.setAlarmSilenceAfterMinutes(25) + wallClock.instant = sevenToday + 10.minutes + + engine.onAutoSilence(1L) + + assertThat(ring.ringing.value).isEqualTo(1L) + assertThat(states.state(1L).ringingSince).isEqualTo(sevenToday) + assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + 25.minutes, 1L)) + } + + @Test + fun `raising silence-after mid-ring moves the backstop at once`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val settings = settings(dir) + val engine = engineOver(settings) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday + 3.minutes + + settings.setAlarmSilenceAfterMinutes(SilenceAfter.NEVER) + engine.onSilenceAfterChanged() + + assertThat(ring.ringing.value).isEqualTo(1L) + assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + SilenceAfter.HARD_STOP, 1L)) + } + + @Test + fun `lowering silence-after below a ring's age closes it as missed at once`(@TempDir dir: Path) = runTest { + givenAlarm() + wallClock.instant = sevenToday + val settings = settings(dir) + val engine = engineOver(settings) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday + 5.minutes + + settings.setAlarmSilenceAfterMinutes(1) + engine.onSilenceAfterChanged() + + assertThat(ring.ringing.value).isNull() + assertThat(states.state(1L).ringingSince).isNull() + assertThat(scheduler.autoSilence).isNull() + // A one-shot alarm's cycle has closed, so it is off, not armed for tomorrow. + assertThat(alarms.find(1L)?.enabled).isFalse() + } + + @Test + fun `changing silence-after with nothing ringing touches nothing`(@TempDir dir: Path) = runTest { + givenAlarm() + val settings = settings(dir) + val engine = engineOver(settings) + + settings.setAlarmSilenceAfterMinutes(1) + engine.onSilenceAfterChanged() + + assertThat(ring.events).isEmpty() + assertThat(scheduler.autoSilence).isNull() + } + + @Test + fun `a one-shot ring missed across a reboot is disabled, not re-armed for tomorrow`(@TempDir dir: Path) = + runTest { + givenAlarm() + wallClock.instant = sevenToday + 40.minutes + givenRingingAt(alarmId = 1L, occurrence = sevenToday, since = sevenToday) + val engine = engine(dir) + + engine.onBootCompleted() + + assertThat(alarms.find(1L)?.enabled).isFalse() + assertThat(scheduler.next).isNull() + } + // --- upcoming() --- @Test diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt index bdfe100..11817ca 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt @@ -162,7 +162,7 @@ class ClockPrefsTest { prefs.setAlarmSilenceAfterMinutes(999) prefs.setTimerSilenceAfterMinutes(-3) assertThat(prefs.defaults.first().alarmSilenceAfterMinutes).isEqualTo(60) - assertThat(prefs.defaults.first().timerSilenceAfterMinutes).isEqualTo(SilenceAfter.NEVER) + assertThat(prefs.defaults.first().timerSilenceAfterMinutes).isEqualTo(SilenceAfter.DEFAULT_MINUTES) dataStore.updateData { stored -> stored.toMutablePreferences() diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolverTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolverTest.kt index e963c99..fb67163 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolverTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolverTest.kt @@ -409,4 +409,39 @@ class AlarmResolverTest { assertThat(kept.nextFire to kept.source).isEqualTo(snoozedUntil to FireSource.SNOOZE) assertThat(dropped.state.snoozedUntil).isNull() } + + @Test + fun `a one-shot ring closed as missed disables the alarm rather than ringing tomorrow`() { + val alarm = alarmAt(hour = 7) + val state = ringState(ringingSince = morning - 2.minutes, handledOccurrence = morning - 2.minutes) + + val resolution = resolve(alarm, state, silenceAfter = SilenceAfter.window(1)) + + assertThat(resolution.disableAlarm).isTrue() + assertThat(resolution.nextFire).isNull() + assertThat(resolution.state.ringingSince).isNull() + } + + @Test + fun `a one-shot snooze that never fired disables the alarm rather than ringing tomorrow`() { + val alarm = alarmAt(hour = 7) + val state = ringState(snoozedUntil = morning - 11.minutes, snoozeCount = 1) + + val resolution = resolve(alarm, state) + + assertThat(resolution.disableAlarm).isTrue() + assertThat(resolution.nextFire).isNull() + assertThat(resolution.state.snoozedUntil).isNull() + } + + @Test + fun `a short window never makes a late snooze easier to lose than v1's ten minutes`() { + val alarm = alarmAt(hour = 7, repeatDays = RepeatDays.EVERY_DAY) + val snoozedUntil = morning - 8.minutes + val state = ringState(snoozedUntil = snoozedUntil, snoozeCount = 1) + + val resolution = resolve(alarm, state, silenceAfter = SilenceAfter.window(1)) + + assertThat(resolution.nextFire to resolution.source).isEqualTo(snoozedUntil to FireSource.SNOOZE) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfterTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfterTest.kt index e977bbb..a484e83 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfterTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfterTest.kt @@ -27,13 +27,18 @@ class SilenceAfterTest { fun `Never is the hard stop, an hour`() { assertThat(SilenceAfter.window(SilenceAfter.NEVER)).isEqualTo(SilenceAfter.HARD_STOP) assertThat(SilenceAfter.HARD_STOP).isEqualTo(1.hours) + assertThat(SilenceAfter.WAKE_LOCK_TIMEOUT).isGreaterThan(SilenceAfter.HARD_STOP) } @Test fun `no value reaches the engines as a window longer than the hard stop`() { assertThat(SilenceAfter.window(24 * 60)).isEqualTo(SilenceAfter.HARD_STOP) - // Negative is clamped to Never rather than read as an instant silence. - assertThat(SilenceAfter.window(-5)).isEqualTo(SilenceAfter.HARD_STOP) + } + + @Test + fun `a negative value is the default, not Never`() { + assertThat(SilenceAfter.sanitise(-1)).isEqualTo(SilenceAfter.DEFAULT_MINUTES) + assertThat(SilenceAfter.window(-5)).isEqualTo(10.minutes) } @Test diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicyTest.kt index 70f4c8f..5019802 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicyTest.kt @@ -156,6 +156,7 @@ class TimerRingPolicyTest { subjectId = 7L, settings = released.sound().settings, silenceAt = now + ClockDefaults().timerSilenceAfter, + openedAt = now, ), soundingSince = now, ), @@ -179,8 +180,10 @@ class TimerRingPolicyTest { val outcome = decide(soundingSince = opened) - assertThat(outcome) - .isEqualTo(TimerRingOutcome(TimerRingDecision.AutoSilenced(7L), soundingSince = opened)) + // The anchor moves back past the longest window, so the session stays run out (#17). + assertThat(outcome).isEqualTo( + TimerRingOutcome(TimerRingDecision.AutoSilenced(7L), soundingSince = now - SilenceAfter.HARD_STOP), + ) } /** §5.4 #15 */ @@ -196,12 +199,13 @@ class TimerRingPolicyTest { /** §5.4 #16 */ @Test fun `an auto-silenced session does not restart a minute later`() { - val opened = now - ClockDefaults().timerSilenceAfter + val silenced = decide(soundingSince = now - ClockDefaults().timerSilenceAfter) - val outcome = decide(soundingSince = opened, at = now + 1.minutes) + val outcome = decide(soundingSince = silenced.soundingSince, at = now + 1.minutes) - assertThat(outcome) - .isEqualTo(TimerRingOutcome(TimerRingDecision.AutoSilenced(7L), soundingSince = opened)) + assertThat(outcome).isEqualTo( + TimerRingOutcome(TimerRingDecision.AutoSilenced(7L), soundingSince = silenced.soundingSince), + ) } /** §5.4 #17 */ @@ -274,4 +278,28 @@ class TimerRingPolicyTest { assertThat(sounding.sound().silenceAt).isEqualTo(now - 59.minutes + SilenceAfter.HARD_STOP) assertThat(silenced.decision).isEqualTo(TimerRingDecision.AutoSilenced(7L)) } + + @Test + fun `raising silence-after does not restart a session that already went quiet`() { + val short = defaults.copy(timerSilenceAfterMinutes = 1) + val silenced = decide(defaults = short, soundingSince = now - 1.minutes) + + val raised = decide( + defaults = defaults.copy(timerSilenceAfterMinutes = SilenceAfter.NEVER), + soundingSince = silenced.soundingSince, + at = now + 4.minutes, + ) + + assertThat(raised.decision).isEqualTo(TimerRingDecision.AutoSilenced(7L)) + } + + @Test + fun `changing silence-after mid-session moves the window but not the session`() { + val opened = now - 2.minutes + + val sound = decide(defaults = defaults.copy(timerSilenceAfterMinutes = 25), soundingSince = opened).sound() + + assertThat(sound.openedAt).isEqualTo(opened) + assertThat(sound.silenceAt).isEqualTo(opened + 25.minutes) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModelTest.kt index 1af202e..f35a2b0 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModelTest.kt @@ -1,13 +1,30 @@ package de.jeanlucmakiola.clockula.ui.settings import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.clockula.alarm.AlarmEngine +import de.jeanlucmakiola.clockula.data.alarms.AlarmMapper +import de.jeanlucmakiola.clockula.data.alarms.AlarmRepositoryImpl +import de.jeanlucmakiola.clockula.data.alarms.AlarmStateRepositoryImpl import de.jeanlucmakiola.clockula.data.appicon.LauncherIcon import de.jeanlucmakiola.clockula.domain.DismissChallenge +import de.jeanlucmakiola.clockula.domain.RepeatDays +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter +import de.jeanlucmakiola.clockula.testing.BERLIN +import de.jeanlucmakiola.clockula.testing.FakeAlarmDao +import de.jeanlucmakiola.clockula.testing.FakeAlarmNotifier +import de.jeanlucmakiola.clockula.testing.FakeAlarmScheduler +import de.jeanlucmakiola.clockula.testing.FakeAlarmStateDao import de.jeanlucmakiola.clockula.testing.FakeDeviceStateReader import de.jeanlucmakiola.clockula.testing.FakeLauncherIconManager import de.jeanlucmakiola.clockula.testing.FakeRingtoneCatalog +import de.jeanlucmakiola.clockula.testing.FakeRingCoordinator import de.jeanlucmakiola.clockula.testing.FakeRingtonePreviewer +import de.jeanlucmakiola.clockula.testing.FakeWallClock +import de.jeanlucmakiola.clockula.testing.FakeZoneProvider import de.jeanlucmakiola.clockula.testing.MainDispatcherExtension +import de.jeanlucmakiola.clockula.testing.alarmAt +import de.jeanlucmakiola.clockula.testing.RecordingRebootRepair +import de.jeanlucmakiola.clockula.testing.instantAt import de.jeanlucmakiola.clockula.testing.worldClockHarness import de.jeanlucmakiola.floret.prefs.ThemeMode import kotlinx.coroutines.Dispatchers @@ -21,6 +38,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.io.TempDir import java.nio.file.Path +import kotlin.time.Duration.Companion.minutes /** * The real [SettingsViewModel] over the real [de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs] @@ -35,13 +53,33 @@ class SettingsViewModelTest { @RegisterExtension val main = MainDispatcherExtension() + // The alarm engine "Silence after" re-measures a ring through, over fakes. + private val alarmDao = FakeAlarmDao() + private val stateDao = FakeAlarmStateDao(alarms = alarmDao) + private val wallClock = FakeWallClock(instantAt(BERLIN, "2026-06-10T07:00")) + private val alarmScheduler = FakeAlarmScheduler() + private val ring = FakeRingCoordinator() + private lateinit var alarmEngine: AlarmEngine + private fun TestScope.newViewModel( tempDir: Path, launcherIcons: FakeLauncherIconManager = FakeLauncherIconManager(), ): SettingsViewModel { val harness = worldClockHarness(tempDir) + alarmEngine = AlarmEngine( + alarms = AlarmRepositoryImpl(alarmDao, wallClock), + states = AlarmStateRepositoryImpl(stateDao), + settings = harness.settings, + scheduler = alarmScheduler, + ring = ring, + notifier = FakeAlarmNotifier(), + rebootRepair = RecordingRebootRepair(), + wallClock = wallClock, + zones = FakeZoneProvider(BERLIN), + ) return SettingsViewModel( settings = harness.settings, + alarmEngine = alarmEngine, ringtones = FakeRingtoneCatalog(), preview = FakeRingtonePreviewer(), worldClocks = harness.source, @@ -119,6 +157,8 @@ class SettingsViewModelTest { viewModel.onSnoozeLimitChanged(2) viewModel.onVolumeRampChanged(30) viewModel.onDismissChallengeChanged(DismissChallenge.MATH) + viewModel.onAlarmSilenceAfterChanged(25) + viewModel.onTimerSilenceAfterChanged(SilenceAfter.NEVER) advanceUntilIdle() val defaults = (viewModel.state.value as SettingsUiState.Loaded).defaults @@ -127,8 +167,24 @@ class SettingsViewModelTest { assertThat(defaults.snoozeLimit).isEqualTo(2) assertThat(defaults.volumeRampSeconds).isEqualTo(30) assertThat(defaults.dismissChallenge).isEqualTo(DismissChallenge.MATH) + assertThat(defaults.alarmSilenceAfterMinutes).isEqualTo(25) + assertThat(defaults.timerSilenceAfterMinutes).isEqualTo(SilenceAfter.NEVER) } + @Test + fun `changing the alarm silence-after re-measures a ring in progress`(@TempDir tempDir: Path) = + runTest(main.dispatcher) { + val viewModel = collecting(newViewModel(tempDir)) + alarmDao.insert(AlarmMapper.toEntity(alarmAt(id = 1L, hour = 7, repeatDays = RepeatDays.EVERY_DAY))) + alarmEngine.onFire(alarmId = 1L, scheduledFor = wallClock.instant) + advanceUntilIdle() + + viewModel.onAlarmSilenceAfterChanged(25) + advanceUntilIdle() + + assertThat(alarmScheduler.autoSilence?.fireAt).isEqualTo(wallClock.instant + 25.minutes) + } + @Test fun `choosing a default alarm ringtone writes through and closes the picker`(@TempDir tempDir: Path) = runTest(main.dispatcher) { diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 31868fc..b035745 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1163,26 +1163,37 @@ Never), **10 minutes** by default, AOSP DeskClock's default and v1's fixed value, so an upgrade changes nothing. Snoozing keeps it open. The window is read from `ClockDefaults.alarmSilenceAfter` everywhere a ring is -measured: the resolver's ringing and late-snooze checks, the backstop `onFire` -arms, how late a snooze fire may arrive, and whether a ring interrupted by a -reboot is resumed. `AlarmResolver.resolve` takes it without a default, so no -caller can measure against a window the user did not choose. +measured: the resolver's ringing check, the backstop `onFire` arms, and whether +a ring interrupted by a reboot is resumed. `AlarmResolver.resolve` takes it +without a default, so no caller can measure against a window the user did not +choose. How late a snooze may come due and still ring is the window **or +`AlarmRing.SNOOZE_GRACE` (v1's ten minutes), whichever is longer**: a short +"Silence after" must not make a promised snooze easier to lose to a reboot. **"Never" is an hour.** The backstop is also what stops a phone left at home from ringing until its battery is flat, what bounds the ring services' wake locks, and what keeps a reboot hours later from resuming a ring nobody was there for. So "Never" maps to `SilenceAfter.HARD_STOP` (60 minutes), longer than any finite choice, and the settings hint says so in words. Stored values -are clamped to 0..60 on read, on write and from a backup, so no value can make -a ring outlast it. +go through `SilenceAfter.sanitise` on read, on write and from a backup: over 60 +is 60, so no value can make a ring outlast the hard stop, and a negative one is +the default rather than the clamp's floor, which would be "Never". -A ring started under one window keeps the backstop it was armed with. When the -window is shortened mid-ring, the next re-resolution closes the ring once it is -past the new window, and `persist` then stops the ring service and cancels the -backstop with it: storage says nothing rings, so nothing may. The same applies -to any ring the resolver closes (a clock jumped forward, a ringing alarm -switched off), which earlier only cleared `ringingSince` and left the sound to -the backstop. +Changing the setting mid-ring applies at once. The settings screen calls +`AlarmEngine.onSilenceAfterChanged()`, which measures the ring in progress +against the new window from when it *started*: past it, the cycle closes as +missed through `closeCycleLocked`; inside it, the backstop moves to the new +end. As a second line, `onAutoSilence` re-arms rather than closes a ring that +is still inside the current window, so a backstop armed for a shorter one can +never end a ring early. + +Whenever the resolver closes a ring (a clock jumped forward, a ringing alarm +switched off, a reboot outlasting the window), `persist` stops the ring service +and cancels the backstop: storage says nothing rings, so nothing may. Earlier +that path only cleared `ringingSince` and left the sound to the backstop. And a +cycle the resolver closes as missed (a ring past its window, or a snooze that +never fired) **disables a one-shot alarm**, exactly as `closeCycleLocked` +does; falling through would have armed it for the same time tomorrow. A **non-repeating alarm is disabled when its cycle closes, never when it opens**. Disabling it at the start would clear its own snooze and the alarm would vanish @@ -1924,7 +1935,12 @@ The window is the timer's own **"Silence after"** setting default: the same choices as the alarm's and the same one-hour "Never", but a separate value, because coupling the two would make one number answer two questions. `TimerRingPolicy` reads it from the defaults it already takes, so a -change applies on the service's next pass. Unlike an alarm's, a timer's +change applies on the service's next pass. A session that has gone quiet stays +quiet: on auto-silence the policy moves the stored anchor back past +`SilenceAfter.HARD_STOP`, so raising the setting afterwards cannot start it +ringing again. The service's one heads-up is keyed to the session's anchor +(`Sound.openedAt`) rather than to the window's end, which an edit can move +without making a new session. Unlike an alarm's, a timer's **auto-silence stops the noise and leaves the row `EXPIRED`.** An auto-silenced alarm is a *missed* alarm and its cycle closes; an auto-silenced timer has still finished, and the user coming back must be able to see that and add a minute diff --git a/docs/BACKUP.md b/docs/BACKUP.md index 670499b..c5d7799 100644 --- a/docs/BACKUP.md +++ b/docs/BACKUP.md @@ -151,7 +151,8 @@ other unknown field. are how long a ringing alarm or a finished timer keeps going before it stops on its own: whole minutes, with `0` meaning "Never" (which still stops after an hour). A file without them, from before the setting existed, imports as `10`, -the value it was made with. Out-of-range values clamp to 0..60. +the value it was made with. A value over 60 reads as 60 (which is what Never +rings for anyway); a negative one reads as the default, 10. Every numeric/duration value is clamped on *apply* using the same ranges and encoding as the existing preference setters, never on parse. From fb875ca71ce82e6051d426f72e8057213be9b330 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Wed, 21 Oct 2026 19:12:18 +0200 Subject: [PATCH 3/8] fix(alarms): measure every ring against one window rule Second round of review fixes for the silence-after setting. A fire now clears any stale ringingSince before it re-resolves the slot. Before, the resolver's new one-shot close could switch off, or delete, the very alarm that was about to ring. A one-shot alarm displaced by another alarm's fire is switched off, as on every other close of an undismissed cycle, instead of being armed for the same time tomorrow. onAutoSilence, onSilenceAfterChanged and the reboot resume now share one rule. A ring still inside the window has its backstop re-armed, measured from when it started, or from now if the clock has moved back behind that start, so a clock change cannot stretch a ring past one window. Refs #17 --- .../clockula/alarm/AlarmEngine.kt | 54 ++++++++++--------- .../clockula/domain/ring/SilenceAfter.kt | 5 +- .../clockula/alarm/AlarmEngineTest.kt | 46 ++++++++++++++++ docs/ARCHITECTURE.md | 4 +- 4 files changed, 81 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt index fc09bc8..ea5ce1d 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt @@ -29,7 +29,6 @@ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock -import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant import javax.inject.Inject @@ -84,15 +83,9 @@ class AlarmEngine @Inject constructor( val since = state.ringingSince ?: return@withLock // A backstop armed for a shorter window than the one now chosen ("Silence - // after" was raised mid-ring, and the re-arm below has not run yet): the - // ring still has time, so the backstop moves rather than firing early. A - // negative age is a clock moved backwards, and closes as it always did. - val age = wallClock.now() - since - val silenceAfter = settings.currentDefaults().alarmSilenceAfter - if (age >= Duration.ZERO && age < silenceAfter) { - scheduler.scheduleAutoSilence(since + silenceAfter, alarmId) - return@withLock - } + // after" was raised mid-ring): the ring still has time, so the backstop + // moves rather than ending it early. + if (rearmIfInsideWindowLocked(alarmId, since)) return@withLock // Missed, not snoozed: the ring stops, the cycle closes, the next // occurrence is scheduled. There is no missed-alarm notification in v1. @@ -109,12 +102,7 @@ class AlarmEngine @Inject constructor( suspend fun onSilenceAfterChanged(): Unit = lock.withLock { val state = states.ringing() ?: return@withLock val since = state.ringingSince ?: return@withLock - val silenceAfter = settings.currentDefaults().alarmSilenceAfter - if (wallClock.now() - since >= silenceAfter) { - closeCycleLocked(state.alarmId, state) - } else { - scheduler.scheduleAutoSilence(since + silenceAfter, state.alarmId) - } + if (!rearmIfInsideWindowLocked(state.alarmId, since)) closeCycleLocked(state.alarmId, state) } /** [minutesOverride] is a one-off, already clamped; it is never persisted anywhere (M9 D15). */ @@ -288,16 +276,22 @@ class AlarmEngine @Inject constructor( // At most one alarm rings, and the newly-firing one takes over. The one // it displaces keeps its handled-occurrence watermark, so it does not // come back the moment the slot is re-resolved. + // Its cycle has closed undismissed, so a one-shot alarm is switched off + // as on every other such close, rather than armed for tomorrow. states.ringing()?.takeIf { it.alarmId != alarmId }?.let { other -> ring.stopRinging(other.alarmId) states.save(other.copy(ringingSince = null, snoozedUntil = null, snoozeCount = 0)) + alarms.find(other.alarmId)?.takeIf { !it.repeatDays.isRepeating }?.let { disableOrDeleteLocked(it) } } + // `ringingSince` is cleared too: this fire opens the ring afresh, and a + // stale value left behind would let the re-resolution below close (and + // switch off) the very alarm that is about to ring. val opened = if (isSnoozeFire) { // The cycle is the same one: the count and the watermark carry over. - state.copy(snoozedUntil = null) + state.copy(ringingSince = null, snoozedUntil = null) } else { - state.copy(snoozedUntil = null, snoozeCount = 0, handledOccurrence = scheduledFor) + state.copy(ringingSince = null, snoozedUntil = null, snoozeCount = 0, handledOccurrence = scheduledFor) } // The watermark is written before anything else can interrupt, and the // slot is re-resolved while the alarm is not yet marked as ringing — so @@ -345,18 +339,30 @@ class AlarmEngine @Inject constructor( private suspend fun resumeRingingIfAnyLocked(): Long? { val state = states.ringing() ?: return null val since = state.ringingSince ?: return null - val silenceAfter = settings.currentDefaults().alarmSilenceAfter - // Slept through it: leave it to the next resolution to close the cycle. - if (wallClock.now() - since >= silenceAfter) return null val alarm = alarms.find(state.alarmId)?.takeIf { it.enabled } ?: return null + // Slept through it: leave it to the next resolution to close the cycle. + if (!rearmIfInsideWindowLocked(alarm.id, since)) return null ring.startRinging(alarm.id) - // The backstop is measured from when the ring started, not from now, so - // a reboot does not buy the alarm a fresh window. - scheduler.scheduleAutoSilence(since + silenceAfter, alarm.id) return alarm.id } + /** + * The one rule for measuring a ring against "Silence after": still inside + * the window ⇒ the backstop is (re-)armed at its end and this returns true; + * run out ⇒ false, and the caller closes or drops it. Measured from when the + * ring started, so neither a reboot nor a setting change buys it a fresh + * window — or from now, if the clock has since moved back behind that + * start, so a clock change cannot stretch a ring past one window either. + */ + private suspend fun rearmIfInsideWindowLocked(alarmId: Long, since: Instant): Boolean { + val now = wallClock.now() + val silenceAfter = settings.currentDefaults().alarmSilenceAfter + if (now - since >= silenceAfter) return false + scheduler.scheduleAutoSilence(minOf(since, now) + silenceAfter, alarmId) + return true + } + /** * Everything the resolver asked to be written, and nothing it did not — * plus stopping the sound of a ring it closed, which storage alone cannot do. diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt index 2982b15..a61b9ab 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt @@ -49,9 +49,8 @@ object SilenceAfter { * than the clamp's floor, which would be "Never". */ fun sanitise(minutes: Int): Int = when { - minutes < NEVER -> DEFAULT_MINUTES - minutes > HARD_STOP_MINUTES -> HARD_STOP_MINUTES - else -> minutes + minutes < MINUTES.first -> DEFAULT_MINUTES + else -> minutes.coerceAtMost(MINUTES.last) } /** The ring window [minutes] stands for, sanitised first so the engines never see an unofferable value. */ diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt index 50f13cd..b8540c4 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt @@ -990,6 +990,52 @@ class AlarmEngineTest { assertThat(scheduler.next).isNull() } + @Test + fun `a one-shot alarm displaced by another's fire is switched off`(@TempDir dir: Path) = runTest { + givenAlarm(id = 1L, hour = 7) + val sevenFive = offsetInstant("2026-06-10T07:05+02:00") + givenAlarm(id = 2L, hour = 7, minute = 5, repeatDays = RepeatDays.EVERY_DAY) + givenRingingAt(alarmId = 1L, occurrence = sevenToday, since = sevenToday) + wallClock.instant = sevenFive + val engine = engine(dir) + + engine.onFire(alarmId = 2L, scheduledFor = sevenFive) + + assertThat(alarms.find(1L)?.enabled).isFalse() + assertThat(ring.ringing.value).isEqualTo(2L) + } + + @Test + fun `a stale ring left in storage cannot switch off the alarm that is firing`(@TempDir dir: Path) = + runTest { + givenAlarm() + val yesterday = offsetInstant("2026-06-09T07:00+02:00") + givenRingingAt(alarmId = 1L, occurrence = yesterday, since = yesterday) + wallClock.instant = sevenToday + val engine = engine(dir) + + val outcome = engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + + assertThat(outcome).isEqualTo(FireOutcome.Ringing(1L)) + assertThat(alarms.find(1L)?.enabled).isTrue() + assertThat(states.state(1L).ringingSince).isEqualTo(sevenToday) + } + + @Test + fun `a clock moved back mid-ring cannot stretch it past one window`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val settings = settings(dir) + val engine = engineOver(settings) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday - 30.minutes + + settings.setAlarmSilenceAfterMinutes(5) + engine.onSilenceAfterChanged() + + assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday - 30.minutes + 5.minutes, 1L)) + } + // --- upcoming() --- @Test diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b035745..4344b71 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1229,7 +1229,9 @@ genuinely ringing alarm sounding with its backstop intact. **At most one alarm rings, and a newly-firing alarm takes over.** Two ringtones at once is not a feature, and queueing invents a state machine nobody can debug at 07:00. The alarm that is displaced keeps its watermark, so it does not come -back the moment the slot is re-resolved. +back the moment the slot is re-resolved. Its cycle has closed undismissed, so a +displaced one-shot alarm is switched off (or deleted, if transient), as on +every other close. `snoozeLimit == 0` means **snoozing is disabled**, not unlimited; v1 offers no unlimited, and "0 means infinite" is a trap. A refused snooze *dismisses*; it From 4cb4b6b6eb8f4a60028a0f2cb1a351769b475f44 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Wed, 21 Oct 2026 19:20:25 +0200 Subject: [PATCH 4/8] fix(alarms): keep clock changes and setting writes inside one window Third round of review fixes for the silence-after setting. A backstop that fires while the clock is still behind the ring's start now closes the ring instead of re-arming in a loop until the wall clock catches up. A clock change re-measures a ring in progress before it reschedules: a clock moved back re-arms the backstop at most one window from the moved clock, and one moved forward past the window closes the ring. The engine now owns the alarm setting's write. setAlarmSilenceAfter stores it and re-measures the ring under one lock and without cancellation, so a write can no longer land without the re-measure. A snooze the resolver drops takes its "Snoozed until" notification with it. SNOOZE_GRACE is derived from the default window, and the silence-after picker moves to ui/settings, since it is not a per-alarm override. Refs #17 --- .../clockula/alarm/AlarmEngine.kt | 41 +++++++++-- .../clockula/domain/alarm/AlarmRing.kt | 3 +- .../clockula/ui/alarms/OverridePickers.kt | 32 --------- .../ui/settings/AlarmDefaultsScreen.kt | 2 - .../clockula/ui/settings/SettingsViewModel.kt | 3 +- .../ui/settings/SilenceAfterPicker.kt | 39 ++++++++++ .../ui/settings/TimerDefaultsScreen.kt | 2 - .../clockula/alarm/AlarmEngineTest.kt | 72 ++++++++++++++++--- docs/ARCHITECTURE.md | 18 +++-- 9 files changed, 151 insertions(+), 61 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SilenceAfterPicker.kt diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt index ea5ce1d..f04f7ca 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt @@ -21,6 +21,7 @@ import de.jeanlucmakiola.clockula.domain.resolveSettings import de.jeanlucmakiola.clockula.domain.time.WallClock import de.jeanlucmakiola.clockula.domain.time.ZoneProvider import de.jeanlucmakiola.clockula.system.RebootRepair +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged @@ -29,6 +30,8 @@ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant import javax.inject.Inject @@ -84,8 +87,11 @@ class AlarmEngine @Inject constructor( // A backstop armed for a shorter window than the one now chosen ("Silence // after" was raised mid-ring): the ring still has time, so the backstop - // moves rather than ending it early. - if (rearmIfInsideWindowLocked(alarmId, since)) return@withLock + // moves rather than ending it early. A negative age is a clock moved back + // behind the ring's start; the backstop was then armed a window from that + // moved clock, so the ring has had its window and closes. + val age = wallClock.now() - since + if (age >= Duration.ZERO && rearmIfInsideWindowLocked(alarmId, since)) return@withLock // Missed, not snoozed: the ring stops, the cycle closes, the next // occurrence is scheduled. There is no missed-alarm notification in v1. @@ -93,15 +99,25 @@ class AlarmEngine @Inject constructor( } /** - * "Silence after" changed. A ring in progress is measured against the new + * Writes the alarms' "Silence after" — the engine is its only writer outside + * a backup restore — and measures a ring in progress against the new * window at once: one already past it closes as missed, exactly as the * backstop would close it, and one still inside it has its backstop moved * to the new end. Measured from when the ring started, so changing the * setting back and forth cannot buy a ring a fresh window. */ - suspend fun onSilenceAfterChanged(): Unit = lock.withLock { - val state = states.ringing() ?: return@withLock - val since = state.ringingSince ?: return@withLock + suspend fun setAlarmSilenceAfter(minutes: Int): Unit = withContext(NonCancellable) { + // Not cancellable: a write that lands without the re-measure would leave + // a ring in progress on the old window. + lock.withLock { + settings.setAlarmSilenceAfterMinutes(minutes) + remeasureRingLocked() + } + } + + private suspend fun remeasureRingLocked() { + val state = states.ringing() ?: return + val since = state.ringingSince ?: return if (!rearmIfInsideWindowLocked(state.alarmId, since)) closeCycleLocked(state.alarmId, state) } @@ -155,7 +171,15 @@ class AlarmEngine @Inject constructor( rescheduleLocked() } - suspend fun onSystemTimeOrZoneChanged(): ScheduledFire? = reschedule() + /** + * The backstop is a wall-clock registration, so a clock change moves it. A + * ring in progress is re-measured first: a clock moved forward past its + * window closes it, one moved back re-arms it a window from now at most. + */ + suspend fun onSystemTimeOrZoneChanged(): ScheduledFire? = lock.withLock { + remeasureRingLocked() + rescheduleLocked() + } suspend fun onPackageReplaced(): ScheduledFire? = reschedule() @@ -369,6 +393,9 @@ class AlarmEngine @Inject constructor( */ private suspend fun persist(alarm: Alarm, before: AlarmRingState, resolution: AlarmResolution) { if (resolution.state != before) states.save(resolution.state) + // A snooze the resolver dropped (it never fired, or the alarm was + // switched off) takes its "Snoozed until" notification with it. + if (before.snoozedUntil != null && resolution.state.snoozedUntil == null) notifier.clearSnoozed(alarm.id) // The resolver closed a ring: its window ran out before the backstop // fired ("Silence after" was shortened mid-ring, or the clock jumped), // or the alarm was switched off while ringing. Storage now says it is diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt index 6d11d99..a062c0e 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.clockula.domain.alarm +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes @@ -23,7 +24,7 @@ object AlarmRing { * window or this, whichever is longer, so a short window never makes a * promised snooze easier to lose. */ - val SNOOZE_GRACE: Duration = 10.minutes + val SNOOZE_GRACE: Duration = SilenceAfter.DEFAULT_MINUTES.minutes /** How late a snooze may come due and still ring, given the ring window. */ fun snoozeGrace(silenceAfter: Duration): Duration = maxOf(silenceAfter, SNOOZE_GRACE) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt index 6046147..4ba9867 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/OverridePickers.kt @@ -5,7 +5,6 @@ import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import de.jeanlucmakiola.clockula.R import de.jeanlucmakiola.clockula.domain.DismissChallenge -import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.floret.components.OptionPicker /** @@ -68,37 +67,6 @@ internal fun challengeText(challenge: DismissChallenge): String = stringResource }, ) -/** [SilenceAfter.NEVER] is "Never" in words, never "0 minutes". */ -@Composable -internal fun silenceAfterText(minutes: Int): String = if (minutes == SilenceAfter.NEVER) { - stringResource(R.string.silence_after_never) -} else { - pluralStringResource(R.plurals.silence_after_minutes, minutes, minutes) -} - -/** - * "Silence after" is app-wide only (#17): no alarm or timer overrides it, so - * this picker has no "App default" rung. A stored value no choice matches (a - * backup can carry any minute up to the hard stop) is offered too, in its - * place, so the picker always shows what is selected and can put it back. - */ -@Composable -internal fun SilenceAfterPicker( - selected: Int, - onSelect: (Int) -> Unit, - onDismiss: () -> Unit, -) { - val finite = (SilenceAfter.CHOICES + selected).filter { it != SilenceAfter.NEVER }.distinct().sorted() - OptionPicker( - title = stringResource(R.string.settings_silence_after), - options = finite + SilenceAfter.NEVER, - selected = selected, - label = { silenceAfterText(it) }, - onSelect = onSelect, - onDismiss = onDismiss, - ) -} - @Composable internal fun VibratePicker( stored: Boolean?, diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/AlarmDefaultsScreen.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/AlarmDefaultsScreen.kt index 4942a8e..0a56420 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/AlarmDefaultsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/AlarmDefaultsScreen.kt @@ -12,13 +12,11 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.clockula.R import de.jeanlucmakiola.clockula.ui.alarms.DismissChallengePicker -import de.jeanlucmakiola.clockula.ui.alarms.SilenceAfterPicker import de.jeanlucmakiola.clockula.ui.alarms.SnoozeLengthPicker import de.jeanlucmakiola.clockula.ui.alarms.SnoozeLimitPicker import de.jeanlucmakiola.clockula.ui.alarms.VibratePicker import de.jeanlucmakiola.clockula.ui.alarms.VolumeRampPicker import de.jeanlucmakiola.clockula.ui.alarms.challengeText -import de.jeanlucmakiola.clockula.ui.alarms.silenceAfterText import de.jeanlucmakiola.clockula.ui.alarms.snoozeLimitText import de.jeanlucmakiola.clockula.ui.alarms.snoozeMinutesText import de.jeanlucmakiola.clockula.ui.alarms.vibrateText diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt index 213ac9c..f8697fa 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt @@ -146,8 +146,7 @@ class SettingsViewModel @Inject internal constructor( /** The engine re-measures a ring in progress against the new window at once. */ fun onAlarmSilenceAfterChanged(minutes: Int) = viewModelScope.launch { - settings.setAlarmSilenceAfterMinutes(minutes) - alarmEngine.onSilenceAfterChanged() + alarmEngine.setAlarmSilenceAfter(minutes) } fun onTimerSilenceAfterChanged(minutes: Int) = diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SilenceAfterPicker.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SilenceAfterPicker.kt new file mode 100644 index 0000000..e926f70 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SilenceAfterPicker.kt @@ -0,0 +1,39 @@ +package de.jeanlucmakiola.clockula.ui.settings + +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import de.jeanlucmakiola.clockula.R +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter +import de.jeanlucmakiola.floret.components.OptionPicker + +/** [SilenceAfter.NEVER] is "Never" in words, never "0 minutes". */ +@Composable +internal fun silenceAfterText(minutes: Int): String = if (minutes == SilenceAfter.NEVER) { + stringResource(R.string.silence_after_never) +} else { + pluralStringResource(R.plurals.silence_after_minutes, minutes, minutes) +} + +/** + * "Silence after" is app-wide only (#17): no alarm or timer overrides it, so + * this picker has no "App default" rung. A stored value no choice matches (a + * backup can carry any minute up to the hard stop) is offered too, in its + * place, so the picker always shows what is selected and can put it back. + */ +@Composable +internal fun SilenceAfterPicker( + selected: Int, + onSelect: (Int) -> Unit, + onDismiss: () -> Unit, +) { + val finite = (SilenceAfter.CHOICES + selected).filter { it != SilenceAfter.NEVER }.distinct().sorted() + OptionPicker( + title = stringResource(R.string.settings_silence_after), + options = finite + SilenceAfter.NEVER, + selected = selected, + label = { silenceAfterText(it) }, + onSelect = onSelect, + onDismiss = onDismiss, + ) +} diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/TimerDefaultsScreen.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/TimerDefaultsScreen.kt index 90ffbb2..a1396ed 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/TimerDefaultsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/TimerDefaultsScreen.kt @@ -11,8 +11,6 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.clockula.R -import de.jeanlucmakiola.clockula.ui.alarms.SilenceAfterPicker -import de.jeanlucmakiola.clockula.ui.alarms.silenceAfterText import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.Position diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt index b8540c4..b469608 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt @@ -50,6 +50,7 @@ import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.nio.file.Path +import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @@ -937,8 +938,7 @@ class AlarmEngineTest { engine.onFire(alarmId = 1L, scheduledFor = sevenToday) wallClock.instant = sevenToday + 3.minutes - settings.setAlarmSilenceAfterMinutes(SilenceAfter.NEVER) - engine.onSilenceAfterChanged() + engine.setAlarmSilenceAfter(SilenceAfter.NEVER) assertThat(ring.ringing.value).isEqualTo(1L) assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + SilenceAfter.HARD_STOP, 1L)) @@ -953,8 +953,7 @@ class AlarmEngineTest { engine.onFire(alarmId = 1L, scheduledFor = sevenToday) wallClock.instant = sevenToday + 5.minutes - settings.setAlarmSilenceAfterMinutes(1) - engine.onSilenceAfterChanged() + engine.setAlarmSilenceAfter(1) assertThat(ring.ringing.value).isNull() assertThat(states.state(1L).ringingSince).isNull() @@ -969,8 +968,7 @@ class AlarmEngineTest { val settings = settings(dir) val engine = engineOver(settings) - settings.setAlarmSilenceAfterMinutes(1) - engine.onSilenceAfterChanged() + engine.setAlarmSilenceAfter(1) assertThat(ring.events).isEmpty() assertThat(scheduler.autoSilence).isNull() @@ -1030,12 +1028,70 @@ class AlarmEngineTest { engine.onFire(alarmId = 1L, scheduledFor = sevenToday) wallClock.instant = sevenToday - 30.minutes - settings.setAlarmSilenceAfterMinutes(5) - engine.onSilenceAfterChanged() + engine.setAlarmSilenceAfter(5) assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday - 30.minutes + 5.minutes, 1L)) } + @Test + fun `a backstop reached with the clock still behind the ring's start closes it`(@TempDir dir: Path) = + runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val engine = engine(dir) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday - 20.minutes + + engine.onAutoSilence(1L) + + assertThat(ring.ringing.value).isNull() + assertThat(states.state(1L).ringingSince).isNull() + } + + @Test + fun `a clock moved back mid-ring re-arms the backstop a window from now`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val engine = engine(dir) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday - 1.hours + + engine.onSystemTimeOrZoneChanged() + + assertThat(ring.ringing.value).isEqualTo(1L) + assertThat(scheduler.autoSilence) + .isEqualTo(Registration(sevenToday - 1.hours + ClockDefaults().alarmSilenceAfter, 1L)) + } + + @Test + fun `a clock moved forward past the window closes the ring`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val engine = engine(dir) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday + 1.hours + + engine.onSystemTimeOrZoneChanged() + + assertThat(ring.ringing.value).isNull() + assertThat(states.state(1L).ringingSince).isNull() + assertThat(scheduler.autoSilence).isNull() + } + + @Test + fun `a snooze the resolver drops takes its notification with it`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + states.save( + ringState(snoozedUntil = sevenToday + 9.minutes, snoozeCount = 1, handledOccurrence = sevenToday), + ) + wallClock.instant = sevenToday + 2.hours + val engine = engine(dir) + + engine.reschedule() + + assertThat(notifier.cleared).contains(1L) + } + // --- upcoming() --- @Test diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4344b71..9beeda0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1179,13 +1179,17 @@ go through `SilenceAfter.sanitise` on read, on write and from a backup: over 60 is 60, so no value can make a ring outlast the hard stop, and a negative one is the default rather than the clamp's floor, which would be "Never". -Changing the setting mid-ring applies at once. The settings screen calls -`AlarmEngine.onSilenceAfterChanged()`, which measures the ring in progress -against the new window from when it *started*: past it, the cycle closes as -missed through `closeCycleLocked`; inside it, the backstop moves to the new -end. As a second line, `onAutoSilence` re-arms rather than closes a ring that -is still inside the current window, so a backstop armed for a shorter one can -never end a ring early. +Changing the setting mid-ring applies at once. The settings screen writes it +through `AlarmEngine.setAlarmSilenceAfter()`, which stores it and, under the +same lock and uncancellably, measures the ring in progress against the new +window from when it *started*: past it, the cycle closes as missed through +`closeCycleLocked`; inside it, the backstop moves to the new end. As a second +line, `onAutoSilence` re-arms rather than closes a ring that is still inside +the current window, so a backstop armed for a shorter one can never end a ring +early. A clock change re-measures the ring the same way before rescheduling: +the backstop is a wall-clock registration, so a clock moved back re-arms it at +most one window from the moved clock (and the backstop then closes the ring, +its age still negative), and one moved forward past the window closes it. Whenever the resolver closes a ring (a clock jumped forward, a ringing alarm switched off, a reboot outlasting the window), `persist` stops the ring service From 0b7af0d57bee6090f860da75b887ef7dec2339da Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Wed, 21 Oct 2026 19:28:09 +0200 Subject: [PATCH 5/8] fix(alarms): let the backstop always close the ring it was armed for Fourth round of review fixes for the silence-after setting. onAutoSilence no longer re-arms a ring it measures as inside the window. After a clock moved back, that check could push the backstop out again and stretch the ring well past its window. Every writer of the window and every clock change already re-arms the backstop under the engine lock, so a backstop that fires has had its window, and it closes the ring as in v1. A one-shot alarm the resolver switches off as missed also clears a pending skip flag, as the resolver's other one-shot disable does. SNOOZE_GRACE is its own ten-minute constant again, not tied to the setting's default. Refs #17 --- .../clockula/alarm/AlarmEngine.kt | 16 ++++++---------- .../clockula/domain/alarm/AlarmResolver.kt | 1 + .../clockula/domain/alarm/AlarmRing.kt | 3 +-- .../clockula/alarm/AlarmEngineTest.kt | 17 ----------------- docs/ARCHITECTURE.md | 15 ++++++++------- 5 files changed, 16 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt index f04f7ca..471ba96 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt @@ -31,7 +31,6 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext -import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant import javax.inject.Inject @@ -83,15 +82,12 @@ class AlarmEngine @Inject constructor( suspend fun onAutoSilence(alarmId: Long): Unit = lock.withLock { val state = states.state(alarmId) - val since = state.ringingSince ?: return@withLock + if (state.ringingSince == null) return@withLock - // A backstop armed for a shorter window than the one now chosen ("Silence - // after" was raised mid-ring): the ring still has time, so the backstop - // moves rather than ending it early. A negative age is a clock moved back - // behind the ring's start; the backstop was then armed a window from that - // moved clock, so the ring has had its window and closes. - val age = wallClock.now() - since - if (age >= Duration.ZERO && rearmIfInsideWindowLocked(alarmId, since)) return@withLock + // The backstop is always armed for the window in force: every writer of + // "Silence after" and every clock change re-arms it under this lock. So + // when it fires, the ring has had its window, whatever the wall clock + // now says about its age. // Missed, not snoozed: the ring stops, the cycle closes, the next // occurrence is scheduled. There is no missed-alarm notification in v1. @@ -377,7 +373,7 @@ class AlarmEngine @Inject constructor( * run out ⇒ false, and the caller closes or drops it. Measured from when the * ring started, so neither a reboot nor a setting change buys it a fresh * window — or from now, if the clock has since moved back behind that - * start, so a clock change cannot stretch a ring past one window either. + * start, so a clock moved back adds at most the time already rung. */ private suspend fun rearmIfInsideWindowLocked(alarmId: Long, since: Instant): Boolean { val now = wallClock.now() diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt index c188d16..df22bd8 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmResolver.kt @@ -107,6 +107,7 @@ object AlarmResolver { nextFire = null, source = FireSource.NONE, state = working.copy(skippedOccurrence = null), + clearSkipFlag = alarm.skipNextOccurrence, disableAlarm = true, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt index a062c0e..6d11d99 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/alarm/AlarmRing.kt @@ -1,6 +1,5 @@ package de.jeanlucmakiola.clockula.domain.alarm -import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes @@ -24,7 +23,7 @@ object AlarmRing { * window or this, whichever is longer, so a short window never makes a * promised snooze easier to lose. */ - val SNOOZE_GRACE: Duration = SilenceAfter.DEFAULT_MINUTES.minutes + val SNOOZE_GRACE: Duration = 10.minutes /** How late a snooze may come due and still ring, given the ring window. */ fun snoozeGrace(silenceAfter: Duration): Duration = maxOf(silenceAfter, SNOOZE_GRACE) diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt index b469608..407d08f 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt @@ -912,23 +912,6 @@ class AlarmEngineTest { assertThat(entry.source).isEqualTo(FireSource.RESUMED_RING) } - @Test - fun `a backstop armed for a shorter window moves rather than firing early`(@TempDir dir: Path) = runTest { - givenAlarm(repeatDays = RepeatDays.EVERY_DAY) - wallClock.instant = sevenToday - val settings = settings(dir) - val engine = engineOver(settings) - engine.onFire(alarmId = 1L, scheduledFor = sevenToday) - settings.setAlarmSilenceAfterMinutes(25) - wallClock.instant = sevenToday + 10.minutes - - engine.onAutoSilence(1L) - - assertThat(ring.ringing.value).isEqualTo(1L) - assertThat(states.state(1L).ringingSince).isEqualTo(sevenToday) - assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + 25.minutes, 1L)) - } - @Test fun `raising silence-after mid-ring moves the backstop at once`(@TempDir dir: Path) = runTest { givenAlarm(repeatDays = RepeatDays.EVERY_DAY) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9beeda0..a4695e1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1183,13 +1183,14 @@ Changing the setting mid-ring applies at once. The settings screen writes it through `AlarmEngine.setAlarmSilenceAfter()`, which stores it and, under the same lock and uncancellably, measures the ring in progress against the new window from when it *started*: past it, the cycle closes as missed through -`closeCycleLocked`; inside it, the backstop moves to the new end. As a second -line, `onAutoSilence` re-arms rather than closes a ring that is still inside -the current window, so a backstop armed for a shorter one can never end a ring -early. A clock change re-measures the ring the same way before rescheduling: -the backstop is a wall-clock registration, so a clock moved back re-arms it at -most one window from the moved clock (and the backstop then closes the ring, -its age still negative), and one moved forward past the window closes it. +`closeCycleLocked`; inside it, the backstop moves to the new end. A clock +change re-measures the ring the same way before rescheduling: the backstop is a +wall-clock registration, so a clock moved back re-arms it at most one window +from the moved clock, and one moved forward past the window closes it. When the +backstop fires it always closes the ring, since every writer of the window and +every clock change has already re-armed it for the window in force. A clock +moved back mid-ring can still add up to the time already rung, which v1's fixed +backstop did not bound at all. Whenever the resolver closes a ring (a clock jumped forward, a ringing alarm switched off, a reboot outlasting the window), `persist` stops the ring service From 1689794da6ef900da8815f2b523e0698e6f4c887 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Wed, 21 Oct 2026 19:38:37 +0200 Subject: [PATCH 6/8] fix(alarms): re-anchor a ring behind a moved clock, own the timer write Fifth round of review fixes for the silence-after setting. A ring whose start the clock has moved back behind is now re-anchored to now, once, and stored. Before, the negative age lingered, and every later re-measure gave the ring a fresh window. With that fixed, onAutoSilence can safely re-arm again when the ring is still inside the window in force, so a backstop queued behind a raised setting no longer ends the ring early. The timers' setting is now written through TimerEngine.setTimerSilenceAfter, which records a session that has already outrun the old window as lapsed, so raising the setting cannot restart a timer that went quiet while no service pass was running. The lapse rule and the lapsed anchor live in TimerRingPolicy, shared by the policy and the engine. Refs #17 --- .../clockula/alarm/AlarmEngine.kt | 38 ++++++++++++------- .../clockula/domain/timer/TimerRingPolicy.kt | 20 +++++++--- .../clockula/timer/TimerEngine.kt | 21 +++++++++- .../clockula/ui/settings/SettingsViewModel.kt | 4 +- .../clockula/alarm/AlarmEngineTest.kt | 36 ++++++++++++++++++ .../clockula/timer/TimerEngineTest.kt | 17 +++++++++ .../ui/settings/SettingsViewModelTest.kt | 38 +++++++++++++++++++ docs/ARCHITECTURE.md | 17 ++++++--- 8 files changed, 166 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt index 471ba96..ab4c309 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/alarm/AlarmEngine.kt @@ -31,6 +31,7 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext +import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant import javax.inject.Inject @@ -82,12 +83,15 @@ class AlarmEngine @Inject constructor( suspend fun onAutoSilence(alarmId: Long): Unit = lock.withLock { val state = states.state(alarmId) - if (state.ringingSince == null) return@withLock + val since = state.ringingSince ?: return@withLock - // The backstop is always armed for the window in force: every writer of - // "Silence after" and every clock change re-arms it under this lock. So - // when it fires, the ring has had its window, whatever the wall clock - // now says about its age. + // A ring still inside the window in force keeps ringing: a backstop + // broadcast already queued when "Silence after" was raised must not end + // the time just granted. A negative age is a clock moved back whose + // TIME_SET has not been handled yet; the backstop has then had its + // window in real time, and closes the ring as in v1. + val age = wallClock.now() - since + if (age >= Duration.ZERO && rearmIfInsideWindowLocked(state)) return@withLock // Missed, not snoozed: the ring stops, the cycle closes, the next // occurrence is scheduled. There is no missed-alarm notification in v1. @@ -113,8 +117,7 @@ class AlarmEngine @Inject constructor( private suspend fun remeasureRingLocked() { val state = states.ringing() ?: return - val since = state.ringingSince ?: return - if (!rearmIfInsideWindowLocked(state.alarmId, since)) closeCycleLocked(state.alarmId, state) + if (!rearmIfInsideWindowLocked(state)) closeCycleLocked(state.alarmId, state) } /** [minutesOverride] is a one-off, already clamped; it is never persisted anywhere (M9 D15). */ @@ -358,10 +361,9 @@ class AlarmEngine @Inject constructor( private suspend fun resumeRingingIfAnyLocked(): Long? { val state = states.ringing() ?: return null - val since = state.ringingSince ?: return null val alarm = alarms.find(state.alarmId)?.takeIf { it.enabled } ?: return null // Slept through it: leave it to the next resolution to close the cycle. - if (!rearmIfInsideWindowLocked(alarm.id, since)) return null + if (!rearmIfInsideWindowLocked(state)) return null ring.startRinging(alarm.id) return alarm.id @@ -372,14 +374,24 @@ class AlarmEngine @Inject constructor( * the window ⇒ the backstop is (re-)armed at its end and this returns true; * run out ⇒ false, and the caller closes or drops it. Measured from when the * ring started, so neither a reboot nor a setting change buys it a fresh - * window — or from now, if the clock has since moved back behind that - * start, so a clock moved back adds at most the time already rung. + * window. + * + * A clock moved back behind that start is re-anchored to now and stored, so + * a negative age never lingers for a later re-measure to read as "a whole + * window left": a clock moved back adds at most the time already rung, once. */ - private suspend fun rearmIfInsideWindowLocked(alarmId: Long, since: Instant): Boolean { + private suspend fun rearmIfInsideWindowLocked(state: AlarmRingState): Boolean { + val stored = state.ringingSince ?: return false val now = wallClock.now() + val since = if (now < stored) { + states.save(state.copy(ringingSince = now)) + now + } else { + stored + } val silenceAfter = settings.currentDefaults().alarmSilenceAfter if (now - since >= silenceAfter) return false - scheduler.scheduleAutoSilence(minOf(since, now) + silenceAfter, alarmId) + scheduler.scheduleAutoSilence(since + silenceAfter, state.alarmId) return true } diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt index f9bce4f..d55a816 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.clockula.domain.timer import de.jeanlucmakiola.clockula.domain.ClockDefaults import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter +import kotlin.time.Duration import kotlin.time.Instant sealed interface TimerRingDecision { @@ -35,6 +36,17 @@ data class TimerRingOutcome( /** The whole audio arbitration, as a pure function of current state (D9–D11). */ object TimerRingPolicy { + /** Whether a session anchored at [soundingSince] has run out of [window] by [now]. The one rule, for every reader. */ + fun isLapsed(soundingSince: Instant?, now: Instant, window: Duration): Boolean = + soundingSince != null && now - soundingSince >= window + + /** + * What a lapsed session's anchor is stored as: moved back past the longest + * window there is, so it stays run out whatever "Silence after" becomes. + */ + fun lapsedAnchor(soundingSince: Instant, now: Instant): Instant = + minOf(soundingSince, now - SilenceAfter.HARD_STOP) + /** * [expired] is `TimerReadings.expired`'s output, so its first element is * already the subject (D10). Nothing here is an event: a timer suppressed @@ -56,13 +68,11 @@ object TimerRingPolicy { // Auto-silence before suppression: a window that has run out stays run // out, and an alarm ringing over it must not hand it a fresh one. val window = defaults.timerSilenceAfter - if (soundingSince != null && now - soundingSince >= window) { + if (soundingSince != null && isLapsed(soundingSince, now, window)) { return TimerRingOutcome( TimerRingDecision.AutoSilenced(subject.timer.id), - // Stays run out whatever "Silence after" becomes: the anchor is - // moved back past the longest window there is, so raising the - // setting later cannot start a silenced timer ringing again. - soundingSince = minOf(soundingSince, now - SilenceAfter.HARD_STOP), + // Raising the setting later cannot start a silenced timer ringing again. + soundingSince = lapsedAnchor(soundingSince, now), ) } diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/timer/TimerEngine.kt b/app/src/main/java/de/jeanlucmakiola/clockula/timer/TimerEngine.kt index ea12615..26dbbcb 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/timer/TimerEngine.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/timer/TimerEngine.kt @@ -14,9 +14,11 @@ import de.jeanlucmakiola.clockula.domain.timer.TimerRing import de.jeanlucmakiola.clockula.domain.timer.TimerRingDecision import de.jeanlucmakiola.clockula.domain.timer.TimerRingPolicy import de.jeanlucmakiola.clockula.system.RebootRepair +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.first import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext import kotlin.time.Duration import kotlin.time.Instant import javax.inject.Inject @@ -115,6 +117,23 @@ class TimerEngine @Inject constructor( suspend fun serviceState(alreadyAlerted: Boolean): TimerServiceState = lock.withLock { serviceStateLocked(alreadyAlerted) } + /** + * Writes the timers' "Silence after". A session that has already run out of + * the old window is recorded as lapsed first — even when no service pass was + * there to see it go — so raising the setting cannot start it sounding + * again. Not cancellable, so the write never lands without that record. + */ + suspend fun setTimerSilenceAfter(minutes: Int): Unit = withContext(NonCancellable) { + lock.withLock { + val anchor = ringState.current() + val now = wall.now() + if (anchor != null && TimerRingPolicy.isLapsed(anchor, now, settings.currentDefaults().timerSilenceAfter)) { + ringState.set(TimerRingPolicy.lapsedAnchor(anchor, now)) + } + settings.setTimerSilenceAfterMinutes(minutes) + } + } + /** Starts IDLE/EXPIRED from the configured duration, resumes PAUSED. No-op when RUNNING. */ suspend fun start(timerId: Long): Unit = lock.withLock { val timer = timers.find(timerId) ?: return@withLock @@ -267,7 +286,7 @@ class TimerEngine @Inject constructor( private suspend fun dropLapsedSessionLocked() { val anchor = ringState.current() ?: return val window = settings.currentDefaults().timerSilenceAfter - if (wall.now() - anchor >= window) ringState.set(null) + if (TimerRingPolicy.isLapsed(anchor, wall.now(), window)) ringState.set(null) } private suspend fun serviceStateLocked(alreadyAlerted: Boolean): TimerServiceState { diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt index f8697fa..576fbf4 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModel.kt @@ -5,6 +5,7 @@ import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.clockula.alarm.AlarmEngine import de.jeanlucmakiola.clockula.alarm.DeviceStateReader +import de.jeanlucmakiola.clockula.timer.TimerEngine import de.jeanlucmakiola.clockula.data.appicon.LauncherIcon import de.jeanlucmakiola.clockula.data.appicon.LauncherIconManager import de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs @@ -50,6 +51,7 @@ import javax.inject.Inject class SettingsViewModel @Inject internal constructor( private val settings: SettingsPrefs, private val alarmEngine: AlarmEngine, + private val timerEngine: TimerEngine, private val ringtones: RingtoneCatalog, private val preview: RingtonePreviewer, private val worldClocks: WorldClockSource, @@ -150,7 +152,7 @@ class SettingsViewModel @Inject internal constructor( } fun onTimerSilenceAfterChanged(minutes: Int) = - viewModelScope.launch { settings.setTimerSilenceAfterMinutes(minutes) } + viewModelScope.launch { timerEngine.setTimerSilenceAfter(minutes) } // --- the default ringtone pickers --- diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt index 407d08f..18a3ff1 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/alarm/AlarmEngineTest.kt @@ -1075,6 +1075,42 @@ class AlarmEngineTest { assertThat(notifier.cleared).contains(1L) } + @Test + fun `a clock moved back re-anchors the ring once, so toggling the setting buys nothing`( + @TempDir dir: Path, + ) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val engine = engine(dir) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + val moved = sevenToday - 1.hours + wallClock.instant = moved + + engine.onSystemTimeOrZoneChanged() + wallClock.instant = moved + 4.minutes + engine.setAlarmSilenceAfter(25) + engine.setAlarmSilenceAfter(5) + + assertThat(states.state(1L).ringingSince).isEqualTo(moved) + assertThat(scheduler.autoSilence).isEqualTo(Registration(moved + 5.minutes, 1L)) + } + + @Test + fun `a backstop queued behind a raised window does not end the ring`(@TempDir dir: Path) = runTest { + givenAlarm(repeatDays = RepeatDays.EVERY_DAY) + wallClock.instant = sevenToday + val engine = engine(dir) + engine.setAlarmSilenceAfter(5) + engine.onFire(alarmId = 1L, scheduledFor = sevenToday) + wallClock.instant = sevenToday + 5.minutes + + engine.setAlarmSilenceAfter(25) + engine.onAutoSilence(1L) + + assertThat(ring.ringing.value).isEqualTo(1L) + assertThat(scheduler.autoSilence).isEqualTo(Registration(sevenToday + 25.minutes, 1L)) + } + // --- upcoming() --- @Test diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/timer/TimerEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/timer/TimerEngineTest.kt index 6f248c5..bd1acbe 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/timer/TimerEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/timer/TimerEngineTest.kt @@ -500,6 +500,23 @@ class TimerEngineTest { assertThat(state.silenceIn).isEqualTo(ClockDefaults().timerSilenceAfter - 30.seconds) } + /** #17 */ + @Test + fun `raising silence-after keeps a session that lapsed unseen silent`( + @TempDir tempDir: Path, + ) = runTest { + val harness = timerEngineHarness(tempDir) + harness.settings.setTimerSilenceAfterMinutes(1) + harness.given(expiredTimer(id = 1L)) + // The session opened ten minutes ago and no pass ran when its window ended. + harness.ringState.set(T0 - 10.minutes) + + harness.engine.setTimerSilenceAfter(25) + val state = harness.engine.serviceState(alreadyAlerted = true) + + assertThat(state.ring).isInstanceOf(TimerRingDecision.AutoSilenced::class.java) + } + /** #17 */ @Test fun `the ring session's window is the timer's silence-after setting`( diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModelTest.kt index f35a2b0..5945ea9 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/ui/settings/SettingsViewModelTest.kt @@ -6,6 +6,10 @@ import de.jeanlucmakiola.clockula.data.alarms.AlarmMapper import de.jeanlucmakiola.clockula.data.alarms.AlarmRepositoryImpl import de.jeanlucmakiola.clockula.data.alarms.AlarmStateRepositoryImpl import de.jeanlucmakiola.clockula.data.appicon.LauncherIcon +import de.jeanlucmakiola.clockula.data.prefs.BootStateStore +import de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.clockula.data.timers.TimerRepositoryImpl +import de.jeanlucmakiola.clockula.data.timers.TimerRingStateStore import de.jeanlucmakiola.clockula.domain.DismissChallenge import de.jeanlucmakiola.clockula.domain.RepeatDays import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter @@ -14,16 +18,26 @@ import de.jeanlucmakiola.clockula.testing.FakeAlarmDao import de.jeanlucmakiola.clockula.testing.FakeAlarmNotifier import de.jeanlucmakiola.clockula.testing.FakeAlarmScheduler import de.jeanlucmakiola.clockula.testing.FakeAlarmStateDao +import de.jeanlucmakiola.clockula.testing.FakeAlarmRingStatus +import de.jeanlucmakiola.clockula.testing.FakeBootIdProvider import de.jeanlucmakiola.clockula.testing.FakeDeviceStateReader +import de.jeanlucmakiola.clockula.testing.FakeElapsedRealtimeClock import de.jeanlucmakiola.clockula.testing.FakeLauncherIconManager import de.jeanlucmakiola.clockula.testing.FakeRingtoneCatalog import de.jeanlucmakiola.clockula.testing.FakeRingCoordinator import de.jeanlucmakiola.clockula.testing.FakeRingtonePreviewer +import de.jeanlucmakiola.clockula.testing.FakeTimerDao +import de.jeanlucmakiola.clockula.testing.FakeTimerScheduler +import de.jeanlucmakiola.clockula.testing.FakeTimerServiceHandle import de.jeanlucmakiola.clockula.testing.FakeWallClock import de.jeanlucmakiola.clockula.testing.FakeZoneProvider import de.jeanlucmakiola.clockula.testing.MainDispatcherExtension import de.jeanlucmakiola.clockula.testing.alarmAt import de.jeanlucmakiola.clockula.testing.RecordingRebootRepair +import de.jeanlucmakiola.clockula.testing.RecordingStopwatchRepository +import de.jeanlucmakiola.clockula.system.RebootRepair +import de.jeanlucmakiola.clockula.timer.TimerEngine +import de.jeanlucmakiola.floret.prefs.PrefStore import de.jeanlucmakiola.clockula.testing.instantAt import de.jeanlucmakiola.clockula.testing.worldClockHarness import de.jeanlucmakiola.floret.prefs.ThemeMode @@ -39,6 +53,7 @@ import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.io.TempDir import java.nio.file.Path import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds /** * The real [SettingsViewModel] over the real [de.jeanlucmakiola.clockula.data.prefs.SettingsPrefs] @@ -61,6 +76,28 @@ class SettingsViewModelTest { private val ring = FakeRingCoordinator() private lateinit var alarmEngine: AlarmEngine + /** The timer engine "Silence after" writes through, over fakes and the harness's own store. */ + private fun timerEngine(settings: SettingsPrefs, store: PrefStore): TimerEngine { + val elapsed = FakeElapsedRealtimeClock(1_000.seconds) + val timers = TimerRepositoryImpl(FakeTimerDao(), elapsed, wallClock) + return TimerEngine( + timers = timers, + settings = settings, + ringState = TimerRingStateStore(store), + scheduler = FakeTimerScheduler(), + service = FakeTimerServiceHandle(), + alarmRing = FakeAlarmRingStatus(), + rebootRepair = RebootRepair( + bootIds = FakeBootIdProvider(), + bootState = BootStateStore(store), + timers = timers, + stopwatch = RecordingStopwatchRepository(), + ), + elapsed = elapsed, + wall = wallClock, + ) + } + private fun TestScope.newViewModel( tempDir: Path, launcherIcons: FakeLauncherIconManager = FakeLauncherIconManager(), @@ -80,6 +117,7 @@ class SettingsViewModelTest { return SettingsViewModel( settings = harness.settings, alarmEngine = alarmEngine, + timerEngine = timerEngine(harness.settings, harness.store), ringtones = FakeRingtoneCatalog(), preview = FakeRingtonePreviewer(), worldClocks = harness.source, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a4695e1..0148559 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1186,11 +1186,18 @@ window from when it *started*: past it, the cycle closes as missed through `closeCycleLocked`; inside it, the backstop moves to the new end. A clock change re-measures the ring the same way before rescheduling: the backstop is a wall-clock registration, so a clock moved back re-arms it at most one window -from the moved clock, and one moved forward past the window closes it. When the -backstop fires it always closes the ring, since every writer of the window and -every clock change has already re-armed it for the window in force. A clock -moved back mid-ring can still add up to the time already rung, which v1's fixed -backstop did not bound at all. +from the moved clock, and one moved forward past the window closes it. A ring +whose start the clock has moved back behind is re-anchored to now and stored, +once, so a later re-measure cannot read the negative age as a whole window +left; a clock moved back mid-ring adds at most the time already rung, which +v1's fixed backstop did not bound at all. A backstop that fires while the ring +is still inside the window in force (one queued behind a raised setting) +re-arms instead of closing. + +The timers' setting is written through `TimerEngine.setTimerSilenceAfter()` for +the same reason: under the engine's lock it first records a session that has +already run out of the old window as lapsed, even one no service pass saw go +quiet, so raising the setting cannot start it sounding again. Whenever the resolver closes a ring (a clock jumped forward, a ringing alarm switched off, a reboot outlasting the window), `persist` stops the ring service From 6239ca047794f7e8462d3f93929e68eb3594a97d Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Wed, 21 Oct 2026 19:45:44 +0200 Subject: [PATCH 7/8] refactor(settings): read a silence-after of an hour or more as Never A stored value of 60 minutes or more now reads as Never, which rings that long anyway. The picker no longer shows both "60 minutes" and "Never" for the same window. Also drops a redundant null check in TimerRingPolicy. Refs #17 --- .../de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt | 7 ++++--- .../clockula/domain/timer/TimerRingPolicy.kt | 2 +- .../jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt | 2 +- .../clockula/data/prefs/SettingsPrefsTest.kt | 3 ++- docs/ARCHITECTURE.md | 4 ++-- docs/BACKUP.md | 4 ++-- 6 files changed, 12 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt index a61b9ab..0137a19 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt @@ -44,13 +44,14 @@ object SilenceAfter { /** * What a stored value is read and written as, from a picker, a hand-edited - * file or a backup. Too long is the hard stop, which is what it would ring - * for anyway. Negative is nothing anyone chose, so it is the default rather + * file or a backup. The hard stop or longer is "Never", which rings that + * long anyway, so the picker never shows two names for one window. Negative is nothing anyone chose, so it is the default rather * than the clamp's floor, which would be "Never". */ fun sanitise(minutes: Int): Int = when { minutes < MINUTES.first -> DEFAULT_MINUTES - else -> minutes.coerceAtMost(MINUTES.last) + minutes >= HARD_STOP_MINUTES -> NEVER + else -> minutes } /** The ring window [minutes] stands for, sanitised first so the engines never see an unofferable value. */ diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt index d55a816..2b67e41 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/timer/TimerRingPolicy.kt @@ -68,7 +68,7 @@ object TimerRingPolicy { // Auto-silence before suppression: a window that has run out stays run // out, and an alarm ringing over it must not hand it a fresh one. val window = defaults.timerSilenceAfter - if (soundingSince != null && isLapsed(soundingSince, now, window)) { + if (soundingSince != null && now - soundingSince >= window) { return TimerRingOutcome( TimerRingDecision.AutoSilenced(subject.timer.id), // Raising the setting later cannot start a silenced timer ringing again. diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt index 11817ca..f52c7cc 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/ClockPrefsTest.kt @@ -161,7 +161,7 @@ class ClockPrefsTest { prefs.setAlarmSilenceAfterMinutes(999) prefs.setTimerSilenceAfterMinutes(-3) - assertThat(prefs.defaults.first().alarmSilenceAfterMinutes).isEqualTo(60) + assertThat(prefs.defaults.first().alarmSilenceAfterMinutes).isEqualTo(SilenceAfter.NEVER) assertThat(prefs.defaults.first().timerSilenceAfterMinutes).isEqualTo(SilenceAfter.DEFAULT_MINUTES) dataStore.updateData { stored -> diff --git a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefsTest.kt index 2abb2d3..084ee05 100644 --- a/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/clockula/data/prefs/SettingsPrefsTest.kt @@ -7,6 +7,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.clockula.domain.ClockDefaults +import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter import de.jeanlucmakiola.clockula.domain.backup.BackupSettings import de.jeanlucmakiola.floret.prefs.Appearance import de.jeanlucmakiola.floret.prefs.PrefStore @@ -91,7 +92,7 @@ class SettingsPrefsTest { assertThat(prefs.currentDefaults().volumeRampSeconds).isEqualTo(60) assertThat(prefs.currentDefaults().alarmRingtoneUri).isNull() assertThat(prefs.currentDefaults().alarmSilenceAfterMinutes).isEqualTo(25) - assertThat(prefs.currentDefaults().timerSilenceAfterMinutes).isEqualTo(60) + assertThat(prefs.currentDefaults().timerSilenceAfterMinutes).isEqualTo(SilenceAfter.NEVER) assertThat(prefs.timerPresets.first()).containsExactly(1.minutes, 5.minutes).inOrder() } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0148559..f4eff10 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1175,8 +1175,8 @@ from ringing until its battery is flat, what bounds the ring services' wake locks, and what keeps a reboot hours later from resuming a ring nobody was there for. So "Never" maps to `SilenceAfter.HARD_STOP` (60 minutes), longer than any finite choice, and the settings hint says so in words. Stored values -go through `SilenceAfter.sanitise` on read, on write and from a backup: over 60 -is 60, so no value can make a ring outlast the hard stop, and a negative one is +go through `SilenceAfter.sanitise` on read, on write and from a backup: 60 or more +is "Never", so no value can make a ring outlast the hard stop, and a negative one is the default rather than the clamp's floor, which would be "Never". Changing the setting mid-ring applies at once. The settings screen writes it diff --git a/docs/BACKUP.md b/docs/BACKUP.md index c5d7799..ff25d84 100644 --- a/docs/BACKUP.md +++ b/docs/BACKUP.md @@ -151,8 +151,8 @@ other unknown field. are how long a ringing alarm or a finished timer keeps going before it stops on its own: whole minutes, with `0` meaning "Never" (which still stops after an hour). A file without them, from before the setting existed, imports as `10`, -the value it was made with. A value over 60 reads as 60 (which is what Never -rings for anyway); a negative one reads as the default, 10. +the value it was made with. A value of 60 or more reads as 0, "Never" (which +rings for that long anyway); a negative one reads as the default, 10. Every numeric/duration value is clamped on *apply* using the same ranges and encoding as the existing preference setters, never on parse. From 26a2b78225ce95ae583f0b0d505fe1b65725a12f Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Thu, 22 Oct 2026 11:06:23 +0200 Subject: [PATCH 8/8] docs(settings): say what SilenceAfter.MINUTES is for Refs #17 --- .../java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt index 0137a19..87fdd7f 100644 --- a/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt +++ b/app/src/main/java/de/jeanlucmakiola/clockula/domain/ring/SilenceAfter.kt @@ -36,7 +36,7 @@ object SilenceAfter { */ val WAKE_LOCK_TIMEOUT: Duration = HARD_STOP + 5.minutes - /** Every value [sanitise] lets through: [NEVER], or that many minutes up to the hard stop. */ + /** The range a stored value is measured against: below it is corrupt, and [sanitise] stores the hard stop itself as [NEVER]. */ val MINUTES: IntRange = NEVER..HARD_STOP_MINUTES /** The choices the pickers offer, in order: Google Clock's, so nothing here surprises. */