Modern Apps git

← Modern-Apps.git

camera: watch shows Open in phone until phone Camera is open, then viewfinder only

Commit
db4b1180e89e8aff2d5d31905bf73870672d0130
Author
Vayun Mathur <[email protected]>
When
2026-12-05 14:21 UTC (20 hours ago)
Parents
21c4860
Owner spec: the watch camera remote has exactly two screens.

- Closed phone: WearRoute.OpenOnPhone is one centred filled
  'Open in phone' button. Tapping sends the OPEN_ON_PHONE conduit
  handoff; WearCameraSync launches MainActivity through the
  PhoneCameraLauncher seam unless already open. A sync-trigger
  receiver starts the sync in a dead process so a queued handoff
  replays and launches, and an open receiver provides the direct
  broadcast form of the same handoff.
- Open phone: MainActivity sets phoneOpen on create and clears it
  on destroy (closing stops the preview and republishes closed).
  The watch routes to WearRoute.Viewfinder with only the streamed
  viewfinder and one small capture button; controls and last-capture
  screens are removed.
- Capture: the pure domain/WearWatchPresentation maps the phone's
  mirrored mode to the button theme/icon (photo/portrait/video/
  recording-stop) and to the handoff op (SHUTTER for still modes,
  RECORD_TOGGLE for video-like/recording), which the phone executes
  in its current mode. Mode comes only from the phone.

Frames keep the existing pipeline: Camera2 analysis frames are
downscaled to at most 320px wide, JPEG-encoded once (quality 60,
adaptive 40-75), sent as WCF1 messages at an adaptive 2-8fps
(nominal 5) with latest-only dropping on both sides.

Tests: new WearWatchPresentationTest (screen transitions, theme
mapping, capture/open handoff emission, launch decision) and
OpenOnPhoneReceiverTest; WearCameraProtocolTest golden JSON updated
for phoneOpen plus the OPEN_ON_PHONE op. Wear screenshot previews
regenerated (:camera:metadata).

Verified: :camera:lint :camera:lintVitalRelease
:camera:testDevUnitTest (665 tests) :library:wearlink:lint
:library:wearlink:testDebugUnitTest (27 tests) all pass; the same
wear tests pass on the origin/main baseline.

Diff

camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex f5559432bb..2676cb591a 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -35,20 +35,25 @@ phones and watches alike. `platform/FormFactor.kt` reads `PackageManager.FEATURE_WATCH` at runtime: `MainActivity` (the sole launcher entry) forwards watches to `ui/WearMainActivity` before any phone state (CameraViewModel, phone wear sync, permission gate) is-touched; phones get the camera UI. The module declares no broadcast-receivers, so `MainActivity`'s forward is the only form-factor gate:-the phone-side `platform/WearCameraSync` starts only on the phone-path, and the watch-side `sync/WearLinkBridge` is created only by-`ui/WearMainActivity` (`exported=false`, no launcher filter).+touched; phones get the camera UI. `MainActivity`'s forward is the+form-factor gate for activities: the phone-side+`platform/WearCameraSync` starts only on the phone path, and the+watch-side `sync/WearLinkBridge` is created only by+`ui/WearMainActivity` (`exported=false`, no launcher filter). Two+manifest broadcast receivers (both exported only under the Watch+conduit's signature permission) serve the phone path:+`sync/ConduitSyncTriggerReceiver` starts the sync so queued conduit+ops replay, and `sync/OpenOnPhoneReceiver` launches `MainActivity`+for a direct open-on-phone broadcast.  ## Wear sync (Watch conduit client) **Protocol:** shared wire types live in `:library:wearlink` at `com.vayunmathur.library.wearlink.camera.WearCameraProtocol`; the golden-JSON tests in this module pin the shared code's wire format.-- Mirrored state + thumbnail: conduit data items (`/camera/state`, `/camera/thumbnail`, phone -> watch)-- Control ops + live viewfinder: conduit messages (`/camera/op` watch -> phone, `/camera/preview-frame` phone -> watch)+- Mirrored state + thumbnail: conduit data items (`/camera/state`, `/camera/thumbnail`, phone -> watch); the state carries `phoneOpen` (MainActivity exists on the phone) and the phone's current mode+- Control ops + live viewfinder: conduit messages (`/camera/op` watch -> phone, `/camera/preview-frame` phone -> watch); `OPEN_ON_PHONE` on `/camera/op` is the open-on-phone handoff (phone launches `MainActivity` unless already open), capture ops are executed by the phone in its current mode - **Transport: Watch conduit client** — phone side `platform/WearCameraSync.kt` and watch side `sync/WearLinkBridge.kt` both use `WearLinkClientNode` (Messenger to the Watch app's `watch_conduit` service, appId `camera`); this app owns no RFCOMM link and holds no Bluetooth permission for this channel, so neither entry activity prompts for Bluetooth. With the Watch app absent the node reports `NotInstalled`/`Unavailable` and the sync stays idle; state + thumbnail republish on conduit `Connected`.  ## Watch experience (in this module)-- `ui/WearMainActivity` (a `WearShellActivity`) routes `ui/WearRoute` over viewfinder / controls / last capture; the watch camera remote never opens a local camera — with no phone nearby it says so, honestly. Mirrored truth is in-memory only in `data/WearCameraStore` (no offline copy: nothing is usable without the phone).+- `ui/WearMainActivity` (a `WearShellActivity`) routes `ui/WearRoute` over exactly two screens, driven by the mirrored `phoneOpen` state via the pure `domain/WearWatchPresentation`: `OpenOnPhone` (one centred filled "Open in phone" button while the phone Camera app is not open) and `Viewfinder` (only the streamed viewfinder plus one small capture button, themed by the phone's mode via `wearCaptureButtonSpec`/`wearCaptureOp`; recording shows the stop theme). The watch camera remote never opens a local camera and offers no other controls. Mirrored truth is in-memory only in `data/WearCameraStore` (no offline copy: nothing is usable without the phone). - Wire protocol (`WearCameraProtocol`, WCF1 preview frames) lives in `:library:wearlink` at `com.vayunmathur.library.wearlink.camera`; this module's `WearCameraProtocolTest` pins the golden JSON/frame bytes (including the watch store's stale-frame rules). Live viewfinder frames travel as `/camera/preview-frame` messages (never the bounded STREAM primitive); phone drops frames latest-only, watch drops stale sequences and clears the live frame when the link drops or streaming stops — a frozen frame is never shown as live. - Watch listing screenshots are the `group = "wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt`, collected by `:camera:metadata` into `metadata_data/photos/camera/wear/`; phone/tablet shots keep their buckets. **Gotchas:**@@ -139,7 +144,9 @@ path, and the watch-side `sync/WearLinkBridge` is created only by - com/vayunmathur/camera/platform/camera2/StreamSelection.kt ### Watch experience (ui/ + data/ + sync/) - com/vayunmathur/camera/ui/WearMainActivity.kt — watch entry (WearShellActivity)-- com/vayunmathur/camera/ui/WearRoute.kt, WearViewfinderScreen.kt, WearControlsScreen.kt, WearLastCaptureScreen.kt+- com/vayunmathur/camera/ui/WearRoute.kt, WearOpenOnPhoneScreen.kt, WearViewfinderScreen.kt+- com/vayunmathur/camera/domain/WearWatchPresentation.kt — pure two-screen state machine + capture-button theme/op mapping+- com/vayunmathur/camera/sync/OpenOnPhoneReceiver.kt, ConduitSyncTriggerReceiver.kt — phone broadcast entries (open launch / sync wake) - com/vayunmathur/camera/platform/FormFactor.kt — watch detection (`FEATURE_WATCH`) - com/vayunmathur/camera/data/WearCameraStore.kt — mirrored phone state + newest preview frame/thumbnail (in-memory only) - com/vayunmathur/camera/sync/WearLinkBridge.kt — watch conduit client node; mirrored state/thumbnail receive, preview frames, op sends
camera/src/main/AndroidManifest.xml
diff --git a/camera/src/main/AndroidManifest.xml b/camera/src/main/AndroidManifest.xmlindex 99db9dd674..50c75deed1 100644--- a/camera/src/main/AndroidManifest.xml+++ b/camera/src/main/AndroidManifest.xml@@ -92,13 +92,34 @@                 <category android:name="android.intent.category.DEFAULT" />             </intent-filter>         </activity>+        <!-- Watch conduit scheduled push sync + direct open-on-phone+             handoff: both receivers are exported only under the Watch+             conduit's signature permission and are inert on a watch (the+             sync trigger starts a sync that publishes nothing without a+             phone ViewModel; the open receiver launches MainActivity,+             which forwards watches to WearMainActivity). -->+        <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>+        <receiver+            android:name=".sync.OpenOnPhoneReceiver"+            android:exported="true"+            android:permission="com.vayunmathur.watch.permissions.CONDUIT">+            <intent-filter>+                <action android:name="com.vayunmathur.camera.action.OPEN_ON_PHONE" />+            </intent-filter>+        </receiver>         <!-- Watch experience: entered only via MainActivity's watch routing              (no launcher filter of its own). Inert on a phone: it is              reached only from MainActivity's FEATURE_WATCH forward, its              WearLinkBridge is created only by this activity, and the              phone-side WearCameraSync starts only on the phone path of-             MainActivity. This module declares no broadcast receivers, so-             there is no wrong-form-factor receiver surface to gate. -->+             MainActivity. -->         <activity             android:name=".ui.WearMainActivity"             android:exported="false"
camera/src/main/java/com/vayunmathur/camera/MainActivity.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt b/camera/src/main/java/com/vayunmathur/camera/MainActivity.ktindex 33967247ce..76e2f56dca 100644--- a/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt+++ b/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt@@ -85,6 +85,16 @@ class MainActivity : MaActivity() {         val wearSync = com.vayunmathur.camera.platform.WearCameraSync.get(this)         wearSync.viewModel = viewModel         wearSync.start()+        // The watch leaves its "Open in phone" button only while this is+        // set; onDestroy clears it, returning the watch to that button.+        wearSync.setPhoneOpen(true)+    }++    override fun onDestroy() {+        if (!routedToWear) {+            com.vayunmathur.camera.platform.WearCameraSync.get(this).setPhoneOpen(false)+        }+        super.onDestroy()     }      @Composable
camera/src/main/java/com/vayunmathur/camera/domain/WearWatchPresentation.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/WearWatchPresentation.kt b/camera/src/main/java/com/vayunmathur/camera/domain/WearWatchPresentation.ktnew file mode 100644index 0000000000..8174063873--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/WearWatchPresentation.kt@@ -0,0 +1,108 @@+package com.vayunmathur.camera.domain++import com.vayunmathur.library.wearlink.camera.WearCameraOp+import com.vayunmathur.library.wearlink.camera.WearCameraProtocol+import com.vayunmathur.library.wearlink.camera.WearCameraState+import com.vayunmathur.library.wearlink.camera.WearOpKind++/**+ * Pure watch-experience state machine (owner spec 2026-12-05): the watch+ * has exactly two screens. While the phone Camera app is not open it shows+ * a single "Open in phone" button; once the phone app is open it shows+ * only the streamed viewfinder and one small capture button whose theme+ * follows the mode selected on the phone. No other watch controls exist,+ * so there is nothing else to decide here. All functions are pure so the+ * transitions are unit-tested without a watch, a phone, or a camera.+ */++/** The two watch screens; screen changes travel through `WearRoute`. */+enum class WearWatchScreen {+    /** Single filled "Open in phone" button (phone Camera app not open). */+    OpenOnPhone,++    /** Streamed viewfinder + the one mode-themed capture button. */+    Viewfinder,+}++/**+ * The screen for the mirrored truth: the viewfinder exists only while the+ * conduit link is up AND the phone reports its Camera app open. A dropped+ * link, a closed phone app, or state from an older phone (which never+ * publishes `phoneOpen`) all fall back to the open-on-phone button.+ */+fun wearWatchScreen(+    linkConnected: Boolean,+    state: WearCameraState,+): WearWatchScreen = if (linkConnected && state.phoneOpen) WearWatchScreen.Viewfinder else WearWatchScreen.OpenOnPhone++/** How the capture button looks: decided by the phone's mode, never by the watch. */+enum class WearCaptureTheme {+    /** Still modes (PHOTO and any non-video mode): the phone's primary theme. */+    Photo,++    /** PORTRAIT: the phone's secondary theme (a still, but not plain photo). */+    Portrait,++    /** Video-like modes, not yet recording: record theme. */+    Video,++    /** Any mode while recording: stop theme (recording wins over mode). */+    Recording,+}++/** Everything the watch capture button renders, derived from the phone's mirrored state. */+data class WearCaptureButtonSpec(+    val theme: WearCaptureTheme,+    /** The phone's mode name, shown on/near the button so the mode is legible. */+    val modeLabel: String,+    /** True when tapping toggles a recording rather than taking a still. */+    val togglesRecording: Boolean,+)++/**+ * The capture button's spec for [state]: recording wins first, then+ * video-like modes ([WearCameraProtocol.VIDEO_MODES]), then PORTRAIT,+ * then every other mode as a plain still. Unknown/future phone modes are+ * stills — the phone executes the capture in whatever mode it is in.+ */+fun wearCaptureButtonSpec(state: WearCameraState): WearCaptureButtonSpec =+    when {+        state.recording -> WearCaptureButtonSpec(WearCaptureTheme.Recording, state.mode, togglesRecording = true)+        state.mode in WearCameraProtocol.VIDEO_MODES ->+            WearCaptureButtonSpec(WearCaptureTheme.Video, state.mode, togglesRecording = true)+        state.mode == "PORTRAIT" ->+            WearCaptureButtonSpec(+                WearCaptureTheme.Portrait,+                state.mode,+                togglesRecording = false,+            )+        else -> WearCaptureButtonSpec(WearCaptureTheme.Photo, state.mode, togglesRecording = false)+    }++/**+ * The capture handoff for one tap of the watch capture button: a recording+ * toggle for video-like modes (and while recording), a shutter for still+ * modes. The phone executes it in its current mode (`takePhoto` /+ * `toggleRecording` behind `WearCameraControls`), so the watch never+ * picks a mode — it only asks for a capture in the phone's mode.+ */+fun wearCaptureOp(state: WearCameraState): WearCameraOp =+    if (wearCaptureButtonSpec(state).togglesRecording) {+        WearCameraOp(WearOpKind.RECORD_TOGGLE)+    } else {+        WearCameraOp(WearOpKind.SHUTTER)+    }++/** The open-on-phone handoff sent by the watch's single button. */+fun wearOpenOnPhoneOp(): WearCameraOp = WearCameraOp(WearOpKind.OPEN_ON_PHONE)++/**+ * Phone-side launch decision for an [WearOpKind.OPEN_ON_PHONE] handoff:+ * launch only when the Camera app is not already open, so a duplicate or+ * replayed handoff never relaunches over a live camera. Pure so the+ * phone's launch policy is unit-tested without an activity.+ */+fun wearOpenOnPhoneShouldLaunch(+    phoneOpen: Boolean,+    kind: WearOpKind,+): Boolean = kind == WearOpKind.OPEN_ON_PHONE && !phoneOpen
camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.kt b/camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.ktindex be5379c3fe..443ca6c443 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.kt@@ -1,6 +1,7 @@ package com.vayunmathur.camera.platform  import android.content.Context+import android.content.Intent import android.graphics.Bitmap import android.hardware.camera2.CameraMetadata import com.vayunmathur.camera.data.setFlashMode@@ -11,7 +12,9 @@ import com.vayunmathur.camera.domain.LatestOnlySlot import com.vayunmathur.camera.domain.PreviewFrameProcessor import com.vayunmathur.camera.domain.PreviewJpegEncoder import com.vayunmathur.camera.domain.Yuv420ToArgb+import com.vayunmathur.camera.MainActivity import com.vayunmathur.camera.domain.previewDimensions+import com.vayunmathur.camera.domain.wearOpenOnPhoneShouldLaunch import com.vayunmathur.library.log.Log import com.vayunmathur.library.wearlink.WearLinkListener import com.vayunmathur.library.wearlink.WearLinkState@@ -107,7 +110,7 @@ fun executeWearOp(op: WearCameraOp, state: WearCameraState, controls: WearCamera         WearOpKind.SET_TORCH -> controls.setTorch(op.torch)         WearOpKind.FLIP_LENS -> controls.flipLens()         WearOpKind.SET_TIMER -> controls.setTimer(op.timerSeconds)-        WearOpKind.PREVIEW_START, WearOpKind.PREVIEW_STOP -> Unit // handled by the sync, not the camera+        WearOpKind.PREVIEW_START, WearOpKind.PREVIEW_STOP, WearOpKind.OPEN_ON_PHONE -> Unit // handled by the sync, not the camera     }     return decision }@@ -117,6 +120,7 @@ fun CameraViewModel.wearCameraState(     previewStreaming: Boolean,     lastCaptureAtMillis: Long = 0L,     lastCaptureKind: String = "",+    phoneOpen: Boolean = false, ): WearCameraState {     val (zoomMin, zoomMax) = currentZoomRange()     return WearCameraState(@@ -137,9 +141,26 @@ fun CameraViewModel.wearCameraState(         previewStreaming = previewStreaming,         lastCaptureAtMillis = lastCaptureAtMillis,         lastCaptureKind = lastCaptureKind,+        phoneOpen = phoneOpen,     ) } +/** Seam for launching the phone Camera app; tests substitute a recording fake. */+interface PhoneCameraLauncher {+    fun launchCamera()+}++/** Launches [MainActivity] as a new task top; the only phone-side launcher for the watch handoff. */+class AndroidPhoneCameraLauncher(private val context: Context) : PhoneCameraLauncher {+    override fun launchCamera() {+        val intent = Intent(context, MainActivity::class.java).apply {+            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP+        }+        runCatching { context.startActivity(intent) }+            .onFailure { Log.status("WearCameraSync", "open-on-phone launch failed: ${it.message}") }+    }+}+ /** Android JPEG encoder behind the pure pipeline seam (Bitmap.compress). */ private object BitmapPreviewEncoder : PreviewJpegEncoder {     override fun encode(argb: IntArray, width: Int, height: Int, quality: Int): ByteArray {@@ -174,7 +195,17 @@ private class RawPreviewFrame(val argb: IntArray, val width: Int, val height: In  * tap never blocks, converts only while the slot is free, and drops  * (counted) otherwise, so the phone's capture/analysis path cannot stall  * behind the watch link. Captured media stays on the phone; only the- * thumbnail crosses the link. Nothing here wakes a dead process.+ * thumbnail crosses the link.+ *+ * Phone-open gate: [setPhoneOpen] (driven by MainActivity's lifecycle)+ * publishes `phoneOpen` in the mirrored state. The watch shows its single+ * "Open in phone" button while it is false; its OPEN_ON_PHONE handoff is+ * handled here and actually launches [MainActivity] through+ * [phoneCameraLauncher] unless the app is already open. A conduit sync+ * trigger (see `sync/ConduitSyncTriggerReceiver`) or the open receiver+ * (see `sync/OpenOnPhoneReceiver`) starts this sync in a dead process, so+ * a queued handoff replays on registration and launches then; the sync+ * alone does not wake a dead process.  */ class WearCameraSync private constructor(context: Context) { @@ -200,6 +231,32 @@ class WearCameraSync private constructor(context: Context) {     @Volatile     var viewModel: CameraViewModel? = null +    /** True while the phone Camera app is open (MainActivity exists); published in the mirrored state. */+    @Volatile+    var phoneOpen: Boolean = false+        private set++    /** Launcher for the open-on-phone handoff; replaceable in tests. */+    @Volatile+    var phoneCameraLauncher: PhoneCameraLauncher = AndroidPhoneCameraLauncher(appContext)++    /**+     * Marks the phone Camera app open/closed and republishes immediately:+     * opening is what lets the watch leave its open-on-phone button, and+     * closing stops the preview and returns the watch to that button.+     */+    fun setPhoneOpen(open: Boolean) {+        if (phoneOpen == open) return+        phoneOpen = open+        if (!open && previewWanted) stopPreview()+        scope.launch { publishState() }+    }++    /** Handles one open-on-phone handoff; launches only when the app is not already open. */+    fun handleOpenOnPhone(kind: WearOpKind) {+        if (wearOpenOnPhoneShouldLaunch(phoneOpen, kind)) phoneCameraLauncher.launchCamera()+    }+     private val _linkState = MutableStateFlow<WearLinkState>(WearLinkState.Stopped)      @Volatile@@ -226,12 +283,13 @@ class WearCameraSync private constructor(context: Context) {                 return             }             when (op.kind) {+                WearOpKind.OPEN_ON_PHONE -> handleOpenOnPhone(op.kind)                 WearOpKind.PREVIEW_START -> startPreview()                 WearOpKind.PREVIEW_STOP -> stopPreview()                 else -> {                     val vm = viewModel ?: return                     scope.launch {-                        val state = withContext(Dispatchers.Main) { vm.wearCameraState(previewWanted, lastCaptureAtMillis, lastCaptureKind) }+                        val state = withContext(Dispatchers.Main) { vm.wearCameraState(previewWanted, lastCaptureAtMillis, lastCaptureKind, phoneOpen) }                         val decision = withContext(Dispatchers.Main) {                             executeWearOp(op, state, ViewModelWearControls(vm))                         }@@ -293,7 +351,7 @@ class WearCameraSync private constructor(context: Context) {     private suspend fun publishState() {         val vm = viewModel ?: return         if (node.state.value !is WearLinkState.Connected) return-        val state = withContext(Dispatchers.Main) { vm.wearCameraState(previewWanted, lastCaptureAtMillis, lastCaptureKind) }+        val state = withContext(Dispatchers.Main) { vm.wearCameraState(previewWanted, lastCaptureAtMillis, lastCaptureKind, phoneOpen) }         node.putData(WearCameraProtocol.STATE_PATH, encodeWearCameraState(state))     } @@ -324,6 +382,7 @@ class WearCameraSync private constructor(context: Context) {      private fun startPreview() {         val vm = viewModel ?: return+        if (!phoneOpen) return // No streaming while the phone app is closed; the watch asks again once it opens.         if (previewWanted) return         previewWanted = true         previewRate.reset()
camera/src/main/java/com/vayunmathur/camera/sync/ConduitSyncTriggerReceiver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/sync/ConduitSyncTriggerReceiver.kt b/camera/src/main/java/com/vayunmathur/camera/sync/ConduitSyncTriggerReceiver.ktnew file mode 100644index 0000000000..3fecb26e78--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/sync/ConduitSyncTriggerReceiver.kt@@ -0,0 +1,50 @@+package com.vayunmathur.camera.sync++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.camera.platform.WearCameraSync+import com.vayunmathur.library.wearlink.camera.WearCameraProtocol+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.ConduitSync++/**+ * Decides whether an incoming intent is this app's sync trigger.+ * Pure (no Android types) so the decision is unit-tested.+ */+object ConduitSyncTriggerHandler {+    /** Conduit appId this app pushes under (first segment of its state paths). */+    val APP_ID: String = ConduitProtocol.routeKey(WearCameraProtocol.STATE_PATH)++    /** True (and [start] invoked) only for the [ConduitSync.ACTION] intent addressed to [APP_ID]. */+    fun handle(+        action: String?,+        appId: String?,+        start: () -> Unit,+    ): Boolean {+        if (!ConduitSync.isTrigger(action, appId, APP_ID)) return false+        start()+        return true+    }+}++/**+ * Receiver for the Watch conduit's scheduled push sync: starting+ * [WearCameraSync] registers the conduit client, which replays any+ * queued watch op — including an OPEN_ON_PHONE handoff sent while this+ * process was dead, which then launches Camera. No UI is shown by the+ * receiver itself; the launch, when one is queued, is the handoff's.+ */+class ConduitSyncTriggerReceiver : BroadcastReceiver() {+    override fun onReceive(+        context: Context,+        intent: Intent,+    ) {+        ConduitSyncTriggerHandler.handle(+            intent.action,+            intent.getStringExtra(ConduitSync.EXTRA_APP_ID),+        ) {+            WearCameraSync.get(context.applicationContext).start()+        }+    }+}
camera/src/main/java/com/vayunmathur/camera/sync/OpenOnPhoneReceiver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/sync/OpenOnPhoneReceiver.kt b/camera/src/main/java/com/vayunmathur/camera/sync/OpenOnPhoneReceiver.ktnew file mode 100644index 0000000000..61423622c7--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/sync/OpenOnPhoneReceiver.kt@@ -0,0 +1,44 @@+package com.vayunmathur.camera.sync++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.camera.platform.AndroidPhoneCameraLauncher++/**+ * Pure decision for the direct open-on-phone broadcast: only this app's+ * action launches, anything else is ignored. Unit-tested without Android.+ */+object OpenOnPhoneHandler {+    /** Broadcast action asking this app to open its Camera on the phone. */+    const val ACTION = "com.vayunmathur.camera.action.OPEN_ON_PHONE"++    /** True (and [launch] invoked) only for [ACTION]. */+    fun handle(+        action: String?,+        launch: () -> Unit,+    ): Boolean {+        if (action != ACTION) return false+        launch()+        return true+    }+}++/**+ * Direct open-on-phone entry (exported only under the Watch conduit's+ * signature permission, package-addressed by the sender): actually+ * launches the Camera activity. The normal watch path is the conduit+ * OPEN_ON_PHONE op handled by `WearCameraSync`; this receiver is the+ * broadcast form of the same handoff for senders that can address the+ * package but have no conduit message for it.+ */+class OpenOnPhoneReceiver : BroadcastReceiver() {+    override fun onReceive(+        context: Context,+        intent: Intent,+    ) {+        OpenOnPhoneHandler.handle(intent.action) {+            AndroidPhoneCameraLauncher(context.applicationContext).launchCamera()+        }+    }+}
camera/src/main/java/com/vayunmathur/camera/sync/WearLinkBridge.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/sync/WearLinkBridge.kt b/camera/src/main/java/com/vayunmathur/camera/sync/WearLinkBridge.ktindex f71875e110..469be75851 100644--- a/camera/src/main/java/com/vayunmathur/camera/sync/WearLinkBridge.kt+++ b/camera/src/main/java/com/vayunmathur/camera/sync/WearLinkBridge.kt@@ -87,6 +87,10 @@ object WearLinkBridge {         scope.launch { sendOp(context, op) }     } +    /** Sends the open-on-phone handoff: ask the phone to open its Camera app. */+    fun openOnPhone(context: Context) =+        sendOpAsync(context, com.vayunmathur.camera.domain.wearOpenOnPhoneOp())+     /** Asks the phone to start streaming the live viewfinder to this watch. */     fun startPreview(context: Context) =         sendOpAsync(context, WearCameraOp(WearOpKind.PREVIEW_START))
camera/src/main/java/com/vayunmathur/camera/ui/WearControlsScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/WearControlsScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/WearControlsScreen.ktdeleted file mode 100644index 22a970de7b..0000000000--- a/camera/src/main/java/com/vayunmathur/camera/ui/WearControlsScreen.kt+++ /dev/null@@ -1,183 +0,0 @@-package com.vayunmathur.camera.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.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.itemsIndexed-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.camera.R-import com.vayunmathur.camera.data.WearCameraStore-import com.vayunmathur.camera.sync.WearLinkBridge-import com.vayunmathur.library.wearlink.camera.WearCameraOp-import com.vayunmathur.library.wearlink.camera.WearCameraProtocol-import com.vayunmathur.library.wearlink.camera.WearOpKind--/**- * Remote controls executed on the phone: zoom presets, a zoom scrub- * (coarse steps over the mirrored range), flash/torch, lens flip and the- * shutter timer. Every value shown is the phone's mirrored state — a tap- * sends one op and the watch believes the next state publish, not the tap.- */-@Composable-fun WearControlsScreen(store: WearCameraStore, onBack: () -> Unit) {-    val context = LocalContext.current-    val state by store.state.collectAsState()-    val listState = rememberScalingLazyListState()--    fun send(op: WearCameraOp) = WearLinkBridge.sendOpAsync(context, op)-    WearControlsContent(state = state, onOp = ::send, onBack = onBack)-}--/** Stateless controls behind [WearControlsScreen]: mirrored state/op sink are parameters for previews. */-@Composable-internal fun WearControlsContent(state: com.vayunmathur.library.wearlink.camera.WearCameraState, onOp: (WearCameraOp) -> Unit, onBack: () -> Unit) {-    val listState = rememberScalingLazyListState()-    fun send(op: WearCameraOp) = onOp(op)--    ScalingLazyColumn(state = listState) {-        item {-            Text(-                stringResource(R.string.wear_controls),-                style = MaterialTheme.typography.title3,-                textAlign = TextAlign.Center,-                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),-            )-        }-        item {-            Text(-                stringResource(R.string.wear_zoom, formatZoomLabel(state.zoomRatio)),-                style = MaterialTheme.typography.body2,-                textAlign = TextAlign.Center,-                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),-            )-        }-        itemsIndexed(state.zoomPresets) { index, preset ->-            Chip(-                onClick = { send(WearCameraOp(WearOpKind.ZOOM_PRESET, zoomPresetIndex = index)) },-                label = { Text(formatZoomLabel(preset), maxLines = 1) },-                colors = if (preset == state.zoomRatio) {-                    ChipDefaults.primaryChipColors()-                } else {-                    ChipDefaults.secondaryChipColors()-                },-                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-            )-        }-        item {-            Chip(-                onClick = { send(WearCameraOp(WearOpKind.SET_ZOOM, zoomRatio = scrubZoom(state.zoomRatio, state.zoomMin, state.zoomMax, up = false))) },-                label = { Text("−", maxLines = 1) },-                colors = ChipDefaults.secondaryChipColors(),-                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-            )-        }-        item {-            Chip(-                onClick = { send(WearCameraOp(WearOpKind.SET_ZOOM, zoomRatio = scrubZoom(state.zoomRatio, state.zoomMin, state.zoomMax, up = true))) },-                label = { Text("+", maxLines = 1) },-                colors = ChipDefaults.secondaryChipColors(),-                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-            )-        }-        if (state.hasFlashUnit) {-            item {-                Chip(-                    onClick = { send(WearCameraOp(WearOpKind.SET_FLASH, flash = nextFlash(state.flash))) },-                    label = { Text(stringResource(R.string.wear_flash, state.flash), maxLines = 1) },-                    colors = ChipDefaults.secondaryChipColors(),-                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-                )-            }-            item {-                Chip(-                    onClick = { send(WearCameraOp(WearOpKind.SET_TORCH, torch = !state.torch)) },-                    label = {-                        Text(-                            "${stringResource(R.string.wear_torch)}: ${if (state.torch) "ON" else "OFF"}",-                            maxLines = 1,-                        )-                    },-                    colors = if (state.torch) ChipDefaults.primaryChipColors() else ChipDefaults.secondaryChipColors(),-                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-                )-            }-        }-        item {-            Chip(-                onClick = { send(WearCameraOp(WearOpKind.FLIP_LENS)) },-                label = {-                    Text(-                        "${stringResource(R.string.wear_flip_lens)}: " +-                            stringResource(if (state.frontLens) R.string.wear_front else R.string.wear_back_lens),-                        maxLines = 1,-                    )-                },-                colors = ChipDefaults.secondaryChipColors(),-                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-            )-        }-        item {-            Chip(-                onClick = { send(WearCameraOp(WearOpKind.SET_TIMER, timerSeconds = nextTimer(state.timerSeconds))) },-                label = {-                    Text(-                        stringResource(R.string.wear_timer, if (state.timerSeconds == 0) "OFF" else "${state.timerSeconds}s"),-                        maxLines = 1,-                    )-                },-                colors = ChipDefaults.secondaryChipColors(),-                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-            )-        }-        item {-            Chip(-                onClick = onBack,-                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },-                colors = ChipDefaults.secondaryChipColors(),-                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-            )-        }-    }-}--/** One scrub step: ×/÷ 1.25 in log space, clamped to the mirrored range. */-internal fun scrubZoom(current: Float, min: Float, max: Float, up: Boolean): Float {-    val stepped = if (up) current * ZOOM_STEP_FACTOR else current / ZOOM_STEP_FACTOR-    return stepped.coerceIn(min, max)-}--/** Next flash value in the OFF -> AUTO -> ON cycle. */-internal fun nextFlash(current: String): String = when (current) {-    "OFF" -> "AUTO"-    "AUTO" -> "ON"-    else -> "OFF"-}--/** Next timer value in the protocol's option set, wrapping to off. */-internal fun nextTimer(currentSeconds: Int): Int {-    val options = WearCameraProtocol.TIMER_OPTIONS_SECONDS-    val index = options.indexOf(currentSeconds)-    return options[(index + 1) % options.size]-}--/** ".5", "1x", "1.5x" — the watch's zoom label (mirrors the phone's format). */-internal fun formatZoomLabel(ratio: Float): String = when {-    ratio < 1f -> ".${(ratio * ZOOM_DECIMAL_SCALE).toInt()}"-    ratio == ratio.toInt().toFloat() -> "${ratio.toInt()}x"-    else -> "%.1fx".format(ratio)-}--private const val ZOOM_STEP_FACTOR = 1.25f-private const val ZOOM_DECIMAL_SCALE = 10f
camera/src/main/java/com/vayunmathur/camera/ui/WearLastCaptureScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/WearLastCaptureScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/WearLastCaptureScreen.ktdeleted file mode 100644index 8a6e1dc694..0000000000--- a/camera/src/main/java/com/vayunmathur/camera/ui/WearLastCaptureScreen.kt+++ /dev/null@@ -1,90 +0,0 @@-package com.vayunmathur.camera.ui--import android.graphics.BitmapFactory-import androidx.compose.foundation.Image-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.remember-import androidx.compose.ui.Modifier-import androidx.compose.ui.graphics.asImageBitmap-import androidx.compose.ui.layout.ContentScale-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.Chip-import androidx.wear.compose.material.ChipDefaults-import androidx.wear.compose.material.MaterialTheme-import androidx.wear.compose.material.Text-import com.vayunmathur.camera.R-import com.vayunmathur.camera.data.WearCameraStore--/** Last-capture thumbnail pushed from the phone; the media itself stays on the phone. */-@Composable-fun WearLastCaptureScreen(store: WearCameraStore, onBack: () -> Unit) {-    val thumbnailJpeg by store.thumbnailJpeg.collectAsState()-    val state by store.state.collectAsState()-    val bitmap = remember(thumbnailJpeg) {-        thumbnailJpeg?.let { runCatching { BitmapFactory.decodeByteArray(it, 0, it.size) }.getOrNull() }-    }-    WearLastCaptureContent(bitmap = bitmap, lastCaptureKind = state.lastCaptureKind, onBack = onBack)-}--/** Stateless last-capture behind [WearLastCaptureScreen]: decoded bitmap is a parameter for previews. */-@Composable-internal fun WearLastCaptureContent(bitmap: android.graphics.Bitmap?, lastCaptureKind: String, onBack: () -> Unit) {--    // ScalingLazyColumn (was a fixed Column): on a 1.4" round screen the-    // thumbnail + caption + Back chip overflowed without scrolling.-    ScalingLazyColumn(state = rememberScalingLazyListState()) {-        item {-            Text(-                stringResource(R.string.wear_last_capture),-                style = MaterialTheme.typography.title3,-                textAlign = TextAlign.Center,-                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),-            )-        }-        if (bitmap != null) {-            item {-                Image(-                    bitmap = bitmap.asImageBitmap(),-                    contentDescription = null,-                    contentScale = ContentScale.FillWidth,-                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),-                )-            }-            if (lastCaptureKind.isNotEmpty()) {-                item {-                    Text(-                        lastCaptureKind,-                        style = MaterialTheme.typography.body2,-                        textAlign = TextAlign.Center,-                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),-                    )-                }-            }-        } else {-            item {-                Text(-                    stringResource(R.string.wear_no_capture),-                    style = MaterialTheme.typography.body2,-                    textAlign = TextAlign.Center,-                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),-                )-            }-        }-        item {-            Chip(-                onClick = onBack,-                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },-                colors = ChipDefaults.secondaryChipColors(),-                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),-            )-        }-    }-}
camera/src/main/java/com/vayunmathur/camera/ui/WearMainActivity.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/WearMainActivity.kt b/camera/src/main/java/com/vayunmathur/camera/ui/WearMainActivity.ktindex ab6843ee92..41354e2fc2 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/WearMainActivity.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/WearMainActivity.kt@@ -1,39 +1,48 @@ package com.vayunmathur.camera.ui  import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue import com.vayunmathur.camera.data.WearCameraStore+import com.vayunmathur.camera.domain.WearWatchScreen+import com.vayunmathur.camera.domain.wearWatchScreen import com.vayunmathur.camera.sync.WearLinkBridge import com.vayunmathur.library.wearlink.WearShellActivity  /**- * Camera watch companion entry: a live viewfinder streamed from the phone- * camera plus remote controls executed on the phone. The watch has no- * camera of its own — with no phone nearby it says so, honestly.+ * Camera watch companion entry: while the phone Camera app is not open+ * the watch shows a single "Open in phone" button; once the phone app is+ * open it shows only the live viewfinder streamed from the phone camera+ * plus one mode-themed capture button. The watch has no camera of its+ * own. Screen changes travel through [WearRoute], driven by the mirrored+ * `phoneOpen` state (see `wearWatchScreen`).  */-class WearMainActivity : WearShellActivity<WearRoute, WearCameraStore>(WearRoute.Viewfinder) {-+class WearMainActivity : WearShellActivity<WearRoute, WearCameraStore>(WearRoute.OpenOnPhone) {     // No Bluetooth prompt here: the Watch app owns the conduit link     // and its permission. With the Watch app absent the bridge stays-    // NotInstalled/Unavailable and the remote shows its no-phone state;-    // the watch camera remote never opens a local camera.+    // NotInstalled/Unavailable and the watch keeps its open-on-phone+    // button; the watch camera remote never opens a local camera.     override fun createStore() = WearCameraStore.get().also { WearLinkBridge.get(this) }      @Composable-    override fun Screen(route: WearRoute, navigate: (WearRoute) -> Unit) {+    override fun Screen(+        route: WearRoute,+        navigate: (WearRoute) -> Unit,+    ) {+        val connected by store.linkConnected.collectAsState()+        val state by store.state.collectAsState()+        val target =+            when (wearWatchScreen(connected, state)) {+                WearWatchScreen.OpenOnPhone -> WearRoute.OpenOnPhone+                WearWatchScreen.Viewfinder -> WearRoute.Viewfinder+            }+        LaunchedEffect(target) {+            if (target != route) navigate(target)+        }         when (route) {-            WearRoute.Viewfinder -> WearViewfinderScreen(-                store = store,-                onOpenControls = { navigate(WearRoute.Controls) },-                onOpenLastCapture = { navigate(WearRoute.LastCapture) },-            )-            WearRoute.Controls -> WearControlsScreen(-                store = store,-                onBack = { navigate(WearRoute.Viewfinder) },-            )-            WearRoute.LastCapture -> WearLastCaptureScreen(-                store = store,-                onBack = { navigate(WearRoute.Viewfinder) },-            )+            WearRoute.OpenOnPhone -> WearOpenOnPhoneScreen()+            WearRoute.Viewfinder -> WearViewfinderScreen(store = store)         }     } }
camera/src/main/java/com/vayunmathur/camera/ui/WearOpenOnPhoneScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/WearOpenOnPhoneScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/WearOpenOnPhoneScreen.ktnew file mode 100644index 0000000000..626786f2a8--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/WearOpenOnPhoneScreen.kt@@ -0,0 +1,38 @@+package com.vayunmathur.camera.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.wear.compose.material.Button+import androidx.wear.compose.material.Text+import com.vayunmathur.camera.R+import com.vayunmathur.camera.sync.WearLinkBridge++/**+ * The watch's only screen while the phone Camera app is not open: one+ * centred filled button (watch design rule: filled buttons only, on the+ * Wear Material themed background the shell provides). Tapping it sends+ * the conduit open-on-phone handoff; the phone launches Camera, reports+ * `phoneOpen`, and the watch routes to the viewfinder.+ */+@Composable+fun WearOpenOnPhoneScreen() {+    val context = LocalContext.current+    WearOpenOnPhoneContent(onOpenOnPhone = { WearLinkBridge.openOnPhone(context) })+}++/** Stateless open-on-phone screen: the tap sink is a parameter for previews. */+@Composable+internal fun WearOpenOnPhoneContent(onOpenOnPhone: () -> Unit) {+    Box(modifier = Modifier.fillMaxSize().padding(horizontal = 24.dp), contentAlignment = Alignment.Center) {+        Button(onClick = onOpenOnPhone) {+            Text(stringResource(R.string.wear_open_in_phone))+        }+    }+}
camera/src/main/java/com/vayunmathur/camera/ui/WearRoute.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/WearRoute.kt b/camera/src/main/java/com/vayunmathur/camera/ui/WearRoute.ktindex e557f6aed5..d4e0705e5b 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/WearRoute.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/WearRoute.kt@@ -2,12 +2,9 @@ package com.vayunmathur.camera.ui  /** Watch navigation destinations. Screen changes only ever happen through these routes. */ sealed interface WearRoute {-    /** Live viewfinder with shutter/record and mode switching. */-    data object Viewfinder : WearRoute--    /** Zoom, flash/torch, lens and timer controls (executed on the phone). */-    data object Controls : WearRoute+    /** Single "Open in phone" button, shown while the phone Camera app is not open. */+    data object OpenOnPhone : WearRoute -    /** Last-capture thumbnail (the media itself stays on the phone). */-    data object LastCapture : WearRoute+    /** Live viewfinder with the one mode-themed capture button (phone Camera app open). */+    data object Viewfinder : WearRoute }
camera/src/main/java/com/vayunmathur/camera/ui/WearViewfinderScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/WearViewfinderScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/WearViewfinderScreen.ktindex b632f92df7..a4b2fdc2a2 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/WearViewfinderScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/WearViewfinderScreen.kt@@ -2,14 +2,10 @@ package com.vayunmathur.camera.ui  import android.graphics.BitmapFactory import androidx.compose.foundation.Image-import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.lazy.LazyRow-import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.collectAsState@@ -24,84 +20,67 @@ 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.material.Chip-import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.Button+import androidx.wear.compose.material.ButtonDefaults import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.Text import com.vayunmathur.camera.R import com.vayunmathur.camera.data.WearCameraStore+import com.vayunmathur.camera.domain.WearCaptureTheme+import com.vayunmathur.camera.domain.wearCaptureButtonSpec+import com.vayunmathur.camera.domain.wearCaptureOp import com.vayunmathur.camera.sync.WearLinkBridge-import com.vayunmathur.library.wearlink.camera.WearCameraOp-import com.vayunmathur.library.wearlink.camera.WearCameraProtocol-import com.vayunmathur.library.wearlink.camera.WearOpKind+import com.vayunmathur.library.ui.IconCamera+import com.vayunmathur.library.ui.IconStop+import com.vayunmathur.library.ui.IconVideoCamera+import com.vayunmathur.library.wearlink.camera.WearCameraState  /**- * The live viewfinder: newest preview frame from the phone camera, the- * mirrored mode/zoom/recording state, and the shutter/record/mode- * controls. The stream runs only while this screen is visible. With no- * phone session there is no viewfinder at all — the watch has no camera.+ * The watch's only screen while the phone Camera app is open: the live+ * viewfinder streamed from the phone camera plus one small capture+ * button — no other controls. The button's theme and icon follow the+ * mode selected on the phone (see `wearCaptureButtonSpec`), and tapping+ * it sends the capture handoff the phone executes in that mode. The+ * stream runs only while this screen is visible.  */ @Composable-fun WearViewfinderScreen(-    store: WearCameraStore,-    onOpenControls: () -> Unit,-    onOpenLastCapture: () -> Unit,-) {+fun WearViewfinderScreen(store: WearCameraStore) {     val context = LocalContext.current     val connected by store.linkConnected.collectAsState()     val state by store.state.collectAsState()     val previewJpeg by store.previewJpeg.collectAsState()     val rotation by store.previewRotation.collectAsState() -    DisposableEffect(connected) {-        if (connected) WearLinkBridge.startPreview(context)+    DisposableEffect(connected, state.phoneOpen) {+        if (connected && state.phoneOpen) WearLinkBridge.startPreview(context)         onDispose { WearLinkBridge.stopPreview(context) }     }-    val decoded = remember(previewJpeg) {-        previewJpeg?.let { runCatching { BitmapFactory.decodeByteArray(it, 0, it.size) }.getOrNull() }-    }-    WearViewfinderContent(connected = connected, state = state, bitmap = decoded, rotation = rotation, onOp = { op -> WearLinkBridge.sendOpAsync(context, op) }, onOpenControls = onOpenControls, onOpenLastCapture = onOpenLastCapture)+    val decoded =+        remember(previewJpeg) {+            previewJpeg?.let { runCatching { BitmapFactory.decodeByteArray(it, 0, it.size) }.getOrNull() }+        }+    WearViewfinderContent(+        state = state,+        bitmap = decoded,+        rotation = rotation,+        onCapture = { WearLinkBridge.sendOpAsync(context, wearCaptureOp(state)) },+    ) }  /**- * Stateless viewfinder behind [WearViewfinderScreen]: connection/mirrored state and the- * decoded frame (null while waiting) are parameters, so previews render the waiting- * state with no phone. Layoutlib cannot render a live phone-camera frame — see MetadataPreviews.+ * Stateless viewfinder behind [WearViewfinderScreen]: the mirrored phone+ * state and the decoded frame (null while waiting) are parameters, so+ * previews render the waiting state with no phone. Only the frame and+ * the one capture button are composed — nothing else.  */ @Composable internal fun WearViewfinderContent(-    connected: Boolean,-    state: com.vayunmathur.library.wearlink.camera.WearCameraState,+    state: WearCameraState,     bitmap: android.graphics.Bitmap?,     rotation: Int,-    onOp: (WearCameraOp) -> Unit,-    onOpenControls: () -> Unit,-    onOpenLastCapture: () -> Unit,+    onCapture: () -> Unit, ) {-    val context = LocalContext.current--    if (!connected) {-        Column(-            modifier = Modifier.fillMaxSize().padding(horizontal = 24.dp, vertical = 24.dp),-            horizontalAlignment = Alignment.CenterHorizontally,-            verticalArrangement = Arrangement.Center,-        ) {-            Text(-                stringResource(R.string.wear_no_phone),-                style = MaterialTheme.typography.title3,-                textAlign = TextAlign.Center,-            )-            Text(-                stringResource(R.string.wear_no_phone_hint),-                style = MaterialTheme.typography.body2,-                textAlign = TextAlign.Center,-            )-        }-        return-    }--    val videoMode = state.mode in WearCameraProtocol.VIDEO_MODES-+    val spec = wearCaptureButtonSpec(state)     Box(modifier = Modifier.fillMaxSize()) {         if (bitmap != null) {             Image(@@ -119,100 +98,26 @@ internal fun WearViewfinderContent(             )         } -        Column(modifier = Modifier.align(Alignment.TopCenter).padding(top = 16.dp, start = 24.dp, end = 24.dp)) {-            Text(-                state.mode,-                style = MaterialTheme.typography.caption1,-                textAlign = TextAlign.Center,-                modifier = Modifier.fillMaxWidth(),-            )-            if (state.recording) {-                Text(-                    "REC ${formatRecordingTime(state.recordingSeconds)}",-                    style = MaterialTheme.typography.caption1,-                    textAlign = TextAlign.Center,-                    modifier = Modifier.fillMaxWidth(),-                )-            } else if (state.timerCountdown > 0) {-                Text(-                    "${state.timerCountdown}",-                    style = MaterialTheme.typography.caption1,-                    textAlign = TextAlign.Center,-                    modifier = Modifier.fillMaxWidth(),-                )-            }-        }--        // Bottom controls sit on the vertical centreline with a 24dp lift so-        // the round bezel never clips the shutter — the previous 4dp inset-        // put the circular Button's text in the bezel curve.-        Column(-            modifier = Modifier.align(Alignment.BottomCenter)-                .padding(bottom = 24.dp, start = 20.dp, end = 20.dp),-            horizontalAlignment = Alignment.CenterHorizontally,-        ) {-            LazyRow {-                items(state.remoteModes) { mode ->-                    Chip(-                        onClick = {-                            onOp(WearCameraOp(WearOpKind.SET_MODE, mode = mode))-                        },-                        label = { Text(mode, maxLines = 1) },-                        colors = if (mode == state.mode) {-                            ChipDefaults.primaryChipColors()-                        } else {-                            ChipDefaults.secondaryChipColors()-                        },-                    )-                }-            }-            Chip(-                onClick = {-                    val op = if (videoMode) {-                        WearCameraOp(WearOpKind.RECORD_TOGGLE)-                    } else {-                        WearCameraOp(WearOpKind.SHUTTER)-                    }-                    onOp(op)-                },-                label = {-                    Text(-                        when {-                            state.recording -> stringResource(R.string.wear_record_stop)-                            videoMode -> stringResource(R.string.wear_record_start)-                            else -> stringResource(R.string.wear_shutter)-                        },-                        maxLines = 1,-                    )+        // Small capture button, lifted 24dp so the round bezel never+        // clips it. Its colours/icon are the phone mode's theme: still+        // modes use the theme's primary/secondary, video modes the error+        // (record) colour, and recording shows the stop icon.+        Button(+            onClick = onCapture,+            colors =+                when (spec.theme) {+                    WearCaptureTheme.Photo -> ButtonDefaults.primaryButtonColors()+                    WearCaptureTheme.Portrait -> ButtonDefaults.secondaryButtonColors()+                    WearCaptureTheme.Video, WearCaptureTheme.Recording ->+                        ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.error)                 },-                colors = ChipDefaults.primaryChipColors(),-                modifier = Modifier.fillMaxWidth(),-            )-            LazyRow {-                item {-                    Chip(-                        onClick = onOpenControls,-                        label = { Text(stringResource(R.string.wear_controls), maxLines = 1) },-                        colors = ChipDefaults.secondaryChipColors(),-                    )-                }-                item {-                    Chip(-                        onClick = onOpenLastCapture,-                        label = { Text(stringResource(R.string.wear_last_capture), maxLines = 1) },-                        colors = ChipDefaults.secondaryChipColors(),-                    )-                }+            modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 24.dp).size(56.dp),+        ) {+            when (spec.theme) {+                WearCaptureTheme.Recording -> IconStop()+                WearCaptureTheme.Video -> IconVideoCamera()+                WearCaptureTheme.Photo, WearCaptureTheme.Portrait -> IconCamera()             }         }     } }--/** mm:ss recording duration for the viewfinder's REC line. */-internal fun formatRecordingTime(totalSeconds: Long): String {-    val minutes = totalSeconds / SECONDS_PER_MINUTE-    val seconds = totalSeconds % SECONDS_PER_MINUTE-    return "%d:%02d".format(minutes, seconds)-}--private const val SECONDS_PER_MINUTE = 60L
camera/src/main/res/values/wear_strings.xml
diff --git a/camera/src/main/res/values/wear_strings.xml b/camera/src/main/res/values/wear_strings.xmlindex ea391a5550..29a7047894 100644--- a/camera/src/main/res/values/wear_strings.xml+++ b/camera/src/main/res/values/wear_strings.xml@@ -1,21 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <resources>-    <string name="wear_no_phone">No phone nearby</string>-    <string name="wear_no_phone_hint">Open Camera on your phone and keep it nearby — the viewfinder streams from the phone camera.</string>-    <string name="wear_connecting">Looking for your phone…</string>+    <string name="wear_open_in_phone">Open in phone</string>     <string name="wear_viewfinder_waiting">Waiting for the phone viewfinder…</string>-    <string name="wear_shutter">Take photo</string>-    <string name="wear_record_start">Start recording</string>-    <string name="wear_record_stop">Stop recording</string>-    <string name="wear_controls">Controls</string>-    <string name="wear_last_capture">Last capture</string>-    <string name="wear_no_capture">No capture yet this session. Media stays on your phone.</string>-    <string name="wear_back">Back</string>-    <string name="wear_flip_lens">Flip lens</string>-    <string name="wear_front">Front</string>-    <string name="wear_back_lens">Back</string>-    <string name="wear_torch">Torch</string>-    <string name="wear_flash">Flash %1$s</string>-    <string name="wear_timer">Timer %1$s</string>-    <string name="wear_zoom">Zoom %1$s</string> </resources>
camera/src/screenshotTest/kotlin/com/vayunmathur/camera/ui/WearMetadataPreviews.kt
diff --git a/camera/src/screenshotTest/kotlin/com/vayunmathur/camera/ui/WearMetadataPreviews.kt b/camera/src/screenshotTest/kotlin/com/vayunmathur/camera/ui/WearMetadataPreviews.ktindex 978574d296..8c099e9dd4 100644--- a/camera/src/screenshotTest/kotlin/com/vayunmathur/camera/ui/WearMetadataPreviews.kt+++ b/camera/src/screenshotTest/kotlin/com/vayunmathur/camera/ui/WearMetadataPreviews.kt@@ -26,41 +26,50 @@ private val fixtureState = WearCameraState(     torch = false,     timerSeconds = 0,     lastCaptureKind = "Photo",+    phoneOpen = true, )  /**- * Store listing images for `:camera` (watch experience) — every top-level screen/route- * (viewfinder, controls, last capture).+ * Store listing images for `:camera` (watch experience) — the two watch+ * screens (open-in-phone while the phone app is closed, viewfinder ++ * capture while it is open).  *- * Exception (honest, not faked): the viewfinder's live frame is a JPEG streamed- * from the phone camera and the last-capture thumbnail is phone media; Layoutlib- * has no phone camera, so both captures render their real waiting/no-capture- * states with all controls visible — no synthetic camera image is invented.+ * Exception (honest, not faked): the viewfinder's live frame is a JPEG+ * streamed from the phone camera; Layoutlib has no phone camera, so the+ * viewfinder capture renders its real waiting state with the capture+ * button visible — no synthetic camera image is invented.  * `./gradlew :camera:metadata` copies renders into `metadata_data/photos/camera/wear/`.  */ class WearMetadataPreviews {      @PreviewTest-    @Preview(name = "1-viewfinder-round", device = ROUND, group = "wear")+    @Preview(name = "1-open-in-phone-round", device = ROUND, group = "wear")     @Composable-    fun Preview1ViewfinderRound() {-        RoundPreview {-            WearViewfinderContent(connected = true, state = fixtureState, bitmap = null, rotation = 0, onOp = {}, onOpenControls = {}, onOpenLastCapture = {})-        }+    fun Preview1OpenInPhoneRound() {+        RoundPreview { WearOpenOnPhoneContent(onOpenOnPhone = {}) }     }      @PreviewTest-    @Preview(name = "2-controls-round", device = ROUND, group = "wear")+    @Preview(name = "2-viewfinder-round", device = ROUND, group = "wear")     @Composable-    fun Preview2ControlsRound() {-        RoundPreview { WearControlsContent(state = fixtureState, onOp = {}, onBack = {}) }+    fun Preview2ViewfinderRound() {+        RoundPreview {+            WearViewfinderContent(state = fixtureState, bitmap = null, rotation = 0, onCapture = {})+        }     }      @PreviewTest-    @Preview(name = "3-last-capture-round", device = ROUND, group = "wear")+    @Preview(name = "3-viewfinder-video-round", device = ROUND, group = "wear")     @Composable-    fun Preview3LastCaptureRound() {-        RoundPreview { WearLastCaptureContent(bitmap = null, lastCaptureKind = "", onBack = {}) }+    fun Preview3ViewfinderVideoRound() {+        RoundPreview {+            WearViewfinderContent(+                state = fixtureState.copy(mode = "VIDEO"),+                bitmap = null,+                rotation = 0,+                onCapture = {},+            )+        }     } } 
camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.ktindex 7975a59c35..1b683f1a6b 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.kt@@ -40,13 +40,31 @@ class WearCameraProtocolTest {             previewStreaming = true,             lastCaptureAtMillis = 7L,             lastCaptureKind = "PHOTO",+            phoneOpen = true,         )         assertEquals(             """{"mode":"VIDEO","frontLens":true,"zoomRatio":2.0,"zoomPresets":[1.0,2.0],"zoomMin":0.5,""" +                 """"zoomMax":10.0,"flash":"AUTO","torch":true,"timerSeconds":3,"recording":true,""" +-                """"recordingSeconds":65,"previewStreaming":true,"lastCaptureAtMillis":7,"lastCaptureKind":"PHOTO"}""",+                """"recordingSeconds":65,"previewStreaming":true,"lastCaptureAtMillis":7,"lastCaptureKind":"PHOTO","phoneOpen":true}""",             encodeWearCameraState(state).decodeToString(),         )+        // State from an older phone (no phoneOpen on the wire) decodes as+        // closed: the watch must show its open-on-phone button, never a+        // viewfinder it cannot stream.+        val legacy = """{"mode":"PHOTO"}"""+        assertEquals(false, decodeWearCameraState(legacy.encodeToByteArray())?.phoneOpen)+    }++    @Test+    fun goldenOpenOnPhoneOpJson() {+        assertEquals(+            """{"kind":"OPEN_ON_PHONE"}""",+            encodeWearCameraOp(WearCameraOp(WearOpKind.OPEN_ON_PHONE)).decodeToString(),+        )+        assertEquals(+            WearOpDecision.Apply,+            planWearCameraOp(WearCameraOp(WearOpKind.OPEN_ON_PHONE), WearCameraState(phoneOpen = false)),+        )     }      @Test
camera/src/test/java/com/vayunmathur/camera/domain/WearWatchPresentationTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/WearWatchPresentationTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/WearWatchPresentationTest.ktnew file mode 100644index 0000000000..e572496ee1--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/WearWatchPresentationTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.camera.domain++import com.vayunmathur.library.wearlink.camera.WearCameraOp+import com.vayunmathur.library.wearlink.camera.WearCameraState+import com.vayunmathur.library.wearlink.camera.WearOpKind+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class WearWatchPresentationTest {+    @Test+    fun phoneClosedShowsOpenOnPhoneButton() {+        // Link up but the phone app is closed (the default state, which is+        // also what an older phone publishes): only the button.+        assertEquals(+            WearWatchScreen.OpenOnPhone,+            wearWatchScreen(linkConnected = true, state = WearCameraState(phoneOpen = false)),+        )+        assertEquals(+            WearWatchScreen.OpenOnPhone,+            wearWatchScreen(linkConnected = true, state = WearCameraState()),+        )+    }++    @Test+    fun phoneOpenShowsViewfinderAndCaptureOnly() {+        assertEquals(+            WearWatchScreen.Viewfinder,+            wearWatchScreen(linkConnected = true, state = WearCameraState(phoneOpen = true)),+        )+    }++    @Test+    fun linkDownReturnsToOpenOnPhoneEvenIfPhoneWasOpen() {+        // Phone closing (or the link dropping) returns the watch to the+        // single button: a stale phoneOpen can never hold the viewfinder.+        assertEquals(+            WearWatchScreen.OpenOnPhone,+            wearWatchScreen(linkConnected = false, state = WearCameraState(phoneOpen = true)),+        )+    }++    @Test+    fun captureThemeFollowsPhoneMode() {+        assertEquals(+            WearCaptureTheme.Photo,+            wearCaptureButtonSpec(WearCameraState(mode = "PHOTO")).theme,+        )+        assertEquals(+            WearCaptureTheme.Portrait,+            wearCaptureButtonSpec(WearCameraState(mode = "PORTRAIT")).theme,+        )+        for (mode in listOf("VIDEO", "TIMELAPSE", "CINEMATIC", "SLOW_MO")) {+            assertEquals(WearCaptureTheme.Video, wearCaptureButtonSpec(WearCameraState(mode = mode)).theme, mode)+            assertTrue(wearCaptureButtonSpec(WearCameraState(mode = mode)).togglesRecording, mode)+        }+        // Panorama/photosphere are phone-guided stills: photo theme, shutter op.+        assertEquals(+            WearCaptureTheme.Photo,+            wearCaptureButtonSpec(WearCameraState(mode = "PANORAMA")).theme,+        )+        // An unknown future phone mode is still captured as a still.+        assertEquals(+            WearCaptureTheme.Photo,+            wearCaptureButtonSpec(WearCameraState(mode = "FUTURE_MODE")).theme,+        )+    }++    @Test+    fun recordingWinsOverModeForThemeAndOp() {+        val recording = WearCameraState(mode = "VIDEO", recording = true)+        assertEquals(WearCaptureTheme.Recording, wearCaptureButtonSpec(recording).theme)+        assertEquals(WearCameraOp(WearOpKind.RECORD_TOGGLE), wearCaptureOp(recording))+    }++    @Test+    fun captureOpEmissionMatchesMode() {+        assertEquals(+            WearCameraOp(WearOpKind.SHUTTER),+            wearCaptureOp(WearCameraState(mode = "PHOTO")),+        )+        assertEquals(+            WearCameraOp(WearOpKind.SHUTTER),+            wearCaptureOp(WearCameraState(mode = "PORTRAIT")),+        )+        assertEquals(+            WearCameraOp(WearOpKind.RECORD_TOGGLE),+            wearCaptureOp(WearCameraState(mode = "VIDEO")),+        )+    }++    @Test+    fun openOnPhoneHandoffAndLaunchDecision() {+        assertEquals(WearCameraOp(WearOpKind.OPEN_ON_PHONE), wearOpenOnPhoneOp())+        // Closed phone: the handoff launches Camera. Already open: a+        // duplicate/replayed handoff is a no-op, never a relaunch.+        assertTrue(wearOpenOnPhoneShouldLaunch(phoneOpen = false, kind = WearOpKind.OPEN_ON_PHONE))+        assertFalse(wearOpenOnPhoneShouldLaunch(phoneOpen = true, kind = WearOpKind.OPEN_ON_PHONE))+        assertFalse(wearOpenOnPhoneShouldLaunch(phoneOpen = false, kind = WearOpKind.SHUTTER))+    }+}
camera/src/test/java/com/vayunmathur/camera/sync/OpenOnPhoneReceiverTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/sync/OpenOnPhoneReceiverTest.kt b/camera/src/test/java/com/vayunmathur/camera/sync/OpenOnPhoneReceiverTest.ktnew file mode 100644index 0000000000..3aa1a68170--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/sync/OpenOnPhoneReceiverTest.kt@@ -0,0 +1,33 @@+package com.vayunmathur.camera.sync++import com.vayunmathur.library.wearlink.conduit.ConduitSync+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class OpenOnPhoneReceiverTest {+    @Test+    fun openActionLaunchesAndOthersAreIgnored() {+        var launches = 0+        assertTrue(OpenOnPhoneHandler.handle(OpenOnPhoneHandler.ACTION) { launches++ })+        assertEquals(1, launches)+        assertFalse(OpenOnPhoneHandler.handle("com.example.OTHER") { launches++ })+        assertFalse(OpenOnPhoneHandler.handle(null) { launches++ })+        assertEquals(1, launches)+    }++    @Test+    fun syncTriggerOnlyStartsForCameraAppId() {+        var starts = 0+        assertEquals("camera", ConduitSyncTriggerHandler.APP_ID)+        assertTrue(+            ConduitSyncTriggerHandler.handle(ConduitSync.ACTION, "camera") { starts++ },+        )+        assertEquals(1, starts)+        assertFalse(ConduitSyncTriggerHandler.handle(ConduitSync.ACTION, "clock") { starts++ })+        assertFalse(ConduitSyncTriggerHandler.handle("com.example.OTHER", "camera") { starts++ })+        assertFalse(ConduitSyncTriggerHandler.handle(null, null) { starts++ })+        assertEquals(1, starts)+    }+}
metadata_data/photos/camera/wear/1.png
diff --git a/metadata_data/photos/camera/wear/1.png b/metadata_data/photos/camera/wear/1.pngindex a56d18f3cf..2be8870afc 100644Binary files a/metadata_data/photos/camera/wear/1.png and b/metadata_data/photos/camera/wear/1.png differ
metadata_data/photos/camera/wear/2.png
diff --git a/metadata_data/photos/camera/wear/2.png b/metadata_data/photos/camera/wear/2.pngindex 6f15acbfd1..9a979d733b 100644Binary files a/metadata_data/photos/camera/wear/2.png and b/metadata_data/photos/camera/wear/2.png differ
metadata_data/photos/camera/wear/3.png
diff --git a/metadata_data/photos/camera/wear/3.png b/metadata_data/photos/camera/wear/3.pngindex 62d21fa4e2..1b0bb2ef40 100644Binary files a/metadata_data/photos/camera/wear/3.png and b/metadata_data/photos/camera/wear/3.png differ