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