camera: one zoom bar, smooth scrub, rotating preview
- Commit
2b251b99e2559ec2ff933bf5343d23cb88bb0c7f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 02:39 UTC (4 days ago)
- Parents
3b849c4
Zoom cleanup: CameraSetting.ZOOM is gone, so the config row no longer carries a magnifier that re-opened the identical ZoomBar above it. The ZoomBar is now the single zoom surface, shown by default when no setting pane is selected and still hidden in the zoom-locked panorama/photosphere modes. The removed icon was only a pane toggle for that same bar; its action now lives in the ZoomBar itself (chips + scrub) and in preview pinch, both always available by default. Scrub jitter: live scrub/pinch moves called setZoomRatio, which persisted to DataStore and synced selectedLens on every move. Crossing a lens stop (0.5x/1x/2x/5x) therefore rebound the session (session bind is keyed on selectedLens) and fought the gesture at exactly those ratios; the ZoomBar also inserted/removed its live-ratio chip mid-scrub, resizing the row under the finger, and the first post-slop emission jumped by a slop-sized factor. Fixed: setZoomRatioLive applies live ratios with no persistence or lens sync and the committed final ratio (router onCommit on release) runs setZoomRatio once, preserving syncSelectedLensToZoomStop semantics; ZoomScrubRouter drives the ratio from the movement past the slop and never rounds/snaps, so drags are strictly monotonic across stops; the ZoomBar chip set is frozen during a scrub. PreviewGestureRouter gets the same live/commit split for pinch. Rotation: ZoomBar numbers and the config-row icons now rotate in place with the animated device rotation like the rest of the chrome (bar/row layouts unchanged), and the live preview display rotates in its view layer with the same physical-orientation quadrant (OrientationEventListener-fed, via DeviceRotation.previewRotationForOrientation + previewCoverScale), never the always-0 window rotation. Display-only: session and CaptureRotation/EXIF paths are untouched, so no capture gets the rotation double-applied. Tests: ZoomScrubTest pins strict monotonicity across lens stops, slop-compensated onset and commit-once-on-release (never on cancel); PreviewGestureRouterTest pins pinch monotonicity and commit-once; ZoomStopLensSyncTest pins live-to-a-stop not syncing until committed; OrientationLayoutGuardTest pins the orientation-to-preview/icon rotation mapping as the inverse of CaptureRotation's display rotation plus the cover scale; pane tests updated for the removed ZOOM setting. camera/AGENTS.md updated. Verified in this worktree: ./gradlew :camera:compileDevKotlin - BUILD SUCCESSFUL ./gradlew :camera:lint :camera:lintVitalRelease :camera:testDevUnitTest - BUILD SUCCESSFUL (lint, release lint and unit tests all green).
Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex 4c9c432e06..ac1fbcfffb 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -19,7 +19,7 @@ _Install: ./install camera (dev by default)._ - Portrait mode with on-device segmentation (MediaPipe selfie + MODNet matting on a Vulkan compute runtime, `.maml` assets) - QR/barcode scanning (zxing) and optional GPS geotagging written into EXIF **Architecture / data-flow:** Single-screen `ui/CameraScreen` + `platform/CameraViewModel` over per-mode `platform/` session objects on the `platform/camera2/` driver; `domain/` holds pure lens-selection logic, `platform/` capability queries; heavy work (stitch, night align, bokeh) goes through Rust JNI (`platform/StitchNative`) and lands in MediaStore via `data/MediaStoreSaver`. `onCreateBeforeContent` only honors the `ACTION_IMAGE_CAPTURE` capture-for-result intent; `Content()` sits behind a camera+mic permission gate.-**Lens selection:** `platform/LensSelector.enumerateLenses` feeds `domain/LensDiscovery` with every top-level camera id plus each logical camera's `getPhysicalCameraIds()` sub-cameras (validated against their stream-configuration maps); the Camera2 preview always opens the facing's logical camera, so lens stops (sub-1x / tele included) are reached through the single continuous `ui/ZoomBar` row and pinch zoom, which apply the ratio to that session via `setZoomRatio` rather than opening a sub-camera id; a committed zoom landing on a lens's nominal ratio also syncs `selectedLens` to that lens (startup persistence + night-detection reset, via `syncSelectedLensToZoomStop`), while a ratio between stops leaves the selection alone.+**Lens selection:** `platform/LensSelector.enumerateLenses` feeds `domain/LensDiscovery` with every top-level camera id plus each logical camera's `getPhysicalCameraIds()` sub-cameras (validated against their stream-configuration maps); the Camera2 preview always opens the facing's logical camera, so lens stops (sub-1x / tele included) are reached through the single continuous `ui/ZoomBar` row and pinch zoom, which apply the ratio to that session rather than opening a sub-camera id; live scrub/pinch moves go through `setZoomRatioLive` (no persistence, no lens sync), and only the committed final ratio (chip tap, scrub/pinch release, lens/Wear selection, via `setZoomRatio`) landing on a lens's nominal ratio syncs `selectedLens` to that lens (startup persistence + night-detection reset, via `syncSelectedLensToZoomStop`), while a ratio between stops leaves the selection alone. **Entry points + reading order:** `MainActivity.kt` → `Route.kt` (`Route.Camera`/`Settings`) → `ui/CameraScreen.kt` → `platform/CameraViewModel.kt` → `platform/CameraSessions.kt` → `platform/PanoramaEngine.kt` / `NightCaptureEngine.kt`. **Gotchas:** - Capture code lives in `platform/` (the Camera2 driver in `platform/camera2/`); there is no `util/` root in this module@@ -27,7 +27,7 @@ _Install: ./install camera (dev by default)._ - Listing screenshots are preview-rendered (`:camera:metadata`): Layoutlib can't open a camera, so `src/screenshotTest` draws the deterministic `FakeCameraPreview` scene behind the real top bar/grid/shutter/mode controls. `Route.Settings` is captured from the stateless `CameraSettingsContent` slice in `ui/SettingsPage.kt` with literal fixtures. The `screenshotFakePreview` parameter on `CameraScreen`/`CameraPreviewSurface` is the same seam in `main` — production-default null, never passed by `MainActivity`, so no fake frame can appear on device - Volume keys act as the shutter, gated on the camera route being foreground; Esc/space covers desktop keyboards - `.maml` model assets ship uncompressed (`noCompress`) — never compress them-- Capture rotation is one decision in `domain/CaptureRotation.kt` (sensor orientation from characteristics + physical display rotation + facing), consumed by stills (`StillCapturePlanner`), analysis frames, and video/slo-mo/Motion-Photo muxer hints. The activity is portrait-locked, so the window display rotation is always 0 and must never orient captures: the physical quadrant comes from the `OrientationEventListener` (fed to sessions via `CameraViewModel.setCaptureDisplayRotationDegrees`); preview sizing/metering keep the window rotation. Metadata convention: JPEG/JPEG_R keep sensor pixels + EXIF orientation (flip-carrying for mirrored raw front pixels), AVIF bakes rotation/mirror into pixels with EXIF Normal and no `irot`, MP4 carries only the muxer orientation hint, night/pano RGB outputs bake pixels upright. No DNG writer is wired (`DngMetadata` only assembles requirements)+- Capture rotation is one decision in `domain/CaptureRotation.kt` (sensor orientation from characteristics + physical display rotation + facing), consumed by stills (`StillCapturePlanner`), analysis frames, and video/slo-mo/Motion-Photo muxer hints. The activity is portrait-locked, so the window display rotation is always 0 and must never orient captures: the physical quadrant comes from the `OrientationEventListener` (fed to sessions via `CameraViewModel.setCaptureDisplayRotationDegrees`); preview sizing/metering keep the window rotation. The live preview's *display* rotates in its view layer with that same physical quadrant (`ui/DeviceRotation.previewRotationForOrientation` + `previewCoverScale`, applied in `CameraPreviewSurface`), as do the ZoomBar numbers and the config-row icons — glyph/display rotation only, never a second capture rotation. Metadata convention: JPEG/JPEG_R keep sensor pixels + EXIF orientation (flip-carrying for mirrored raw front pixels), AVIF bakes rotation/mirror into pixels with EXIF Normal and no `irot`, MP4 carries only the muxer orientation hint, night/pano RGB outputs bake pixels upright. No DNG writer is wired (`DngMetadata` only assembles requirements) ## Key files ### Root — entry + navigation@@ -69,7 +69,7 @@ _Install: ./install camera (dev by default)._ - com/vayunmathur/camera/ui/CameraSettingsColumn.kt - com/vayunmathur/camera/ui/CameraStatusIndicators.kt - com/vayunmathur/camera/ui/CameraWideLayout.kt-- com/vayunmathur/camera/ui/ZoomBar.kt — the single zoom row: continuous scrub + lens-stop chips, applying ratios via `setZoomRatio`+- com/vayunmathur/camera/ui/ZoomBar.kt — the single zoom row (shown by default in `CameraSettingsColumn` when no setting pane is selected, hidden in zoom-locked panorama/photosphere; there is no zoom entry in the config row below it): continuous relative scrub (live via `setZoomRatioLive`, committed on release) + lens-stop chips, numbers rotating with device orientation. Scrub mapping is the pure `domain/ZoomScrub.kt` (log-scale, slop-compensated, monotonic across lens stops, chip set frozen mid-scrub) - com/vayunmathur/camera/ui/SettingsPage.kt - com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt ### platform/ — ViewModel, sessions, engines
camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.kt b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.ktindex 53a854193a..c3c76cb95e 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.kt@@ -26,6 +26,11 @@ class PreviewGestureRouter( private val onZoom: (Float) -> Unit, private val onTap: (x: Float, y: Float) -> Unit, private val onLongPress: (x: Float, y: Float) -> Unit,+ // Committed pinch zoom (gesture end only): lens-stop selection sync+ // and persistence run here, once — never per live pinch move, where+ // a sync at a stop ratio would rebind the session mid-gesture and+ // fight the pinch at exactly that ratio.+ private val onZoomCommitted: ((Float) -> Unit)? = null, ) { /** Device zoom range; updated from the live session before each pinch. */ var minZoomRatio: Float = 1f@@ -43,6 +48,7 @@ class PreviewGestureRouter( private var lastY = 0f private var zoomAtPinchStart = 1f private var accumulatedScale = 1f+ private var lastPinchRatio: Float? = null val isPinchActive: Boolean get() = pinchActive val isLongPressFired: Boolean get() = longPressFired@@ -81,6 +87,7 @@ class PreviewGestureRouter( pinchActive = true zoomAtPinchStart = currentZoom.takeIf { it.isFinite() && it > 0f } ?: 1f accumulatedScale = 1f+ lastPinchRatio = null } } @@ -110,6 +117,7 @@ class PreviewGestureRouter( accumulatedScale *= scaleFactor val target = (zoomAtPinchStart * accumulatedScale) .coerceIn(minZoomRatio, maxZoomRatio)+ lastPinchRatio = target onZoom(target) } @@ -125,9 +133,11 @@ class PreviewGestureRouter( val wasPinch = pinchActive val wasLongPress = longPressFired val wasSlop = movedBeyondSlop+ val pinchRatio = lastPinchRatio val x = lastX val y = lastY reset()+ if (wasPinch && pinchRatio != null) onZoomCommitted?.invoke(pinchRatio) if (!wasPinch && !wasLongPress && !wasSlop) onTap(x, y) } @@ -140,5 +150,6 @@ class PreviewGestureRouter( longPressFired = false movedBeyondSlop = false accumulatedScale = 1f+ lastPinchRatio = null } }
camera/src/main/java/com/vayunmathur/camera/domain/ZoomScrub.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/ZoomScrub.kt b/camera/src/main/java/com/vayunmathur/camera/domain/ZoomScrub.ktindex db4a4e0da9..803a516465 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/ZoomScrub.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/ZoomScrub.kt@@ -132,9 +132,26 @@ fun zoomRatioForDragDelta( * scrub once it moves past the touch slop (touch-down and sub-slop * movement emit nothing); the handler uses [dragEnd]'s result to tell * a scrub from a chip tap.+ *+ * Smoothness invariants (the jitter fix):+ * - No slop step: the delta that drives the ratio is the movement+ * *past* the slop (`dx - sign(dx) * slop`), so the first emission+ * sits on the anchor ratio instead of jumping by a slop-sized factor.+ * - No detents: nothing rounds, snaps or quantises the ratio on the+ * way out — the log-scale mapping is strictly monotonic in the+ * effective delta, including across lens-stop ratios, so a steady+ * drag emits a strictly monotonic sequence (a reversal of the finger+ * reverses the ratio, by design).+ * - Live vs committed: live emissions go to [onZoom] only. Lens-stop+ * selection sync and persistence are *committed* side effects and+ * must not run per move (syncing mid-scrub changes `selectedLens`,+ * which the session bind is keyed on, and the rebind fights the+ * scrub at exactly the stop ratios). [onCommit] fires once, from+ * [dragEnd], with the final ratio. */ class ZoomScrubRouter( private val onZoom: (Float) -> Unit,+ private val onCommit: ((Float) -> Unit)? = null, ) { var minZoomRatio: Float = 1f private set@@ -145,6 +162,8 @@ class ZoomScrubRouter( private var downXPx = 0f private var anchorRatio = 1f private var scrubbing = false+ private var slopAtScrubStartPx = 0f+ private var lastEmittedRatio: Float? = null val isScrubbing: Boolean get() = scrubbing @@ -165,6 +184,8 @@ class ZoomScrubRouter( widthAtDragStartPx = widthPx anchorRatio = currentRatio scrubbing = false+ slopAtScrubStartPx = 0f+ lastEmittedRatio = null } /**@@ -174,26 +195,38 @@ class ZoomScrubRouter( * never from the absolute position. */ fun dragTo(xPx: Float, touchSlopPx: Float = 0f) {+ val dx = xPx - downXPx if (!scrubbing) {- val dx = xPx - downXPx if (dx * dx <= touchSlopPx * touchSlopPx) return scrubbing = true+ slopAtScrubStartPx = touchSlopPx }- onZoom(- zoomRatioForDragDelta(- anchorRatio,- xPx - downXPx,- widthAtDragStartPx,- minZoomRatio,- maxZoomRatio,- )+ // Drive the ratio from the movement past the slop, not the raw+ // delta: at the moment the scrub starts the effective delta is+ // ~0 and the ratio is the anchor, so there is no onset step.+ val effectiveDx = dx - kotlin.math.sign(dx) * slopAtScrubStartPx+ val ratio = zoomRatioForDragDelta(+ anchorRatio,+ effectiveDx,+ widthAtDragStartPx,+ minZoomRatio,+ maxZoomRatio, )+ lastEmittedRatio = ratio+ onZoom(ratio) } - /** All pointers up: true when the gesture was a scrub (not a tap). */+ /**+ * All pointers up: true when the gesture was a scrub (not a tap).+ * A scrub commits its final ratio through `onCommit` (committed-zoom+ * side effects — lens-stop sync, persistence — run there, once,+ * never per live move); a tap commits nothing here.+ */ fun dragEnd(): Boolean { val wasScrubbing = scrubbing+ val committed = lastEmittedRatio reset()+ if (wasScrubbing && committed != null) onCommit?.invoke(committed) return wasScrubbing } @@ -204,5 +237,7 @@ class ZoomScrubRouter( scrubbing = false widthAtDragStartPx = 0f anchorRatio = 1f+ slopAtScrubStartPx = 0f+ lastEmittedRatio = null } }
camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.ktindex 9685e49758..6e00629da8 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt@@ -45,19 +45,24 @@ fun CameraViewModel.currentZoomRange(): Pair<Float, Float> { return if (range != null) range.lower to range.upper else 1f to 1f } -fun CameraViewModel.setZoomRatio(ratio: Float) {+/**+ * Applies a zoom change to the live session (and recording engine) and+ * the displayed ratio, clamped to the session range. Shared by the live+ * and committed paths; committed-only side effects (persistence,+ * lens-stop sync) are the caller's, in [setZoomRatio].+ */+private fun CameraViewModel.applyZoomRatio(ratio: Float): Float? { // Zoom-locked modes ignore the request entirely (the zoom bar is // hidden there; this is the backstop for any other caller): apply // 1x to the session, never to the stored/persisted ratio. if (cameraModeMutable.value.isZoomLockedTo1x()) { activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)- return+ return null } val session = activeCamera2Session val range = session?.characteristics?.zoomRatioRange val clamped = if (range != null) ratio.coerceIn(range.lower, range.upper) else ratio zoomRatioMutable.value = clamped- viewModelScope.launch { ds.setString("camera_zoom_ratio", clamped.toString()) } session?.setZoomRatio(clamped) // While recording, the preview session above is torn down and the // recording engine owns the camera: forward the change there (it@@ -65,6 +70,26 @@ fun CameraViewModel.setZoomRatio(ratio: Float) { // change mid-take silently left the encoder at the record-press // framing while the UI showed the new ratio. camera2RecordingState.engine?.setZoomRatio(clamped)+ return clamped+}++/**+ * Live (in-gesture) zoom: a ZoomBar scrub or preview pinch move. Applies+ * the ratio continuously, but runs NO committed side effects — no+ * DataStore persist per move and no lens-stop sync. Syncing the lens+ * mid-scrub changes `selectedLens`, which the session bind is keyed on,+ * so crossing a stop (0.5x/1x/2x/5x) rebound the session and fought+ * the gesture at exactly those ratios (the scrub jitter). The gesture's+ * final ratio is committed through [setZoomRatio] on release.+ */+fun CameraViewModel.setZoomRatioLive(ratio: Float) {+ applyZoomRatio(ratio)+}++/** Committed zoom (chip tap, scrub/pinch release, lens/Wear selection). */+fun CameraViewModel.setZoomRatio(ratio: Float) {+ val clamped = applyZoomRatio(ratio) ?: return+ viewModelScope.launch { ds.setString("camera_zoom_ratio", clamped.toString()) } // A committed zoom landing on a lens stop commits that lens too // (selectedLens + startup persistence + night reset); between stops // the selection is left alone. See syncSelectedLensToZoomStop.
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex dd16846a3e..e248927cd6 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -41,6 +41,7 @@ import com.vayunmathur.camera.data.setShadows import com.vayunmathur.camera.data.setWarmth import com.vayunmathur.camera.platform.currentZoomRange import com.vayunmathur.camera.platform.setZoomRatio+import com.vayunmathur.camera.platform.setZoomRatioLive import com.vayunmathur.camera.platform.toggleNightModeOverride /**@@ -167,7 +168,8 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( mirrorPreview = state.mirrorPreview, currentZoom = { viewModel.zoomRatio.value }, zoomRange = { viewModel.currentZoomRange() },- onZoom = { viewModel.setZoomRatio(it) },+ onZoom = { viewModel.setZoomRatioLive(it) },+ onZoomCommitted = { viewModel.setZoomRatio(it) }, onFocus = { x, y -> viewModel.startFocusAndMeteringAt(x, y) }, onLockFocus = { x, y -> viewModel.lockFocusAndMeteringAt(x, y) }, onFallback = { viewModel.fallbackToDefaultMetering() },@@ -179,6 +181,11 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( viewModel = viewModel, previewModifier = previewModifier, screenshotFakePreview = screenshotFakePreview,+ // Display-only preview rotation (physical orientation, same+ // animated icon-rotation value the chrome uses): the live image+ // turns with the device while the session/capture rotation is+ // untouched (CaptureRotation still decides EXIF/muxer output).+ previewRotation = animatedRotation, ) CaptureFlashOverlay(viewModel.shutterFeedback, previewSize.clip(RoundedCornerShape(12.dp)))@@ -211,6 +218,8 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( zoomRatio = state.zoomRatio, availableZoomLevels = state.availableZoomLevels, onZoomSelected = { viewModel.setZoomRatio(it) },+ onZoomLive = { viewModel.setZoomRatioLive(it) },+ iconRotation = animatedRotation, zoomRange = viewModel.currentZoomRange(), exposureComp = state.exposureComp, onExposureComp = { viewModel.setExposureCompensation(it) },
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.ktindex 27c0e06003..87cacd2b50 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -8,6 +8,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import com.vayunmathur.camera.R@@ -45,9 +46,25 @@ internal fun CameraPreviewSurface( viewModel: CameraViewModel, previewModifier: Modifier, screenshotFakePreview: (@Composable (Modifier) -> Unit)? = null,+ // Display-only rotation of the live image (clockwise degrees, the+ // animated physical-orientation value the chrome icons use). The+ // session and its CaptureRotation decision are untouched, so stills/+ // video never get this rotation double-applied.+ previewRotation: Float = 0f, ) {+ // Rotate the rendered preview in place, scaled to keep covering its+ // box at quarter turns. Applied only to the surface below, never to+ // the gesture layer or overlays the caller stacks over it.+ val rotatedModifier = previewModifier.then(+ Modifier.graphicsLayer {+ rotationZ = previewRotation+ val cover = previewCoverScale(previewRotation, size.width, size.height)+ scaleX *= cover+ scaleY *= cover+ }+ ) if (screenshotFakePreview != null) {- screenshotFakePreview(previewModifier)+ screenshotFakePreview(rotatedModifier) return } val useCamera2Preview = state.useCamera2Preview@@ -61,7 +78,7 @@ internal fun CameraPreviewSurface( ) { // The recording engine owns the camera; the recording preview's // own TextureView surface is the engine's preview target.- Camera2RecordingPreview(viewModel = viewModel, modifier = previewModifier)+ Camera2RecordingPreview(viewModel = viewModel, modifier = rotatedModifier) return } @@ -80,10 +97,10 @@ internal fun CameraPreviewSurface( viewModel.registerCamera2SloMoControl(control) }, onError = { viewModel.onCamera2SloMoFailed(sloMoCamera2Id) },- modifier = previewModifier,+ modifier = rotatedModifier, ) } else {- Box(modifier = previewModifier.background(Color.Black))+ Box(modifier = rotatedModifier.background(Color.Black)) } } @@ -101,10 +118,10 @@ internal fun CameraPreviewSurface( viewModel.registerCamera2ExtensionSession(session) }, onError = { viewModel.onCamera2NightPreviewFailed(nightCamera2Id) },- modifier = previewModifier,+ modifier = rotatedModifier, ) } else {- Box(modifier = previewModifier.background(Color.Black))+ Box(modifier = rotatedModifier.background(Color.Black)) } } if (useCamera2Preview && !useCamera2NightPreview && !useCamera2SloMoPreview) {@@ -137,17 +154,17 @@ internal fun CameraPreviewSurface( analysisConsumer = viewModel.camera2AnalysisConsumer(), onError = { viewModel.onCamera2PreviewFailed(camera2Id) }, onBindRequested = { viewModel.noteCamera2BindRequested() },- modifier = previewModifier,+ modifier = rotatedModifier, ) } else {- Box(modifier = previewModifier.background(Color.Black))+ Box(modifier = rotatedModifier.background(Color.Black)) } } if (!useCamera2Preview && !useCamera2NightPreview && !useCamera2SloMoPreview) { if (state.sessionBindFailed) { // Bind exhausted its retries: a visible, retryable error instead // of parking on a black preview until the next mode/lens change.- Box(modifier = previewModifier.background(Color.Black), contentAlignment = Alignment.Center) {+ Box(modifier = rotatedModifier.background(Color.Black), contentAlignment = Alignment.Center) { ErrorState( title = stringResource(R.string.camera_bind_failed_title), message = stringResource(R.string.camera_bind_failed_message),@@ -158,7 +175,7 @@ internal fun CameraPreviewSurface( } else { // Brief gap between a mode's teardown and the next session's first frame. // Show a plain black fill (no debug text) so the switch reads as instant.- Box(modifier = previewModifier.background(Color.Black))+ Box(modifier = rotatedModifier.background(Color.Black)) } } }
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex 8500f99ea2..029dba50bc 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -99,7 +99,7 @@ internal fun CameraScreenEffects( } // Re-render (not close) the settings pane on a mode switch: a pane the- // new mode also offers (BRIGHTNESS/ZOOM in VIDEO) stays open with its+ // new mode also offers (BRIGHTNESS in VIDEO) stays open with its // correct control; a photo-only pane (SHADOWS/WARMTH/EXPOSURE_TIME/ // ISO/PORTRAIT_BLUR) is cleared so the column falls back to the new // mode's zoom bar instead of showing the stale photo slider, and
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.ktindex 05eaa93ae7..f536eea36d 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.kt@@ -5,26 +5,22 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import com.vayunmathur.camera.platform.CameraMode-import com.vayunmathur.camera.platform.isZoomLockedTo1x -/** Which settings pane is open below the preview. */+/** Which settings pane is open below the preview. Zoom is not a pane:+ * the ZoomBar is the single zoom surface, shown by default (no pane+ * selected) in every mode that does not lock zoom to 1x. */ internal enum class CameraSetting {- BRIGHTNESS, SHADOWS, WARMTH, EXPOSURE_TIME, PORTRAIT_BLUR, ISO, ZOOM+ BRIGHTNESS, SHADOWS, WARMTH, EXPOSURE_TIME, PORTRAIT_BLUR, ISO } /**- * The settings offered in [mode], in button-row order.+ * The settings offered in [mode], in button-row order. Zoom has no entry+ * here: it is not opened from this row (the ZoomBar above the row is+ * already the zoom control, shown by default), and zoom-locked modes+ * (PANORAMA/PHOTOSPHERE, `isZoomLockedTo1x`) hide that bar instead. * * Applicability is judged by whether the capture path actually honours the * setting in that mode:- * - [CameraSetting.ZOOM]: `setZoomRatio` goes through the bound camera's- * `CameraControl`, which drives every bound use case — photo stills and- * the video Preview+VideoCapture alike (preview and recording), and is- * re-applied on every bind by `refreshCapabilities`/`restoreZoom`. So- * zoom is offered everywhere the zoom bar already worked — EXCEPT- * PANORAMA/PHOTOSPHERE, where stitch input must be at 1x: those modes- * lock zoom to 1.0x (see `isZoomLockedTo1x`), so offering a zoom pane- * there would be a control that cannot take effect. * - [CameraSetting.BRIGHTNESS] (exposure compensation): likewise a * `CameraControl` call (`setExposureCompensationIndex`), re-applied on * video binds too, so it is live for stills and video. Offered for@@ -57,11 +53,6 @@ internal fun settingsForMode(mode: CameraMode): List<CameraSetting> { add(CameraSetting.ISO) } if (mode == CameraMode.PORTRAIT) add(CameraSetting.PORTRAIT_BLUR)- // Zoom-locked modes (PANORAMA/PHOTOSPHERE) get no ZOOM entry at- // all: the magnifier must not be offered for a locked control,- // and effectiveSettingForMode then resolves a stale ZOOM pane- // to null, which CameraSettingsColumn renders without any bars.- if (!mode.isZoomLockedTo1x()) add(CameraSetting.ZOOM) } }
camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.ktindex f949474639..7ad6c044c3 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt@@ -16,6 +16,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight@@ -31,7 +32,6 @@ import com.vayunmathur.library.ui.IconIso import com.vayunmathur.library.ui.IconLightbulb import com.vayunmathur.library.ui.IconSunny import com.vayunmathur.library.ui.IconTimer-import com.vayunmathur.library.ui.IconZoomIn import com.vayunmathur.library.ui.Slider import com.vayunmathur.library.ui.SliderDefaults import com.vayunmathur.library.ui.Text@@ -91,15 +91,18 @@ internal fun SettingsButtonRow( activeSetting: CameraSetting?, cameraMode: CameraMode, onSelect: (CameraSetting?) -> Unit,- modifier: Modifier = Modifier+ modifier: Modifier = Modifier,+ // Glyph rotation for the physical device orientation (icons rotate+ // in place, the row layout does not), like the top/shutter chrome.+ iconRotation: Float = 0f, ) { // Offer only settings the capture path honours in this mode (see // settingsForMode): elsewhere they'd silently move a preview effect- // that the capture path drops. Video gets brightness (exposure- // compensation) and zoom, both CameraControl-driven. Zoom-locked- // modes (PANORAMA/PHOTOSPHERE) offer nothing at all — in particular- // no ZOOM magnifier for the locked 1x — so the row itself is hidden- // rather than rendering an empty pill.+ // that the capture path drops. Zoom is not in this row: the ZoomBar+ // above it is the zoom control (shown by default), so there is no+ // magnifier entry to re-open it. Zoom-locked modes+ // (PANORAMA/PHOTOSPHERE) offer nothing at all, so the row itself is+ // hidden rather than rendering an empty pill. val settings: List<Pair<CameraSetting, @Composable (Modifier, Color) -> Unit>> = settingsForMode(cameraMode).map { setting -> setting to when (setting) {@@ -109,7 +112,6 @@ internal fun SettingsButtonRow( CameraSetting.EXPOSURE_TIME -> { m: Modifier, c: Color -> IconTimer(m, c) } CameraSetting.ISO -> { m: Modifier, c: Color -> IconIso(m, c) } CameraSetting.PORTRAIT_BLUR -> { m: Modifier, c: Color -> IconBlur(m, c) }- CameraSetting.ZOOM -> { m: Modifier, c: Color -> IconZoomIn(m, c) } } } if (settings.isEmpty()) return@@ -131,7 +133,7 @@ internal fun SettingsButtonRow( .clickable { onSelect(if (isActive) null else setting) }, contentAlignment = Alignment.Center ) {- icon(Modifier.size(20.dp), if (isActive) Color.White else Color(0xFFBBBBBB))+ icon(Modifier.size(20.dp).rotate(iconRotation), if (isActive) Color.White else Color(0xFFBBBBBB)) } } }
camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.ktindex cfd84ee1e1..146e32f2e5 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt@@ -27,6 +27,10 @@ internal fun CameraSettingsColumn( zoomRatio: Float, availableZoomLevels: List<Pair<String, Float>>, onZoomSelected: (Float) -> Unit,+ // Live in-scrub zoom (no committed side effects); defaults to the+ // committed callback for previews/tests without a live session.+ onZoomLive: (Float) -> Unit = onZoomSelected,+ iconRotation: Float = 0f, zoomRange: Pair<Float, Float> = (availableZoomLevels.minOfOrNull { it.second } ?: 1f) to (availableZoomLevels.maxOfOrNull { it.second } ?: 1f),@@ -87,7 +91,10 @@ internal fun CameraSettingsColumn( // clears the stored pane so it does not resurrect on switching back. val effectiveSetting = effectiveSettingForMode(activeSetting, cameraMode) when (effectiveSetting) {- null, CameraSetting.ZOOM -> {+ null -> {+ // The single zoom surface, shown by default (no pane+ // selected): zoom is not a config-row pane, so nothing+ // else renders a second zoom bar above this one. // Zoom-locked modes (PANORAMA/PHOTOSPHERE) show no zoom // bar: it is a control that cannot take effect at the // locked 1x, which is exactly the field-of-view change@@ -98,7 +105,9 @@ internal fun CameraSettingsColumn( currentZoom = zoomRatio, zoomLevels = availableZoomLevels, onZoomSelected = onZoomSelected,- zoomRange = zoomRange+ onZoomLive = onZoomLive,+ zoomRange = zoomRange,+ iconRotation = iconRotation, ) } }@@ -138,7 +147,8 @@ internal fun CameraSettingsColumn( SettingsButtonRow( activeSetting = effectiveSetting, cameraMode = cameraMode,- onSelect = onSelectSetting+ onSelect = onSelectSetting,+ iconRotation = iconRotation, ) } }
camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt b/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.ktindex ed1f50f395..662efd8db2 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt@@ -27,6 +27,38 @@ internal fun deviceRotationForOrientation(orientation: Int): Int? = when { else -> 0 } +/**+ * Clockwise degrees the live preview *display* rotates for an+ * `OrientationEventListener` angle, or null when unknown (keep the last+ * rotation). This is the same physical-orientation source and quadrant+ * as the icon rotation ([deviceRotationForOrientation]) and as capture+ * rotation (`CaptureRotation.displayRotationForOrientationAngle` — the+ * two are exact inverses via `CaptureRotation.displayRotationDegrees`),+ * NOT the window display rotation, which is always 0 in this+ * portrait-locked activity. Display-only: rotating the preview view+ * never touches the session, so captures keep their single+ * `CaptureRotation` decision (EXIF/muxer) with no double application.+ */+internal fun previewRotationForOrientation(orientation: Int): Int? =+ deviceRotationForOrientation(orientation)++/**+ * Uniform scale that keeps a [width]x[height] preview covering its box+ * while the display rotates it by [rotationDegrees] (clockwise) in+ * place: the rotated content's bounding box must still cover the+ * unrotated box on both axes. 1 at 0/180 for a square box; for a+ * 90/270 turn it is `max(w/h, h/w)`. Pure so the mapping is testable.+ */+internal fun previewCoverScale(rotationDegrees: Float, width: Float, height: Float): Float {+ if (width <= 0f || height <= 0f || !rotationDegrees.isFinite()) return 1f+ val rad = Math.toRadians(rotationDegrees.toDouble())+ val cos = kotlin.math.abs(kotlin.math.cos(rad)).toFloat()+ val sin = kotlin.math.abs(kotlin.math.sin(rad)).toFloat()+ val boundW = width * cos + height * sin+ val boundH = width * sin + height * cos+ return maxOf(boundW / width, boundH / height).coerceAtLeast(1f)+}+ /** * Whether the capture controls (shutter row + mode/bottom rows) rearrange * side-by-side for [deviceRotation]. Always false: rotating the phone must
camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt b/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.ktindex e251dd3614..ee4e1e8ed5 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt@@ -97,6 +97,9 @@ internal fun Modifier.previewGestures( currentZoom: () -> Float, zoomRange: () -> Pair<Float, Float>, onZoom: (Float) -> Unit,+ // Committed pinch zoom at gesture end (lens-stop sync/persistence+ // run there, once); live moves go through [onZoom] only.+ onZoomCommitted: ((Float) -> Unit)? = null, onFocus: (Float, Float) -> Unit, onLockFocus: (Float, Float) -> Unit, onFallback: () -> Unit,@@ -127,6 +130,7 @@ internal fun Modifier.previewGestures( val router = PreviewGestureRouter( onZoom = onZoom,+ onZoomCommitted = onZoomCommitted, onTap = { x, y -> val now = SystemClock.uptimeMillis() if (now - state.lastTapMs >= FOCUS_TAP_DEBOUNCE_MS) {
camera/src/main/java/com/vayunmathur/camera/ui/ZoomBar.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/ZoomBar.kt b/camera/src/main/java/com/vayunmathur/camera/ui/ZoomBar.ktindex bc34f5b29a..75c0dc86e5 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/ZoomBar.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/ZoomBar.kt@@ -18,6 +18,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned@@ -54,11 +55,19 @@ internal fun ZoomBar( // defaults to the offered levels' span for previews/tests without a // live session. zoomRange: Pair<Float, Float> =- (zoomLevels.minOfOrNull { it.second } ?: 1f) to (zoomLevels.maxOfOrNull { it.second } ?: 1f)+ (zoomLevels.minOfOrNull { it.second } ?: 1f) to (zoomLevels.maxOfOrNull { it.second } ?: 1f),+ // Live in-scrub ratios (applied continuously, no committed side+ // effects); chip taps and the scrub's final ratio go through+ // [onZoomSelected] as committed zoom. Defaults to [onZoomSelected]+ // for previews/tests without a live session.+ onZoomLive: (Float) -> Unit = onZoomSelected,+ // Glyph rotation for the physical device orientation: the numbers+ // rotate in place like the other chrome, the bar layout does not.+ iconRotation: Float = 0f, ) { // Insert the live zoom ratio between the two fixed levels it falls between, // unless it already matches one of the listed options.- val displayLevels = remember(zoomLevels, currentZoom) {+ val liveDisplayLevels = remember(zoomLevels, currentZoom) { if (zoomLevels.any { kotlin.math.abs(it.second - currentZoom) < 0.05f }) { zoomLevels } else {@@ -68,10 +77,18 @@ internal fun ZoomBar( else zoomLevels.toMutableList().apply { add(insertAt, entry) } } }+ // While scrubbing, the chip set is frozen at its drag-start shape:+ // inserting/removing the live-ratio chip mid-scrub resized the row+ // under the finger and made the bar itself jitter, even though the+ // ratio mapping (frozen width + anchor) was stable.+ var frozenLevels by remember { mutableStateOf<List<Pair<String, Float>>?>(null) }+ val displayLevels = frozenLevels ?: liveDisplayLevels // Latest values for the long-lived gesture handler below. val currentOnZoomSelected by rememberUpdatedState(onZoomSelected)+ val currentOnZoomLive by rememberUpdatedState(onZoomLive) val currentZoomRange by rememberUpdatedState(zoomRange) val currentZoomState by rememberUpdatedState(currentZoom)+ val currentDisplayLevels by rememberUpdatedState(liveDisplayLevels) var chipBounds by remember { mutableStateOf<List<ZoomChipBounds>>(emptyList()) } val currentChipBounds by rememberUpdatedState(chipBounds) Row(@@ -83,18 +100,24 @@ internal fun ZoomBar( // anchored at drag start is scaled log-scale by the drag delta // (never by the finger's absolute position, so touch-down alone // emits nothing and a small move never jumps) and is applied- // live through onZoomSelected (CameraViewModel.setZoomRatio, so- // clamping and the panorama/photosphere zoom lock compose- // exactly as for pinch); a release without scrubbing selects+ // live through onZoomLive (CameraViewModel.setZoomRatioLive:+ // clamping and the panorama/photosphere zoom lock, but no+ // lens-stop sync or persistence mid-scrub); the release+ // commits the final ratio through onZoomSelected, and a+ // release without scrubbing selects // the chip under the finger. Chips carry only a semantics click // action (accessibility / test clicks), no touch detector of // their own. .pointerInput(Unit) {- val router = ZoomScrubRouter(onZoom = { currentOnZoomSelected(it) })+ val router = ZoomScrubRouter(+ onZoom = { currentOnZoomLive(it) },+ onCommit = { currentOnZoomSelected(it) },+ ) awaitEachGesture { val down = awaitFirstDown(requireUnconsumed = false) val (minZoom, maxZoom) = currentZoomRange router.updateZoomRange(minZoom, maxZoom)+ frozenLevels = currentDisplayLevels router.dragStart(down.position.x, size.width.toFloat(), currentZoomState) try { while (true) {@@ -104,12 +127,18 @@ internal fun ZoomBar( router.dragTo(pressed[0].position.x, viewConfiguration.touchSlop) if (router.isScrubbing) event.changes.forEach { it.consume() } }- if (!router.dragEnd()) {+ // dragEnd commits a scrub's final ratio (lens-stop+ // sync + persistence run there, once); a release+ // without scrubbing selects the chip under the finger.+ val wasScrub = router.dragEnd()+ frozenLevels = null+ if (!wasScrub) { zoomChipAt(currentChipBounds, down.position.x) ?.let { currentOnZoomSelected(it) } } } catch (e: Exception) { router.dragCancel()+ frozenLevels = null throw e } }@@ -146,7 +175,8 @@ internal fun ZoomBar( label, color = if (isSelected) Color.White else Color(0xFFBBBBBB), fontSize = 13.sp,- fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal+ fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,+ modifier = Modifier.rotate(iconRotation), ) } }
camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.ktindex f8689431ad..cab4832cc0 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.kt@@ -134,6 +134,37 @@ class PreviewGestureRouterTest { assertEquals(listOf(2f), r.zooms) } + @Test+ fun pinchIsMonotonicAcrossLensStopsAndCommitsOnceAtEnd() {+ val zooms = mutableListOf<Float>()+ val committed = mutableListOf<Float>()+ val router = PreviewGestureRouter(+ onZoom = { zooms.add(it) },+ onTap = { _, _ -> },+ onLongPress = { _, _ -> },+ onZoomCommitted = { committed.add(it) },+ )+ router.updateZoomRange(0.5f, 10f)+ router.pointerDown(1, 100f, 100f, 0.5f)+ router.pointerDown(2, 150f, 100f, 0.5f)+ repeat(12) { router.pinch(1.25f) }+ assertTrue(committed.isEmpty(), "no commit may fire mid-pinch: $committed")+ assertTrue(+ zooms.zipWithNext().all { (a, b) -> b > a },+ "pinch must be strictly monotonic across stops: $zooms",+ )+ assertTrue(zooms.any { it < 1f } && zooms.any { it > 5f }, "must cross stops: $zooms")+ router.gestureEnd()+ assertEquals(listOf(zooms.last()), committed, "one commit with the final ratio")++ // A cancelled pinch commits nothing.+ router.pointerDown(1, 100f, 100f, 1f)+ router.pointerDown(2, 150f, 100f, 1f)+ router.pinch(2f)+ router.gestureCancel()+ assertEquals(1, committed.size, "cancelled pinch must not commit: $committed")+ }+ @Test fun degenerateZoomRangeCollapsesToOne() { val r = Recorder()
camera/src/test/java/com/vayunmathur/camera/domain/ZoomScrubTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/ZoomScrubTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/ZoomScrubTest.ktindex 9590a31dea..3eed121432 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/ZoomScrubTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/ZoomScrubTest.kt@@ -92,10 +92,11 @@ class ZoomScrubTest { router.dragTo(200f, touchSlopPx = 10f) assertTrue(router.isScrubbing) assertEquals(2, emitted.size)- // Relative from the 1x anchor: dx=50 -> 16^(50/400) = 1.414x,- // dx=100 -> 16^(100/400) = 2x. Position on the bar is irrelevant.- assertEquals(1.4142f, emitted[0], 0.001f)- assertEquals(2f, emitted[1], 0.001f)+ // Relative from the 1x anchor, driven by the movement PAST the+ // 10px slop: dx=50 -> eff 40 -> 16^(40/400) = 1.32x, dx=100 ->+ // eff 90 -> 16^(90/400) = 1.87x. Position on the bar is irrelevant.+ assertEquals(1.3195f, emitted[0], 0.001f)+ assertEquals(1.8661f, emitted[1], 0.001f) assertTrue(router.dragEnd(), "a scrubbed gesture must not read as a tap") } @@ -144,7 +145,7 @@ class ZoomScrubTest { router.dragStart(195f, 200f, currentRatio = 1f) router.dragTo(215f, touchSlopPx = 1f) assertEquals(1, emitted.size)- assertEquals(1.1487f, emitted[0], 0.001f)+ assertEquals(1.1408f, emitted[0], 0.001f) assertTrue(emitted[0] < 1.3f, "small drag must stay near anchor, got $emitted") } @@ -188,14 +189,73 @@ class ZoomScrubTest { router.dragStart(50f, 100f, currentRatio = 2f) // Same delta always yields the same ratio within one gesture, even // though the live-chip insertion would widen the real bar and the- // live ratio has since moved: dx=50 -> 2x * 4^(50/200) = 2.83x.+ // live ratio has since moved: dx=50, past the 1px slop ->+ // 2x * 4^(49/200) = 2.81x. router.dragTo(100f, touchSlopPx = 1f) router.dragTo(100f, touchSlopPx = 1f) assertEquals(2, emitted.size)- assertEquals(2.8284f, emitted[0], 0.001f)+ assertEquals(2.8089f, emitted[0], 0.001f) assertEquals(emitted[0], emitted[1], 0.0001f) } + @Test+ fun scrubIsStrictlyMonotonicAcrossLensStops() {+ // A steady rightward drag must emit a strictly increasing sequence+ // over the whole range, with no plateau, snap or reversal at the+ // 1x/2x/5x lens-stop ratios it crosses.+ val emitted = mutableListOf<Float>()+ val router = ZoomScrubRouter(onZoom = { emitted.add(it) })+ router.updateZoomRange(0.5f, 10f)+ router.dragStart(0f, 200f, currentRatio = 0.5f)+ for (x in 10..400 step 10) router.dragTo(x.toFloat(), touchSlopPx = 0f)+ assertTrue(router.dragEnd())+ assertTrue(emitted.size > 20, "expected many live emissions, got $emitted")+ assertTrue(+ emitted.zipWithNext().all { (a, b) -> b > a },+ "scrub must be strictly monotonic across stops: $emitted",+ )+ assertTrue(emitted.first() > 0.5f && emitted.last() == 10f, "endpoints: $emitted")+ // It really crossed the stops (values on both sides of each).+ for (stop in listOf(1f, 2f, 5f)) {+ assertTrue(emitted.any { it < stop } && emitted.any { it > stop }, "must cross $stop: $emitted")+ }+ }++ @Test+ fun scrubOnsetHasNoSlopStep() {+ // The first emission past the slop sits on the anchor, not a+ // slop-sized factor away from it.+ val emitted = mutableListOf<Float>()+ val router = ZoomScrubRouter(onZoom = { emitted.add(it) })+ router.updateZoomRange(0.5f, 10f)+ router.dragStart(100f, 200f, currentRatio = 2f)+ router.dragTo(121f, touchSlopPx = 20f)+ assertEquals(1, emitted.size)+ assertTrue(+ kotlin.math.abs(emitted[0] / 2f - 1f) < 0.02f,+ "first scrub emission must stay near the 2x anchor, got $emitted",+ )+ }++ @Test+ fun scrubCommitsOnceAtDragEndAndNeverOnCancel() {+ val live = mutableListOf<Float>()+ val committed = mutableListOf<Float>()+ val router = ZoomScrubRouter(onZoom = { live.add(it) }, onCommit = { committed.add(it) })+ router.updateZoomRange(0.5f, 10f)+ router.dragStart(0f, 200f, currentRatio = 1f)+ router.dragTo(80f, touchSlopPx = 0f)+ router.dragTo(160f, touchSlopPx = 0f)+ assertTrue(committed.isEmpty(), "no commit may fire mid-scrub: $committed")+ assertTrue(router.dragEnd())+ assertEquals(listOf(live.last()), committed, "one commit with the final ratio")++ router.dragStart(0f, 200f, currentRatio = 1f)+ router.dragTo(80f, touchSlopPx = 0f)+ router.dragCancel()+ assertEquals(1, committed.size, "a cancelled scrub must not commit: $committed")+ }+ @Test fun routerDegenerateRangeEmitsLockedRatio() { val emitted = mutableListOf<Float>()
camera/src/test/java/com/vayunmathur/camera/platform/ZoomStopLensSyncTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/ZoomStopLensSyncTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/ZoomStopLensSyncTest.ktindex 5041bd5900..c753457328 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/ZoomStopLensSyncTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/ZoomStopLensSyncTest.kt@@ -109,6 +109,26 @@ class ZoomStopLensSyncTest { assertEquals(2.5f, viewModel.zoomRatio.value) } + @Test+ fun liveZoomToAStopDoesNotSyncLensUntilCommitted() {+ val viewModel = vmWithLenses()+ viewModel.lowLightDetectedMutable.value = true++ // A scrub/pinch move landing exactly on the tele stop is live+ // only: the ratio applies, but the lens must not commit mid-+ // gesture (that commit rebinds the session and fights the scrub).+ viewModel.setZoomRatioLive(2f)+ assertEquals(2f, viewModel.zoomRatio.value)+ assertEquals(wide, viewModel.selectedLens.value, "live zoom must not sync the lens")+ assertTrue(viewModel.lowLightDetected.value, "live zoom must not reset night detection")++ // Committing the same ratio runs the sync exactly as before.+ viewModel.setZoomRatio(2f)+ assertEquals(tele, viewModel.selectedLens.value)+ assertFalse(viewModel.lowLightDetected.value, "commit must reset night detection")+ awaitStored(viewModel, LAST_LENS_ID_KEY, "2")+ }+ @Test fun selectLensStillAppliesZoomWithoutRecursing() { val viewModel = vmWithLenses()
camera/src/test/java/com/vayunmathur/camera/ui/CameraVideoSettingsComposeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraVideoSettingsComposeTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraVideoSettingsComposeTest.ktindex b28ced8ebd..015f4436f9 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraVideoSettingsComposeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraVideoSettingsComposeTest.kt@@ -18,7 +18,8 @@ import kotlin.test.assertTrue import org.junit.Rule import org.junit.runner.RunWith -/** Video-mode settings: no stale photo panes, zoom + exposure available. */+/** Video-mode settings: no stale photo panes; the ZoomBar is the default+ * pane (not a config-row setting), exposure stays a pane. */ @RunWith(AndroidJUnit4::class) class CameraVideoSettingsComposeTest { @@ -49,12 +50,12 @@ class CameraVideoSettingsComposeTest { assertEquals( listOf( CameraSetting.BRIGHTNESS, CameraSetting.SHADOWS, CameraSetting.WARMTH,- CameraSetting.EXPOSURE_TIME, CameraSetting.ISO, CameraSetting.ZOOM,+ CameraSetting.EXPOSURE_TIME, CameraSetting.ISO, ), settingsForMode(CameraMode.PHOTO), ) assertEquals(- listOf(CameraSetting.BRIGHTNESS, CameraSetting.ZOOM),+ listOf(CameraSetting.BRIGHTNESS), settingsForMode(CameraMode.VIDEO), ) assertEquals(settingsForMode(CameraMode.VIDEO), settingsForMode(CameraMode.TIMELAPSE))@@ -69,10 +70,8 @@ class CameraVideoSettingsComposeTest { CameraSetting.BRIGHTNESS, effectiveSettingForMode(CameraSetting.BRIGHTNESS, CameraMode.VIDEO), )- assertEquals(- CameraSetting.ZOOM,- effectiveSettingForMode(CameraSetting.ZOOM, CameraMode.VIDEO),- )+ // Zoom is not a setting at all: there is no zoom entry to resolve.+ assertTrue(CameraSetting.entries.none { it.name == "ZOOM" }) } @Test fun switchingPhotoShadowsPanelToVideoShowsZoomAndAppliesIt() {@@ -107,18 +106,20 @@ class CameraVideoSettingsComposeTest { rule.onNodeWithText("+0.5").assertIsDisplayed() } - @Test fun videoModeZoomSettingShowsZoomBar() {- column(CameraMode.VIDEO, CameraSetting.ZOOM)+ @Test fun videoModeDefaultPaneShowsZoomBar() {+ // No pane selected: the ZoomBar is the default (and only) zoom+ // surface in video too — it is not opened from the config row.+ column(CameraMode.VIDEO, null) rule.onNodeWithText("2x").assertIsDisplayed() } - @Test fun videoSettingsRowOffersOnlyBrightnessAndZoom() {+ @Test fun videoSettingsRowOffersOnlyBrightness() { rule.setContent { SettingsButtonRow( activeSetting = null, cameraMode = CameraMode.VIDEO, onSelect = {}, ) } rule.waitForIdle()- assertEquals(2, rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size)+ assertEquals(1, rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size) } }
camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.ktindex b4929874b1..fa4a8f7157 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.kt@@ -61,6 +61,36 @@ class OrientationLayoutGuardTest { assertNull(deviceRotationForOrientation(-1)) } + @Test+ fun previewDisplayRotationFollowsTheSamePhysicalQuadrant() {+ // The live preview image rotates with the same OrientationEventListener+ // quadrant as the icons (not the always-0 window rotation), and that+ // quadrant is the exact inverse of CaptureRotation's physical display+ // rotation, so preview and capture can never disagree about the holding+ // and the display rotation is never applied twice to a capture.+ for ((angle, icon) in listOf(0 to 0, 90 to 270, 180 to 180, 270 to 90)) {+ assertEquals(icon, previewRotationForOrientation(angle), "preview rotation for angle $angle")+ assertEquals(+ com.vayunmathur.camera.domain.CaptureRotation.displayRotationForOrientationAngle(angle),+ com.vayunmathur.camera.domain.CaptureRotation.displayRotationDegrees(icon),+ "capture display rotation must be the inverse of the preview/icon rotation at $angle",+ )+ }+ assertNull(previewRotationForOrientation(-1))+ }++ @Test+ fun previewCoverScaleKeepsRotatedPreviewCoveringItsBox() {+ // Upright / upside-down in a portrait box: no scale needed at 180,+ // and a quarter turn needs max(w/h, h/w) to keep covering.+ assertEquals(1f, previewCoverScale(0f, 300f, 400f), 0.001f)+ assertEquals(1f, previewCoverScale(180f, 300f, 400f), 0.001f)+ assertEquals(400f / 300f, previewCoverScale(90f, 300f, 400f), 0.001f)+ assertEquals(400f / 300f, previewCoverScale(270f, 300f, 400f), 0.001f)+ assertEquals(1f, previewCoverScale(90f, 400f, 400f), 0.001f)+ assertEquals(1f, previewCoverScale(45f, 0f, 400f), 0.001f)+ }+ @Test fun controlPlacementIdenticalAcrossOrientations() { for (rotation in listOf(0, 90, 180, 270)) {
camera/src/test/java/com/vayunmathur/camera/ui/PanoramaZoomLockComposeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/PanoramaZoomLockComposeTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/PanoramaZoomLockComposeTest.ktindex 986eff297e..388896adc7 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/PanoramaZoomLockComposeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/PanoramaZoomLockComposeTest.kt@@ -9,17 +9,16 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.vayunmathur.camera.platform.CameraMode import kotlin.test.Test import kotlin.test.assertEquals-import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.Rule import org.junit.runner.RunWith /**- * Panorama/Photosphere zoom lock, UI side: no ZOOM setting is offered,- * and the settings column renders no zoom bar (a zoom change would- * change the native field of view, which is the change the lock- * forbids for stitch input).+ * Panorama/Photosphere zoom lock, UI side: zoom is not a config-row+ * setting anywhere, and the settings column renders no zoom bar in the+ * locked modes (a zoom change would change the native field of view,+ * which is the change the lock forbids for stitch input). */ @RunWith(AndroidJUnit4::class) class PanoramaZoomLockComposeTest {@@ -43,20 +42,19 @@ class PanoramaZoomLockComposeTest { } @Test- fun settingsForModeExcludesZoomOnlyInLockedModes() {+ fun zoomIsNotAConfigRowSettingInAnyMode() {+ // The magnifier is gone from the config row: zoom lives only in+ // the default ZoomBar pane, so no mode offers a ZOOM setting.+ assertTrue(CameraSetting.entries.none { it.name == "ZOOM" }) for (mode in listOf(CameraMode.PANORAMA, CameraMode.PHOTOSPHERE)) {- assertFalse(CameraSetting.ZOOM in settingsForMode(mode), "ZOOM offered in $mode") assertEquals(emptyList(), settingsForMode(mode), "settings offered in $mode")- // A ZOOM pane left open from Photo resolves to no pane there.- assertNull(effectiveSettingForMode(CameraSetting.ZOOM, mode))- }- // Every other mode keeps its zoom entry, unchanged.- for (mode in CameraMode.entries - CameraMode.PANORAMA - CameraMode.PHOTOSPHERE) {- assertTrue(CameraSetting.ZOOM in settingsForMode(mode), "ZOOM missing in $mode") }+ // A stale photo-only pane left open resolves to no pane (the+ // default ZoomBar, hidden in the locked modes) there.+ assertNull(effectiveSettingForMode(CameraSetting.SHADOWS, CameraMode.PANORAMA)) assertEquals(- CameraSetting.ZOOM,- effectiveSettingForMode(CameraSetting.ZOOM, CameraMode.PHOTO),+ CameraSetting.BRIGHTNESS,+ effectiveSettingForMode(CameraSetting.BRIGHTNESS, CameraMode.PHOTO), ) } @@ -71,7 +69,7 @@ class PanoramaZoomLockComposeTest { @Test fun photosphereShowsNoZoomBar() {- column(CameraMode.PHOTOSPHERE, CameraSetting.ZOOM)+ column(CameraMode.PHOTOSPHERE, null) assertTrue(rule.onAllNodesWithText("2x").fetchSemanticsNodes().isEmpty()) assertTrue(rule.onAllNodesWithText("1x").fetchSemanticsNodes().isEmpty()) assertTrue(rule.onAllNodesWithText(".5").fetchSemanticsNodes().isEmpty())
camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.ktindex 95f835da13..cc9c50592e 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.kt@@ -38,9 +38,10 @@ class QrInPhotoRoutingTest { @Test fun photoSettingsIncludePhotoControlsZoomIncluded() { // PHOTO keeps its full control set; scanning adds no mode-specific- // pane and removes none.+ // pane and removes none. Zoom is not a config-row setting (the+ // ZoomBar is the default pane), so it is absent here by design. val settings = settingsForMode(CameraMode.PHOTO)- assertTrue(CameraSetting.ZOOM in settings)+ assertTrue(CameraSetting.entries.none { it.name == "ZOOM" }) assertTrue(CameraSetting.BRIGHTNESS in settings) } }