email: add Wear OS watch experience in merged APK
- Commit
446e433c76664bbb278fe8bac75d1ac2c765654b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 03:50 UTC (5 hours ago)
- Parents
2b51024
Single merged phone+watch APK following contacts/notes: FormFactor (FEATURE_WATCH) routes MainActivity to WearMainActivity (WearShellActivity, no launcher entry) before phone state loads; manifest gains touchscreen not-required, standalone=false, the ConduitSyncTriggerReceiver (CONDUIT signature permission) and nativeAbis armv7. Watch: inbox list (sender/subject/time, unread bold) and message detail with readable plain-text body from the bounded conduit snapshot (30 recent unified-inbox messages via WearEmailSync/WearLinkBridge over WearLinkClientNode, appId email; only the Watch conduit app holds Bluetooth permission). Mark read/unread is a filled button that queues a pending op in WearEmailStore; the phone applies it in Room and mirrors the IMAP Seen flag, and the op clears only when a fresh snapshot reflects it. Open on phone is the last action. No archive button: Email has no archive/move primitive on the phone. Sync triggers: conduit Connected, watch snapshot request, and the Watch app sync-trigger intent. group=wear screenshot previews added and :email:metadata generated the wear listing images. Verified: ./gradlew :email:lint :email:lintVitalRelease :email:testDevUnitTest :email:metadata green (combined run with securemail also green).
Diff
email/AGENTS.md
diff --git a/email/AGENTS.md b/email/AGENTS.mdindex e10c39412f..6a46c03863 100644--- a/email/AGENTS.md+++ b/email/AGENTS.md@@ -5,8 +5,8 @@ _Install: ./install email (dev by default)._ - Gradle: :email / dir: email/ - Package roots present: ui, data, platform, network, intents, widget-- Entry files: MainActivity.kt, Route.kt, Navigation.kt-- Deps: :library:room, :library:widgets, :library:network+- Entry files: MainActivity.kt (sole launcher; routes watches to WearMainActivity), Route.kt, Navigation.kt, ui/WearMainActivity.kt+- Deps: :library:room, :library:widgets, :library:network, :library:wearlink, :library:log, Wear Compose (material + foundation) - Metadata: metadata_data/email.md (present) - Rust: no / screenshotTest: yes @@ -126,12 +126,29 @@ _Install: ./install email (dev by default)._ - com/vayunmathur/email/intents/GetRecentIntent.kt - com/vayunmathur/email/intents/SearchIntent.kt - com/vayunmathur/email/intents/EmailDataMapper.kt+### Watch experience (ui/ + data/ + sync/ + platform/)+- com/vayunmathur/email/ui/WearMainActivity.kt — watch entry (WearShellActivity, exported=false)+- com/vayunmathur/email/ui/WearRoute.kt, WearInboxListScreen.kt, WearMessageScreen.kt+- com/vayunmathur/email/data/WearEmailStore.kt — watch snapshot + pending mark-read ops+- com/vayunmathur/email/sync/WearEmailSync.kt — phone conduit publish + op apply+- com/vayunmathur/email/sync/WearLinkBridge.kt, WearWatchStatePublisher.kt, ConduitSyncTriggerReceiver.kt+- com/vayunmathur/email/platform/FormFactor.kt — watch detection (FEATURE_WATCH) ### widget/ — unified-inbox home widget - com/vayunmathur/email/widget/EmailWidget.kt — includes `EmailWidgetReceiver` (one widget, one file) +## One APK, two form factors (phone + watch)+Single merged APK (same applicationId/signing on phone and watch; no watch uses-feature, touchscreen not-required, standalone=false). `platform/FormFactor` reads `PackageManager.FEATURE_WATCH`: `MainActivity` forwards watches to `ui/WearMainActivity` before any phone state loads; the watch activity has no launcher entry.++## Wear sync (Watch conduit client)+Protocol in `:library:wearlink` at `com.vayunmathur.library.wearlink.email.WearEmailProtocol` (golden/cap tests in `src/test/.../sync/WearEmailProtocolTest`). Phone publishes a bounded recent unified-inbox snapshot (`/email/snapshot`: 30 messages, sender/subject capped, plain-text body ≤4,000 chars, ≤90,000 JSON bytes) via `sync/WearEmailSync`; watch persists it in `data/WearEmailStore` and renders offline. Watch mark read/unread ops (`/email/op`) apply on the phone (Room + IMAP \\Seen, mirroring `EmailViewModel.markAsRead`) and stay pending until a snapshot reflects them. No archive op: the phone has no IMAP archive/move primitive (only seen, expunge-delete, snooze), so the watch offers no fake archive. Triggers: conduit Connected, watch request (`/email/request-sync`), and `sync/ConduitSyncTriggerReceiver` (CONDUIT signature permission). Transport is `WearLinkClientNode` (appId `email`); only the Watch conduit app holds Bluetooth permission.++## Watch experience+`ui/WearMainActivity` (WearShellActivity) routes `ui/WearRoute` (Inbox / Message(id)): inbox list (sender/subject/time, unread bold) and message detail (readable plain-text body, Mark read/unread filled button, Open on phone last via `/email/open-on-phone`). Watch screenshots are `group="wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt` via `:email:metadata`.+ ## Verify (this module only) ``` ./gradlew :email:compileDevKotlin-./gradlew :email:lint+./gradlew :email:lint :email:lintVitalRelease :email:testDevUnitTest ./gradlew :email:checkMetadata+./gradlew :email:metadata ```
email/build.gradle.kts
diff --git a/email/build.gradle.kts b/email/build.gradle.ktsindex 83d93ff790..75a99f12dd 100644--- a/email/build.gradle.kts+++ b/email/build.gradle.kts@@ -7,6 +7,11 @@ launcherIcon { symbol = "mail" } +// Pixel Watch is armeabi-v7a (32-bit) only: an arm64-only APK is rejected at install.+nativeAbis {+ armv7 = true+}+ android { namespace = "com.vayunmathur.email" defaultConfig {@@ -63,6 +68,13 @@ dependencies { implementation(libs.androidx.glance.material3) implementation(project(":library:widgets")) implementation(project(":library:network"))+ // Merged phone+watch Wear OS experience (single APK, FormFactor routing).+ implementation(project(":library:wearlink"))+ implementation(project(":library:log"))+ implementation(libs.androidx.wear.compose.material)+ implementation(libs.androidx.wear.compose.foundation)+ implementation(libs.kotlinx.coroutines.android)+ implementation(libs.kotlinx.serialization.json) testImplementation(libs.androidx.work.testing) testImplementation(libs.androidx.glance.testing) testImplementation(libs.androidx.glance.appwidget.testing)
email/src/main/AndroidManifest.xml
diff --git a/email/src/main/AndroidManifest.xml b/email/src/main/AndroidManifest.xmlindex b3dca0d01c..b93ba3b302 100644--- a/email/src/main/AndroidManifest.xml+++ b/email/src/main/AndroidManifest.xml@@ -13,6 +13,9 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + <!-- Single merged phone+watch APK: no watch uses-feature (see contacts/notes). -->+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />+ <permission android:name="com.vayunmathur.email.permissions.ACCESS_EMAIL" android:protectionLevel="signature" />@@ -28,6 +31,7 @@ android:networkSecurityConfig="@xml/network_security_config" android:theme="@style/Theme.General" tools:replace="android:networkSecurityConfig">+ <meta-data android:name="com.google.android.wearable.standalone" android:value="false" /> <activity android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:name=".MainActivity"@@ -141,6 +145,19 @@ android:exported="true" android:theme="@android:style/Theme.NoDisplay" android:permission="com.vayunmathur.email.permissions.ACCESS_EMAIL" />+ <receiver+ android:name=".sync.ConduitSyncTriggerReceiver"+ android:exported="true"+ android:permission="com.vayunmathur.watch.permissions.CONDUIT">+ <intent-filter>+ <action android:name="com.vayunmathur.watch.action.SYNC_TRIGGER" />+ </intent-filter>+ </receiver>++ <activity+ android:name=".ui.WearMainActivity"+ android:exported="false"+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar" /> </application> </manifest>
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex f12ebc703c..8e7ba3e228 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -1,6 +1,7 @@ package com.vayunmathur.email import android.content.Intent+import android.os.Bundle import androidx.compose.runtime.Composable import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewmodel.compose.viewModel@@ -17,6 +18,9 @@ import com.vayunmathur.email.platform.StartupGuard import com.vayunmathur.email.platform.IntentState import com.vayunmathur.email.ui.MainContent import com.vayunmathur.email.widget.EmailWidgetReceiver+import com.vayunmathur.email.platform.FormFactor+import com.vayunmathur.email.sync.WearEmailSync+import com.vayunmathur.email.ui.WearMainActivity import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.ui.MaActivity@@ -28,8 +32,22 @@ import kotlinx.coroutines.launch /** Entry activity that wires the email UI, navigation and background sync startup. */ class MainActivity : MaActivity() { + /** True on a watch, where this activity only forwards to [WearMainActivity]. */+ private var routedToWear = false++ override fun onCreate(savedInstanceState: Bundle?) {+ routedToWear = FormFactor.isWatch(this)+ super.onCreate(savedInstanceState)+ if (routedToWear) {+ startActivity(Intent(this, WearMainActivity::class.java))+ finish()+ }+ }+ override fun onCreateBeforeContent() {+ if (routedToWear) return NetworkClient.init(this, TrustBundle.SYSTEM)+ WearEmailSync.get(this).start() handleIntent(intent) // Single deferred startup block: every worker/service enqueue below // is thread-safe (WorkManager enqueues, startForegroundService) and@@ -66,6 +84,7 @@ class MainActivity : MaActivity() { @Composable override fun Content() {+ if (routedToWear) return OfflineAware { val viewModel: EmailViewModel = viewModel() MainContent(viewModel = viewModel)
email/src/main/java/com/vayunmathur/email/data/WearEmailStore.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/WearEmailStore.kt b/email/src/main/java/com/vayunmathur/email/data/WearEmailStore.ktnew file mode 100644index 0000000000..f4601add4d--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/data/WearEmailStore.kt@@ -0,0 +1,104 @@+package com.vayunmathur.email.data++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.email.WearEmailMessage+import com.vayunmathur.library.wearlink.email.WearEmailOp+import com.vayunmathur.library.wearlink.email.WearEmailProtocol+import com.vayunmathur.library.wearlink.email.WearEmailSnapshot+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString+import java.io.File++/** Watch local truth: last phone snapshot merged with pending mark-read ops, persisted as JSON. */+class WearEmailStore private constructor(+ private val context: Context,+) {+ companion object {+ private const val TAG = "WearEmailStore"++ @Volatile private var instance: WearEmailStore? = null++ fun get(context: Context): WearEmailStore =+ instance ?: synchronized(this) {+ instance ?: WearEmailStore(context.applicationContext).also { instance = it }+ }+ }++ private val snapshotFile = File(context.filesDir, "wear-email-snapshot.json")+ private val pendingFile = File(context.filesDir, "wear-email-pending.json")+ private var lastSnapshot: WearEmailSnapshot = loadSnapshot()+ private val _pendingOps = MutableStateFlow(loadPending())+ val pendingOps: StateFlow<List<WearEmailOp>> = _pendingOps.asStateFlow()+ private val _messages = MutableStateFlow(merge(lastSnapshot, _pendingOps.value))+ val messages: StateFlow<List<WearEmailMessage>> = _messages.asStateFlow()+ val appliedGeneratedAtMillis: Long get() = lastSnapshot.generatedAtMillis++ fun setSnapshot(snapshot: WearEmailSnapshot) {+ lastSnapshot = snapshot+ val reflected =+ _pendingOps.value.filter { op ->+ snapshot.messages.firstOrNull { it.id == op.messageId }?.isRead == op.read+ }+ if (reflected.isNotEmpty()) {+ _pendingOps.value = _pendingOps.value - reflected.toSet()+ persistPending()+ }+ _messages.value = merge(snapshot, _pendingOps.value)+ persistSnapshot()+ com.vayunmathur.email.sync.WearLinkBridge+ .publishWatchState(context)+ }++ fun markRead(+ message: WearEmailMessage,+ read: Boolean,+ ) {+ val op =+ WearEmailOp(+ com.vayunmathur.library.wearlink.email.WearEmailOpKind.MARK_READ,+ message.id,+ message.accountEmail,+ message.folderName,+ message.uid,+ read,+ )+ _pendingOps.value = _pendingOps.value.filter { it.messageId != message.id } + op+ persistPending()+ _messages.value = merge(lastSnapshot, _pendingOps.value)+ com.vayunmathur.email.sync.WearLinkBridge+ .flushPending(context)+ }++ private fun merge(+ snapshot: WearEmailSnapshot,+ ops: List<WearEmailOp>,+ ): List<WearEmailMessage> {+ val byId = ops.associateBy { it.messageId }+ return snapshot.messages.map { m -> byId[m.id]?.let { m.copy(isRead = it.read) } ?: m }+ }++ private fun loadSnapshot(): WearEmailSnapshot =+ runCatching {+ WearEmailProtocol.json.decodeFromString<WearEmailSnapshot>(snapshotFile.readText())+ }.getOrDefault(WearEmailSnapshot())++ private fun loadPending(): List<WearEmailOp> =+ runCatching {+ WearEmailProtocol.json.decodeFromString<List<WearEmailOp>>(pendingFile.readText())+ }.getOrDefault(emptyList())++ private fun persistSnapshot() {+ runCatching {+ snapshotFile.writeText(WearEmailProtocol.json.encodeToString(lastSnapshot))+ }.onFailure { Log.status(TAG, "persist failed: ${it.message}") }+ }++ private fun persistPending() {+ runCatching {+ pendingFile.writeText(WearEmailProtocol.json.encodeToString(_pendingOps.value))+ }.onFailure { Log.status(TAG, "persist pending failed: ${it.message}") }+ }+}
email/src/main/java/com/vayunmathur/email/platform/FormFactor.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/FormFactor.kt b/email/src/main/java/com/vayunmathur/email/platform/FormFactor.ktnew file mode 100644index 0000000000..df8ac3d47d--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/platform/FormFactor.kt@@ -0,0 +1,12 @@+package com.vayunmathur.email.platform++import android.content.Context+import android.content.pm.PackageManager++/** Runtime watch detection for the single merged Email APK (see contacts/notes pattern). */+object FormFactor {+ fun isWatch(context: Context): Boolean =+ isWatch(context.packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH))++ fun isWatch(hasWatchSystemFeature: Boolean): Boolean = hasWatchSystemFeature+}
email/src/main/java/com/vayunmathur/email/sync/ConduitSyncTriggerReceiver.kt
diff --git a/email/src/main/java/com/vayunmathur/email/sync/ConduitSyncTriggerReceiver.kt b/email/src/main/java/com/vayunmathur/email/sync/ConduitSyncTriggerReceiver.ktnew file mode 100644index 0000000000..b49a877bd0--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/sync/ConduitSyncTriggerReceiver.kt@@ -0,0 +1,50 @@+package com.vayunmathur.email.sync++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.ConduitSync+import com.vayunmathur.library.wearlink.email.WearEmailProtocol+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/** Pure trigger decision for the Watch conduit scheduled push (unit-tested). */+object ConduitSyncTriggerHandler {+ val APP_ID: String = ConduitProtocol.routeKey(WearEmailProtocol.SNAPSHOT_PATH)++ fun handle(+ action: String?,+ appId: String?,+ publish: () -> Unit,+ ): Boolean {+ if (!ConduitSync.isTrigger(action, appId, APP_ID)) return false+ publish()+ return true+ }+}++/** Fires the existing conduit publish when the phone Watch app asks for a push. No UI, no prompt. */+class ConduitSyncTriggerReceiver : BroadcastReceiver() {+ override fun onReceive(+ context: Context,+ intent: Intent,+ ) {+ ConduitSyncTriggerHandler.handle(intent.action, intent.getStringExtra(ConduitSync.EXTRA_APP_ID)) {+ val pending = goAsync()+ val appContext = context.applicationContext+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ scope.launch {+ try {+ val sync = WearEmailSync.get(appContext)+ sync.start()+ sync.triggerPush()+ } finally {+ pending.finish()+ }+ }+ }+ }+}
email/src/main/java/com/vayunmathur/email/sync/WearEmailSync.kt
diff --git a/email/src/main/java/com/vayunmathur/email/sync/WearEmailSync.kt b/email/src/main/java/com/vayunmathur/email/sync/WearEmailSync.ktnew file mode 100644index 0000000000..6d4fa2935b--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/sync/WearEmailSync.kt@@ -0,0 +1,176 @@+package com.vayunmathur.email.sync++import android.content.Context+import android.content.Intent+import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.EmailRepository+import com.vayunmathur.email.data.plainTextBody+import com.vayunmathur.email.data.senderDisplayName+import com.vayunmathur.email.platform.EmailManager+import com.vayunmathur.email.platform.imapServer+import com.vayunmathur.email.platform.loginUser+import com.vayunmathur.email.platform.resolveAuth+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode+import com.vayunmathur.library.wearlink.email.WearEmailMessage+import com.vayunmathur.library.wearlink.email.WearEmailOp+import com.vayunmathur.library.wearlink.email.WearEmailProtocol+import com.vayunmathur.library.wearlink.email.WearEmailWatchState+import com.vayunmathur.library.wearlink.email.buildWearEmailSnapshot+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/** Phone -> watch wire row: readable plain-text body, sender display name. */+fun EmailMessage.toWearEmail(): WearEmailMessage =+ WearEmailMessage(+ id = "$accountEmail|$folderName|$id",+ accountEmail = accountEmail,+ folderName = folderName,+ uid = id,+ sender = senderDisplayName(from).ifBlank { from },+ subject = subject,+ dateMillis = dateMillis,+ isRead = isRead,+ body = plainTextBody() ?: body ?: peekContent,+ )++/**+ * Phone side of Email wear sync over the Watch conduit client: bounded+ * inbox snapshot as a data item, watch state as a data item, and+ * mark-read ops / snapshot requests as messages. Republishes on conduit+ * Connected, on request, and on the sync-trigger intent; inbox changes+ * while this process lives republish through [triggerPush] callers.+ * With the Watch app absent the node reports NotInstalled/Unavailable+ * and the sync stays idle.+ */+class WearEmailSync private constructor(+ context: Context,+) {+ companion object {+ private const val TAG = "WearEmailSync"++ @Volatile private var instance: WearEmailSync? = null++ fun get(context: Context): WearEmailSync =+ instance ?: synchronized(this) {+ instance ?: WearEmailSync(context.applicationContext).also { instance = it }+ }+ }++ private val appContext = context.applicationContext+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val listener =+ object : WearLinkListener {+ override fun onData(+ path: String,+ body: ByteArray,+ ) {+ if (path != WearEmailProtocol.WATCH_STATE_PATH) return+ runCatching { WearEmailProtocol.json.decodeFromString<WearEmailWatchState>(body.decodeToString()) }+ }++ override fun onMessage(+ path: String,+ body: ByteArray,+ ) {+ if (path.endsWith("/open-on-phone")) {+ runCatching {+ appContext.startActivity(+ Intent(+ appContext,+ com.vayunmathur.email.MainActivity::class.java,+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("wear_open_id", body.decodeToString()),+ )+ }+ return+ }+ when (path) {+ WearEmailProtocol.REQUEST_SYNC_PATH -> scope.launch { publishSnapshot() }+ WearEmailProtocol.OP_PATH -> {+ val op =+ runCatching {+ WearEmailProtocol.json.decodeFromString<WearEmailOp>(+ body.decodeToString(),+ )+ }.getOrNull()+ ?: return+ scope.launch { if (applyWearOp(op)) publishSnapshot() }+ }+ }+ }+ }+ private val node =+ WearLinkClientNode(appContext, ConduitProtocol.routeKey(WearEmailProtocol.SNAPSHOT_PATH), listener)+ private var started = false++ fun start() {+ if (started) return+ started = true+ scope.launch {+ var wasConnected = false+ node.state.collect { state ->+ val connected = state is WearLinkState.Connected+ if (connected && !wasConnected) publishSnapshot()+ wasConnected = connected+ }+ }+ node.start()+ }++ /** Push the current snapshot now (sync-trigger intent / watch request path). */+ fun triggerPush() {+ scope.launch { publishSnapshot() }+ }++ fun syncNow() = triggerPush()++ suspend fun publishSnapshot() {+ val rows =+ runCatching {+ EmailRepository+ .get(+ appContext,+ ).queries+ .getRecentUnifiedMessages()+ }.getOrDefault(emptyList())+ val snapshot = buildWearEmailSnapshot(rows.map { it.toWearEmail() }, System.currentTimeMillis())+ val sent =+ node.putData(+ WearEmailProtocol.SNAPSHOT_PATH,+ WearEmailProtocol.json.encodeToString(snapshot).encodeToByteArray(),+ )+ if (!sent) Log.status(TAG, "publish not delivered (conduit link not connected)")+ }++ /** Apply one watch mark-read op: local DB first, then the IMAP seen flag, mirroring EmailViewModel.markAsRead. */+ internal suspend fun applyWearOp(op: WearEmailOp): Boolean {+ val repo = EmailRepository.get(appContext)+ runCatching { repo.messages.updateReadStatus(op.accountEmail, op.folderName, op.uid, op.read) }+ .onFailure {+ Log.status(TAG, "mark-read failed: ${it.message}")+ return false+ }+ val account =+ runCatching { repo.accounts.getAccounts().firstOrNull { it.email == op.accountEmail } }+ .getOrNull()+ if (account != null) {+ runCatching {+ EmailManager().setSeenFlag(+ account.imapServer(),+ account.loginUser(),+ account.resolveAuth(appContext),+ op.folderName,+ op.uid,+ op.read,+ )+ }.onFailure { Log.status(TAG, "IMAP seen sync failed: ${it.message}") }+ }+ return true+ }+}
email/src/main/java/com/vayunmathur/email/sync/WearLinkBridge.kt
diff --git a/email/src/main/java/com/vayunmathur/email/sync/WearLinkBridge.kt b/email/src/main/java/com/vayunmathur/email/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..c72d556569--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/sync/WearLinkBridge.kt@@ -0,0 +1,97 @@+package com.vayunmathur.email.sync++import android.content.Context+import com.vayunmathur.email.data.WearEmailStore+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode+import com.vayunmathur.library.wearlink.email.WearEmailProtocol+import com.vayunmathur.library.wearlink.email.WearEmailSnapshot+import com.vayunmathur.library.wearlink.email.WearEmailWatchState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/** Watch side of the conduit client for Email: snapshot into the store, ops/state out. */+object WearLinkBridge {+ private const val TAG = "WearEmailBridge"+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile private var node: WearLinkClientNode? = null++ fun get(context: Context): WearLinkClientNode {+ val appContext = context.applicationContext+ return node ?: synchronized(this) { node ?: create(appContext).also { node = it } }+ }++ private fun create(context: Context): WearLinkClientNode {+ val listener =+ object : WearLinkListener {+ override fun onData(+ path: String,+ body: ByteArray,+ ) {+ if (path != WearEmailProtocol.SNAPSHOT_PATH) return+ val snapshot =+ runCatching {+ WearEmailProtocol.json.decodeFromString<WearEmailSnapshot>(body.decodeToString())+ }.getOrNull()+ if (snapshot == null) {+ Log.status(TAG, "ignoring malformed snapshot")+ return+ }+ WearEmailStore.get(context).setSnapshot(snapshot)+ }+ }+ val created = WearLinkClientNode(context, ConduitProtocol.routeKey(WearEmailProtocol.SNAPSHOT_PATH), listener)+ scope.launch {+ var wasConnected = false+ created.state.collect { state ->+ val connected = state is WearLinkState.Connected+ if (connected && !wasConnected) {+ flushPending(context)+ publishWatchState(context)+ }+ wasConnected = connected+ }+ }+ created.start()+ return created+ }++ fun flushPending(context: Context) {+ val ops = WearEmailStore.get(context).pendingOps.value+ if (ops.isEmpty()) return+ scope.launch {+ val link = get(context)+ for (op in ops) {+ link.sendMessage(+ WearEmailProtocol.OP_PATH,+ WearEmailProtocol.json.encodeToString(op).encodeToByteArray(),+ requireAck = true,+ )+ }+ }+ }++ fun publishWatchState(context: Context) {+ val store = WearEmailStore.get(context)+ val state =+ WearEmailWatchState(store.appliedGeneratedAtMillis, store.messages.value.size, store.pendingOps.value.size)+ scope.launch {+ get(+ context,+ ).putData(+ WearEmailProtocol.WATCH_STATE_PATH,+ WearEmailProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ }+ }++ suspend fun requestSync(context: Context): Boolean =+ get(context).sendMessage(WearEmailProtocol.REQUEST_SYNC_PATH, ByteArray(0))+}
email/src/main/java/com/vayunmathur/email/sync/WearWatchStatePublisher.kt
diff --git a/email/src/main/java/com/vayunmathur/email/sync/WearWatchStatePublisher.kt b/email/src/main/java/com/vayunmathur/email/sync/WearWatchStatePublisher.ktnew file mode 100644index 0000000000..cc3488df10--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/sync/WearWatchStatePublisher.kt@@ -0,0 +1,27 @@+package com.vayunmathur.email.sync++import android.content.Context+import com.vayunmathur.email.data.WearEmailStore+import com.vayunmathur.library.wearlink.email.WearEmailProtocol+import com.vayunmathur.library.wearlink.email.WearEmailWatchState+import kotlinx.serialization.encodeToString++/** Watch -> phone received-state publisher (kept for parity with the other merged apps). */+object WearWatchStatePublisher {+ suspend fun publish(context: Context) {+ val store = WearEmailStore.get(context)+ val state =+ WearEmailWatchState(store.appliedGeneratedAtMillis, store.messages.value.size, store.pendingOps.value.size)+ WearLinkBridge+ .get(+ context,+ ).putData(+ WearEmailProtocol.WATCH_STATE_PATH,+ WearEmailProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ }++ suspend fun requestSnapshot(context: Context) {+ WearLinkBridge.requestSync(context)+ }+}
email/src/main/java/com/vayunmathur/email/ui/WearInboxListScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/WearInboxListScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/WearInboxListScreen.ktnew file mode 100644index 0000000000..719e43c8c8--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/WearInboxListScreen.kt@@ -0,0 +1,103 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.email.R+import com.vayunmathur.email.data.WearEmailStore+import com.vayunmathur.library.wearlink.email.WearEmailMessage+import java.text.DateFormat+import java.util.Date++/** Watch inbox: sender/subject/time from the synced snapshot, unread emphasised. */+@Composable+fun WearInboxListScreen(+ store: WearEmailStore,+ onOpenMessage: (String) -> Unit,+) {+ val messages by store.messages.collectAsState()+ val pending by store.pendingOps.collectAsState()+ WearInboxListContent(messages = messages, pendingCount = pending.size, onOpenMessage = onOpenMessage)+}++/** Stateless inbox body for previews. */+@Composable+internal fun WearInboxListContent(+ messages: List<WearEmailMessage>,+ pendingCount: Int,+ onOpenMessage: (String) -> Unit,+) {+ val listState = rememberScalingLazyListState()+ ScalingLazyColumn(state = listState) {+ item {+ Text(+ stringResource(R.string.app_name),+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ if (pendingCount > 0) {+ item {+ Text(+ stringResource(R.string.wear_pending, pendingCount),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ }+ if (messages.isEmpty()) {+ item {+ Text(+ stringResource(R.string.wear_empty),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ items(messages, key = { it.id }) { message ->+ Chip(+ onClick = { onOpenMessage(message.id) },+ label = {+ Text(+ message.sender.ifBlank { message.subject },+ maxLines = 1,+ fontWeight = if (message.isRead) FontWeight.Normal else FontWeight.Bold,+ )+ },+ secondaryLabel = {+ Text(+ listOf(+ message.subject,+ wearTime(message.dateMillis),+ ).filter { it.isNotBlank() }.joinToString(" · "),+ maxLines = 1,+ fontWeight = if (message.isRead) FontWeight.Normal else FontWeight.Bold,+ )+ },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+ }+}++private fun wearTime(millis: Long): String =+ if (millis <= 0L) "" else DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(millis))
email/src/main/java/com/vayunmathur/email/ui/WearMainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/WearMainActivity.kt b/email/src/main/java/com/vayunmathur/email/ui/WearMainActivity.ktnew file mode 100644index 0000000000..20074a11f5--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/WearMainActivity.kt@@ -0,0 +1,29 @@+package com.vayunmathur.email.ui++import androidx.compose.runtime.Composable+import com.vayunmathur.email.data.WearEmailStore+import com.vayunmathur.email.sync.WearLinkBridge+import com.vayunmathur.library.wearlink.WearShellActivity++/** Watch Email entry: inbox + message from the locally synced snapshot (offline-safe). */+class WearMainActivity : WearShellActivity<WearRoute, WearEmailStore>(WearRoute.Inbox) {+ override fun createStore(): WearEmailStore {+ val created = WearEmailStore.get(this)+ WearLinkBridge.get(this)+ if (created.messages.value.isEmpty()) {+ WearLinkBridge.publishWatchState(this)+ }+ return created+ }++ @Composable+ override fun Screen(+ route: WearRoute,+ navigate: (WearRoute) -> Unit,+ ) {+ when (val current = route) {+ WearRoute.Inbox -> WearInboxListScreen(store = store, onOpenMessage = { navigate(WearRoute.Message(it)) })+ is WearRoute.Message -> WearMessageScreen(store = store, messageId = current.messageId)+ }+ }+}
email/src/main/java/com/vayunmathur/email/ui/WearMessageScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/WearMessageScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/WearMessageScreen.ktnew file mode 100644index 0000000000..485854930a--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/WearMessageScreen.kt@@ -0,0 +1,122 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.email.R+import com.vayunmathur.email.data.WearEmailStore+import com.vayunmathur.email.sync.WearLinkBridge+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.IconMail+import com.vayunmathur.library.ui.IconMobileArrowRight+import com.vayunmathur.library.wearlink.WearFilledButton+import com.vayunmathur.library.wearlink.email.WearEmailMessage+import com.vayunmathur.library.wearlink.wearOpenOnPhoneItem+import kotlinx.coroutines.launch++/** One message: readable body, mark read/unread, then Open on phone last. */+@Composable+fun WearMessageScreen(+ store: WearEmailStore,+ messageId: String,+) {+ val messages by store.messages.collectAsState()+ val message = messages.firstOrNull { it.id == messageId }+ WearMessageContent(+ message = message,+ onToggleRead = { msg, read -> store.markRead(msg, read) },+ )+}++/** Stateless message body for previews. */+@Composable+internal fun WearMessageContent(+ message: WearEmailMessage?,+ onToggleRead: (WearEmailMessage, Boolean) -> Unit,+) {+ val listState = rememberScalingLazyListState()+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ ScalingLazyColumn(state = listState) {+ if (message == null) {+ item {+ Text(+ stringResource(R.string.wear_empty),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ item {+ Text(+ message.subject.ifBlank { message.sender },+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ item {+ Text(+ message.sender,+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ if (message.body.isNotBlank()) {+ item {+ Text(+ message.body,+ style = MaterialTheme.typography.body2,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ }+ if (message.bodyTruncated) {+ item {+ Text(+ stringResource(R.string.wear_body_truncated),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ }+ item {+ WearFilledButton(+ label = stringResource(if (message.isRead) R.string.wear_mark_unread else R.string.wear_mark_read),+ onClick = { onToggleRead(message, !message.isRead) },+ icon = { if (message.isRead) IconMail(tint = Color.White) else IconCheck(tint = Color.White) },+ )+ }+ }+ wearOpenOnPhoneItem(+ onClick = {+ scope.launch {+ WearLinkBridge.get(context).sendMessage(+ "/email/open-on-phone",+ (+ message?.id+ ?: ""+ ).encodeToByteArray(),+ )+ }+ },+ icon = { IconMobileArrowRight(tint = Color.White) },+ )+ }+}
email/src/main/java/com/vayunmathur/email/ui/WearRoute.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/WearRoute.kt b/email/src/main/java/com/vayunmathur/email/ui/WearRoute.ktnew file mode 100644index 0000000000..139cce199c--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/WearRoute.kt@@ -0,0 +1,10 @@+package com.vayunmathur.email.ui++/** Watch destinations: detail carries the message id, never selection state. */+sealed interface WearRoute {+ data object Inbox : WearRoute++ data class Message(+ val messageId: String,+ ) : WearRoute+}
email/src/main/res/values/wear_strings.xml
diff --git a/email/src/main/res/values/wear_strings.xml b/email/src/main/res/values/wear_strings.xmlnew file mode 100644index 0000000000..365c1d57a7--- /dev/null+++ b/email/src/main/res/values/wear_strings.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="wear_empty">No mail synced yet. Open Email on your phone to sync this watch.</string>+ <string name="wear_pending">Waiting for your phone to confirm %1$d change(s)</string>+ <string name="wear_body_truncated">\u2026 (full text on your phone)</string>+ <string name="wear_mark_read">Mark read</string>+ <string name="wear_mark_unread">Mark unread</string>+</resources>
email/src/screenshotTest/kotlin/com/vayunmathur/email/ui/WearMetadataPreviews.kt
diff --git a/email/src/screenshotTest/kotlin/com/vayunmathur/email/ui/WearMetadataPreviews.kt b/email/src/screenshotTest/kotlin/com/vayunmathur/email/ui/WearMetadataPreviews.ktnew file mode 100644index 0000000000..ce08f76bc3--- /dev/null+++ b/email/src/screenshotTest/kotlin/com/vayunmathur/email/ui/WearMetadataPreviews.kt@@ -0,0 +1,76 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.tooling.preview.Preview+import androidx.wear.compose.material.MaterialTheme+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.library.wearlink.email.WearEmailMessage++private const val ROUND = "spec:width=227dp,height=227dp,dpi=320"++private val fixtureMessages =+ listOf(+ WearEmailMessage(+ "a|INBOX|1",+ "[email protected]",+ "INBOX",+ 1,+ "Ada Lovelace",+ "Quarterly report",+ 1_700_000_000_000,+ false,+ "The report is attached for review.",+ ),+ WearEmailMessage(+ "a|INBOX|2",+ "[email protected]",+ "INBOX",+ 2,+ "Grace Hopper",+ "Compiler notes",+ 1_699_999_000_000,+ true,+ "Notes from today's session.",+ ),+ WearEmailMessage(+ "a|INBOX|3",+ "[email protected]",+ "INBOX",+ 3,+ "Alan Turing",+ "Meeting tomorrow",+ 1_699_998_000_000,+ false,+ "See you at ten.",+ ),+ )++/** Watch listing screenshots for `:email`, collected by `:email:metadata`. */+class WearMetadataPreviews {+ @PreviewTest+ @Preview(name = "1-inbox-round", device = ROUND, group = "wear")+ @Composable+ fun Preview1InboxRound() {+ RoundPreview { WearInboxListContent(messages = fixtureMessages, pendingCount = 0, onOpenMessage = {}) }+ }++ @PreviewTest+ @Preview(name = "2-message-round", device = ROUND, group = "wear")+ @Composable+ fun Preview2MessageRound() {+ RoundPreview { WearMessageContent(message = fixtureMessages[0], onToggleRead = { _, _ -> }) }+ }+}++@Composable+private fun RoundPreview(content: @Composable () -> Unit) {+ MaterialTheme {+ Box(Modifier.fillMaxSize().clip(CircleShape).background(MaterialTheme.colors.background)) { content() }+ }+}
email/src/test/java/com/vayunmathur/email/sync/WearEmailProtocolTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/sync/WearEmailProtocolTest.kt b/email/src/test/java/com/vayunmathur/email/sync/WearEmailProtocolTest.ktnew file mode 100644index 0000000000..32537ae051--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/sync/WearEmailProtocolTest.kt@@ -0,0 +1,53 @@+package com.vayunmathur.email.sync++import com.vayunmathur.library.wearlink.email.WearEmailMessage+import com.vayunmathur.library.wearlink.email.WearEmailOp+import com.vayunmathur.library.wearlink.email.WearEmailOpKind+import com.vayunmathur.library.wearlink.email.WearEmailProtocol+import com.vayunmathur.library.wearlink.email.buildWearEmailSnapshot+import kotlinx.serialization.encodeToString+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class WearEmailProtocolTest {+ @Test fun snapshotCapsAndOrder() {+ val msgs =+ (1..40).map {+ WearEmailMessage(+ "a|INBOX|$it",+ "a@x",+ "INBOX",+ it.toLong(),+ "S$it",+ "Sub $it",+ it.toLong(),+ false,+ "b".repeat(5000),+ )+ }+ val snap = buildWearEmailSnapshot(msgs, 99)+ assertTrue(snap.messages.size <= WearEmailProtocol.MAX_MESSAGES)+ assertTrue(snap.truncated)+ assertEquals(40L, snap.messages.first().dateMillis)+ assertTrue(snap.messages.all { it.body.length <= WearEmailProtocol.MAX_BODY_CHARS })+ }++ @Test fun goldenOpJson() {+ val op = WearEmailOp(WearEmailOpKind.MARK_READ, "a|INBOX|7", "a@x", "INBOX", 7, true)+ val json = WearEmailProtocol.json.encodeToString(op)+ assertEquals(op, WearEmailProtocol.json.decodeFromString<WearEmailOp>(json))+ }++ @Test fun triggerHandler() {+ var pushed = false+ assertTrue(+ ConduitSyncTriggerHandler.handle("com.vayunmathur.watch.action.SYNC_TRIGGER", "email") {+ pushed =+ true+ },+ )+ assertTrue(pushed)+ assertTrue(!ConduitSyncTriggerHandler.handle("com.vayunmathur.watch.action.SYNC_TRIGGER", "notes") {})+ }+}
metadata_data/photos/email/wear/1.png
diff --git a/metadata_data/photos/email/wear/1.png b/metadata_data/photos/email/wear/1.pngnew file mode 100644index 0000000000..96644fe7baBinary files /dev/null and b/metadata_data/photos/email/wear/1.png differ
metadata_data/photos/email/wear/2.png
diff --git a/metadata_data/photos/email/wear/2.png b/metadata_data/photos/email/wear/2.pngnew file mode 100644index 0000000000..33cb5448c7Binary files /dev/null and b/metadata_data/photos/email/wear/2.png differ