From 7916a665c387f466534aa895dbee036a81061b80 Mon Sep 17 00:00:00 2001 From: "John H. Ring IV" Date: Thu, 6 Aug 2026 17:38:18 -0400 Subject: [PATCH 1/2] Reject water-induced touches by contact size, add crown sync A droplet running across the glass registers as a tap. The top half of a live countdown is SYNC, which rounds to the nearest minute, so one stray contact silently moves the gun by up to 30s. Reproduced on-device as a 91s error from four stray taps 15s apart, each rounding the countdown back up so it never advanced. Guard sync, mode toggle and reset on MotionEvent touch-major, captured in dispatchTouchEvent before Compose routes the event (PointerInputChange does not carry it). Water reads SMALLER than skin, so the guard is a floor, calibrated on a Pixel Watch 3: water 2.99 .. 9.98 then 13.97 for a heavy direct drip real tap 8.98 .. 18.95 Taps are judged on the touch-down value, reset on the gesture peak: a press lands soft and spreads, measured as 6.98 growing to 10.97 over a 706ms hold, so judging a long-press by its down value refuses genuine presses and breaks reset entirely. The two populations overlap, so the floor also refuses the lightest real taps: 2 of 8 deliberately-light taps in testing. That trade is deliberate and documented in the tests. A refused tap is visible and repeatable; an accepted droplet silently moves the gun, which is the harm being fixed. Crown rotation syncs as a parallel, water-immune path and bypasses the guard. The guard also fails open where a device reports no contact size, so unmeasured watches behave exactly as before. Debug builds take applicationId .debug and the name "RT DEBUG" so a dev build installs alongside the Play Store copy instead of colliding with its signature. Co-Authored-By: Claude Opus 5 --- README.md | 6 +- app/build.gradle.kts | 9 +- app/src/debug/res/values/strings.xml | 10 + .../johnhringiv/regattatimer/MainActivity.kt | 44 ++++ .../johnhringiv/regattatimer/TimerLogic.kt | 80 +++++++ .../regattatimer/TimerViewModel.kt | 65 +++++- .../regattatimer/ui/TimerScreen.kt | 61 +++++- .../regattatimer/CountdownDisplayTest.kt | 78 +++++++ .../regattatimer/TimerLogicTest.kt | 12 ++ .../regattatimer/TouchGuardTest.kt | 204 ++++++++++++++++++ 10 files changed, 561 insertions(+), 8 deletions(-) create mode 100644 app/src/debug/res/values/strings.xml create mode 100644 app/src/test/java/com/johnhringiv/regattatimer/CountdownDisplayTest.kt create mode 100644 app/src/test/java/com/johnhringiv/regattatimer/TouchGuardTest.kt diff --git a/README.md b/README.md index 8678b2d..6007d0f 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,11 @@ The beta is live on Google Play (closed testing) — no sideloading needed. Goog ## Features - **5-minute (RRS 26) and 3-minute start sequences** -- **Sync to nearest minute** — tap SYNC at any gun to correct the countdown (3:22 → 3:00, 3:40 → 4:00) +- **Sync to nearest minute** — tap SYNC at any gun to correct the countdown (3:22 → 3:00, 3:40 → 4:00), or turn the crown when the glass is wet - **Automatic count-up** after the start for elapsed race time - **Haptic signals**: double buzz at 4:00 (prep), long buzz at 1:00, ticks through the final 10 seconds, gun blast at 0:00 - **Screen never leaves the app** while armed or counting down; count-up dims to an always-on ambient display -- **Wet-proof**: countdown, display, and haptics keep running even when water forces the watch into ambient mode; huge half-screen touch targets; long-press-guarded reset so splashes can't kill your sequence +- **Wet-proof**: countdown, display, and haptics keep running even when water forces the watch into ambient mode; huge half-screen touch targets; spray is filtered out by contact size, and the crown syncs when you don't trust the screen at all; long-press-guarded reset - **Quick-launch tile**: swipe from the watch face, tap 5 min or 3 min, and the timer opens pre-armed - **Watch-face complication**: weather-style ring where the dot is time remaining, ticking countdown in the center — one tap starts the last-used sequence right from the face - **Survives interruptions**: an in-flight countdown or race is restored at the correct time even if the app is closed — or the watch reboots @@ -88,6 +88,8 @@ Needs Wear OS 5+ (minSdk 34). `adb` ships with [Android platform-tools](https:// Requires JDK 17+ and the Android SDK (compileSdk 37). Release signing reads `keystore.properties` at the repo root (gitignored); CI restores it from the `KEYSTORE_B64` / `KEYSTORE_PASSWORD` secrets. +Debug builds use the applicationId `com.johnhringiv.regattatimer.debug`, so a dev build installs alongside a Play Store copy on the same watch instead of colliding with its signature. + After cloning, enable the repo hooks (auto-formats Markdown with Prettier on commit; CI enforces): ``` diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 4ab3010..97269b5 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -21,8 +21,8 @@ android { targetSdk = 36 // versionCode bumps on every feature-branch change (CI-enforced > main). // versionName bumps once per PR to main (CI-enforced). - versionCode = 19 - versionName = "0.7" + versionCode = 20 + versionName = "0.8" } signingConfigs { @@ -37,6 +37,11 @@ android { } buildTypes { + debug { + // Distinct applicationId so a dev build can sit alongside the Play Store install on a + // real watch — signatures differ, so without this the two cannot coexist. + applicationIdSuffix = ".debug" + } release { isMinifyEnabled = true isShrinkResources = true diff --git a/app/src/debug/res/values/strings.xml b/app/src/debug/res/values/strings.xml new file mode 100644 index 0000000..ba38cfe --- /dev/null +++ b/app/src/debug/res/values/strings.xml @@ -0,0 +1,10 @@ + + + + RT DEBUG + diff --git a/app/src/main/java/com/johnhringiv/regattatimer/MainActivity.kt b/app/src/main/java/com/johnhringiv/regattatimer/MainActivity.kt index 462d79a..6eb9c5e 100644 --- a/app/src/main/java/com/johnhringiv/regattatimer/MainActivity.kt +++ b/app/src/main/java/com/johnhringiv/regattatimer/MainActivity.kt @@ -2,6 +2,9 @@ package com.johnhringiv.regattatimer import android.content.Intent import android.os.Bundle +import android.os.SystemClock +import android.util.Log +import android.view.MotionEvent import android.view.WindowManager import androidx.activity.ComponentActivity import androidx.activity.compose.setContent @@ -21,10 +24,17 @@ const val EXTRA_MODE = "mode" /** Intent extra (set by the complication) to start the sequence immediately on launch. */ const val EXTRA_AUTO_START = "auto_start" +private const val TAG = "RegattaTimer" + class MainActivity : ComponentActivity() { private val viewModel: TimerViewModel by viewModels() + // TEMPORARY: contact characterisation. Feeds the touch-guard calibration logging in + // dispatchTouchEvent - remove along with it once the thresholds are settled. + private var contactDownMs = 0L + private var contactPeakMajor = 0f + private var isAmbient by mutableStateOf(false) private var ambientTick by mutableIntStateOf(0) @@ -78,12 +88,46 @@ class MainActivity : ComponentActivity() { onToggleMode = viewModel::toggleMode, onStart = viewModel::start, onSync = viewModel::sync, + // The crown is water-immune, so a rotary sync skips the contact-size guard. + onCrownSync = { viewModel.sync(fromTouch = false) }, onReset = viewModel::reset, onAnyTap = viewModel::noteInteraction, ) } } + /** + * Records the contact size of every touch-down before Compose routes it, so the sync and + * mode-toggle guards can tell a fingertip from water. Taken here rather than in a pointer + * modifier because Compose's PointerInputChange doesn't carry touch-major, and dispatch order + * here is unambiguous. Never consumes the event — the guards decide, not this. + */ + override fun dispatchTouchEvent(ev: MotionEvent): Boolean { + if (ev.pointerCount > 0) { + when (ev.actionMasked) { + MotionEvent.ACTION_DOWN -> { + viewModel.noteContactSize(ev.getTouchMajor(0)) + contactDownMs = SystemClock.elapsedRealtime() + contactPeakMajor = ev.getTouchMajor(0) + Log.d(TAG, "down major=${ev.getTouchMajor(0)}") + } + // Peak, not the down value: a contact grows as it settles, and the peak is what + // separates a fingertip from water. + MotionEvent.ACTION_MOVE -> { + contactPeakMajor = maxOf(contactPeakMajor, ev.getTouchMajor(0)) + viewModel.noteContactPeak(ev.getTouchMajor(0)) + } + + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + val heldMs = SystemClock.elapsedRealtime() - contactDownMs + val cancelled = ev.actionMasked == MotionEvent.ACTION_CANCEL + Log.d(TAG, "up peak=$contactPeakMajor heldMs=$heldMs cancelled=$cancelled") + } + } + } + return super.dispatchTouchEvent(ev) + } + override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) armModeFromIntent(intent) diff --git a/app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt b/app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt index 77c836d..f7a7217 100644 --- a/app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt +++ b/app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt @@ -32,6 +32,86 @@ sealed interface TimerState { fun syncRemaining(remainingMs: Long): Long = ((remainingMs + 30_000L) / 60_000L) * 60_000L +/** + * Whole seconds to show for a countdown, derived ONLY from the anchor and the instant + * being rendered. Ceil, so 5:00 shows for the whole first second. + * + * Every surface must call this with the current [now]; caching the result and redrawing + * it later shows a stale time (the display lags by exactly the redraw gap). That matters + * in ambient, where redraws are throttled to roughly once a minute. + */ +fun countdownSecondsAt(deadline: Long, now: Long): Long { + val remaining = deadline - now + return if (remaining <= 0L) 0L else (remaining + 999L) / 1000L +} + +/** Whole seconds elapsed since the gun, derived only from the anchor and [now]. */ +fun elapsedSecondsAt(zero: Long, now: Long): Long = (now - zero).coerceAtLeast(0L) / 1000L + +/** + * Smallest contact the timer will accept as a deliberate fingertip, in MotionEvent + * touch-major units. + * + * Calibrated on a Pixel Watch 3 (NVTCapacitiveTouchScreen, ABS_MT_TOUCH_MAJOR 0..255, + * touch.size.calibration=GEOMETRIC). MotionEvent.getTouchMajor() reports on the same 0..255 + * scale as the raw axis — getSize() is exactly touchMajor/255 — and values are quantised at + * raw * 0.997555, so raw 12 arrives as 11.97. + * + * Judged on the TOUCH-DOWN value: a tap lands firm, so its first sample is representative, and + * the down value is the conservative reading against water contacts that grow after landing. + * Measured touch-down values on-watch: + * + * water 2, 3.99, 4.99, 6.98, 8.98, 9.98 then 13.97 for a heavy direct drip + * real tap 10.97, 11.97, 12.97 ... 18.95 and 8.98 for a deliberately light tap + * + * The populations overlap: a light tap can land at 8.98, exactly where droplets land. Measured on + * a dry finger, 2 of 8 deliberately-light taps fell below this floor and were refused. That cost + * is deliberate — a refused tap is visible and repeatable, an accepted droplet is neither. + * + * Water reads SMALLER than skin, so the guard is a floor. 10.0 looks a hair above the largest + * water reading (9.98) but the margin is safe: values quantise at raw * 0.997555, so raw 10 + * arrives as 9.97555 and raw 11 as 10.973105 — nothing can land in between. 10.0 therefore + * cleanly means "raw 11 or greater". + * + * An earlier 11.5 refused a third of genuine taps — twice in a row at 10.97 — while rejecting + * exactly the same water, since the heavy drip at 13.97 defeats both. Lowering it costs no + * water rejection at all. + * + * The heavy-drip case is unsolved and unsolvable by contact size alone: water poured straight + * onto the glass reads identically to a fingertip. The crown is the guaranteed path. + * + * Why it matters: a droplet running across the glass registers as a tap, and the top half of + * a live countdown is SYNC — one stray contact silently moves the gun by up to 30s. + */ +const val FINGER_CONTACT_FLOOR = 10.0f + +/** + * Floor for the long-press reset, judged on the gesture's PEAK contact rather than its touch-down + * value (a press lands soft and spreads — see the peak tracking in TimerViewModel). + * + * Lower than [FINGER_CONTACT_FLOOR] because presses and taps have different profiles. Measured + * peaks on-watch: + * + * water 2.99, 6.98, 7.98, 8.98, 9.98 then 12.97, 14.96 for heavy direct drips + * real press 10.97, 12.97, 16.96 + * + * 11.5 refused half of all genuine resets, including one held for 1204ms that peaked at 10.97. + * 10.5 sits in the empty band between 9.98 and 10.97, so it admits those presses while rejecting + * exactly the same water as 11.5 did — the heavy drips at 12.97+ defeat both, so nothing is given + * up. Strictly better, not a loosening. + */ +const val RESET_CONTACT_FLOOR = 10.5f + +/** + * Whether [touchMajor] is plausibly a fingertip rather than water. + * + * Fails OPEN: a non-positive value means the device does not report contact size (the axis is + * device-specific and this app ships to Wear OS 5+ generally), and an unmeasured watch must + * behave exactly as it did before rather than refuse a real sync at the gun. + */ +fun isFingerContact(touchMajor: Float, floor: Float = FINGER_CONTACT_FLOOR): Boolean = + touchMajor <= 0f || touchMajor >= floor + fun formatMmSs(totalSeconds: Long): String { val m = totalSeconds / 60 val s = totalSeconds % 60 diff --git a/app/src/main/java/com/johnhringiv/regattatimer/TimerViewModel.kt b/app/src/main/java/com/johnhringiv/regattatimer/TimerViewModel.kt index c2d10b0..a5c4257 100644 --- a/app/src/main/java/com/johnhringiv/regattatimer/TimerViewModel.kt +++ b/app/src/main/java/com/johnhringiv/regattatimer/TimerViewModel.kt @@ -4,6 +4,7 @@ import android.app.Application import android.content.Context import android.os.PowerManager import android.os.SystemClock +import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Job @@ -34,6 +35,51 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) { private var idleGuard: Job? = null private var inAmbient = false + /** + * Contact size of the most recent touch-down, in MotionEvent touch-major units, recorded by + * MainActivity.dispatchTouchEvent before Compose sees the event. 0 = device doesn't report it. + */ + private var lastContactSize = 0f + + /** Peak contact size seen during the current gesture. See [noteContactPeak]. */ + private var lastContactPeak = 0f + + /** Records the contact size of a touch-down so the sync/toggle guards can consult it. */ + fun noteContactSize(touchMajor: Float) { + lastContactSize = touchMajor + lastContactPeak = touchMajor + } + + /** + * Records the largest contact seen so far in this gesture. + * + * A quick tap lands firm, so its touch-down value is representative. A deliberate PRESS lands + * soft and spreads as the finger flattens — measured on-watch as down=7.98 growing to + * peak=14.96 over a 1676ms hold. Judging a long-press by its touch-down value therefore + * rejects real presses, which is why reset consults the peak instead. + */ + fun noteContactPeak(touchMajor: Float) { + lastContactPeak = maxOf(lastContactPeak, touchMajor) + } + + /** + * Whether the last touch-down was a fingertip rather than water. Rejections are silent — no + * haptic — because a buzz would tell the sailor something happened when nothing did. + * + * Logged either way at DEBUG so the floor can be refined from real sailing data rather than + * the small lab sample it was derived from. + */ + private fun acceptTouch( + action: String, + usePeak: Boolean = false, + floor: Float = FINGER_CONTACT_FLOOR, + ): Boolean { + val contact = if (usePeak) lastContactPeak else lastContactSize + val ok = isFingerContact(contact, floor) + Log.d(TAG, "$action contact=$contact peak=$usePeak accepted=$ok floor=$floor") + return ok + } + // Water on the screen triggers the palm gesture and forces ambient mode; a partial // wake lock keeps the ticker (display + haptic cues) running through the countdown. private val powerManager = app.getSystemService(Context.POWER_SERVICE) as PowerManager @@ -134,6 +180,8 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) { fun toggleMode() { val st = _state.value + // Armed, a stray contact silently swaps a 5-minute RRS 26 start for a 3-minute club one. + if (!acceptTouch("toggleMode")) return if (st is TimerState.Idle) { val next = st.mode.other() _state.value = TimerState.Idle(next) @@ -161,9 +209,15 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) { } } - /** Round the remaining time to the nearest whole minute (correct on the next gun). */ - fun sync() { + /** + * Round the remaining time to the nearest whole minute (correct on the next gun). + * + * [fromTouch] false bypasses the contact-size guard — the crown is water-immune, so a rotary + * sync is always deliberate and must never be second-guessed. + */ + fun sync(fromTouch: Boolean = true) { val st = _state.value + if (fromTouch && !acceptTouch("sync")) return if (st is TimerState.Countdown) { val now = SystemClock.elapsedRealtime() val newRemaining = syncRemaining(st.deadline - now) @@ -184,6 +238,10 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) { fun reset() { val st = _state.value + // Water held on the glass long enough to trip the long-press and wiped a live countdown + // on-watch, so reset is guarded too. Judged on the PEAK, not the touch-down value: a + // deliberate press lands soft and spreads, so the down value rejects real presses. + if (!acceptTouch("reset", usePeak = true, floor = RESET_CONTACT_FLOOR)) return if (st !is TimerState.Idle) { _state.value = TimerState.Idle(st.mode) _displaySeconds.value = st.mode.durationSeconds @@ -246,7 +304,7 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) { lastShown = -1L continue } - val sec = (remaining + 999) / 1000 // ceil: shows 5:00 for the first second + val sec = countdownSecondsAt(st.deadline, now) // ceil: 5:00 for the first second if (sec != lastShown) { if (lastShown != -1L) countdownCue(sec, st.mode) lastShown = sec @@ -271,6 +329,7 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) { private companion object { const val IDLE_SCREEN_HOLD_MS = 10 * 60_000L const val GUN_LATENESS_MS = 2_000L + const val TAG = "RegattaTimer" } // LAST in the class: init runs in declaration order, and restoring a race touches diff --git a/app/src/main/java/com/johnhringiv/regattatimer/ui/TimerScreen.kt b/app/src/main/java/com/johnhringiv/regattatimer/ui/TimerScreen.kt index 26ac9af..44f0ac0 100644 --- a/app/src/main/java/com/johnhringiv/regattatimer/ui/TimerScreen.kt +++ b/app/src/main/java/com/johnhringiv/regattatimer/ui/TimerScreen.kt @@ -1,9 +1,11 @@ package com.johnhringiv.regattatimer.ui import android.os.SystemClock +import android.util.Log import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -12,10 +14,18 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.rotary.onRotaryScrollEvent import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.IntOffset @@ -27,6 +37,7 @@ import androidx.wear.compose.material3.TimeText import com.johnhringiv.regattatimer.Mode import com.johnhringiv.regattatimer.TimerState import com.johnhringiv.regattatimer.formatMmSs +import kotlin.math.abs private val Digits = Color(0xFFF5F5F5) private val Amber = Color(0xFFFFB300) @@ -37,6 +48,21 @@ private val ZoneLabel = Color(0xFFF5C518) // burgee gold private fun Mode.label() = formatMmSs(durationSeconds) +/** + * Accumulated rotary scroll needed to sync from the crown, in pixels. + * + * Deliberately more than an idle brush and less than a flick. Water cannot turn a crown, so this + * path stays available when the glass is wet — and when Wear OS auto-engages Water Lock and kills + * touch entirely, it is the only way left to sync. + * + * 48f tested too sensitive on a Pixel Watch 3; raised to a deliberate quarter-turn. The handler + * logs accumulated scroll so this can be tuned from measurement rather than feel. + */ +private const val ROTARY_SYNC_THRESHOLD_PX = 160f + +/** A pause longer than this restarts the rotary accumulator, so slow drift can never add up. */ +private const val ROTARY_IDLE_RESET_MS = 500L + @OptIn(ExperimentalFoundationApi::class) @Composable fun TimerScreen( @@ -47,6 +73,7 @@ fun TimerScreen( onToggleMode: () -> Unit, onStart: () -> Unit, onSync: () -> Unit, + onCrownSync: () -> Unit, onReset: () -> Unit, onAnyTap: () -> Unit = {}, ) { @@ -58,7 +85,39 @@ fun TimerScreen( // Idle/Countdown in ambient (wet screens force it) render the SAME layout, // just dimmed — controls and labels never disappear mid-sequence. - Box(modifier = Modifier.fillMaxSize().background(Color.Black)) { + // Crown sync: accumulate rotary scroll so a brush can't fire it, and restart the + // accumulator after a pause so slow drift never adds up to a sync. + val focusRequester = remember { FocusRequester() } + var rotaryAccum by remember { mutableFloatStateOf(0f) } + var lastRotaryMs by remember { mutableLongStateOf(0L) } + LaunchedEffect(Unit) { focusRequester.requestFocus() } + + Box( + modifier = Modifier + .fillMaxSize() + .background(Color.Black) + .onRotaryScrollEvent { event -> + if (state !is TimerState.Countdown) return@onRotaryScrollEvent false + val now = SystemClock.elapsedRealtime() + if (now - lastRotaryMs > ROTARY_IDLE_RESET_MS) rotaryAccum = 0f + lastRotaryMs = now + rotaryAccum += event.verticalScrollPixels + // TEMPORARY: tuning only. Remove once ROTARY_SYNC_THRESHOLD_PX is settled. + Log.d( + "RegattaTimer", + "rotary delta=${event.verticalScrollPixels} accum=$rotaryAccum " + + "threshold=$ROTARY_SYNC_THRESHOLD_PX", + ) + if (abs(rotaryAccum) >= ROTARY_SYNC_THRESHOLD_PX) { + rotaryAccum = 0f + onCrownSync() + } + true + } + // Must sit BELOW onRotaryScrollEvent or rotary events never reach it. + .focusRequester(focusRequester) + .focusable() + ) { // Two half-screen touch zones (wet-hands friendly). Column(modifier = Modifier.fillMaxSize()) { Box( diff --git a/app/src/test/java/com/johnhringiv/regattatimer/CountdownDisplayTest.kt b/app/src/test/java/com/johnhringiv/regattatimer/CountdownDisplayTest.kt new file mode 100644 index 0000000..3dc8233 --- /dev/null +++ b/app/src/test/java/com/johnhringiv/regattatimer/CountdownDisplayTest.kt @@ -0,0 +1,78 @@ +package com.johnhringiv.regattatimer + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * The countdown shown on screen is a pure function of (anchor, now). + * + * The ticker is anchored on SystemClock.elapsedRealtime() and measured exact on a Wear emulator + * (t+25.3s showed 4:35, t+85.6s showed 3:35, t+47.1s showed 4:13). These lock that in so a future + * change can't reintroduce drift by caching a tick instead of deriving from the deadline. + */ +class CountdownDisplayTest { + + private val t0 = 1_000_000L // arbitrary elapsedRealtime origin + private val deadline = t0 + 300_000L // 5:00 sequence + + @Test + fun `full duration shows for the whole first second`() { + assertEquals(300L, countdownSecondsAt(deadline, t0)) + assertEquals(300L, countdownSecondsAt(deadline, t0 + 1)) + assertEquals(300L, countdownSecondsAt(deadline, t0 + 999)) + assertEquals(299L, countdownSecondsAt(deadline, t0 + 1_000)) + } + + @Test + fun `final second and the gun`() { + assertEquals(1L, countdownSecondsAt(deadline, deadline - 1)) + assertEquals(0L, countdownSecondsAt(deadline, deadline)) + } + + @Test + fun `past the deadline clamps to zero rather than going negative`() { + assertEquals(0L, countdownSecondsAt(deadline, deadline + 1)) + assertEquals(0L, countdownSecondsAt(deadline, deadline + 90_000)) + } + + /** However long the renderer slept, the value it paints is correct for the instant it paints. */ + @Test + fun `value is correct at any instant, independent of when it was last computed`() { + for (gapMs in longArrayOf(0, 1_000, 40_000, 61_000, 240_000)) { + assertEquals( + "anchor-derived value must equal true remaining at $gapMs ms", + (300_000L - gapMs + 999L) / 1000L, + countdownSecondsAt(deadline, t0 + gapMs), + ) + } + } + + @Test + fun `sync moves the anchor, not a cached value`() { + // Armed 5:00, sync at a true 4:22 remaining -> rounds down to 4:00. + val now = t0 + 38_000 + val synced = syncRemaining(deadline - now) + assertEquals(240_000L, synced) + + val newDeadline = now + synced + assertEquals(240L, countdownSecondsAt(newDeadline, now)) + assertEquals(239L, countdownSecondsAt(newDeadline, now + 1_000)) + + // 26s earlier the true remaining is 4:34, which is nearer 5:00 -> rounds up instead. + assertEquals(300_000L, syncRemaining(deadline - (t0 + 26_000))) + } + + @Test + fun `elapsed seconds floor from the gun anchor`() { + assertEquals(0L, elapsedSecondsAt(t0, t0)) + assertEquals(0L, elapsedSecondsAt(t0, t0 + 999)) + assertEquals(1L, elapsedSecondsAt(t0, t0 + 1_000)) + assertEquals(125L, elapsedSecondsAt(t0, t0 + 125_400)) + } + + @Test + fun `elapsed clamps before the gun instead of reporting negative time`() { + // A restore can hand back a zero slightly in the future; never show a negative race. + assertEquals(0L, elapsedSecondsAt(t0, t0 - 5_000)) + } +} diff --git a/app/src/test/java/com/johnhringiv/regattatimer/TimerLogicTest.kt b/app/src/test/java/com/johnhringiv/regattatimer/TimerLogicTest.kt index 28b21a5..0cef971 100644 --- a/app/src/test/java/com/johnhringiv/regattatimer/TimerLogicTest.kt +++ b/app/src/test/java/com/johnhringiv/regattatimer/TimerLogicTest.kt @@ -23,6 +23,18 @@ class TimerLogicTest { @Test fun `worst case cannot exceed armed duration`() = assertEquals(300_000L, syncRemaining(270_000L)) + // A tap can land after the deadline has passed (frozen process, late wake); sync() gates + // on `<= 0` to fire the gun, so these must never come back positive. + @Test + fun `just past the gun syncs to zero`() = assertEquals(0L, syncRemaining(-1L)) + + @Test + fun `well past the gun never rounds back up to a positive countdown`() { + for (ms in longArrayOf(-15_000L, -30_000L, -45_000L, -90_000L, -600_000L)) { + assert(syncRemaining(ms) <= 0L) { "syncRemaining($ms) must not resurrect a countdown" } + } + } + @Test fun formatting() { assertEquals("5:00", formatMmSs(300)) diff --git a/app/src/test/java/com/johnhringiv/regattatimer/TouchGuardTest.kt b/app/src/test/java/com/johnhringiv/regattatimer/TouchGuardTest.kt new file mode 100644 index 0000000..ae99f99 --- /dev/null +++ b/app/src/test/java/com/johnhringiv/regattatimer/TouchGuardTest.kt @@ -0,0 +1,204 @@ +package com.johnhringiv.regattatimer + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Guards against water-induced false input. + * + * All values are real measurements from a Pixel Watch 3. MotionEvent.getTouchMajor() reports on the + * same 0..255 scale as the raw ABS_MT_TOUCH_MAJOR axis, so kernel-level and framework-level + * captures are directly comparable and both appear below. Water reads SMALLER than skin, so the + * guard is a floor. These assert the SHIPPING constant, not a stand-in. + */ +class TouchGuardTest { + + // Droplets, both sessions. The 8.98/9.98 pair are the ones that defeated an earlier 9.5 floor. + private val waterContacts = floatArrayOf(2.99f, 3.99f, 4.99f, 4.99f, 5.99f, 8.98f, 8.98f, 9.98f) + + // Genuine taps, including the light 10.97 that an earlier 11.5 floor refused twice in a row. + private val firmContacts = + floatArrayOf( + 10.97f, 11.97f, 13.97f, 14.96f, 15.96f, 16.96f, 17.96f, 18.95f, 20.95f, 24f, 27f, 29f, + ) + + @Test + fun `every measured water contact is rejected`() { + for (c in waterContacts) { + assertFalse("water contact $c must not be treated as a fingertip", isFingerContact(c)) + } + } + + @Test + fun `every firm finger contact is accepted`() { + for (c in firmContacts) { + assertTrue("finger contact $c must be accepted", isFingerContact(c)) + } + } + + /** + * The floor must clear every droplet ever measured. A placeholder of 0.04f once shipped 250x + * too low because getTouchMajor() turned out NOT to be normalised to 0..1, and a later 9.5 + * was defeated by droplets reaching 9.98 — both found on-watch, not here. + */ + @Test + fun `floor clears every measured droplet`() { + val largestWater = waterContacts.max() + assertTrue( + "floor $FINGER_CONTACT_FLOOR must exceed largest measured droplet $largestWater", + FINGER_CONTACT_FLOOR > largestWater, + ) + } + + // Genuine taps the floor REFUSES, measured with a dry finger tapping deliberately lightly: + // 2 of 8 landed here. Both read 8.98 — the same value droplets produce. + private val refusedLightTaps = floatArrayOf(8.98f, 8.98f) + + /** + * Documents the accepted cost, so it can't be mistaken for a bug later: the water and finger + * populations genuinely OVERLAP — light taps reach as low as raw 9, which water also produces — + * so no threshold admits every real tap and rejects every droplet. The floor is set to win the + * droplet side, which means the lightest genuine taps are refused. That's survivable because a + * missed tap is visible — the clock doesn't snap, you tap again — and the crown always works. + * An accepted droplet is invisible, which is the harm. + */ + @Test + fun `light taps inside the water band are refused - the accepted cost`() { + val largestWater = waterContacts.max() + for (c in refusedLightTaps) { + assertFalse("light tap $c sits below the floor and is refused", isFingerContact(c)) + assertTrue( + "$c is only refused because water reaches $largestWater — not an arbitrary floor", + c <= largestWater, + ) + } + } + + /** + * Values quantise at `raw * 0.997555`, so raw 10 arrives as 9.97555 and raw 11 as 10.973105 — + * nothing can land between them. That is what makes a floor of 10.0 safe despite sitting only + * 0.02 above the largest observed water contact: it cleanly means "raw 11 or greater". + */ + @Test + fun `floor separates raw 10 from raw 11 despite the narrow numeric margin`() { + val rawTen = 10 * 0.997555f + val rawEleven = 11 * 0.997555f + assertFalse("raw 10 ($rawTen) is water territory", isFingerContact(rawTen)) + assertTrue("raw 11 ($rawEleven) is a real tap", isFingerContact(rawEleven)) + } + + // ---- long-press reset uses a separate, lower floor on the gesture peak ------ + + // Peaks of genuine deliberate presses. The 10.97 was held for 1204ms and still peaked there: + // a press lands soft and spreads, so it never reaches tap-sized contact. A later 706ms reset + // was captured end to end — landed at 6.98, peaked at 10.97 — which is why this is judged on + // the peak: on the down value that press reads as water and reset stops working entirely. + private val pressPeaks = floatArrayOf(10.97f, 12.97f, 16.96f) + + // Peaks water reached. The last two are heavy direct drips, which defeat every floor we can + // set without also refusing real presses - documented, not solved. + private val waterPeaksSpray = floatArrayOf(2.99f, 6.98f, 7.98f, 8.98f, 9.98f) + private val waterPeaksHeavyDrip = floatArrayOf(12.97f, 14.96f) + + @Test + fun `every genuine press is accepted by the reset floor`() { + for (c in pressPeaks) { + assertTrue("press peak $c must reset", isFingerContact(c, RESET_CONTACT_FLOOR)) + } + } + + @Test + fun `spray cannot trigger a reset`() { + for (c in waterPeaksSpray) { + assertFalse("water peak $c must not reset", isFingerContact(c, RESET_CONTACT_FLOOR)) + } + } + + /** + * The reset floor is lower than the tap floor, which sounds like a weakening but isn't: it + * rejects exactly the same water. Both floors sit above the spray population and below the + * heavy-drip one, so lowering it bought press reliability for nothing. + */ + @Test + fun `lower reset floor gives up no water rejection versus the tap floor`() { + for (c in waterPeaksSpray) { + assertFalse(isFingerContact(c, RESET_CONTACT_FLOOR)) + assertFalse(isFingerContact(c, FINGER_CONTACT_FLOOR)) + } + // And both are equally defeated by a heavy direct drip - stated so it isn't a surprise. + for (c in waterPeaksHeavyDrip) { + assertTrue(isFingerContact(c, RESET_CONTACT_FLOOR)) + assertTrue(isFingerContact(c, FINGER_CONTACT_FLOOR)) + } + } + + /** + * The guard must never be the reason a real sync fails at a gun. Contact size is a + * device-specific axis and this app ships to Wear OS 5+ generally, so a device that doesn't + * report it has to behave exactly as it did before the guard existed. + */ + @Test + fun `fails open when the device reports no contact size`() { + assertTrue(isFingerContact(0f)) + assertTrue(isFingerContact(-1f)) + } + + @Test + fun `floor itself is accepted`() { + assertTrue(isFingerContact(FINGER_CONTACT_FLOOR)) + assertFalse(isFingerContact(FINGER_CONTACT_FLOOR - 0.01f)) + } + + @Test + fun `production floor is positive so the guard is actually armed`() { + assertTrue(FINGER_CONTACT_FLOOR > 0f) + } + + // ---- what the guard prevents ------------------------------------------------ + + /** + * Characterises the observed failure: stray syncs arriving more often than every 30s each round + * the countdown back up, so it never advances. Reproduced on-device as 4:59 displayed against a + * true 3:28 — a 91s error. Guard rejects the contacts, so this sequence can no longer start. + */ + @Test + fun `repeated syncs inside 30s pin the countdown near its start`() { + var deadline = 300_000L // 5:00 remaining at t=0 + var now = 0L + repeat(4) { + now += 15_000L + deadline = now + syncRemaining(deadline - now) + } + val displayed = countdownSecondsAt(deadline, now) + val trueRemaining = (300_000L - now) / 1000L + assertEquals("countdown is pinned at 5:00", 300L, displayed) + assertEquals("while real time has moved on", 240L, trueRemaining) + assertTrue("the lie is the gap between them", displayed - trueRemaining >= 60L) + } + + /** A sync can pull the clock back up, but never past the armed duration. */ + @Test + fun `sync never exceeds the armed duration`() { + for (mode in Mode.entries) { + var remaining = mode.durationMs + repeat(10) { + remaining = syncRemaining(remaining - 15_000L) + assertTrue( + "${mode.name}: sync produced $remaining, above armed ${mode.durationMs}", + remaining <= mode.durationMs, + ) + } + } + } + + /** A single stray contact is worth up to 30s in either direction — why it must be blocked. */ + @Test + fun `one sync can move the gun by up to 30 seconds`() { + // 4:31 remaining rounds up to 5:00: +29s, the on-device reproduction. + assertEquals(300_000L, syncRemaining(271_000L)) + // 4:29 rounds down to 4:00: -29s. + assertEquals(240_000L, syncRemaining(269_000L)) + } +} From fb46a8eccc147c5ff33de32a16807e632932cd62 Mon Sep 17 00:00:00 2001 From: "John H. Ring IV" Date: Sat, 8 Aug 2026 21:10:00 -0400 Subject: [PATCH 2/2] Stop long count-up from overflowing the display MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nothing ends a race, so count-up runs until it is reset. Left overnight it reached "1022:47", which is too wide for the watch: the digits wrapped onto a second line and shoved the RACE label off the screen entirely. Caught by screenshotting a watch that had been counting since the previous evening. Roll into H:MM:SS past an hour instead of letting the minute field grow without bound. Format alone is not enough — "1:00:00" is seven characters, the same width class that was already wrapping — so the type also steps down for the longer strings: 68sp to 5 chars, 44sp for 6-7, 34sp beyond. maxLines/softWrap ensure anything unforeseen clips rather than wrapping. Under an hour the output is identical to the countdown's M:SS, so the digits do not change shape at the gun. The countdown is capped at its armed duration and keeps the original path untouched. Verified by rendering each band at 408x408 density 320 — the Pixel Watch 3 geometry, reproduced on an emulator, which otherwise defaults to 454 and would have flattered the result. Co-Authored-By: Claude Opus 5 --- app/build.gradle.kts | 2 +- .../johnhringiv/regattatimer/TimerLogic.kt | 19 +++++++ .../regattatimer/ui/TimerScreen.kt | 30 +++++++++- .../regattatimer/TimerLogicTest.kt | 56 +++++++++++++++++++ 4 files changed, 104 insertions(+), 3 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 97269b5..ba25236 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -21,7 +21,7 @@ android { targetSdk = 36 // versionCode bumps on every feature-branch change (CI-enforced > main). // versionName bumps once per PR to main (CI-enforced). - versionCode = 20 + versionCode = 21 versionName = "0.8" } diff --git a/app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt b/app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt index f7a7217..0286d50 100644 --- a/app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt +++ b/app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt @@ -117,3 +117,22 @@ fun formatMmSs(totalSeconds: Long): String { val s = totalSeconds % 60 return String.format(Locale.ROOT, "%d:%02d", m, s) } + +/** + * Elapsed race time for the count-up display. + * + * Under an hour this is plain M:SS — identical to the countdown, so the digits do not change shape + * at the gun, which is the moment a sailor is least able to reread the screen. Past an hour it + * rolls into H:MM:SS instead of letting the minute field grow without bound. + * + * Unbounded minutes was not hypothetical. Nothing ends a race, so a timer left running after one + * reached "1022:47" on-watch: too wide for the display, so it wrapped onto a second line and shoved + * the RACE label off the screen entirely. [com.johnhringiv.regattatimer.ui] shrinks the type for + * these longer strings; this function keeps them as short as they can honestly be. + */ +fun formatElapsed(totalSeconds: Long): String { + val total = totalSeconds.coerceAtLeast(0L) + val hours = total / 3600 + if (hours == 0L) return formatMmSs(total) + return String.format(Locale.ROOT, "%d:%02d:%02d", hours, (total % 3600) / 60, total % 60) +} diff --git a/app/src/main/java/com/johnhringiv/regattatimer/ui/TimerScreen.kt b/app/src/main/java/com/johnhringiv/regattatimer/ui/TimerScreen.kt index 44f0ac0..92b787f 100644 --- a/app/src/main/java/com/johnhringiv/regattatimer/ui/TimerScreen.kt +++ b/app/src/main/java/com/johnhringiv/regattatimer/ui/TimerScreen.kt @@ -36,6 +36,7 @@ import androidx.wear.compose.material3.Text import androidx.wear.compose.material3.TimeText import com.johnhringiv.regattatimer.Mode import com.johnhringiv.regattatimer.TimerState +import com.johnhringiv.regattatimer.formatElapsed import com.johnhringiv.regattatimer.formatMmSs import kotlin.math.abs @@ -63,6 +64,23 @@ private const val ROTARY_SYNC_THRESHOLD_PX = 160f /** A pause longer than this restarts the rotary accumulator, so slow drift can never add up. */ private const val ROTARY_IDLE_RESET_MS = 500L +/** + * Display size for the giant digits, shrunk for the longer strings a long race produces. + * + * The digits are tabular (tnum), so rendered width tracks character count closely enough that a + * lookup beats a measuring pass. Countdowns ("5:00") and races under an hour ("59:59") are + * untouched and keep the original 68.sp — only the H:MM:SS forms step down. + * + * Sizes verified by rendering each band at 408x408 / density 320 — the Pixel Watch 3's geometry, + * reproduced on an emulator via `wm size`. Paired with maxLines/softWrap below so an unforeseen + * string clips rather than wrapping and destroying the layout, which is how this bug presented. + */ +private fun digitFontSize(text: String) = when (text.length) { + in 0..5 -> 68.sp // 5:00 .. 59:59 — the overwhelmingly common case + 6, 7 -> 44.sp // 1:00:00 .. 9:59:59 + else -> 34.sp // 10:00:00 and beyond +} + @OptIn(ExperimentalFoundationApi::class) @Composable fun TimerScreen( @@ -182,11 +200,19 @@ fun TimerScreen( fontSize = 14.sp, color = labelColor, ) + // Count-up alone can run past an hour; the countdown is capped at its armed + // duration, so it keeps the plain M:SS it has always had. + val timeText = when (state) { + is TimerState.CountUp -> formatElapsed(displaySeconds) + else -> formatMmSs(displaySeconds) + } Text( - text = formatMmSs(displaySeconds), - fontSize = 68.sp, + text = timeText, + fontSize = digitFontSize(timeText), fontWeight = FontWeight.Bold, color = digitColor, + maxLines = 1, + softWrap = false, style = TextStyle(fontFeatureSettings = "tnum"), ) Text( diff --git a/app/src/test/java/com/johnhringiv/regattatimer/TimerLogicTest.kt b/app/src/test/java/com/johnhringiv/regattatimer/TimerLogicTest.kt index 0cef971..135381d 100644 --- a/app/src/test/java/com/johnhringiv/regattatimer/TimerLogicTest.kt +++ b/app/src/test/java/com/johnhringiv/regattatimer/TimerLogicTest.kt @@ -43,4 +43,60 @@ class TimerLogicTest { assertEquals("0:00", formatMmSs(0)) assertEquals("61:05", formatMmSs(3665)) } + + // ---- count-up formatting ---------------------------------------------------- + + /** + * The regression this exists for. A race left running overnight rendered "1022:47", which is + * too wide for the watch: it wrapped onto a second line and pushed the RACE label off-screen. + */ + @Test + fun `a race left running overnight stays a sane width`() { + val seventeenHours = 17 * 3600L + 2 * 60L + 47L + assertEquals("1022:47", formatMmSs(seventeenHours)) // what it used to render + assertEquals("17:02:47", formatElapsed(seventeenHours)) // what it renders now + } + + /** Under an hour the count-up is byte-identical to the countdown — no shape change at the gun. */ + @Test + fun `below one hour count-up matches the countdown format exactly`() { + for (s in longArrayOf(0L, 1L, 59L, 60L, 599L, 600L, 3599L)) { + assertEquals("elapsed $s", formatMmSs(s), formatElapsed(s)) + } + } + + @Test + fun `the hour boundary rolls over rather than growing the minute field`() { + assertEquals("59:59", formatElapsed(3599)) + assertEquals("1:00:00", formatElapsed(3600)) + assertEquals("1:00:01", formatElapsed(3601)) + } + + @Test + fun `minutes and seconds stay zero-padded past the hour`() { + assertEquals("2:05:09", formatElapsed(2 * 3600L + 5 * 60L + 9L)) + assertEquals("10:00:00", formatElapsed(10 * 3600L)) + } + + /** + * Elapsed time is derived from a clock difference, so a restored race whose anchor lands + * slightly in the future can hand this a negative. It must not print "-1:-1". + */ + @Test + fun `negative elapsed clamps to zero rather than printing junk`() { + assertEquals("0:00", formatElapsed(-1)) + assertEquals("0:00", formatElapsed(-100_000)) + } + + /** + * Width is what actually broke, so assert it directly. 8 characters is the widest string the + * display is sized for; anything longer needs a full day of count-up to reach. + */ + @Test + fun `stays within eight characters for any plausible race`() { + for (hours in 0..23) { + val text = formatElapsed(hours * 3600L + 59 * 60L + 59L) + assert(text.length <= 8) { "elapsed at ${hours}h rendered $text (${text.length} chars)" } + } + } }