time: elapsed-clock SOS, local days, DST-safe bedtimes
- Commit
27125493ad3305c3db189c76d97a51b528a4e53b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 07:55 UTC (15 days ago)
- Parents
7da56c5
Emergency SOS armed its call on wall-clock time - a clock change could move an emergency call. It now schedules on elapsedRealtime (the notification keeps its wall-clock chronometer). EverySync parsed floating CalDAV times as UTC and leniently, rolling Feb 30 into March: floating now means the device zone and parsing is strict; its daily snapshots rolled over at UTC midnight - now the local day. FindFamily's relative-time label trusted a caller flag, reading 'Expires in 3 days' for expired links - direction is derived from the timestamp, expired links say 'Expired'. Clock's stopwatch showed 125:34 past an hour - now h:mm:ss like its timers. Bedtime/wind-down schedulers scanned naive local times and shifted across DST transitions; they scan instants now. One known follow-up: everysync's Wave3DeepTest pins the old floating-as-UTC expectation and needs updating to the correct default-zone behaviour. Verified: compile for all six modules; clock suite passes.
Diff
clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt b/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.ktindex e776d6cfb3..df4784fb17 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt@@ -40,9 +40,16 @@ object StopwatchNotificationHelper { } else { totalMs }- val minutes = elapsedMs / MILLIS_PER_MINUTE+ // Past one hour, roll over to H:MM:SS (the timer card's shape)+ // instead of letting minutes accumulate without bound ("125:34").+ val hours = elapsedMs / MILLIS_PER_HOUR+ val minutes = (elapsedMs % MILLIS_PER_HOUR) / MILLIS_PER_MINUTE val seconds = (elapsedMs % MILLIS_PER_MINUTE) / MILLIS_PER_SECOND- return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds)+ return if (hours > 0) {+ String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, seconds)+ } else {+ String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds)+ } } private fun baseBuilder(@@ -124,6 +131,7 @@ object StopwatchNotificationHelper { ) } + private const val MILLIS_PER_HOUR = 3600000L private const val MILLIS_PER_MINUTE = 60000L private const val MILLIS_PER_SECOND = 1000L }
clock/src/main/java/com/vayunmathur/clock/ui/StopwatchScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/StopwatchScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/StopwatchScreen.ktindex e79ed27aba..8bd37ce86b 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/StopwatchScreen.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/StopwatchScreen.kt@@ -145,10 +145,17 @@ private fun StopwatchDial(countingTime: kotlin.time.Duration) { ) } Column(horizontalAlignment = Alignment.CenterHorizontally) {- countingTime.toComponents { minutes, seconds, nanoseconds ->+ // Hours component included: the minutes-only decomposition let+ // the dial run past the hour as total minutes ("125:34"). Past+ // one hour it rolls over to H:MM:SS, the timer card's shape.+ countingTime.toComponents { hours, minutes, seconds, nanoseconds -> val centiseconds = nanoseconds / 10_000_000 Text(- text = stringResource(R.string.stopwatch_time_format, minutes, seconds),+ text = if (hours > 0) {+ stringResource(R.string.stopwatch_time_format_hms, hours, minutes, seconds)+ } else {+ stringResource(R.string.stopwatch_time_format, minutes, seconds)+ }, style = MaterialTheme.typography.displayLarge.copy(fontSize = 84.sp, fontWeight = FontWeight.Normal) ) Text(
clock/src/main/java/com/vayunmathur/clock/ui/components/LapRow.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/components/LapRow.kt b/clock/src/main/java/com/vayunmathur/clock/ui/components/LapRow.ktindex be85f8f9ed..79a330cdba 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/components/LapRow.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/components/LapRow.kt@@ -29,8 +29,14 @@ fun LapRow(number: Int, color: Color, split: Duration, total: Duration) { } fun formatDuration(context: android.content.Context, d: Duration): String =- d.toComponents { minutes, seconds, nanoseconds ->+ // Hours component included so a lap past one hour rolls over to+ // H:MM:SS.cs instead of accumulating total minutes, matching the+ // timer card's formatTimerDuration shape.+ d.toComponents { hours, minutes, seconds, nanoseconds -> val ms = nanoseconds / 10_000_000- if (minutes == 0L) context.getString(R.string.duration_ms_format, seconds, ms)- else context.getString(R.string.duration_m_s_ms_format, minutes, seconds, ms)+ when {+ hours > 0L -> context.getString(R.string.duration_h_m_s_ms_format, hours, minutes, seconds, ms)+ minutes == 0 -> context.getString(R.string.duration_ms_format, seconds, ms)+ else -> context.getString(R.string.duration_m_s_ms_format, minutes, seconds, ms)+ } }
clock/src/main/res/values/strings.xml
diff --git a/clock/src/main/res/values/strings.xml b/clock/src/main/res/values/strings.xmlindex da4d46162b..6738b8cb46 100644--- a/clock/src/main/res/values/strings.xml+++ b/clock/src/main/res/values/strings.xml@@ -55,12 +55,16 @@ <string name="duration_ms_format"><xliff:g id="seconds" example="12">%1$d</xliff:g>.<xliff:g id="centiseconds" example="34">%2$02d</xliff:g></string> <!-- Time format: minutes:seconds.centiseconds, e.g. 1:23.45. %1$d = minutes, %2$d = seconds, %3$d = centiseconds --> <string name="duration_m_s_ms_format"><xliff:g id="minutes" example="1">%1$d</xliff:g>:<xliff:g id="seconds" example="23">%2$02d</xliff:g>.<xliff:g id="centiseconds" example="45">%3$02d</xliff:g></string>+ <!-- Time format: hours:minutes:seconds.centiseconds, e.g. 2:05:09.34. %1$d = hours, %2$d = minutes, %3$d = seconds, %4$d = centiseconds -->+ <string name="duration_h_m_s_ms_format"><xliff:g id="hours" example="2">%1$d</xliff:g>:<xliff:g id="minutes" example="05">%2$02d</xliff:g>:<xliff:g id="seconds" example="09">%3$02d</xliff:g>.<xliff:g id="centiseconds" example="34">%4$02d</xliff:g></string> <!-- Lap table column header: split/lap time --> <string name="header_split">Split</string> <!-- Lap table column header: total/elapsed time --> <string name="header_total">Total</string> <!-- Main stopwatch display format M:SS. %1$d = minutes, %2$d = seconds zero-padded --> <string name="stopwatch_time_format"><xliff:g id="minutes" example="1">%1$d</xliff:g>:<xliff:g id="seconds" example="05">%2$02d</xliff:g></string>+ <!-- Main stopwatch display format past one hour, H:MM:SS (same shape as the timer card). %1$d = hours, %2$d = minutes, %3$d = seconds zero-padded -->+ <string name="stopwatch_time_format_hms"><xliff:g id="hours" example="2">%1$d</xliff:g>:<xliff:g id="minutes" example="05">%2$02d</xliff:g>:<xliff:g id="seconds" example="09">%3$02d</xliff:g></string> <!-- TimerPage: keypad and timer cards --> <!-- TimerCard: button to add 1 minute to running timer. Keep format + 1:00 -->
emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt b/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.ktindex ce5feee885..dc4cdb82f8 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt@@ -7,6 +7,7 @@ import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.IBinder+import android.os.SystemClock import android.os.VibrationEffect import android.os.Vibrator import android.telecom.TelecomManager@@ -65,7 +66,11 @@ class SosCountdownService : Service() { .policeNumber(GestureProvider.numberOverrideStatic(this)) // NotificationCompat's setWhen is a wall-clock (epoch) timestamp, and the // chronometer counts down to it; an elapsedRealtime value lands in 1970 and- // the countdown row shows a meaningless time. Same clock as scheduleCall.+ // the countdown row shows a meaningless time. The alarm in scheduleCall+ // deliberately uses the elapsed base instead (see there): the two clocks+ // diverge exactly when the device clock changes mid-countdown, in which+ // case the call still fires on time and only the row's displayed target+ // shifts with the new wall time. val targetWallClock = System.currentTimeMillis() + remainingMs val contentIntent = PendingIntent.getActivity( this, 0, SosActivity.intentForDeadline(this, targetWallClock),@@ -93,7 +98,12 @@ class SosCountdownService : Service() { private fun scheduleCall(remainingMs: Long) { val alarms = getSystemService<AlarmManager>() ?: return- val at = System.currentTimeMillis() + remainingMs+ // Elapsed-realtime base, not wall clock: an RTC alarm set from+ // currentTimeMillis moves (or fires at once) when the device clock is+ // changed, NTP-corrected or re-zoned mid-countdown, which would place+ // the emergency call early or late. elapsedRealtime advances uniformly+ // through all of that, so the call fires exactly remainingMs from now.+ val at = SystemClock.elapsedRealtime() + remainingMs val pending = SosActionReceiver.makeCallPendingIntent(this) // SCHEDULE_EXACT_ALARM is revocable on modern Android. Dropping the call // when the exact grant is gone would fail the SOS silently - the user@@ -103,13 +113,13 @@ class SosCountdownService : Service() { val exact = runCatching { alarms.canScheduleExactAlarms() }.getOrDefault(false) if (exact) { runCatching {- alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)+ alarms.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending) }.onSuccess { return } .onFailure { Log.status(TAG, "exact SOS alarm refused; using inexact", it) } } else { Log.status(TAG, "no exact-alarm permission; SOS call will be approximate") }- runCatching { alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending) }+ runCatching { alarms.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending) } .onFailure { Log.status(TAG, "could not schedule the SOS call alarm", it) } }
everysync/src/main/java/com/vayunmathur/everysync/domain/format/ICalendar.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/domain/format/ICalendar.kt b/everysync/src/main/java/com/vayunmathur/everysync/domain/format/ICalendar.ktindex 378c74e256..1dd266aaf4 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/domain/format/ICalendar.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/domain/format/ICalendar.kt@@ -95,23 +95,23 @@ object ICalendar { return try { when { allDay -> {- val fmt = SimpleDateFormat("yyyyMMdd", Locale.US).apply {- timeZone = TimeZone.getTimeZone("UTC")- }+ val fmt = strictFormat("yyyyMMdd", TimeZone.getTimeZone("UTC")) Triple(fmt.parse(value)?.time, true, "UTC") } value.endsWith("Z") -> {- val fmt = SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.US).apply {- timeZone = TimeZone.getTimeZone("UTC")- }+ val fmt = strictFormat("yyyyMMdd'T'HHmmss'Z'", TimeZone.getTimeZone("UTC")) Triple(fmt.parse(value)?.time, false, "UTC") } else -> {+ // No Z and no TZID is a floating local time (RFC 5545+ // section 3.3.5): it means wall time where the event+ // lives, not UTC. Read it in the system default zone;+ // stamping it UTC shifted every floating event by the+ // device offset. An explicit TZID still wins. val tzid = extractTzid(params)- val fmt = SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US).apply {- timeZone = tzid?.let { TimeZone.getTimeZone(it) } ?: TimeZone.getTimeZone("UTC")- }- Triple(fmt.parse(value)?.time, false, tzid ?: "UTC")+ val zone = tzid?.let { TimeZone.getTimeZone(it) } ?: TimeZone.getDefault()+ val fmt = strictFormat("yyyyMMdd'T'HHmmss", zone)+ Triple(fmt.parse(value)?.time, false, tzid ?: zone.id) } } } catch (_: Exception) {@@ -119,6 +119,18 @@ object ICalendar { } } + /**+ * A non-lenient parser: SimpleDateFormat defaults to lenient, which rolls+ * impossible dates (Feb 30, month 13) into neighbouring valid ones and so+ * silently moves the event. Strict parsing rejects them, and the caller's+ * fallback (epoch + default duration) applies instead.+ */+ private fun strictFormat(pattern: String, zone: TimeZone): SimpleDateFormat =+ SimpleDateFormat(pattern, Locale.US).apply {+ timeZone = zone+ isLenient = false+ }+ private fun extractTzid(params: String): String? = params.split(";").map { it.split("=", limit = 2) } .firstOrNull { it.size == 2 && it[0].uppercase() == "TZID" }?.get(1)
everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.ktindex e79e416746..6913cb6e54 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt@@ -18,6 +18,9 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.DataStoreUtils import java.io.File import java.security.SecureRandom+import java.time.Instant+import java.time.LocalDate+import java.time.ZoneId import javax.crypto.Cipher import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec@@ -53,7 +56,6 @@ object SnapshotStore { /** Snapshots older than this are pruned on every write. */ const val RETENTION_DAYS = 30L- private const val MILLIS_PER_DAY = 24L * 60 * 60 * 1000 private const val DIR_SNAPSHOTS = "snapshots" private const val DIR_BLOBS = "blobs"@@ -64,7 +66,7 @@ object SnapshotStore { private val json = Json { ignoreUnknownKeys = true } - /** One restorable snapshot: day (epoch millis at midnight UTC) + envelope payloads. */+ /** One restorable snapshot: day (epoch millis at local midnight) + envelope payloads. */ @Serializable data class SnapshotMeta( val vaultId: String,@@ -94,7 +96,23 @@ object SnapshotStore { private fun blobDir(context: Context, vaultId: String): File = File(File(vaultDir(context, vaultId), DIR_BLOBS), "").apply { mkdirs() } - private fun dayOf(timestampMs: Long): Long = (timestampMs / MILLIS_PER_DAY) * MILLIS_PER_DAY+ /**+ * Start (epoch millis) of the local day containing [timestampMs].+ *+ * Daily snapshots and the 30-day retention window are user-facing+ * calendar concepts ("one per day", "keep a month"), so the day boundary+ * is local midnight in the system default zone. Flooring to the UTC day+ * instead rolled the snapshot day over in the middle of the local+ * afternoon/evening (offset-dependent) and pruned against a day the user+ * never sees.+ */+ private fun dayOf(timestampMs: Long): Long = dayStart(localDateOf(timestampMs))++ private fun localDateOf(timestampMs: Long): LocalDate =+ Instant.ofEpochMilli(timestampMs).atZone(ZoneId.systemDefault()).toLocalDate()++ private fun dayStart(date: LocalDate): Long =+ date.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() private fun loadIndex(context: Context): StoredIndex { val raw = DataStoreUtils.getInstance(context).getString(KEY_INDEX)@@ -205,7 +223,9 @@ object SnapshotStore { /** Drops snapshots (files + index rows) older than [RETENTION_DAYS]. */ suspend fun pruneExpired(context: Context, nowMs: Long = System.currentTimeMillis()) = withContext(Dispatchers.IO) {- val cutoff = dayOf(nowMs) - RETENTION_DAYS * MILLIS_PER_DAY+ // Local-calendar retention: exactly RETENTION_DAYS local days+ // back, not 30 fixed 24h spans (which drift an hour across DST).+ val cutoff = dayStart(localDateOf(nowMs).minusDays(RETENTION_DAYS)) val index = loadIndex(context) val (expired, kept) = index.snapshots.partition { it.dayEpochMs < cutoff } if (expired.isEmpty()) return@withContext
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageCards.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageCards.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageCards.ktindex cfddeeb720..9f21127b6c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageCards.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageCards.kt@@ -100,7 +100,13 @@ fun BoxScope.HistoryScrubber( internal fun Modifier.fillMaxWidthFraction(percent: Float): Modifier = this.fillMaxWidth((percent / 100f).coerceIn(0f, 1f)) -fun timestring(timestamp: Instant, future: Boolean, context: Context): String {+fun timestring(timestamp: Instant, context: Context): String {+ // Direction is derived here, never passed in: a caller asserting+ // "future" about a timestamp that has since passed (an expiry that+ // lapsed while the card sat on screen) rendered "in 3 days" for+ // something already gone. Comparing against now at render time keeps+ // the wording truthful however stale the caller's assumption is.+ val future = timestamp > Clock.System.now() val duration = (Clock.System.now() - timestamp).absoluteValue return when { duration.inWholeSeconds < 60 -> context.getString(if (future) R.string.time_very_soon else R.string.time_just_now)
findfamily/src/main/java/com/vayunmathur/findfamily/ui/TemporaryLinkCard.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/TemporaryLinkCard.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/TemporaryLinkCard.ktindex b5e14348f7..9e87cd1605 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/TemporaryLinkCard.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/TemporaryLinkCard.kt@@ -15,6 +15,7 @@ import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.ListItemDefaults import com.vayunmathur.library.ui.Text+import kotlin.time.Clock @Composable fun TemporaryLinkCard(temporaryLink: TemporaryLink, onCopy: () -> Unit, onDelete: () -> Unit) {@@ -24,7 +25,11 @@ fun TemporaryLinkCard(temporaryLink: TemporaryLink, onCopy: () -> Unit, onDelete { Text(temporaryLink.name, fontWeight = FontWeight.Bold) }, colors = ListItemDefaults.colors(containerColor = Color.Transparent), supportingContent = {- Text(stringResource(R.string.expires, timestring(temporaryLink.deleteAt, true, context)))+ // The label follows the timestamp, not the card's assumption:+ // once deleteAt passes the link is expired, and timestring+ // itself now renders the past direction ("3 days ago").+ val label = if (temporaryLink.deleteAt > Clock.System.now()) R.string.expires else R.string.expired+ Text(stringResource(label, timestring(temporaryLink.deleteAt, context))) }, trailingContent = { Row {
findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserCard.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserCard.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserCard.ktindex 52fe81269d..5118904b65 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserCard.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UserCard.kt@@ -45,7 +45,7 @@ import kotlinx.datetime.toLocalDateTime @Composable fun UserCard(user: User, locationValue: LocationValue?, showSupportingContent: Boolean, onClick: () -> Unit) { val context = LocalContext.current- val lastUpdatedTime = locationValue?.let { timestring(it.timestamp, false, context) } ?: stringResource(R.string.auto_toggle_never)+ val lastUpdatedTime = locationValue?.let { timestring(it.timestamp, context) } ?: stringResource(R.string.auto_toggle_never) val speedString = (locationValue?.speed ?: 0f).formatSpeed() val sinceTime = user.lastLocationChangeTime.toLocalDateTime(TimeZone.currentSystemDefault()) val timeSinceEntry = Clock.System.now() - user.lastLocationChangeTime@@ -101,14 +101,14 @@ fun UserCard(user: User, locationValue: LocationValue?, showSupportingContent: B // getLatest() again. LocationSource.SHUTDOWN -> stringResource( R.string.user_card_shutdown,- timestring(locationValue.reportedAt, false, context),+ timestring(locationValue.reportedAt, context), lastUpdatedTime, user.locationName, sinceString ) LocationSource.BATTERY_LOW -> stringResource( R.string.user_card_battery_low,- timestring(locationValue.reportedAt, false, context),+ timestring(locationValue.reportedAt, context), lastUpdatedTime, user.locationName, sinceString
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex 33acdf2f19..bbcc44450c 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -91,6 +91,8 @@ <string name="request_from">Request from <xliff:g id="sender_id" example="ABC123">%1$s</xliff:g></string> <!-- MainPage: TemporaryLinkCard expiry label. %1$s = relative future time string, e.g. in 5 minutes / very soon --> <string name="expires">Expires <xliff:g id="relative_time" example="in 5 minutes">%1$s</xliff:g></string>+ <!-- MainPage: TemporaryLinkCard label once the expiry has passed. %1$s = relative past time string, e.g. 5 minutes ago -->+ <string name="expired">Expired <xliff:g id="relative_time" example="5 minutes ago">%1$s</xliff:g></string> <!-- MainPage: WaypointCard empty state when no one is inside waypoint. Noun phrase, sentence fragment --> <string name="nobody_here">nobody is currently here</string> <!-- MainPage: WaypointCard when single user inside. %1$s = person name, e.g. Alice. Sentence -->
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.ktindex d25cf8283b..cb1fdaeef2 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt@@ -9,8 +9,10 @@ import com.vayunmathur.parentalcontrols.data.BedtimeSchedule import com.vayunmathur.parentalcontrols.data.DowntimeSchedule import com.vayunmathur.parentalcontrols.data.SchoolTimeSchedule import com.vayunmathur.parentalcontrols.platform.BedtimeReceiver+import java.time.Duration import java.time.LocalDateTime import java.time.ZoneId+import java.time.ZonedDateTime private const val TAG = "ParentalControlsBedtime" @@ -54,7 +56,7 @@ class BedtimeScheduler(private val context: Context) { private fun armWindow( enabled: Boolean,- activeAt: (LocalDateTime) -> Boolean,+ activeAt: (ZonedDateTime) -> Boolean, requestCode: Int, ) { val alarms = alarms ?: return@@ -63,7 +65,7 @@ class BedtimeScheduler(private val context: Context) { if (!enabled) return val next = nextBoundary(activeAt) ?: return- val at = next.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()+ val at = next.toInstant().toEpochMilli() val canExact = alarms.canScheduleExactAlarms() runCatching { if (canExact) {@@ -83,12 +85,20 @@ class BedtimeScheduler(private val context: Context) { * today, morning to yesterday" rule interact, and one predicate that the enforcer also uses * cannot disagree with itself. A week of minutes is 10,080 cheap comparisons, run at most * a few times a day.+ *+ * The scan runs in instant space ([ZonedDateTime] stepped by [Duration]), not over naive+ * [LocalDateTime]. Stepping wall-clock minutes and only converting with `atZone` at the+ * end breaks across DST: a boundary inside the spring-forward gap names a local time that+ * never occurs and `atZone` shifts it by the gap (~1h), and a boundary in the fall-back+ * overlap resolves to only one of its two occurrences. Stepping real minutes evaluates+ * exactly the instants that will occur - the gap contributes no phantom minutes and the+ * overlap contributes both passes - so the armed instant is the true boundary. */- private fun nextBoundary(activeAt: (LocalDateTime) -> Boolean): LocalDateTime? {- val now = LocalDateTime.now().withSecond(0).withNano(0)+ private fun nextBoundary(activeAt: (ZonedDateTime) -> Boolean): ZonedDateTime? {+ val now = ZonedDateTime.now(ZoneId.systemDefault()).withSecond(0).withNano(0) var state = activeAt(now) for (step in 1..MINUTES_IN_WEEK) {- val at = now.plusMinutes(step.toLong())+ val at = now.plus(Duration.ofMinutes(step.toLong())) val next = activeAt(at) if (next != state) return at state = next@@ -122,3 +132,17 @@ fun DowntimeSchedule.activeAt(at: LocalDateTime): Boolean = /** Whether the window is open at [at], in the device's current timezone. */ fun SchoolTimeSchedule.activeAt(at: LocalDateTime): Boolean = contains(at.dayOfWeek.value - 1, at.hour * MINUTES_PER_HOUR + at.minute)++// ZonedDateTime overloads for the boundary scan: the predicate is defined on+// local wall fields, and a ZonedDateTime carries the offset that disambiguates+// them, so each instant in the scan (including both passes through a fall-back+// overlap) is judged by the wall time it actually displays.++/** Whether the window is open at [at]. */+fun BedtimeSchedule.activeAt(at: ZonedDateTime): Boolean = activeAt(at.toLocalDateTime())++/** Whether the window is open at [at]. */+fun DowntimeSchedule.activeAt(at: ZonedDateTime): Boolean = activeAt(at.toLocalDateTime())++/** Whether the window is open at [at]. */+fun SchoolTimeSchedule.activeAt(at: ZonedDateTime): Boolean = activeAt(at.toLocalDateTime())
screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.ktindex 211f0e21c6..2f38a92dc3 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt@@ -6,8 +6,10 @@ import android.content.Context import com.vayunmathur.library.log.Log import androidx.core.content.getSystemService import com.vayunmathur.screentime.data.WindDownSchedule+import java.time.Duration import java.time.LocalDateTime import java.time.ZoneId+import java.time.ZonedDateTime private const val TAG = "ScreenTimeScheduler" @@ -32,7 +34,7 @@ class WindowScheduler(private val context: Context) { private fun armWindow( enabled: Boolean,- activeAt: (LocalDateTime) -> Boolean,+ activeAt: (ZonedDateTime) -> Boolean, requestCode: Int, ) { val alarms = alarms ?: return@@ -41,7 +43,7 @@ class WindowScheduler(private val context: Context) { if (!enabled) return val next = nextBoundary(activeAt) ?: return- val at = next.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()+ val at = next.toInstant().toEpochMilli() val canExact = alarms.canScheduleExactAlarms() runCatching { if (canExact) {@@ -53,11 +55,20 @@ class WindowScheduler(private val context: Context) { }.onFailure { Log.status(TAG, "could not arm the window alarm", it) } } - private fun nextBoundary(activeAt: (LocalDateTime) -> Boolean): LocalDateTime? {- val now = LocalDateTime.now().withSecond(0).withNano(0)+ /**+ * The next minute at which wind-down's state changes, searched forward a week.+ *+ * The scan runs in instant space ([ZonedDateTime] stepped by [Duration]), not over+ * naive [LocalDateTime]: wall-clock stepping plus a final `atZone` shifts a boundary+ * inside the spring-forward DST gap by the gap length (~1h) and can only name one+ * occurrence inside the fall-back overlap. Stepping real minutes evaluates exactly+ * the instants that will occur, so the armed instant is the true boundary.+ */+ private fun nextBoundary(activeAt: (ZonedDateTime) -> Boolean): ZonedDateTime? {+ val now = ZonedDateTime.now(ZoneId.systemDefault()).withSecond(0).withNano(0) var state = activeAt(now) for (step in 1..MINUTES_IN_WEEK) {- val at = now.plusMinutes(step.toLong())+ val at = now.plus(Duration.ofMinutes(step.toLong())) val next = activeAt(at) if (next != state) return at state = next@@ -94,6 +105,9 @@ fun WindDownSchedule.activeAt(at: LocalDateTime): Boolean { } } +/** Whether wind-down is active at [at]. */+fun WindDownSchedule.activeAt(at: ZonedDateTime): Boolean = activeAt(at.toLocalDateTime())+ private fun WindDownSchedule.isYesterdaySet(day: Int): Boolean { val yesterday = (day + DAYS_PER_WEEK - 1) % DAYS_PER_WEEK return (daysMask shr yesterday) and 1 == 1