diff --git a/app/detekt-baseline-debug.xml b/app/detekt-baseline-debug.xml
index e52fcca96..68bb8348e 100644
--- a/app/detekt-baseline-debug.xml
+++ b/app/detekt-baseline-debug.xml
@@ -20,8 +20,6 @@
InstanceOfCheckForException:CameraSession.kt:CameraSessionImpl$exception !is IllegalArgumentException
InstanceOfCheckForException:CameraSession.kt:CameraSessionImpl$exception !is UnsupportedOperationException
InstanceOfCheckForException:CameraSession.kt:CameraSessionImpl$exception is IllegalArgumentException
-
- LargeClass:CameraSession.kt:CameraSessionImpl : CameraSession
LargeClass:MainActivity.kt:MainActivity : AppCompatActivity
LongMethod:BlurBitmap.kt:BlurBitmap$operator fun get: Bitmap
LongMethod:CameraSession.kt:CameraSessionImpl$@SuppressLint("RestrictedApi") override fun bind: BindOutcome
diff --git a/app/src/androidTest/java/app/grapheneos/camera/CameraSessionAccess.kt b/app/src/androidTest/java/app/grapheneos/camera/CameraSessionAccess.kt
index 1e3e4357d..5053fe6e5 100644
--- a/app/src/androidTest/java/app/grapheneos/camera/CameraSessionAccess.kt
+++ b/app/src/androidTest/java/app/grapheneos/camera/CameraSessionAccess.kt
@@ -1,6 +1,7 @@
package app.grapheneos.camera
import app.grapheneos.camera.data.camera.session.CameraSession
+import app.grapheneos.camera.data.camera.session.ZoomControl
import app.grapheneos.camera.di.camera.CameraSessionEntryPoint
import app.grapheneos.camera.ui.activities.MainActivity
import dagger.hilt.android.EntryPointAccessors
@@ -10,3 +11,9 @@ internal fun cameraSession(activity: MainActivity): CameraSession {
.fromActivity(activity, CameraSessionEntryPoint::class.java)
.cameraSession()
}
+
+internal fun zoomControl(activity: MainActivity): ZoomControl {
+ return EntryPointAccessors
+ .fromActivity(activity, CameraSessionEntryPoint::class.java)
+ .zoomControl()
+}
diff --git a/app/src/androidTest/java/app/grapheneos/camera/ModeSwitchLatencyRegressionTest.kt b/app/src/androidTest/java/app/grapheneos/camera/ModeSwitchLatencyRegressionTest.kt
index a53766203..5262a54b7 100644
--- a/app/src/androidTest/java/app/grapheneos/camera/ModeSwitchLatencyRegressionTest.kt
+++ b/app/src/androidTest/java/app/grapheneos/camera/ModeSwitchLatencyRegressionTest.kt
@@ -10,9 +10,11 @@ import app.grapheneos.camera.data.core.model.CameraMode
import app.grapheneos.camera.data.core.model.VideoQuality
import app.grapheneos.camera.di.camera.SnapshotProbeCacheEntryPoint
import app.grapheneos.camera.ui.activities.MainActivity
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.PreviewControlUiModel
import app.grapheneos.camera.ui.quicksettings.screen.model.QuickSettingsAction.RequiresIdleRecorder
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.CameraAction
import dagger.hilt.android.EntryPointAccessors
+import kotlin.math.abs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
@@ -140,17 +142,17 @@ class ModeSwitchLatencyRegressionTest {
ActivityScenario.launch(MainActivity::class.java).use { scenario ->
awaitModeTabs(scenario)
waitUntil(scenario, "the zoom state is attached") {
- cameraSession(it).zoom != null
+ zoomControl(it).zoom != null
}
scenario.onActivity {
it.viewfinder.onAction(CameraAction.ModeSelected(CameraMode.VIDEO))
- assertNull("the bind read the zoom state", cameraSession(it).zoom)
+ assertNull("the bind read the zoom state", zoomControl(it).zoom)
}
waitUntil(scenario, "the zoom state is attached again") {
- cameraSession(it).zoom != null
+ zoomControl(it).zoom != null
}
}
}
@@ -160,7 +162,7 @@ class ModeSwitchLatencyRegressionTest {
* camera that was just bound rather than the one it replaced.
*/
@Test
- fun switchingModes_leavesTheZoomBarUsable() {
+ fun switchingModes_leavesTheZoomControlUsable() {
ActivityScenario.launch(MainActivity::class.java).use { scenario ->
awaitModeTabs(scenario)
@@ -168,16 +170,20 @@ class ModeSwitchLatencyRegressionTest {
it.viewfinder.onAction(CameraAction.ModeSelected(CameraMode.VIDEO))
}
waitUntil(scenario, "the zoom state is attached") {
- cameraSession(it).zoom != null
+ zoomControl(it).zoom != null
}
scenario.onActivity { cameraSession(it).camera!!.cameraControl.setLinearZoom(0.5f) }
- waitUntil(scenario, "the zoom bar caught up with the camera") {
- it.zoomBar.progress == 50
+ waitUntil(scenario, "the zoom control caught up with the camera") {
+ val zoom = zoomControl(it).zoom
+ val isHalfway = zoom != null && abs(zoom.linearZoom - 0.5f) < 0.01f
+ val control = it.previewOverlays.uiState.value.control
+ val isZoomShown = control is PreviewControlUiModel.Zoom
+ isHalfway && isZoomShown && it.previewOverlays.zoomRatio.value == zoom.zoomRatio
}
scenario.onActivity {
- assertEquals(0.5f, cameraSession(it).zoom!!.linearZoom, 0.01f)
+ assertEquals(0.5f, zoomControl(it).zoom!!.linearZoom, 0.01f)
}
}
}
diff --git a/app/src/androidTest/java/app/grapheneos/camera/SelfTimerRegressionTest.kt b/app/src/androidTest/java/app/grapheneos/camera/SelfTimerRegressionTest.kt
index 178285149..d6e48af08 100644
--- a/app/src/androidTest/java/app/grapheneos/camera/SelfTimerRegressionTest.kt
+++ b/app/src/androidTest/java/app/grapheneos/camera/SelfTimerRegressionTest.kt
@@ -16,6 +16,7 @@ import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.Capture
import kotlin.time.Duration.Companion.seconds
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
@@ -57,7 +58,7 @@ class SelfTimerRegressionTest {
scenario.onActivity { activity ->
assertFalse(isSelfTimerRunning(activity))
- assertEquals(View.GONE, activity.cdTimer.visibility)
+ assertNull(activity.previewOverlays.uiState.value.selfTimerRemaining)
assertEquals(View.INVISIBLE, activity.cbCross.visibility)
}
@@ -138,7 +139,7 @@ class SelfTimerRegressionTest {
activity.captureButton.performClick()
assertTrue(isSelfTimerRunning(activity))
- assertEquals(View.VISIBLE, activity.cdTimer.visibility)
+ assertEquals(10.seconds, activity.previewOverlays.uiState.value.selfTimerRemaining)
assertEquals(View.VISIBLE, activity.cbCross.visibility)
assertFalse(activity.viewfinder.uiState.value.isSettingsPanelAvailable)
assertEquals(View.INVISIBLE, activity.tabLayout.visibility)
@@ -169,7 +170,7 @@ class SelfTimerRegressionTest {
activity.captureButton.performClick()
assertFalse(isSelfTimerRunning(activity))
- assertEquals(View.GONE, activity.cdTimer.visibility)
+ assertNull(activity.previewOverlays.uiState.value.selfTimerRemaining)
assertEquals(View.INVISIBLE, activity.cbCross.visibility)
assertTrue(activity.viewfinder.uiState.value.isSettingsPanelAvailable)
assertEquals(View.VISIBLE, activity.tabLayout.visibility)
diff --git a/app/src/androidTest/java/app/grapheneos/camera/SettingsPanelRegressionTest.kt b/app/src/androidTest/java/app/grapheneos/camera/SettingsPanelRegressionTest.kt
index c48a618f7..e7f1e8954 100644
--- a/app/src/androidTest/java/app/grapheneos/camera/SettingsPanelRegressionTest.kt
+++ b/app/src/androidTest/java/app/grapheneos/camera/SettingsPanelRegressionTest.kt
@@ -63,7 +63,7 @@ class SettingsPanelRegressionTest {
waitUntil(scenario, "the settings panel takes back") { interceptsBack(it) }
scenario.onActivity {
- it.viewfinder.onAction(CameraAction.Preview.Tapped(x = 0f, y = 0f))
+ it.viewfinder.onAction(CameraAction.Preview.Tapped)
}
waitUntil(scenario, "the settings panel gives back up") { !interceptsBack(it) }
}
diff --git a/app/src/debug/java/app/grapheneos/camera/di/camera/CameraSessionEntryPoint.kt b/app/src/debug/java/app/grapheneos/camera/di/camera/CameraSessionEntryPoint.kt
index ba900bf61..869d830e7 100644
--- a/app/src/debug/java/app/grapheneos/camera/di/camera/CameraSessionEntryPoint.kt
+++ b/app/src/debug/java/app/grapheneos/camera/di/camera/CameraSessionEntryPoint.kt
@@ -1,6 +1,7 @@
package app.grapheneos.camera.di.camera
import app.grapheneos.camera.data.camera.session.CameraSession
+import app.grapheneos.camera.data.camera.session.ZoomControl
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityComponent
@@ -9,4 +10,5 @@ import dagger.hilt.android.components.ActivityComponent
@InstallIn(ActivityComponent::class)
internal interface CameraSessionEntryPoint {
fun cameraSession(): CameraSession
+ fun zoomControl(): ZoomControl
}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/mapper/CameraFlashMapper.kt b/app/src/main/java/app/grapheneos/camera/data/camera/mapper/CameraFlashMapper.kt
new file mode 100644
index 000000000..181bc6ce7
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/mapper/CameraFlashMapper.kt
@@ -0,0 +1,52 @@
+package app.grapheneos.camera.data.camera.mapper
+
+import app.grapheneos.camera.data.camera.model.BoundCamera
+import app.grapheneos.camera.data.camera.model.CameraFlash
+import app.grapheneos.camera.data.camera.model.HighFrameRateSupport
+import app.grapheneos.camera.data.core.model.FlashMode
+import app.grapheneos.camera.data.core.model.VideoFrameRate
+import javax.inject.Inject
+
+interface CameraFlashMapper {
+
+ fun map(
+ camera: BoundCamera,
+ requestedMode: FlashMode,
+ frameRate: VideoFrameRate,
+ ): CameraFlash
+}
+
+internal class CameraFlashMapperImpl @Inject constructor() : CameraFlashMapper {
+
+ override fun map(
+ camera: BoundCamera,
+ requestedMode: FlashMode,
+ frameRate: VideoFrameRate,
+ ): CameraFlash {
+ val unavailableModes = buildSet {
+ if (limitsLowLightBoost(camera = camera, frameRate = frameRate)) {
+ add(FlashMode.LOW_LIGHT_BOOST)
+ }
+ }
+ val isSelectable = requestedMode in camera.flashModes() &&
+ requestedMode !in unavailableModes
+
+ return CameraFlash(
+ selectedMode = when {
+ isSelectable -> requestedMode
+ else -> FlashMode.OFF
+ },
+ unavailableModes = unavailableModes,
+ )
+ }
+
+ // CameraX turns low light boost off above 30 fps.
+ private fun limitsLowLightBoost(
+ camera: BoundCamera,
+ frameRate: VideoFrameRate,
+ ): Boolean {
+ return camera.isLowLightBoostSupported && camera.isVideoMode &&
+ frameRate == VideoFrameRate.FPS_60 &&
+ camera.highFrameRate == HighFrameRateSupport.Supported
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/mapper/CameraXStateMapper.kt b/app/src/main/java/app/grapheneos/camera/data/camera/mapper/CameraXStateMapper.kt
index 94a78ae1c..7dd82d2bb 100644
--- a/app/src/main/java/app/grapheneos/camera/data/camera/mapper/CameraXStateMapper.kt
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/mapper/CameraXStateMapper.kt
@@ -30,6 +30,8 @@ internal class CameraXStateMapperImpl @Inject constructor() : CameraXStateMapper
return CameraExposure(
compensationIndex = exposureState.exposureCompensationIndex,
compensationRange = range.lower..range.upper,
+ compensationStep = exposureState.exposureCompensationStep.toFloat(),
+ isCompensationSupported = exposureState.isExposureCompensationSupported,
)
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/mapper/VideoQualityMapper.kt b/app/src/main/java/app/grapheneos/camera/data/camera/mapper/VideoQualityMapper.kt
new file mode 100644
index 000000000..57ecef1c3
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/mapper/VideoQualityMapper.kt
@@ -0,0 +1,27 @@
+package app.grapheneos.camera.data.camera.mapper
+
+import app.grapheneos.camera.data.camera.model.BoundCamera
+import app.grapheneos.camera.data.core.model.VideoQuality
+import javax.inject.Inject
+
+interface VideoQualityMapper {
+
+ fun map(
+ camera: BoundCamera,
+ requestedQuality: VideoQuality,
+ ): VideoQuality
+}
+
+internal class VideoQualityMapperImpl @Inject constructor() : VideoQualityMapper {
+
+ override fun map(
+ camera: BoundCamera,
+ requestedQuality: VideoQuality,
+ ): VideoQuality {
+ // CameraX lists supported qualities from highest to lowest.
+ return when (requestedQuality) {
+ VideoQuality.HIGHEST -> camera.videoQualities.firstOrNull() ?: requestedQuality
+ else -> requestedQuality
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/model/BoundCamera.kt b/app/src/main/java/app/grapheneos/camera/data/camera/model/BoundCamera.kt
index 34eb1c1b6..57daee58a 100644
--- a/app/src/main/java/app/grapheneos/camera/data/camera/model/BoundCamera.kt
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/model/BoundCamera.kt
@@ -4,7 +4,6 @@ import app.grapheneos.camera.data.core.model.CameraMode
import app.grapheneos.camera.data.core.model.FlashMode
import app.grapheneos.camera.data.core.model.LensFacing
import app.grapheneos.camera.data.core.model.ModeSlot
-import app.grapheneos.camera.data.core.model.VideoFrameRate
import app.grapheneos.camera.data.core.model.VideoQuality
data class BoundCamera(
@@ -41,33 +40,4 @@ data class BoundCamera(
}
}
}
-
- fun appliedFlashMode(
- stored: FlashMode,
- frameRate: VideoFrameRate,
- ): FlashMode {
- val isApplied = stored in flashModes() &&
- (stored != FlashMode.LOW_LIGHT_BOOST || !limitsLowLightBoost(frameRate))
-
- return when {
- isApplied -> stored
- else -> FlashMode.OFF
- }
- }
-
- // CameraX turns low light boost off above 30 fps.
- fun limitsLowLightBoost(frameRate: VideoFrameRate): Boolean {
- return isLowLightBoostSupported &&
- isVideoMode &&
- frameRate == VideoFrameRate.FPS_60 &&
- highFrameRate == HighFrameRateSupport.Supported
- }
-
- fun recordedVideoQuality(stored: VideoQuality): VideoQuality {
- // CameraX lists the supported qualities from the highest down.
- return when (stored) {
- VideoQuality.HIGHEST -> videoQualities.firstOrNull() ?: stored
- else -> stored
- }
- }
}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraExposure.kt b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraExposure.kt
index a62fe96c8..75e3aa402 100644
--- a/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraExposure.kt
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraExposure.kt
@@ -3,4 +3,16 @@ package app.grapheneos.camera.data.camera.model
data class CameraExposure(
val compensationIndex: Int,
val compensationRange: IntRange,
-)
+ val compensationStep: Float,
+ val isCompensationSupported: Boolean,
+) {
+
+ fun isCompensated(): Boolean {
+ return compensationIndex != 0
+ }
+
+ fun isAdjustable(): Boolean {
+ return isCompensationSupported && compensationRange.first < compensationRange.last &&
+ compensationStep.isFinite() && compensationStep > 0f
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFlash.kt b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFlash.kt
new file mode 100644
index 000000000..1783b5bdf
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFlash.kt
@@ -0,0 +1,13 @@
+package app.grapheneos.camera.data.camera.model
+
+import app.grapheneos.camera.data.core.model.FlashMode
+
+data class CameraFlash(
+ val selectedMode: FlashMode,
+ val unavailableModes: Set,
+) {
+
+ fun isSelfIlluminating(): Boolean {
+ return selectedMode == FlashMode.SELF_ILLUMINATION
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFocusEvent.kt b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFocusEvent.kt
new file mode 100644
index 000000000..a4a07c588
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFocusEvent.kt
@@ -0,0 +1,20 @@
+package app.grapheneos.camera.data.camera.model
+
+sealed interface CameraFocusEvent {
+
+ data class Started(
+ val requestId: Long,
+ ) : CameraFocusEvent
+
+ data class Focused(
+ val requestId: Long,
+ ) : CameraFocusEvent
+
+ data class Locked(
+ val requestId: Long,
+ ) : CameraFocusEvent
+
+ data class Cancelled(
+ val requestId: Long,
+ ) : CameraFocusEvent
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFocusRequest.kt b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFocusRequest.kt
new file mode 100644
index 000000000..3374d0ed1
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraFocusRequest.kt
@@ -0,0 +1,11 @@
+package app.grapheneos.camera.data.camera.model
+
+import kotlin.time.Duration
+
+data class CameraFocusRequest(
+ val id: Long,
+ val x: Float,
+ val y: Float,
+ val autoCancelAfter: Duration,
+ val isLocked: Boolean = false,
+)
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraZoom.kt b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraZoom.kt
index 142c81859..02c58a7c9 100644
--- a/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraZoom.kt
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/model/CameraZoom.kt
@@ -5,4 +5,9 @@ data class CameraZoom(
val linearZoom: Float,
val minZoomRatio: Float,
val maxZoomRatio: Float,
-)
+) {
+
+ fun isAdjustable(): Boolean {
+ return minZoomRatio > 0f && maxZoomRatio.isFinite() && minZoomRatio < maxZoomRatio
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/session/CameraFeatureSupport.kt b/app/src/main/java/app/grapheneos/camera/data/camera/session/CameraFeatureSupport.kt
index 95e8f09bc..8d5d7d44e 100644
--- a/app/src/main/java/app/grapheneos/camera/data/camera/session/CameraFeatureSupport.kt
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/session/CameraFeatureSupport.kt
@@ -5,14 +5,22 @@ import androidx.camera.core.DynamicRange
import androidx.camera.core.ExperimentalZeroShutterLag
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
+import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.video.Recorder
import app.grapheneos.camera.data.camera.model.LensFeatures
+import app.grapheneos.camera.data.core.model.LensFacing
import app.grapheneos.camera.data.core.model.VideoFrameRate
import javax.inject.Inject
interface CameraFeatureSupport {
fun features(cameraInfo: CameraInfo): LensFeatures
+
+ /**
+ * Every camera rather than the one in use: a setting stays where the user left it whichever
+ * camera the settings were opened from, and is applied wherever the camera supports it.
+ */
+ fun featuresByLens(provider: ProcessCameraProvider): Map
}
internal class CameraFeatureSupportImpl @Inject constructor(
@@ -37,6 +45,16 @@ internal class CameraFeatureSupportImpl @Inject constructor(
)
}
+ override fun featuresByLens(provider: ProcessCameraProvider): Map {
+ return LensFacing.entries
+ .filter { lensFacing ->
+ provider.hasCamera(cameraSelectorFor(lensFacing))
+ }
+ .associateWith { lensFacing ->
+ features(provider.getCameraInfo(cameraSelectorFor(lensFacing)))
+ }
+ }
+
// The toggle asks for both kinds of stabilization (see the preferred feature group in
// bind), preferring the preview kind and falling back to the recording-only kind,
// so it is meaningful whenever either one is available. Testing only the recorder
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/session/CameraSession.kt b/app/src/main/java/app/grapheneos/camera/data/camera/session/CameraSession.kt
index 3c68cc31f..324dd72a2 100644
--- a/app/src/main/java/app/grapheneos/camera/data/camera/session/CameraSession.kt
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/session/CameraSession.kt
@@ -19,18 +19,15 @@ import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.video.Recorder
import androidx.camera.video.VideoCapture
import androidx.lifecycle.Lifecycle
+import app.grapheneos.camera.data.camera.mapper.CameraFlashMapper
import app.grapheneos.camera.data.camera.mapper.CameraXConstantsMapper
-import app.grapheneos.camera.data.camera.mapper.CameraXStateMapper
import app.grapheneos.camera.data.camera.model.BindOutcome
import app.grapheneos.camera.data.camera.model.BoundCamera
import app.grapheneos.camera.data.camera.model.CameraBindRequest
import app.grapheneos.camera.data.camera.model.CameraBindSettings
import app.grapheneos.camera.data.camera.model.CameraCapabilities
-import app.grapheneos.camera.data.camera.model.CameraExposure
import app.grapheneos.camera.data.camera.model.CameraSessionEvent
import app.grapheneos.camera.data.camera.model.CameraSessionPlan
-import app.grapheneos.camera.data.camera.model.CameraZoom
-import app.grapheneos.camera.data.camera.model.CameraZoomEvent
import app.grapheneos.camera.data.camera.model.ExtensionKey
import app.grapheneos.camera.data.camera.model.FeatureGroupRequest
import app.grapheneos.camera.data.camera.model.HighFrameRateSupport
@@ -43,17 +40,17 @@ import app.grapheneos.camera.data.camera.model.SnapshotProbeKey
import app.grapheneos.camera.data.camera.model.VideoFeatureGroup
import app.grapheneos.camera.data.camera.repository.CameraProviderSource
import app.grapheneos.camera.data.camera.repository.ExtensionAvailabilityRepository
+import app.grapheneos.camera.data.camera.session.ZoomControl.Restoration
import app.grapheneos.camera.data.core.model.DeviceOrientation
import app.grapheneos.camera.data.core.model.ExtensionMode
import app.grapheneos.camera.data.core.model.FlashMode
import app.grapheneos.camera.data.core.model.LensFacing
+import app.grapheneos.camera.data.core.model.VideoFrameRate
import app.grapheneos.camera.di.core.CameraSessionScope
import app.grapheneos.camera.di.core.MainImmediateDispatcher
-import app.grapheneos.camera.di.core.MainLooperDispatcher
import app.grapheneos.camera.di.core.QrAnalysisDispatcher
import com.google.zxing.BarcodeFormat
import java.util.concurrent.Executor
-import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CoroutineDispatcher
@@ -69,9 +66,10 @@ import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
+internal const val CAMERA_EVENT_BUFFER_CAPACITY = 64
+
interface CameraSession {
val events: Flow
- val zoomEvents: Flow
val boundCamera: StateFlow
val cameraProvider: ProcessCameraProvider?
@@ -83,9 +81,7 @@ interface CameraSession {
val imageCapture: ImageCapture?
val videoCapture: VideoCapture?
- val exposure: CameraExposure?
val sensorOrientationDegrees: Int?
- val zoom: CameraZoom?
fun setPreviewTarget(target: PreviewTarget?)
fun initialize(forced: Boolean, extensionMode: ExtensionMode?)
@@ -98,16 +94,10 @@ interface CameraSession {
fun unbind()
fun capabilities(): CameraCapabilities
- fun setPreviewRotation(rotation: Int)
+ fun setPreviewRotation(rotation: DeviceOrientation)
fun setCaptureOrientation(orientation: DeviceOrientation)
fun setFlashMode(flashMode: FlashMode)
- fun setZoomRatio(zoomRatio: Float)
- fun setLinearZoom(linearZoom: Float)
- fun reattachZoomState()
- fun setExposureCompensationIndex(index: Int)
- fun startFocusAndMetering(x: Float, y: Float, autoCancelSeconds: Long)
- fun cancelFocusAndMetering()
fun setBarcodeFormats(barcodeFormats: Set)
}
@@ -127,25 +117,21 @@ internal class CameraSessionImpl @Inject constructor(
private val lowLightBoostSupport: LowLightBoostSupport,
private val videoQualitySupport: VideoQualitySupport,
private val cameraXConstantsMapper: CameraXConstantsMapper,
- private val cameraXStateMapper: CameraXStateMapper,
- private val zoomStateTracker: ZoomStateTracker,
+ private val flashMapper: CameraFlashMapper,
+ private val zoomControl: ZoomControl,
+ private val focusControl: FocusControl,
+ private val exposureControl: ExposureControl,
private val sceneLightControl: SceneLightControl,
- @MainImmediateDispatcher mainDispatcher: CoroutineDispatcher,
- @MainLooperDispatcher private val mainLooperDispatcher: CoroutineDispatcher,
@QrAnalysisDispatcher qrAnalysisDispatcher: CoroutineDispatcher,
+ @MainImmediateDispatcher private val mainDispatcher: CoroutineDispatcher,
@CameraSessionScope private val scope: CoroutineScope,
) : CameraSession {
private val _events = MutableSharedFlow(
- extraBufferCapacity = EVENT_BUFFER_CAPACITY,
+ extraBufferCapacity = CAMERA_EVENT_BUFFER_CAPACITY,
)
override val events: Flow = _events.asSharedFlow()
- private val _zoomEvents = MutableSharedFlow(
- extraBufferCapacity = EVENT_BUFFER_CAPACITY,
- )
- override val zoomEvents: Flow = _zoomEvents.asSharedFlow()
-
private val _boundCamera = MutableStateFlow(null)
override val boundCamera: StateFlow = _boundCamera.asStateFlow()
@@ -171,21 +157,11 @@ internal class CameraSessionImpl @Inject constructor(
override var videoCapture: VideoCapture? = null
- override val exposure: CameraExposure?
- get() {
- return camera?.cameraInfo?.exposureState?.let { cameraXStateMapper.map(it) }
- }
-
override val sensorOrientationDegrees: Int?
get() {
return camera?.cameraInfo?.sensorRotationDegrees
}
- override val zoom: CameraZoom?
- get() {
- return zoomStateTracker.zoomState?.let { cameraXStateMapper.map(it) }
- }
-
private var extensionsManager: ExtensionsManager? = null
private var previewTarget: PreviewTarget? = null
@@ -200,10 +176,12 @@ internal class CameraSessionImpl @Inject constructor(
private var captureRotation: Int? = null
private var previewRotation: Int? = null
+ private var requestedFlashMode: FlashMode = FlashMode.OFF
+ private var videoFrameRate: VideoFrameRate = VideoFrameRate.FPS_30
+
private val mainExecutor: Executor = mainDispatcher.asExecutor()
private val qrAnalysisExecutor: Executor = qrAnalysisDispatcher.asExecutor()
- private var attachZoomStateJob: Job? = null
private var qrAutofocusJob: Job? = null
override fun setPreviewTarget(target: PreviewTarget?) {
@@ -279,23 +257,19 @@ internal class CameraSessionImpl @Inject constructor(
}
override fun bind(settings: CameraBindSettings): BindOutcome {
- val provider = requireNotNull(cameraProvider) {
- "Camera provider is not ready yet"
- }
- val target = requireNotNull(previewTarget) {
- "No screen to show the camera on"
- }
+ val provider = requireNotNull(cameraProvider) { "Camera provider is not ready yet" }
+ val target = requireNotNull(previewTarget) { "No screen to show the camera on" }
unbind()
- qrAutofocusJob?.cancel()
+
+ videoFrameRate = settings.video?.frameRate ?: VideoFrameRate.FPS_30
val appliedExtension = settings.mode.extensionMode?.let(::applyExtension)
// Asked of the selector this bind uses, extensions included: an extension mode decides for
// itself whether it can produce Ultra HDR.
- val features = currentCameraInfoOrNull()?.let {
- cameraFeatureSupport.features(it)
- } ?: LensFeatures()
+ val cameraInfo = currentCameraInfoOrNull()
+ val features = cameraInfo?.let(cameraFeatureSupport::features) ?: LensFeatures()
val videoFeatureGroup = resolveFeatureGroup(
provider = provider,
settings = settings,
@@ -331,41 +305,61 @@ internal class CameraSessionImpl @Inject constructor(
appliedExtension = appliedExtension,
)
if (outcome == BindOutcome.BOUND) {
- val cameraInfo = requireNotNull(camera) { "A bound session has a camera" }.cameraInfo
-
- _boundCamera.value = boundCameraOf(
- cameraInfo = cameraInfo,
+ onBound(
settings = settings,
highFrameRate = videoFeatureGroup.highFrameRate,
- appliedExtensionMode = appliedExtension?.extensionMode,
+ appliedExtension = appliedExtension,
)
- attachControls()
}
return outcome
}
+ private fun onBound(
+ settings: CameraBindSettings,
+ highFrameRate: HighFrameRateSupport?,
+ appliedExtension: ExtensionKey?,
+ ) {
+ _boundCamera.value = boundCameraOf(
+ cameraInfo = requireNotNull(camera) { "A bound session has a camera" }.cameraInfo,
+ settings = settings,
+ highFrameRate = highFrameRate,
+ appliedExtensionMode = appliedExtension?.extensionMode,
+ )
+ val zoomRestoration = when {
+ settings.qr != null -> Restoration.DISABLED
+ appliedExtension != null -> Restoration.WHEN_ZOOM_LOADS
+ else -> Restoration.BEFORE_PREVIEW
+ }
+ attachControls(zoomRestoration)
+ applyFlashMode()
+ }
+
override fun unbind() {
- sceneLightControl.detach()
+ detachControls()
+ qrAutofocusJob?.cancel()
cameraProvider?.unbindAll()
_boundCamera.value = null
}
override fun capabilities(): CameraCapabilities {
- val cameraInfo = camera?.cameraInfo ?: return CameraCapabilities()
+ val cameraInfo = camera?.cameraInfo
+ val provider = cameraProvider
+
+ if (cameraInfo == null || provider == null) return CameraCapabilities()
return CameraCapabilities(
lensFacing = lensFacing,
- lensFeatures = lensFeatures(),
+ lensFeatures = cameraFeatureSupport.featuresByLens(provider),
photoMegapixels = photoResolutionSupport.standardMegapixels(cameraInfo),
photoResolutions = photoResolutionSupport.resolutions(cameraInfo),
videoBitrates = videoBitrateSupport.bitrates(cameraInfo),
)
}
- override fun setPreviewRotation(rotation: Int) {
- previewRotation = rotation
- preview?.targetRotation = rotation
+ override fun setPreviewRotation(rotation: DeviceOrientation) {
+ previewRotation = cameraXConstantsMapper.map(rotation)
+ preview?.targetRotation = displayRotation()
}
override fun setCaptureOrientation(orientation: DeviceOrientation) {
@@ -375,54 +369,8 @@ internal class CameraSessionImpl @Inject constructor(
}
override fun setFlashMode(flashMode: FlashMode) {
- imageCapture?.flashMode = cameraXConstantsMapper.map(flashMode)
-
- sceneLightControl.setFlashMode(flashMode)
- }
-
- override fun setZoomRatio(zoomRatio: Float) {
- camera?.cameraControl?.setZoomRatio(zoomRatio)
- }
-
- override fun setLinearZoom(linearZoom: Float) {
- camera?.cameraControl?.setLinearZoom(linearZoom)
- }
-
- // Every bind hands out a fresh LiveData in extension modes, and the old observer would
- // otherwise stay attached: after a handful of mode switches a single zoom step redrew the
- // thumb once per bind that had ever happened.
- override fun reattachZoomState() {
- zoomStateTracker.detach()
- // Reading the new one is what costs ~100 ms behind an extension, and nothing before the
- // next message needs it: the bar is drawn once CameraZoomEvent.Loaded arrives, and every
- // other reader is a gesture.
- attachZoomStateJob?.cancel()
- attachZoomStateJob = scope.launch(mainLooperDispatcher) { attachZoomState() }
- }
-
- override fun setExposureCompensationIndex(index: Int) {
- camera?.cameraControl?.setExposureCompensationIndex(index)
- }
-
- override fun startFocusAndMetering(
- x: Float,
- y: Float,
- autoCancelSeconds: Long,
- ) {
- val meteringPointFactory = previewTarget?.meteringPointFactory ?: return
- val point = meteringPointFactory.createPoint(x, y)
- val builder = FocusMeteringAction.Builder(point)
-
- when (autoCancelSeconds) {
- 0L -> builder.disableAutoCancel()
- else -> builder.setAutoCancelDuration(autoCancelSeconds, TimeUnit.SECONDS)
- }
-
- camera?.cameraControl?.startFocusAndMetering(builder.build())
- }
-
- override fun cancelFocusAndMetering() {
- camera?.cameraControl?.cancelFocusAndMetering()
+ requestedFlashMode = flashMode
+ applyFlashMode()
}
override fun setBarcodeFormats(barcodeFormats: Set) {
@@ -432,10 +380,8 @@ internal class CameraSessionImpl @Inject constructor(
// CameraX unbinds every use case of a lifecycle that reaches ON_DESTROY, and this session
// outlives the screen whose lifecycle that was.
private fun forgetBoundCamera() {
- sceneLightControl.detach()
- attachZoomStateJob?.cancel()
+ detachControls()
qrAutofocusJob?.cancel()
- zoomStateTracker.detach()
camera = null
preview = null
imageCapture = null
@@ -445,16 +391,6 @@ internal class CameraSessionImpl @Inject constructor(
_boundCamera.value = null
}
- private fun attachControls() {
- val attachedCamera = camera ?: return
- val boundCamera = _boundCamera.value ?: return
-
- sceneLightControl.attach(
- control = attachedCamera.cameraControl,
- boundCamera = boundCamera,
- )
- }
-
private fun onCameraProviderReady(
provider: ProcessCameraProvider,
forced: Boolean,
@@ -624,7 +560,7 @@ internal class CameraSessionImpl @Inject constructor(
)
useCases.add(analysis)
- qrAutofocusJob = scope.launch(mainLooperDispatcher) {
+ qrAutofocusJob = scope.launch(mainDispatcher) {
do {
delay(QR_AUTOFOCUS_INTERVAL)
} while (focusOnQrScanAreaIfResumed())
@@ -794,21 +730,6 @@ internal class CameraSessionImpl @Inject constructor(
)
}
- // Every camera rather than the one in use: a setting stays where the user left it whichever
- // camera the settings were opened from, and is applied wherever the camera supports it.
- private fun lensFeatures(): Map {
- val provider = cameraProvider ?: return emptyMap()
-
- return LensFacing.entries
- .filter { lensFacing ->
- provider.hasCamera(cameraSelectorFor(lensFacing))
- }
- .associateWith { lensFacing ->
- val cameraInfo = provider.getCameraInfo(cameraSelectorFor(lensFacing))
- cameraFeatureSupport.features(cameraInfo)
- }
- }
-
private fun currentCameraInfoOrNull(): CameraInfo? {
return try {
cameraProvider?.getCameraInfo(cameraSelector)
@@ -832,17 +753,44 @@ internal class CameraSessionImpl @Inject constructor(
iAnalyzer?.targetRotation = rotation
}
- private fun attachZoomState() {
- val lifecycleOwner = previewTarget?.lifecycleOwner
- if (!isActive || lifecycleOwner == null) return
+ private fun applyFlashMode() {
+ val boundCamera = _boundCamera.value ?: return
+ val flash = flashMapper.map(
+ camera = boundCamera,
+ requestedMode = requestedFlashMode,
+ frameRate = videoFrameRate,
+ )
+ imageCapture?.flashMode = cameraXConstantsMapper.map(flash.selectedMode)
+ sceneLightControl.setFlashMode(flash.selectedMode)
+ }
+
+ private fun attachControls(zoomRestoration: Restoration) {
+ val attachedCamera = camera
+ val target = previewTarget
+ val boundCamera = _boundCamera.value
+ if (attachedCamera == null || target == null || boundCamera == null) return
- camera?.cameraInfo?.zoomState?.let { source ->
- zoomStateTracker.attach(
- source = source,
- lifecycleOwner = lifecycleOwner,
- onEvent = _zoomEvents::tryEmit,
- )
- }
+ focusControl.attach(
+ control = attachedCamera.cameraControl,
+ meteringPointFactory = target.meteringPointFactory,
+ )
+ zoomControl.attach(
+ camera = attachedCamera,
+ lensFacing = lensFacing,
+ restoration = zoomRestoration,
+ )
+ exposureControl.attach(attachedCamera)
+ sceneLightControl.attach(
+ control = attachedCamera.cameraControl,
+ boundCamera = boundCamera,
+ )
+ }
+
+ private fun detachControls() {
+ focusControl.detach()
+ zoomControl.detach()
+ exposureControl.detach()
+ sceneLightControl.detach()
}
private fun focusOnQrScanAreaIfResumed(): Boolean {
@@ -867,7 +815,6 @@ internal class CameraSessionImpl @Inject constructor(
companion object {
private const val TAG = "CameraSession"
- private const val EVENT_BUFFER_CAPACITY = 64
private val QR_AUTOFOCUS_INTERVAL = 2.seconds
private val DEFAULT_LENS_FACING = LensFacing.BACK
}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/session/ExposureControl.kt b/app/src/main/java/app/grapheneos/camera/data/camera/session/ExposureControl.kt
new file mode 100644
index 000000000..2ad7804c4
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/session/ExposureControl.kt
@@ -0,0 +1,116 @@
+package app.grapheneos.camera.data.camera.session
+
+import androidx.camera.core.Camera
+import androidx.camera.core.CameraControl
+import app.grapheneos.camera.data.camera.mapper.CameraXStateMapper
+import app.grapheneos.camera.data.camera.model.CameraExposure
+import app.grapheneos.camera.di.core.MainImmediateDispatcher
+import com.google.common.util.concurrent.ListenableFuture
+import java.util.concurrent.CancellationException
+import java.util.concurrent.ExecutionException
+import java.util.concurrent.Executor
+import javax.inject.Inject
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.asExecutor
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+interface ExposureControl {
+
+ /** Shows pending compensation immediately and restores the last confirmed value on failure. */
+ val exposure: StateFlow
+
+ fun attach(camera: Camera)
+
+ fun detach()
+
+ fun setCompensationIndex(index: Int)
+}
+
+internal class ExposureControlImpl @Inject constructor(
+ private val cameraXStateMapper: CameraXStateMapper,
+ @MainImmediateDispatcher mainDispatcher: CoroutineDispatcher,
+) : ExposureControl {
+
+ private val _exposure = MutableStateFlow(null)
+ override val exposure: StateFlow = _exposure.asStateFlow()
+
+ private val mainExecutor: Executor = mainDispatcher.asExecutor()
+
+ private var attachment: Attachment? = null
+
+ override fun attach(camera: Camera) {
+ detach()
+ val exposure = cameraXStateMapper.map(camera.cameraInfo.exposureState)
+ attachment = Attachment(
+ control = camera.cameraControl,
+ confirmedExposure = exposure,
+ )
+ _exposure.value = exposure
+ }
+
+ override fun detach() {
+ attachment = null
+ _exposure.value = null
+ }
+
+ override fun setCompensationIndex(index: Int) {
+ val attached = attachment ?: return
+ val exposure = attached.confirmedExposure
+ if (!exposure.isAdjustable() || index !in exposure.compensationRange) return
+
+ // CameraX fails the request this one replaces before it returns, and that listener runs
+ // inside the call: the request has to be the latest one by then.
+ val request = attached.lastRequest + 1
+ attached.lastRequest = request
+ _exposure.value = exposure.copy(compensationIndex = index)
+
+ val result = attached.control.setExposureCompensationIndex(index)
+ result.addListener(
+ {
+ onResult(
+ attachment = attached,
+ request = request,
+ result = result,
+ )
+ },
+ mainExecutor,
+ )
+ }
+
+ private fun onResult(
+ attachment: Attachment,
+ request: Int,
+ result: ListenableFuture,
+ ) {
+ if (this.attachment !== attachment) return
+
+ val index = confirmedIndex(result)
+ if (index != null) {
+ attachment.confirmedExposure = attachment.confirmedExposure.copy(
+ compensationIndex = index,
+ )
+ }
+ if (attachment.lastRequest == request) {
+ _exposure.value = attachment.confirmedExposure
+ }
+ }
+
+ private fun confirmedIndex(result: ListenableFuture): Int? {
+ return try {
+ result.get()
+ } catch (_: ExecutionException) {
+ null
+ } catch (_: CancellationException) {
+ null
+ }
+ }
+
+ private class Attachment(
+ val control: CameraControl,
+ var confirmedExposure: CameraExposure,
+ ) {
+ var lastRequest = 0
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/session/FocusControl.kt b/app/src/main/java/app/grapheneos/camera/data/camera/session/FocusControl.kt
new file mode 100644
index 000000000..8edc8767f
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/session/FocusControl.kt
@@ -0,0 +1,200 @@
+package app.grapheneos.camera.data.camera.session
+
+import androidx.camera.core.CameraControl
+import androidx.camera.core.FocusMeteringAction
+import androidx.camera.core.FocusMeteringResult
+import androidx.camera.core.MeteringPoint
+import androidx.camera.core.MeteringPointFactory
+import app.grapheneos.camera.data.camera.model.CameraFocusEvent
+import app.grapheneos.camera.data.camera.model.CameraFocusRequest
+import app.grapheneos.camera.di.core.CameraSessionScope
+import app.grapheneos.camera.di.core.MainImmediateDispatcher
+import com.google.common.util.concurrent.ListenableFuture
+import java.util.concurrent.ExecutionException
+import java.util.concurrent.Executor
+import javax.inject.Inject
+import kotlin.time.Duration
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.asExecutor
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.launch
+
+interface FocusControl {
+
+ val events: Flow
+
+ fun attach(
+ control: CameraControl,
+ meteringPointFactory: MeteringPointFactory,
+ )
+
+ fun detach()
+
+ fun focus(request: CameraFocusRequest)
+
+ fun lock()
+
+ fun cancel()
+}
+
+internal class FocusControlImpl @Inject constructor(
+ @CameraSessionScope private val scope: CoroutineScope,
+ @MainImmediateDispatcher private val mainDispatcher: CoroutineDispatcher,
+) : FocusControl {
+
+ private val _events = MutableSharedFlow(
+ extraBufferCapacity = CAMERA_EVENT_BUFFER_CAPACITY,
+ )
+ override val events: Flow = _events.asSharedFlow()
+
+ private val mainExecutor: Executor = mainDispatcher.asExecutor()
+ private var attachment: Attachment? = null
+ private var activeRequest: ActiveRequest? = null
+ private var autoCancelJob: Job? = null
+
+ override fun attach(
+ control: CameraControl,
+ meteringPointFactory: MeteringPointFactory,
+ ) {
+ detach()
+ attachment = Attachment(
+ control = control,
+ meteringPointFactory = meteringPointFactory,
+ )
+ }
+
+ override fun detach() {
+ releaseRequest()
+ attachment = null
+ }
+
+ override fun focus(request: CameraFocusRequest) {
+ releaseRequest()
+
+ val attached = attachment
+ if (attached == null) {
+ emit(CameraFocusEvent.Cancelled(requestId = request.id))
+ return
+ }
+
+ val active = ActiveRequest(
+ id = request.id,
+ point = attached.meteringPointFactory.createPoint(request.x, request.y),
+ isLocked = request.isLocked,
+ )
+ activeRequest = active
+ emit(CameraFocusEvent.Started(requestId = active.id))
+ when {
+ active.isLocked -> emit(CameraFocusEvent.Locked(requestId = active.id))
+ else -> scheduleAutoCancel(request.autoCancelAfter)
+ }
+ submit(active)
+ }
+
+ override fun lock() {
+ val request = activeRequest ?: return
+
+ stopAutoCancel()
+ val locked = request.copy(isLocked = true)
+ activeRequest = locked
+ emit(CameraFocusEvent.Locked(requestId = locked.id))
+ submit(locked)
+ }
+
+ override fun cancel() {
+ if (activeRequest == null) return
+
+ releaseRequest()
+ attachment?.control?.cancelFocusAndMetering()
+ }
+
+ private fun releaseRequest() {
+ stopAutoCancel()
+ val request = activeRequest ?: return
+
+ activeRequest = null
+ emit(CameraFocusEvent.Cancelled(requestId = request.id))
+ }
+
+ private fun scheduleAutoCancel(autoCancelAfter: Duration) {
+ if (autoCancelAfter <= Duration.ZERO) return
+
+ autoCancelJob = scope.launch(mainDispatcher) {
+ delay(autoCancelAfter)
+ cancel()
+ }
+ }
+
+ private fun stopAutoCancel() {
+ autoCancelJob?.cancel()
+ autoCancelJob = null
+ }
+
+ private fun submit(request: ActiveRequest) {
+ val control = attachment?.control ?: return
+
+ val result = control.startFocusAndMetering(fixedFocusAction(request.point))
+ val deliverResult = { onResult(request = request, result = result) }
+
+ result.addListener(deliverResult, mainExecutor)
+ }
+
+ private fun onResult(
+ request: ActiveRequest,
+ result: ListenableFuture,
+ ) {
+ if (activeRequest !== request) return
+
+ when (outcomeOf(result)) {
+ FocusOutcome.FOCUSED -> emit(CameraFocusEvent.Focused(requestId = request.id))
+ FocusOutcome.CANCELLED -> releaseRequest()
+ FocusOutcome.NOT_FOCUSED -> Unit
+ }
+ }
+
+ private fun emit(event: CameraFocusEvent) {
+ _events.tryEmit(event)
+ }
+
+ private fun fixedFocusAction(point: MeteringPoint): FocusMeteringAction {
+ return FocusMeteringAction.Builder(point).disableAutoCancel().build()
+ }
+
+ private fun outcomeOf(result: ListenableFuture): FocusOutcome {
+ if (result.isCancelled) return FocusOutcome.CANCELLED
+
+ return try {
+ when {
+ result.get().isFocusSuccessful -> FocusOutcome.FOCUSED
+ else -> FocusOutcome.NOT_FOCUSED
+ }
+ } catch (exception: ExecutionException) {
+ when (exception.cause) {
+ is CameraControl.OperationCanceledException -> FocusOutcome.CANCELLED
+ else -> FocusOutcome.NOT_FOCUSED
+ }
+ }
+ }
+
+ private enum class FocusOutcome {
+ FOCUSED,
+ NOT_FOCUSED,
+ CANCELLED,
+ }
+
+ private data class Attachment(
+ val control: CameraControl,
+ val meteringPointFactory: MeteringPointFactory,
+ )
+
+ private data class ActiveRequest(
+ val id: Long,
+ val point: MeteringPoint,
+ val isLocked: Boolean,
+ )
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/session/ZoomControl.kt b/app/src/main/java/app/grapheneos/camera/data/camera/session/ZoomControl.kt
new file mode 100644
index 000000000..042a1ffcb
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/data/camera/session/ZoomControl.kt
@@ -0,0 +1,301 @@
+package app.grapheneos.camera.data.camera.session
+
+import androidx.camera.core.Camera
+import androidx.camera.core.CameraControl
+import androidx.camera.core.ZoomState
+import androidx.lifecycle.asFlow
+import app.grapheneos.camera.data.camera.mapper.CameraXStateMapper
+import app.grapheneos.camera.data.camera.model.CameraZoom
+import app.grapheneos.camera.data.camera.model.CameraZoomEvent
+import app.grapheneos.camera.data.camera.session.ZoomControl.Restoration
+import app.grapheneos.camera.data.core.model.LensFacing
+import app.grapheneos.camera.di.core.CameraSessionScope
+import app.grapheneos.camera.di.core.MainLooperDispatcher
+import javax.inject.Inject
+import kotlin.math.pow
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.milliseconds
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeoutOrNull
+
+interface ZoomControl {
+
+ val events: Flow
+
+ /** Null until the zoom state of the attached camera has been read; see [attach]. */
+ val zoom: CameraZoom?
+
+ val lensFacing: LensFacing?
+
+ /**
+ * The ratio last requested for a lens is applied again to the next camera attached for it,
+ * within that camera's range. [restoration] controls when to apply it. [Restoration.DISABLED]
+ * keeps the saved ratio untouched for a later binding.
+ */
+ fun attach(
+ camera: Camera,
+ lensFacing: LensFacing,
+ restoration: Restoration,
+ )
+
+ fun detach()
+
+ /**
+ * Applied within the camera's range once [zoom] has been read, when the camera attached is the
+ * one for [lensFacing]. Otherwise it waits for that camera; see [attach].
+ */
+ fun setZoomRatio(
+ zoomRatio: Float,
+ lensFacing: LensFacing,
+ )
+
+ /** For a ratio that [animateZoomRatio] is about to bring the camera to. */
+ fun rememberZoomRatio(
+ zoomRatio: Float,
+ lensFacing: LensFacing,
+ )
+
+ suspend fun animateZoomRatio(zoomRatio: Float)
+
+ fun stopZoomAnimation()
+
+ enum class Restoration {
+ BEFORE_PREVIEW,
+ WHEN_ZOOM_LOADS,
+ DISABLED,
+ }
+}
+
+internal class ZoomControlImpl @Inject constructor(
+ private val cameraXStateMapper: CameraXStateMapper,
+ @CameraSessionScope private val scope: CoroutineScope,
+ @MainLooperDispatcher private val mainLooperDispatcher: CoroutineDispatcher,
+) : ZoomControl {
+
+ private val _events = MutableSharedFlow(
+ extraBufferCapacity = CAMERA_EVENT_BUFFER_CAPACITY,
+ )
+ override val events: Flow = _events.asSharedFlow()
+
+ override var zoom: CameraZoom? = null
+ private set
+
+ override var lensFacing: LensFacing? = null
+ private set
+
+ private val rememberedRatios = mutableMapOf()
+ private var remembersZoom = false
+ private var pendingRatio: Float? = null
+ private var control: CameraControl? = null
+ private var trackJob: Job? = null
+ private var zoomAnimation: Job? = null
+
+ override fun attach(
+ camera: Camera,
+ lensFacing: LensFacing,
+ restoration: Restoration,
+ ) {
+ detach()
+ this.lensFacing = lensFacing
+ remembersZoom = restoration != Restoration.DISABLED
+ control = camera.cameraControl
+
+ if (restoration == Restoration.BEFORE_PREVIEW) {
+ restoreBeforePreview(
+ camera = camera,
+ lensFacing = lensFacing,
+ )
+ }
+
+ trackJob = scope.launch(mainLooperDispatcher) {
+ camera.cameraInfo.zoomState.asFlow().collect { state ->
+ onZoomState(state)
+ }
+ }
+ }
+
+ override fun detach() {
+ stopZoomAnimation()
+ trackJob?.cancel()
+ trackJob = null
+ pendingRatio = null
+ control = null
+ zoom = null
+ lensFacing = null
+ remembersZoom = false
+ }
+
+ override fun setZoomRatio(
+ zoomRatio: Float,
+ lensFacing: LensFacing,
+ ) {
+ if (!zoomRatio.isFinite() || zoomRatio <= 0f) return
+
+ val isAttached = lensFacing == this.lensFacing
+
+ if (!isAttached || remembersZoom) {
+ rememberedRatios[lensFacing] = zoomRatio
+ }
+
+ if (!isAttached) return
+
+ stopZoomAnimation()
+ val current = zoom
+ when {
+ current == null && !remembersZoom -> pendingRatio = zoomRatio
+ current?.isAdjustable() == true -> control?.setZoomRatio(current.clampRatio(zoomRatio))
+ }
+ }
+
+ override fun rememberZoomRatio(
+ zoomRatio: Float,
+ lensFacing: LensFacing,
+ ) {
+ if (zoomRatio.isFinite() && zoomRatio > 0f) {
+ rememberedRatios[lensFacing] = zoomRatio
+ }
+ }
+
+ override suspend fun animateZoomRatio(zoomRatio: Float) {
+ if (!zoomRatio.isFinite() || zoomRatio <= 0f) return
+
+ stopZoomAnimation()
+
+ val animation = scope.launch(mainLooperDispatcher) { animateTo(zoomRatio) }
+ zoomAnimation = animation
+ try {
+ animation.join()
+ } finally {
+ animation.cancel()
+ }
+ }
+
+ override fun stopZoomAnimation() {
+ zoomAnimation?.cancel()
+ zoomAnimation = null
+ }
+
+ private suspend fun animateTo(zoomRatio: Float) {
+ val state = zoom ?: return
+ val cameraControl = control ?: return
+ val target = state.clampRatio(zoomRatio)
+
+ rememberForAttachedLens(target)
+ interpolateZoom(
+ cameraControl = cameraControl,
+ start = state.zoomRatio,
+ target = target,
+ )
+
+ if (zoom?.zoomRatio != target) {
+ withTimeoutOrNull(ZOOM_CONFIRMATION_TIMEOUT) {
+ events.first { zoom?.zoomRatio == target }
+ }
+ }
+ }
+
+ private suspend fun interpolateZoom(
+ cameraControl: CameraControl,
+ start: Float,
+ target: Float,
+ ) {
+ if (start == target) return
+
+ var elapsed = Duration.ZERO
+ while (elapsed < ZOOM_ANIMATION_DURATION) {
+ val next = minOf(elapsed + ZOOM_FRAME_INTERVAL, ZOOM_ANIMATION_DURATION)
+ delay(next - elapsed)
+ val fraction = (next / ZOOM_ANIMATION_DURATION).toFloat()
+ val ratio = when (next) {
+ ZOOM_ANIMATION_DURATION -> target
+ else -> start * (target / start).pow(fraction)
+ }
+ cameraControl.setZoomRatio(ratio)
+ elapsed = next
+ }
+ }
+
+ private fun onZoomState(state: ZoomState) {
+ val previous = zoom
+ val reported = cameraXStateMapper.map(state)
+ val current = when (previous) {
+ null -> applyInitialRatio(
+ zoom = reported,
+ targetRatio = when {
+ remembersZoom -> rememberedRatios[lensFacing]
+ else -> pendingRatio
+ },
+ )
+ else -> reported
+ }
+ pendingRatio = null
+ zoom = current
+
+ val event = when {
+ previous == null -> CameraZoomEvent.Loaded
+ current != previous -> CameraZoomEvent.Changed
+ else -> null
+ }
+ event?.let(_events::tryEmit)
+ }
+
+ private fun rememberForAttachedLens(zoomRatio: Float) {
+ val attachedLens = lensFacing
+
+ if (attachedLens != null && remembersZoom) {
+ rememberZoomRatio(
+ zoomRatio = zoomRatio,
+ lensFacing = attachedLens,
+ )
+ }
+ }
+
+ private fun restoreBeforePreview(
+ camera: Camera,
+ lensFacing: LensFacing,
+ ) {
+ val ratio = rememberedRatios[lensFacing] ?: return
+ val state = camera.cameraInfo.zoomState.value ?: return
+
+ applyInitialRatio(
+ zoom = cameraXStateMapper.map(state),
+ targetRatio = ratio,
+ )
+ }
+
+ private fun applyInitialRatio(
+ zoom: CameraZoom,
+ targetRatio: Float?,
+ ): CameraZoom {
+ if (targetRatio == null || !zoom.isAdjustable()) return zoom
+
+ val target = zoom.clampRatio(targetRatio)
+ if (target != zoom.zoomRatio) {
+ control?.setZoomRatio(target)
+ }
+
+ return zoom.copy(zoomRatio = target)
+ }
+
+ private fun CameraZoom.clampRatio(zoomRatio: Float): Float {
+ return zoomRatio.coerceIn(
+ minimumValue = minZoomRatio,
+ maximumValue = maxZoomRatio,
+ )
+ }
+
+ private companion object {
+ private val ZOOM_ANIMATION_DURATION = 200.milliseconds
+ private val ZOOM_FRAME_INTERVAL = 16.milliseconds
+ private val ZOOM_CONFIRMATION_TIMEOUT = 1.seconds
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/data/camera/session/ZoomStateTracker.kt b/app/src/main/java/app/grapheneos/camera/data/camera/session/ZoomStateTracker.kt
deleted file mode 100644
index c59b426c1..000000000
--- a/app/src/main/java/app/grapheneos/camera/data/camera/session/ZoomStateTracker.kt
+++ /dev/null
@@ -1,72 +0,0 @@
-package app.grapheneos.camera.data.camera.session
-
-import androidx.camera.core.ZoomState
-import androidx.lifecycle.LifecycleOwner
-import androidx.lifecycle.LiveData
-import androidx.lifecycle.Observer
-import app.grapheneos.camera.data.camera.model.CameraZoomEvent
-import javax.inject.Inject
-
-interface ZoomStateTracker {
-
- /** Read instead of CameraInfo, which costs ~100 ms behind an extension. Null until [attach]. */
- val zoomState: ZoomState?
-
- fun attach(
- source: LiveData,
- lifecycleOwner: LifecycleOwner,
- onEvent: (CameraZoomEvent) -> Unit,
- )
-
- fun detach()
-}
-
-internal class ZoomStateTrackerImpl @Inject constructor() : ZoomStateTracker {
-
- override var zoomState: ZoomState? = null
- private set
-
- private var source: LiveData? = null
-
- private var isLoaded = false
-
- private var onEvent: (CameraZoomEvent) -> Unit = {}
-
- private val observer = Observer {
- val event = when {
- !isLoaded -> {
- CameraZoomEvent.Loaded
- }
-
- it.zoomRatio != zoomState?.zoomRatio || it.linearZoom != zoomState?.linearZoom -> {
- CameraZoomEvent.Changed
- }
-
- else -> null
- }
-
- zoomState = it
- isLoaded = true
-
- event?.let(onEvent)
- }
-
- override fun attach(
- source: LiveData,
- lifecycleOwner: LifecycleOwner,
- onEvent: (CameraZoomEvent) -> Unit,
- ) {
- this.onEvent = onEvent
- this.source = source
- source.observe(lifecycleOwner, observer)
-
- zoomState = source.value
- }
-
- override fun detach() {
- source?.removeObserver(observer)
- source = null
- zoomState = null
- isLoaded = false
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/data/orientation/model/DeviceMotion.kt b/app/src/main/java/app/grapheneos/camera/data/orientation/model/DeviceMotion.kt
index a7cde2bae..63e4004cf 100644
--- a/app/src/main/java/app/grapheneos/camera/data/orientation/model/DeviceMotion.kt
+++ b/app/src/main/java/app/grapheneos/camera/data/orientation/model/DeviceMotion.kt
@@ -4,6 +4,6 @@ import app.grapheneos.camera.data.core.model.DeviceOrientation
data class DeviceMotion(
val orientation: DeviceOrientation,
- val tiltDegrees: Int,
- val horizonDegrees: Int,
+ val tiltDegrees: Float,
+ val horizonDegrees: Float,
)
diff --git a/app/src/main/java/app/grapheneos/camera/data/orientation/repository/DeviceOrientationRepository.kt b/app/src/main/java/app/grapheneos/camera/data/orientation/repository/DeviceOrientationRepository.kt
index e926d364f..c4eb47f08 100644
--- a/app/src/main/java/app/grapheneos/camera/data/orientation/repository/DeviceOrientationRepository.kt
+++ b/app/src/main/java/app/grapheneos/camera/data/orientation/repository/DeviceOrientationRepository.kt
@@ -9,58 +9,88 @@ import android.hardware.SensorManager
import android.provider.Settings
import app.grapheneos.camera.data.core.model.DeviceOrientation
import app.grapheneos.camera.data.orientation.model.DeviceMotion
+import app.grapheneos.camera.di.core.ApplicationScope
import app.grapheneos.camera.di.core.IoDispatcher
import javax.inject.Inject
import kotlin.math.abs
-import kotlin.math.atan
-import kotlin.math.floor
+import kotlin.math.atan2
import kotlin.math.sqrt
+import kotlin.time.Duration
import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.WhileSubscribed
import kotlinx.coroutines.flow.callbackFlow
+import kotlinx.coroutines.flow.conflate
+import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.shareIn
interface DeviceOrientationRepository {
- fun motion(): Flow
+ val orientation: Flow
- fun autoRotateEnabled(): Flow
+ val motion: Flow
+
+ val autoRotateEnabled: Flow
}
internal class DeviceOrientationRepositoryImpl @Inject constructor(
private val sensorManager: SensorManager,
private val contentResolver: ContentResolver,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
+ @ApplicationScope applicationScope: CoroutineScope,
) : DeviceOrientationRepository {
- override fun motion(): Flow {
+ override val orientation: Flow = observeMotion(
+ samplingPeriod = SensorManager.SENSOR_DELAY_NORMAL,
+ )
+ .map { motion -> motion.orientation }
+ .distinctUntilChanged()
+ .shareIn(
+ scope = applicationScope,
+ started = SharingStarted.WhileSubscribed(replayExpiration = Duration.ZERO),
+ replay = 1,
+ )
+
+ override val motion: Flow = observeMotion(
+ samplingPeriod = SensorManager.SENSOR_DELAY_GAME,
+ )
+ .conflate()
+ .shareIn(
+ scope = applicationScope,
+ started = SharingStarted.WhileSubscribed(replayExpiration = Duration.ZERO),
+ replay = 1,
+ )
+
+ override val autoRotateEnabled: Flow = observeAutoRotate()
+ .flowOn(ioDispatcher)
+
+ private fun observeMotion(samplingPeriod: Int): Flow {
return callbackFlow {
- val gravity = FloatArray(size = 3)
- var orientation: DeviceOrientation? = null
+ var gravity: FloatArray? = null
+ var orientation = DeviceOrientation.DEGREES_0
+ val gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY)
+ val sensor = gravitySensor ?: sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
val listener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
- for (axis in gravity.indices) {
- gravity[axis] = smooth(
- previous = gravity[axis],
- reading = event.values[axis],
- )
+ val reading = event.values.copyOf(newSize = GRAVITY_AXES)
+ val previous = gravity
+ val current = when {
+ gravitySensor != null || previous == null -> reading
+ else -> smooth(previous = previous, reading = reading)
}
-
+ gravity = current
orientation = orientationOf(
- gravityX = gravity[0],
- gravityY = gravity[1],
+ gravityX = current[0],
+ gravityY = current[1],
) ?: orientation
- orientation?.let { current ->
- val deviceMotion = motionOf(
- gravity = gravity,
- orientation = current,
- )
-
- trySend(deviceMotion)
- }
+ trySend(motionOf(gravity = current, orientation = orientation))
}
@Suppress("EmptyFunctionBlock")
@@ -69,8 +99,8 @@ internal class DeviceOrientationRepositoryImpl @Inject constructor(
sensorManager.registerListener(
listener,
- sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
- SensorManager.SENSOR_DELAY_NORMAL,
+ sensor,
+ samplingPeriod,
)
awaitClose {
@@ -79,7 +109,7 @@ internal class DeviceOrientationRepositoryImpl @Inject constructor(
}
}
- override fun autoRotateEnabled(): Flow {
+ private fun observeAutoRotate(): Flow {
return callbackFlow {
val observer = object : ContentObserver(null) {
override fun onChange(selfChange: Boolean) {
@@ -97,14 +127,16 @@ internal class DeviceOrientationRepositoryImpl @Inject constructor(
awaitClose {
contentResolver.unregisterContentObserver(observer)
}
- }.flowOn(ioDispatcher)
+ }
}
private fun smooth(
- previous: Float,
- reading: Float,
- ): Float {
- return previous + (reading - previous) * READING_WEIGHT
+ previous: FloatArray,
+ reading: FloatArray,
+ ): FloatArray {
+ return FloatArray(size = reading.size) { axis ->
+ previous[axis] + (reading[axis] - previous[axis]) * READING_WEIGHT
+ }
}
private fun orientationOf(
@@ -131,28 +163,39 @@ internal class DeviceOrientationRepositoryImpl @Inject constructor(
orientation == DeviceOrientation.DEGREES_270
val isUpsideDown = orientation == DeviceOrientation.DEGREES_180 ||
orientation == DeviceOrientation.DEGREES_270
+ val isVerticalAxisReversed = orientation == DeviceOrientation.DEGREES_90 ||
+ orientation == DeviceOrientation.DEGREES_180
- val (across, along) = when {
- isSideways -> gravity[1] to gravity[0]
- else -> gravity[0] to gravity[1]
+ val across = when {
+ isSideways -> gravity[1]
+ else -> gravity[0]
+ }
+ val along = when {
+ isSideways -> gravity[0]
+ else -> gravity[1]
}
val depth = gravity[2]
- val tilt = floorDegrees(atan(across / sqrt(along * along + depth * depth)))
- val horizon = floorDegrees(atan(depth / sqrt(along * along + across * across)))
+ val horizontal = when {
+ isUpsideDown -> -across
+ else -> across
+ }
+ val vertical = when {
+ isVerticalAxisReversed -> -along
+ else -> along
+ }
+ val tilt = degrees(atan2(horizontal, vertical))
+ val horizon = degrees(atan2(depth, sqrt(along * along + across * across)))
return DeviceMotion(
orientation = orientation,
- tiltDegrees = when {
- isUpsideDown -> -tilt
- else -> tilt
- },
+ tiltDegrees = tilt,
horizonDegrees = horizon,
)
}
- private fun floorDegrees(radians: Float): Int {
- return floor(Math.toDegrees(radians.toDouble())).toInt()
+ private fun degrees(radians: Float): Float {
+ return Math.toDegrees(radians.toDouble()).toFloat()
}
private fun isAutoRotateEnabled(): Boolean {
@@ -164,6 +207,7 @@ internal class DeviceOrientationRepositoryImpl @Inject constructor(
}
private companion object {
+ private const val GRAVITY_AXES = 3
private const val READING_WEIGHT = 0.3f
private const val TILT_THRESHOLD = 5f
}
diff --git a/app/src/main/java/app/grapheneos/camera/di/camera/CameraBindsModule.kt b/app/src/main/java/app/grapheneos/camera/di/camera/CameraBindsModule.kt
index d17410d81..2ec5b5235 100644
--- a/app/src/main/java/app/grapheneos/camera/di/camera/CameraBindsModule.kt
+++ b/app/src/main/java/app/grapheneos/camera/di/camera/CameraBindsModule.kt
@@ -1,5 +1,7 @@
package app.grapheneos.camera.di.camera
+import app.grapheneos.camera.data.camera.mapper.CameraFlashMapper
+import app.grapheneos.camera.data.camera.mapper.CameraFlashMapperImpl
import app.grapheneos.camera.data.camera.mapper.CameraXConstantsMapper
import app.grapheneos.camera.data.camera.mapper.CameraXConstantsMapperImpl
import app.grapheneos.camera.data.camera.mapper.CameraXStateMapper
@@ -8,6 +10,8 @@ import app.grapheneos.camera.data.camera.mapper.RecordingEventMapper
import app.grapheneos.camera.data.camera.mapper.RecordingEventMapperImpl
import app.grapheneos.camera.data.camera.mapper.VideoQualityFeatureMapper
import app.grapheneos.camera.data.camera.mapper.VideoQualityFeatureMapperImpl
+import app.grapheneos.camera.data.camera.mapper.VideoQualityMapper
+import app.grapheneos.camera.data.camera.mapper.VideoQualityMapperImpl
import app.grapheneos.camera.data.camera.repository.CameraProviderSource
import app.grapheneos.camera.data.camera.repository.CameraProviderSourceImpl
import app.grapheneos.camera.data.camera.repository.ExtensionAvailabilityRepository
@@ -40,6 +44,8 @@ import app.grapheneos.camera.data.camera.session.VideoBitrateSupport
import app.grapheneos.camera.data.camera.session.VideoBitrateSupportImpl
import app.grapheneos.camera.data.camera.session.VideoQualitySupport
import app.grapheneos.camera.data.camera.session.VideoQualitySupportImpl
+import app.grapheneos.camera.domain.camera.mapper.ZoomPresetsMapper
+import app.grapheneos.camera.domain.camera.mapper.ZoomPresetsMapperImpl
import app.grapheneos.camera.domain.camera.usecase.ResolveAvailableModes
import app.grapheneos.camera.domain.camera.usecase.ResolveAvailableModesImpl
import dagger.Binds
@@ -95,6 +101,18 @@ internal abstract class CameraBindsModule {
impl: CameraFeatureSupportImpl,
): CameraFeatureSupport
+ @Binds
+ @Reusable
+ abstract fun bindCameraFlashMapper(
+ impl: CameraFlashMapperImpl,
+ ): CameraFlashMapper
+
+ @Binds
+ @Reusable
+ abstract fun bindVideoQualityMapper(
+ impl: VideoQualityMapperImpl,
+ ): VideoQualityMapper
+
@Binds
@Reusable
abstract fun bindCameraXConstantsMapper(
@@ -119,6 +137,12 @@ internal abstract class CameraBindsModule {
impl: VideoQualityFeatureMapperImpl,
): VideoQualityFeatureMapper
+ @Binds
+ @Reusable
+ abstract fun bindZoomPresetsMapper(
+ impl: ZoomPresetsMapperImpl,
+ ): ZoomPresetsMapper
+
@Binds
@Reusable
abstract fun bindCameraSessionPlanFactory(
diff --git a/app/src/main/java/app/grapheneos/camera/di/camera/CameraSessionBindsModule.kt b/app/src/main/java/app/grapheneos/camera/di/camera/CameraSessionBindsModule.kt
index 427aa0e6b..154455017 100644
--- a/app/src/main/java/app/grapheneos/camera/di/camera/CameraSessionBindsModule.kt
+++ b/app/src/main/java/app/grapheneos/camera/di/camera/CameraSessionBindsModule.kt
@@ -2,14 +2,18 @@ package app.grapheneos.camera.di.camera
import app.grapheneos.camera.data.camera.session.CameraSession
import app.grapheneos.camera.data.camera.session.CameraSessionImpl
+import app.grapheneos.camera.data.camera.session.ExposureControl
+import app.grapheneos.camera.data.camera.session.ExposureControlImpl
import app.grapheneos.camera.data.camera.session.ExtensionUsability
import app.grapheneos.camera.data.camera.session.ExtensionUsabilityImpl
+import app.grapheneos.camera.data.camera.session.FocusControl
+import app.grapheneos.camera.data.camera.session.FocusControlImpl
import app.grapheneos.camera.data.camera.session.SceneLightControl
import app.grapheneos.camera.data.camera.session.SceneLightControlImpl
import app.grapheneos.camera.data.camera.session.VideoRecordingSession
import app.grapheneos.camera.data.camera.session.VideoRecordingSessionImpl
-import app.grapheneos.camera.data.camera.session.ZoomStateTracker
-import app.grapheneos.camera.data.camera.session.ZoomStateTrackerImpl
+import app.grapheneos.camera.data.camera.session.ZoomControl
+import app.grapheneos.camera.data.camera.session.ZoomControlImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
@@ -26,12 +30,24 @@ internal abstract class CameraSessionBindsModule {
impl: CameraSessionImpl,
): CameraSession
+ @Binds
+ @ActivityRetainedScoped
+ abstract fun bindExposureControl(
+ impl: ExposureControlImpl,
+ ): ExposureControl
+
@Binds
@ActivityRetainedScoped
abstract fun bindExtensionUsability(
impl: ExtensionUsabilityImpl,
): ExtensionUsability
+ @Binds
+ @ActivityRetainedScoped
+ abstract fun bindFocusControl(
+ impl: FocusControlImpl,
+ ): FocusControl
+
@Binds
@ActivityRetainedScoped
abstract fun bindSceneLightControl(
@@ -46,7 +62,7 @@ internal abstract class CameraSessionBindsModule {
@Binds
@ActivityRetainedScoped
- abstract fun bindZoomStateTracker(
- impl: ZoomStateTrackerImpl,
- ): ZoomStateTracker
+ abstract fun bindZoomControl(
+ impl: ZoomControlImpl,
+ ): ZoomControl
}
diff --git a/app/src/main/java/app/grapheneos/camera/di/core/SystemServicesProvidesModule.kt b/app/src/main/java/app/grapheneos/camera/di/core/SystemServicesProvidesModule.kt
index 3c6b51fc5..9657fe344 100644
--- a/app/src/main/java/app/grapheneos/camera/di/core/SystemServicesProvidesModule.kt
+++ b/app/src/main/java/app/grapheneos/camera/di/core/SystemServicesProvidesModule.kt
@@ -11,9 +11,6 @@ import android.content.res.Resources
import android.hardware.SensorManager
import android.hardware.camera2.CameraManager
import android.location.LocationManager
-import android.os.Build
-import android.os.Vibrator
-import android.os.VibratorManager
import app.grapheneos.camera.data.core.notification.NotificationBuilderFactory
import dagger.Module
import dagger.Provides
@@ -107,20 +104,4 @@ internal class SystemServicesProvidesModule {
Notification.Builder(context, channelId)
}
}
-
- @Provides
- @Reusable
- fun provideVibrator(
- @ApplicationContext context: Context,
- ): Vibrator {
- return when {
- Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
- context.getSystemService(VibratorManager::class.java).defaultVibrator
- }
-
- else -> {
- context.getSystemService(Vibrator::class.java)
- }
- }
- }
}
diff --git a/app/src/main/java/app/grapheneos/camera/di/orientation/OrientationBindsModule.kt b/app/src/main/java/app/grapheneos/camera/di/orientation/OrientationBindsModule.kt
index 35008f06f..6a413b430 100644
--- a/app/src/main/java/app/grapheneos/camera/di/orientation/OrientationBindsModule.kt
+++ b/app/src/main/java/app/grapheneos/camera/di/orientation/OrientationBindsModule.kt
@@ -4,16 +4,16 @@ import app.grapheneos.camera.data.orientation.repository.DeviceOrientationReposi
import app.grapheneos.camera.data.orientation.repository.DeviceOrientationRepositoryImpl
import dagger.Binds
import dagger.Module
-import dagger.Reusable
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
+import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal abstract class OrientationBindsModule {
@Binds
- @Reusable
+ @Singleton
abstract fun bindDeviceOrientationRepository(
impl: DeviceOrientationRepositoryImpl,
): DeviceOrientationRepository
diff --git a/app/src/main/java/app/grapheneos/camera/di/previewoverlays/PreviewOverlaysBindsModule.kt b/app/src/main/java/app/grapheneos/camera/di/previewoverlays/PreviewOverlaysBindsModule.kt
new file mode 100644
index 000000000..2412b2122
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/di/previewoverlays/PreviewOverlaysBindsModule.kt
@@ -0,0 +1,28 @@
+package app.grapheneos.camera.di.previewoverlays
+
+import app.grapheneos.camera.ui.previewoverlays.screen.mapper.LevelStateMapper
+import app.grapheneos.camera.ui.previewoverlays.screen.mapper.LevelStateMapperImpl
+import app.grapheneos.camera.ui.previewoverlays.screen.mapper.PreviewOverlaysUiStateMapper
+import app.grapheneos.camera.ui.previewoverlays.screen.mapper.PreviewOverlaysUiStateMapperImpl
+import dagger.Binds
+import dagger.Module
+import dagger.Reusable
+import dagger.hilt.InstallIn
+import dagger.hilt.components.SingletonComponent
+
+@Module
+@InstallIn(SingletonComponent::class)
+internal abstract class PreviewOverlaysBindsModule {
+
+ @Binds
+ @Reusable
+ abstract fun bindLevelStateMapper(
+ impl: LevelStateMapperImpl,
+ ): LevelStateMapper
+
+ @Binds
+ @Reusable
+ abstract fun bindPreviewOverlaysUiStateMapper(
+ impl: PreviewOverlaysUiStateMapperImpl,
+ ): PreviewOverlaysUiStateMapper
+}
diff --git a/app/src/main/java/app/grapheneos/camera/di/previewoverlays/PreviewOverlaysViewModelBindsModule.kt b/app/src/main/java/app/grapheneos/camera/di/previewoverlays/PreviewOverlaysViewModelBindsModule.kt
new file mode 100644
index 000000000..fc7878e9c
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/di/previewoverlays/PreviewOverlaysViewModelBindsModule.kt
@@ -0,0 +1,44 @@
+package app.grapheneos.camera.di.previewoverlays
+
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.ExposureDelegate
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.ExposureDelegateImpl
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.FocusDelegate
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.FocusDelegateImpl
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.LevelDelegate
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.LevelDelegateImpl
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.ZoomDelegate
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.ZoomDelegateImpl
+import dagger.Binds
+import dagger.Module
+import dagger.hilt.InstallIn
+import dagger.hilt.android.components.ViewModelComponent
+import dagger.hilt.android.scopes.ViewModelScoped
+
+@Module
+@InstallIn(ViewModelComponent::class)
+internal abstract class PreviewOverlaysViewModelBindsModule {
+
+ @Binds
+ @ViewModelScoped
+ abstract fun bindFocusDelegate(
+ impl: FocusDelegateImpl,
+ ): FocusDelegate
+
+ @Binds
+ @ViewModelScoped
+ abstract fun bindLevelDelegate(
+ impl: LevelDelegateImpl,
+ ): LevelDelegate
+
+ @Binds
+ @ViewModelScoped
+ abstract fun bindZoomDelegate(
+ impl: ZoomDelegateImpl,
+ ): ZoomDelegate
+
+ @Binds
+ @ViewModelScoped
+ abstract fun bindExposureDelegate(
+ impl: ExposureDelegateImpl,
+ ): ExposureDelegate
+}
diff --git a/app/src/main/java/app/grapheneos/camera/di/viewfinder/ViewfinderBindsModule.kt b/app/src/main/java/app/grapheneos/camera/di/viewfinder/ViewfinderBindsModule.kt
index f75c390b2..42af100c9 100644
--- a/app/src/main/java/app/grapheneos/camera/di/viewfinder/ViewfinderBindsModule.kt
+++ b/app/src/main/java/app/grapheneos/camera/di/viewfinder/ViewfinderBindsModule.kt
@@ -2,16 +2,10 @@ package app.grapheneos.camera.di.viewfinder
import app.grapheneos.camera.ui.viewfinder.screen.mapper.CameraBindSettingsMapper
import app.grapheneos.camera.ui.viewfinder.screen.mapper.CameraBindSettingsMapperImpl
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.NextZoomStopMapper
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.NextZoomStopMapperImpl
import app.grapheneos.camera.ui.viewfinder.screen.mapper.SwipeOutcomeMapper
import app.grapheneos.camera.ui.viewfinder.screen.mapper.SwipeOutcomeMapperImpl
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.ViewfinderLevelStateMapper
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.ViewfinderLevelStateMapperImpl
import app.grapheneos.camera.ui.viewfinder.screen.mapper.ViewfinderUiStateMapper
import app.grapheneos.camera.ui.viewfinder.screen.mapper.ViewfinderUiStateMapperImpl
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.VolumeKeyActionMapper
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.VolumeKeyActionMapperImpl
import dagger.Binds
import dagger.Module
import dagger.Reusable
@@ -34,27 +28,9 @@ internal abstract class ViewfinderBindsModule {
impl: CameraBindSettingsMapperImpl,
): CameraBindSettingsMapper
- @Binds
- @Reusable
- abstract fun bindViewfinderLevelStateMapper(
- impl: ViewfinderLevelStateMapperImpl,
- ): ViewfinderLevelStateMapper
-
@Binds
@Reusable
abstract fun bindSwipeOutcomeMapper(
impl: SwipeOutcomeMapperImpl,
): SwipeOutcomeMapper
-
- @Binds
- @Reusable
- abstract fun bindVolumeKeyActionMapper(
- impl: VolumeKeyActionMapperImpl,
- ): VolumeKeyActionMapper
-
- @Binds
- @Reusable
- abstract fun bindNextZoomStopMapper(
- impl: NextZoomStopMapperImpl,
- ): NextZoomStopMapper
}
diff --git a/app/src/main/java/app/grapheneos/camera/di/viewfinder/ViewfinderViewModelBindsModule.kt b/app/src/main/java/app/grapheneos/camera/di/viewfinder/ViewfinderViewModelBindsModule.kt
index edc0891e8..36003922b 100644
--- a/app/src/main/java/app/grapheneos/camera/di/viewfinder/ViewfinderViewModelBindsModule.kt
+++ b/app/src/main/java/app/grapheneos/camera/di/viewfinder/ViewfinderViewModelBindsModule.kt
@@ -1,7 +1,5 @@
package app.grapheneos.camera.di.viewfinder
-import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderCameraControlsDelegate
-import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderCameraControlsDelegateImpl
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderCameraDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderCameraDelegateImpl
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderCaptureDelegate
@@ -20,8 +18,6 @@ import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderOrientation
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderOrientationDelegateImpl
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderPermissionDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderPermissionDelegateImpl
-import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderPreviewControlsDelegate
-import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderPreviewControlsDelegateImpl
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderRecordingDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderRecordingDelegateImpl
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderScreenWakeDelegate
@@ -92,18 +88,6 @@ internal abstract class ViewfinderViewModelBindsModule {
impl: ViewfinderOrientationDelegateImpl,
): ViewfinderOrientationDelegate
- @Binds
- @ViewModelScoped
- abstract fun bindViewfinderCameraControlsDelegate(
- impl: ViewfinderCameraControlsDelegateImpl,
- ): ViewfinderCameraControlsDelegate
-
- @Binds
- @ViewModelScoped
- abstract fun bindViewfinderPreviewControlsDelegate(
- impl: ViewfinderPreviewControlsDelegateImpl,
- ): ViewfinderPreviewControlsDelegate
-
@Binds
@ViewModelScoped
abstract fun bindViewfinderScreenWakeDelegate(
diff --git a/app/src/main/java/app/grapheneos/camera/domain/camera/mapper/ZoomPresetsMapper.kt b/app/src/main/java/app/grapheneos/camera/domain/camera/mapper/ZoomPresetsMapper.kt
new file mode 100644
index 000000000..28748c51f
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/domain/camera/mapper/ZoomPresetsMapper.kt
@@ -0,0 +1,34 @@
+package app.grapheneos.camera.domain.camera.mapper
+
+import app.grapheneos.camera.data.camera.model.CameraZoom
+import app.grapheneos.camera.data.core.model.LensFacing
+import javax.inject.Inject
+
+internal interface ZoomPresetsMapper {
+
+ fun map(
+ zoom: CameraZoom,
+ lensFacing: LensFacing,
+ ): List
+}
+
+internal class ZoomPresetsMapperImpl @Inject constructor() : ZoomPresetsMapper {
+
+ override fun map(
+ zoom: CameraZoom,
+ lensFacing: LensFacing,
+ ): List {
+ val presets = when (lensFacing) {
+ LensFacing.FRONT -> STANDARD_PRESETS
+ LensFacing.BACK -> listOf(zoom.minZoomRatio) + STANDARD_PRESETS
+ }
+ return presets
+ .filter { it in zoom.minZoomRatio..zoom.maxZoomRatio }
+ .distinct()
+ .ifEmpty { listOf(zoom.minZoomRatio) }
+ }
+
+ private companion object {
+ private val STANDARD_PRESETS = listOf(1f, 2f)
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/domain/capture/usecase/CaptureImage.kt b/app/src/main/java/app/grapheneos/camera/domain/capture/usecase/CaptureImage.kt
index aca72c715..b67d8d440 100644
--- a/app/src/main/java/app/grapheneos/camera/domain/capture/usecase/CaptureImage.kt
+++ b/app/src/main/java/app/grapheneos/camera/domain/capture/usecase/CaptureImage.kt
@@ -1,6 +1,7 @@
package app.grapheneos.camera.domain.capture.usecase
import android.location.Location
+import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.takePicture
import app.grapheneos.camera.data.camera.session.CameraSession
@@ -32,7 +33,16 @@ internal class CaptureImageImpl @Inject constructor(
needsThumbnail: () -> Boolean,
onEvent: (CapturedImageEvent) -> Unit,
) {
- val imageCapture = cameraSession.imageCapture ?: return
+ val imageCapture = cameraSession.imageCapture
+ if (imageCapture == null) {
+ val notBound = ImageCaptureException(
+ ImageCapture.ERROR_INVALID_CAMERA,
+ NOT_BOUND_MESSAGE,
+ null,
+ )
+ onEvent(captureFailed(notBound))
+ return
+ }
val reversedHorizontal = cameraSession.lensFacing == LensFacing.FRONT &&
request.saveAsPreviewed
@@ -52,17 +62,20 @@ internal class CaptureImageImpl @Inject constructor(
val image = try {
imageCapture.takePicture()
} catch (exception: ImageCaptureException) {
- val failure = CapturedImageEvent.CaptureFailed(
- errorCode = exception.imageCaptureError,
- cause = exception,
- )
- onEvent(failure)
+ onEvent(captureFailed(exception))
return
}
imageSaver.onCaptureSuccess(image)
}
+ private fun captureFailed(exception: ImageCaptureException): CapturedImageEvent {
+ return CapturedImageEvent.CaptureFailed(
+ errorCode = exception.imageCaptureError,
+ cause = exception,
+ )
+ }
+
private suspend fun location(
request: CaptureImageRequest,
onEvent: (CapturedImageEvent) -> Unit,
@@ -77,4 +90,8 @@ internal class CaptureImageImpl @Inject constructor(
}
}
}
+
+ private companion object {
+ private const val NOT_BOUND_MESSAGE = "No image capture is bound"
+ }
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/activities/MainActivity.kt b/app/src/main/java/app/grapheneos/camera/ui/activities/MainActivity.kt
index bb08a1af2..8d3f5434f 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/activities/MainActivity.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/activities/MainActivity.kt
@@ -6,15 +6,13 @@ import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.os.Bundle
-import android.os.Vibrator
import android.view.GestureDetector
import android.view.KeyEvent
import android.view.MotionEvent
+import android.view.Surface
import android.view.View
import android.view.ViewGroup
-import android.widget.FrameLayout
import android.widget.ImageView
-import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
@@ -31,6 +29,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.unit.Density
+import androidx.compose.ui.unit.DpRect
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
@@ -42,6 +41,8 @@ import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.MutableCreationExtras
import app.grapheneos.camera.R
import app.grapheneos.camera.data.camera.model.PreviewTarget
+import app.grapheneos.camera.data.camera.session.ZoomControl
+import app.grapheneos.camera.data.core.model.DeviceOrientation
import app.grapheneos.camera.data.settings.repository.SettingsRepository
import app.grapheneos.camera.data.sound.player.CameraSoundPlayer
import app.grapheneos.camera.databinding.ActivityMainBinding
@@ -55,6 +56,7 @@ import app.grapheneos.camera.ui.camerascreen.CameraScreenNavigationHandlerImpl
import app.grapheneos.camera.ui.camerascreen.HiddenStatusBar
import app.grapheneos.camera.ui.camerasettings.navigation.CameraSettingsIntents
import app.grapheneos.camera.ui.common.TunePlayer
+import app.grapheneos.camera.ui.components.focusindicator.FOCUS_INDICATOR_SIZE
import app.grapheneos.camera.ui.core.gesture.MIN_FLING_DISTANCE
import app.grapheneos.camera.ui.core.gesture.SETTLE_VELOCITY
import app.grapheneos.camera.ui.core.theme.CameraTheme
@@ -62,6 +64,12 @@ import app.grapheneos.camera.ui.gallery.navigation.GalleryIntents
import app.grapheneos.camera.ui.mediaactions.CapturedItemIntents
import app.grapheneos.camera.ui.navigation.Navigator
import app.grapheneos.camera.ui.navigation.NavigatorImpl
+import app.grapheneos.camera.ui.previewoverlays.screen.PreviewOverlaysViewModel
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.FocusAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.PreviewAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.ZoomAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.input.ZoomDirection
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewContentState
import app.grapheneos.camera.ui.quicksettings.components.QuickSettingsSheetState
import app.grapheneos.camera.ui.quicksettings.navigation.QuickSettingsNavigator
import app.grapheneos.camera.ui.quicksettings.navigation.QuickSettingsNavigatorImpl
@@ -70,15 +78,13 @@ import app.grapheneos.camera.ui.statusbar.screen.StatusBarViewModel
import app.grapheneos.camera.ui.videoplayer.navigation.VideoPlayerLauncher
import app.grapheneos.camera.ui.viewfinder.components.BottomTabLayout
import app.grapheneos.camera.ui.viewfinder.components.CaptureButton
-import app.grapheneos.camera.ui.viewfinder.components.CountDownTimerUI
-import app.grapheneos.camera.ui.viewfinder.components.CustomGrid
-import app.grapheneos.camera.ui.viewfinder.components.ExposureBar
-import app.grapheneos.camera.ui.viewfinder.components.ZoomBar
import app.grapheneos.camera.ui.viewfinder.components.qr.QROverlay
import app.grapheneos.camera.ui.viewfinder.components.qr.QRToggle
import app.grapheneos.camera.ui.viewfinder.components.qr.showMoreQrFormatOptions
+import app.grapheneos.camera.ui.viewfinder.screen.PreviewFocusCallbacks
import app.grapheneos.camera.ui.viewfinder.screen.PreviewFrameHolder
import app.grapheneos.camera.ui.viewfinder.screen.PreviewFrameHolderImpl
+import app.grapheneos.camera.ui.viewfinder.screen.PreviewZoomCallbacks
import app.grapheneos.camera.ui.viewfinder.screen.SettingsPanelDragCallbacks
import app.grapheneos.camera.ui.viewfinder.screen.ViewfinderEffectHandler
import app.grapheneos.camera.ui.viewfinder.screen.ViewfinderEffectHandlerImpl
@@ -91,6 +97,7 @@ import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.Capture
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.LifecycleAction
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.RecordingAction
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.SettingsAction
+import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderUiState
import app.grapheneos.camera.ui.viewfinder.screen.model.input.ThumbnailSize
import app.grapheneos.camera.ui.viewfinder.screen.model.input.VolumeKey
import com.google.android.material.imageview.ShapeableImageView
@@ -116,9 +123,6 @@ open class MainActivity : AppCompatActivity() {
@Inject
lateinit var cameraSoundPlayer: CameraSoundPlayer
- @Inject
- lateinit var vibrator: Vibrator
-
@Inject
internal lateinit var capturedItemIntents: CapturedItemIntents
@@ -131,6 +135,9 @@ open class MainActivity : AppCompatActivity() {
@Inject
internal lateinit var videoPlayerLauncher: VideoPlayerLauncher
+ @Inject
+ internal lateinit var zoomControl: ZoomControl
+
internal lateinit var binding: ActivityMainBinding
val viewfinder: ViewfinderViewModel by viewModels(
@@ -145,10 +152,37 @@ open class MainActivity : AppCompatActivity() {
extrasProducer = { cameraEntryPointCreationExtras() },
)
+ internal val previewOverlays: PreviewOverlaysViewModel by viewModels(
+ extrasProducer = { cameraEntryPointCreationExtras() },
+ )
+
+ private val focusHitRadius by lazy {
+ Density(context = this).run { FOCUS_INDICATOR_SIZE.toPx() / 2 }
+ }
+
internal val gestureHandler by lazy {
ViewfinderGestureHandler(
context = this,
onAction = viewfinder::onAction,
+ previewFocus = PreviewFocusCallbacks(
+ onPressed = { x, y ->
+ previewOverlays.onAction(
+ FocusAction.PreviewPressed(x = x, y = y, hitRadius = focusHitRadius),
+ )
+ },
+ onTapped = { previewOverlays.onAction(FocusAction.PreviewTapped) },
+ onLongPressed = { previewOverlays.onAction(FocusAction.PreviewLongPressed) },
+ onGestureStarted = {
+ previewOverlays.onAction(FocusAction.PreviewGestureStarted)
+ },
+ ),
+ previewZoom = PreviewZoomCallbacks(
+ onPinchStarted = { previewOverlays.onAction(ZoomAction.PreviewPinchStarted) },
+ onPinchScaleChanged = { scaleFactor ->
+ previewOverlays.onAction(ZoomAction.PreviewPinchScaleChanged(scaleFactor))
+ },
+ onPinchFinished = { previewOverlays.onAction(ZoomAction.PreviewPinchFinished) },
+ ),
settingsPanelDrag = SettingsPanelDragCallbacks(
isShown = { !quickSettingsSheet.isHidden },
onDragStarted = quickSettingsSheet::startDrag,
@@ -217,39 +251,18 @@ open class MainActivity : AppCompatActivity() {
val previewLoader: ProgressBar
get() = binding.previewLoading
- val zoomBar: ZoomBar
- get() = binding.zoomBar
-
- val zoomBarPanel: LinearLayout
- get() = binding.zoomBarPanel
-
- val exposureBar: ExposureBar
- get() = binding.exposureBar
-
- val exposureBarPanel: LinearLayout
- get() = binding.exposureBarPanel
-
val qrOverlay: QROverlay
get() = binding.qrOverlay
val mainOverlay: ImageView
get() = binding.mainOverlay
- val previewGrid: CustomGrid
- get() = binding.previewGrid
-
- val cdTimer: CountDownTimerUI
- get() = binding.cTimer
-
val cbText: TextView
get() = binding.captureButtonText
val cbCross: ImageView
get() = binding.captureButtonCross
- val gCircleFrame: FrameLayout
- get() = binding.gCircleFrame
-
val muteToggle: ShapeableImageView
get() = binding.muteToggle
@@ -326,13 +339,13 @@ open class MainActivity : AppCompatActivity() {
viewfinder.onAction(CaptureAction.CaptureKeyPressed)
}
KeyEvent.KEYCODE_FOCUS -> {
- viewfinder.onAction(CameraAction.FocusKeyPressed)
+ previewOverlays.onAction(FocusAction.FocusKeyPressed)
}
KeyEvent.KEYCODE_ZOOM_IN -> {
- viewfinder.onAction(CameraAction.ZoomInKeyPressed)
+ previewOverlays.onAction(ZoomAction.ZoomKeyPressed(ZoomDirection.IN))
}
KeyEvent.KEYCODE_ZOOM_OUT -> {
- viewfinder.onAction(CameraAction.ZoomOutKeyPressed)
+ previewOverlays.onAction(ZoomAction.ZoomKeyPressed(ZoomDirection.OUT))
}
}
return super.onKeyUp(keyCode, event)
@@ -348,6 +361,7 @@ open class MainActivity : AppCompatActivity() {
if (event?.repeatCount == 0) {
viewfinder.onAction(CaptureAction.VolumeKeyEvent.Pressed(volumeKey))
+ previewOverlays.onAction(ZoomAction.VolumeKeyPressed(zoomDirectionOf(volumeKey)))
}
return true
}
@@ -357,6 +371,14 @@ open class MainActivity : AppCompatActivity() {
tabLayout.settleNow()
viewfinder.onAction(CaptureAction.VolumeKeyEvent.Released(key))
+ previewOverlays.onAction(ZoomAction.VolumeKeyReleased)
+ }
+
+ private fun zoomDirectionOf(key: VolumeKey): ZoomDirection {
+ return when (key) {
+ VolumeKey.UP -> ZoomDirection.IN
+ VolumeKey.DOWN -> ZoomDirection.OUT
+ }
}
private fun volumeKeyOf(keyCode: Int): VolumeKey? {
@@ -413,9 +435,13 @@ open class MainActivity : AppCompatActivity() {
)
val effectHandler: ViewfinderEffectHandler = ViewfinderEffectHandlerImpl(
activity = this,
- vibrator = vibrator,
capturedItemIntents = capturedItemIntents,
onAction = viewfinder::onAction,
+ onPreviewFlashVisibilityChanged = { visible ->
+ previewOverlays.onAction(
+ PreviewAction.PreviewFlashVisibilityChanged(visible = visible),
+ )
+ },
)
viewfinder.onAction(
LifecycleAction.ScreenCreated(
@@ -434,13 +460,16 @@ open class MainActivity : AppCompatActivity() {
),
)
- viewfinder.onAction(CameraAction.DisplayRotationChanged(rotation = displayRotation()))
+ updateDisplayRotation()
tunePlayer = TunePlayer(cameraSoundPlayer = cameraSoundPlayer)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewfinder.uiState.collect { state ->
+ previewOverlays.onAction(
+ PreviewAction.PreviewContentChanged(content = previewContentOf(state)),
+ )
renderer.render(state)
}
}
@@ -453,16 +482,8 @@ open class MainActivity : AppCompatActivity() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
- viewfinder.zoomUiState.collect { zoom ->
- renderer.renderZoom(zoom)
- }
- }
- }
-
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- viewfinder.levelUiState.collect { level ->
- renderer.renderLevel(level)
+ zoomControl.events.collect {
+ previewFrames.discardPrefetch()
}
}
}
@@ -479,6 +500,7 @@ open class MainActivity : AppCompatActivity() {
CameraTheme {
CameraOverlay(
viewfinder = viewfinder,
+ previewOverlays = previewOverlays,
statusBar = statusBar,
quickSettings = quickSettings,
sheetState = quickSettingsSheet,
@@ -572,15 +594,6 @@ open class MainActivity : AppCompatActivity() {
viewfinder.onAction(CaptureAction.CaptureButtonClicked)
}
- zoomBar.onLinearZoomDragged = { linearZoom ->
- viewfinder.onAction(CameraAction.ZoomSliderDragged(linearZoom = linearZoom))
- }
- exposureBar.onCompensationDragged = { compensationIndex ->
- viewfinder.onAction(
- CameraAction.ExposureSliderDragged(compensationIndex = compensationIndex),
- )
- }
-
setContentView(binding.getRoot())
var isInsetSet = false
@@ -609,8 +622,6 @@ open class MainActivity : AppCompatActivity() {
it
}
- zoomBarPanel.setPadding(0, 0, 0, insets.bottom)
- exposureBarPanel.setPadding(0, 0, 0, insets.bottom)
binding.bottomRow.updateLayoutParams {
bottomMargin = insets.bottom +
resources.getDimensionPixelSize(R.dimen.bottom_row_above_navigation_bar)
@@ -710,13 +721,19 @@ open class MainActivity : AppCompatActivity() {
overlay.viewTreeObserver.addOnGlobalLayoutListener {
previewView.getDrawingRect(previewBounds)
overlayParent.offsetDescendantRectToMyCoords(previewView, previewBounds)
+ previewBounds.offset(-overlay.left, -overlay.top)
overlayInsets = with(Density(context = this)) {
CameraOverlayInsets(
- previewTop = previewBounds.top.toDp(),
+ previewBounds = DpRect(
+ left = previewBounds.left.toDp(),
+ top = previewBounds.top.toDp(),
+ right = previewBounds.right.toDp(),
+ bottom = previewBounds.bottom.toDp(),
+ ),
previewBottom = (overlay.height - previewBounds.bottom).toDp(),
- shutterRow = (overlay.height - threeButtons.top).toDp(),
- bottomRow = (overlay.height - binding.bottomRow.bottom).toDp(),
+ shutterRow = (overlay.bottom - threeButtons.top).toDp(),
+ bottomRow = (overlay.bottom - binding.bottomRow.bottom).toDp(),
)
}
}
@@ -824,11 +841,38 @@ open class MainActivity : AppCompatActivity() {
// The activity declares configChanges for orientation, so nothing else refreshes
// rotation-dependent state.
// The preview follows the window; the capture use cases follow the sensor.
- viewfinder.onAction(CameraAction.DisplayRotationChanged(rotation = displayRotation()))
+ updateDisplayRotation()
renderer.reapplyPreviewRatio()
}
+ private fun previewContentOf(state: ViewfinderUiState): PreviewContentState {
+ return PreviewContentState(
+ mode = state.mode,
+ lensFacing = state.flipCamera.lensFacing,
+ isPreviewStreaming = state.preview.isStreaming,
+ isTransitionFrameVisible = state.preview.lastFrameVisible,
+ isCaptureResultVisible = state.captureResult.visible,
+ selfTimerRemaining = state.selfTimer.remaining,
+ )
+ }
+
+ private fun updateDisplayRotation() {
+ val rotation = displayOrientation()
+
+ viewfinder.onAction(CameraAction.DisplayRotationChanged(rotation = rotation))
+ previewOverlays.onAction(PreviewAction.DisplayRotationChanged(rotation = rotation))
+ }
+
+ private fun displayOrientation(): DeviceOrientation {
+ return when (displayRotation()) {
+ Surface.ROTATION_90 -> DeviceOrientation.DEGREES_270
+ Surface.ROTATION_180 -> DeviceOrientation.DEGREES_180
+ Surface.ROTATION_270 -> DeviceOrientation.DEGREES_90
+ else -> DeviceOrientation.DEGREES_0
+ }
+ }
+
private fun displayRotation(): Int {
@Suppress("DEPRECATION")
val defaultDisplayRotation = windowManager.defaultDisplay.rotation
diff --git a/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraOverlay.kt b/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraOverlay.kt
index c770c28c4..063fdc361 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraOverlay.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraOverlay.kt
@@ -16,6 +16,8 @@ import app.grapheneos.camera.ui.components.motion.FADE_IN
import app.grapheneos.camera.ui.components.motion.FADE_OUT
import app.grapheneos.camera.ui.core.model.QuickSetting
import app.grapheneos.camera.ui.core.theme.SelfIlluminationTheme
+import app.grapheneos.camera.ui.previewoverlays.screen.PreviewOverlaysScreen
+import app.grapheneos.camera.ui.previewoverlays.screen.PreviewOverlaysScreenModel
import app.grapheneos.camera.ui.quicksettings.components.QuickSettingsSheetState
import app.grapheneos.camera.ui.quicksettings.navigation.QuickSettingsNavKey
import app.grapheneos.camera.ui.quicksettings.screen.QuickSettingsScreen
@@ -33,6 +35,7 @@ import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderUiState
@Composable
internal fun CameraOverlay(
viewfinder: ViewfinderScreenModel,
+ previewOverlays: PreviewOverlaysScreenModel,
statusBar: StatusBarScreenModel,
quickSettings: QuickSettingsScreenModel,
sheetState: QuickSettingsSheetState,
@@ -50,6 +53,12 @@ internal fun CameraOverlay(
!isModeSwitching
Box(modifier = Modifier.fillMaxSize()) {
+ PreviewOverlaysScreen(
+ previewBounds = insets.previewBounds,
+ shutterRowInset = insets.shutterRow,
+ screenModel = previewOverlays,
+ )
+
AnimatedVisibility(
visible = statusBarVisible,
enter = FADE_IN,
@@ -59,7 +68,7 @@ internal fun CameraOverlay(
statusBar = statusBar,
sheetState = sheetState,
enabled = controlsEnabled && statusBarVisible,
- height = insets.previewTop,
+ height = insets.previewBounds.top,
onItemClick = { setting ->
viewfinder.onAction(SettingsAction.StatusBarClicked(setting))
},
@@ -81,7 +90,7 @@ internal fun CameraOverlay(
sheetState = sheetState,
visible = sheet != null,
insets = QuickSettingsInsets(
- previewTop = insets.previewTop,
+ previewTop = insets.previewBounds.top,
previewBottom = insets.previewBottom,
shutterRow = insets.shutterRow,
),
diff --git a/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraOverlayInsets.kt b/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraOverlayInsets.kt
index 41ced86ac..63a8533db 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraOverlayInsets.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraOverlayInsets.kt
@@ -2,12 +2,18 @@ package app.grapheneos.camera.ui.camerascreen
import androidx.compose.runtime.Immutable
import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.DpRect
import androidx.compose.ui.unit.dp
-/** Distances from the screen's edges: to the preview, the shutter row and the bottom row. */
+/** Preview bounds and bottom-edge distances, all relative to the Compose overlay. */
@Immutable
internal data class CameraOverlayInsets(
- val previewTop: Dp = 0.dp,
+ val previewBounds: DpRect = DpRect(
+ left = 0.dp,
+ top = 0.dp,
+ right = 0.dp,
+ bottom = 0.dp,
+ ),
val previewBottom: Dp = 0.dp,
val shutterRow: Dp = 0.dp,
val bottomRow: Dp = 0.dp,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraScreenSample.kt b/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraScreenSample.kt
index 9abad7827..d02a42b6a 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraScreenSample.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/camerascreen/CameraScreenSample.kt
@@ -34,6 +34,8 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
+import app.grapheneos.camera.data.camera.mapper.CameraFlashMapperImpl
+import app.grapheneos.camera.data.camera.mapper.VideoQualityMapperImpl
import app.grapheneos.camera.data.camera.model.BoundCamera
import app.grapheneos.camera.data.camera.model.HighFrameRateLimit
import app.grapheneos.camera.data.camera.model.HighFrameRateSupport
@@ -338,8 +340,14 @@ private class CameraScreenSampleState {
private var modeSettings by mutableStateOf(ModeSettings())
private var shownLimit by mutableStateOf(null)
- private val quickSettingsMapper = QuickSettingsUiStateMapperImpl()
- private val statusBarMapper = StatusBarUiStateMapperImpl()
+ private val quickSettingsMapper = QuickSettingsUiStateMapperImpl(
+ flashMapper = CameraFlashMapperImpl(),
+ videoQualityMapper = VideoQualityMapperImpl(),
+ )
+ private val statusBarMapper = StatusBarUiStateMapperImpl(
+ flashMapper = CameraFlashMapperImpl(),
+ videoQualityMapper = VideoQualityMapperImpl(),
+ )
val quickSettings: QuickSettingsUiState
get() {
diff --git a/app/src/main/java/app/grapheneos/camera/ui/camerasettings/licenses/LicensesViewModel.kt b/app/src/main/java/app/grapheneos/camera/ui/camerasettings/licenses/LicensesViewModel.kt
index 664d3f89a..b7c4c1d06 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/camerasettings/licenses/LicensesViewModel.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/camerasettings/licenses/LicensesViewModel.kt
@@ -35,7 +35,9 @@ internal class LicensesViewModel @Inject constructor(
LicensesState(),
)
- override val uiState: StateFlow = stateHolder.derive(uiStateMapper::map)
+ override val uiState: StateFlow = stateHolder.derive { state ->
+ uiStateMapper.map(state)
+ }
override val effects: Flow = stateHolder.effects
diff --git a/app/src/main/java/app/grapheneos/camera/ui/camerasettings/screen/CameraSettingsViewModel.kt b/app/src/main/java/app/grapheneos/camera/ui/camerasettings/screen/CameraSettingsViewModel.kt
index 6634f7fda..f6aad0359 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/camerasettings/screen/CameraSettingsViewModel.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/camerasettings/screen/CameraSettingsViewModel.kt
@@ -72,7 +72,9 @@ internal class CameraSettingsViewModel @Inject constructor(
},
)
- override val uiState: StateFlow = stateHolder.derive(uiStateMapper::map)
+ override val uiState: StateFlow = stateHolder.derive { state ->
+ uiStateMapper.map(state)
+ }
override val effects: Flow = stateHolder.effects
override val navigationEvents: Flow = stateHolder.navigationEvents
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBar.kt b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBar.kt
index fbff4fab9..2d8c6e81d 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBar.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBar.kt
@@ -14,6 +14,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -25,6 +26,7 @@ import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import app.grapheneos.camera.ui.components.adjustmentbar.gesture.AdjustmentBarState
+import app.grapheneos.camera.ui.components.adjustmentbar.gesture.adjustmentBarPress
import app.grapheneos.camera.ui.components.adjustmentbar.gesture.rememberAdjustmentBarState
import app.grapheneos.camera.ui.components.motion.animateEnabledAlpha
import app.grapheneos.camera.ui.components.ruler.RULER_SIZE
@@ -43,6 +45,9 @@ import app.grapheneos.camera.ui.core.preview.PREVIEW_WARM_TINT
* every tick that passes the indicator during a drag, and for the nearest tick on release before
* [onValueChangeFinished]. Tapping or holding [startIcon] or [endIcon] steps toward that end of
* [valueRange]. Any change of [value] that is not a drag, such as a step or a reset, is animated to.
+ * [onPressChanged] reports a hold on the scale or either icon until all pointers are released,
+ * the gesture is canceled, or the bar is disabled or removed. Set [showContainer] to false when the
+ * caller draws the container behind the bar.
*/
@Composable
internal fun AdjustmentBar(
@@ -55,11 +60,14 @@ internal fun AdjustmentBar(
majorTickInterval: Int = 4,
startIcon: ImageVector? = null,
endIcon: ImageVector? = null,
+ showContainer: Boolean = true,
onValueChangeFinished: () -> Unit = {},
+ onPressChanged: (Boolean) -> Unit = {},
colors: AdjustmentBarColors = AdjustmentBarColors.fromTheme(),
interactionSource: MutableInteractionSource? = null,
) {
val resolvedInteractionSource = interactionSource ?: remember { MutableInteractionSource() }
+ val currentOnPressChanged by rememberUpdatedState(onPressChanged)
val scale = remember(valueRange, steps, majorTickInterval) {
AdjustmentBarScale(
valueRange = valueRange,
@@ -85,6 +93,10 @@ internal fun AdjustmentBar(
modifier = modifier
.size(size = RULER_SIZE)
.graphicsLayer { this.alpha = alpha }
+ .adjustmentBarPress(
+ enabled = enabled,
+ onPressChanged = { pressed -> currentOnPressChanged(pressed) },
+ )
.rulerInput(
state = state,
rangeInfo = ProgressBarRangeInfo(
@@ -103,6 +115,7 @@ internal fun AdjustmentBar(
scale = scale,
startIcon = startIcon,
endIcon = endIcon,
+ showContainer = showContainer,
tint = tint,
metrics = metrics,
colors = colors,
@@ -118,6 +131,7 @@ private fun BoxScope.AdjustmentBarLayers(
scale: AdjustmentBarScale,
startIcon: ImageVector?,
endIcon: ImageVector?,
+ showContainer: Boolean,
tint: AdjustmentBarTint,
metrics: RulerMetrics,
colors: AdjustmentBarColors,
@@ -141,6 +155,7 @@ private fun BoxScope.AdjustmentBarLayers(
scale = scale,
window = window,
isFocused = isFocused,
+ showContainer = showContainer,
tint = tint,
metrics = metrics,
colors = colors,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarRuler.kt b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarRuler.kt
index 4dedab3c0..c68c0e744 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarRuler.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarRuler.kt
@@ -14,11 +14,14 @@ internal fun DrawScope.drawAdjustmentBar(
scale: AdjustmentBarScale,
window: RulerWindow,
isFocused: Boolean,
+ showContainer: Boolean,
tint: AdjustmentBarTint,
metrics: RulerMetrics,
colors: AdjustmentBarColors,
) {
- drawRulerContainer(color = colors.containerColor)
+ if (showContainer) {
+ drawRulerContainer(color = colors.containerColor)
+ }
tint.draw(
drawScope = this,
position = position,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarSample.kt b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarSample.kt
index 8d714924e..c1588c48f 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarSample.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarSample.kt
@@ -117,7 +117,7 @@ private fun SampleControls(
verticalArrangement = Arrangement.spacedBy(space = 12.dp),
) {
SampleValueChip(
- isVisible = state.adjustment == SampleAdjustment.WhiteBalance,
+ visible = state.adjustment == SampleAdjustment.WhiteBalance,
text = valueLabel,
)
Box(modifier = Modifier.fillMaxWidth()) {
@@ -129,7 +129,7 @@ private fun SampleControls(
.padding(horizontal = OVERLAY_ICON_BUTTON_SIZE + RESET_BUTTON_GAP * 2),
)
SampleResetButton(
- isVisible = state.isAdjusted,
+ visible = state.isAdjusted,
onClick = state::reset,
modifier = Modifier
.align(Alignment.CenterEnd)
@@ -141,7 +141,7 @@ private fun SampleControls(
@Composable
private fun SampleValueChip(
- isVisible: Boolean,
+ visible: Boolean,
text: String,
) {
Box(contentAlignment = Alignment.Center) {
@@ -152,7 +152,7 @@ private fun SampleValueChip(
.clearAndSetSemantics {},
)
AnimatedVisibility(
- visible = isVisible,
+ visible = visible,
enter = POP_IN,
exit = POP_OUT,
) {
@@ -163,12 +163,12 @@ private fun SampleValueChip(
@Composable
private fun SampleResetButton(
- isVisible: Boolean,
+ visible: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
AnimatedVisibility(
- visible = isVisible,
+ visible = visible,
modifier = modifier,
enter = POP_IN,
exit = POP_OUT,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarScale.kt b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarScale.kt
index 861c932d7..fdab9c908 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarScale.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/AdjustmentBarScale.kt
@@ -11,9 +11,11 @@ internal data class AdjustmentBarScale(
val majorTickInterval: Int,
) : RulerScale {
+ private val zeroTick: Int = tickOf(value = 0f)
+
init {
- require(steps > 0) {
- "steps must be positive, was $steps"
+ require(steps >= 0) {
+ "steps must not be negative, was $steps"
}
require(valueRange.endInclusive > valueRange.start) {
"valueRange must not be empty, was $valueRange"
@@ -26,7 +28,7 @@ internal data class AdjustmentBarScale(
override val lastTick: Int = steps + 1
override fun isMajor(tick: Int): Boolean {
- return tick % majorTickInterval == 0
+ return (tick - zeroTick) % majorTickInterval == 0
}
override fun position(value: Float): Float {
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/gesture/AdjustmentBarPress.kt b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/gesture/AdjustmentBarPress.kt
new file mode 100644
index 000000000..99f4eb9a4
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/gesture/AdjustmentBarPress.kt
@@ -0,0 +1,31 @@
+package app.grapheneos.camera.ui.components.adjustmentbar.gesture
+
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.input.pointer.PointerEventPass
+import androidx.compose.ui.input.pointer.pointerInput
+
+internal fun Modifier.adjustmentBarPress(
+ enabled: Boolean,
+ onPressChanged: (Boolean) -> Unit,
+): Modifier {
+ return pointerInput(enabled) {
+ if (!enabled) return@pointerInput
+
+ awaitEachGesture {
+ awaitFirstDown(
+ requireUnconsumed = false,
+ pass = PointerEventPass.Initial,
+ )
+ try {
+ onPressChanged(true)
+ while (currentEvent.changes.any { change -> change.pressed }) {
+ awaitPointerEvent(pass = PointerEventPass.Final)
+ }
+ } finally {
+ onPressChanged(false)
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/gesture/AdjustmentBarState.kt b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/gesture/AdjustmentBarState.kt
index 4c757f475..3812e0876 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/gesture/AdjustmentBarState.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/adjustmentbar/gesture/AdjustmentBarState.kt
@@ -107,7 +107,7 @@ internal class AdjustmentBarState(
}
private suspend fun animateTo(tick: Int) {
- animatePosition(
+ syncPosition(
target = tick.toFloat(),
onStart = { reportedTick = tick },
)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/capturebutton/CaptureButton.kt b/app/src/main/java/app/grapheneos/camera/ui/components/capturebutton/CaptureButton.kt
index 9efff75c0..1288be596 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/capturebutton/CaptureButton.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/capturebutton/CaptureButton.kt
@@ -121,7 +121,7 @@ private fun CaptureButtonLayers(
val rotation = LocalContentRotation.current
val isPressed by interactionSource.collectIsPressedAsState()
val isFocused by interactionSource.collectIsFocusedAsState()
- val targetVisibility by animateVisibility(isVisible = holdState.isHeld)
+ val targetVisibility by animateVisibility(visible = holdState.isHeld)
val pull = animateHoldPull(
holdState = holdState,
targets = holdTargets,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/capturebutton/CaptureButtonMotion.kt b/app/src/main/java/app/grapheneos/camera/ui/components/capturebutton/CaptureButtonMotion.kt
index bc3f6abd4..4c0b947b9 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/capturebutton/CaptureButtonMotion.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/capturebutton/CaptureButtonMotion.kt
@@ -52,10 +52,10 @@ internal fun animatePressedColor(
}
@Composable
-internal fun animateVisibility(isVisible: Boolean): State {
+internal fun animateVisibility(visible: Boolean): State {
return animateFloatAsState(
targetValue = when {
- isVisible -> 1f
+ visible -> 1f
else -> 0f
},
animationSpec = QUICK_SPEC,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/focusindicator/FocusIndicatorSample.kt b/app/src/main/java/app/grapheneos/camera/ui/components/focusindicator/FocusIndicatorSample.kt
index 7d5ffcce7..d71941420 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/focusindicator/FocusIndicatorSample.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/focusindicator/FocusIndicatorSample.kt
@@ -79,7 +79,7 @@ private fun FocusIndicatorSample() {
ProvideContentRotation(degrees = state.rotation.degrees) {
key(state.focusRequest) {
FocusIndicator(
- visible = state.isVisible,
+ visible = state.visible,
appearance = state.appearance,
lockIcon = PREVIEW_LOCK_ICON,
modifier = Modifier.centerAt(point = state.point),
@@ -109,7 +109,7 @@ private class FocusIndicatorSampleState {
var point by mutableStateOf(Offset.Zero)
private set
- var isVisible by mutableStateOf(false)
+ var visible by mutableStateOf(false)
private set
var appearance by mutableStateOf(FocusIndicatorAppearance.Focusing)
private set
@@ -121,7 +121,7 @@ private class FocusIndicatorSampleState {
val status: String
get() {
return when {
- !isVisible -> "Tap to focus, hold to lock"
+ !visible -> "Tap to focus, hold to lock"
else -> appearance.name
}
}
@@ -131,7 +131,7 @@ private class FocusIndicatorSampleState {
center: Offset,
ringRadius: Float,
) {
- isPressOnRing = isVisible &&
+ isPressOnRing = visible &&
(point - this.point).getDistanceSquared() <= ringRadius * ringRadius
if (!isPressOnRing) {
show(point = center)
@@ -140,7 +140,7 @@ private class FocusIndicatorSampleState {
fun tap() {
if (isPressOnRing) {
- isVisible = false
+ visible = false
}
}
@@ -157,7 +157,7 @@ private class FocusIndicatorSampleState {
private fun show(point: Offset) {
this.point = point
appearance = FocusIndicatorAppearance.Focusing
- isVisible = true
+ visible = true
focusRequest += 1
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelAngleFilter.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelAngleFilter.kt
new file mode 100644
index 000000000..65f3f9283
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelAngleFilter.kt
@@ -0,0 +1,128 @@
+package app.grapheneos.camera.ui.components.levelindicator
+
+import app.grapheneos.camera.ui.components.motion.shortestTurn
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.milliseconds
+import kotlin.time.Duration.Companion.seconds
+
+internal class LevelAngleFilter(
+ private val wrapsAtFullTurn: Boolean,
+) {
+
+ private var acceptedDegrees: Float? = null
+ private var filteredDegrees: Float? = null
+ private var previousInputDegrees: Float = 0f
+ private var speedDegreesPerSecond: Float = 0f
+
+ var isSettled: Boolean = true
+ private set
+
+ fun update(
+ degrees: Float,
+ elapsed: Duration,
+ ): Float {
+ val reading = acceptReading(degrees)
+ val previous = filteredDegrees
+ if (previous == null) {
+ filteredDegrees = reading
+ previousInputDegrees = reading
+ return reading
+ }
+
+ val elapsedSeconds = (elapsed.coerceAtMost(MAXIMUM_FRAME_INTERVAL) / 1.seconds).toFloat()
+ val cutoff = updateCutoff(
+ reading = reading,
+ elapsedSeconds = elapsedSeconds,
+ )
+ val positionWeight = smoothingWeight(
+ cutoff = cutoff,
+ elapsedSeconds = elapsedSeconds,
+ )
+ return updatePosition(
+ current = previous,
+ reading = reading,
+ weight = positionWeight,
+ )
+ }
+
+ private fun acceptReading(degrees: Float): Float {
+ val normalizedDegrees = when {
+ !wrapsAtFullTurn -> degrees
+ degrees >= -HALF_TURN_DEGREES && degrees <= HALF_TURN_DEGREES -> degrees
+ else -> shortestTurn(from = 0f, to = degrees)
+ }
+ val previous = acceptedDegrees ?: normalizedDegrees
+ val movementDegrees = abs(difference(from = previous, to = normalizedDegrees))
+ val accepted = when {
+ movementDegrees >= MOVEMENT_THRESHOLD_DEGREES -> normalizedDegrees
+ else -> previous
+ }
+ acceptedDegrees = accepted
+ return accepted
+ }
+
+ private fun updateCutoff(
+ reading: Float,
+ elapsedSeconds: Float,
+ ): Float {
+ val speed = when {
+ elapsedSeconds > 0f -> {
+ difference(from = previousInputDegrees, to = reading) / elapsedSeconds
+ }
+ else -> 0f
+ }
+ val speedWeight = smoothingWeight(cutoff = SPEED_CUTOFF, elapsedSeconds = elapsedSeconds)
+ speedDegreesPerSecond += speedWeight * (speed - speedDegreesPerSecond)
+ previousInputDegrees = reading
+ return MINIMUM_CUTOFF + SPEED_WEIGHT * abs(speedDegreesPerSecond)
+ }
+
+ private fun updatePosition(
+ current: Float,
+ reading: Float,
+ weight: Float,
+ ): Float {
+ val remainingDegrees = difference(from = current, to = reading)
+ val smoothed = current + weight * remainingDegrees
+ isSettled = abs(difference(from = smoothed, to = reading)) <= SETTLED_THRESHOLD_DEGREES
+ val result = when {
+ isSettled -> reading
+ else -> smoothed
+ }
+ if (isSettled) {
+ speedDegreesPerSecond = 0f
+ }
+ filteredDegrees = result
+ return result
+ }
+
+ private fun difference(
+ from: Float,
+ to: Float,
+ ): Float {
+ return when {
+ wrapsAtFullTurn -> shortestTurn(from = from, to = to)
+ else -> to - from
+ }
+ }
+
+ private fun smoothingWeight(
+ cutoff: Float,
+ elapsedSeconds: Float,
+ ): Float {
+ val timeConstant = 1f / (2f * PI.toFloat() * cutoff)
+ return elapsedSeconds / (timeConstant + elapsedSeconds)
+ }
+
+ private companion object {
+ private const val HALF_TURN_DEGREES = 180f
+ private const val MOVEMENT_THRESHOLD_DEGREES = 0.35f
+ private const val SETTLED_THRESHOLD_DEGREES = 0.01f
+ private const val MINIMUM_CUTOFF = 2f
+ private const val SPEED_CUTOFF = 1f
+ private const val SPEED_WEIGHT = 0.2f
+ private val MAXIMUM_FRAME_INTERVAL = 50.milliseconds
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelTracker.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelHapticTracker.kt
similarity index 92%
rename from app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelTracker.kt
rename to app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelHapticTracker.kt
index eb12813af..62f9b9a85 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelTracker.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelHapticTracker.kt
@@ -1,6 +1,6 @@
package app.grapheneos.camera.ui.components.levelindicator
-internal class LevelTracker(
+internal class LevelHapticTracker(
initialZone: LevelZone,
) {
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicator.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicator.kt
index 2950791d0..7c2834334 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicator.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicator.kt
@@ -11,6 +11,7 @@ import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
import app.grapheneos.camera.ui.components.motion.LocalContentRotation
import app.grapheneos.camera.ui.core.preview.CameraPreviewColumn
import app.grapheneos.camera.ui.core.preview.CameraPreviewViewfinder
@@ -26,6 +27,7 @@ private val SHADOW_RADIUS = 1.dp
*/
@Composable
internal fun LevelIndicator(
+ mode: LevelIndicatorMode,
roll: () -> Float,
pitch: () -> Float,
modifier: Modifier = Modifier,
@@ -33,6 +35,7 @@ internal fun LevelIndicator(
) {
val rotation = LocalContentRotation.current
val motion = rememberLevelIndicatorMotion(
+ mode = mode,
roll = roll,
pitch = pitch,
)
@@ -74,12 +77,36 @@ private fun LevelIndicatorPreview() {
horizontalArrangement = Arrangement.spacedBy(space = 16.dp),
verticalArrangement = Arrangement.spacedBy(space = 16.dp),
) {
- PreviewLevelIndicator(roll = -22f, pitch = -30f)
- PreviewLevelIndicator(roll = -23f, pitch = 0f)
- PreviewLevelIndicator(roll = 0f, pitch = 20f)
- PreviewLevelIndicator(roll = 0f, pitch = 0f)
- PreviewLevelIndicator(roll = 150f, pitch = -70f)
- PreviewLevelIndicator(roll = 0f, pitch = -90f)
+ PreviewLevelIndicator(
+ mode = LevelIndicatorMode.Horizon,
+ roll = -22f,
+ pitch = -30f,
+ )
+ PreviewLevelIndicator(
+ mode = LevelIndicatorMode.Horizon,
+ roll = -23f,
+ pitch = 0f,
+ )
+ PreviewLevelIndicator(
+ mode = LevelIndicatorMode.Horizon,
+ roll = 0f,
+ pitch = 20f,
+ )
+ PreviewLevelIndicator(
+ mode = LevelIndicatorMode.Horizon,
+ roll = 0f,
+ pitch = 0f,
+ )
+ PreviewLevelIndicator(
+ mode = LevelIndicatorMode.Crosshairs,
+ roll = 150f,
+ pitch = -70f,
+ )
+ PreviewLevelIndicator(
+ mode = LevelIndicatorMode.Crosshairs,
+ roll = 0f,
+ pitch = -90f,
+ )
}
}
}
@@ -87,10 +114,12 @@ private fun LevelIndicatorPreview() {
@Composable
private fun PreviewLevelIndicator(
+ mode: LevelIndicatorMode,
roll: Float,
pitch: Float,
) {
LevelIndicator(
+ mode = mode,
roll = { roll },
pitch = { pitch },
)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorAngles.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorAngles.kt
new file mode 100644
index 000000000..d600447b6
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorAngles.kt
@@ -0,0 +1,65 @@
+package app.grapheneos.camera.ui.components.levelindicator
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.State
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.runtime.snapshots.Snapshot
+import androidx.compose.runtime.withFrameNanos
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.nanoseconds
+import kotlinx.coroutines.flow.collectLatest
+
+@Composable
+internal fun rememberLevelIndicatorAngles(
+ mode: LevelIndicatorMode,
+ roll: () -> Float,
+ pitch: () -> Float,
+): State {
+ val currentRoll by rememberUpdatedState(roll)
+ val currentPitch by rememberUpdatedState(pitch)
+ val filter = remember(mode) { LevelIndicatorFilter(mode = mode) }
+ val filteredAngles = remember(filter) {
+ mutableStateOf(
+ Snapshot.withoutReadObservation {
+ filter.update(
+ roll = roll(),
+ pitch = pitch(),
+ elapsed = Duration.ZERO,
+ )
+ },
+ )
+ }
+
+ LaunchedEffect(filter) {
+ var previousFrameNanos: Long? = null
+
+ snapshotFlow {
+ LevelIndicatorFilter.Angles(
+ roll = currentRoll(),
+ pitch = currentPitch(),
+ )
+ }.collectLatest { angles ->
+ do {
+ withFrameNanos { frameNanos ->
+ val elapsed = previousFrameNanos?.let { previous ->
+ (frameNanos - previous).nanoseconds
+ } ?: Duration.ZERO
+ previousFrameNanos = frameNanos
+ filteredAngles.value = filter.update(
+ roll = angles.roll,
+ pitch = angles.pitch,
+ elapsed = elapsed,
+ )
+ }
+ } while (!filter.isSettled)
+ }
+ }
+
+ return filteredAngles
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorDrawing.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorDrawing.kt
index 02a2907e4..fc7f99b61 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorDrawing.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorDrawing.kt
@@ -8,6 +8,7 @@ import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
import app.grapheneos.camera.ui.components.text.drawCenteredText
import kotlin.math.abs
import kotlin.math.cos
@@ -22,11 +23,13 @@ private val LINE_WIDTH = 1.5.dp
private val LEVEL_LINE_WIDTH = 2.5.dp
private val DASH_LENGTH = 4.dp
private val LABEL_OFFSET = 10.dp
-private val CROSS_ARM = 10.dp
-private val CROSS_DOT_RADIUS = 2.25.dp
-private val TILT_SHIFT_RANGE = 24.dp
+private val CROSSHAIR_ARM = 10.dp
+private val CROSSHAIR_DOT_RADIUS = 2.25.dp
+private val CROSSHAIR_SHIFT_RANGE = 24.dp
+private val HORIZON_SHIFT_RANGE = 40.dp
-private const val TILT_RANGE = 45f
+private const val CROSSHAIR_TILT_RANGE = 15f
+private const val HORIZON_PITCH_RANGE = 45f
internal fun DrawScope.drawLevelIndicator(
motion: LevelIndicatorMotion,
@@ -34,111 +37,100 @@ internal fun DrawScope.drawLevelIndicator(
paint: LevelPaint,
colors: LevelIndicatorColors,
) {
- drawHorizonLevel(
- motion = motion,
- labels = labels,
- paint = paint,
- colors = colors,
- alpha = 1f - motion.topDown,
- )
- drawTopDownLevel(
- motion = motion,
- paint = paint,
- colors = colors,
- alpha = motion.topDown,
- )
+ when (motion.mode) {
+ LevelIndicatorMode.Horizon -> drawHorizon(
+ motion = motion,
+ labels = labels,
+ paint = paint,
+ colors = colors,
+ )
+
+ LevelIndicatorMode.Crosshairs -> drawCrosshairs(
+ motion = motion,
+ paint = paint,
+ colors = colors,
+ )
+ }
}
-private fun DrawScope.drawHorizonLevel(
+private fun DrawScope.drawHorizon(
motion: LevelIndicatorMotion,
labels: LevelIndicatorLabels,
paint: LevelPaint,
colors: LevelIndicatorColors,
- alpha: Float,
) {
- if (alpha <= 0f) return
-
val color = lerp(
start = colors.lineColor,
stop = colors.levelColor,
- fraction = motion.pitchLevel,
+ fraction = motion.pitchAlignmentFraction,
)
drawDashes(
paint = paint,
color = color,
- alpha = alpha,
)
rotate(degrees = motion.roll) {
- drawLevelLine(
+ drawHorizonLine(
paint = paint,
halfLength = lerp(
start = LINE_LENGTH.toPx(),
stop = LEVEL_LINE_LENGTH.toPx(),
- fraction = motion.rollLevel,
+ fraction = motion.rollAlignmentFraction,
) / 2,
y = center.y,
- level = motion.rollLevel,
+ alignmentFraction = motion.rollAlignmentFraction,
color = color,
- alpha = alpha,
)
- drawLevelLine(
+ drawHorizonLine(
paint = paint,
halfLength = LINE_LENGTH.toPx() / 2,
- y = center.y + tiltShift(degrees = motion.pitch),
- level = 0f,
+ y = center.y + horizonShift(degrees = motion.pitch),
+ alignmentFraction = 0f,
color = colors.levelColor,
- alpha = alpha * (1f - motion.rollLevel * motion.pitchLevel),
+ alpha = 1f - motion.rollAlignmentFraction * motion.pitchAlignmentFraction,
)
drawCenteredText(
text = labels.label(degrees = abs(motion.roll).roundToInt()),
center = center - Offset(x = 0f, y = LABEL_OFFSET.toPx()),
color = color,
- alpha = alpha,
- shadow = labels.shadow(alpha = alpha),
+ shadow = labels.shadow,
)
}
}
-private fun DrawScope.drawTopDownLevel(
+private fun DrawScope.drawCrosshairs(
motion: LevelIndicatorMotion,
paint: LevelPaint,
colors: LevelIndicatorColors,
- alpha: Float,
) {
- if (alpha <= 0f) return
-
val tilt = LevelZone.tiltFromVertical(pitch = motion.pitch)
- val shift = tiltShift(degrees = tilt) * sign(motion.pitch)
+ val shift = crosshairShift(degrees = tilt) * sign(motion.pitch)
val radians = Math.toRadians(motion.roll.toDouble())
- drawCross(
+ drawCrosshair(
paint = paint,
center = center,
- level = motion.verticalLevel,
+ alignmentFraction = motion.verticalAlignmentFraction,
color = lerp(
start = colors.lineColor,
stop = colors.levelColor,
- fraction = motion.verticalLevel,
+ fraction = motion.verticalAlignmentFraction,
),
- alpha = alpha,
)
- drawCross(
+ drawCrosshair(
paint = paint,
center = center + Offset(
x = shift * sin(radians).toFloat(),
y = -shift * cos(radians).toFloat(),
),
- level = motion.verticalLevel,
+ alignmentFraction = motion.verticalAlignmentFraction,
color = colors.levelColor,
- alpha = alpha,
)
}
private fun DrawScope.drawDashes(
paint: LevelPaint,
color: Color,
- alpha: Float,
) {
val outer = LEVEL_LINE_LENGTH.toPx() / 2
val inner = outer - DASH_LENGTH.toPx()
@@ -148,85 +140,85 @@ private fun DrawScope.drawDashes(
canvas = canvas,
start = center - Offset(x = outer, y = 0f),
end = center - Offset(x = inner, y = 0f),
- width = lineWidth(level = 0f),
+ width = lineWidth(alignmentFraction = 0f),
color = color,
- alpha = alpha,
)
paint.drawLine(
canvas = canvas,
start = center + Offset(x = inner, y = 0f),
end = center + Offset(x = outer, y = 0f),
- width = lineWidth(level = 0f),
+ width = lineWidth(alignmentFraction = 0f),
color = color,
- alpha = alpha,
)
}
}
-private fun DrawScope.drawLevelLine(
+private fun DrawScope.drawHorizonLine(
paint: LevelPaint,
halfLength: Float,
y: Float,
- level: Float,
+ alignmentFraction: Float,
color: Color,
- alpha: Float,
+ alpha: Float = 1f,
) {
drawIntoCanvas { canvas ->
paint.drawLine(
canvas = canvas,
start = Offset(x = center.x - halfLength, y = y),
end = Offset(x = center.x + halfLength, y = y),
- width = lineWidth(level = level),
+ width = lineWidth(alignmentFraction = alignmentFraction),
color = color,
alpha = alpha,
)
}
}
-private fun DrawScope.drawCross(
+private fun DrawScope.drawCrosshair(
paint: LevelPaint,
center: Offset,
- level: Float,
+ alignmentFraction: Float,
color: Color,
- alpha: Float,
) {
- val arm = CROSS_ARM.toPx()
+ val arm = CROSSHAIR_ARM.toPx()
drawIntoCanvas { canvas ->
paint.drawLine(
canvas = canvas,
start = center - Offset(x = arm, y = 0f),
end = center + Offset(x = arm, y = 0f),
- width = lineWidth(level = level),
+ width = lineWidth(alignmentFraction = alignmentFraction),
color = color,
- alpha = alpha,
)
paint.drawLine(
canvas = canvas,
start = center - Offset(x = 0f, y = arm),
end = center + Offset(x = 0f, y = arm),
- width = lineWidth(level = level),
+ width = lineWidth(alignmentFraction = alignmentFraction),
color = color,
- alpha = alpha,
)
paint.drawDot(
canvas = canvas,
center = center,
- radius = CROSS_DOT_RADIUS.toPx(),
+ radius = CROSSHAIR_DOT_RADIUS.toPx(),
color = color,
- alpha = alpha,
)
}
}
-private fun DrawScope.lineWidth(level: Float): Float {
+private fun DrawScope.lineWidth(alignmentFraction: Float): Float {
return lerp(
start = LINE_WIDTH.toPx(),
stop = LEVEL_LINE_WIDTH.toPx(),
- fraction = level,
+ fraction = alignmentFraction,
)
}
-private fun DrawScope.tiltShift(degrees: Float): Float {
- return degrees.coerceIn(-TILT_RANGE, TILT_RANGE) / TILT_RANGE * TILT_SHIFT_RANGE.toPx()
+private fun DrawScope.horizonShift(degrees: Float): Float {
+ val fraction = degrees.coerceIn(-HORIZON_PITCH_RANGE, HORIZON_PITCH_RANGE) / HORIZON_PITCH_RANGE
+ return fraction * HORIZON_SHIFT_RANGE.toPx()
+}
+
+private fun DrawScope.crosshairShift(degrees: Float): Float {
+ val fraction = degrees.coerceIn(0f, CROSSHAIR_TILT_RANGE) / CROSSHAIR_TILT_RANGE
+ return fraction * CROSSHAIR_SHIFT_RANGE.toPx()
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorFilter.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorFilter.kt
new file mode 100644
index 000000000..14cdee8df
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorFilter.kt
@@ -0,0 +1,105 @@
+package app.grapheneos.camera.ui.components.levelindicator
+
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
+import app.grapheneos.camera.ui.components.motion.shortestTurn
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.hypot
+import kotlin.math.sign
+import kotlin.math.sin
+import kotlin.time.Duration
+
+internal class LevelIndicatorFilter(
+ private val mode: LevelIndicatorMode,
+) {
+
+ private val horizontalAngleFilter = LevelAngleFilter(
+ wrapsAtFullTurn = mode == LevelIndicatorMode.Horizon,
+ )
+ private val verticalAngleFilter = LevelAngleFilter(
+ wrapsAtFullTurn = false,
+ )
+
+ val isSettled: Boolean
+ get() {
+ return horizontalAngleFilter.isSettled && verticalAngleFilter.isSettled
+ }
+
+ fun update(
+ roll: Float,
+ pitch: Float,
+ elapsed: Duration,
+ ): Angles {
+ return when (mode) {
+ LevelIndicatorMode.Horizon -> filterHorizon(
+ roll = roll,
+ pitch = pitch,
+ elapsed = elapsed,
+ )
+
+ LevelIndicatorMode.Crosshairs -> filterCrosshairTilt(
+ roll = roll,
+ pitch = pitch,
+ elapsed = elapsed,
+ )
+ }
+ }
+
+ private fun filterHorizon(
+ roll: Float,
+ pitch: Float,
+ elapsed: Duration,
+ ): Angles {
+ val alignedRoll = when {
+ LevelZone.isRollLevel(shortestTurn(from = 0f, to = roll)) -> 0f
+ else -> roll
+ }
+ val alignedPitch = when {
+ LevelZone.isPitchLevel(pitch) -> 0f
+ else -> pitch
+ }
+
+ return Angles(
+ roll = horizontalAngleFilter.update(degrees = alignedRoll, elapsed = elapsed),
+ pitch = verticalAngleFilter.update(degrees = alignedPitch, elapsed = elapsed),
+ )
+ }
+
+ private fun filterCrosshairTilt(
+ roll: Float,
+ pitch: Float,
+ elapsed: Duration,
+ ): Angles {
+ val tiltDegrees = LevelZone.tiltFromVertical(pitch)
+ val tiltMagnitude = when {
+ tiltDegrees < VERTICAL_SNAP_DEGREES -> 0f
+ else -> tiltDegrees
+ }
+ val rollRadians = Math.toRadians(roll.toDouble())
+ // Near vertical, azimuth is unstable even when the projected tilt barely moves.
+ val horizontalTilt = horizontalAngleFilter.update(
+ degrees = tiltMagnitude * sin(rollRadians).toFloat(),
+ elapsed = elapsed,
+ )
+ val verticalTilt = verticalAngleFilter.update(
+ degrees = tiltMagnitude * cos(rollRadians).toFloat(),
+ elapsed = elapsed,
+ )
+ val filteredRollRadians = atan2(horizontalTilt.toDouble(), verticalTilt.toDouble())
+
+ return Angles(
+ roll = Math.toDegrees(filteredRollRadians).toFloat(),
+ pitch = sign(pitch) * (VERTICAL_DEGREES - hypot(horizontalTilt, verticalTilt)),
+ )
+ }
+
+ data class Angles(
+ val roll: Float,
+ val pitch: Float,
+ )
+
+ private companion object {
+ private const val VERTICAL_DEGREES = 90f
+ private const val VERTICAL_SNAP_DEGREES = 0.15f
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorHapticEffect.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorHapticEffect.kt
new file mode 100644
index 000000000..5d844cd33
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorHapticEffect.kt
@@ -0,0 +1,37 @@
+package app.grapheneos.camera.ui.components.levelindicator
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.State
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.platform.LocalHapticFeedback
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
+
+@Composable
+internal fun LevelIndicatorHapticEffect(
+ mode: LevelIndicatorMode,
+ roll: State,
+ pitch: State,
+) {
+ fun currentZone(): LevelZone {
+ return LevelZone.of(
+ mode = mode,
+ roll = roll.value,
+ pitch = pitch.value,
+ )
+ }
+
+ val currentHapticFeedback = rememberUpdatedState(LocalHapticFeedback.current)
+
+ LaunchedEffect(mode, roll, pitch) {
+ val tracker = LevelHapticTracker(initialZone = currentZone())
+
+ snapshotFlow { currentZone() }.collect { zone ->
+ if (tracker.reachesLevel(zone = zone)) {
+ currentHapticFeedback.value.performHapticFeedback(HapticFeedbackType.SegmentTick)
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorLabels.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorLabels.kt
index cf52d186a..238175f4c 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorLabels.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorLabels.kt
@@ -24,18 +24,11 @@ internal class LevelIndicatorLabels(
private val textMeasurer: TextMeasurer,
private val style: TextStyle,
private val numberFormat: NumberFormat,
- private val shadow: Shadow,
+ val shadow: Shadow,
) {
private val labels = HashMap()
- fun shadow(alpha: Float): Shadow {
- return when {
- alpha >= 1f -> shadow
- else -> shadow.copy(color = shadow.color.copy(alpha = shadow.color.alpha * alpha))
- }
- }
-
fun label(degrees: Int): CenteredText {
return labels.getOrPut(degrees) {
val number = numberFormat.format(degrees.toLong())
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorMotion.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorMotion.kt
index 4e58c7aed..8fd85505b 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorMotion.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorMotion.kt
@@ -5,83 +5,92 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
+import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.snapshots.Snapshot
-import androidx.compose.ui.hapticfeedback.HapticFeedbackType
-import androidx.compose.ui.platform.LocalHapticFeedback
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
import app.grapheneos.camera.ui.components.motion.SETTLE_SPEC
-import app.grapheneos.camera.ui.components.motion.animateFollow
-import app.grapheneos.camera.ui.components.motion.animateTurn
import kotlinx.coroutines.flow.collectLatest
-import kotlinx.coroutines.flow.distinctUntilChanged
-import kotlinx.coroutines.flow.map
@Stable
internal class LevelIndicatorMotion(
+ val mode: LevelIndicatorMode,
roll: State,
pitch: State,
- rollLevel: State,
- pitchLevel: State,
- verticalLevel: State,
- topDown: State,
+ rollAlignmentFraction: State,
+ pitchAlignmentFraction: State,
+ verticalAlignmentFraction: State,
) {
val roll by roll
val pitch by pitch
- val rollLevel by rollLevel
- val pitchLevel by pitchLevel
- val verticalLevel by verticalLevel
- val topDown by topDown
+ val rollAlignmentFraction by rollAlignmentFraction
+ val pitchAlignmentFraction by pitchAlignmentFraction
+ val verticalAlignmentFraction by verticalAlignmentFraction
}
@Composable
internal fun rememberLevelIndicatorMotion(
+ mode: LevelIndicatorMode,
roll: () -> Float,
pitch: () -> Float,
): LevelIndicatorMotion {
- val shownRoll = animateTurn(
- degrees = roll,
- animationSpec = SETTLE_SPEC,
+ val shownAngles = rememberLevelIndicatorAngles(
+ mode = mode,
+ roll = roll,
+ pitch = pitch,
)
- val shownPitch = animateFollow(
- value = pitch,
- animationSpec = SETTLE_SPEC,
- )
- val rollLevel = animateLevelFraction { LevelZone.isRollLevel(roll = shownRoll.value) }
- val pitchLevel = animateLevelFraction { LevelZone.isPitchLevel(pitch = shownPitch.value) }
- val verticalLevel = animateLevelFraction { LevelZone.isVertical(pitch = shownPitch.value) }
- val topDown = animateTopDownFraction(pitch = shownPitch)
+ val shownRoll = remember(shownAngles) { derivedStateOf { shownAngles.value.roll } }
+ val shownPitch = remember(shownAngles) { derivedStateOf { shownAngles.value.pitch } }
+ val rollAlignmentFraction = animateAlignmentFraction {
+ LevelZone.isRollLevel(roll = shownRoll.value)
+ }
+ val pitchAlignmentFraction = animateAlignmentFraction {
+ LevelZone.isPitchLevel(pitch = shownPitch.value)
+ }
+ val verticalAlignmentFraction = animateAlignmentFraction {
+ LevelZone.isVertical(pitch = shownPitch.value)
+ }
- LevelHapticEffect(
+ LevelIndicatorHapticEffect(
+ mode = mode,
roll = shownRoll,
pitch = shownPitch,
)
- return remember(shownRoll, shownPitch, rollLevel, pitchLevel, verticalLevel, topDown) {
+ return remember(
+ mode,
+ shownRoll,
+ shownPitch,
+ rollAlignmentFraction,
+ pitchAlignmentFraction,
+ verticalAlignmentFraction,
+ ) {
LevelIndicatorMotion(
+ mode = mode,
roll = shownRoll,
pitch = shownPitch,
- rollLevel = rollLevel,
- pitchLevel = pitchLevel,
- verticalLevel = verticalLevel,
- topDown = topDown,
+ rollAlignmentFraction = rollAlignmentFraction,
+ pitchAlignmentFraction = pitchAlignmentFraction,
+ verticalAlignmentFraction = verticalAlignmentFraction,
)
}
}
@Composable
-private fun animateLevelFraction(isLevel: () -> Boolean): State {
- val currentIsLevel by rememberUpdatedState(isLevel)
+private fun animateAlignmentFraction(isAligned: () -> Boolean): State {
+ val currentIsAligned by rememberUpdatedState(isAligned)
val fraction = remember {
- Animatable(initialValue = fractionOf(level = Snapshot.withoutReadObservation(isLevel)))
+ val initiallyAligned = Snapshot.withoutReadObservation(isAligned)
+ Animatable(initialValue = alignmentFraction(isAligned = initiallyAligned))
}
LaunchedEffect(fraction) {
- snapshotFlow { currentIsLevel() }.collectLatest { level ->
+ snapshotFlow { currentIsAligned() }.collectLatest { aligned ->
fraction.animateTo(
- targetValue = fractionOf(level = level),
+ targetValue = alignmentFraction(isAligned = aligned),
animationSpec = SETTLE_SPEC,
)
}
@@ -90,70 +99,9 @@ private fun animateLevelFraction(isLevel: () -> Boolean): State {
return fraction.asState()
}
-@Composable
-private fun animateTopDownFraction(pitch: State): State {
- val fraction = remember {
- val isTopDown = Snapshot.withoutReadObservation {
- LevelZone.isTopDown(
- pitch = pitch.value,
- wasTopDown = false,
- )
- }
-
- Animatable(initialValue = fractionOf(level = isTopDown))
- }
-
- LaunchedEffect(pitch) {
- var isTopDown = fraction.value == 1f
-
- snapshotFlow { pitch.value }
- .map { value ->
- isTopDown = LevelZone.isTopDown(
- pitch = value,
- wasTopDown = isTopDown,
- )
- isTopDown
- }
- .distinctUntilChanged()
- .collectLatest { topDown ->
- fraction.animateTo(
- targetValue = fractionOf(level = topDown),
- animationSpec = SETTLE_SPEC,
- )
- }
- }
-
- return fraction.asState()
-}
-
-@Composable
-private fun LevelHapticEffect(
- roll: State,
- pitch: State,
-) {
- fun currentZone(): LevelZone {
- return LevelZone.of(
- roll = roll.value,
- pitch = pitch.value,
- )
- }
-
- val hapticFeedback = rememberUpdatedState(LocalHapticFeedback.current)
-
- LaunchedEffect(roll, pitch) {
- val tracker = LevelTracker(initialZone = currentZone())
-
- snapshotFlow { currentZone() }.collect { zone ->
- if (tracker.reachesLevel(zone = zone)) {
- hapticFeedback.value.performHapticFeedback(HapticFeedbackType.SegmentTick)
- }
- }
- }
-}
-
-private fun fractionOf(level: Boolean): Float {
+private fun alignmentFraction(isAligned: Boolean): Float {
return when {
- level -> 1f
+ isAligned -> 1f
else -> 0f
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorSample.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorSample.kt
index f37da19c1..405959657 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorSample.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelIndicatorSample.kt
@@ -7,6 +7,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -17,8 +18,10 @@ import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import app.grapheneos.camera.ui.components.adjustmentbar.AdjustmentBar
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
import app.grapheneos.camera.ui.components.motion.ProvideContentRotation
import app.grapheneos.camera.ui.components.motion.rotateLayout
+import app.grapheneos.camera.ui.core.preview.CameraPreviewControl
import app.grapheneos.camera.ui.core.preview.CameraPreviewSample
import app.grapheneos.camera.ui.core.preview.PreviewRotation
@@ -54,10 +57,15 @@ private fun LevelIndicatorSample() {
status = "Roll ${degrees.format(state.roll)}°, pitch ${degrees.format(state.pitch)}°",
controls = {
state.rotation.Control()
+ CameraPreviewControl(
+ text = state.mode.name,
+ onClick = state::changeMode,
+ )
},
) {
ProvideContentRotation(degrees = state.rotation.degrees) {
LevelIndicator(
+ mode = state.mode,
roll = state::roll,
pitch = state::pitch,
modifier = Modifier.align(Alignment.Center),
@@ -99,11 +107,21 @@ private class LevelIndicatorSampleState {
val rotation = PreviewRotation()
+ var mode by mutableStateOf(LevelIndicatorMode.Horizon)
+ private set
+
var roll by mutableFloatStateOf(INITIAL_ROLL)
private set
var pitch by mutableFloatStateOf(0f)
private set
+ fun changeMode() {
+ mode = when (mode) {
+ LevelIndicatorMode.Horizon -> LevelIndicatorMode.Crosshairs
+ LevelIndicatorMode.Crosshairs -> LevelIndicatorMode.Horizon
+ }
+ }
+
fun changeRoll(value: Float) {
roll = value
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelPaint.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelPaint.kt
index a0f8520e5..ffb70842c 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelPaint.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelPaint.kt
@@ -22,7 +22,7 @@ internal class LevelPaint(
end: Offset,
width: Float,
color: Color,
- alpha: Float,
+ alpha: Float = 1f,
) {
prepare(
color = color,
@@ -38,19 +38,15 @@ internal class LevelPaint(
center: Offset,
radius: Float,
color: Color,
- alpha: Float,
) {
- prepare(
- color = color,
- alpha = alpha,
- )
+ prepare(color = color)
paint.style = Paint.Style.FILL
canvas.nativeCanvas.drawCircle(center.x, center.y, radius, paint)
}
private fun prepare(
color: Color,
- alpha: Float,
+ alpha: Float = 1f,
) {
paint.color = color.copy(alpha = color.alpha * alpha).toArgb()
paint.setShadowLayer(
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelZone.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelZone.kt
index 254737d92..6f8b233c1 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelZone.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/LevelZone.kt
@@ -1,5 +1,6 @@
package app.grapheneos.camera.ui.components.levelindicator
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
import kotlin.math.abs
internal enum class LevelZone {
@@ -12,8 +13,6 @@ internal enum class LevelZone {
private const val LEVEL_ROLL_DEGREES = 0.5f
private const val LEVEL_DEGREES = 1f
private const val AWAY_DEGREES = 2f
- private const val TOP_DOWN_ENTER_DEGREES = 60f
- private const val TOP_DOWN_EXIT_DEGREES = 50f
private const val VERTICAL_DEGREES = 90f
fun isRollLevel(roll: Float): Boolean {
@@ -32,25 +31,19 @@ internal enum class LevelZone {
return VERTICAL_DEGREES - abs(pitch)
}
- fun isTopDown(
- pitch: Float,
- wasTopDown: Boolean,
- ): Boolean {
- return when {
- abs(pitch) >= TOP_DOWN_ENTER_DEGREES -> true
- abs(pitch) <= TOP_DOWN_EXIT_DEGREES -> false
- else -> wasTopDown
- }
- }
-
fun of(
+ mode: LevelIndicatorMode,
roll: Float,
pitch: Float,
): LevelZone {
- val isLevel = isVertical(pitch = pitch) ||
- (isRollLevel(roll = roll) && isPitchLevel(pitch = pitch))
- val isNear = tiltFromVertical(pitch = pitch) < AWAY_DEGREES ||
- (abs(roll) < AWAY_DEGREES && abs(pitch) < AWAY_DEGREES)
+ val isLevel = when (mode) {
+ LevelIndicatorMode.Horizon -> isRollLevel(roll) && isPitchLevel(pitch)
+ LevelIndicatorMode.Crosshairs -> isVertical(pitch)
+ }
+ val isNear = when (mode) {
+ LevelIndicatorMode.Horizon -> abs(roll) < AWAY_DEGREES && abs(pitch) < AWAY_DEGREES
+ LevelIndicatorMode.Crosshairs -> tiltFromVertical(pitch) < AWAY_DEGREES
+ }
return when {
isLevel -> Level
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/model/LevelIndicatorMode.kt b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/model/LevelIndicatorMode.kt
new file mode 100644
index 000000000..542207f42
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/levelindicator/model/LevelIndicatorMode.kt
@@ -0,0 +1,6 @@
+package app.grapheneos.camera.ui.components.levelindicator.model
+
+internal enum class LevelIndicatorMode {
+ Horizon,
+ Crosshairs,
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/motion/Transitions.kt b/app/src/main/java/app/grapheneos/camera/ui/components/motion/Transitions.kt
index d6945f3dd..b9b91d78a 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/motion/Transitions.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/motion/Transitions.kt
@@ -4,11 +4,14 @@ import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.ContentTransform
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.core.snap
+import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
+import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.togetherWith
+import androidx.compose.ui.Alignment
private const val POP_SCALE = 0.8f
@@ -16,6 +19,15 @@ internal val FADE_IN = fadeIn(animationSpec = SETTLE_SPEC)
internal val FADE_OUT = fadeOut(animationSpec = SETTLE_SPEC)
private val HIDE_AT_ONCE = fadeOut(animationSpec = snap())
+internal val EXPAND_HORIZONTALLY = expandHorizontally(
+ animationSpec = SETTLE_SIZE_SPEC,
+ expandFrom = Alignment.CenterHorizontally,
+) + FADE_IN
+internal val SHRINK_HORIZONTALLY = shrinkHorizontally(
+ animationSpec = SETTLE_SIZE_SPEC,
+ shrinkTowards = Alignment.CenterHorizontally,
+) + FADE_OUT
+
internal val POP_IN = FADE_IN + scaleIn(
animationSpec = MORPH_SPEC,
initialScale = POP_SCALE,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelector.kt b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelector.kt
index 0c6395b1a..011b19458 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelector.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelector.kt
@@ -1,12 +1,15 @@
package app.grapheneos.camera.ui.components.pillselector
+import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
@@ -17,7 +20,9 @@ import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
@@ -28,12 +33,17 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onPlaced
+import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInParent
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import app.grapheneos.camera.ui.components.highlight.drawHighlight
import app.grapheneos.camera.ui.components.highlight.highlightedContent
+import app.grapheneos.camera.ui.components.motion.EXPAND_HORIZONTALLY
+import app.grapheneos.camera.ui.components.motion.SHRINK_HORIZONTALLY
import app.grapheneos.camera.ui.components.motion.animateEnabledAlpha
import app.grapheneos.camera.ui.components.pillselector.gesture.PillSelectorSelection
import app.grapheneos.camera.ui.components.pillselector.gesture.pillSelectorInput
@@ -50,32 +60,52 @@ private val CONTAINER_PADDING = 2.dp
* announced as a radio button, with the semantics its content sets. [onItemSelected] reports a
* tapped item and, when [draggable], the item a lifted horizontal drag leaves the highlight nearest
* to; a canceled drag reports nothing. Otherwise drags pass to the parent.
+ *
+ * [items] are told apart by [key] when they change: an item with a new key grows in, one whose key
+ * is gone shrinks away, and an item that keeps its key stays in its slot and is drawn with its new
+ * value. The highlight stays on the item it is on while the others make room, and slides when
+ * [selected] changes.
*/
@Composable
-internal fun PillSelector(
- selectedIndex: Int,
- itemCount: Int,
- onItemSelected: (index: Int) -> Unit,
+internal fun - PillSelector(
+ items: List
- ,
+ selected: Item,
+ key: (item: Item) -> Key,
+ onItemSelected: (item: Item) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
draggable: Boolean = false,
spacing: PillSelectorSpacing = PillSelectorSpacing.Spaced,
colors: PillSelectorColors = PillSelectorColors.fromTheme(),
- item: @Composable PillSelectorItemScope.(index: Int) -> Unit,
+ item: @Composable PillSelectorItemScope.(item: Item) -> Unit,
) {
- require(selectedIndex in 0 until itemCount) {
- "selectedIndex must be in 0 until $itemCount, was $selectedIndex"
+ val entries = rememberPillSelectorEntries(
+ items = items,
+ key = key,
+ )
+ val selectedIndex = entries.keys.indexOf(key(selected))
+ require(selectedIndex >= 0 && selected in items) {
+ "selected must be one of items, was $selected"
}
val selection = rememberPillSelectorSelection(
selectedIndex = selectedIndex,
- itemCount = itemCount,
+ keys = entries.keys,
)
+ val currentOnItemSelected = rememberUpdatedState(onItemSelected)
+ val onIndexSelected: (index: Int) -> Unit = remember(entries) {
+ { index ->
+ val entry = entries.renderedEntries.getOrNull(index)
+ if (entry != null && entry.isShown) {
+ currentOnItemSelected.value(entry.item)
+ }
+ }
+ }
PillSelectorLayers(
+ entries = entries.renderedEntries,
selectedIndex = selectedIndex,
- itemCount = itemCount,
- onItemSelected = onItemSelected,
+ onIndexSelected = onIndexSelected,
selection = selection,
enabled = enabled,
spacing = spacing,
@@ -83,27 +113,38 @@ internal fun PillSelector(
item = item,
modifier = modifier.pillSelectorInput(
selection = selection,
- enabled = enabled && draggable && itemCount > 1,
- onItemSelected = onItemSelected,
+ enabled = enabled && draggable && entries.renderedEntries.size > 1,
+ onItemSelected = onIndexSelected,
),
)
}
@Composable
-private fun PillSelectorLayers(
+private fun
- PillSelectorLayers(
+ entries: List>,
selectedIndex: Int,
- itemCount: Int,
- onItemSelected: (index: Int) -> Unit,
- selection: PillSelectorSelection,
+ onIndexSelected: (index: Int) -> Unit,
+ selection: PillSelectorSelection<*>,
enabled: Boolean,
spacing: PillSelectorSpacing,
colors: PillSelectorColors,
- item: @Composable PillSelectorItemScope.(index: Int) -> Unit,
+ item: @Composable PillSelectorItemScope.(item: Item) -> Unit,
modifier: Modifier = Modifier,
) {
val currentColors = rememberUpdatedState(colors)
val alpha by animateEnabledAlpha(enabled = enabled)
+ val halfGap = spacing.gap / 2
+ // Two separately rounded half gaps can differ from Row's full gap by a pixel.
+ val remainingGap = with(LocalDensity.current) {
+ (spacing.gap.roundToPx() - halfGap.roundToPx()).toDp()
+ }
+ val edgePadding = PaddingValues(horizontal = halfGap)
+ val itemPadding = PaddingValues(
+ start = halfGap,
+ end = remainingGap,
+ )
+
Row(
modifier = modifier
.graphicsLayer { this.alpha = alpha }
@@ -111,7 +152,10 @@ private fun PillSelectorLayers(
color = colors.containerColor,
shape = CircleShape,
)
- .padding(all = CONTAINER_PADDING)
+ .padding(
+ horizontal = CONTAINER_PADDING - halfGap,
+ vertical = CONTAINER_PADDING,
+ )
.selectableGroup()
.drawBehind {
drawHighlight(
@@ -120,28 +164,89 @@ private fun PillSelectorLayers(
color = currentColors.value.selectedContainerColor,
)
},
- horizontalArrangement = Arrangement.spacedBy(space = spacing.gap),
verticalAlignment = Alignment.CenterVertically,
) {
- repeat(itemCount) { index ->
- val scope = remember(index, selection) {
- PillSelectorItemScope(
+ entries.forEachIndexed { index, entry ->
+ key(entry.key) {
+ PillSelectorEntryItem(
+ entry = entry,
index = index,
+ selected = index == selectedIndex,
+ onIndexSelected = onIndexSelected,
selection = selection,
- colors = currentColors,
+ enabled = enabled,
+ padding = when (index) {
+ entries.lastIndex -> edgePadding
+ else -> itemPadding
+ },
+ colors = colors,
+ currentColors = currentColors,
+ item = item,
)
}
+ }
+ }
+}
+
+@Composable
+private fun
- RowScope.PillSelectorEntryItem(
+ entry: PillSelectorEntry
- ,
+ index: Int,
+ selected: Boolean,
+ onIndexSelected: (index: Int) -> Unit,
+ selection: PillSelectorSelection<*>,
+ enabled: Boolean,
+ padding: PaddingValues,
+ colors: PillSelectorColors,
+ currentColors: State,
+ item: @Composable PillSelectorItemScope.(item: Item) -> Unit,
+) {
+ val density = LocalDensity.current
+ val layoutDirection = LocalLayoutDirection.current
+ val leftPadding = with(density) { padding.calculateLeftPadding(layoutDirection).roundToPx() }
+ val rightPadding = with(density) { padding.calculateRightPadding(layoutDirection).roundToPx() }
+ var contentWidth by remember { mutableIntStateOf(0) }
+ val scope = remember(index, selection) {
+ PillSelectorItemScope(
+ index = index,
+ selection = selection,
+ colors = currentColors,
+ )
+ }
- PillSelectorItem(
- selected = index == selectedIndex,
- enabled = enabled,
- onClick = { onItemSelected(index) },
- selection = selection,
+ AnimatedVisibility(
+ visibleState = entry.visibility,
+ modifier = Modifier.onPlaced { coordinates ->
+ val start = coordinates.positionInParent().x
+ val width = coordinates.size.width
+ val contentOffset = Alignment.CenterHorizontally.align(
+ size = contentWidth,
+ space = width,
+ layoutDirection = layoutDirection,
+ )
+
+ selection.geometry.place(
index = index,
- colors = colors,
- ) {
- scope.item(index)
- }
+ start = start + leftPadding,
+ width = (width - leftPadding - rightPadding).coerceAtLeast(0).toFloat(),
+ contentStart = start + contentOffset + leftPadding,
+ )
+ },
+ enter = EXPAND_HORIZONTALLY,
+ exit = SHRINK_HORIZONTALLY,
+ ) {
+ PillSelectorItem(
+ selected = selected,
+ enabled = enabled && entry.isShown,
+ onClick = { onIndexSelected(index) },
+ selection = selection,
+ index = index,
+ colors = colors,
+ modifier = Modifier
+ .onSizeChanged { size -> contentWidth = size.width }
+ .padding(padding),
+ ) {
+ scope.item(entry.item)
}
}
}
@@ -151,30 +256,23 @@ private fun PillSelectorItem(
selected: Boolean,
enabled: Boolean,
onClick: () -> Unit,
- selection: PillSelectorSelection,
+ selection: PillSelectorSelection<*>,
index: Int,
colors: PillSelectorColors,
+ modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
val interactionSource = remember { MutableInteractionSource() }
Box(
- modifier = Modifier
- .onPlaced { coordinates ->
- selection.geometry.place(
- index = index,
- start = coordinates.positionInParent().x,
- width = coordinates.size.width.toFloat(),
- )
- }
- .selectable(
- selected = selected,
- interactionSource = interactionSource,
- indication = null,
- enabled = enabled,
- role = Role.RadioButton,
- onClick = onClick,
- ),
+ modifier = modifier.selectable(
+ selected = selected,
+ interactionSource = interactionSource,
+ indication = null,
+ enabled = enabled,
+ role = Role.RadioButton,
+ onClick = onClick,
+ ),
contentAlignment = Alignment.Center,
) {
Spacer(
@@ -192,7 +290,7 @@ private fun PillSelectorItem(
highlightContentColor = colors.selectedContentColor,
highlightStart = {
selection.geometry.start(selection = selection.value) -
- selection.geometry.itemStart(index = index)
+ selection.geometry.contentStart(index = index)
},
highlightWidth = { selection.geometry.width(selection = selection.value) },
),
@@ -226,12 +324,13 @@ private fun PreviewTextSelector() {
var currentIndex by remember { mutableIntStateOf(1) }
PillSelector(
- selectedIndex = currentIndex,
- itemCount = labels.size,
- onItemSelected = { index -> currentIndex = index },
- ) { index ->
+ items = labels,
+ key = { it },
+ selected = labels[currentIndex],
+ onItemSelected = { label -> currentIndex = labels.indexOf(label) },
+ ) { label ->
BasicText(
- text = labels[index],
+ text = label,
modifier = Modifier.padding(
horizontal = 16.dp,
vertical = 8.dp,
@@ -251,17 +350,18 @@ private fun PreviewCircleSelector(
var currentIndex by remember { mutableIntStateOf(selectedIndex) }
PillSelector(
- selectedIndex = currentIndex,
- itemCount = labels.size,
- onItemSelected = { index -> currentIndex = index },
+ items = labels,
+ key = { it },
+ selected = labels[currentIndex],
+ onItemSelected = { label -> currentIndex = labels.indexOf(label) },
enabled = enabled,
- ) { index ->
+ ) { label ->
Box(
modifier = Modifier.size(size = 48.dp),
contentAlignment = Alignment.Center,
) {
BasicText(
- text = labels[index],
+ text = label,
style = MaterialTheme.typography.labelLarge,
color = contentColor,
)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorEntries.kt b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorEntries.kt
new file mode 100644
index 000000000..488c858ea
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorEntries.kt
@@ -0,0 +1,128 @@
+package app.grapheneos.camera.ui.components.pillselector
+
+import androidx.compose.animation.core.MutableTransitionState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.Stable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshotFlow
+
+@Stable
+internal class PillSelectorEntry
- (
+ val key: Key,
+ item: Item,
+ isEntering: Boolean,
+) {
+
+ var item by mutableStateOf(item)
+ private set
+
+ val visibility = MutableTransitionState(initialState = !isEntering).apply {
+ targetState = true
+ }
+
+ val isShown: Boolean
+ get() {
+ return visibility.targetState
+ }
+
+ val isGone: Boolean
+ get() {
+ return !visibility.targetState && !visibility.currentState && visibility.isIdle
+ }
+
+ fun show(item: Item) {
+ this.item = item
+ visibility.targetState = true
+ }
+
+ fun hide() {
+ visibility.targetState = false
+ }
+}
+
+@Stable
+internal class PillSelectorEntries
- {
+
+ var renderedEntries by mutableStateOf
>>(emptyList())
+ private set
+
+ var keys by mutableStateOf>(emptyList())
+ private set
+
+ private var shownItems by mutableStateOf>(emptyList())
+ private var shownKeys by mutableStateOf>(emptyList())
+
+ fun update(
+ items: List- ,
+ keyOf: (Item) -> Key,
+ ) {
+ val itemKeys = items.map(keyOf)
+ if (items == shownItems && itemKeys == shownKeys) return
+
+ val activeKeys = itemKeys.toSet()
+ require(activeKeys.size == items.size) {
+ "Each item must have a distinct key, were $itemKeys"
+ }
+
+ val previousByKey = renderedEntries.associateBy { entry -> entry.key }
+ val entries = items.mapIndexed { index, item ->
+ val key = itemKeys[index]
+ previousByKey[key]?.apply { show(item) } ?: PillSelectorEntry(
+ key = key,
+ item = item,
+ isEntering = renderedEntries.isNotEmpty(),
+ )
+ }.toMutableList()
+
+ // Keep each exiting entry immediately before its next surviving neighbor.
+ var insertionIndex = entries.size
+ for (entry in renderedEntries.asReversed()) {
+ if (entry.key in activeKeys) {
+ insertionIndex = entries.indexOf(entry)
+ } else {
+ entry.hide()
+ entries.add(insertionIndex, entry)
+ }
+ }
+
+ shownKeys = itemKeys
+ shownItems = items
+ replace(entries)
+ }
+
+ suspend fun removeGoneEntries() {
+ snapshotFlow { renderedEntries.any { entry -> entry.isGone } }.collect { hasGone ->
+ if (hasGone) {
+ replace(entries = renderedEntries.filterNot { entry -> entry.isGone })
+ }
+ }
+ }
+
+ private fun replace(entries: List>) {
+ renderedEntries = entries
+ keys = entries.map { entry -> entry.key }
+ }
+}
+
+@Composable
+internal fun
- rememberPillSelectorEntries(
+ items: List
- ,
+ key: (item: Item) -> Key,
+): PillSelectorEntries
- {
+ val entries = remember { PillSelectorEntries
- () }
+
+ entries.update(
+ items = items,
+ keyOf = key,
+ )
+
+ LaunchedEffect(entries) {
+ entries.removeGoneEntries()
+ }
+
+ return entries
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorGeometry.kt b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorGeometry.kt
index 0870f7ab8..d8a0f80cb 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorGeometry.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorGeometry.kt
@@ -1,5 +1,9 @@
package app.grapheneos.camera.ui.components.pillselector
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
import androidx.compose.ui.util.lerp
import kotlin.math.ceil
import kotlin.math.floor
@@ -10,56 +14,67 @@ internal class PillSelectorGeometry(
val lastIndex: Int
get() {
- return starts.lastIndex
+ return slots.lastIndex
}
- private val starts = FloatArray(itemCount)
- private val widths = FloatArray(itemCount)
+ private var slots by mutableStateOf(List(itemCount) { Slot() })
+
+ fun resize(itemCount: Int) {
+ val previous = slots
+
+ slots = List(itemCount) { index -> previous.getOrNull(index) ?: Slot() }
+ }
fun place(
index: Int,
start: Float,
width: Float,
+ contentStart: Float,
) {
- starts[index] = start
- widths[index] = width
+ val slot = slots[index]
+
+ slot.start = start
+ slot.width = width
+ slot.contentStart = contentStart
}
fun start(selection: Float): Float {
- return interpolate(
- values = starts,
- selection = selection,
- )
+ return interpolate(selection = selection) { slot -> slot.start }
}
fun width(selection: Float): Float {
- return interpolate(
- values = widths,
- selection = selection,
- )
+ return interpolate(selection = selection) { slot -> slot.width }
}
- fun itemStart(index: Int): Float {
- return starts[index]
+ fun contentStart(index: Int): Float {
+ return slots[index].contentStart
}
fun pitch(selection: Float): Float {
+ if (lastIndex < 1) return 0f
+
val from = floor(selection).toInt().coerceIn(0, lastIndex - 1)
- return starts[from + 1] - starts[from]
+ return slots[from + 1].start - slots[from].start
}
- private fun interpolate(
- values: FloatArray,
+ private inline fun interpolate(
selection: Float,
+ value: (Slot) -> Float,
): Float {
- val from = floor(selection).toInt().coerceIn(0, values.lastIndex)
- val to = ceil(selection).toInt().coerceIn(0, values.lastIndex)
+ val from = floor(selection).toInt().coerceIn(0, lastIndex)
+ val to = ceil(selection).toInt().coerceIn(0, lastIndex)
return lerp(
- start = values[from],
- stop = values[to],
+ start = value(slots[from]),
+ stop = value(slots[to]),
fraction = selection - from,
)
}
+
+ private class Slot {
+ var start by mutableFloatStateOf(0f)
+ var width by mutableFloatStateOf(0f)
+ var contentStart by mutableFloatStateOf(0f)
+ }
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorItemScope.kt b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorItemScope.kt
index e2190b2da..5c07b4529 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorItemScope.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/PillSelectorItemScope.kt
@@ -9,7 +9,7 @@ import kotlin.math.abs
@Stable
internal class PillSelectorItemScope(
private val index: Int,
- private val selection: PillSelectorSelection,
+ private val selection: PillSelectorSelection<*>,
colors: State,
) {
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/gesture/PillSelectorInput.kt b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/gesture/PillSelectorInput.kt
index d0510cba3..8926ae698 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/gesture/PillSelectorInput.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/gesture/PillSelectorInput.kt
@@ -5,7 +5,7 @@ import androidx.compose.foundation.gestures.draggable
import androidx.compose.ui.Modifier
internal fun Modifier.pillSelectorInput(
- selection: PillSelectorSelection,
+ selection: PillSelectorSelection<*>,
enabled: Boolean,
onItemSelected: (index: Int) -> Unit,
): Modifier {
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/gesture/PillSelectorSelection.kt b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/gesture/PillSelectorSelection.kt
index b629e7eb6..aafa405e7 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/gesture/PillSelectorSelection.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/pillselector/gesture/PillSelectorSelection.kt
@@ -13,6 +13,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
@@ -22,13 +23,13 @@ import app.grapheneos.camera.ui.components.pillselector.PillSelectorGeometry
import kotlin.math.roundToInt
@Stable
-internal class PillSelectorSelection(
+internal class PillSelectorSelection(
initialIndex: Int,
- itemCount: Int,
+ keys: List,
private val hapticFeedback: State,
) {
- val geometry = PillSelectorGeometry(itemCount = itemCount)
+ val geometry = PillSelectorGeometry(itemCount = keys.size)
val dragState = DraggableState { pixels -> dragBy(pixels = pixels) }
val dragInteractions: MutableInteractionSource = DragEndInteractions(
onStop = { isDragCanceled = false },
@@ -48,10 +49,34 @@ internal class PillSelectorSelection(
var revision by mutableIntStateOf(0)
private set
- private val animatable = Animatable(initialValue = initialIndex.toFloat())
+ private var animatable by mutableStateOf(Animatable(initialValue = initialIndex.toFloat()))
+ private var keys by mutableStateOf(keys)
private var dragValue by mutableStateOf(null)
private var isDragCanceled = false
+ fun rebase(
+ index: Int,
+ keys: List,
+ ) {
+ Snapshot.withoutReadObservation {
+ if (keys == this.keys) return@withoutReadObservation
+
+ val position = positionIn(
+ newKeys = keys,
+ selectedIndex = index,
+ )
+ this.keys = keys
+ geometry.resize(itemCount = keys.size)
+ animatable = Animatable(initialValue = position)
+
+ if (isDragging) {
+ dragValue = position
+ }
+
+ revision++
+ }
+ }
+
fun startDrag() {
dragValue = animatable.value
}
@@ -74,9 +99,28 @@ internal class PillSelectorSelection(
)
}
+ private fun positionIn(
+ newKeys: List,
+ selectedIndex: Int,
+ ): Float {
+ val position = value
+ val anchorIndex = position.roundToInt().coerceIn(keys.indices)
+ val newAnchorIndex = newKeys.indexOf(keys[anchorIndex])
+ if (newAnchorIndex < 0) {
+ return selectedIndex.toFloat()
+ }
+
+ val offsetFromAnchor = position - anchorIndex
+ return (newAnchorIndex + offsetFromAnchor)
+ .coerceIn(0f, newKeys.lastIndex.toFloat())
+ }
+
private fun dragBy(pixels: Float) {
val previous = dragValue ?: return
- val items = pixels / geometry.pitch(selection = previous)
+ val pitch = geometry.pitch(selection = previous)
+ if (pitch == 0f) return
+
+ val items = pixels / pitch
val next = (previous + items).coerceIn(0f, geometry.lastIndex.toFloat())
dragValue = next
@@ -87,35 +131,29 @@ internal class PillSelectorSelection(
}
@Composable
-internal fun rememberPillSelectorSelection(
+internal fun rememberPillSelectorSelection(
selectedIndex: Int,
- itemCount: Int,
-): PillSelectorSelection {
+ keys: List,
+): PillSelectorSelection {
val currentHapticFeedback = rememberUpdatedState(LocalHapticFeedback.current)
- val selection = remember(itemCount) {
+ val selection = remember {
PillSelectorSelection(
initialIndex = selectedIndex,
- itemCount = itemCount,
+ keys = keys,
hapticFeedback = currentHapticFeedback,
)
}
- PillSelectorSyncEffect(
- selection = selection,
- selectedIndex = selectedIndex,
+ selection.rebase(
+ index = selectedIndex,
+ keys = keys,
)
- return selection
-}
-
-@Composable
-private fun PillSelectorSyncEffect(
- selection: PillSelectorSelection,
- selectedIndex: Int,
-) {
if (!selection.isDragging) {
LaunchedEffect(selection, selectedIndex, selection.revision) {
selection.animateTo(index = selectedIndex)
}
}
+
+ return selection
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/ruler/RulerState.kt b/app/src/main/java/app/grapheneos/camera/ui/components/ruler/RulerState.kt
index 5eb80fe7e..0e0e2c216 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/ruler/RulerState.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/ruler/RulerState.kt
@@ -123,18 +123,22 @@ internal abstract class RulerState(
to: Float,
)
- protected suspend fun animatePosition(
+ protected suspend fun syncPosition(
target: Float,
onStart: () -> Unit,
+ animated: Boolean = true,
) {
mutex.mutate {
onStart()
- animate(
- initialValue = position,
- targetValue = target,
- animationSpec = SETTLE_SPEC,
- ) { value, _ ->
- position = value
+ when {
+ animated -> animate(
+ initialValue = position,
+ targetValue = target,
+ animationSpec = SETTLE_SPEC,
+ ) { value, _ ->
+ position = value
+ }
+ else -> position = target
}
}
}
@@ -145,6 +149,11 @@ internal abstract class RulerState(
bindings.onValueChangeFinished.value()
}
+ protected fun resetPosition(position: Float) {
+ this.position = position
+ revision++
+ }
+
protected fun commit(value: Float) {
bindings.onValueChange.value(value)
bindings.onValueChangeFinished.value()
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/segmentedicontoggle/SegmentedIconToggle.kt b/app/src/main/java/app/grapheneos/camera/ui/components/segmentedicontoggle/SegmentedIconToggle.kt
index 54e887009..418376a96 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/segmentedicontoggle/SegmentedIconToggle.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/segmentedicontoggle/SegmentedIconToggle.kt
@@ -49,17 +49,18 @@ internal fun SegmentedIconToggle(
colors: PillSelectorColors = PillSelectorColors.fromSurfaceTheme(),
) {
PillSelector(
- selectedIndex = selectedIndex,
- itemCount = options.size,
- onItemSelected = onOptionSelected,
+ items = options,
+ key = { it },
+ selected = options[selectedIndex],
+ onItemSelected = { option -> onOptionSelected(options.indexOf(option)) },
modifier = modifier,
enabled = enabled,
draggable = true,
spacing = PillSelectorSpacing.Joined,
colors = colors,
- ) { index ->
+ ) { option ->
SegmentedIconToggleIcon(
- option = options[index],
+ option = option,
color = contentColor,
)
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomControl.kt b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomControl.kt
index ba0915704..0c0844695 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomControl.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomControl.kt
@@ -14,9 +14,11 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
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.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalLayoutDirection
@@ -44,9 +46,11 @@ import app.grapheneos.camera.ui.core.preview.CameraPreviewColumn
* Collapsed, it shows [stops], and a tap on one reports it through [onStopClick]. A horizontal
* swipe or a long press on the stops calls [onExpand], and the same touch goes on moving the value
* as on the expanded bar. [expanded] belongs to the caller: it expands on [onExpand] and collapses
- * whenever the screen decides to. [interactionSource] holds a press for as long as a finger is on
- * the control, so a screen that collapses on a timer can wait for the release. [expandLabel] names
+ * whenever the screen decides to. [onPressChanged] reports a hold until release or cancellation,
+ * so a screen that collapses on a timer can wait for the release. [expandLabel] names
* the accessibility action that expands the stops, the only way to the bar without a gesture.
+ * Set [animateValueChanges] to false when [value] is already driven by a continuous gesture.
+ * Set [showContainer] to false when the caller draws the container behind the control.
*/
@Composable
internal fun ZoomControl(
@@ -61,7 +65,11 @@ internal fun ZoomControl(
expandLabel: String,
modifier: Modifier = Modifier,
enabled: Boolean = true,
+ showCurrentValue: Boolean = true,
+ showContainer: Boolean = true,
+ animateValueChanges: Boolean = true,
onValueChangeFinished: () -> Unit = {},
+ onPressChanged: (Boolean) -> Unit = {},
barColors: ZoomBarColors = ZoomBarColors.fromTheme(),
stopsColors: PillSelectorColors = PillSelectorColors.fromTheme(),
interactionSource: MutableInteractionSource? = null,
@@ -83,18 +91,18 @@ internal fun ZoomControl(
onValueChangeFinished = onValueChangeFinished,
tickSpacing = metrics.tickSpacing,
),
+ animateValueChanges = animateValueChanges,
)
val expander = rememberZoomControlExpander(
enabled = enabled,
expanded = expanded,
onExpand = onExpand,
+ onPressChanged = onPressChanged,
)
val alpha by animateEnabledAlpha(enabled = enabled)
- val valueDescription = rememberZoomFormat().format(value = value) + valueSuffix
ZoomControlLayers(
value = value,
- valueDescription = valueDescription,
valueRange = valueRange,
stops = stops,
valueSuffix = valueSuffix,
@@ -107,6 +115,8 @@ internal fun ZoomControl(
},
expandLabel = expandLabel,
enabled = enabled,
+ showCurrentValue = showCurrentValue,
+ showContainer = showContainer,
alpha = { alpha },
state = state,
scale = scale,
@@ -127,7 +137,6 @@ internal fun ZoomControl(
@Composable
private fun ZoomControlLayers(
value: Float,
- valueDescription: String,
valueRange: ClosedFloatingPointRange,
stops: List,
valueSuffix: String,
@@ -136,6 +145,8 @@ private fun ZoomControlLayers(
onStopClick: (Float) -> Unit,
expandLabel: String,
enabled: Boolean,
+ showCurrentValue: Boolean,
+ showContainer: Boolean,
alpha: () -> Float,
state: ZoomBarState,
scale: ZoomBarScale,
@@ -145,19 +156,23 @@ private fun ZoomControlLayers(
interactionSource: MutableInteractionSource,
modifier: Modifier = Modifier,
) {
+ val valueDescription = rememberZoomFormat().format(value = value) + valueSuffix
+
Box(
- modifier = modifier,
+ modifier = modifier.clip(shape = CircleShape),
contentAlignment = Alignment.Center,
) {
- Spacer(
- modifier = Modifier
- .matchParentSize()
- .graphicsLayer { this.alpha = alpha() }
- .background(
- color = barColors.containerColor,
- shape = CircleShape,
- ),
- )
+ if (showContainer) {
+ Spacer(
+ modifier = Modifier
+ .matchParentSize()
+ .graphicsLayer { this.alpha = alpha() }
+ .background(
+ color = barColors.containerColor,
+ shape = CircleShape,
+ ),
+ )
+ }
AnimatedContent(
targetState = expanded,
transitionSpec = { revealResizing() },
@@ -185,6 +200,7 @@ private fun ZoomControlLayers(
onStopClick = onStopClick,
expandLabel = expandLabel,
enabled = enabled,
+ showCurrentValue = showCurrentValue,
colors = stopsColors,
)
}
@@ -201,20 +217,27 @@ private fun ZoomControlStops(
onStopClick: (Float) -> Unit,
expandLabel: String,
enabled: Boolean,
+ showCurrentValue: Boolean,
colors: PillSelectorColors,
) {
+ val currentOnExpand = rememberUpdatedState(onExpand)
+ val customActions = remember(expandLabel) {
+ listOf(
+ CustomAccessibilityAction(label = expandLabel) {
+ currentOnExpand.value()
+ true
+ },
+ )
+ }
+
ZoomStops(
value = value,
stops = stops,
valueSuffix = valueSuffix,
onStopClick = onStopClick,
enabled = enabled,
- customActions = listOf(
- CustomAccessibilityAction(label = expandLabel) {
- onExpand()
- true
- },
- ),
+ showCurrentValue = showCurrentValue,
+ customActions = customActions,
colors = colors.copy(containerColor = Color.Transparent),
)
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomStopList.kt b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomStopList.kt
index b07400d64..28b9ead08 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomStopList.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomStopList.kt
@@ -5,7 +5,7 @@ import kotlin.math.max
@Immutable
internal class ZoomStopList(
- val stops: List,
+ private val stops: List,
) {
init {
@@ -20,4 +20,20 @@ internal class ZoomStopList(
fun selectedIndex(value: Float): Int {
return max(0, stops.indexOfLast { stop -> stop <= value })
}
+
+ fun keyOf(stop: Float): Key {
+ return when {
+ stop == stops.first() && stop < 1f -> Key.WideAngle
+ else -> Key.Ratio(value = stop)
+ }
+ }
+
+ sealed interface Key {
+
+ data object WideAngle : Key
+
+ data class Ratio(
+ val value: Float,
+ ) : Key
+ }
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomStops.kt b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomStops.kt
index 9466796b7..0ebb41add 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomStops.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/ZoomStops.kt
@@ -1,5 +1,6 @@
package app.grapheneos.camera.ui.components.zoom
+import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -9,9 +10,9 @@ import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
-import androidx.compose.runtime.key
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -31,6 +32,7 @@ import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import app.grapheneos.camera.ui.components.motion.LocalContentRotation
+import app.grapheneos.camera.ui.components.motion.SETTLE_SPEC
import app.grapheneos.camera.ui.components.pillselector.PillSelector
import app.grapheneos.camera.ui.components.pillselector.PillSelectorColors
import app.grapheneos.camera.ui.components.pillselector.PillSelectorItemScope
@@ -45,8 +47,10 @@ private const val SELECTED_LABEL_SCALE = 1.15f
/**
* The selected stop is the last one at or below [value], or the first one below all of them. It
- * shows [value] followed by [valueSuffix]; the others show only their number. [onStopClick] reports
- * a tapped stop, and [value] changes only when the caller sets it.
+ * shows [value] followed by [valueSuffix], or its preset when [showCurrentValue] is false.
+ * The others show only their number. [onStopClick] reports a tapped stop, and [value] changes
+ * only when the caller sets it. A first stop below 1× keeps its slot when its ratio changes, with
+ * its label crossfading; other stops that come or go grow in or shrink away.
*/
@Composable
internal fun ZoomStops(
@@ -56,6 +60,7 @@ internal fun ZoomStops(
onStopClick: (Float) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
+ showCurrentValue: Boolean = true,
customActions: List = emptyList(),
colors: PillSelectorColors = PillSelectorColors.fromTheme(),
) {
@@ -68,37 +73,68 @@ internal fun ZoomStops(
fontFeatureSettings = TABULAR_FIGURES,
)
- key(stops) {
- PillSelector(
- selectedIndex = selectedIndex,
- itemCount = stops.size,
- onItemSelected = { index -> onStopClick(stops[index]) },
- modifier = modifier,
- enabled = enabled,
- colors = colors,
- ) { index ->
- val isSelected = index == selectedIndex
- val number = format.format(
- value = when {
- isSelected -> value
- else -> stops[index]
- },
- )
+ val selectedStop = stops[selectedIndex]
+ val currentValue = rememberUpdatedState(value)
- ZoomStopLabel(
- text = when {
- isSelected -> number + valueSuffix
- else -> number
- },
- description = number + valueSuffix,
- customActions = customActions,
- style = when {
- isSelected -> style.copy(fontWeight = FontWeight.Bold)
- else -> style
- },
- scope = this,
- )
- }
+ PillSelector(
+ items = stops,
+ key = stopList::keyOf,
+ selected = selectedStop,
+ onItemSelected = onStopClick,
+ modifier = modifier,
+ enabled = enabled,
+ colors = colors,
+ ) { stop ->
+ ZoomStopContent(
+ stop = stop,
+ isSelected = stop == selectedStop,
+ currentValue = { currentValue.value },
+ showCurrentValue = showCurrentValue,
+ valueSuffix = valueSuffix,
+ customActions = customActions,
+ format = format,
+ style = style,
+ scope = this,
+ )
+ }
+}
+
+@Composable
+private fun ZoomStopContent(
+ stop: Float,
+ isSelected: Boolean,
+ currentValue: () -> Float,
+ showCurrentValue: Boolean,
+ valueSuffix: String,
+ customActions: List,
+ format: ZoomFormat,
+ style: TextStyle,
+ scope: PillSelectorItemScope,
+) {
+ Crossfade(
+ targetState = stop,
+ animationSpec = SETTLE_SPEC,
+ ) { shownStop ->
+ val number = format.format(
+ value = when {
+ isSelected && showCurrentValue -> currentValue()
+ else -> shownStop
+ },
+ )
+
+ ZoomStopLabel(
+ text = when {
+ isSelected -> number + valueSuffix
+ else -> number
+ },
+ description = number + valueSuffix,
+ customActions = customActions,
+ style = when {
+ isSelected -> style.copy(fontWeight = FontWeight.Bold)
+ else -> style
+ },
+ scope = scope,
+ )
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/gesture/ZoomBarState.kt b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/gesture/ZoomBarState.kt
index 94adcc2bc..d6d296f6e 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/gesture/ZoomBarState.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/gesture/ZoomBarState.kt
@@ -1,6 +1,7 @@
package app.grapheneos.camera.ui.components.zoom.gesture
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
@@ -19,8 +20,9 @@ import kotlin.math.sign
@Stable
internal class ZoomBarState(
initialValue: Float,
- private val currentScale: State,
bindings: RulerBindings,
+ private val currentScale: State,
+ private val animateValueChanges: State,
) : RulerState(
initialPosition = currentScale.value.position(value = initialValue),
currentScale = currentScale,
@@ -28,6 +30,7 @@ internal class ZoomBarState(
) {
private var reportedValue by mutableFloatStateOf(initialValue)
+ private var previousScale = currentScale.value
private var detentTravel = 0f
override fun step(ticks: Int): Boolean {
@@ -59,12 +62,13 @@ internal class ZoomBarState(
}
override suspend fun syncTo(value: Float) {
- animatePosition(
+ syncPosition(
target = currentScale.value.position(value = value),
onStart = {
detentTravel = 0f
reportedValue = value
},
+ animated = animateValueChanges.value,
)
}
@@ -102,6 +106,16 @@ internal class ZoomBarState(
}
}
+ fun updateScale() {
+ val scale = currentScale.value
+ if (scale != previousScale) {
+ previousScale = scale
+ detentTravel = 0f
+ reportedValue = bindings.value.value
+ resetPosition(position = scale.position(value = reportedValue))
+ }
+ }
+
private fun holdAt(
stop: Float,
travel: Float,
@@ -134,16 +148,21 @@ internal fun rememberZoomBarState(
value: Float,
scale: ZoomBarScale,
bindings: RulerBindings,
+ animateValueChanges: Boolean = true,
): ZoomBarState {
val currentScale = rememberUpdatedState(scale)
- val state = remember(scale) {
+ val currentAnimateValueChanges = rememberUpdatedState(animateValueChanges)
+ val state = remember {
ZoomBarState(
initialValue = value,
- currentScale = currentScale,
bindings = bindings,
+ currentScale = currentScale,
+ animateValueChanges = currentAnimateValueChanges,
)
}
+ SideEffect { state.updateScale() }
+
RulerSyncEffect(
state = state,
value = value,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/gesture/ZoomControlExpander.kt b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/gesture/ZoomControlExpander.kt
index 31f9910ae..e9d222c5e 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/components/zoom/gesture/ZoomControlExpander.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/components/zoom/gesture/ZoomControlExpander.kt
@@ -25,6 +25,7 @@ internal class ZoomControlExpander(
private val enabled: State,
private val expanded: State,
private val onExpand: State<() -> Unit>,
+ private val onPressChanged: State<(Boolean) -> Unit>,
private val hapticFeedback: State,
) {
@@ -36,6 +37,10 @@ internal class ZoomControlExpander(
onExpand.value()
}
+ fun reportPress(pressed: Boolean) {
+ onPressChanged.value(pressed)
+ }
+
fun expandOnDrag() {
if (isCollapsed()) {
expand()
@@ -55,10 +60,12 @@ internal fun rememberZoomControlExpander(
enabled: Boolean,
expanded: Boolean,
onExpand: () -> Unit,
+ onPressChanged: (Boolean) -> Unit,
): ZoomControlExpander {
val currentEnabled = rememberUpdatedState(enabled)
val currentExpanded = rememberUpdatedState(expanded)
val currentOnExpand = rememberUpdatedState(onExpand)
+ val currentOnPressChanged = rememberUpdatedState(onPressChanged)
val currentHapticFeedback = rememberUpdatedState(LocalHapticFeedback.current)
return remember {
@@ -66,6 +73,7 @@ internal fun rememberZoomControlExpander(
enabled = currentEnabled,
expanded = currentExpanded,
onExpand = currentOnExpand,
+ onPressChanged = currentOnPressChanged,
hapticFeedback = currentHapticFeedback,
)
}
@@ -88,21 +96,26 @@ internal fun Modifier.zoomControlInput(
)
.zoomControlPress(
expander = expander,
+ enabled = enabled,
interactionSource = interactionSource,
)
}
private fun Modifier.zoomControlPress(
expander: ZoomControlExpander,
+ enabled: Boolean,
interactionSource: MutableInteractionSource,
): Modifier {
- return pointerInput(expander, interactionSource) {
+ return pointerInput(expander, interactionSource, enabled) {
+ if (!enabled) return@pointerInput
+
awaitEachGesture {
val press = PressInteraction.Press(awaitFirstDown(requireUnconsumed = false).position)
var end: PressInteraction = PressInteraction.Cancel(press)
interactionSource.tryEmit(press)
try {
+ expander.reportPress(pressed = true)
val isLongPress = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {
waitForUpOrCancellation()
false
@@ -115,6 +128,7 @@ private fun Modifier.zoomControlPress(
end = PressInteraction.Release(press)
} finally {
interactionSource.tryEmit(end)
+ expander.reportPress(pressed = false)
}
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/core/screen/StateHolder.kt b/app/src/main/java/app/grapheneos/camera/ui/core/screen/StateHolder.kt
index 016df1522..4e2c21d69 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/core/screen/StateHolder.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/core/screen/StateHolder.kt
@@ -4,32 +4,47 @@ import androidx.annotation.MainThread
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
-import kotlinx.coroutines.flow.update
open class StateHolder(
initial: State,
) {
- private val derivations = mutableListOf<(State) -> Unit>()
+ private val derivations = mutableListOf<(previous: State, current: State) -> Unit>()
private val _state = MutableStateFlow(initial)
val state: StateFlow = _state.asStateFlow()
/**
* A flow of [map] applied to the state, recomputed within every [update], so it is current by
- * the time [update] returns. It only emits when its own value changes.
+ * the time [update] returns. It only emits when its own value changes. A change of the state
+ * that [isAffected] rejects leaves it as it was, without calling [map].
*/
@MainThread
- fun derive(map: (State) -> T): StateFlow {
+ fun derive(
+ isAffected: (previous: State, current: State) -> Boolean = { _, _ -> true },
+ map: (State) -> T,
+ ): StateFlow {
val derived = MutableStateFlow(map(_state.value))
- derivations += { state -> derived.value = map(state) }
+ derivations += { previous, current ->
+ if (isAffected(previous, current)) {
+ derived.value = map(current)
+ }
+ }
return derived.asStateFlow()
}
@MainThread
fun update(transform: (State) -> State) {
- _state.update(transform)
- derivations.forEach { derivation -> derivation(_state.value) }
+ val previous = _state.value
+ val current = transform(previous)
+ if (current != previous) {
+ _state.value = current
+
+ // A collector can update the state again from inside this loop or the line above.
+ derivations.forEach { derivation ->
+ derivation(previous, _state.value)
+ }
+ }
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryScaffold.kt b/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryScaffold.kt
index fe1cffa00..ee2594eb7 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryScaffold.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryScaffold.kt
@@ -66,7 +66,7 @@ internal fun GalleryScaffold(
content: @Composable (PaddingValues) -> Unit,
) {
val visibility = animateBarsVisibilityAsState(
- isVisible = uiState.chrome.showsBars && !isPanelVisible,
+ visible = uiState.chrome.showsBars && !isPanelVisible,
hidesInstantly = uiState.isZoomed || isPanelVisible,
)
val isShown by remember(visibility) { derivedStateOf { visibility.value > 0f } }
@@ -172,16 +172,16 @@ private fun ActionBarSlot(
@Composable
private fun animateBarsVisibilityAsState(
- isVisible: Boolean,
+ visible: Boolean,
hidesInstantly: Boolean,
): State {
return animateFloatAsState(
targetValue = when {
- isVisible -> 1f
+ visible -> 1f
else -> 0f
},
animationSpec = when {
- hidesInstantly && !isVisible -> snap()
+ hidesInstantly && !visible -> snap()
else -> CONTROLS_SPEC
},
)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryVideoOverlay.kt b/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryVideoOverlay.kt
index 946a9b0d2..a02421d0b 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryVideoOverlay.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryVideoOverlay.kt
@@ -55,7 +55,7 @@ internal fun GalleryVideoOverlay(
skip = playback.skip,
)
FastForwardIndicator(
- isVisible = playback.isFastForwarding,
+ visible = playback.isFastForwarding,
topPadding = PaddingValues(top = contentPadding.calculateTopPadding()),
modifier = Modifier.align(Alignment.TopCenter),
)
@@ -63,7 +63,7 @@ internal fun GalleryVideoOverlay(
playback = playback,
isMuted = video.isMuted,
position = position,
- isVisible = showsControls,
+ visible = showsControls,
showsButtons = playback.skip == null,
bottomPadding = PaddingValues(bottom = contentPadding.calculateBottomPadding()),
onAction = onAction,
@@ -101,12 +101,12 @@ private fun SkipIndicator(
@Composable
private fun FastForwardIndicator(
- isVisible: Boolean,
+ visible: Boolean,
topPadding: PaddingValues,
modifier: Modifier = Modifier,
) {
AnimatedVisibility(
- visible = isVisible,
+ visible = visible,
enter = fadeIn(),
exit = fadeOut(),
modifier = modifier
@@ -124,14 +124,14 @@ private fun PlaybackControls(
playback: VideoPlaybackUiModel.Active,
isMuted: Boolean,
position: () -> Duration,
- isVisible: Boolean,
+ visible: Boolean,
showsButtons: Boolean,
bottomPadding: PaddingValues,
onAction: (Action) -> Unit,
modifier: Modifier = Modifier,
) {
val visibility = remember { MutableTransitionState(initialState = false) }
- visibility.targetState = isVisible
+ visibility.targetState = visible
AnimatedVisibility(
visibleState = visibility,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryViewModel.kt b/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryViewModel.kt
index 1f293ce88..a07f36553 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryViewModel.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/gallery/screen/GalleryViewModel.kt
@@ -72,7 +72,9 @@ internal class GalleryViewModel @Inject constructor(
),
)
- override val uiState: StateFlow = stateHolder.derive(uiStateMapper::map)
+ override val uiState: StateFlow = stateHolder.derive { state ->
+ uiStateMapper.map(state)
+ }
override val effects: Flow = stateHolder.effects
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewControls.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewControls.kt
new file mode 100644
index 000000000..43b2d1563
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewControls.kt
@@ -0,0 +1,143 @@
+package app.grapheneos.camera.ui.previewoverlays.components
+
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.MaterialTheme
+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.tooling.preview.PreviewLightDark
+import androidx.compose.ui.unit.dp
+import app.grapheneos.camera.ui.components.motion.revealResizing
+import app.grapheneos.camera.ui.components.overlayiconbutton.OVERLAY_ICON_BUTTON_SIZE
+import app.grapheneos.camera.ui.core.preview.CameraPreviewViewfinder
+import app.grapheneos.camera.ui.core.theme.cameraColors
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction as Action
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.PreviewControlUiModel
+import kotlinx.collections.immutable.persistentListOf
+
+private val VALUE_SPACING = 12.dp
+private val RESET_BUTTON_GAP = 8.dp
+
+@Composable
+internal fun PreviewControls(
+ control: PreviewControlUiModel?,
+ zoomRatio: () -> Float,
+ onAction: (Action) -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ val zoom = control as? PreviewControlUiModel.Zoom
+ val exposure = control as? PreviewControlUiModel.Exposure
+
+ Column(
+ modifier = modifier,
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(space = VALUE_SPACING),
+ ) {
+ zoom?.let { visibleZoom ->
+ PreviewZoomValue(
+ zoom = visibleZoom,
+ zoomRatio = zoomRatio,
+ )
+ }
+ Box(modifier = Modifier.fillMaxWidth()) {
+ PreviewControlContainer(
+ control = control,
+ zoomRatio = zoomRatio,
+ onAction = onAction,
+ modifier = Modifier
+ .align(Alignment.Center)
+ .padding(horizontal = OVERLAY_ICON_BUTTON_SIZE + RESET_BUTTON_GAP * 2),
+ )
+ exposure?.let { visibleExposure ->
+ PreviewExposureReset(
+ exposure = visibleExposure,
+ onAction = onAction,
+ modifier = Modifier
+ .align(Alignment.CenterEnd)
+ .padding(end = RESET_BUTTON_GAP),
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun PreviewControlContainer(
+ control: PreviewControlUiModel?,
+ zoomRatio: () -> Float,
+ onAction: (Action) -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ Box(
+ modifier = modifier.clip(shape = CircleShape),
+ contentAlignment = Alignment.Center,
+ ) {
+ Spacer(
+ modifier = Modifier
+ .matchParentSize()
+ .background(color = MaterialTheme.cameraColors.overlayScrim),
+ )
+ AnimatedContent(
+ targetState = control,
+ transitionSpec = { revealResizing() },
+ contentAlignment = Alignment.Center,
+ contentKey = { visibleControl -> visibleControl?.let { it::class } },
+ ) { visibleControl ->
+ when (visibleControl) {
+ is PreviewControlUiModel.Exposure -> PreviewExposure(
+ exposure = visibleControl,
+ onAction = onAction,
+ showContainer = false,
+ )
+ is PreviewControlUiModel.Zoom -> PreviewZoom(
+ zoom = visibleControl,
+ zoomRatio = zoomRatio,
+ onAction = onAction,
+ showContainer = false,
+ )
+ null -> Unit
+ }
+ }
+ }
+}
+
+@PreviewLightDark
+@Composable
+private fun PreviewControlsPreview() {
+ CameraPreviewViewfinder {
+ Column(
+ modifier = Modifier.align(Alignment.Center),
+ verticalArrangement = Arrangement.spacedBy(space = 16.dp),
+ ) {
+ PreviewControls(
+ control = PreviewControlUiModel.Zoom(
+ range = 0.5f..8f,
+ presets = persistentListOf(0.5f, 1f, 2f),
+ isExpanded = true,
+ ),
+ zoomRatio = { 1.5f },
+ onAction = {},
+ )
+ PreviewControls(
+ control = PreviewControlUiModel.Exposure(
+ value = 0.5f,
+ range = -2f..2f,
+ steps = 23,
+ majorTickInterval = 6,
+ isResetVisible = true,
+ ),
+ zoomRatio = { 1f },
+ onAction = {},
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewExposure.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewExposure.kt
new file mode 100644
index 000000000..8c5a1b302
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewExposure.kt
@@ -0,0 +1,89 @@
+package app.grapheneos.camera.ui.previewoverlays.components
+
+import android.icu.text.NumberFormat
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.BrightnessHigh
+import androidx.compose.material.icons.outlined.BrightnessLow
+import androidx.compose.material.icons.outlined.RestartAlt
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalLocale
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.stateDescription
+import app.grapheneos.camera.R
+import app.grapheneos.camera.ui.components.adjustmentbar.AdjustmentBar
+import app.grapheneos.camera.ui.components.motion.POP_IN
+import app.grapheneos.camera.ui.components.motion.POP_OUT
+import app.grapheneos.camera.ui.components.overlayiconbutton.OverlayIconButton
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.ExposureAction as Action
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.PreviewControlUiModel
+
+private const val EXPOSURE_FRACTION_DIGITS = 2
+
+@Composable
+internal fun PreviewExposure(
+ exposure: PreviewControlUiModel.Exposure,
+ onAction: (Action) -> Unit,
+ modifier: Modifier = Modifier,
+ showContainer: Boolean = true,
+) {
+ val description = stringResource(R.string.exposure_compensation)
+ val valueDescription = exposureValueDescription(exposure.value)
+
+ AdjustmentBar(
+ value = exposure.value,
+ onValueChange = { value -> onAction(Action.ValueChanged(value)) },
+ valueRange = exposure.range,
+ steps = exposure.steps,
+ majorTickInterval = exposure.majorTickInterval,
+ startIcon = Icons.Outlined.BrightnessLow,
+ endIcon = Icons.Outlined.BrightnessHigh,
+ showContainer = showContainer,
+ onPressChanged = { pressed -> onAction(Action.PressChanged(isPressed = pressed)) },
+ modifier = modifier.semantics {
+ contentDescription = description
+ stateDescription = valueDescription
+ },
+ )
+}
+
+@Composable
+private fun exposureValueDescription(value: Float): String {
+ val locale = LocalLocale.current.platformLocale
+ val format = remember(locale) {
+ NumberFormat.getNumberInstance(locale).apply {
+ maximumFractionDigits = EXPOSURE_FRACTION_DIGITS
+ }
+ }
+
+ return stringResource(
+ R.string.exposure_value,
+ format.format(value.toDouble()),
+ )
+}
+
+@Composable
+internal fun PreviewExposureReset(
+ exposure: PreviewControlUiModel.Exposure,
+ onAction: (Action) -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ val description = stringResource(R.string.exposure_reset)
+
+ AnimatedVisibility(
+ visible = exposure.isResetVisible,
+ modifier = modifier,
+ enter = POP_IN,
+ exit = POP_OUT,
+ ) {
+ OverlayIconButton(
+ onClick = { onAction(Action.ResetClicked) },
+ icon = Icons.Outlined.RestartAlt,
+ modifier = Modifier.semantics { contentDescription = description },
+ )
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewFocus.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewFocus.kt
new file mode 100644
index 000000000..ff65b7183
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewFocus.kt
@@ -0,0 +1,51 @@
+package app.grapheneos.camera.ui.previewoverlays.components
+
+import androidx.compose.foundation.layout.absoluteOffset
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.Lock
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.key
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.tooling.preview.PreviewLightDark
+import androidx.compose.ui.unit.dp
+import app.grapheneos.camera.ui.components.focusindicator.FOCUS_INDICATOR_SIZE
+import app.grapheneos.camera.ui.components.focusindicator.FocusIndicator
+import app.grapheneos.camera.ui.core.preview.CameraPreviewViewfinder
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.FocusUiModel
+
+@Composable
+internal fun PreviewFocus(
+ focus: FocusUiModel,
+ modifier: Modifier = Modifier,
+) {
+ val density = LocalDensity.current
+ key(focus.requestId) {
+ val x = with(density) { focus.x.toDp() } - FOCUS_INDICATOR_SIZE / 2
+ val y = with(density) { focus.y.toDp() } - FOCUS_INDICATOR_SIZE / 2
+ FocusIndicator(
+ visible = focus.visible,
+ appearance = focus.appearance,
+ lockIcon = Icons.Outlined.Lock,
+ modifier = modifier.absoluteOffset(
+ x = x,
+ y = y,
+ ),
+ )
+ }
+}
+
+@PreviewLightDark
+@Composable
+private fun PreviewFocusPreview() {
+ val density = LocalDensity.current
+ CameraPreviewViewfinder {
+ PreviewFocus(
+ focus = FocusUiModel(
+ x = with(density) { 100.dp.toPx() },
+ y = with(density) { 100.dp.toPx() },
+ visible = true,
+ ),
+ )
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewLayer.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewLayer.kt
new file mode 100644
index 000000000..b5b16ef33
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewLayer.kt
@@ -0,0 +1,69 @@
+package app.grapheneos.camera.ui.previewoverlays.components
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
+import androidx.compose.foundation.layout.absoluteOffset
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.AbsoluteAlignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clipToBounds
+import androidx.compose.ui.tooling.preview.PreviewLightDark
+import androidx.compose.ui.unit.DpRect
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.height
+import androidx.compose.ui.unit.width
+import app.grapheneos.camera.ui.core.preview.CameraPreviewColumn
+
+@Composable
+internal fun BoxScope.PreviewLayer(
+ bounds: DpRect,
+ modifier: Modifier = Modifier,
+ content: @Composable BoxScope.() -> Unit,
+) {
+ Box(
+ modifier = modifier
+ .align(AbsoluteAlignment.TopLeft)
+ .absoluteOffset(
+ x = bounds.left,
+ y = bounds.top,
+ )
+ .size(
+ width = bounds.width,
+ height = bounds.height,
+ )
+ .clipToBounds(),
+ content = content,
+ )
+}
+
+@PreviewLightDark
+@Composable
+private fun PreviewLayerPreview() {
+ CameraPreviewColumn {
+ Box(
+ modifier = Modifier.size(
+ width = 280.dp,
+ height = 400.dp,
+ ),
+ ) {
+ PreviewLayer(
+ bounds = DpRect(
+ left = 20.dp,
+ top = 40.dp,
+ right = 260.dp,
+ bottom = 360.dp,
+ ),
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(color = MaterialTheme.colorScheme.surfaceContainerHighest),
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewLevel.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewLevel.kt
new file mode 100644
index 000000000..8f953244e
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewLevel.kt
@@ -0,0 +1,56 @@
+package app.grapheneos.camera.ui.previewoverlays.components
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.State
+import androidx.compose.runtime.derivedStateOf
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.tooling.preview.PreviewLightDark
+import app.grapheneos.camera.ui.components.levelindicator.LevelIndicator
+import app.grapheneos.camera.ui.components.motion.ProvideContentRotation
+import app.grapheneos.camera.ui.core.preview.CameraPreviewColumn
+import app.grapheneos.camera.ui.core.preview.CameraPreviewViewfinder
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.LevelUiState
+
+@Composable
+internal fun PreviewLevel(
+ level: State,
+ modifier: Modifier = Modifier,
+) {
+ val visible by remember(level) { derivedStateOf { level.value.visible } }
+ val mode by remember(level) { derivedStateOf { level.value.mode } }
+ val rotation by remember(level) { derivedStateOf { level.value.rotationDegrees } }
+
+ if (visible) {
+ ProvideContentRotation(degrees = rotation) {
+ LevelIndicator(
+ mode = mode,
+ roll = { level.value.rollDegrees },
+ pitch = { level.value.pitchDegrees },
+ modifier = modifier,
+ )
+ }
+ }
+}
+
+@PreviewLightDark
+@Composable
+private fun PreviewLevelPreview() {
+ CameraPreviewColumn {
+ CameraPreviewViewfinder {
+ PreviewLevel(
+ level = rememberUpdatedState(
+ LevelUiState(
+ visible = true,
+ rollDegrees = -4f,
+ pitchDegrees = 2f,
+ ),
+ ),
+ modifier = Modifier.align(Alignment.Center),
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewZoom.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewZoom.kt
new file mode 100644
index 000000000..04c24bbdb
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/PreviewZoom.kt
@@ -0,0 +1,61 @@
+package app.grapheneos.camera.ui.previewoverlays.components
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import app.grapheneos.camera.R
+import app.grapheneos.camera.ui.components.motion.POP_IN
+import app.grapheneos.camera.ui.components.motion.POP_OUT
+import app.grapheneos.camera.ui.components.valuechip.ValueChip
+import app.grapheneos.camera.ui.components.zoom.ZoomControl
+import app.grapheneos.camera.ui.components.zoom.rememberZoomFormat
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.ZoomAction as Action
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.PreviewControlUiModel
+
+@Composable
+internal fun PreviewZoom(
+ zoom: PreviewControlUiModel.Zoom,
+ zoomRatio: () -> Float,
+ onAction: (Action) -> Unit,
+ modifier: Modifier = Modifier,
+ showContainer: Boolean = true,
+) {
+ ZoomControl(
+ value = zoomRatio().coerceIn(zoom.range),
+ onValueChange = { ratio -> onAction(Action.RatioChanged(ratio)) },
+ valueRange = zoom.range,
+ stops = zoom.presets,
+ valueSuffix = stringResource(R.string.zoom_value_suffix),
+ expanded = zoom.isExpanded,
+ showCurrentValue = zoom.isCurrentValueVisible,
+ showContainer = showContainer,
+ animateValueChanges = !zoom.isPinching,
+ expandLabel = stringResource(R.string.zoom_expand),
+ onExpand = { onAction(Action.Expanded) },
+ onStopClick = { ratio -> onAction(Action.PresetSelected(ratio)) },
+ onPressChanged = { pressed ->
+ onAction(Action.ControlPressChanged(isPressed = pressed))
+ },
+ modifier = modifier,
+ )
+}
+
+@Composable
+internal fun PreviewZoomValue(
+ zoom: PreviewControlUiModel.Zoom,
+ zoomRatio: () -> Float,
+ modifier: Modifier = Modifier,
+) {
+ val suffix = stringResource(R.string.zoom_value_suffix)
+ val format = rememberZoomFormat()
+
+ AnimatedVisibility(
+ visible = zoom.isExpanded,
+ modifier = modifier,
+ enter = POP_IN,
+ exit = POP_OUT,
+ ) {
+ ValueChip(text = format.format(value = zoomRatio().coerceIn(zoom.range)) + suffix)
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/SelfTimerCountdown.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/SelfTimerCountdown.kt
new file mode 100644
index 000000000..54adc33b6
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/components/SelfTimerCountdown.kt
@@ -0,0 +1,36 @@
+package app.grapheneos.camera.ui.previewoverlays.components
+
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.tooling.preview.PreviewLightDark
+import app.grapheneos.camera.ui.components.countdowntimer.CountDownTimer
+import app.grapheneos.camera.ui.core.preview.CameraPreviewColumn
+import app.grapheneos.camera.ui.core.preview.CameraPreviewViewfinder
+import kotlin.math.ceil
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.seconds
+
+@Composable
+internal fun SelfTimerCountdown(
+ remaining: Duration,
+ modifier: Modifier = Modifier,
+) {
+ CountDownTimer(
+ value = ceil(remaining / 1.seconds).toInt(),
+ modifier = modifier,
+ )
+}
+
+@PreviewLightDark
+@Composable
+private fun SelfTimerCountdownPreview() {
+ CameraPreviewColumn {
+ CameraPreviewViewfinder {
+ SelfTimerCountdown(
+ remaining = 3.seconds,
+ modifier = Modifier.align(Alignment.Center),
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/PreviewOverlaysScreen.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/PreviewOverlaysScreen.kt
new file mode 100644
index 000000000..f2dc05305
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/PreviewOverlaysScreen.kt
@@ -0,0 +1,154 @@
+package app.grapheneos.camera.ui.previewoverlays.screen
+
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.State
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.tooling.preview.PreviewLightDark
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.DpRect
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.compose.LifecycleResumeEffect
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.lifecycle.viewmodel.compose.viewModel
+import app.grapheneos.camera.ui.components.compositiongrid.CompositionGrid
+import app.grapheneos.camera.ui.components.compositiongrid.model.CompositionGridPattern
+import app.grapheneos.camera.ui.core.preview.CameraPreviewColumn
+import app.grapheneos.camera.ui.core.preview.CameraPreviewViewfinder
+import app.grapheneos.camera.ui.previewoverlays.components.PreviewControls
+import app.grapheneos.camera.ui.previewoverlays.components.PreviewFocus
+import app.grapheneos.camera.ui.previewoverlays.components.PreviewLayer
+import app.grapheneos.camera.ui.previewoverlays.components.PreviewLevel
+import app.grapheneos.camera.ui.previewoverlays.components.SelfTimerCountdown
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction as Action
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.LifecycleAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.FocusUiModel
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.LevelUiState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.PreviewOverlaysUiState
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.seconds
+
+private val CONTROLS_GAP = 24.dp
+
+@Composable
+internal fun PreviewOverlaysScreen(
+ previewBounds: DpRect,
+ shutterRowInset: Dp,
+ modifier: Modifier = Modifier,
+ screenModel: PreviewOverlaysScreenModel = viewModel(),
+) {
+ val uiState by screenModel.uiState.collectAsStateWithLifecycle()
+ val level = screenModel.levelUiState.collectAsStateWithLifecycle()
+ val zoomRatio = screenModel.zoomRatio.collectAsStateWithLifecycle()
+
+ LifecycleResumeEffect(screenModel) {
+ screenModel.onAction(LifecycleAction.ScreenResumed)
+ onPauseOrDispose { screenModel.onAction(LifecycleAction.ScreenPaused) }
+ }
+
+ PreviewOverlaysContent(
+ uiState = uiState,
+ level = level,
+ zoomRatio = { zoomRatio.value },
+ previewBounds = previewBounds,
+ shutterRowInset = shutterRowInset,
+ modifier = modifier,
+ onAction = screenModel::onAction,
+ )
+}
+
+@Composable
+private fun PreviewOverlaysContent(
+ uiState: PreviewOverlaysUiState,
+ level: State,
+ zoomRatio: () -> Float,
+ previewBounds: DpRect,
+ shutterRowInset: Dp,
+ modifier: Modifier = Modifier,
+ onAction: (Action) -> Unit = {},
+) {
+ Box(modifier = modifier.fillMaxSize()) {
+ PreviewIndicators(
+ gridPattern = uiState.gridPattern,
+ focus = uiState.focus,
+ selfTimerRemaining = uiState.selfTimerRemaining,
+ level = level,
+ previewBounds = previewBounds,
+ )
+ PreviewControls(
+ control = uiState.control,
+ zoomRatio = zoomRatio,
+ onAction = onAction,
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .padding(bottom = shutterRowInset + CONTROLS_GAP),
+ )
+ }
+}
+
+@Composable
+private fun BoxScope.PreviewIndicators(
+ gridPattern: CompositionGridPattern?,
+ focus: FocusUiModel?,
+ selfTimerRemaining: Duration?,
+ level: State,
+ previewBounds: DpRect,
+) {
+ PreviewLayer(bounds = previewBounds) {
+ gridPattern?.let { pattern ->
+ CompositionGrid(
+ pattern = pattern,
+ modifier = Modifier.matchParentSize(),
+ )
+ }
+ PreviewLevel(
+ level = level,
+ modifier = Modifier.align(Alignment.Center),
+ )
+ focus?.let { visibleFocus ->
+ PreviewFocus(focus = visibleFocus)
+ }
+ selfTimerRemaining?.let { remaining ->
+ SelfTimerCountdown(
+ remaining = remaining,
+ modifier = Modifier.align(Alignment.Center),
+ )
+ }
+ }
+}
+
+@PreviewLightDark
+@Composable
+private fun PreviewOverlaysPreview() {
+ CameraPreviewColumn {
+ CameraPreviewViewfinder(
+ modifier = Modifier.size(
+ width = 240.dp,
+ height = 320.dp,
+ ),
+ ) {
+ PreviewOverlaysContent(
+ uiState = PreviewOverlaysUiState(
+ gridPattern = CompositionGridPattern.GoldenRatio,
+ selfTimerRemaining = 3.seconds,
+ ),
+ level = rememberUpdatedState(LevelUiState()),
+ zoomRatio = { 1f },
+ previewBounds = DpRect(
+ left = 0.dp,
+ top = 0.dp,
+ right = 240.dp,
+ bottom = 320.dp,
+ ),
+ shutterRowInset = 0.dp,
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/PreviewOverlaysViewModel.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/PreviewOverlaysViewModel.kt
new file mode 100644
index 000000000..88fce8823
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/PreviewOverlaysViewModel.kt
@@ -0,0 +1,167 @@
+package app.grapheneos.camera.ui.previewoverlays.screen
+
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import app.grapheneos.camera.data.settings.repository.SettingsRepository
+import app.grapheneos.camera.ui.core.screen.StateHolder
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.ExposureDelegate
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.FocusDelegate
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.LevelDelegate
+import app.grapheneos.camera.ui.previewoverlays.screen.delegate.ZoomDelegate
+import app.grapheneos.camera.ui.previewoverlays.screen.mapper.PreviewOverlaysUiStateMapper
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction as Action
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.ExposureAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.FocusAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.LifecycleAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.PreviewAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.ZoomAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewOverlaysState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.LevelUiState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.PreviewOverlaysUiState
+import dagger.hilt.android.lifecycle.HiltViewModel
+import javax.inject.Inject
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.launch
+
+internal interface PreviewOverlaysScreenModel {
+
+ val uiState: StateFlow
+
+ val levelUiState: StateFlow
+
+ val zoomRatio: StateFlow
+
+ fun onAction(action: Action)
+}
+
+@HiltViewModel
+internal class PreviewOverlaysViewModel @Inject constructor(
+ settingsRepository: SettingsRepository,
+ uiStateMapper: PreviewOverlaysUiStateMapper,
+ private val focusDelegate: FocusDelegate,
+ private val levelDelegate: LevelDelegate,
+ private val zoomDelegate: ZoomDelegate,
+ private val exposureDelegate: ExposureDelegate,
+) : ViewModel(),
+ PreviewOverlaysScreenModel {
+
+ private val stateHolder = StateHolder(
+ initial = PreviewOverlaysState(
+ settings = settingsRepository.settings.value,
+ ),
+ )
+
+ override val uiState: StateFlow = stateHolder.derive(
+ isAffected = { previous, current ->
+ previous.withPerFrameValuesOf(current) != current
+ },
+ ) { state ->
+ uiStateMapper.map(state)
+ }
+
+ override val levelUiState: StateFlow = stateHolder.derive { state ->
+ uiStateMapper.mapLevel(state)
+ }
+
+ override val zoomRatio: StateFlow = stateHolder.derive { state ->
+ uiStateMapper.mapZoomRatio(state)
+ }
+
+ private var resumedWork: Job? = null
+
+ init {
+ levelDelegate.bind(stateHolder)
+ focusDelegate.bind(stateHolder)
+ zoomDelegate.bind(stateHolder)
+ exposureDelegate.bind(stateHolder)
+
+ viewModelScope.launch {
+ settingsRepository.settings.collect { settings ->
+ updatePreview { state -> state.copy(settings = settings) }
+ }
+ }
+ }
+
+ override fun onAction(action: Action) {
+ when (action) {
+ is LifecycleAction -> onLifecycleAction(action)
+ is PreviewAction -> onPreviewAction(action)
+ is FocusAction -> focusDelegate.onAction(action)
+ is ZoomAction -> zoomDelegate.onAction(action)
+ is ExposureAction -> exposureDelegate.onAction(action)
+ }
+ }
+
+ private fun onLifecycleAction(action: LifecycleAction) {
+ when (action) {
+ is LifecycleAction.ScreenResumed -> onScreenResumed()
+ is LifecycleAction.ScreenPaused -> onScreenPaused()
+ }
+ }
+
+ private fun onPreviewAction(action: PreviewAction) {
+ when (action) {
+ is PreviewAction.DisplayRotationChanged -> onRotationChanged(action)
+ is PreviewAction.PreviewContentChanged -> onContentChanged(action)
+ is PreviewAction.PreviewFlashVisibilityChanged -> onFlashChanged(action)
+ }
+ }
+
+ private fun onRotationChanged(action: PreviewAction.DisplayRotationChanged) {
+ stateHolder.update { state -> state.copy(displayRotation = action.rotation) }
+ }
+
+ private fun onContentChanged(action: PreviewAction.PreviewContentChanged) {
+ updatePreview { state -> state.copy(previewContent = action.content) }
+ }
+
+ private fun onFlashChanged(action: PreviewAction.PreviewFlashVisibilityChanged) {
+ updatePreview { state -> state.copy(isPreviewFlashVisible = action.visible) }
+ }
+
+ private fun updatePreview(transform: (PreviewOverlaysState) -> PreviewOverlaysState) {
+ stateHolder.update { previous ->
+ val current = transform(previous)
+ current.copy(
+ level = levelDelegate.levelAfterChange(
+ previous = previous,
+ current = current,
+ ),
+ focus = focusDelegate.focusAfterChange(
+ previous = previous,
+ current = current,
+ ),
+ zoom = zoomDelegate.zoomAfterChange(
+ previous = previous,
+ current = current,
+ ),
+ exposure = exposureDelegate.exposureAfterChange(
+ previous = previous,
+ current = current,
+ ),
+ ).withVisibleControlActive()
+ }
+ }
+
+ private fun onScreenResumed() {
+ if (resumedWork?.isActive == true) return
+
+ resumedWork = viewModelScope.launch {
+ launch { levelDelegate.trackLevel() }
+ launch { focusDelegate.trackFocus() }
+ launch { zoomDelegate.trackZoom() }
+ launch { exposureDelegate.trackExposure() }
+ }
+ }
+
+ private fun onScreenPaused() {
+ resumedWork?.cancel()
+ resumedWork = null
+ levelDelegate.onScreenPaused()
+ focusDelegate.onScreenPaused()
+ zoomDelegate.onScreenPaused()
+ exposureDelegate.onScreenPaused()
+ stateHolder.update { state -> state.copy(isPreviewFlashVisible = false) }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/ExposureDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/ExposureDelegate.kt
new file mode 100644
index 000000000..0cd08d6d4
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/ExposureDelegate.kt
@@ -0,0 +1,211 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.delegate
+
+import app.grapheneos.camera.data.camera.session.ExposureControl
+import app.grapheneos.camera.ui.core.screen.StateHolder
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.ExposureAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.ExposureState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewControl
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewOverlaysState
+import javax.inject.Inject
+import kotlin.math.roundToInt
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.filterNotNull
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.launch
+
+internal interface ExposureDelegate {
+
+ fun bind(stateHolder: StateHolder)
+
+ fun exposureAfterChange(
+ previous: PreviewOverlaysState,
+ current: PreviewOverlaysState,
+ ): ExposureState
+
+ fun onAction(action: ExposureAction)
+
+ fun onScreenPaused()
+
+ suspend fun trackExposure()
+}
+
+internal class ExposureDelegateImpl @Inject constructor(
+ private val exposureControl: ExposureControl,
+) : ExposureDelegate {
+
+ private lateinit var stateHolder: StateHolder
+
+ private val state: PreviewOverlaysState
+ get() = stateHolder.state.value
+
+ override fun bind(stateHolder: StateHolder) {
+ this.stateHolder = stateHolder
+ }
+
+ override fun exposureAfterChange(
+ previous: PreviewOverlaysState,
+ current: PreviewOverlaysState,
+ ): ExposureState {
+ val content = current.previewContent
+ val cameraChanged = previous.previewContent?.mode != content?.mode ||
+ previous.previewContent?.lensFacing != content?.lensFacing
+ val isLivePreview = content?.isPreviewStreaming == true && !content.isTransitionFrameVisible
+ return when {
+ cameraChanged || !isLivePreview -> current.exposure.reset()
+ !current.isPreviewInputAvailable() -> current.exposure.idle()
+ else -> current.exposure
+ }
+ }
+
+ override fun onAction(action: ExposureAction) {
+ when (action) {
+ is ExposureAction.ValueChanged -> onValueChanged(action.value)
+ is ExposureAction.ResetClicked -> onResetClicked()
+ is ExposureAction.PressChanged -> onPressChanged(action.isPressed)
+ }
+ }
+
+ override fun onScreenPaused() {
+ hidePanel(ExposureState())
+ }
+
+ override suspend fun trackExposure() {
+ coroutineScope {
+ launch { trackCameraExposure() }
+ launch { trackFocusRequests() }
+ trackPanelTimeout()
+ }
+ }
+
+ private fun onValueChanged(value: Float) {
+ val exposure = state.exposure.value ?: return
+ if (!state.isExposureVisible() || !value.isFinite()) return
+
+ val index = (value / exposure.compensationStep).roundToInt()
+ .coerceIn(exposure.compensationRange)
+ setCompensationIndex(
+ index = index,
+ isAdjusted = state.exposure.isAdjusted || index != exposure.compensationIndex,
+ )
+ }
+
+ private fun onResetClicked() {
+ if (!state.isExposureVisible()) return
+
+ setCompensationIndex(
+ index = 0,
+ isAdjusted = false,
+ )
+ }
+
+ private fun onPressChanged(isPressed: Boolean) {
+ if (isPressed == state.exposure.isPressed) return
+ if (isPressed && !state.isExposureVisible()) return
+
+ updateExposure { exposure ->
+ exposure.copy(
+ isPressed = isPressed,
+ interactionId = exposure.interactionId + 1,
+ )
+ }
+ }
+
+ private suspend fun trackCameraExposure() {
+ exposureControl.exposure.collect { value ->
+ when (value) {
+ null -> hidePanel(state.exposure.reset())
+ else -> updateExposure { exposure ->
+ exposure.copy(
+ value = value,
+ isAdjusted = exposure.isAdjusted || value.isCompensated(),
+ )
+ }
+ }
+ }
+ }
+
+ private suspend fun trackFocusRequests() {
+ stateHolder.state
+ .map { state -> state.focus.selection?.requestId }
+ .distinctUntilChanged()
+ .filterNotNull()
+ .collect { showPanel() }
+ }
+
+ private suspend fun trackPanelTimeout() {
+ stateHolder.state
+ .map { state ->
+ state.exposure.takeIf { exposure ->
+ state.isExposureVisible() && !exposure.isPressed
+ }
+ }
+ .distinctUntilChanged()
+ .collectLatest { exposure ->
+ if (exposure != null) {
+ delay(PANEL_VISIBILITY_DURATION)
+ hidePanel(state.exposure.idle())
+ }
+ }
+ }
+
+ private fun showPanel() {
+ val value = exposureControl.exposure.value
+ if (value == null || !value.isAdjustable() || !state.isPreviewInputAvailable()) return
+
+ stateHolder.update { state ->
+ state.copy(
+ activeControl = PreviewControl.Exposure,
+ exposure = state.exposure.copy(
+ value = value,
+ isPressed = false,
+ isAdjusted = state.exposure.isAdjusted || value.isCompensated(),
+ interactionId = state.exposure.interactionId + 1,
+ ),
+ )
+ }
+ }
+
+ private fun hidePanel(exposure: ExposureState) {
+ stateHolder.update { state ->
+ state.copy(
+ activeControl = when (state.activeControl) {
+ PreviewControl.Exposure -> PreviewControl.Zoom
+ else -> state.activeControl
+ },
+ exposure = exposure,
+ )
+ }
+ }
+
+ private fun setCompensationIndex(
+ index: Int,
+ isAdjusted: Boolean,
+ ) {
+ exposureControl.setCompensationIndex(index)
+
+ val value = exposureControl.exposure.value ?: return
+ val isApplied = value.compensationIndex == index
+ updateExposure { exposure ->
+ exposure.copy(
+ value = value,
+ isAdjusted = when {
+ isApplied -> isAdjusted
+ else -> exposure.isAdjusted
+ },
+ interactionId = exposure.interactionId + 1,
+ )
+ }
+ }
+
+ private fun updateExposure(transform: (ExposureState) -> ExposureState) {
+ stateHolder.update { state -> state.copy(exposure = transform(state.exposure)) }
+ }
+
+ private companion object {
+ private val PANEL_VISIBILITY_DURATION = 2.seconds
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/FocusDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/FocusDelegate.kt
new file mode 100644
index 000000000..987d56131
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/FocusDelegate.kt
@@ -0,0 +1,273 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.delegate
+
+import app.grapheneos.camera.data.camera.model.CameraFocusEvent
+import app.grapheneos.camera.data.camera.model.CameraFocusRequest
+import app.grapheneos.camera.data.camera.session.FocusControl
+import app.grapheneos.camera.data.core.model.CameraMode
+import app.grapheneos.camera.data.sound.model.CameraSound
+import app.grapheneos.camera.domain.sound.usecase.PlayCameraSound
+import app.grapheneos.camera.ui.core.screen.StateHolder
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.FocusAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.FocusPhase
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.FocusPress
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.FocusSelection
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.FocusState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewOverlaysState
+import javax.inject.Inject
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.filterNotNull
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.launch
+
+internal interface FocusDelegate {
+
+ fun bind(stateHolder: StateHolder)
+
+ fun focusAfterChange(
+ previous: PreviewOverlaysState,
+ current: PreviewOverlaysState,
+ ): FocusState
+
+ fun onAction(action: FocusAction)
+
+ fun onScreenPaused()
+
+ suspend fun trackFocus()
+}
+
+internal class FocusDelegateImpl @Inject constructor(
+ private val focusControl: FocusControl,
+ private val playCameraSound: PlayCameraSound,
+) : FocusDelegate {
+
+ private lateinit var stateHolder: StateHolder
+
+ private val state: PreviewOverlaysState
+ get() = stateHolder.state.value
+
+ private var lastRequestId = 0L
+ private var activeRequestId: Long? = null
+
+ override fun bind(stateHolder: StateHolder) {
+ this.stateHolder = stateHolder
+ }
+
+ override fun focusAfterChange(
+ previous: PreviewOverlaysState,
+ current: PreviewOverlaysState,
+ ): FocusState {
+ val modeChanged = previous.previewContent?.mode != current.previewContent?.mode
+ return when {
+ current.isPreviewInteractive() && !modeChanged -> current.focus
+ else -> current.focus.hidden()
+ }
+ }
+
+ override fun onAction(action: FocusAction) {
+ when (action) {
+ is FocusAction.FocusKeyPressed -> cancelFocus()
+ is FocusAction.PreviewTapped -> onPreviewTapped()
+ is FocusAction.PreviewLongPressed -> onPreviewLongPressed()
+ is FocusAction.PreviewGestureStarted -> onPreviewGestureStarted()
+ is FocusAction.PreviewPressed -> onPreviewPressed(
+ x = action.x,
+ y = action.y,
+ hitRadius = action.hitRadius,
+ )
+ }
+ }
+
+ private fun onPreviewPressed(
+ x: Float,
+ y: Float,
+ hitRadius: Float,
+ ) {
+ if (!state.isPreviewInputAvailable()) return
+
+ val selection = state.focus.selection
+ val isOnRing = selection != null && selection.visible &&
+ selection.isNear(
+ x = x,
+ y = y,
+ radius = hitRadius,
+ )
+ val press = when {
+ isOnRing -> FocusPress.OnRing(
+ x = x,
+ y = y,
+ )
+ else -> newPoint(
+ x = x,
+ y = y,
+ )
+ }
+ updateFocus { focus -> focus.copy(press = press) }
+ }
+
+ private fun onPreviewTapped() {
+ when (val press = takePress()) {
+ null -> Unit
+ is FocusPress.OnRing -> cancelFocus()
+ is FocusPress.NewPoint -> startFocus(
+ press = press,
+ isLocked = false,
+ )
+ }
+ }
+
+ private fun onPreviewLongPressed() {
+ when (val press = takePress()) {
+ null -> Unit
+ is FocusPress.OnRing -> lockFocus(press)
+ is FocusPress.NewPoint -> startFocus(
+ press = press,
+ isLocked = true,
+ )
+ }
+ }
+
+ private fun onPreviewGestureStarted() {
+ updateFocus { focus -> focus.copy(press = null) }
+ }
+
+ private fun cancelFocus() {
+ cancelMetering()
+ updateFocus { focus -> focus.hidden() }
+ }
+
+ override fun onScreenPaused() {
+ cancelMetering()
+ updateFocus { FocusState() }
+ }
+
+ override suspend fun trackFocus() {
+ coroutineScope {
+ launch { trackHiddenSelection() }
+ focusControl.events.collect { event ->
+ when (event) {
+ is CameraFocusEvent.Started -> {
+ if (state.previewContent?.mode != CameraMode.VIDEO) {
+ this@coroutineScope.launch { playCameraSound(CameraSound.FOCUS_START) }
+ }
+ }
+
+ is CameraFocusEvent.Focused -> updateSelection(event.requestId) { selection ->
+ when (selection.phase) {
+ FocusPhase.Locked -> selection
+ else -> selection.copy(phase = FocusPhase.Focused)
+ }
+ }
+
+ is CameraFocusEvent.Locked -> updateSelection(event.requestId) { selection ->
+ selection.copy(phase = FocusPhase.Locked)
+ }
+
+ is CameraFocusEvent.Cancelled -> {
+ if (activeRequestId == event.requestId) {
+ activeRequestId = null
+ }
+ updateSelection(event.requestId) { selection ->
+ selection.copy(visible = false)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private suspend fun trackHiddenSelection() {
+ stateHolder.state
+ .map { state ->
+ state.focus.selection
+ ?.takeUnless { selection -> selection.visible }
+ ?.requestId
+ }
+ .distinctUntilChanged()
+ .filterNotNull()
+ .collect { requestId ->
+ if (activeRequestId == requestId) {
+ cancelMetering()
+ }
+ }
+ }
+
+ private fun cancelMetering() {
+ activeRequestId = null
+ focusControl.cancel()
+ }
+
+ private fun takePress(): FocusPress? {
+ val press = state.focus.press?.takeIf { state.isPreviewInputAvailable() }
+ updateFocus { focus -> focus.copy(press = null) }
+ return press
+ }
+
+ private fun lockFocus(press: FocusPress.OnRing) {
+ when {
+ state.focus.selection?.visible == true -> focusControl.lock()
+ else -> startFocus(
+ press = newPoint(
+ x = press.x,
+ y = press.y,
+ ),
+ isLocked = true,
+ )
+ }
+ }
+
+ private fun startFocus(
+ press: FocusPress.NewPoint,
+ isLocked: Boolean,
+ ) {
+ activeRequestId = press.requestId
+ updateFocus {
+ FocusState(
+ selection = FocusSelection(
+ requestId = press.requestId,
+ x = press.x,
+ y = press.y,
+ ),
+ )
+ }
+ focusControl.focus(
+ request = CameraFocusRequest(
+ id = press.requestId,
+ x = press.x,
+ y = press.y,
+ autoCancelAfter = state.settings.focusTimeoutSeconds.seconds,
+ isLocked = isLocked,
+ ),
+ )
+ }
+
+ private fun newPoint(
+ x: Float,
+ y: Float,
+ ): FocusPress.NewPoint {
+ lastRequestId += 1
+ return FocusPress.NewPoint(
+ requestId = lastRequestId,
+ x = x,
+ y = y,
+ )
+ }
+
+ private fun updateFocus(transform: (FocusState) -> FocusState) {
+ stateHolder.update { state -> state.copy(focus = transform(state.focus)) }
+ }
+
+ private fun updateSelection(
+ requestId: Long,
+ transform: (FocusSelection) -> FocusSelection,
+ ) {
+ updateFocus { focus ->
+ val selection = focus.selection
+ when {
+ selection?.requestId != requestId -> focus
+ else -> focus.copy(selection = transform(selection))
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/LevelDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/LevelDelegate.kt
new file mode 100644
index 000000000..20e579ea1
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/LevelDelegate.kt
@@ -0,0 +1,156 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.delegate
+
+import app.grapheneos.camera.data.orientation.model.DeviceMotion
+import app.grapheneos.camera.data.orientation.repository.DeviceOrientationRepository
+import app.grapheneos.camera.ui.core.screen.StateHolder
+import app.grapheneos.camera.ui.previewoverlays.screen.mapper.LevelStateMapper
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.LevelPose
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.LevelState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewOverlaysState
+import javax.inject.Inject
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.launch
+
+internal interface LevelDelegate {
+
+ fun bind(stateHolder: StateHolder)
+
+ fun levelAfterChange(
+ previous: PreviewOverlaysState,
+ current: PreviewOverlaysState,
+ ): LevelState
+
+ fun onScreenPaused()
+
+ suspend fun trackLevel()
+}
+
+internal class LevelDelegateImpl @Inject constructor(
+ private val deviceOrientationRepository: DeviceOrientationRepository,
+ private val levelStateMapper: LevelStateMapper,
+) : LevelDelegate {
+
+ private lateinit var stateHolder: StateHolder
+
+ private val state: PreviewOverlaysState
+ get() = stateHolder.state.value
+
+ override fun bind(stateHolder: StateHolder) {
+ this.stateHolder = stateHolder
+ }
+
+ override fun levelAfterChange(
+ previous: PreviewOverlaysState,
+ current: PreviewOverlaysState,
+ ): LevelState {
+ val modeChanged = previous.previewContent?.mode != current.previewContent?.mode
+ return when {
+ current.isLevelAvailable() && !modeChanged -> current.level
+ else -> LevelState()
+ }
+ }
+
+ override fun onScreenPaused() {
+ resetLevel()
+ }
+
+ override suspend fun trackLevel() {
+ stateHolder.state
+ .map { state ->
+ when {
+ state.isLevelAvailable() -> state.previewContent?.mode
+ else -> null
+ }
+ }
+ .distinctUntilChanged()
+ .collectLatest { mode ->
+ resetLevel()
+
+ if (mode != null) {
+ trackMotion()
+ }
+ }
+ }
+
+ private suspend fun trackMotion() {
+ coroutineScope {
+ var latestMotion: DeviceMotion
+ var pendingReveal: Job? = null
+
+ deviceOrientationRepository.motion.collect { motion ->
+ latestMotion = motion
+ val previousPose = state.level.pose
+ val level = publishMotion(motion)
+ val pose = level.pose
+ val poseChanged = previousPose != pose
+ val isRevealPending = pendingReveal?.isActive == true
+
+ when {
+ pose == null || level.visible -> {
+ pendingReveal?.cancel()
+ pendingReveal = null
+ }
+
+ poseChanged || !isRevealPending -> {
+ pendingReveal?.cancel()
+ pendingReveal = this@coroutineScope.launch {
+ delay(REVEAL_DELAY)
+ revealLevel(
+ motion = latestMotion,
+ expectedPose = pose,
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private fun publishMotion(motion: DeviceMotion): LevelState {
+ val level = levelStateMapper.map(
+ state = state,
+ motion = motion,
+ )
+ val published = when {
+ level.visible -> level
+ else -> level.copy(
+ tiltDegrees = state.level.tiltDegrees,
+ horizonDegrees = state.level.horizonDegrees,
+ )
+ }
+
+ stateHolder.update { state -> state.copy(level = published) }
+
+ return level
+ }
+
+ private fun revealLevel(
+ motion: DeviceMotion,
+ expectedPose: LevelPose,
+ ) {
+ stateHolder.update { state ->
+ val candidate = levelStateMapper.map(
+ state = state,
+ motion = motion,
+ )
+ when {
+ state.level.pose != expectedPose || candidate.pose != expectedPose -> state
+ else -> state.copy(level = candidate.copy(visible = true))
+ }
+ }
+ }
+
+ private fun resetLevel() {
+ stateHolder.update { state -> state.copy(level = LevelState()) }
+ }
+
+ private companion object {
+ private val REVEAL_DELAY = 1.seconds
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/ZoomDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/ZoomDelegate.kt
new file mode 100644
index 000000000..2fb8a74a5
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/delegate/ZoomDelegate.kt
@@ -0,0 +1,450 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.delegate
+
+import app.grapheneos.camera.data.camera.model.CameraZoom
+import app.grapheneos.camera.data.camera.model.CameraZoomEvent
+import app.grapheneos.camera.data.camera.session.ZoomControl
+import app.grapheneos.camera.data.core.model.LensFacing
+import app.grapheneos.camera.data.settings.model.VolumeKeyAction
+import app.grapheneos.camera.domain.camera.mapper.ZoomPresetsMapper
+import app.grapheneos.camera.ui.core.screen.StateHolder
+import app.grapheneos.camera.ui.previewoverlays.screen.model.PreviewOverlaysAction.ZoomAction
+import app.grapheneos.camera.ui.previewoverlays.screen.model.input.ZoomDirection
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewControl
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewOverlaysState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.ZoomState
+import javax.inject.Inject
+import kotlin.math.pow
+import kotlin.time.Duration.Companion.milliseconds
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.merge
+import kotlinx.coroutines.launch
+
+internal interface ZoomDelegate {
+
+ fun bind(stateHolder: StateHolder)
+
+ fun zoomAfterChange(
+ previous: PreviewOverlaysState,
+ current: PreviewOverlaysState,
+ ): ZoomState
+
+ fun onAction(action: ZoomAction)
+
+ fun onScreenPaused()
+
+ suspend fun trackZoom()
+}
+
+internal class ZoomDelegateImpl @Inject constructor(
+ private val zoomControl: ZoomControl,
+ private val zoomPresetsMapper: ZoomPresetsMapper,
+) : ZoomDelegate {
+
+ private lateinit var stateHolder: StateHolder
+
+ private val state: PreviewOverlaysState
+ get() = stateHolder.state.value
+
+ private var lastPresetId = 0L
+
+ override fun bind(stateHolder: StateHolder) {
+ this.stateHolder = stateHolder
+ }
+
+ override fun zoomAfterChange(
+ previous: PreviewOverlaysState,
+ current: PreviewOverlaysState,
+ ): ZoomState {
+ val cameraChanged = previous.previewContent?.mode != current.previewContent?.mode ||
+ previous.previewContent?.lensFacing != current.previewContent?.lensFacing
+ return when {
+ !current.isZoomAvailable() -> current.zoom.idle()
+ cameraChanged -> current.zoom.copy(pendingPreset = null)
+ else -> current.zoom
+ }
+ }
+
+ override fun onAction(action: ZoomAction) {
+ when (action) {
+ is ZoomAction.Expanded -> onExpanded()
+ is ZoomAction.RatioChanged -> onRatioChanged(action.ratio)
+ is ZoomAction.PresetSelected -> onPresetSelected(action.ratio)
+ is ZoomAction.ControlPressChanged -> onControlPressChanged(action.isPressed)
+ is ZoomAction.PreviewPinchStarted -> onPreviewPinchStarted()
+ is ZoomAction.PreviewPinchScaleChanged -> onPreviewPinchScaleChanged(action.scaleFactor)
+ is ZoomAction.PreviewPinchFinished -> onPreviewPinchFinished()
+ is ZoomAction.ZoomKeyPressed -> onZoomKeyPressed(action.direction)
+ is ZoomAction.VolumeKeyPressed -> onVolumeKeyPressed(action.direction)
+ is ZoomAction.VolumeKeyReleased -> onVolumeKeyReleased()
+ }
+ }
+
+ override fun onScreenPaused() {
+ updateZoom { zoom -> zoom.idle() }
+ }
+
+ override suspend fun trackZoom() {
+ coroutineScope {
+ launch { trackCameraZoom() }
+ launch { trackControlSelection() }
+ launch { trackPresets() }
+ launch { trackKeySteps() }
+ trackPanel()
+ }
+ }
+
+ private fun onExpanded() {
+ if (!state.isZoomAvailable()) return
+
+ updateZoom(selectsControl = true) { zoom ->
+ zoom.copy(
+ isExpanded = true,
+ interactionId = zoom.interactionId + 1,
+ )
+ }
+ }
+
+ private fun onRatioChanged(ratio: Float) {
+ setRatio(
+ ratio = ratio,
+ expands = false,
+ )
+ }
+
+ private fun onPresetSelected(ratio: Float) {
+ val requested = acceptRatio(ratio) ?: return
+
+ zoomControl.stopZoomAnimation()
+ rememberForSelectedLens(requested)
+
+ lastPresetId += 1
+ updateZoom(selectsControl = true) { zoom ->
+ zoom.copy(
+ pendingPreset = ZoomState.Preset(
+ ratio = requested,
+ requestId = lastPresetId,
+ ),
+ interactionId = zoom.interactionId + 1,
+ )
+ }
+ }
+
+ private fun onControlPressChanged(isPressed: Boolean) {
+ if (isPressed == state.zoom.isControlPressed) return
+ if (isPressed && !state.isZoomAvailable()) return
+
+ if (isPressed) {
+ zoomControl.stopZoomAnimation()
+ }
+
+ updateZoom(selectsControl = isPressed) { zoom ->
+ zoom.copy(
+ isControlPressed = isPressed,
+ pendingPreset = when {
+ isPressed -> null
+ else -> zoom.pendingPreset
+ },
+ interactionId = zoom.interactionId + 1,
+ )
+ }
+ }
+
+ private fun onPreviewPinchStarted() {
+ if (!state.isZoomAvailable()) return
+
+ zoomControl.stopZoomAnimation()
+
+ updateZoom(selectsControl = true) { zoom ->
+ zoom.copy(
+ isExpanded = true,
+ isPreviewPinching = true,
+ pendingPreset = null,
+ interactionId = zoom.interactionId + 1,
+ )
+ }
+ }
+
+ private fun onPreviewPinchScaleChanged(scaleFactor: Float) {
+ val ratio = state.zoom.value?.zoomRatio ?: return
+ if (!scaleFactor.isFinite() || scaleFactor <= 0f) return
+
+ setRatio(
+ ratio = ratio * scaleFactor.pow(PINCH_ZOOM_EXPONENT),
+ expands = true,
+ )
+ }
+
+ private fun onPreviewPinchFinished() {
+ updateZoom { zoom -> zoom.copy(isPreviewPinching = false) }
+ }
+
+ private fun onZoomKeyPressed(direction: ZoomDirection) {
+ val current = state.zoom.value?.zoomRatio ?: return
+ val stepped = when (direction) {
+ ZoomDirection.IN -> current + ZOOM_KEY_STEP
+ ZoomDirection.OUT -> current - ZOOM_KEY_STEP
+ }
+ val ratio = when {
+ // The wide-angle camera hands over to the main one at 1×.
+ current < 1f && stepped > 1f -> 1f
+ else -> stepped
+ }
+
+ setRatio(
+ ratio = ratio,
+ expands = true,
+ )
+ }
+
+ private fun onVolumeKeyPressed(direction: ZoomDirection) {
+ if (state.settings.volumeKeyAction != VolumeKeyAction.ZOOM || !state.isZoomAvailable()) {
+ return
+ }
+
+ if (state.zoom.keyStepDirection != direction) {
+ updateZoom(selectsControl = true) { zoom -> zoom.copy(keyStepDirection = direction) }
+ }
+ }
+
+ private fun onVolumeKeyReleased() {
+ updateZoom { zoom -> zoom.copy(keyStepDirection = null) }
+ }
+
+ private suspend fun trackControlSelection() {
+ stateHolder.state
+ .map { state -> state.activeControl }
+ .distinctUntilChanged()
+ .collect { control ->
+ if (control != PreviewControl.Zoom) {
+ finishPendingPreset()
+ updateZoom { zoom -> zoom.idle() }
+ }
+ }
+ }
+
+ private fun finishPendingPreset() {
+ val preset = state.zoom.pendingPreset
+ val selectedLens = state.previewContent?.lensFacing
+
+ if (preset != null && selectedLens != null) {
+ zoomControl.setZoomRatio(
+ zoomRatio = preset.ratio,
+ lensFacing = selectedLens,
+ )
+ }
+ }
+
+ private suspend fun trackCameraZoom() {
+ merge(
+ zoomControl.events.map { event -> event is CameraZoomEvent.Loaded },
+ stateHolder.state
+ .map { state -> state.previewContent }
+ .distinctUntilChanged { previous, current ->
+ previous?.mode == current?.mode &&
+ previous?.lensFacing == current?.lensFacing
+ }
+ .map { true },
+ ).collect { isNewCamera ->
+ if (isSelectedCameraAttached()) {
+ refreshZoom(isNewCamera = isNewCamera)
+ }
+ }
+ }
+
+ private suspend fun trackPresets() {
+ stateHolder.state
+ .map { state ->
+ state.zoom.pendingPreset?.takeIf {
+ state.isZoomVisible() && isSelectedCameraAttached()
+ }
+ }
+ .distinctUntilChanged()
+ .collectLatest { preset ->
+ if (preset != null) {
+ try {
+ zoomControl.animateZoomRatio(preset.ratio)
+ } finally {
+ updateZoom { zoom ->
+ when (zoom.pendingPreset) {
+ preset -> zoom.copy(
+ value = zoomControl.zoom ?: zoom.value,
+ pendingPreset = null,
+ )
+ else -> zoom
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private suspend fun trackKeySteps() {
+ stateHolder.state
+ .map { state -> state.zoom.keyStepDirection }
+ .distinctUntilChanged()
+ .collectLatest { direction ->
+ if (direction != null) {
+ while (stepToNextStop(direction)) {
+ delay(KEY_STEP_INTERVAL)
+ }
+ }
+ }
+ }
+
+ private suspend fun trackPanel() {
+ stateHolder.state
+ .map { state ->
+ state.zoom.takeIf { zoom ->
+ state.isZoomVisible() && zoom.isExpanded && zoom.pendingPreset == null &&
+ !zoom.isControlPressed && !zoom.isPreviewPinching &&
+ zoom.keyStepDirection == null
+ }
+ }
+ .distinctUntilChanged()
+ .collectLatest { zoom ->
+ if (zoom != null) {
+ delay(COLLAPSE_DELAY)
+ updateZoom { it.copy(isExpanded = false) }
+ }
+ }
+ }
+
+ private fun refreshZoom(isNewCamera: Boolean) {
+ val zoom = zoomControl.zoom ?: return
+ val lensFacing = zoomControl.lensFacing ?: return
+
+ stateHolder.update { state ->
+ val updated = state.copy(
+ zoom = state.zoom.copy(
+ value = zoom,
+ lensFacing = lensFacing,
+ pendingPreset = when {
+ isNewCamera -> null
+ else -> state.zoom.pendingPreset
+ },
+ ),
+ )
+ updated.copy(
+ zoom = zoomAfterChange(
+ previous = state,
+ current = updated,
+ ),
+ )
+ }
+ }
+
+ private fun setRatio(
+ ratio: Float,
+ expands: Boolean,
+ ) {
+ val requested = acceptRatio(ratio) ?: return
+
+ updateZoom(selectsControl = true) { zoom ->
+ zoom.copy(
+ value = zoom.value?.copy(zoomRatio = requested),
+ isExpanded = zoom.isExpanded || expands,
+ pendingPreset = null,
+ interactionId = zoom.interactionId + 1,
+ )
+ }
+
+ state.previewContent?.lensFacing?.let { selectedLens ->
+ zoomControl.setZoomRatio(
+ zoomRatio = requested,
+ lensFacing = selectedLens,
+ )
+ }
+ }
+
+ private fun stepToNextStop(direction: ZoomDirection): Boolean {
+ val zoom = state.zoom.value
+ val lensFacing = state.previewContent?.lensFacing
+ val stop = when {
+ zoom == null || lensFacing == null || !state.isZoomAvailable() -> null
+ else -> nextStop(
+ zoom = zoom,
+ lensFacing = lensFacing,
+ direction = direction,
+ )
+ }
+
+ if (stop != null) {
+ setRatio(
+ ratio = stop,
+ expands = true,
+ )
+ }
+
+ return stop != null
+ }
+
+ private fun nextStop(
+ zoom: CameraZoom,
+ lensFacing: LensFacing,
+ direction: ZoomDirection,
+ ): Float? {
+ val presets = zoomPresetsMapper.map(
+ zoom = zoom,
+ lensFacing = lensFacing,
+ )
+ val stops = presets + zoom.minZoomRatio + zoom.maxZoomRatio
+
+ return when (direction) {
+ ZoomDirection.IN -> stops.filter { stop -> stop > zoom.zoomRatio }.minOrNull()
+ ZoomDirection.OUT -> stops.filter { stop -> stop < zoom.zoomRatio }.maxOrNull()
+ }
+ }
+
+ private fun acceptRatio(ratio: Float): Float? {
+ val zoom = state.zoom.value
+
+ return when {
+ zoom == null || !state.isZoomAvailable() || !ratio.isFinite() -> null
+ else -> ratio.coerceIn(
+ minimumValue = zoom.minZoomRatio,
+ maximumValue = zoom.maxZoomRatio,
+ )
+ }
+ }
+
+ private fun rememberForSelectedLens(ratio: Float) {
+ state.previewContent?.lensFacing?.let { selectedLens ->
+ zoomControl.rememberZoomRatio(
+ zoomRatio = ratio,
+ lensFacing = selectedLens,
+ )
+ }
+ }
+
+ private fun isSelectedCameraAttached(): Boolean {
+ return zoomControl.zoom != null &&
+ zoomControl.lensFacing == state.previewContent?.lensFacing
+ }
+
+ private fun updateZoom(
+ selectsControl: Boolean = false,
+ transform: (ZoomState) -> ZoomState,
+ ) {
+ stateHolder.update { state ->
+ state.copy(
+ activeControl = when {
+ selectsControl -> PreviewControl.Zoom
+ else -> state.activeControl
+ },
+ zoom = transform(state.zoom),
+ )
+ }
+ }
+
+ private companion object {
+ private const val PINCH_ZOOM_EXPONENT = 2
+ private const val ZOOM_KEY_STEP = 1f
+ private val KEY_STEP_INTERVAL = 500.milliseconds
+ private val COLLAPSE_DELAY = 2.seconds
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/mapper/LevelStateMapper.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/mapper/LevelStateMapper.kt
new file mode 100644
index 000000000..3daa86d91
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/mapper/LevelStateMapper.kt
@@ -0,0 +1,71 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.mapper
+
+import app.grapheneos.camera.data.orientation.model.DeviceMotion
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.LevelPose
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.LevelState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewOverlaysState
+import javax.inject.Inject
+import kotlin.math.abs
+
+internal interface LevelStateMapper {
+
+ fun map(
+ state: PreviewOverlaysState,
+ motion: DeviceMotion,
+ ): LevelState
+}
+
+internal class LevelStateMapperImpl @Inject constructor() : LevelStateMapper {
+
+ override fun map(
+ state: PreviewOverlaysState,
+ motion: DeviceMotion,
+ ): LevelState {
+ val current = state.level
+ val pose = when {
+ state.isLevelAvailable() -> poseOf(
+ current = current,
+ motion = motion,
+ )
+ else -> null
+ }
+ val visible = current.visible && pose != null && pose == current.pose
+
+ return current.copy(
+ visible = visible,
+ pose = pose,
+ tiltDegrees = motion.tiltDegrees,
+ horizonDegrees = motion.horizonDegrees,
+ orientation = motion.orientation,
+ )
+ }
+
+ private fun poseOf(
+ current: LevelState,
+ motion: DeviceMotion,
+ ): LevelPose? {
+ val isHorizonVisible = current.visible && current.pose == LevelPose.Horizon
+ val rollLimit = when {
+ isHorizonVisible -> HORIZON_EXIT_DEGREES
+ else -> HORIZON_ROLL_ENTRY_DEGREES
+ }
+ val pitchLimit = when {
+ isHorizonVisible -> HORIZON_EXIT_DEGREES
+ else -> HORIZON_PITCH_ENTRY_DEGREES
+ }
+ return when {
+ motion.horizonDegrees >= VERTICAL_ENTRY_DEGREES -> LevelPose.FacingDown
+ motion.horizonDegrees <= -VERTICAL_ENTRY_DEGREES -> LevelPose.FacingUp
+ abs(motion.tiltDegrees) <= rollLimit &&
+ abs(motion.horizonDegrees) <= pitchLimit -> LevelPose.Horizon
+ else -> null
+ }
+ }
+
+ private companion object {
+ private const val HORIZON_ROLL_ENTRY_DEGREES = 8f
+ private const val HORIZON_PITCH_ENTRY_DEGREES = 25f
+ private const val HORIZON_EXIT_DEGREES = 45f
+ private const val VERTICAL_ENTRY_DEGREES = 75f
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/mapper/PreviewOverlaysUiStateMapper.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/mapper/PreviewOverlaysUiStateMapper.kt
new file mode 100644
index 000000000..b0a2b71f0
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/mapper/PreviewOverlaysUiStateMapper.kt
@@ -0,0 +1,151 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.mapper
+
+import app.grapheneos.camera.data.settings.model.GridType
+import app.grapheneos.camera.domain.camera.mapper.ZoomPresetsMapper
+import app.grapheneos.camera.ui.components.compositiongrid.model.CompositionGridPattern
+import app.grapheneos.camera.ui.components.focusindicator.model.FocusIndicatorAppearance
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.FocusPhase
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.LevelPose
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewControl
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewOverlaysState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.FocusUiModel
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.LevelUiState
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.PreviewControlUiModel
+import app.grapheneos.camera.ui.previewoverlays.screen.model.ui.PreviewOverlaysUiState
+import javax.inject.Inject
+import kotlin.math.roundToInt
+import kotlinx.collections.immutable.toImmutableList
+
+internal interface PreviewOverlaysUiStateMapper {
+
+ fun map(state: PreviewOverlaysState): PreviewOverlaysUiState
+
+ fun mapLevel(state: PreviewOverlaysState): LevelUiState
+
+ fun mapZoomRatio(state: PreviewOverlaysState): Float
+}
+
+internal class PreviewOverlaysUiStateMapperImpl @Inject constructor(
+ private val zoomPresetsMapper: ZoomPresetsMapper,
+) : PreviewOverlaysUiStateMapper {
+
+ override fun map(state: PreviewOverlaysState): PreviewOverlaysUiState {
+ return PreviewOverlaysUiState(
+ focus = focus(state),
+ control = control(state),
+ gridPattern = gridPattern(state),
+ selfTimerRemaining = state.visibleSelfTimerRemaining(),
+ )
+ }
+
+ override fun mapLevel(state: PreviewOverlaysState): LevelUiState {
+ val level = state.level
+ val pose = level.pose ?: return LevelUiState()
+
+ return LevelUiState(
+ visible = state.isLevelVisible(),
+ mode = when (pose) {
+ LevelPose.FacingUp -> LevelIndicatorMode.Crosshairs
+ LevelPose.FacingDown -> LevelIndicatorMode.Crosshairs
+ LevelPose.Horizon -> LevelIndicatorMode.Horizon
+ },
+ rollDegrees = level.tiltDegrees,
+ pitchDegrees = 0f - level.horizonDegrees,
+ rotationDegrees = levelRotationDegrees(state),
+ )
+ }
+
+ override fun mapZoomRatio(state: PreviewOverlaysState): Float {
+ val zoom = state.zoom.value
+
+ return when {
+ zoom == null || !zoom.isAdjustable() -> DEFAULT_ZOOM_RATIO
+ else -> zoom.zoomRatio.coerceIn(
+ minimumValue = zoom.minZoomRatio,
+ maximumValue = zoom.maxZoomRatio,
+ )
+ }
+ }
+
+ private fun gridPattern(state: PreviewOverlaysState): CompositionGridPattern? {
+ if (!state.isGridVisible()) return null
+
+ return when (state.settings.gridType) {
+ GridType.THREE_BY_THREE -> CompositionGridPattern.Thirds
+ GridType.FOUR_BY_FOUR -> CompositionGridPattern.Quarters
+ GridType.GOLDEN_RATIO -> CompositionGridPattern.GoldenRatio
+ GridType.NONE -> null
+ }
+ }
+
+ private fun levelRotationDegrees(state: PreviewOverlaysState): Float {
+ val orientation = state.level.orientation ?: return 0f
+ val difference = state.displayRotation.degrees - orientation.degrees
+
+ return difference.mod(FULL_TURN_DEGREES).toFloat()
+ }
+
+ private fun focus(state: PreviewOverlaysState): FocusUiModel? {
+ val selection = state.focus.selection ?: return null
+ return FocusUiModel(
+ requestId = selection.requestId,
+ x = selection.x,
+ y = selection.y,
+ appearance = when (selection.phase) {
+ FocusPhase.Focusing -> FocusIndicatorAppearance.Focusing
+ FocusPhase.Focused -> FocusIndicatorAppearance.Focused
+ FocusPhase.Locked -> FocusIndicatorAppearance.Locked
+ },
+ visible = selection.visible && state.isPreviewInputAvailable(),
+ )
+ }
+
+ private fun control(state: PreviewOverlaysState): PreviewControlUiModel? {
+ return when (state.visibleControl()) {
+ PreviewControl.Zoom -> zoom(state)
+ PreviewControl.Exposure -> exposure(state)
+ null -> null
+ }
+ }
+
+ private fun zoom(state: PreviewOverlaysState): PreviewControlUiModel.Zoom? {
+ val content = state.previewContent
+ val zoom = state.zoom.value
+ if (content == null || zoom == null) return null
+
+ val range = zoom.minZoomRatio..zoom.maxZoomRatio
+ val presets = zoomPresetsMapper.map(
+ zoom = zoom,
+ lensFacing = state.zoom.lensFacing,
+ )
+
+ return PreviewControlUiModel.Zoom(
+ range = range,
+ presets = presets.toImmutableList(),
+ isCurrentValueVisible = state.zoom.pendingPreset == null,
+ isExpanded = state.zoom.isExpanded,
+ isPinching = state.zoom.isPreviewPinching,
+ )
+ }
+
+ private fun exposure(state: PreviewOverlaysState): PreviewControlUiModel.Exposure? {
+ val exposure = state.exposure.value ?: return null
+
+ val step = exposure.compensationStep
+ val range = exposure.compensationRange
+
+ return PreviewControlUiModel.Exposure(
+ value = exposure.compensationIndex.coerceIn(range) * step,
+ range = range.first * step..range.last * step,
+ steps = range.last - range.first - 1,
+ majorTickInterval = (1f / step).roundToInt().coerceAtLeast(1),
+ isResetVisible = state.exposure.isAdjusted,
+ )
+ }
+
+ private companion object {
+ private const val FULL_TURN_DEGREES = 360
+ private const val DEFAULT_ZOOM_RATIO = 1f
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/PreviewOverlaysAction.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/PreviewOverlaysAction.kt
new file mode 100644
index 000000000..7f91bff15
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/PreviewOverlaysAction.kt
@@ -0,0 +1,95 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model
+
+import app.grapheneos.camera.data.core.model.DeviceOrientation
+import app.grapheneos.camera.ui.previewoverlays.screen.model.input.ZoomDirection
+import app.grapheneos.camera.ui.previewoverlays.screen.model.state.PreviewContentState
+
+internal sealed interface PreviewOverlaysAction {
+
+ sealed interface LifecycleAction : PreviewOverlaysAction {
+
+ data object ScreenResumed : LifecycleAction
+
+ data object ScreenPaused : LifecycleAction
+ }
+
+ sealed interface FocusAction : PreviewOverlaysAction {
+
+ data object FocusKeyPressed : FocusAction
+
+ data object PreviewTapped : FocusAction
+
+ data object PreviewLongPressed : FocusAction
+
+ data object PreviewGestureStarted : FocusAction
+
+ data class PreviewPressed(
+ val x: Float,
+ val y: Float,
+ val hitRadius: Float,
+ ) : FocusAction
+ }
+
+ sealed interface PreviewAction : PreviewOverlaysAction {
+
+ data class DisplayRotationChanged(
+ val rotation: DeviceOrientation,
+ ) : PreviewAction
+
+ data class PreviewContentChanged(
+ val content: PreviewContentState,
+ ) : PreviewAction
+
+ data class PreviewFlashVisibilityChanged(
+ val visible: Boolean,
+ ) : PreviewAction
+ }
+
+ sealed interface ExposureAction : PreviewOverlaysAction {
+
+ data object ResetClicked : ExposureAction
+
+ data class ValueChanged(
+ val value: Float,
+ ) : ExposureAction
+
+ data class PressChanged(
+ val isPressed: Boolean,
+ ) : ExposureAction
+ }
+
+ sealed interface ZoomAction : PreviewOverlaysAction {
+
+ data object VolumeKeyReleased : ZoomAction
+
+ data class ZoomKeyPressed(
+ val direction: ZoomDirection,
+ ) : ZoomAction
+
+ data class VolumeKeyPressed(
+ val direction: ZoomDirection,
+ ) : ZoomAction
+
+ data object Expanded : ZoomAction
+
+ data class RatioChanged(
+ val ratio: Float,
+ ) : ZoomAction
+
+ data class PresetSelected(
+ val ratio: Float,
+ ) : ZoomAction
+
+ data object PreviewPinchStarted : ZoomAction
+
+ data class PreviewPinchScaleChanged(
+ val scaleFactor: Float,
+ ) : ZoomAction
+
+ data object PreviewPinchFinished : ZoomAction
+
+ data class ControlPressChanged(
+ val isPressed: Boolean,
+ ) : ZoomAction
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/input/ZoomDirection.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/input/ZoomDirection.kt
new file mode 100644
index 000000000..1730dee5f
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/input/ZoomDirection.kt
@@ -0,0 +1,6 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.input
+
+internal enum class ZoomDirection {
+ IN,
+ OUT,
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/ExposureState.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/ExposureState.kt
new file mode 100644
index 000000000..483476882
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/ExposureState.kt
@@ -0,0 +1,19 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+import app.grapheneos.camera.data.camera.model.CameraExposure
+
+internal data class ExposureState(
+ val value: CameraExposure? = null,
+ val isPressed: Boolean = false,
+ val isAdjusted: Boolean = false,
+ val interactionId: Long = 0,
+) {
+
+ fun idle(): ExposureState {
+ return copy(isPressed = false)
+ }
+
+ fun reset(): ExposureState {
+ return ExposureState(interactionId = interactionId)
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusPhase.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusPhase.kt
new file mode 100644
index 000000000..2e96c3ed8
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusPhase.kt
@@ -0,0 +1,7 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+internal enum class FocusPhase {
+ Focusing,
+ Focused,
+ Locked,
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusPress.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusPress.kt
new file mode 100644
index 000000000..d37b30ff4
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusPress.kt
@@ -0,0 +1,15 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+internal sealed interface FocusPress {
+
+ data class OnRing(
+ val x: Float,
+ val y: Float,
+ ) : FocusPress
+
+ data class NewPoint(
+ val requestId: Long,
+ val x: Float,
+ val y: Float,
+ ) : FocusPress
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusSelection.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusSelection.kt
new file mode 100644
index 000000000..b3033ee5c
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusSelection.kt
@@ -0,0 +1,20 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+internal data class FocusSelection(
+ val requestId: Long,
+ val x: Float,
+ val y: Float,
+ val phase: FocusPhase = FocusPhase.Focusing,
+ val visible: Boolean = true,
+) {
+
+ fun isNear(
+ x: Float,
+ y: Float,
+ radius: Float,
+ ): Boolean {
+ val distanceX = this.x - x
+ val distanceY = this.y - y
+ return distanceX * distanceX + distanceY * distanceY <= radius * radius
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusState.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusState.kt
new file mode 100644
index 000000000..6da2fadf9
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/FocusState.kt
@@ -0,0 +1,11 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+internal data class FocusState(
+ val selection: FocusSelection? = null,
+ val press: FocusPress? = null,
+) {
+
+ fun hidden(): FocusState {
+ return FocusState(selection = selection?.copy(visible = false))
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/LevelPose.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/LevelPose.kt
new file mode 100644
index 000000000..27a701b02
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/LevelPose.kt
@@ -0,0 +1,7 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+internal enum class LevelPose {
+ Horizon,
+ FacingUp,
+ FacingDown,
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/LevelState.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/LevelState.kt
new file mode 100644
index 000000000..881fc8b89
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/LevelState.kt
@@ -0,0 +1,11 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+import app.grapheneos.camera.data.core.model.DeviceOrientation
+
+internal data class LevelState(
+ val visible: Boolean = false,
+ val pose: LevelPose? = null,
+ val tiltDegrees: Float = 0f,
+ val horizonDegrees: Float = 0f,
+ val orientation: DeviceOrientation? = null,
+)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewContentState.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewContentState.kt
new file mode 100644
index 000000000..afb2abc91
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewContentState.kt
@@ -0,0 +1,14 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+import app.grapheneos.camera.data.core.model.CameraMode
+import app.grapheneos.camera.data.core.model.LensFacing
+import kotlin.time.Duration
+
+internal data class PreviewContentState(
+ val mode: CameraMode = CameraMode.CAMERA,
+ val lensFacing: LensFacing = LensFacing.BACK,
+ val isPreviewStreaming: Boolean = false,
+ val isTransitionFrameVisible: Boolean = false,
+ val isCaptureResultVisible: Boolean = false,
+ val selfTimerRemaining: Duration? = null,
+)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewControl.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewControl.kt
new file mode 100644
index 000000000..f2e39d0fd
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewControl.kt
@@ -0,0 +1,6 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+internal enum class PreviewControl {
+ Zoom,
+ Exposure,
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewOverlaysState.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewOverlaysState.kt
new file mode 100644
index 000000000..5b68995e6
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/PreviewOverlaysState.kt
@@ -0,0 +1,117 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+import app.grapheneos.camera.data.core.model.CameraMode
+import app.grapheneos.camera.data.core.model.DeviceOrientation
+import app.grapheneos.camera.data.core.model.LensFacing
+import app.grapheneos.camera.data.settings.model.CameraSettings
+import app.grapheneos.camera.data.settings.model.GridType
+import kotlin.time.Duration
+
+internal data class PreviewOverlaysState(
+ val settings: CameraSettings = CameraSettings(),
+ val previewContent: PreviewContentState? = null,
+ val isPreviewFlashVisible: Boolean = false,
+ val displayRotation: DeviceOrientation = DeviceOrientation.DEGREES_0,
+ val focus: FocusState = FocusState(),
+ val level: LevelState = LevelState(),
+ val activeControl: PreviewControl = PreviewControl.Zoom,
+ val zoom: ZoomState = ZoomState(),
+ val exposure: ExposureState = ExposureState(),
+) {
+
+ fun isPreviewInteractive(): Boolean {
+ val content = previewContent ?: return false
+ return content.mode != CameraMode.QR_SCAN &&
+ content.isPreviewStreaming &&
+ !isPreviewReplaced(content)
+ }
+
+ fun isPreviewInputAvailable(): Boolean {
+ return isPreviewInteractive() && !isPreviewFlashVisible
+ }
+
+ fun isGridVisible(): Boolean {
+ val content = previewContent ?: return false
+ return settings.gridType != GridType.NONE &&
+ content.mode != CameraMode.QR_SCAN &&
+ !isPreviewHidden(content)
+ }
+
+ fun visibleSelfTimerRemaining(): Duration? {
+ val content = previewContent ?: return null
+ return when {
+ content.mode == CameraMode.QR_SCAN || isPreviewHidden(content) -> null
+ else -> content.selfTimerRemaining
+ }
+ }
+
+ fun isLevelVisible(): Boolean {
+ return isLevelAvailable() && level.visible
+ }
+
+ fun isLevelAvailable(): Boolean {
+ val content = previewContent ?: return false
+ val isPhotoMode = when (content.mode) {
+ CameraMode.QR_SCAN -> false
+ CameraMode.VIDEO -> false
+ CameraMode.AUTO,
+ CameraMode.FACE_RETOUCH,
+ CameraMode.PORTRAIT,
+ CameraMode.NIGHT,
+ CameraMode.HDR,
+ CameraMode.CAMERA,
+ -> true
+ }
+
+ return settings.gyroscopeSuggestions && isPhotoMode &&
+ content.lensFacing == LensFacing.BACK &&
+ content.isPreviewStreaming &&
+ content.selfTimerRemaining == null &&
+ !isPreviewReplaced(content)
+ }
+
+ fun isZoomAvailable(): Boolean {
+ val content = previewContent ?: return false
+ return content.mode != CameraMode.QR_SCAN &&
+ !content.isCaptureResultVisible &&
+ !isPreviewFlashVisible &&
+ zoom.isAdjustable()
+ }
+
+ fun isZoomVisible(): Boolean {
+ return visibleControl() == PreviewControl.Zoom
+ }
+
+ fun isExposureVisible(): Boolean {
+ return visibleControl() == PreviewControl.Exposure
+ }
+
+ fun visibleControl(): PreviewControl? {
+ val defaultControl = PreviewControl.Zoom.takeIf { isZoomAvailable() }
+ return when (activeControl) {
+ PreviewControl.Zoom -> defaultControl
+ PreviewControl.Exposure -> PreviewControl.Exposure.takeIf {
+ isPreviewInputAvailable() && exposure.value?.isAdjustable() == true
+ } ?: defaultControl
+ }
+ }
+
+ fun withPerFrameValuesOf(other: PreviewOverlaysState): PreviewOverlaysState {
+ return copy(
+ level = other.level,
+ zoom = zoom.withPerFrameValuesOf(other.zoom),
+ )
+ }
+
+ fun withVisibleControlActive(): PreviewOverlaysState {
+ return copy(activeControl = visibleControl() ?: PreviewControl.Zoom)
+ }
+
+ private fun isPreviewHidden(content: PreviewContentState): Boolean {
+ return isPreviewReplaced(content) || isPreviewFlashVisible
+ }
+
+ private fun isPreviewReplaced(content: PreviewContentState): Boolean {
+ return content.isTransitionFrameVisible || content.isCaptureResultVisible
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/ZoomState.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/ZoomState.kt
new file mode 100644
index 000000000..17f9f0a00
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/state/ZoomState.kt
@@ -0,0 +1,49 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.state
+
+import app.grapheneos.camera.data.camera.model.CameraZoom
+import app.grapheneos.camera.data.core.model.LensFacing
+import app.grapheneos.camera.ui.previewoverlays.screen.model.input.ZoomDirection
+
+internal data class ZoomState(
+ val value: CameraZoom? = null,
+ val lensFacing: LensFacing = LensFacing.BACK,
+ val isExpanded: Boolean = false,
+ val isControlPressed: Boolean = false,
+ val isPreviewPinching: Boolean = false,
+ val interactionId: Long = 0,
+ val pendingPreset: Preset? = null,
+ val keyStepDirection: ZoomDirection? = null,
+) {
+
+ fun isAdjustable(): Boolean {
+ return value?.isAdjustable() == true
+ }
+
+ fun withPerFrameValuesOf(other: ZoomState): ZoomState {
+ val otherValue = other.value
+
+ return copy(
+ value = when {
+ value == null || otherValue == null -> value
+ else -> value.copy(
+ zoomRatio = otherValue.zoomRatio,
+ linearZoom = otherValue.linearZoom,
+ )
+ },
+ interactionId = other.interactionId,
+ )
+ }
+
+ fun idle(): ZoomState {
+ return ZoomState(
+ value = value,
+ lensFacing = lensFacing,
+ interactionId = interactionId,
+ )
+ }
+
+ data class Preset(
+ val ratio: Float,
+ val requestId: Long,
+ )
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/FocusUiModel.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/FocusUiModel.kt
new file mode 100644
index 000000000..27f795b43
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/FocusUiModel.kt
@@ -0,0 +1,13 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.ui
+
+import androidx.compose.runtime.Immutable
+import app.grapheneos.camera.ui.components.focusindicator.model.FocusIndicatorAppearance
+
+@Immutable
+internal data class FocusUiModel(
+ val requestId: Long = 0,
+ val x: Float = 0f,
+ val y: Float = 0f,
+ val appearance: FocusIndicatorAppearance = FocusIndicatorAppearance.Focusing,
+ val visible: Boolean = false,
+)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/LevelUiState.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/LevelUiState.kt
new file mode 100644
index 000000000..9d331ba7a
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/LevelUiState.kt
@@ -0,0 +1,13 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.ui
+
+import androidx.compose.runtime.Immutable
+import app.grapheneos.camera.ui.components.levelindicator.model.LevelIndicatorMode
+
+@Immutable
+internal data class LevelUiState(
+ val visible: Boolean = false,
+ val mode: LevelIndicatorMode = LevelIndicatorMode.Horizon,
+ val rollDegrees: Float = 0f,
+ val pitchDegrees: Float = 0f,
+ val rotationDegrees: Float = 0f,
+)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/PreviewControlUiModel.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/PreviewControlUiModel.kt
new file mode 100644
index 000000000..0a9db716a
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/PreviewControlUiModel.kt
@@ -0,0 +1,26 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.ui
+
+import androidx.compose.runtime.Immutable
+import kotlinx.collections.immutable.ImmutableList
+
+@Immutable
+internal sealed interface PreviewControlUiModel {
+
+ @Immutable
+ data class Zoom(
+ val range: ClosedFloatingPointRange,
+ val presets: ImmutableList,
+ val isCurrentValueVisible: Boolean = true,
+ val isExpanded: Boolean = false,
+ val isPinching: Boolean = false,
+ ) : PreviewControlUiModel
+
+ @Immutable
+ data class Exposure(
+ val value: Float,
+ val range: ClosedFloatingPointRange,
+ val steps: Int,
+ val majorTickInterval: Int,
+ val isResetVisible: Boolean = false,
+ ) : PreviewControlUiModel
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/PreviewOverlaysUiState.kt b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/PreviewOverlaysUiState.kt
new file mode 100644
index 000000000..ffe4f2895
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/previewoverlays/screen/model/ui/PreviewOverlaysUiState.kt
@@ -0,0 +1,13 @@
+package app.grapheneos.camera.ui.previewoverlays.screen.model.ui
+
+import androidx.compose.runtime.Immutable
+import app.grapheneos.camera.ui.components.compositiongrid.model.CompositionGridPattern
+import kotlin.time.Duration
+
+@Immutable
+internal data class PreviewOverlaysUiState(
+ val focus: FocusUiModel? = null,
+ val control: PreviewControlUiModel? = null,
+ val gridPattern: CompositionGridPattern? = null,
+ val selfTimerRemaining: Duration? = null,
+)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/quicksettings/screen/QuickSettingsViewModel.kt b/app/src/main/java/app/grapheneos/camera/ui/quicksettings/screen/QuickSettingsViewModel.kt
index ad0d9c8a0..1ab478844 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/quicksettings/screen/QuickSettingsViewModel.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/quicksettings/screen/QuickSettingsViewModel.kt
@@ -3,6 +3,7 @@ package app.grapheneos.camera.ui.quicksettings.screen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.grapheneos.camera.BuildConfig
+import app.grapheneos.camera.data.camera.mapper.CameraFlashMapper
import app.grapheneos.camera.data.camera.session.CameraSession
import app.grapheneos.camera.data.camera.session.VideoRecordingSession
import app.grapheneos.camera.data.core.model.AspectRatio
@@ -29,6 +30,7 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.launch
@@ -49,6 +51,7 @@ internal class QuickSettingsViewModel @Inject constructor(
private val settingsRepository: SettingsRepository,
private val session: CameraSession,
private val recordingSession: VideoRecordingSession,
+ private val flashMapper: CameraFlashMapper,
private val copyText: CopyText,
private val appLabel: AppLabel,
) : ViewModel(),
@@ -60,7 +63,9 @@ internal class QuickSettingsViewModel @Inject constructor(
),
)
- override val uiState: StateFlow = stateHolder.derive(uiStateMapper::map)
+ override val uiState: StateFlow = stateHolder.derive { state ->
+ uiStateMapper.map(state)
+ }
override val effects: Flow = stateHolder.effects
@@ -161,9 +166,15 @@ internal class QuickSettingsViewModel @Inject constructor(
}
private fun setFlashMode(mode: FlashMode) {
- val slot = state.boundCamera?.modeSlot() ?: return
+ val camera = state.boundCamera ?: return
+ val flash = flashMapper.map(
+ camera = camera,
+ requestedMode = mode,
+ frameRate = state.modeSettings.videoFrameRate,
+ )
+ if (mode != flash.selectedMode) return
- settingsRepository.updateMode(slot = slot) { it.copy(flashMode = mode) }
+ settingsRepository.updateMode(slot = camera.modeSlot()) { it.copy(flashMode = mode) }
}
private fun setVideoFrameRate(frameRate: VideoFrameRate) {
diff --git a/app/src/main/java/app/grapheneos/camera/ui/quicksettings/screen/mapper/QuickSettingsUiStateMapper.kt b/app/src/main/java/app/grapheneos/camera/ui/quicksettings/screen/mapper/QuickSettingsUiStateMapper.kt
index 0ce62e6cb..c5dc7f284 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/quicksettings/screen/mapper/QuickSettingsUiStateMapper.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/quicksettings/screen/mapper/QuickSettingsUiStateMapper.kt
@@ -1,6 +1,9 @@
package app.grapheneos.camera.ui.quicksettings.screen.mapper
+import app.grapheneos.camera.data.camera.mapper.CameraFlashMapper
+import app.grapheneos.camera.data.camera.mapper.VideoQualityMapper
import app.grapheneos.camera.data.camera.model.BoundCamera
+import app.grapheneos.camera.data.camera.model.CameraFlash
import app.grapheneos.camera.data.camera.model.HighFrameRateSupport
import app.grapheneos.camera.data.core.model.AspectRatio
import app.grapheneos.camera.data.core.model.FlashMode
@@ -16,12 +19,16 @@ import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlinx.collections.immutable.persistentSetOf
import kotlinx.collections.immutable.toImmutableList
+import kotlinx.collections.immutable.toImmutableSet
internal interface QuickSettingsUiStateMapper {
fun map(state: QuickSettingsState): QuickSettingsUiState
}
-internal class QuickSettingsUiStateMapperImpl @Inject constructor() : QuickSettingsUiStateMapper {
+internal class QuickSettingsUiStateMapperImpl @Inject constructor(
+ private val flashMapper: CameraFlashMapper,
+ private val videoQualityMapper: VideoQualityMapper,
+) : QuickSettingsUiStateMapper {
override fun map(state: QuickSettingsState): QuickSettingsUiState {
val settingsButtonVisible = !state.isRecording
@@ -29,19 +36,19 @@ internal class QuickSettingsUiStateMapperImpl @Inject constructor() : QuickSetti
settingsButtonVisible = settingsButtonVisible,
)
- val flashMode = camera.appliedFlashMode(
- stored = state.modeSettings.flashMode,
+ val flash = flashMapper.map(
+ camera = camera,
+ requestedMode = state.modeSettings.flashMode,
frameRate = state.modeSettings.videoFrameRate,
)
return QuickSettingsUiState(
settingsButtonVisible = settingsButtonVisible,
isVideoMode = camera.isVideoMode,
- isSelfIlluminating = flashMode == FlashMode.SELF_ILLUMINATION,
+ isSelfIlluminating = flash.isSelfIlluminating(),
flash = flash(
- state = state,
camera = camera,
- flashMode = flashMode,
+ flash = flash,
),
selfTimer = selfTimer(
state = state,
@@ -68,26 +75,20 @@ internal class QuickSettingsUiStateMapperImpl @Inject constructor() : QuickSetti
}
private fun flash(
- state: QuickSettingsState,
camera: BoundCamera,
- flashMode: FlashMode,
+ flash: CameraFlash,
): QuickChoiceUiModel? {
val options = camera.flashModes()
- val isLowLightBoostLimited = camera.limitsLowLightBoost(state.modeSettings.videoFrameRate)
-
- return when {
- options.size > 1 -> QuickChoiceUiModel(
- selected = flashMode,
- options = options.toImmutableList(),
- unavailable = when {
- isLowLightBoostLimited -> persistentSetOf(FlashMode.LOW_LIGHT_BOOST)
- else -> persistentSetOf()
- },
- limit = OptionLimit.LowLightBoostAtHighFrameRate.takeIf { isLowLightBoostLimited },
- )
-
- else -> null
- }
+ if (options.size <= 1) return null
+
+ return QuickChoiceUiModel(
+ selected = flash.selectedMode,
+ options = options.toImmutableList(),
+ unavailable = flash.unavailableModes.toImmutableSet(),
+ limit = OptionLimit.LowLightBoostAtHighFrameRate.takeIf {
+ FlashMode.LOW_LIGHT_BOOST in flash.unavailableModes
+ },
+ )
}
private fun selfTimer(
@@ -124,7 +125,10 @@ internal class QuickSettingsUiStateMapperImpl @Inject constructor() : QuickSetti
): QuickChoiceUiModel? {
return when {
!state.isRecording && camera.isVideoMode -> QuickChoiceUiModel(
- selected = camera.recordedVideoQuality(stored = state.modeSettings.videoQuality),
+ selected = videoQualityMapper.map(
+ camera = camera,
+ requestedQuality = state.modeSettings.videoQuality,
+ ),
options = camera.videoQualities.reversed().toImmutableList(),
)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/statusbar/screen/StatusBarViewModel.kt b/app/src/main/java/app/grapheneos/camera/ui/statusbar/screen/StatusBarViewModel.kt
index 11867a427..1859af31c 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/statusbar/screen/StatusBarViewModel.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/statusbar/screen/StatusBarViewModel.kt
@@ -36,7 +36,9 @@ internal class StatusBarViewModel @Inject constructor(
),
)
- override val uiState: StateFlow = stateHolder.derive(uiStateMapper::map)
+ override val uiState: StateFlow = stateHolder.derive { state ->
+ uiStateMapper.map(state)
+ }
init {
viewModelScope.launch {
diff --git a/app/src/main/java/app/grapheneos/camera/ui/statusbar/screen/mapper/StatusBarUiStateMapper.kt b/app/src/main/java/app/grapheneos/camera/ui/statusbar/screen/mapper/StatusBarUiStateMapper.kt
index ddcfa109d..aae0a13d8 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/statusbar/screen/mapper/StatusBarUiStateMapper.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/statusbar/screen/mapper/StatusBarUiStateMapper.kt
@@ -1,5 +1,7 @@
package app.grapheneos.camera.ui.statusbar.screen.mapper
+import app.grapheneos.camera.data.camera.mapper.CameraFlashMapper
+import app.grapheneos.camera.data.camera.mapper.VideoQualityMapper
import app.grapheneos.camera.data.camera.model.BoundCamera
import app.grapheneos.camera.data.core.model.FlashMode
import app.grapheneos.camera.ui.statusbar.screen.model.StatusBarState
@@ -14,12 +16,16 @@ internal interface StatusBarUiStateMapper {
fun map(state: StatusBarState): StatusBarUiState
}
-internal class StatusBarUiStateMapperImpl @Inject constructor() : StatusBarUiStateMapper {
+internal class StatusBarUiStateMapperImpl @Inject constructor(
+ private val flashMapper: CameraFlashMapper,
+ private val videoQualityMapper: VideoQualityMapper,
+) : StatusBarUiStateMapper {
override fun map(state: StatusBarState): StatusBarUiState {
val camera = state.boundCamera ?: return StatusBarUiState()
- val flashMode = camera.appliedFlashMode(
- stored = state.modeSettings.flashMode,
+ val flash = flashMapper.map(
+ camera = camera,
+ requestedMode = state.modeSettings.flashMode,
frameRate = state.modeSettings.videoFrameRate,
)
@@ -27,9 +33,9 @@ internal class StatusBarUiStateMapperImpl @Inject constructor() : StatusBarUiSta
items = items(
state = state,
camera = camera,
- flashMode = flashMode,
+ flashMode = flash.selectedMode,
),
- isSelfIlluminating = flashMode == FlashMode.SELF_ILLUMINATION,
+ isSelfIlluminating = flash.isSelfIlluminating(),
)
}
@@ -49,7 +55,10 @@ internal class StatusBarUiStateMapperImpl @Inject constructor() : StatusBarUiSta
add(StatusItemUiModel.SelfTimer(duration = selfTimer))
}
if (camera.isVideoMode) {
- val quality = camera.recordedVideoQuality(stored = state.modeSettings.videoQuality)
+ val quality = videoQualityMapper.map(
+ camera = camera,
+ requestedQuality = state.modeSettings.videoQuality,
+ )
add(StatusItemUiModel.Resolution(quality = quality))
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/VideoPlayerScreen.kt b/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/VideoPlayerScreen.kt
index f37cc342b..146d72598 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/VideoPlayerScreen.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/VideoPlayerScreen.kt
@@ -34,6 +34,7 @@ import app.grapheneos.camera.ui.mediaviewer.components.video.VideoSurface
import app.grapheneos.camera.ui.mediaviewer.playback.VideoPlaybackUiModel
import app.grapheneos.camera.ui.videoplayer.screen.model.VideoPlayerAction as Action
import app.grapheneos.camera.ui.videoplayer.screen.model.VideoPlayerUiState as UiState
+import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
@Composable
@@ -43,6 +44,7 @@ internal fun VideoPlayerScreen(
screenModel: VideoPlayerScreenModel = hiltViewModel(),
) {
val uiState by screenModel.uiState.collectAsStateWithLifecycle()
+ val videoPosition = screenModel.videoPosition.collectAsStateWithLifecycle()
val effectHandler = rememberVideoPlayerEffectHandler(onNavigateBack)
ViewerLeftEffect(
@@ -58,6 +60,7 @@ internal fun VideoPlayerScreen(
VideoPlayerContent(
uiState = uiState,
+ videoPosition = { videoPosition.value },
onAction = screenModel::onAction,
onNavigateBack = onNavigateBack,
modifier = modifier,
@@ -67,6 +70,7 @@ internal fun VideoPlayerScreen(
@Composable
private fun VideoPlayerContent(
uiState: UiState,
+ videoPosition: () -> Duration,
onAction: (Action) -> Unit,
onNavigateBack: () -> Unit,
modifier: Modifier = Modifier,
@@ -112,15 +116,11 @@ private fun VideoPlayerContent(
)
Spacer(modifier = Modifier.weight(1f))
if (video != null) {
- VideoControls(
- isPlaying = video.isPlaying,
+ VideoPlayerControls(
+ video = video,
isMuted = uiState.isMuted,
- position = uiState.position,
- duration = video.duration,
- onPlayPauseClick = { onAction(Action.PlayPauseClicked) },
- onMuteClick = { onAction(Action.MuteClicked) },
- onSeek = { position -> onAction(Action.SeekDragged(position)) },
- onSeekFinished = { onAction(Action.SeekReleased) },
+ position = videoPosition,
+ onAction = onAction,
)
}
}
@@ -128,6 +128,25 @@ private fun VideoPlayerContent(
}
}
+@Composable
+private fun VideoPlayerControls(
+ video: VideoPlaybackUiModel.Active,
+ isMuted: Boolean,
+ position: () -> Duration,
+ onAction: (Action) -> Unit,
+) {
+ VideoControls(
+ isPlaying = video.isPlaying,
+ isMuted = isMuted,
+ position = position(),
+ duration = video.duration,
+ onPlayPauseClick = { onAction(Action.PlayPauseClicked) },
+ onMuteClick = { onAction(Action.MuteClicked) },
+ onSeek = { seekPosition -> onAction(Action.SeekDragged(seekPosition)) },
+ onSeekFinished = { onAction(Action.SeekReleased) },
+ )
+}
+
@PreviewScreenLightDark
@Composable
private fun VideoPlayerContentPreview() {
@@ -139,8 +158,8 @@ private fun VideoPlayerContentPreview() {
duration = 12.seconds,
aspectRatio = 16f / 9f,
),
- position = 5.seconds,
),
+ videoPosition = { 5.seconds },
onAction = {},
onNavigateBack = {},
)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/VideoPlayerViewModel.kt b/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/VideoPlayerViewModel.kt
index a773441b3..05973bbeb 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/VideoPlayerViewModel.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/VideoPlayerViewModel.kt
@@ -11,6 +11,7 @@ import app.grapheneos.camera.ui.videoplayer.screen.model.VideoPlayerScreenEffect
import app.grapheneos.camera.ui.videoplayer.screen.model.VideoPlayerUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
+import kotlin.time.Duration
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
@@ -26,6 +27,8 @@ internal interface VideoPlayerScreenModel {
val uiState: StateFlow
+ val videoPosition: StateFlow
+
val effects: Flow
fun onAction(action: Action)
@@ -47,6 +50,8 @@ internal class VideoPlayerViewModel @Inject constructor(
private val playback = videoPlaybackFactory.create()
private val controller = VideoPlaybackController(playback)
+ override val videoPosition: StateFlow = controller.position
+
init {
playback.load(
uri = videoUriOf(arguments),
@@ -60,12 +65,6 @@ internal class VideoPlayerViewModel @Inject constructor(
}
}
- viewModelScope.launch {
- controller.position.collect { position ->
- _uiState.update { it.copy(position = position) }
- }
- }
-
viewModelScope.launch {
controller.track(followsPosition = _uiState.map { it.areControlsVisible })
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/model/VideoPlayerUiState.kt b/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/model/VideoPlayerUiState.kt
index d101a776b..909b28093 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/model/VideoPlayerUiState.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/videoplayer/screen/model/VideoPlayerUiState.kt
@@ -2,12 +2,10 @@ package app.grapheneos.camera.ui.videoplayer.screen.model
import androidx.compose.runtime.Immutable
import app.grapheneos.camera.ui.mediaviewer.playback.VideoPlaybackUiModel
-import kotlin.time.Duration
@Immutable
internal data class VideoPlayerUiState(
val video: VideoPlaybackUiModel = VideoPlaybackUiModel.Active(),
- val position: Duration = Duration.ZERO,
val isMuted: Boolean = false,
val areControlsVisible: Boolean = true,
)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/CountDownTimerUI.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/CountDownTimerUI.kt
deleted file mode 100644
index 3c2365760..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/CountDownTimerUI.kt
+++ /dev/null
@@ -1,59 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.components
-
-import android.animation.ValueAnimator
-import android.content.Context
-import android.util.AttributeSet
-import android.view.Gravity
-import android.view.animation.AccelerateDecelerateInterpolator
-import androidx.appcompat.widget.AppCompatTextView
-import kotlin.time.Duration
-
-class CountDownTimerUI @JvmOverloads constructor(
- context: Context,
- attrs: AttributeSet? = null,
-) : AppCompatTextView(context, attrs) {
-
- private var renderedRemaining: Duration? = null
-
- init {
- gravity = Gravity.CENTER
- }
-
- fun render(remaining: Duration?) {
- if (remaining == renderedRemaining) return
- renderedRemaining = remaining
-
- if (remaining == null) return
-
- onTick(remaining.inWholeSeconds)
- }
-
- private fun onTick(secondsLeft: Long) {
- val scaleAnimation = ValueAnimator.ofFloat(START_SIZE, END_SIZE)
- scaleAnimation.interpolator = AccelerateDecelerateInterpolator()
- scaleAnimation.duration = TEXT_ANIMATION_DURATION
-
- scaleAnimation.addUpdateListener { valueAnimator ->
- textSize = valueAnimator.animatedValue as Float
- }
-
- val opacityAnimation = ValueAnimator.ofFloat(1f, 0f)
- opacityAnimation.interpolator = AccelerateDecelerateInterpolator()
- opacityAnimation.duration = TEXT_ANIMATION_DURATION
-
- opacityAnimation.addUpdateListener { valueAnimator ->
- alpha = valueAnimator.animatedValue as Float
- }
-
- scaleAnimation.start()
- opacityAnimation.start()
-
- text = secondsLeft.toString()
- }
-
- private companion object {
- private const val TEXT_ANIMATION_DURATION = 700L
- private const val START_SIZE = 12f
- private const val END_SIZE = 100f
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/CustomGrid.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/CustomGrid.kt
deleted file mode 100644
index aa4ba439b..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/CustomGrid.kt
+++ /dev/null
@@ -1,95 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.components
-
-import android.content.Context
-import android.graphics.Canvas
-import android.graphics.Color
-import android.graphics.Paint
-import android.util.AttributeSet
-import android.view.View
-import app.grapheneos.camera.data.settings.model.GridType
-
-class CustomGrid @JvmOverloads constructor(
- context: Context,
- attrs: AttributeSet? = null,
- defStyle: Int = 0,
-) : View(context, attrs, defStyle) {
-
- private val paint: Paint = Paint()
-
- var gridType: GridType = GridType.NONE
- set(value) {
- if (field == value) return
-
- field = value
-
- postInvalidate()
- }
-
- init {
- paint.isAntiAlias = true
- paint.strokeWidth = 1f
- paint.style = Paint.Style.STROKE
- paint.color = Color.argb(255, 255, 255, 255)
- }
-
- override fun onDraw(canvas: Canvas) {
- super.onDraw(canvas)
-
- if (gridType == GridType.NONE) {
- return
- }
-
- if (gridType == GridType.GOLDEN_RATIO) {
- val cx = width / 2f
- val cy = height / 2f
-
- val dxH = width / 8f
- val dyH = height / 8f
-
- canvas.drawLine(cx - dxH, 0f, cx - dxH, height.toFloat(), paint)
- canvas.drawLine(cx + dxH, 0f, cx + dxH, height.toFloat(), paint)
- canvas.drawLine(0f, cy - dyH, width.toFloat(), cy - dyH, paint)
- canvas.drawLine(0f, cy + dyH, width.toFloat(), cy + dyH, paint)
- } else {
- val seed = if (gridType == GridType.THREE_BY_THREE) {
- 3f
- } else {
- 4f
- }
-
- canvas.drawLine(
- width / seed * 2f,
- 0f,
- width / seed * 2f,
- height.toFloat(),
- paint
- )
- canvas.drawLine(width / seed, 0f, width / seed, height.toFloat(), paint)
- canvas.drawLine(
- 0f,
- height / seed * 2f,
- width.toFloat(),
- height / seed * 2f,
- paint
- )
- canvas.drawLine(0f, height / seed, width.toFloat(), height / seed, paint)
-
- if (seed == 4f) {
- canvas.drawLine(
- width / seed * 3f,
- 0f,
- width / seed * 3f,
- height.toFloat(),
- paint
- )
- canvas.drawLine(
- 0f,
- height / seed * 3f,
- width.toFloat(),
- height / seed * 3f,
- paint
- )
- }
- }
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/ExposureBar.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/ExposureBar.kt
deleted file mode 100644
index 493f5cc83..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/ExposureBar.kt
+++ /dev/null
@@ -1,76 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.components
-
-import android.annotation.SuppressLint
-import android.content.Context
-import android.graphics.Canvas
-import android.util.AttributeSet
-import android.util.Log
-import android.view.MotionEvent
-import androidx.appcompat.widget.AppCompatSeekBar
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ExposureUiModel
-
-class ExposureBar : AppCompatSeekBar {
- constructor(context: Context) : super(context)
- constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
- context,
- attrs,
- defStyle
- )
-
- var onCompensationDragged: (Int) -> Unit = {}
-
- private var renderedExposure: ExposureUiModel? = null
-
- fun render(exposure: ExposureUiModel) {
- if (exposure == renderedExposure) return
- renderedExposure = exposure
-
- val range = exposure.range ?: return
-
- max = range.last
- min = range.first
- progress = exposure.progress
-
- onSizeChanged(width, height, 0, 0)
- }
-
- constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
-
- override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
- super.onSizeChanged(h, w, oldh, oldw)
- }
-
- @Synchronized
- override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
- super.onMeasure(heightMeasureSpec, widthMeasureSpec)
- setMeasuredDimension(measuredHeight, measuredWidth)
- }
-
- override fun onDraw(c: Canvas) {
- c.rotate(-90f)
- c.translate(-height.toFloat(), 0f)
- super.onDraw(c)
- }
-
- @SuppressLint("ClickableViewAccessibility")
- override fun onTouchEvent(event: MotionEvent): Boolean {
- if (!isEnabled) {
- return false
- }
- when (event.action) {
- MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP -> {
- progress = max - (max * event.y / (height / 2)).toInt()
-
- Log.i("progress", progress.toString())
- Log.i("max", max.toString())
-
- onCompensationDragged(progress)
-
- onSizeChanged(width, height, 0, 0)
- }
- MotionEvent.ACTION_CANCEL -> {
- }
- }
- return true
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/ZoomBar.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/ZoomBar.kt
deleted file mode 100644
index e70977520..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/components/ZoomBar.kt
+++ /dev/null
@@ -1,100 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.components
-
-import android.annotation.SuppressLint
-import android.content.Context
-import android.graphics.Bitmap
-import android.graphics.Canvas
-import android.graphics.drawable.BitmapDrawable
-import android.util.AttributeSet
-import android.view.LayoutInflater
-import android.view.MotionEvent
-import android.view.View
-import android.widget.TextView
-import androidx.appcompat.widget.AppCompatSeekBar
-import app.grapheneos.camera.R
-import app.grapheneos.camera.ui.viewfinder.screen.model.ZoomUiState
-import java.util.Locale
-import kotlin.math.roundToInt
-
-class ZoomBar : AppCompatSeekBar {
- constructor(context: Context) : super(context)
- constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
- context,
- attrs,
- defStyle
- )
-
- @SuppressLint("InflateParams")
- private var thumbView: View = LayoutInflater.from(context)
- .inflate(R.layout.zoom_bar_thumb, null, false)
-
- var onLinearZoomDragged: (Float) -> Unit = {}
-
- constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
-
- override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
- super.onSizeChanged(h, w, oldh, oldw)
- }
-
- private var renderedZoom: ZoomUiState? = null
-
- fun render(zoom: ZoomUiState) {
- if (zoom == renderedZoom) return
- renderedZoom = zoom
-
- progress = (zoom.linearZoom * 100).roundToInt()
-
- val textView: TextView = thumbView.findViewById(R.id.progress) as TextView
- val text = String.format(Locale.getDefault(), "%.1fx", zoom.zoomRatio)
-
- textView.text = text
-
- thumbView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
- val bitmap = Bitmap.createBitmap(
- thumbView.measuredWidth,
- thumbView.measuredHeight,
- Bitmap.Config.ARGB_8888
- )
- val canvas = Canvas(bitmap)
- thumbView.layout(0, 0, thumbView.measuredWidth, thumbView.measuredHeight)
- thumbView.draw(canvas)
- thumb = BitmapDrawable(resources, bitmap)
- onSizeChanged(width, height, 0, 0)
- }
-
- @Synchronized
- override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
- super.onMeasure(heightMeasureSpec, widthMeasureSpec)
- setMeasuredDimension(measuredHeight, measuredWidth)
- }
-
- override fun onDraw(c: Canvas) {
- c.rotate(-90f)
- c.translate(-height.toFloat(), 0f)
- super.onDraw(c)
- }
-
- @SuppressLint("ClickableViewAccessibility")
- override fun onTouchEvent(event: MotionEvent): Boolean {
- if (!isEnabled) {
- return false
- }
- when (event.action) {
- MotionEvent.ACTION_MOVE, MotionEvent.ACTION_DOWN -> {
- var progress = max - (max * event.y / height).toInt()
-
- if (progress < 1) progress = 1
- if (progress > 100) progress = 100
-
- onLinearZoomDragged(progress / LINEAR_ZOOM_SCALE)
- }
- MotionEvent.ACTION_CANCEL -> {
- }
- }
- return true
- }
-
- private companion object {
- private const val LINEAR_ZOOM_SCALE = 100f
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewFocusCallbacks.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewFocusCallbacks.kt
new file mode 100644
index 000000000..aa4b3f370
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewFocusCallbacks.kt
@@ -0,0 +1,8 @@
+package app.grapheneos.camera.ui.viewfinder.screen
+
+internal class PreviewFocusCallbacks(
+ val onPressed: (x: Float, y: Float) -> Unit,
+ val onTapped: () -> Unit,
+ val onLongPressed: () -> Unit,
+ val onGestureStarted: () -> Unit,
+)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewFrameHolder.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewFrameHolder.kt
index 9923e8bef..ed60822da 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewFrameHolder.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewFrameHolder.kt
@@ -25,6 +25,12 @@ interface PreviewFrameHolder {
fun prefetch()
+ /**
+ * The preview no longer looks like a copy made before this call, a zoom change for one, so
+ * that copy is not held in its place.
+ */
+ fun discardPrefetch()
+
fun clear()
fun release()
@@ -88,6 +94,10 @@ internal class PreviewFrameHolderImpl(
)
}
+ override fun discardPrefetch() {
+ synchronized(lock) { framePrefetchedAt = 0 }
+ }
+
override fun currentFrame(): Bitmap? {
return previewView.bitmap ?: lastFrame
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewPinchTracker.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewPinchTracker.kt
new file mode 100644
index 000000000..19c0579f9
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewPinchTracker.kt
@@ -0,0 +1,59 @@
+package app.grapheneos.camera.ui.viewfinder.screen
+
+import kotlin.math.abs
+
+// TODO: replace with Modifier.transformable on the preview once its gestures move to Compose.
+internal class PreviewPinchTracker(
+ private val spanSlop: Float,
+) {
+
+ var isPinching = false
+ private set
+
+ private var isTracking = false
+ private var initialSpan = 0f
+ private var previousSpan = 0f
+
+ fun restart(span: Float) {
+ isTracking = true
+ initialSpan = span
+ previousSpan = span
+ }
+
+ fun move(span: Float): Pinch? {
+ val pinch = when {
+ !isTracking || span <= 0f -> null
+ isPinching && previousSpan > 0f -> Pinch.Scaled(scaleFactor = span / previousSpan)
+ !isPinching && abs(span - initialSpan) > spanSlop -> Pinch.Started
+ else -> null
+ }
+ if (pinch != null) {
+ isPinching = true
+ previousSpan = span
+ }
+
+ return pinch
+ }
+
+ fun reject() {
+ isTracking = false
+ isPinching = false
+ }
+
+ fun stop(): Boolean {
+ val wasPinching = isPinching
+ isTracking = false
+ isPinching = false
+
+ return wasPinching
+ }
+
+ sealed interface Pinch {
+
+ data object Started : Pinch
+
+ data class Scaled(
+ val scaleFactor: Float,
+ ) : Pinch
+ }
+}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewZoomCallbacks.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewZoomCallbacks.kt
new file mode 100644
index 000000000..214591a93
--- /dev/null
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/PreviewZoomCallbacks.kt
@@ -0,0 +1,7 @@
+package app.grapheneos.camera.ui.viewfinder.screen
+
+internal class PreviewZoomCallbacks(
+ val onPinchStarted: () -> Unit,
+ val onPinchScaleChanged: (scaleFactor: Float) -> Unit,
+ val onPinchFinished: () -> Unit,
+)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderEffectHandler.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderEffectHandler.kt
index 974eef9c4..d387d87b9 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderEffectHandler.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderEffectHandler.kt
@@ -3,8 +3,6 @@ package app.grapheneos.camera.ui.viewfinder.screen
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
-import android.os.VibrationEffect
-import android.os.Vibrator
import android.provider.MediaStore
import android.provider.Settings
import android.view.View
@@ -37,9 +35,9 @@ internal interface ViewfinderEffectHandler {
internal class ViewfinderEffectHandlerImpl(
private val activity: MainActivity,
- private val vibrator: Vibrator,
private val capturedItemIntents: CapturedItemIntents,
private val onAction: (ViewfinderAction) -> Unit,
+ private val onPreviewFlashVisibilityChanged: (Boolean) -> Unit,
) : ViewfinderEffectHandler {
private val permissionRequests = AppPermission.entries.associateWith { permission ->
@@ -55,7 +53,6 @@ internal class ViewfinderEffectHandlerImpl(
is Effect.ShowMessage -> activity.showMessage(effect.message)
is Effect.ShowVideoQualityUnsupported -> showVideoQualityUnsupported(effect.quality)
is Effect.ShowQrResult -> showQrResult(effect.text)
- is Effect.PlayLevelHaptic -> playLevelHaptic()
is Effect.FlashPreview -> flashPreview(effect.selfIlluminate)
is Effect.ShowQrFormats -> showQrFormats()
is Effect.ShareCapturedItem -> share(effect.item)
@@ -138,10 +135,6 @@ internal class ViewfinderEffectHandlerImpl(
)
}
- private fun playLevelHaptic() {
- vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK))
- }
-
private fun flashPreview(selfIlluminate: Boolean) {
val animation: Animation = when {
selfIlluminate -> AlphaAnimation(SELF_ILLUMINATION_OVERLAY_ALPHA, 0f)
@@ -167,12 +160,14 @@ internal class ViewfinderEffectHandlerImpl(
animation.setAnimationListener(
object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {
+ onPreviewFlashVisibilityChanged(true)
activity.mainOverlay.visibility = View.VISIBLE
}
override fun onAnimationEnd(animation: Animation?) {
activity.mainOverlay.visibility = View.INVISIBLE
activity.mainOverlay.setImageResource(android.R.color.transparent)
+ onPreviewFlashVisibilityChanged(false)
}
override fun onAnimationRepeat(animation: Animation?) {}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderGestureHandler.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderGestureHandler.kt
index 5244a85ce..78532eb21 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderGestureHandler.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderGestureHandler.kt
@@ -11,10 +11,13 @@ import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.CameraAction
import app.grapheneos.camera.ui.viewfinder.screen.model.input.SwipeDirection
import kotlin.math.abs
+import kotlin.math.hypot
internal class ViewfinderGestureHandler(
context: Context,
private val onAction: (ViewfinderAction) -> Unit,
+ private val previewFocus: PreviewFocusCallbacks,
+ private val previewZoom: PreviewZoomCallbacks,
private val settingsPanelDrag: SettingsPanelDragCallbacks,
) : GestureDetector.SimpleOnGestureListener(),
View.OnTouchListener,
@@ -30,21 +33,36 @@ internal class ViewfinderGestureHandler(
touchSlop = ViewConfiguration.get(context).scaledTouchSlop.toFloat(),
)
+ private val pinchTracker = PreviewPinchTracker(
+ spanSlop = ViewConfiguration.get(context).scaledTouchSlop * 2f,
+ )
+
private var velocityTracker: VelocityTracker? = null
+ private var pointerCount = 0
+
private var isZooming = false
private var wasSwiping = false
+ private var pendingTap: PendingTap? = null
+
override fun onTouch(v: View, event: MotionEvent): Boolean {
- if (event.actionMasked == MotionEvent.ACTION_DOWN) {
- wasSwiping = false
- isZooming = false
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN -> {
+ wasSwiping = false
+ isZooming = false
+ }
+
+ MotionEvent.ACTION_POINTER_DOWN -> cancelTap()
+ MotionEvent.ACTION_CANCEL -> cancelTap()
}
+ pointerCount = event.pointerCount
scaleGestureDetector.onTouchEvent(event)
gestureDetector.onTouchEvent(event)
trackSettingsPanelDrag(event)
+ trackPinch(event)
if (event.action != MotionEvent.ACTION_UP) return true
@@ -58,30 +76,68 @@ internal class ViewfinderGestureHandler(
return true
}
- onAction(CameraAction.Preview.Tapped(x = event.x, y = event.y))
+ when (pendingTap) {
+ PendingTap.WITH_FOCUS -> {
+ onAction(CameraAction.Preview.Tapped)
+ previewFocus.onTapped()
+ }
+
+ PendingTap.WITHOUT_FOCUS -> onAction(CameraAction.Preview.Tapped)
+ null -> Unit
+ }
return v.performClick()
}
- override fun onScale(detector: ScaleGestureDetector): Boolean {
- isZooming = true
+ override fun onDown(event: MotionEvent): Boolean {
+ pendingTap = when {
+ settingsPanelDrag.isShown() -> PendingTap.WITHOUT_FOCUS
+ else -> PendingTap.WITH_FOCUS
+ }
- onAction(CameraAction.Preview.Pinched(scaleFactor = detector.scaleFactor))
+ if (pendingTap == PendingTap.WITH_FOCUS) {
+ previewFocus.onPressed(event.x, event.y)
+ }
return true
}
- // A pinch, or a double tap held and dragged, zooms only while the panel is down, and stops the
- // panel from following the same finger.
- override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
- if (settingsPanelDrag.isShown()) return false
+ override fun onLongPress(event: MotionEvent) {
+ if (pendingTap == PendingTap.WITH_FOCUS) {
+ onAction(CameraAction.Preview.Tapped)
+ previewFocus.onLongPressed()
+ }
+
+ pendingTap = null
+ }
+
+ override fun onScroll(
+ first: MotionEvent?,
+ current: MotionEvent,
+ distanceX: Float,
+ distanceY: Float,
+ ): Boolean {
+ cancelTap()
+
+ return false
+ }
- stopSettingsPanelDrag(velocity = 0f)
+ override fun onScale(detector: ScaleGestureDetector): Boolean {
+ isZooming = true
+
+ previewZoom.onPinchScaleChanged(detector.scaleFactor)
return true
}
- override fun onScaleEnd(detector: ScaleGestureDetector) {}
+ // The detector is left with the double tap held and dragged; pinchTracker follows two fingers.
+ override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
+ return pointerCount == 1 && startZoom()
+ }
+
+ override fun onScaleEnd(detector: ScaleGestureDetector) {
+ previewZoom.onPinchFinished()
+ }
override fun onFling(
e1: MotionEvent?,
@@ -108,6 +164,100 @@ internal class ViewfinderGestureHandler(
return direction != null
}
+ private fun startZoom(): Boolean {
+ val starts = !settingsPanelDrag.isShown()
+
+ if (starts) {
+ cancelTap()
+ stopSettingsPanelDrag(velocity = 0f)
+ previewZoom.onPinchStarted()
+ }
+
+ return starts
+ }
+
+ private fun trackPinch(event: MotionEvent) {
+ when (event.actionMasked) {
+ MotionEvent.ACTION_POINTER_DOWN -> pinchTracker.restart(
+ span = pointerSpan(
+ event = event,
+ liftedIndex = NO_POINTER,
+ ),
+ )
+
+ MotionEvent.ACTION_POINTER_UP -> when {
+ event.pointerCount > 2 -> pinchTracker.restart(
+ span = pointerSpan(
+ event = event,
+ liftedIndex = event.actionIndex,
+ ),
+ )
+
+ else -> stopPinch()
+ }
+
+ MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1) movePinch(event)
+ MotionEvent.ACTION_UP -> stopPinch()
+ MotionEvent.ACTION_CANCEL -> stopPinch()
+ }
+ }
+
+ private fun movePinch(event: MotionEvent) {
+ val span = pointerSpan(
+ event = event,
+ liftedIndex = NO_POINTER,
+ )
+
+ when (val pinch = pinchTracker.move(span)) {
+ null -> Unit
+ is PreviewPinchTracker.Pinch.Started -> if (!startZoom()) pinchTracker.reject()
+
+ is PreviewPinchTracker.Pinch.Scaled -> {
+ isZooming = true
+ previewZoom.onPinchScaleChanged(pinch.scaleFactor)
+ }
+ }
+ }
+
+ private fun stopPinch() {
+ if (pinchTracker.stop()) previewZoom.onPinchFinished()
+ }
+
+ private fun pointerSpan(
+ event: MotionEvent,
+ liftedIndex: Int,
+ ): Float {
+ var count = 0
+ var sumX = 0f
+ var sumY = 0f
+ for (index in 0 until event.pointerCount) {
+ if (index != liftedIndex) {
+ count++
+ sumX += event.getX(index)
+ sumY += event.getY(index)
+ }
+ }
+
+ var deviationX = 0f
+ var deviationY = 0f
+ for (index in 0 until event.pointerCount) {
+ if (index != liftedIndex) {
+ deviationX += abs(event.getX(index) - sumX / count)
+ deviationY += abs(event.getY(index) - sumY / count)
+ }
+ }
+
+ return hypot(deviationX, deviationY) * 2 / count
+ }
+
+ private fun cancelTap() {
+ if (pendingTap == PendingTap.WITH_FOCUS) {
+ previewFocus.onGestureStarted()
+ }
+
+ pendingTap = null
+ }
+
private fun trackSettingsPanelDrag(event: MotionEvent) {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
@@ -188,9 +338,15 @@ internal class ViewfinderGestureHandler(
return abs(distance) > SWIPE_THRESHOLD && abs(velocity) > SWIPE_VELOCITY_THRESHOLD
}
+ private enum class PendingTap {
+ WITH_FOCUS,
+ WITHOUT_FOCUS,
+ }
+
private companion object {
private const val SWIPE_THRESHOLD = 100
private const val SWIPE_VELOCITY_THRESHOLD = 100
private const val PIXELS_PER_SECOND = 1000
+ private const val NO_POINTER = -1
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderOverlay.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderOverlay.kt
index 738537ddf..9717200a4 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderOverlay.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderOverlay.kt
@@ -14,7 +14,7 @@ internal fun ViewfinderOverlay(
val uiState by screenModel.uiState.collectAsStateWithLifecycle()
ProvideContentRotation(
- degrees = uiState.rotation.iconDegrees,
+ degrees = uiState.iconRotationDegrees,
) {
content(uiState)
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderViewModel.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderViewModel.kt
index 6b69f66a0..836d444d8 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderViewModel.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderViewModel.kt
@@ -6,12 +6,12 @@ import androidx.lifecycle.viewModelScope
import app.grapheneos.camera.R
import app.grapheneos.camera.data.camera.model.BindOutcome
import app.grapheneos.camera.data.core.model.CameraMode
+import app.grapheneos.camera.data.core.model.DeviceOrientation
import app.grapheneos.camera.data.core.model.LensFacing
import app.grapheneos.camera.data.core.model.ModeSlot
import app.grapheneos.camera.data.permission.model.AppPermission
+import app.grapheneos.camera.data.settings.model.VolumeKeyAction
import app.grapheneos.camera.domain.core.model.CameraEntryPoint
-import app.grapheneos.camera.ui.core.screen.StateHolder
-import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderCameraControlsDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderCameraDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderCaptureDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderDialogDelegate
@@ -21,14 +21,11 @@ import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderModeDelegat
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderModeSwitchDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderOrientationDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderPermissionDelegate
-import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderPreviewControlsDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderRecordingDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderScreenWakeDelegate
import app.grapheneos.camera.ui.viewfinder.screen.delegate.ViewfinderSettingsDelegate
import app.grapheneos.camera.ui.viewfinder.screen.mapper.CameraBindSettingsMapper
import app.grapheneos.camera.ui.viewfinder.screen.mapper.ViewfinderUiStateMapper
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.VolumeKeyActionMapper
-import app.grapheneos.camera.ui.viewfinder.screen.model.LevelUiState
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.CameraAction
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.CaptureAction
@@ -41,12 +38,10 @@ import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.Setting
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderNavEvent as NavEvent
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderScreenEffect as Effect
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderUiState
-import app.grapheneos.camera.ui.viewfinder.screen.model.ZoomUiState
import app.grapheneos.camera.ui.viewfinder.screen.model.delegate.ViewfinderCameraEvent
import app.grapheneos.camera.ui.viewfinder.screen.model.delegate.ViewfinderCaptureEvent
import app.grapheneos.camera.ui.viewfinder.screen.model.delegate.ViewfinderRecordingEvent
import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderCaptureResult
-import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderLevelState
import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderState
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
@@ -62,9 +57,6 @@ interface ViewfinderScreenModel {
val uiState: StateFlow
- val zoomUiState: StateFlow
- val levelUiState: StateFlow
-
val effects: Flow
val navigationEvents: Flow
@@ -78,7 +70,6 @@ class ViewfinderViewModel @AssistedInject constructor(
private val settingsDelegate: ViewfinderSettingsDelegate,
private val modeDelegate: ViewfinderModeDelegate,
private val cameraDelegate: ViewfinderCameraDelegate,
- private val cameraControlsDelegate: ViewfinderCameraControlsDelegate,
private val captureDelegate: ViewfinderCaptureDelegate,
private val recordingDelegate: ViewfinderRecordingDelegate,
private val permissionDelegate: ViewfinderPermissionDelegate,
@@ -88,9 +79,7 @@ class ViewfinderViewModel @AssistedInject constructor(
private val galleryDelegate: ViewfinderGalleryDelegate,
private val dialogDelegate: ViewfinderDialogDelegate,
private val modeSwitchDelegate: ViewfinderModeSwitchDelegate,
- private val previewControlsDelegate: ViewfinderPreviewControlsDelegate,
private val cameraBindSettingsMapper: CameraBindSettingsMapper,
- private val volumeKeyActionMapper: VolumeKeyActionMapper,
uiStateMapper: ViewfinderUiStateMapper,
) : ViewModel(),
ViewfinderScreenModel {
@@ -104,22 +93,10 @@ class ViewfinderViewModel @AssistedInject constructor(
),
)
- private val levelStateHolder = StateHolder(
- initial = ViewfinderLevelState(),
- )
-
override val uiState: StateFlow = stateHolder.derive { state ->
uiStateMapper.map(state)
}
- override val zoomUiState: StateFlow = stateHolder.derive { state ->
- uiStateMapper.mapZoom(state)
- }
-
- override val levelUiState: StateFlow = levelStateHolder.derive { state ->
- uiStateMapper.mapLevel(state)
- }
-
override val effects: Flow = stateHolder.effects
override val navigationEvents: Flow = stateHolder.navigationEvents
@@ -145,15 +122,8 @@ class ViewfinderViewModel @AssistedInject constructor(
dialogDelegate.bind(stateHolder)
modeSwitchDelegate.bind(stateHolder)
cameraDelegate.bind(stateHolder)
+ orientationDelegate.bind(stateHolder)
- orientationDelegate.bind(
- stateHolder = stateHolder,
- levelStateHolder = levelStateHolder,
- )
- cameraControlsDelegate.bind(
- scope = viewModelScope,
- stateHolder = stateHolder,
- )
captureDelegate.bind(
scope = viewModelScope,
stateHolder = stateHolder,
@@ -162,10 +132,6 @@ class ViewfinderViewModel @AssistedInject constructor(
scope = viewModelScope,
stateHolder = stateHolder,
)
- previewControlsDelegate.bind(
- scope = viewModelScope,
- stateHolder = stateHolder,
- )
}
private fun prepareCaptureSession() {
@@ -176,7 +142,6 @@ class ViewfinderViewModel @AssistedInject constructor(
private fun trackSources() {
viewModelScope.launch { cameraDelegate.trackSession() }
- viewModelScope.launch { cameraControlsDelegate.trackZoom() }
viewModelScope.launch { settingsDelegate.trackSettings() }
viewModelScope.launch { settingsDelegate.trackModeSettings() }
viewModelScope.launch { settingsDelegate.trackSettingsPanelAvailability() }
@@ -192,12 +157,6 @@ class ViewfinderViewModel @AssistedInject constructor(
}
}
- viewModelScope.launch {
- cameraControlsDelegate.zoomChanges.collect {
- previewControlsDelegate.showZoomPanel()
- }
- }
-
viewModelScope.launch {
captureDelegate.captureEvents.collect { event ->
onCaptureEvent(event)
@@ -229,23 +188,8 @@ class ViewfinderViewModel @AssistedInject constructor(
is CameraAction.ModeSelected -> switchMode(action.mode)
is CameraAction.ModeStrip -> onModeStripAction(action)
is CameraAction.FlipCameraClicked -> onFlipCameraClicked()
- is CameraAction.ZoomStepKey -> onZoomStepKey(action)
is CameraAction.Preview -> onPreviewAction(action)
- is CameraAction.ZoomInKeyPressed -> cameraControlsDelegate.stepZoom(ZOOM_KEY_STEP)
- is CameraAction.ZoomOutKeyPressed -> cameraControlsDelegate.stepZoom(-ZOOM_KEY_STEP)
- is CameraAction.FocusKeyPressed -> cameraControlsDelegate.cancelFocus()
- is CameraAction.ZoomSliderDragged -> {
- cameraControlsDelegate.setLinearZoom(action.linearZoom)
- }
-
- is CameraAction.ExposureSliderDragged -> {
- cameraControlsDelegate.setExposureCompensation(action.compensationIndex)
- previewControlsDelegate.showExposurePanel()
- }
-
- is CameraAction.DisplayRotationChanged -> {
- onDisplayRotationChanged(action.rotation)
- }
+ is CameraAction.DisplayRotationChanged -> onDisplayRotationChanged(action.rotation)
}
}
@@ -262,15 +206,7 @@ class ViewfinderViewModel @AssistedInject constructor(
is CaptureAction.RetakeClicked -> retake()
is CaptureAction.ConfirmClicked -> captureDelegate.confirmResult(outputUri)
is CaptureAction.PlayResultClicked -> captureDelegate.playResult()
-
- is CaptureAction.VolumeKeyEvent -> {
- volumeKeyActionMapper
- .map(
- event = action,
- volumeKeyAction = state.settings.volumeKeyAction,
- )
- ?.let(::onAction)
- }
+ is CaptureAction.VolumeKeyEvent -> onVolumeKeyEvent(action)
}
}
@@ -352,18 +288,6 @@ class ViewfinderViewModel @AssistedInject constructor(
}
}
- private fun onZoomStepKey(action: CameraAction.ZoomStepKey) {
- when (action) {
- is CameraAction.ZoomStepKey.Released -> {
- cameraControlsDelegate.stopZoomStepping()
- }
-
- is CameraAction.ZoomStepKey.Pressed -> {
- cameraControlsDelegate.startZoomStepping(action.direction)
- }
- }
- }
-
private fun onModeStripAction(action: CameraAction.ModeStrip) {
when (action) {
is CameraAction.ModeStrip.Dragged -> modeSwitchDelegate.onStripDragged()
@@ -375,12 +299,8 @@ class ViewfinderViewModel @AssistedInject constructor(
private fun onPreviewAction(action: CameraAction.Preview) {
when (action) {
- is CameraAction.Preview.Pinched -> cameraControlsDelegate.scaleZoom(action.scaleFactor)
is CameraAction.Preview.Swiped -> modeSwitchDelegate.onPreviewSwiped(action.direction)
- is CameraAction.Preview.Tapped -> when {
- state.isSettingsPanelOpen -> settingsDelegate.closeSettingsPanel()
- else -> focusAt(x = action.x, y = action.y)
- }
+ is CameraAction.Preview.Tapped -> settingsDelegate.closeSettingsPanel()
}
}
@@ -458,7 +378,7 @@ class ViewfinderViewModel @AssistedInject constructor(
}
}
- private fun onDisplayRotationChanged(rotation: Int) {
+ private fun onDisplayRotationChanged(rotation: DeviceOrientation) {
cameraDelegate.setPreviewRotation(rotation)
orientationDelegate.setDisplayRotation(rotation)
}
@@ -507,14 +427,13 @@ class ViewfinderViewModel @AssistedInject constructor(
}
}
- private fun focusAt(
- x: Float,
- y: Float,
- ) {
- if (state.isQrMode()) return
+ private fun onVolumeKeyEvent(event: CaptureAction.VolumeKeyEvent) {
+ val takesShot = event is CaptureAction.VolumeKeyEvent.Released &&
+ state.settings.volumeKeyAction == VolumeKeyAction.SHUTTER
- cameraControlsDelegate.focusAt(x = x, y = y)
- previewControlsDelegate.showFocus(x = x, y = y)
+ if (takesShot) {
+ onCaptureKeyPressed()
+ }
}
private fun onCaptureKeyPressed() {
@@ -730,8 +649,6 @@ class ViewfinderViewModel @AssistedInject constructor(
captureDelegate.cancelPictureCapture()
- previewControlsDelegate.hideExposurePanel()
-
slotCurrentMode()
// Before the builder below reads it: the mode just slotted may store a different flash mode
@@ -777,7 +694,6 @@ class ViewfinderViewModel @AssistedInject constructor(
BindOutcome.BOUND -> {
cameraDelegate.announceBind()
- previewControlsDelegate.hideZoomPanel()
}
}
}
@@ -799,8 +715,4 @@ class ViewfinderViewModel @AssistedInject constructor(
interface Factory {
fun create(outputUri: Uri?): ViewfinderViewModel
}
-
- companion object {
- private const val ZOOM_KEY_STEP = 1f
- }
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderViewRenderer.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderViewRenderer.kt
index 2d0e74c17..205a5df78 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderViewRenderer.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/ViewfinderViewRenderer.kt
@@ -4,52 +4,31 @@ import android.animation.ValueAnimator
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Color
-import android.provider.Settings
import android.view.View
-import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageView
-import androidx.annotation.IdRes
import androidx.compose.ui.graphics.toArgb
-import androidx.constraintlayout.widget.ConstraintLayout
-import androidx.core.content.ContextCompat
import androidx.core.graphics.ColorUtils
-import androidx.core.view.updateLayoutParams
-import androidx.core.view.updateMargins
-import androidx.lifecycle.lifecycleScope
-import androidx.transition.Fade
-import androidx.transition.TransitionManager
import app.grapheneos.camera.R
import app.grapheneos.camera.data.core.model.AspectRatio
import app.grapheneos.camera.data.core.model.LensFacing
import app.grapheneos.camera.ui.activities.MainActivity
import app.grapheneos.camera.ui.core.theme.cameraColorScheme
-import app.grapheneos.camera.ui.viewfinder.screen.model.LevelUiState
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderUiState
-import app.grapheneos.camera.ui.viewfinder.screen.model.ZoomUiState
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.CaptureButtonUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.CaptureResultUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ExposureUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.FlipCameraUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.FocusRingUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.PreviewUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.QrUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.RecordingUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.RotationUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.SelfTimerUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ThirdOptionUiModel
import app.grapheneos.camera.util.setBlurBitmapCompat
import com.google.android.material.color.MaterialColors
-import kotlin.math.abs
-import kotlin.math.roundToInt
-import kotlin.time.Duration.Companion.milliseconds
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
internal class ViewfinderViewRenderer(
private val activity: MainActivity,
@@ -67,22 +46,18 @@ internal class ViewfinderViewRenderer(
private var renderedAspectRatio: AspectRatio? = null
private var renderedSensorOrientationDegrees: Int? = null
private var renderedIconRotation: Float? = null
- private var renderedLevelFrameRotation: Float? = null
private var renderedKeepScreenOn = false
private var renderedSelfIlluminating = false
private var litFraction = 0f
private var settingsPanelFraction = 0f
private val panelTextColor by lazy { panelTextColor() }
private var renderedThumbnail: Bitmap? = null
- private var renderedFocusRingId: Int? = null
private var renderedLensFacing: LensFacing? = null
private var renderedLastFrameVisible: Boolean? = null
private var renderedStreaming: Boolean? = null
private var blursLastFrame = true
private var renderedResultVisible = false
private var renderedResultImage: Bitmap? = null
- private var isFocusRingRendered = false
- private var focusRingTimeout: Job? = null
fun render(state: ViewfinderUiState) {
renderPreview(state)
@@ -94,42 +69,20 @@ internal class ViewfinderViewRenderer(
renderThirdOption(state.thirdOption)
renderSelfTimer(state.selfTimer)
renderRecording(state.recording)
- renderFocusRing(state.focusRing)
- renderExposure(state.exposure)
renderKeepScreenOn(state.keepScreenOn)
renderSelfIllumination(state.isSelfIlluminating)
- renderRotation(state.rotation)
+ renderRotation(state.iconRotationDegrees)
renderSettingsPanelAvailability(state.isSettingsPanelAvailable)
}
- fun renderZoom(zoom: ZoomUiState) {
- activity.zoomBar.render(zoom)
- renderPanel(
- panel = activity.zoomBarPanel,
- visible = zoom.panelVisible,
- fadeTarget = R.id.zoom_bar_panel,
- )
- }
-
- fun renderLevel(level: LevelUiState) {
- activity.gCircleFrame.visibility = visibleOrGone(level.visible)
-
- renderTilt(level.tiltDegrees)
- renderHorizon(level.horizonDegrees)
- }
-
private fun renderPreview(state: ViewfinderUiState) {
val result = state.captureResult
activity.previewView.visibility = visibleOrInvisible(!result.visible)
- activity.previewGrid.gridType = state.preview.gridType
renderBoundPreview(state.preview)
renderCaptureResult(result)
- renderLastFrame(
- preview = state.preview,
- isQrMode = state.mode.isQr,
- )
+ renderLastFrame(state.preview)
}
private fun renderCaptureResult(result: CaptureResultUiModel) {
@@ -167,10 +120,7 @@ internal class ViewfinderViewRenderer(
}
}
- private fun renderLastFrame(
- preview: PreviewUiModel,
- isQrMode: Boolean,
- ) {
+ private fun renderLastFrame(preview: PreviewUiModel) {
// A camera that stops streaming under a frame already up puts the still up again, now over
// the frame held for the bind.
val isUnchanged = preview.lastFrameVisible == renderedLastFrameVisible &&
@@ -182,14 +132,12 @@ internal class ViewfinderViewRenderer(
when {
isUnchanged -> Unit
preview.lastFrameVisible -> showLastFrame()
- else -> hideLastFrame(isQrMode)
+ else -> hideLastFrame()
}
}
// The blurred still that stands in for the preview whenever the camera is not streaming.
private fun showLastFrame() {
- activity.previewGrid.visibility = View.INVISIBLE
-
val lastFrame = activity.previewFrames.lastFrame
if (lastFrame == null || !blursLastFrame) return
@@ -202,9 +150,8 @@ internal class ViewfinderViewRenderer(
activity.mainOverlay.visibility = View.VISIBLE
}
- private fun hideLastFrame(isQrMode: Boolean) {
+ private fun hideLastFrame() {
activity.mainOverlay.visibility = View.INVISIBLE
- activity.previewGrid.visibility = visibleOrInvisible(!isQrMode)
}
private fun renderQr(qr: QrUiModel) {
@@ -264,8 +211,6 @@ internal class ViewfinderViewRenderer(
activity.cbText.text = selfTimer.badge
activity.cbText.visibility = visibleOrInvisible(selfTimer.badgeVisible)
- activity.cdTimer.visibility = visibleOrGone(isRunning)
- activity.cdTimer.render(selfTimer.remaining)
activity.cbCross.visibility = visibleOrInvisible(isRunning)
}
@@ -277,96 +222,6 @@ internal class ViewfinderViewRenderer(
activity.timerView.text = recording.timerText
}
- private fun renderFocusRing(focusRing: FocusRingUiModel?) {
- // A recreated screen is handed the last request again, and that ring has already faded.
- val newRing = focusRing?.takeIf { ring ->
- isFocusRingRendered && ring.id != renderedFocusRingId
- }
- renderedFocusRingId = focusRing?.id
- isFocusRingRendered = true
-
- newRing?.let(::showFocusRing)
- }
-
- private fun showFocusRing(focusRing: FocusRingUiModel) {
- val ring = activity.binding.focusRing
- val radius = ring.width / 2f
-
- ring.updateLayoutParams {
- updateMargins(
- left = (focusRing.x - radius).roundToInt(),
- top = (focusRing.y - radius).roundToInt(),
- )
- }
- ring.visibility = View.VISIBLE
- ring.alpha = 1f
-
- when {
- areSystemAnimationsEnabled() -> {
- ring.animate()
- .setStartDelay(FOCUS_RING_FADE_DELAY)
- .setDuration(FOCUS_RING_FADE_DURATION)
- .alpha(0f)
- .withEndAction { ring.visibility = View.INVISIBLE }
- .start()
- }
-
- else -> {
- focusRingTimeout?.cancel()
- focusRingTimeout = activity.lifecycleScope.launch {
- delay(FOCUS_RING_STILL_DURATION)
- ring.visibility = View.INVISIBLE
- }
- }
- }
- }
-
- private fun areSystemAnimationsEnabled(): Boolean {
- val resolver = activity.contentResolver
- val duration = Settings.Global.getFloat(
- resolver,
- Settings.Global.ANIMATOR_DURATION_SCALE,
- 1f,
- )
- val transition = Settings.Global.getFloat(
- resolver,
- Settings.Global.TRANSITION_ANIMATION_SCALE,
- 1f,
- )
-
- return duration != 0f && transition != 0f
- }
-
- private fun renderExposure(exposure: ExposureUiModel) {
- activity.exposureBar.render(exposure)
- renderPanel(
- panel = activity.exposureBarPanel,
- visible = exposure.panelVisible,
- fadeTarget = R.id.exposure_bar,
- )
- }
-
- private fun renderPanel(
- panel: View,
- visible: Boolean,
- @IdRes fadeTarget: Int,
- ) {
- val visibility = visibleOrGone(visible)
- if (panel.visibility == visibility) return
-
- val transition = Fade().addTarget(fadeTarget)
- transition.duration = when {
- visible -> 0L
- else -> PANEL_FADE_OUT_DURATION
- }
-
- TransitionManager.beginDelayedTransition(
- activity.window.decorView.rootView as ViewGroup,
- transition,
- )
- panel.visibility = visibility
- }
-
private fun renderKeepScreenOn(keepScreenOn: Boolean) {
if (keepScreenOn == renderedKeepScreenOn) return
renderedKeepScreenOn = keepScreenOn
@@ -486,20 +341,14 @@ internal class ViewfinderViewRenderer(
}
}
- private fun renderRotation(rotation: RotationUiModel) {
- if (rotation.iconDegrees != renderedIconRotation) {
- renderedIconRotation = rotation.iconDegrees
+ private fun renderRotation(degrees: Float) {
+ if (degrees != renderedIconRotation) {
+ renderedIconRotation = degrees
rotatingIcons().forEach { icon ->
- rotate(icon, rotation.iconDegrees)
+ rotate(icon, degrees)
}
}
-
- if (rotation.levelFrameDegrees != renderedLevelFrameRotation) {
- renderedLevelFrameRotation = rotation.levelFrameDegrees
-
- rotate(activity.gCircleFrame, rotation.levelFrameDegrees)
- }
}
private fun rotatingIcons(): List {
@@ -507,10 +356,6 @@ internal class ViewfinderViewRenderer(
activity.flipCameraCircle,
activity.cancelButtonView,
activity.thirdOption,
- activity.binding.exposurePlusIcon,
- activity.binding.exposureNegIcon,
- activity.binding.zoomInIcon,
- activity.binding.zoomOutIcon,
activity.micOffIcon,
activity.muteToggle,
)
@@ -539,61 +384,6 @@ internal class ViewfinderViewRenderer(
.start()
}
- private fun renderTilt(tiltDegrees: Int) {
- val binding = activity.binding
- val isLevel = tiltDegrees == 0
-
- binding.gCircle.rotation = tiltDegrees.toFloat()
- binding.gCircleLineZ.rotation = tiltDegrees.toFloat()
- binding.gCircleText.text = activity.getString(R.string.degree_format, abs(tiltDegrees))
-
- val thickness = when {
- isLevel -> LEVEL_LINE_THICKNESS_DP
- else -> TILTED_LINE_THICKNESS_DP
- }
-
- listOf(
- binding.gCircleLeftDash,
- binding.gCircleRightDash,
- binding.gCircleLineX,
- ).forEach { line ->
- line.updateLayoutParams {
- height = pixels(thickness)
- }
- }
- }
-
- private fun renderHorizon(horizonDegrees: Int) {
- val binding = activity.binding
- val isLevel = horizonDegrees == 0
-
- val lineBackground = when {
- isLevel -> R.drawable.yellow_shadow_rect
- else -> R.drawable.white_shadow_rect
- }
- val textColor = when {
- isLevel -> R.color.z_yellow
- else -> android.R.color.white
- }
-
- binding.gCircleLineX.setBackgroundResource(lineBackground)
- binding.gCircleLeftDash.setBackgroundResource(lineBackground)
- binding.gCircleRightDash.setBackgroundResource(lineBackground)
- binding.gCircleText.setTextColor(ContextCompat.getColor(activity, textColor))
- binding.gCircleLineZ.visibility = visibleOrGone(!isLevel)
-
- val clampedHorizon = horizonDegrees.coerceIn(-HORIZON_RANGE_DEGREES, HORIZON_RANGE_DEGREES)
- val horizonOffset = clampedHorizon / HORIZON_OFFSET_DIVISOR * pixels(HORIZON_OFFSET_DP)
-
- binding.gCircleLineZ.updateLayoutParams {
- bottomMargin = horizonOffset.toInt()
- }
- }
-
- private fun pixels(dp: Int): Int {
- return (dp * activity.resources.displayMetrics.density).toInt()
- }
-
private fun visibleOrInvisible(visible: Boolean): Int {
return when {
visible -> View.VISIBLE
@@ -611,17 +401,7 @@ internal class ViewfinderViewRenderer(
private companion object {
private const val ROTATION_DURATION = 400L
private const val SELF_ILLUMINATION_DURATION = 300L
- private const val PANEL_FADE_OUT_DURATION = 300L
- private const val FOCUS_RING_FADE_DELAY = 500L
- private const val FOCUS_RING_FADE_DURATION = 300L
private const val LENS_SWITCH_DURATION = 400L
private const val HALF_TURN_DEGREES = 180f
- private const val LEVEL_LINE_THICKNESS_DP = 4
- private const val TILTED_LINE_THICKNESS_DP = 2
- private const val HORIZON_RANGE_DEGREES = 45
- private const val HORIZON_OFFSET_DIVISOR = 60f
- private const val HORIZON_OFFSET_DP = 32
-
- private val FOCUS_RING_STILL_DURATION = 800.milliseconds
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCameraControlsDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCameraControlsDelegate.kt
deleted file mode 100644
index ba07dcf09..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCameraControlsDelegate.kt
+++ /dev/null
@@ -1,173 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.delegate
-
-import app.grapheneos.camera.data.camera.model.CameraZoomEvent
-import app.grapheneos.camera.data.camera.session.CameraSession
-import app.grapheneos.camera.data.sound.model.CameraSound
-import app.grapheneos.camera.domain.sound.usecase.PlayCameraSound
-import app.grapheneos.camera.ui.viewfinder.screen.ViewfinderStateHolder
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.NextZoomStopMapper
-import app.grapheneos.camera.ui.viewfinder.screen.model.input.ZoomDirection
-import javax.inject.Inject
-import kotlin.time.Duration.Companion.milliseconds
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.channels.Channel
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.receiveAsFlow
-import kotlinx.coroutines.launch
-
-interface ViewfinderCameraControlsDelegate {
-
- val zoomChanges: Flow
-
- fun bind(
- scope: CoroutineScope,
- stateHolder: ViewfinderStateHolder,
- )
-
- suspend fun trackZoom()
-
- fun stepZoom(step: Float)
- fun startZoomStepping(direction: ZoomDirection)
- fun stopZoomStepping()
- fun scaleZoom(scaleFactor: Float)
- fun setLinearZoom(linearZoom: Float)
-
- fun setExposureCompensation(compensationIndex: Int)
-
- fun focusAt(x: Float, y: Float)
- fun cancelFocus()
-}
-
-internal class ViewfinderCameraControlsDelegateImpl @Inject constructor(
- private val session: CameraSession,
- private val playCameraSound: PlayCameraSound,
- private val nextZoomStopMapper: NextZoomStopMapper,
-) : ViewfinderCameraControlsDelegate {
-
- private lateinit var scope: CoroutineScope
-
- private lateinit var stateHolder: ViewfinderStateHolder
-
- private var zoomStepping: Job? = null
-
- private val _zoomChanges = Channel(capacity = Channel.BUFFERED)
- override val zoomChanges: Flow = _zoomChanges.receiveAsFlow()
-
- override fun bind(
- scope: CoroutineScope,
- stateHolder: ViewfinderStateHolder,
- ) {
- this.scope = scope
- this.stateHolder = stateHolder
- }
-
- override suspend fun trackZoom() {
- session.zoomEvents.collect { event ->
- refreshZoom()
-
- when (event) {
- is CameraZoomEvent.Loaded -> Unit
- is CameraZoomEvent.Changed -> _zoomChanges.trySend(Unit)
- }
- }
- }
-
- override fun stepZoom(step: Float) {
- val state = stateHolder.state.value
- if (state.isQrMode()) return
-
- val zoom = session.zoom ?: return
- val requested = zoom.zoomRatio + step
-
- val zoomRatio = when {
- requested > zoom.maxZoomRatio -> zoom.maxZoomRatio
- requested < zoom.minZoomRatio -> zoom.minZoomRatio
- // smoothly transition between wide angle camera to primary one
- zoom.zoomRatio < 1f && requested > 1f -> 1f
- else -> requested
- }
-
- session.setZoomRatio(zoomRatio)
- }
-
- override fun startZoomStepping(direction: ZoomDirection) {
- stopZoomStepping()
-
- zoomStepping = scope.launch {
- while (stepToNextZoomStop(direction)) {
- delay(ZOOM_STOP_INTERVAL)
- }
- }
- }
-
- override fun stopZoomStepping() {
- zoomStepping?.cancel()
- }
-
- override fun scaleZoom(scaleFactor: Float) {
- val zoomRatio = session.zoom?.let { it.zoomRatio * scaleFactor } ?: 1f
-
- session.setZoomRatio(zoomRatio)
- }
-
- override fun setLinearZoom(linearZoom: Float) {
- session.setLinearZoom(linearZoom)
- }
-
- override fun setExposureCompensation(compensationIndex: Int) {
- session.setExposureCompensationIndex(compensationIndex)
-
- stateHolder.update {
- val exposure = it.session.exposure?.copy(compensationIndex = compensationIndex)
-
- it.copy(session = it.session.copy(exposure = exposure))
- }
- }
-
- override fun focusAt(
- x: Float,
- y: Float,
- ) {
- val state = stateHolder.state.value
-
- session.startFocusAndMetering(
- x = x,
- y = y,
- autoCancelSeconds = state.settings.focusTimeoutSeconds,
- )
-
- if (!state.isVideoMode()) {
- scope.launch {
- playCameraSound(CameraSound.FOCUS_START)
- }
- }
- }
-
- override fun cancelFocus() {
- if (stateHolder.state.value.isQrMode()) return
-
- // cancel any manual focus
- // CameraX will start the continuous autofocus (if supported) automatically
- session.cancelFocusAndMetering()
- }
-
- private fun refreshZoom() {
- stateHolder.update {
- it.copy(session = it.session.copy(zoom = session.zoom))
- }
- }
-
- private fun stepToNextZoomStop(direction: ZoomDirection): Boolean {
- val zoom = session.zoom.takeUnless { stateHolder.state.value.isQrMode() }
- val stop = zoom?.let { nextZoomStopMapper.map(zoom = it, direction = direction) }
-
- stop?.let(session::setZoomRatio)
- return stop != null
- }
-
- private companion object {
- private val ZOOM_STOP_INTERVAL = 500.milliseconds
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCameraDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCameraDelegate.kt
index 4fb25844c..6c2d5fdc7 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCameraDelegate.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCameraDelegate.kt
@@ -10,6 +10,7 @@ import app.grapheneos.camera.data.camera.model.CameraCapabilities
import app.grapheneos.camera.data.camera.model.CameraSessionEvent
import app.grapheneos.camera.data.camera.session.CameraSession
import app.grapheneos.camera.data.camera.session.TorchControl
+import app.grapheneos.camera.data.core.model.DeviceOrientation
import app.grapheneos.camera.data.core.model.ExtensionMode
import app.grapheneos.camera.data.core.model.FlashMode
import app.grapheneos.camera.data.core.model.LensFacing
@@ -55,7 +56,7 @@ interface ViewfinderCameraDelegate {
fun unbindCamera()
fun switchLens(extensionMode: ExtensionMode?): Boolean
- fun setPreviewRotation(rotation: Int)
+ fun setPreviewRotation(rotation: DeviceOrientation)
fun applyFlashMode(value: FlashMode)
fun toggleTorch()
@@ -204,17 +205,6 @@ internal class ViewfinderCameraDelegateImpl @Inject constructor(
override fun announceBind() {
loadTabs()
-
- session.reattachZoomState()
-
- stateHolder.update {
- it.copy(
- session = it.session.copy(
- zoom = session.zoom,
- exposure = session.exposure,
- ),
- )
- }
}
override fun unbindCamera() {
@@ -236,7 +226,7 @@ internal class ViewfinderCameraDelegateImpl @Inject constructor(
return isSupported
}
- override fun setPreviewRotation(rotation: Int) {
+ override fun setPreviewRotation(rotation: DeviceOrientation) {
session.setPreviewRotation(rotation)
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCaptureDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCaptureDelegate.kt
index 44d434715..58e2c1bae 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCaptureDelegate.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderCaptureDelegate.kt
@@ -312,6 +312,7 @@ internal class ViewfinderCaptureDelegateImpl @Inject constructor(
finish(pending)
if (pending.isCancelled) {
+ Log.w(TAG, "a cancelled picture capture failed", event.cause)
return
}
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderOrientationDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderOrientationDelegate.kt
index 1e0eed847..17842514e 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderOrientationDelegate.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderOrientationDelegate.kt
@@ -1,139 +1,55 @@
package app.grapheneos.camera.ui.viewfinder.screen.delegate
-import app.grapheneos.camera.data.orientation.model.DeviceMotion
+import app.grapheneos.camera.data.core.model.DeviceOrientation
import app.grapheneos.camera.data.orientation.repository.DeviceOrientationRepository
-import app.grapheneos.camera.ui.core.screen.StateHolder
import app.grapheneos.camera.ui.viewfinder.screen.ViewfinderStateHolder
-import app.grapheneos.camera.ui.viewfinder.screen.mapper.ViewfinderLevelStateMapper
-import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderScreenEffect as Effect
-import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderLevelState
import javax.inject.Inject
-import kotlin.math.abs
-import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.coroutineScope
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.flow.collectLatest
-import kotlinx.coroutines.flow.distinctUntilChanged
-import kotlinx.coroutines.flow.drop
-import kotlinx.coroutines.flow.filterNot
-import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
interface ViewfinderOrientationDelegate {
- fun bind(
- stateHolder: ViewfinderStateHolder,
- levelStateHolder: StateHolder,
- )
+ fun bind(stateHolder: ViewfinderStateHolder)
- fun setDisplayRotation(rotation: Int)
+ fun setDisplayRotation(rotation: DeviceOrientation)
suspend fun trackOrientation()
}
internal class ViewfinderOrientationDelegateImpl @Inject constructor(
private val deviceOrientationRepository: DeviceOrientationRepository,
- private val levelStateMapper: ViewfinderLevelStateMapper,
) : ViewfinderOrientationDelegate {
private lateinit var stateHolder: ViewfinderStateHolder
- private lateinit var levelStateHolder: StateHolder
-
- override fun bind(
- stateHolder: ViewfinderStateHolder,
- levelStateHolder: StateHolder,
- ) {
+ override fun bind(stateHolder: ViewfinderStateHolder) {
this.stateHolder = stateHolder
- this.levelStateHolder = levelStateHolder
}
- override fun setDisplayRotation(rotation: Int) {
- stateHolder.update { state ->
- state.copy(displayRotation = rotation)
- }
+ override fun setDisplayRotation(rotation: DeviceOrientation) {
+ stateHolder.update { state -> state.copy(displayRotation = rotation) }
}
override suspend fun trackOrientation() {
coroutineScope {
- launch { trackMotion() }
+ launch { trackDeviceOrientation() }
launch { trackAutoRotate() }
- launch { hideLevelOutsidePhotoMode() }
- launch { announceLevelReached() }
}
}
- private suspend fun trackMotion() {
- var previousMotion: DeviceMotion? = null
-
- deviceOrientationRepository.motion().collect { motion ->
+ private suspend fun trackDeviceOrientation() {
+ deviceOrientationRepository.orientation.collect { orientation ->
stateHolder.update { state ->
- state.copy(deviceOrientation = motion.orientation)
- }
-
- levelStateHolder.update { current ->
- levelStateMapper.map(
- current = current,
- previousMotion = previousMotion,
- motion = motion,
- state = stateHolder.state.value,
- )
+ state.copy(deviceOrientation = orientation)
}
- previousMotion = motion
}
}
private suspend fun trackAutoRotate() {
- deviceOrientationRepository.autoRotateEnabled().collect { enabled ->
+ deviceOrientationRepository.autoRotateEnabled.collect { enabled ->
stateHolder.update { state ->
state.copy(autoRotateEnabled = enabled)
}
}
}
-
- private suspend fun hideLevelOutsidePhotoMode() {
- stateHolder.state
- .map { state -> state.showsLevel() }
- .distinctUntilChanged()
- .filterNot { shown -> shown }
- .collect {
- levelStateHolder.update { level ->
- level.copy(visible = false)
- }
- }
- }
-
- private suspend fun announceLevelReached() {
- var isArmed = true
- var isAnnounced = false
-
- levelStateHolder.state
- .map { level -> level.tiltDegrees }
- .distinctUntilChanged()
- .drop(1)
- .collectLatest { tilt ->
- val isLevel = tilt == 0
- val hasTiltedAway = !isAnnounced || abs(tilt) > REARM_TILT_DEGREES
-
- when {
- isLevel && isArmed -> {
- isArmed = false
- isAnnounced = false
- delay(LEVEL_HOLD)
- isAnnounced = true
- stateHolder.postEffect(Effect.PlayLevelHaptic)
- }
-
- !isLevel && hasTiltedAway -> {
- isArmed = true
- }
- }
- }
- }
-
- private companion object {
- private const val REARM_TILT_DEGREES = 5
-
- private val LEVEL_HOLD = 250.milliseconds
- }
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderPreviewControlsDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderPreviewControlsDelegate.kt
deleted file mode 100644
index 113582076..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderPreviewControlsDelegate.kt
+++ /dev/null
@@ -1,118 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.delegate
-
-import app.grapheneos.camera.ui.viewfinder.screen.ViewfinderStateHolder
-import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderFocusRequest
-import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderPreviewControlsState as Controls
-import javax.inject.Inject
-import kotlin.time.Duration.Companion.seconds
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
-
-interface ViewfinderPreviewControlsDelegate {
-
- fun bind(
- scope: CoroutineScope,
- stateHolder: ViewfinderStateHolder,
- )
-
- fun showFocus(x: Float, y: Float)
-
- fun showZoomPanel()
- fun hideZoomPanel()
-
- fun showExposurePanel()
- fun hideExposurePanel()
-}
-
-internal class ViewfinderPreviewControlsDelegateImpl @Inject constructor() :
- ViewfinderPreviewControlsDelegate {
-
- private lateinit var scope: CoroutineScope
-
- private lateinit var stateHolder: ViewfinderStateHolder
-
- private val zoomPanel = AutoHidingPanel { controls, shown ->
- controls.copy(isZoomPanelShown = shown)
- }
-
- private val exposurePanel = AutoHidingPanel { controls, shown ->
- controls.copy(isExposurePanelShown = shown)
- }
-
- override fun bind(
- scope: CoroutineScope,
- stateHolder: ViewfinderStateHolder,
- ) {
- this.scope = scope
- this.stateHolder = stateHolder
- }
-
- override fun showFocus(
- x: Float,
- y: Float,
- ) {
- stateHolder.update { state ->
- val controls = state.previewControls
- val request = ViewfinderFocusRequest(
- x = x,
- y = y,
- id = (controls.focusRequest?.id ?: 0) + 1,
- )
-
- state.copy(previewControls = controls.copy(focusRequest = request))
- }
-
- exposurePanel.show()
- zoomPanel.show()
- }
-
- override fun showZoomPanel() {
- zoomPanel.show()
- }
-
- override fun hideZoomPanel() {
- zoomPanel.hide()
- }
-
- override fun showExposurePanel() {
- exposurePanel.show()
- }
-
- override fun hideExposurePanel() {
- exposurePanel.hide()
- }
-
- private inner class AutoHidingPanel(
- private val withShown: (Controls, Boolean) -> Controls,
- ) {
-
- private var timeout: Job? = null
-
- fun show() {
- setShown(true)
-
- timeout?.cancel()
- timeout = scope.launch {
- delay(PANEL_VISIBILITY_DURATION)
- setShown(false)
- }
- }
-
- fun hide() {
- timeout?.cancel()
- setShown(false)
- }
-
- private fun setShown(shown: Boolean) {
- stateHolder.update { state ->
- state.copy(previewControls = withShown(state.previewControls, shown))
- }
- }
- }
-
- private companion object {
- private val PANEL_VISIBILITY_DURATION = 2.seconds
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderSettingsDelegate.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderSettingsDelegate.kt
index c4f76b7b1..4fb830fe7 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderSettingsDelegate.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/delegate/ViewfinderSettingsDelegate.kt
@@ -129,6 +129,8 @@ internal class ViewfinderSettingsDelegateImpl @Inject constructor(
}
override fun closeSettingsPanel() {
+ if (!stateHolder.state.value.isSettingsPanelOpen) return
+
stateHolder.postNavEvent(NavEvent.CloseSettingsPanel)
}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/NextZoomStopMapper.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/NextZoomStopMapper.kt
deleted file mode 100644
index 2ec4195de..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/NextZoomStopMapper.kt
+++ /dev/null
@@ -1,35 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.mapper
-
-import app.grapheneos.camera.data.camera.model.CameraZoom
-import app.grapheneos.camera.ui.viewfinder.screen.model.input.ZoomDirection
-import javax.inject.Inject
-
-interface NextZoomStopMapper {
-
- fun map(
- zoom: CameraZoom,
- direction: ZoomDirection,
- ): Float?
-}
-
-internal class NextZoomStopMapperImpl @Inject constructor() : NextZoomStopMapper {
-
- override fun map(
- zoom: CameraZoom,
- direction: ZoomDirection,
- ): Float? {
- val stops = (listOf(zoom.minZoomRatio) + MIDDLE_STOPS + zoom.maxZoomRatio)
- .filter { it in zoom.minZoomRatio..zoom.maxZoomRatio }
- .distinct()
- .sorted()
-
- return when (direction) {
- ZoomDirection.IN -> stops.firstOrNull { it > zoom.zoomRatio }
- ZoomDirection.OUT -> stops.lastOrNull { it < zoom.zoomRatio }
- }
- }
-
- private companion object {
- val MIDDLE_STOPS = listOf(1f, 2f)
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/ViewfinderLevelStateMapper.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/ViewfinderLevelStateMapper.kt
deleted file mode 100644
index ec29c79ec..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/ViewfinderLevelStateMapper.kt
+++ /dev/null
@@ -1,75 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.mapper
-
-import app.grapheneos.camera.data.orientation.model.DeviceMotion
-import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderLevelState
-import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderState
-import javax.inject.Inject
-import kotlin.math.abs
-
-interface ViewfinderLevelStateMapper {
-
- fun map(
- current: ViewfinderLevelState,
- state: ViewfinderState,
- motion: DeviceMotion,
- previousMotion: DeviceMotion?,
- ): ViewfinderLevelState
-}
-
-internal class ViewfinderLevelStateMapperImpl @Inject constructor() : ViewfinderLevelStateMapper {
-
- override fun map(
- current: ViewfinderLevelState,
- state: ViewfinderState,
- motion: DeviceMotion,
- previousMotion: DeviceMotion?,
- ): ViewfinderLevelState {
- val visible = current.visible || isSteadyNearLevel(
- previousMotion = previousMotion,
- motion = motion,
- )
-
- return when {
- !state.showsLevel() || isBeyondLevelRange(motion) -> {
- current.copy(visible = false)
- }
-
- state.capture.isSelfTimerRunning() -> {
- current.copy(visible = visible)
- }
-
- else -> {
- ViewfinderLevelState(
- visible = visible,
- tiltDegrees = motion.tiltDegrees,
- horizonDegrees = motion.horizonDegrees,
- )
- }
- }
- }
-
- private fun isBeyondLevelRange(motion: DeviceMotion): Boolean {
- return abs(motion.tiltDegrees) > LEVEL_RANGE_DEGREES ||
- abs(motion.horizonDegrees) > LEVEL_RANGE_DEGREES
- }
-
- private fun isSteadyNearLevel(
- previousMotion: DeviceMotion?,
- motion: DeviceMotion,
- ): Boolean {
- val previousTilt = previousMotion?.tiltDegrees ?: 0
- val previousHorizon = previousMotion?.horizonDegrees ?: 0
-
- return abs(motion.tiltDegrees) <= TILT_ENTRY_DEGREES &&
- abs(motion.horizonDegrees) <= HORIZON_ENTRY_DEGREES &&
- abs(motion.tiltDegrees - previousTilt) < STEADY_DEGREES &&
- abs(motion.horizonDegrees - previousHorizon) < STEADY_DEGREES
- }
-
- private companion object {
- private const val LEVEL_RANGE_DEGREES = 45
- private const val TILT_ENTRY_DEGREES = 8
- private const val HORIZON_ENTRY_DEGREES = 25
- private const val STEADY_DEGREES = 5
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/ViewfinderUiStateMapper.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/ViewfinderUiStateMapper.kt
index 72230430f..9f84341f6 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/ViewfinderUiStateMapper.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/ViewfinderUiStateMapper.kt
@@ -1,23 +1,16 @@
package app.grapheneos.camera.ui.viewfinder.screen.mapper
-import android.view.Surface
import app.grapheneos.camera.R
import app.grapheneos.camera.data.settings.model.VolumeKeyAction
-import app.grapheneos.camera.ui.viewfinder.screen.model.LevelUiState
import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderUiState
-import app.grapheneos.camera.ui.viewfinder.screen.model.ZoomUiState
-import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderLevelState
import app.grapheneos.camera.ui.viewfinder.screen.model.state.ViewfinderState
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.CaptureButtonUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.CaptureResultUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ExposureUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.FlipCameraUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.FocusRingUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ModeTabsUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.PreviewUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.QrUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.RecordingUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.RotationUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.SelfTimerUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ThirdOptionUiModel
import app.grapheneos.camera.util.formatVideoDuration
@@ -27,10 +20,6 @@ import kotlinx.collections.immutable.toImmutableSet
interface ViewfinderUiStateMapper {
fun map(state: ViewfinderState): ViewfinderUiState
-
- fun mapZoom(state: ViewfinderState): ZoomUiState
-
- fun mapLevel(state: ViewfinderLevelState): LevelUiState
}
internal class ViewfinderUiStateMapperImpl @Inject constructor() : ViewfinderUiStateMapper {
@@ -47,9 +36,7 @@ internal class ViewfinderUiStateMapperImpl @Inject constructor() : ViewfinderUiS
selfTimer = selfTimer(state),
recording = recording(state),
qr = qr(state),
- focusRing = focusRing(state),
- exposure = exposure(state),
- rotation = rotation(state),
+ iconRotationDegrees = iconRotationDegrees(state),
captureResult = captureResult(state),
keepScreenOn = keepScreenOn(state),
isSelfIlluminating = state.selfIlluminates(),
@@ -59,33 +46,10 @@ internal class ViewfinderUiStateMapperImpl @Inject constructor() : ViewfinderUiS
)
}
- override fun mapZoom(state: ViewfinderState): ZoomUiState {
- val zoom = state.session.zoom
- val panelVisible = state.previewControls.isZoomPanelShown
-
- return when (zoom) {
- null -> ZoomUiState(panelVisible = panelVisible)
- else -> ZoomUiState(
- zoomRatio = zoom.zoomRatio,
- linearZoom = zoom.linearZoom,
- panelVisible = panelVisible,
- )
- }
- }
-
- override fun mapLevel(state: ViewfinderLevelState): LevelUiState {
- return LevelUiState(
- visible = state.visible,
- tiltDegrees = state.tiltDegrees,
- horizonDegrees = state.horizonDegrees,
- )
- }
-
private fun preview(state: ViewfinderState): PreviewUiModel {
return PreviewUiModel(
aspectRatio = state.aspectRatio(),
sensorOrientationDegrees = state.session.sensorOrientationDegrees,
- gridType = state.settings.gridType,
isStreaming = state.preview.isStreaming,
lastFrameVisible = state.preview.isLastFrameShown,
blursLastFrame = !state.isCaptureSession,
@@ -276,55 +240,20 @@ internal class ViewfinderUiStateMapperImpl @Inject constructor() : ViewfinderUiS
)
}
- private fun focusRing(state: ViewfinderState): FocusRingUiModel? {
- val request = state.previewControls.focusRequest ?: return null
-
- return FocusRingUiModel(
- x = request.x,
- y = request.y,
- id = request.id,
- )
- }
-
- private fun exposure(state: ViewfinderState): ExposureUiModel {
- val exposure = state.session.exposure
-
- return ExposureUiModel(
- range = exposure?.compensationRange,
- progress = exposure?.compensationIndex ?: 0,
- panelVisible = state.previewControls.isExposurePanelShown,
- )
- }
-
- private fun rotation(state: ViewfinderState): RotationUiModel {
- val deviceRotation = deviceRotationDegrees(state)
-
- return RotationUiModel(
- iconDegrees = when {
- state.autoRotateEnabled -> deviceRotation
- else -> 0f
- },
- levelFrameDegrees = deviceRotation,
- )
+ private fun iconRotationDegrees(state: ViewfinderState): Float {
+ return when {
+ state.autoRotateEnabled -> deviceRotationDegrees(state)
+ else -> 0f
+ }
}
private fun deviceRotationDegrees(state: ViewfinderState): Float {
val orientation = state.recording.orientationAtStart
?: state.deviceOrientation
?: return 0f
- val displayDegrees = displayDegrees(state.displayRotation)
+ val degrees = state.displayRotation.degrees - orientation.degrees
- return (displayDegrees - orientation.degrees).mod(FULL_TURN_DEGREES).toFloat()
- }
-
- @Suppress("MagicNumber")
- private fun displayDegrees(displayRotation: Int): Int {
- return when (displayRotation) {
- Surface.ROTATION_90 -> 270
- Surface.ROTATION_180 -> 180
- Surface.ROTATION_270 -> 90
- else -> 0
- }
+ return degrees.mod(FULL_TURN_DEGREES).toFloat()
}
private fun captureResult(state: ViewfinderState): CaptureResultUiModel {
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/VolumeKeyActionMapper.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/VolumeKeyActionMapper.kt
deleted file mode 100644
index 65c8e2ace..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/mapper/VolumeKeyActionMapper.kt
+++ /dev/null
@@ -1,50 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.mapper
-
-import app.grapheneos.camera.data.settings.model.VolumeKeyAction
-import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction
-import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.CameraAction
-import app.grapheneos.camera.ui.viewfinder.screen.model.ViewfinderAction.CaptureAction
-import app.grapheneos.camera.ui.viewfinder.screen.model.input.VolumeKey
-import app.grapheneos.camera.ui.viewfinder.screen.model.input.ZoomDirection
-import javax.inject.Inject
-
-interface VolumeKeyActionMapper {
-
- fun map(
- event: CaptureAction.VolumeKeyEvent,
- volumeKeyAction: VolumeKeyAction,
- ): ViewfinderAction?
-}
-
-internal class VolumeKeyActionMapperImpl @Inject constructor() : VolumeKeyActionMapper {
-
- override fun map(
- event: CaptureAction.VolumeKeyEvent,
- volumeKeyAction: VolumeKeyAction,
- ): ViewfinderAction? {
- return when (volumeKeyAction) {
- VolumeKeyAction.SHUTTER -> shutter(event)
- VolumeKeyAction.ZOOM -> zoom(event)
- VolumeKeyAction.VOLUME -> null
- VolumeKeyAction.OFF -> null
- }
- }
-
- private fun shutter(event: CaptureAction.VolumeKeyEvent): ViewfinderAction? {
- return when (event) {
- is CaptureAction.VolumeKeyEvent.Pressed -> null
- is CaptureAction.VolumeKeyEvent.Released -> CaptureAction.CaptureKeyPressed
- }
- }
-
- private fun zoom(event: CaptureAction.VolumeKeyEvent): ViewfinderAction {
- return when (event) {
- is CaptureAction.VolumeKeyEvent.Released -> CameraAction.ZoomStepKey.Released
-
- is CaptureAction.VolumeKeyEvent.Pressed -> when (event.key) {
- VolumeKey.UP -> CameraAction.ZoomStepKey.Pressed(ZoomDirection.IN)
- VolumeKey.DOWN -> CameraAction.ZoomStepKey.Pressed(ZoomDirection.OUT)
- }
- }
- }
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/LevelUiState.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/LevelUiState.kt
deleted file mode 100644
index def7d1c9f..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/LevelUiState.kt
+++ /dev/null
@@ -1,10 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model
-
-import androidx.compose.runtime.Immutable
-
-@Immutable
-data class LevelUiState(
- val visible: Boolean = false,
- val tiltDegrees: Int = 0,
- val horizonDegrees: Int = 0,
-)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderAction.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderAction.kt
index d9d78d76b..990b6a432 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderAction.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderAction.kt
@@ -1,12 +1,12 @@
package app.grapheneos.camera.ui.viewfinder.screen.model
import app.grapheneos.camera.data.core.model.CameraMode
+import app.grapheneos.camera.data.core.model.DeviceOrientation
import app.grapheneos.camera.data.permission.model.AppPermission
import app.grapheneos.camera.ui.core.model.QuickSetting
import app.grapheneos.camera.ui.viewfinder.screen.ViewfinderHost
import app.grapheneos.camera.ui.viewfinder.screen.model.input.SwipeDirection
import app.grapheneos.camera.ui.viewfinder.screen.model.input.VolumeKey
-import app.grapheneos.camera.ui.viewfinder.screen.model.input.ZoomDirection
sealed interface ViewfinderAction {
@@ -14,37 +14,14 @@ sealed interface ViewfinderAction {
data object FlipCameraClicked : CameraAction
- data object ZoomInKeyPressed : CameraAction
-
- data object ZoomOutKeyPressed : CameraAction
-
- data object FocusKeyPressed : CameraAction
-
- data class ZoomSliderDragged(
- val linearZoom: Float,
- ) : CameraAction
-
- data class ExposureSliderDragged(
- val compensationIndex: Int,
- ) : CameraAction
-
data class ModeSelected(
val mode: CameraMode,
) : CameraAction
data class DisplayRotationChanged(
- val rotation: Int,
+ val rotation: DeviceOrientation,
) : CameraAction
- sealed interface ZoomStepKey : CameraAction {
-
- data class Pressed(
- val direction: ZoomDirection,
- ) : ZoomStepKey
-
- data object Released : ZoomStepKey
- }
-
sealed interface ModeStrip : CameraAction {
data object Dragged : ModeStrip
@@ -62,14 +39,7 @@ sealed interface ViewfinderAction {
sealed interface Preview : CameraAction {
- data class Tapped(
- val x: Float,
- val y: Float,
- ) : Preview
-
- data class Pinched(
- val scaleFactor: Float,
- ) : Preview
+ data object Tapped : Preview
data class Swiped(
val direction: SwipeDirection,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderScreenEffect.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderScreenEffect.kt
index 28593f73d..8e06bffec 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderScreenEffect.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderScreenEffect.kt
@@ -9,8 +9,6 @@ import app.grapheneos.camera.data.permission.model.AppPermission
sealed interface ViewfinderScreenEffect {
- data object PlayLevelHaptic : ViewfinderScreenEffect
-
data object ShowQrFormats : ViewfinderScreenEffect
data class ShowMessage(
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderUiState.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderUiState.kt
index 0cddd11ce..8d89c3373 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderUiState.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ViewfinderUiState.kt
@@ -4,14 +4,11 @@ import androidx.compose.runtime.Immutable
import app.grapheneos.camera.data.core.model.CameraMode
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.CaptureButtonUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.CaptureResultUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ExposureUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.FlipCameraUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.FocusRingUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ModeTabsUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.PreviewUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.QrUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.RecordingUiModel
-import app.grapheneos.camera.ui.viewfinder.screen.model.ui.RotationUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.SelfTimerUiModel
import app.grapheneos.camera.ui.viewfinder.screen.model.ui.ThirdOptionUiModel
@@ -23,14 +20,12 @@ data class ViewfinderUiState(
val captureButton: CaptureButtonUiModel = CaptureButtonUiModel(),
val flipCamera: FlipCameraUiModel = FlipCameraUiModel(),
val thirdOption: ThirdOptionUiModel = ThirdOptionUiModel(),
- val cancelButtonVisible: Boolean = true,
val selfTimer: SelfTimerUiModel = SelfTimerUiModel(),
val recording: RecordingUiModel = RecordingUiModel(),
val qr: QrUiModel = QrUiModel(),
- val focusRing: FocusRingUiModel? = null,
- val exposure: ExposureUiModel = ExposureUiModel(),
- val rotation: RotationUiModel = RotationUiModel(),
val captureResult: CaptureResultUiModel = CaptureResultUiModel(),
+ val iconRotationDegrees: Float = 0f,
+ val cancelButtonVisible: Boolean = true,
val keepScreenOn: Boolean = false,
val isSelfIlluminating: Boolean = false,
val isSettingsPanelAvailable: Boolean = false,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ZoomUiState.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ZoomUiState.kt
deleted file mode 100644
index ff5d98234..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ZoomUiState.kt
+++ /dev/null
@@ -1,10 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model
-
-import androidx.compose.runtime.Immutable
-
-@Immutable
-data class ZoomUiState(
- val zoomRatio: Float = 1f,
- val linearZoom: Float = 0f,
- val panelVisible: Boolean = false,
-)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/input/ZoomDirection.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/input/ZoomDirection.kt
deleted file mode 100644
index a58da391a..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/input/ZoomDirection.kt
+++ /dev/null
@@ -1,6 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model.input
-
-enum class ZoomDirection {
- IN,
- OUT,
-}
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderFocusRequest.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderFocusRequest.kt
deleted file mode 100644
index f771923a5..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderFocusRequest.kt
+++ /dev/null
@@ -1,7 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model.state
-
-data class ViewfinderFocusRequest(
- val x: Float,
- val y: Float,
- val id: Int,
-)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderLevelState.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderLevelState.kt
deleted file mode 100644
index de7cf75ab..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderLevelState.kt
+++ /dev/null
@@ -1,7 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model.state
-
-data class ViewfinderLevelState(
- val visible: Boolean = false,
- val tiltDegrees: Int = 0,
- val horizonDegrees: Int = 0,
-)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderPreviewControlsState.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderPreviewControlsState.kt
deleted file mode 100644
index c68cdda91..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderPreviewControlsState.kt
+++ /dev/null
@@ -1,7 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model.state
-
-data class ViewfinderPreviewControlsState(
- val focusRequest: ViewfinderFocusRequest? = null,
- val isZoomPanelShown: Boolean = false,
- val isExposurePanelShown: Boolean = false,
-)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderSessionState.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderSessionState.kt
index 13e65a576..f125d7148 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderSessionState.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderSessionState.kt
@@ -1,7 +1,5 @@
package app.grapheneos.camera.ui.viewfinder.screen.model.state
-import app.grapheneos.camera.data.camera.model.CameraExposure
-import app.grapheneos.camera.data.camera.model.CameraZoom
import app.grapheneos.camera.data.core.model.CameraMode
import app.grapheneos.camera.data.core.model.LensFacing
@@ -11,7 +9,5 @@ data class ViewfinderSessionState(
val isTorchOn: Boolean = false,
val isQrResultShown: Boolean = false,
val sensorOrientationDegrees: Int? = null,
- val zoom: CameraZoom? = null,
- val exposure: CameraExposure? = null,
val availableModes: Set = emptySet(),
)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderState.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderState.kt
index 3cd18acf2..ffd7ffa85 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderState.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/state/ViewfinderState.kt
@@ -1,6 +1,5 @@
package app.grapheneos.camera.ui.viewfinder.screen.model.state
-import android.view.Surface
import app.grapheneos.camera.data.core.model.AspectRatio
import app.grapheneos.camera.data.core.model.CameraMode
import app.grapheneos.camera.data.core.model.DeviceOrientation
@@ -30,9 +29,8 @@ data class ViewfinderState(
val missingPermissions: Set = emptySet(),
val dialog: ViewfinderDialog? = null,
val isSettingsPanelOpen: Boolean = false,
- val previewControls: ViewfinderPreviewControlsState = ViewfinderPreviewControlsState(),
val deviceOrientation: DeviceOrientation? = null,
- val displayRotation: Int = Surface.ROTATION_0,
+ val displayRotation: DeviceOrientation = DeviceOrientation.DEGREES_0,
val autoRotateEnabled: Boolean = false,
val keepsScreenAwake: Boolean = false,
) {
@@ -84,10 +82,6 @@ data class ViewfinderState(
return settings.includeAudio && AppPermission.MICROPHONE in missingPermissions
}
- fun showsLevel(): Boolean {
- return settings.gyroscopeSuggestions && isPhotoMode()
- }
-
fun selfIlluminates(): Boolean {
return modeSettings.flashMode == FlashMode.SELF_ILLUMINATION &&
session.lensFacing == LensFacing.FRONT
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/ExposureUiModel.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/ExposureUiModel.kt
deleted file mode 100644
index 1c7a9d04d..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/ExposureUiModel.kt
+++ /dev/null
@@ -1,10 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model.ui
-
-import androidx.compose.runtime.Immutable
-
-@Immutable
-data class ExposureUiModel(
- val range: IntRange? = null,
- val progress: Int = 0,
- val panelVisible: Boolean = false,
-)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/FocusRingUiModel.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/FocusRingUiModel.kt
deleted file mode 100644
index 2fd7696c7..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/FocusRingUiModel.kt
+++ /dev/null
@@ -1,10 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model.ui
-
-import androidx.compose.runtime.Immutable
-
-@Immutable
-data class FocusRingUiModel(
- val x: Float,
- val y: Float,
- val id: Int,
-)
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/PreviewUiModel.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/PreviewUiModel.kt
index 2008547db..bd9e4f20e 100644
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/PreviewUiModel.kt
+++ b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/PreviewUiModel.kt
@@ -2,13 +2,11 @@ package app.grapheneos.camera.ui.viewfinder.screen.model.ui
import androidx.compose.runtime.Immutable
import app.grapheneos.camera.data.core.model.AspectRatio
-import app.grapheneos.camera.data.settings.model.GridType
@Immutable
data class PreviewUiModel(
val aspectRatio: AspectRatio = AspectRatio.RATIO_4_3,
val sensorOrientationDegrees: Int? = null,
- val gridType: GridType = GridType.NONE,
val isStreaming: Boolean = false,
val lastFrameVisible: Boolean = false,
val blursLastFrame: Boolean = true,
diff --git a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/RotationUiModel.kt b/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/RotationUiModel.kt
deleted file mode 100644
index c48e523af..000000000
--- a/app/src/main/java/app/grapheneos/camera/ui/viewfinder/screen/model/ui/RotationUiModel.kt
+++ /dev/null
@@ -1,9 +0,0 @@
-package app.grapheneos.camera.ui.viewfinder.screen.model.ui
-
-import androidx.compose.runtime.Immutable
-
-@Immutable
-data class RotationUiModel(
- val iconDegrees: Float = 0f,
- val levelFrameDegrees: Float = 0f,
-)
diff --git a/app/src/main/res/drawable/exposure_icon.xml b/app/src/main/res/drawable/exposure_icon.xml
deleted file mode 100644
index 6e4f4d9ac..000000000
--- a/app/src/main/res/drawable/exposure_icon.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
diff --git a/app/src/main/res/drawable/exposure_neg.xml b/app/src/main/res/drawable/exposure_neg.xml
deleted file mode 100644
index dbde23dfc..000000000
--- a/app/src/main/res/drawable/exposure_neg.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-
diff --git a/app/src/main/res/drawable/exposure_plus.xml b/app/src/main/res/drawable/exposure_plus.xml
deleted file mode 100644
index aaad104a9..000000000
--- a/app/src/main/res/drawable/exposure_plus.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
diff --git a/app/src/main/res/drawable/exposure_thumb.xml b/app/src/main/res/drawable/exposure_thumb.xml
deleted file mode 100644
index 7dfa5c57a..000000000
--- a/app/src/main/res/drawable/exposure_thumb.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
diff --git a/app/src/main/res/drawable/focus_ring.xml b/app/src/main/res/drawable/focus_ring.xml
deleted file mode 100644
index 2bfda6754..000000000
--- a/app/src/main/res/drawable/focus_ring.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/drawable/thumb.xml b/app/src/main/res/drawable/thumb.xml
deleted file mode 100644
index ed3e50309..000000000
--- a/app/src/main/res/drawable/thumb.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
- -
-
-
-
-
-
-
-
diff --git a/app/src/main/res/drawable/white_shadow_rect.xml b/app/src/main/res/drawable/white_shadow_rect.xml
deleted file mode 100644
index 77849a317..000000000
--- a/app/src/main/res/drawable/white_shadow_rect.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
diff --git a/app/src/main/res/drawable/yellow_shadow_rect.xml b/app/src/main/res/drawable/yellow_shadow_rect.xml
deleted file mode 100644
index 090f8b6ab..000000000
--- a/app/src/main/res/drawable/yellow_shadow_rect.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
diff --git a/app/src/main/res/drawable/zoom_in.xml b/app/src/main/res/drawable/zoom_in.xml
deleted file mode 100644
index 7ed1f5f16..000000000
--- a/app/src/main/res/drawable/zoom_in.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
diff --git a/app/src/main/res/drawable/zoom_out.xml b/app/src/main/res/drawable/zoom_out.xml
deleted file mode 100644
index 85e9df71d..000000000
--- a/app/src/main/res/drawable/zoom_out.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
index c6ee5f052..e7f940794 100644
--- a/app/src/main/res/layout/activity_main.xml
+++ b/app/src/main/res/layout/activity_main.xml
@@ -45,17 +45,6 @@
app:layout_constraintEnd_toEndOf="@id/preview"
app:layout_constraintBottom_toBottomOf="@id/preview" />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml
index f01e073bf..4a3b9e2fc 100644
--- a/app/src/main/res/values/colors.xml
+++ b/app/src/main/res/values/colors.xml
@@ -8,8 +8,6 @@
#ffe8cf
- #ffdf00
-
#E1E3E5
#ff0000
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 5a8557056..004b029db 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -30,8 +30,9 @@
Cancel Timer
Capture
- %d°
Exposure compensation
+ Reset exposure compensation
+ %1$s EV
Flip Camera
Loading camera
Mute audio
@@ -51,7 +52,8 @@
Turn torch on
Unmute audio
Record Video
- Zoom
+ ×
+ Adjust zoom