Watch app uses ambient mode, looks correct when idle, doesn't lose taps when woken

This commit is contained in:
James Babcock committed 2026-09-01 22:32:24 -07:00
1 parent fddb6ea886
commit 984c65a90e
12 files changed
+518 -73

No files matched your search

+5
View File
@@ -13,6 +13,11 @@ Compass app:
Files app: Files app:
* Viewing image files gamma-corrects and dithers them * Viewing image files gamma-corrects and dithers them
Watch app:
* Ambient mode: the watch no longer blurs when idle
* Fix flicker on waking the watch
* Tapping the idle watch to wake it counts as a tap on the pad
## 0.6.3 - 2026-09-01 ## 0.6.3 - 2026-09-01
* Update custom firmware base version from 2.2.6 to 2.2.9 * Update custom firmware base version from 2.2.6 to 2.2.9
* Add support for the short-then-long-press gesture * Add support for the short-then-long-press gesture
+17 -2
View File
@@ -51,8 +51,23 @@ down beginning in the button tray to hide them.
The pad keeps the watch display awake while it is showing (Watch settings > The pad keeps the watch display awake while it is showing (Watch settings >
"Keep screen on", default on). Wear OS otherwise dozes within seconds of the "Keep screen on", default on). Wear OS otherwise dozes within seconds of the
wrist dropping and freezes the app, so the remote would need a wake-up tap wrist dropping, so the remote would need a wake-up tap before every gesture.
before every gesture.
When the watch does doze (wrist down, or "Keep screen on" off), the app stays
in front as an always-on face: the pad's clock and status line on black,
redrawn once a minute. Wear OS would otherwise blur a snapshot of the app
under the system clock and, after its app timeout, drop back to the watch
face; being ambient-aware avoids both. Motion and crown input pause in ambient.
**Waking with a tap.** The system consumes the touch that wakes the watch, so
the pad treats each wake as a first tap it never saw:
- With the Wear OS "Always-on screen" setting on, the dozing pad is the same
screen, so a tap on it is a tap: one tap wakes the watch and sends *select*
to the glasses; a double-tap wakes it and sends *back*.
- With "Always-on screen" off the display was dark, so a lone tap just turns
it on; a double-tap turns it on and sends *back*.
- A wrist raise (the wrist-tilt gesture sensor) or a crown turn is not a tap.
Phone-side switches live in Faceclaw's Settings > Watch: turn watch control Phone-side switches live in Faceclaw's Settings > Watch: turn watch control
off entirely, reverse the crown direction, forbid unlocking from the watch, off entirely, reverse the crown direction, forbid unlocking from the watch,
+2
View File
@@ -68,6 +68,8 @@ dependencies {
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.9.2") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.9.2")
// RemoteInputIntentHelper: the system keyboard / voice / emoji text entry. // RemoteInputIntentHelper: the system keyboard / voice / emoji text entry.
implementation("androidx.wear:wear-input:1.1.0") implementation("androidx.wear:wear-input:1.1.0")
// AmbientLifecycleObserver: the always-on (ambient) display callbacks.
implementation("androidx.wear:wear:1.3.0")
implementation("com.google.android.gms:play-services-wearable:19.0.0") implementation("com.google.android.gms:play-services-wearable:19.0.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.1") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.1")
+2
View File
@@ -4,6 +4,8 @@
<uses-feature android:name="android.hardware.type.watch" /> <uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.VIBRATE" />
<!-- Required by AmbientLifecycleObserver (always-on display support). -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Not standalone: the watch app is a remote for Faceclaw on the phone <!-- Not standalone: the watch app is a remote for Faceclaw on the phone
and does nothing useful without it. --> and does nothing useful without it. -->
@@ -0,0 +1,20 @@
package com.faceclaw.wear
/**
* The watch's ambient (always-on, low-power) display state, as reported by
* the system through [androidx.wear.ambient.AmbientLifecycleObserver].
*/
data class AmbientMode(
/** The display is in ambient: draw black, still, and as few pixels as possible. */
val active: Boolean = false,
/** The panel burns in: nudge the content between redraws. */
val burnInProtectionRequired: Boolean = false,
/** The panel is 1-bit in ambient: no greys, no anti-aliasing worth relying on. */
val lowBit: Boolean = false,
/**
* Bumped on entering ambient and on every ambient update (about once a
* minute), so the clock redraws: the CPU may be suspended in between, so
* no timer can be relied on for that.
*/
val tick: Long = 0,
)
@@ -3,18 +3,56 @@ package com.faceclaw.wear
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.os.PowerManager
import android.util.Log
import android.view.KeyEvent import android.view.KeyEvent
import android.view.WindowManager import android.view.WindowManager
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.wear.ambient.AmbientLifecycleObserver
import com.faceclaw.wear.ui.FaceclawWearApp import com.faceclaw.wear.ui.FaceclawWearApp
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
private lateinit var link: PhoneLink private lateinit var link: PhoneLink
private lateinit var prefs: WatchPrefs private lateinit var prefs: WatchPrefs
private lateinit var haptics: Haptics private lateinit var haptics: Haptics
private lateinit var wakeTracker: WakeTracker
private val ambient = MutableStateFlow(AmbientMode())
/** The last stop was the display turning off (not the user leaving). */
private var stoppedForScreenOff = false
// Always-on support: with these callbacks Wear OS keeps the activity in
// front in ambient (we draw the clock) instead of blurring a snapshot of
// it under the system clock and, after a timeout, dropping back to the
// watch face.
private val ambientCallback = object : AmbientLifecycleObserver.AmbientLifecycleCallback {
override fun onEnterAmbient(ambientDetails: AmbientLifecycleObserver.AmbientDetails) {
Log.d(TAG, "enter ambient (burnIn=${ambientDetails.burnInProtectionRequired} lowBit=${ambientDetails.deviceHasLowBitAmbient})")
ambient.update {
AmbientMode(
active = true,
burnInProtectionRequired = ambientDetails.burnInProtectionRequired,
lowBit = ambientDetails.deviceHasLowBitAmbient,
tick = it.tick + 1,
)
}
}
override fun onUpdateAmbient() {
Log.d(TAG, "update ambient")
ambient.update { it.copy(tick = it.tick + 1) }
}
override fun onExitAmbient() {
Log.d(TAG, "exit ambient")
ambient.update { it.copy(active = false) }
wakeTracker.onWake(fromScreenOff = false)
}
}
// Side (stem) buttons: button 1 is click / hold, 2 double-click, 3 "Hey Even". // Side (stem) buttons: button 1 is click / hold, 2 double-click, 3 "Hey Even".
private val stemHandler = Handler(Looper.getMainLooper()) private val stemHandler = Handler(Looper.getMainLooper())
@@ -27,8 +65,17 @@ class MainActivity : ComponentActivity() {
link = PhoneLink(this) link = PhoneLink(this)
prefs = WatchPrefs(this) prefs = WatchPrefs(this)
haptics = Haptics(this) { prefs.prefs.value.haptics } haptics = Haptics(this) { prefs.prefs.value.haptics }
wakeTracker = WakeTracker(this)
wakeTracker.start()
lifecycle.addObserver(AmbientLifecycleObserver(this, ambientCallback))
setContent { setContent {
FaceclawWearApp(link = link, prefsStore = prefs, haptics = haptics) FaceclawWearApp(
link = link,
prefsStore = prefs,
haptics = haptics,
ambient = ambient,
wakes = wakeTracker.wakes,
)
} }
// A remote that dozes mid-gesture is no remote: hold the display while // A remote that dozes mid-gesture is no remote: hold the display while
// the app is in front (every screen, not just the pad), unless the // the app is in front (every screen, not just the pad), unless the
@@ -46,10 +93,29 @@ class MainActivity : ComponentActivity() {
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
Log.d(TAG, "onStart")
link.start() link.start()
} }
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
if (stoppedForScreenOff) {
stoppedForScreenOff = false
wakeTracker.onWake(fromScreenOff = true)
}
}
override fun onPause() {
Log.d(TAG, "onPause")
super.onPause()
}
override fun onStop() { override fun onStop() {
// With always-on off the display going dark stops the activity; the
// next resume is then a wake, and its tap deserves the wake treatment.
stoppedForScreenOff = getSystemService(PowerManager::class.java)?.isInteractive == false
Log.d(TAG, "onStop (screenOff=$stoppedForScreenOff)")
cancelStemHold() cancelStemHold()
// A stopped activity never sees the key-up, and the phone keeps the // A stopped activity never sees the key-up, and the phone keeps the
// hold (and its escape-menu countdown) running until it hears the // hold (and its escape-menu countdown) running until it hears the
@@ -62,6 +128,11 @@ class MainActivity : ComponentActivity() {
super.onStop() super.onStop()
} }
override fun onDestroy() {
wakeTracker.stop()
super.onDestroy()
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
when (keyCode) { when (keyCode) {
KeyEvent.KEYCODE_STEM_1 -> { KeyEvent.KEYCODE_STEM_1 -> {
@@ -132,6 +203,7 @@ class MainActivity : ComponentActivity() {
link.state.value?.let { it.connected && !it.screenOn } == true link.state.value?.let { it.connected && !it.screenOn } == true
private companion object { private companion object {
const val TAG = "FaceclawWear"
const val STEM_HOLD_MS = 450L const val STEM_HOLD_MS = 450L
} }
} }
@@ -0,0 +1,98 @@
package com.faceclaw.wear
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/** A wake of the watch display that a tap on the pad may have caused. */
data class Wake(
val id: Long,
/** SystemClock.uptimeMillis when the app learned of the wake. */
val uptimeMillis: Long,
/**
* The display was fully off (always-on disabled), so the activity was
* stopped and the tap's job was to turn the screen on; a lone tap should
* not also reach the glasses. False for an exit from ambient, where the
* pad was already showing and a tap on it means a tap.
*/
val fromScreenOff: Boolean,
)
/**
* Which display wakes were taps. The system consumes the touch that wakes
* the watch (from ambient or from off), so the pad never sees it; this
* reports each wake so the pad can treat it as a virtual first tap. Wakes by
* wrist raise are filtered out with the wrist-tilt gesture sensor, the same
* signal tilt-to-wake uses. Rotary and button wakes are left to the pad to
* cancel (a crown event follows straight away; a button wake leaves the app).
* Lives for the activity's lifetime (start()/stop() from onCreate/onDestroy):
* the sensor is a wake-up one, so a tilt is seen even while the activity sits
* stopped behind an off display.
*/
class WakeTracker(context: Context) : SensorEventListener {
private val sensorManager: SensorManager? = context.getSystemService(SensorManager::class.java)
private val sensor: Sensor? = sensorManager?.getDefaultSensor(TYPE_WRIST_TILT_GESTURE, true)
?: sensorManager?.getDefaultSensor(TYPE_WRIST_TILT_GESTURE)
private val handler = Handler(Looper.getMainLooper())
private var running = false
private var lastTiltAt = Long.MIN_VALUE / 2
private var nextId = 1L
private val _wakes = MutableStateFlow<Wake?>(null)
/** The latest wake, or null once it was attributed to a wrist raise. */
val wakes: StateFlow<Wake?> = _wakes.asStateFlow()
fun start() {
val manager = sensorManager ?: return
val target = sensor ?: run { Log.i(TAG, "no wrist-tilt sensor: wakes are all taken for taps"); return }
if (running) return
running = manager.registerListener(this, target, SensorManager.SENSOR_DELAY_NORMAL, handler)
}
fun stop() {
if (!running) return
running = false
sensorManager?.unregisterListener(this)
}
/** The display just woke with the app in front. Main thread. */
fun onWake(fromScreenOff: Boolean) {
val now = SystemClock.uptimeMillis()
if (now - lastTiltAt <= TILT_GRACE_MS) {
Log.d(TAG, "wake (fromScreenOff=$fromScreenOff): wrist raise, ignored")
return
}
Log.d(TAG, "wake (fromScreenOff=$fromScreenOff): possible tap")
_wakes.value = Wake(id = nextId++, uptimeMillis = now, fromScreenOff = fromScreenOff)
}
override fun onSensorChanged(event: SensorEvent) {
lastTiltAt = SystemClock.uptimeMillis()
val pending = _wakes.value
if (pending != null && lastTiltAt - pending.uptimeMillis <= TILT_GRACE_MS) {
Log.d(TAG, "wrist tilt: wake ${pending.id} was a wrist raise")
_wakes.value = null
} else {
Log.d(TAG, "wrist tilt")
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
private companion object {
const val TAG = "FaceclawWear"
/** Sensor.TYPE_WRIST_TILT_GESTURE ("android.sensor.wrist_tilt_gesture"): hidden in the SDK. */
const val TYPE_WRIST_TILT_GESTURE = 26
/** A tilt this close to a wake (either side) means the tilt caused it. */
const val TILT_GRACE_MS = 500L
}
}
@@ -0,0 +1,80 @@
package com.faceclaw.wear.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import com.faceclaw.wear.AmbientMode
import com.faceclaw.wear.PhoneLink
import java.util.Date
import kotlin.random.Random
/** Burn-in protection shifts the content by up to this many pixels each way. */
private const val BURN_IN_SHIFT_PX = 8
/**
* The always-on face: the pad's clock and its status line on black, nothing
* else and nothing moving. Redraws when [AmbientMode.tick] changes (the
* system's once-a-minute ambient update) and when the phone's state does.
*/
@Composable
fun AmbientScreen(link: PhoneLink, ambient: AmbientMode) {
val state by link.state.collectAsStateWithLifecycle()
val linkStatus by link.link.collectAsStateWithLifecycle()
val formatter = rememberClockFormatter()
val time = remember(ambient.tick, formatter) { formatter.format(Date()) }
val shift = remember(ambient.tick, ambient.burnInProtectionRequired) {
if (!ambient.burnInProtectionRequired) IntOffset.Zero else {
val random = Random(ambient.tick)
IntOffset(
random.nextInt(-BURN_IN_SHIFT_PX, BURN_IN_SHIFT_PX + 1),
random.nextInt(-BURN_IN_SHIFT_PX, BURN_IN_SHIFT_PX + 1),
)
}
}
// A 1-bit panel renders grey as noise: everything white there.
val statusColor = if (ambient.lowBit) Color.White else Color(0xFF8A8A8A)
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
.offset { shift },
) {
Text(
text = time,
color = Color.White,
fontSize = 42.sp,
textAlign = TextAlign.Center,
maxLines = 1,
modifier = Modifier.align(Alignment.Center),
)
Text(
text = padLine(state, linkStatus).text,
style = MaterialTheme.typography.title3,
color = statusColor,
textAlign = TextAlign.Center,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.align(Alignment.Center)
.offset(y = 46.dp)
.padding(horizontal = 42.dp),
)
}
}
@@ -3,15 +3,18 @@ package com.faceclaw.wear.ui
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut import androidx.compose.animation.fadeOut
import android.text.format.DateFormat
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -20,6 +23,16 @@ import androidx.wear.compose.material.Text
import com.faceclaw.wear.LinkStatus import com.faceclaw.wear.LinkStatus
import com.faceclaw.wear.Notice import com.faceclaw.wear.Notice
import com.faceclaw.wear.PhoneState import com.faceclaw.wear.PhoneState
import java.text.SimpleDateFormat
import java.util.Locale
/** Hours and minutes in the watch's 12/24-hour preference, for the pad's clock. */
@Composable
fun rememberClockFormatter(): SimpleDateFormat {
val context = LocalContext.current
val pattern = remember(context) { if (DateFormat.is24HourFormat(context)) "HH:mm" else "h:mm" }
return remember(pattern) { SimpleDateFormat(pattern, Locale.getDefault()) }
}
/** A transient pill at the bottom of the screen: ack failures and confirmations. */ /** A transient pill at the bottom of the screen: ack failures and confirmations. */
@Composable @Composable
@@ -1,17 +1,27 @@
package com.faceclaw.wear.ui package com.faceclaw.wear.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.wear.compose.material.Colors import androidx.wear.compose.material.Colors
import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.navigation.SwipeDismissableNavHost import androidx.wear.compose.navigation.SwipeDismissableNavHost
import androidx.wear.compose.navigation.composable import androidx.wear.compose.navigation.composable
import androidx.wear.compose.navigation.rememberSwipeDismissableNavController import androidx.wear.compose.navigation.rememberSwipeDismissableNavController
import com.faceclaw.wear.AmbientMode
import com.faceclaw.wear.Haptics import com.faceclaw.wear.Haptics
import com.faceclaw.wear.PhoneLink import com.faceclaw.wear.PhoneLink
import com.faceclaw.wear.Prefs
import com.faceclaw.wear.Wake
import com.faceclaw.wear.WatchPrefs import com.faceclaw.wear.WatchPrefs
import kotlinx.coroutines.flow.StateFlow
object Routes { object Routes {
const val REMOTE = "remote" const val REMOTE = "remote"
@@ -30,36 +40,70 @@ private val FaceclawColors = Colors(
onSecondary = Color(0xFF101010), onSecondary = Color(0xFF101010),
) )
/** Root: the remote pad, with every other screen a swipe-back away. */ /** The watch's ambient state, for screens that pause work while it is on. */
val LocalAmbientMode = compositionLocalOf { AmbientMode() }
/**
* Root: the remote pad, with every other screen a swipe-back away. In ambient
* [AmbientScreen] is laid over the lot. The screens stay composed underneath
* (the nav host animates any destination it composes, which on every wake
* was a visible flicker between two identical frames) and read
* [LocalAmbientMode] to pause their sensors.
*/
@Composable @Composable
fun FaceclawWearApp(link: PhoneLink, prefsStore: WatchPrefs, haptics: Haptics) { fun FaceclawWearApp(
link: PhoneLink,
prefsStore: WatchPrefs,
haptics: Haptics,
ambient: StateFlow<AmbientMode>,
wakes: StateFlow<Wake?>,
) {
val prefs by prefsStore.prefs.collectAsStateWithLifecycle() val prefs by prefsStore.prefs.collectAsStateWithLifecycle()
val ambientMode by ambient.collectAsStateWithLifecycle()
val navController = rememberSwipeDismissableNavController() val navController = rememberSwipeDismissableNavController()
MaterialTheme(colors = FaceclawColors) { MaterialTheme(colors = FaceclawColors) {
SwipeDismissableNavHost(navController = navController, startDestination = Routes.REMOTE) { CompositionLocalProvider(LocalAmbientMode provides ambientMode) {
composable(Routes.REMOTE) { Box(modifier = Modifier.fillMaxSize()) {
RemoteScreen( Screens(navController, link, prefs, prefsStore, haptics, wakes)
link = link, if (ambientMode.active) AmbientScreen(link = link, ambient = ambientMode)
prefs = prefs,
haptics = haptics,
onOpenApps = { navController.navigate(Routes.APPS) },
onOpenAssistant = { navController.navigate(Routes.ASSISTANT) },
onOpenStatus = { navController.navigate(Routes.STATUS) },
)
}
composable(Routes.APPS) {
AppsScreen(link = link, haptics = haptics, onDone = { navController.popBackStack() })
}
composable(Routes.ASSISTANT) {
AssistantScreen(link = link, haptics = haptics)
}
composable(Routes.STATUS) {
StatusScreen(link = link, haptics = haptics, onOpenSettings = { navController.navigate(Routes.SETTINGS) })
}
composable(Routes.SETTINGS) {
SettingsScreen(prefs = prefs, store = prefsStore)
} }
} }
} }
} }
@Composable
private fun Screens(
navController: NavHostController,
link: PhoneLink,
prefs: Prefs,
prefsStore: WatchPrefs,
haptics: Haptics,
wakes: StateFlow<Wake?>,
) {
SwipeDismissableNavHost(navController = navController, startDestination = Routes.REMOTE) {
composable(Routes.REMOTE) {
RemoteScreen(
link = link,
prefs = prefs,
haptics = haptics,
wakes = wakes,
onOpenApps = { navController.navigate(Routes.APPS) },
onOpenAssistant = { navController.navigate(Routes.ASSISTANT) },
onOpenStatus = { navController.navigate(Routes.STATUS) },
)
}
composable(Routes.APPS) {
AppsScreen(link = link, haptics = haptics, onDone = { navController.popBackStack() })
}
composable(Routes.ASSISTANT) {
AssistantScreen(link = link, haptics = haptics)
}
composable(Routes.STATUS) {
StatusScreen(link = link, haptics = haptics, onOpenSettings = { navController.navigate(Routes.SETTINGS) })
}
composable(Routes.SETTINGS) {
SettingsScreen(prefs = prefs, store = prefsStore)
}
}
}
@@ -1,6 +1,6 @@
package com.faceclaw.wear.ui package com.faceclaw.wear.ui
import android.text.format.DateFormat import android.os.SystemClock
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut import androidx.compose.animation.fadeOut
@@ -30,9 +30,9 @@ import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.rotary.onRotaryScrollEvent import androidx.compose.ui.input.rotary.onRotaryScrollEvent
import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
@@ -59,17 +59,24 @@ import com.faceclaw.wear.PhoneLink
import com.faceclaw.wear.Prefs import com.faceclaw.wear.Prefs
import com.faceclaw.wear.R import com.faceclaw.wear.R
import com.faceclaw.wear.SwipeAction import com.faceclaw.wear.SwipeAction
import com.faceclaw.wear.Wake
import com.faceclaw.wear.WristTwistDetector import com.faceclaw.wear.WristTwistDetector
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import java.text.SimpleDateFormat import kotlinx.coroutines.flow.StateFlow
import java.util.Date import java.util.Date
import java.util.Locale
import kotlin.math.abs import kotlin.math.abs
/** A two-finger swipe scrolls this many steps: a "page". */ /** A two-finger swipe scrolls this many steps: a "page". */
private const val TWO_FINGER_SWIPE_STEPS = 3 private const val TWO_FINGER_SWIPE_STEPS = 3
private val EDGE_REVEAL_ZONE = 24.dp private val EDGE_REVEAL_ZONE = 24.dp
private val BUTTON_TRAY_HEIGHT = 62.dp private val BUTTON_TRAY_HEIGHT = 62.dp
/**
* After a wake from an off display, how long a press still counts as the
* second tap of the double-tap that woke it. Longer than the double-tap
* timeout because the window only gets input focus ~300 ms into such a wake
* and the press queues behind that.
*/
private const val SCREEN_ON_SECOND_TAP_WINDOW_MS = 600L
/** /**
* The touchpad. The whole screen is the pad: tap = select, double-tap = * The touchpad. The whole screen is the pad: tap = select, double-tap =
@@ -79,6 +86,12 @@ private val BUTTON_TRAY_HEIGHT = 62.dp
* at a time for the latter). Fingertip pinch-taps from the motion sensors * at a time for the latter). Fingertip pinch-taps from the motion sensors
* select / go back, and two quick wrist twists go back. An upward swipe that * select / go back, and two quick wrist twists go back. An upward swipe that
* begins at the bottom edge reveals the otherwise-hidden action buttons. * begins at the bottom edge reveals the otherwise-hidden action buttons.
*
* A tap that wakes the display never reaches the pad (the system eats it),
* so each wake in [wakes] stands in for a first tap: a press inside the
* double-tap window makes the pair a double-tap, and a lone wake from ambient
* (where the pad was already showing) becomes a tap once the window closes.
* A lone wake from an off display just turned the screen on.
*/ */
// rememberActiveFocusRequester (rotary focus) is still experimental in Wear Compose 1.4. // rememberActiveFocusRequester (rotary focus) is still experimental in Wear Compose 1.4.
@OptIn(ExperimentalWearFoundationApi::class) @OptIn(ExperimentalWearFoundationApi::class)
@@ -87,6 +100,7 @@ fun RemoteScreen(
link: PhoneLink, link: PhoneLink,
prefs: Prefs, prefs: Prefs,
haptics: Haptics, haptics: Haptics,
wakes: StateFlow<Wake?>,
onOpenApps: () -> Unit, onOpenApps: () -> Unit,
onOpenAssistant: () -> Unit, onOpenAssistant: () -> Unit,
onOpenStatus: () -> Unit, onOpenStatus: () -> Unit,
@@ -94,6 +108,10 @@ fun RemoteScreen(
val state by link.state.collectAsStateWithLifecycle() val state by link.state.collectAsStateWithLifecycle()
val linkStatus by link.link.collectAsStateWithLifecycle() val linkStatus by link.link.collectAsStateWithLifecycle()
val notice by link.notice.collectAsStateWithLifecycle() val notice by link.notice.collectAsStateWithLifecycle()
val wake by wakes.collectAsStateWithLifecycle()
val ambientActive = LocalAmbientMode.current.active
val doubleTapTimeout = LocalViewConfiguration.current.doubleTapTimeoutMillis
val pendingTap = remember { PendingTap() }
val currentPrefs by rememberUpdatedState(prefs) val currentPrefs by rememberUpdatedState(prefs)
val currentState by rememberUpdatedState(state) val currentState by rememberUpdatedState(state)
val view = LocalView.current val view = LocalView.current
@@ -243,9 +261,25 @@ fun RemoteScreen(
) )
} }
// Motion-sensor gestures only count on a wrist (see OnBodyMonitor). // The wake-tap: arm the detector for a second press, and when none comes
// decide what the lone tap meant. A wake the tracker re-attributes to a
// wrist raise arrives as null and cancels all of it.
LaunchedEffect(wake) {
val current = wake
if (current == null) {
pendingTap.disarm()
return@LaunchedEffect
}
val window = if (current.fromScreenOff) SCREEN_ON_SECOND_TAP_WINDOW_MS else doubleTapTimeout
pendingTap.arm(current.uptimeMillis, window)
delay((current.uptimeMillis + window - SystemClock.uptimeMillis()).coerceAtLeast(0L))
if (pendingTap.expire() && !current.fromScreenOff) click()
}
// Motion-sensor gestures only count on a wrist (see OnBodyMonitor); none
// of the sensors run in ambient.
val onBody = remember { OnBodyMonitor(view.context) } val onBody = remember { OnBodyMonitor(view.context) }
WhileStartedEffect(onBody, start = onBody::start, stop = onBody::stop) WhileStartedEffect(onBody, enabled = !ambientActive, start = onBody::start, stop = onBody::stop)
// Fingertip (pinch) taps from the motion sensors, only while the pad is up. // Fingertip (pinch) taps from the motion sensors, only while the pad is up.
val fingerTapsEnabled = prefs.fingerTaps val fingerTapsEnabled = prefs.fingerTaps
@@ -259,7 +293,7 @@ fun RemoteScreen(
onDoubleTap = { doubleClick() }, onDoubleTap = { doubleClick() },
) )
} }
WhileStartedEffect(fingerTapDetector, start = { fingerTapDetector?.start() }, stop = { fingerTapDetector?.stop() }) WhileStartedEffect(fingerTapDetector, enabled = !ambientActive, start = { fingerTapDetector?.start() }, stop = { fingerTapDetector?.stop() })
// Two quick wrist twists = back, from the gyroscope, only while the pad is up. // Two quick wrist twists = back, from the gyroscope, only while the pad is up.
val wristTwistEnabled = prefs.wristTwist val wristTwistEnabled = prefs.wristTwist
val wristTwistDetector = remember(wristTwistEnabled, link, haptics) { val wristTwistDetector = remember(wristTwistEnabled, link, haptics) {
@@ -271,7 +305,7 @@ fun RemoteScreen(
onDoubleTwist = { doubleClick() }, onDoubleTwist = { doubleClick() },
) )
} }
WhileStartedEffect(wristTwistDetector, start = { wristTwistDetector?.start() }, stop = { wristTwistDetector?.stop() }) WhileStartedEffect(wristTwistDetector, enabled = !ambientActive, start = { wristTwistDetector?.start() }, stop = { wristTwistDetector?.stop() })
// A refused or unanswered gesture gets a distinct buzz, so the wrist knows // A refused or unanswered gesture gets a distinct buzz, so the wrist knows
// without looking (the notice pill says why). // without looking (the notice pill says why).
@@ -284,6 +318,8 @@ fun RemoteScreen(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.onRotaryScrollEvent { event -> .onRotaryScrollEvent { event ->
// A crown turn can be what woke the display: not a tap, then.
pendingTap.disarm()
crownAccumulator += event.verticalScrollPixels crownAccumulator += event.verticalScrollPixels
val threshold = currentPrefs.crownSensitivity.pixelsPerStep val threshold = currentPrefs.crownSensitivity.pixelsPerStep
var steps = 0 var steps = 0
@@ -299,7 +335,7 @@ fun RemoteScreen(
.focusRequester(focusRequester) .focusRequester(focusRequester)
.focusable() .focusable()
.onSizeChanged { padHeight[0] = it.height.toFloat() } .onSizeChanged { padHeight[0] = it.height.toFloat() }
.pointerInput(callbacks) { detectTouchpadGestures(callbacks) }, .pointerInput(callbacks) { detectTouchpadGestures(callbacks, pendingTap) },
) { ) {
StraightTime(modifier = Modifier.align(Alignment.Center)) StraightTime(modifier = Modifier.align(Alignment.Center))
@@ -362,11 +398,14 @@ fun RemoteScreen(
* leaving the composition. A plain DisposableEffect keeps sensors registered * leaving the composition. A plain DisposableEffect keeps sensors registered
* while the activity sits stopped-but-cached (palmed screen, back on the watch * while the activity sits stopped-but-cached (palmed screen, back on the watch
* face), which at gyroscope/accelerometer rates is a real battery drain. * face), which at gyroscope/accelerometer rates is a real battery drain.
* [enabled] false holds it stopped regardless (ambient, where the activity
* stays started for the clock).
*/ */
@Composable @Composable
private fun WhileStartedEffect(key: Any?, start: () -> Unit, stop: () -> Unit) { private fun WhileStartedEffect(key: Any?, enabled: Boolean = true, start: () -> Unit, stop: () -> Unit) {
val lifecycleOwner = LocalLifecycleOwner.current val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, key) { DisposableEffect(lifecycleOwner, key, enabled) {
if (!enabled) return@DisposableEffect onDispose { }
val observer = LifecycleEventObserver { _, event -> val observer = LifecycleEventObserver { _, event ->
when (event) { when (event) {
Lifecycle.Event.ON_START -> start() Lifecycle.Event.ON_START -> start()
@@ -382,14 +421,18 @@ private fun WhileStartedEffect(key: Any?, start: () -> Unit, stop: () -> Unit) {
} }
} }
/** A large, straight clock fixed on the vertical centre of the touchpad. */ /**
* A large, straight clock fixed on the vertical centre of the touchpad. The
* minute timer cannot run while the watch dozes, so the clock also resyncs
* on every ambient tick and on the way out of ambient: the first frame after
* a wake would otherwise show the minute the watch dozed off at.
*/
@Composable @Composable
private fun StraightTime(modifier: Modifier = Modifier) { private fun StraightTime(modifier: Modifier = Modifier) {
val context = LocalContext.current
var now by remember { mutableStateOf(System.currentTimeMillis()) } var now by remember { mutableStateOf(System.currentTimeMillis()) }
val pattern = remember(context) { if (DateFormat.is24HourFormat(context)) "HH:mm" else "h:mm" } val formatter = rememberClockFormatter()
val formatter = remember(pattern) { SimpleDateFormat(pattern, Locale.getDefault()) } val ambient = LocalAmbientMode.current
LaunchedEffect(Unit) { LaunchedEffect(ambient.tick, ambient.active) {
while (true) { while (true) {
val current = System.currentTimeMillis() val current = System.currentTimeMillis()
now = current now = current
@@ -2,9 +2,10 @@ package com.faceclaw.wear.ui
import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.AwaitPointerEventScope
import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.positionChanged import androidx.compose.ui.input.pointer.positionChanged
import kotlin.math.abs import kotlin.math.abs
@@ -24,15 +25,51 @@ class TouchpadCallbacks(
val onSwipe: (start: Offset, dx: Float, dy: Float, durationMs: Long) -> Unit, val onSwipe: (start: Offset, dx: Float, dy: Float, durationMs: Long) -> Unit,
) )
/**
* A first tap the pad never saw: the touch that woke the display, which the
* system consumes. Armed by the pad on a wake; the next press inside the
* window is then the second tap of a pair (a double-tap, or tap-then-hold),
* and if no press comes the pad decides what a lone wake-tap meant. Main
* thread only.
*/
class PendingTap {
private var armedAt = -1L
private var windowMs = 0L
fun arm(uptimeMillis: Long, windowMs: Long) {
armedAt = uptimeMillis
this.windowMs = windowMs
}
fun disarm() {
armedAt = -1L
}
/** A press just landed: whether it pairs with the pending tap (which is spent either way). */
fun claim(downUptimeMillis: Long): Boolean {
val at = armedAt
armedAt = -1L
return at >= 0 && downUptimeMillis - at in 0..windowMs
}
/** The window closed: whether the tap was still pending (it is spent now). */
fun expire(): Boolean {
val pending = armedAt >= 0
armedAt = -1L
return pending
}
}
/** /**
* One detector for everything the pad does, so a gesture is reported exactly * One detector for everything the pad does, so a gesture is reported exactly
* once: tap, double-tap (a second tap inside the double-tap timeout), a hold * once: tap, double-tap (a second tap inside the double-tap timeout), a hold
* (reported at the long-press timeout and again on release), tap-then-hold (a * (reported at the long-press timeout and again on release), tap-then-hold (a
* second tap held past the long-press timeout), a swipe, and a two-finger tap * second tap held past the long-press timeout), a swipe, and a two-finger tap
* or swipe. Written as a single awaitEachGesture loop because the stock * or swipe. Written as a single awaitEachGesture loop because the stock
* detectors would each claim the same finger. * detectors would each claim the same finger. A press that pairs with
* [pendingTap] skips straight to the second-tap handling.
*/ */
suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallbacks) { suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallbacks, pendingTap: PendingTap) {
val longPressTimeout = viewConfiguration.longPressTimeoutMillis val longPressTimeout = viewConfiguration.longPressTimeoutMillis
val doubleTapTimeout = viewConfiguration.doubleTapTimeoutMillis val doubleTapTimeout = viewConfiguration.doubleTapTimeoutMillis
val slop = viewConfiguration.touchSlop val slop = viewConfiguration.touchSlop
@@ -41,6 +78,10 @@ suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallback
val down = awaitFirstDown() val down = awaitFirstDown()
down.consume() down.consume()
val downTime = down.uptimeMillis val downTime = down.uptimeMillis
if (pendingTap.claim(downTime)) {
secondTap(callbacks, longPressTimeout, down.position, down)
return@awaitEachGesture
}
var maxPointers = 1 var maxPointers = 1
var moved = false var moved = false
var longPressed = false var longPressed = false
@@ -98,33 +139,7 @@ suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallback
if (second == null) { if (second == null) {
callbacks.onTap(down.position) callbacks.onTap(down.position)
} else { } else {
second.consume() secondTap(callbacks, longPressTimeout, down.position, second)
// Released within the long-press timeout it's a
// double-tap; held past it, the G2 tap-then-hold
// gesture (reported once at the timeout, movement
// tolerated, the rest of the hold swallowed).
var held = false
while (true) {
val remaining2 = if (held) {
HOLD_POLL_MS
} else {
longPressTimeout - (System.currentTimeMillis() - wallClockAt(second.uptimeMillis))
}
val event2 = withTimeoutOrNull(remaining2.coerceAtLeast(1L)) { awaitPointerEvent() }
if (event2 == null) {
if (!held) {
held = true
callbacks.onShortThenLongPress()
}
continue
}
if (event2.changes.any { it.isConsumed }) break
for (change in event2.changes) change.consume()
if (event2.changes.none { it.pressed }) {
if (!held) callbacks.onDoubleTap(down.position)
break
}
}
} }
} }
} }
@@ -136,6 +151,42 @@ suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallback
} }
} }
/**
* The second press of a pair. Released within the long-press timeout it's a
* double-tap; held past it, the G2 tap-then-hold gesture (reported once at
* the timeout, movement tolerated, the rest of the hold swallowed).
*/
private suspend fun AwaitPointerEventScope.secondTap(
callbacks: TouchpadCallbacks,
longPressTimeout: Long,
first: Offset,
second: PointerInputChange,
) {
second.consume()
var held = false
while (true) {
val remaining = if (held) {
HOLD_POLL_MS
} else {
longPressTimeout - (System.currentTimeMillis() - wallClockAt(second.uptimeMillis))
}
val event = withTimeoutOrNull(remaining.coerceAtLeast(1L)) { awaitPointerEvent() }
if (event == null) {
if (!held) {
held = true
callbacks.onShortThenLongPress()
}
continue
}
if (event.changes.any { it.isConsumed }) break
for (change in event.changes) change.consume()
if (event.changes.none { it.pressed }) {
if (!held) callbacks.onDoubleTap(first)
break
}
}
}
/** /**
* Observe the button tray before its child buttons consume a pointer. A * Observe the button tray before its child buttons consume a pointer. A
* downward drag claims the gesture and dismisses the tray; a tap remains * downward drag claims the gesture and dismisses the tray; a tap remains