8fe09a4f2fc2
feat: D10 CodexRestore camera path — choose view (scan/import cards) + CameraX live Aztec scan (permission gate, corner guides, 10s timeout/retry) feeding existing decode→restore; CameraX 1.3.4 deps + CAMERA permission (v2.1.35)
- time
- 2026-06-09 04:58 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- peach remaining gaps
- parent
- 29a0599352cf
↓ peach-android-8fe09a4f.tar.gzatlas at this save
files changed8 files
app/build.gradle+4 −0app/drafts/D10/CodexAztecFrame.kt+0 −69app/drafts/D10/CodexRestoreChooseAndCamera.kt+0 −367app/src/main/AndroidManifest.xml+2 −0app/src/main/java/com/peachpasswords/codex/CodexAztecFrame.kt+69 −0app/src/main/java/com/peachpasswords/ui/codex/CodexRestoreChooseAndCamera.kt+367 −0app/src/main/java/com/peachpasswords/ui/codex/CodexRestoreScreen.kt+24 −2app/src/main/java/com/peachpasswords/ui/codex/CodexViewModel.kt+61 −0app/build.gradle+4 −0
@@ -97,6 +97,10 @@9797 implementation "com.google.dagger:hilt-android:2.51.1"9898 kapt "com.google.dagger:hilt-compiler:2.51.1"9999 implementation "com.google.zxing:core:3.5.3"100+ implementation "androidx.camera:camera-core:1.3.4"101+ implementation "androidx.camera:camera-camera2:1.3.4"102+ implementation "androidx.camera:camera-lifecycle:1.3.4"103+ implementation "androidx.camera:camera-view:1.3.4"100104 implementation "com.squareup.okhttp3:okhttp:4.12.0"101105 implementation "org.bouncycastle:bcprov-jdk18on:1.78.1"102106 implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1"app/drafts/D10/CodexAztecFrame.kt+0 −69
@@ -1,69 +0,0 @@1-package com.peachpasswords.codex2-3-import androidx.camera.core.ImageProxy4-import com.google.zxing.BinaryBitmap5-import com.google.zxing.DecodeHintType6-import com.google.zxing.PlanarYUVLuminanceSource7-import com.google.zxing.aztec.AztecReader8-import com.google.zxing.common.GlobalHistogramBinarizer9-import com.google.zxing.common.HybridBinarizer10-11-/**12- * Live-camera Aztec decode for the Codex restore camera path (D10).13- *14- * Distinct from [CodexAztec.decode], which decodes a tightly-cropped render of a15- * single PDF cell. A camera frame is a full scene that may contain one Aztec among16- * the printed 6×6 grid, so we use the scene detector (no PURE_BARCODE) and read the17- * Y plane directly — converting the YUV_420_888 frame to an ARGB bitmap every frame18- * would be wasteful at preview frame rates.19- */20-object CodexAztecFrame {21-22- /**23- * Decode the first readable Aztec code from a CameraX [ImageProxy]24- * (YUV_420_888). Returns the raw text, or null if no code reads. Does NOT25- * close the proxy — the caller owns its lifecycle.26- */27- fun decode(image: ImageProxy): String? {28- val plane = image.planes.getOrNull(0) ?: return null29- val buffer = plane.buffer30- val data = ByteArray(buffer.remaining())31- buffer.get(data)32-33- val width = image.width34- val height = image.height35- val rowStride = plane.rowStride36-37- // PlanarYUVLuminanceSource expects a tightly-packed Y plane; when the38- // camera reports row padding (rowStride > width) we repack row by row.39- val luma: ByteArray = if (rowStride == width) {40- data41- } else {42- val packed = ByteArray(width * height)43- for (row in 0 until height) {44- System.arraycopy(data, row * rowStride, packed, row * width, width)45- }46- packed47- }48-49- val source = PlanarYUVLuminanceSource(50- luma, width, height, 0, 0, width, height, false,51- )52- val hints = mapOf(DecodeHintType.TRY_HARDER to true)53- // Cross both binarizers: Hybrid adapts to uneven lighting, Global handles54- // flat well-lit prints. Rotating the source covers codes shot sideways.55- val attempts = listOf(56- BinaryBitmap(HybridBinarizer(source)),57- BinaryBitmap(GlobalHistogramBinarizer(source)),58- BinaryBitmap(HybridBinarizer(source.rotateCounterClockwise())),59- )60- for (binary in attempts) {61- try {62- return AztecReader().decode(binary, hints).text63- } catch (_: Exception) {64- // try next strategy65- }66- }67- return null68- }69-}app/drafts/D10/CodexRestoreChooseAndCamera.kt+0 −367
@@ -1,367 +0,0 @@1-// D10 — Codex restore "choose" surface + camera scan path.2-//3-// Drop-in composables for ui/codex/CodexRestoreScreen.kt. Self-contained: depends4-// only on what already exists in the module plus the camera additions drafted in5-// CodexViewModel.camera.kt (CameraScanState, chooseRestore/startCameraScan/6-// cameraTimedOut/onCameraFrame on CodexViewModel) and CodexAztecFrame (decode).7-//8-// Package is the real screen's package so these merge in with no import churn.9-// Required NEW imports for CodexRestoreScreen.kt are listed in INTEGRATION.md.10-//11-// CameraX deps must be added to app/build.gradle (see INTEGRATION.md). Until then12-// this file will not compile in isolation — that is expected; the orchestrator13-// adds the deps and the camera VM members in the same pass.14-15-package com.peachpasswords.ui.codex16-17-import android.Manifest18-import android.content.Intent19-import android.content.pm.PackageManager20-import android.net.Uri21-import android.provider.Settings22-import androidx.activity.compose.rememberLauncherForActivityResult23-import androidx.activity.result.contract.ActivityResultContracts24-import androidx.camera.core.CameraSelector25-import androidx.camera.core.ImageAnalysis26-import androidx.camera.core.Preview27-import androidx.camera.lifecycle.ProcessCameraProvider28-import androidx.camera.view.PreviewView29-import androidx.compose.foundation.BorderStroke30-import androidx.compose.foundation.background31-import androidx.compose.foundation.border32-import androidx.compose.foundation.clickable33-import androidx.compose.foundation.layout.Arrangement34-import androidx.compose.foundation.layout.Box35-import androidx.compose.foundation.layout.Column36-import androidx.compose.foundation.layout.Row37-import androidx.compose.foundation.layout.Spacer38-import androidx.compose.foundation.layout.aspectRatio39-import androidx.compose.foundation.layout.fillMaxSize40-import androidx.compose.foundation.layout.fillMaxWidth41-import androidx.compose.foundation.layout.height42-import androidx.compose.foundation.layout.padding43-import androidx.compose.foundation.shape.RoundedCornerShape44-import androidx.compose.material.icons.Icons45-import androidx.compose.material.icons.outlined.Description46-import androidx.compose.material.icons.outlined.NoPhotography47-import androidx.compose.material.icons.outlined.PhotoCamera48-import androidx.compose.material3.Icon49-import androidx.compose.material3.Text50-import androidx.compose.runtime.Composable51-import androidx.compose.runtime.DisposableEffect52-import androidx.compose.runtime.LaunchedEffect53-import androidx.compose.runtime.getValue54-import androidx.compose.runtime.mutableStateOf55-import androidx.compose.runtime.remember56-import androidx.compose.runtime.setValue57-import androidx.compose.ui.Alignment58-import androidx.compose.ui.Modifier59-import androidx.compose.ui.draw.clip60-import androidx.compose.ui.draw.drawBehind61-import androidx.compose.ui.geometry.Offset62-import androidx.compose.ui.graphics.Color63-import androidx.compose.ui.graphics.StrokeCap64-import androidx.compose.ui.platform.LocalContext65-import androidx.compose.ui.text.font.FontStyle66-import androidx.compose.ui.unit.dp67-import androidx.compose.ui.unit.sp68-import androidx.compose.ui.viewinterop.AndroidView69-import androidx.core.content.ContextCompat70-import androidx.lifecycle.compose.LocalLifecycleOwner71-import com.peachpasswords.ui.theme.PeachColors72-import com.peachpasswords.ui.theme.PeachType73-import java.util.concurrent.Executors74-75-/**76- * The two-card "choose" surface shown before any restore work begins. Replaces77- * the old straight-to-PDF-picker behaviour: the user explicitly picks scanning78- * with the camera or importing the previously-saved PDF.79- *80- * Glass-panel cards mirror the OnboardingScreen / SurfaceElevated style.81- */82-@Composable83-internal fun CodexRestoreChoose(84- accent: Color,85- onScanCamera: () -> Unit,86- onImportPdf: () -> Unit,87-) {88- Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {89- ChooseCard(90- icon = Icons.Outlined.PhotoCamera,91- iconTint = accent,92- title = "Scan with camera",93- body = "Point your camera at the printed Aztec grid",94- accent = accent,95- onClick = onScanCamera,96- )97- ChooseCard(98- icon = Icons.Outlined.Description,99- iconTint = PeachColors.T2,100- title = "Import PDF",101- body = "Import the PDF you saved when generating your Codex",102- accent = accent,103- onClick = onImportPdf,104- )105- }106-}107-108-@Composable109-private fun ChooseCard(110- icon: androidx.compose.ui.graphics.vector.ImageVector,111- iconTint: Color,112- title: String,113- body: String,114- accent: Color,115- onClick: () -> Unit,116-) {117- Row(118- Modifier119- .fillMaxWidth()120- .clip(RoundedCornerShape(18.dp))121- .background(PeachColors.SurfaceElevated)122- .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))123- .clickable(onClick = onClick)124- .padding(horizontal = 18.dp, vertical = 18.dp),125- verticalAlignment = Alignment.CenterVertically,126- horizontalArrangement = Arrangement.spacedBy(16.dp),127- ) {128- Icon(icon, contentDescription = null, tint = iconTint, modifier = Modifier.height(24.dp))129- Column(Modifier.fillMaxWidth()) {130- Text(131- title,132- color = PeachColors.T0,133- fontFamily = PeachType.Display,134- fontStyle = FontStyle.Italic,135- fontSize = 19.sp,136- )137- Spacer(Modifier.height(4.dp))138- Text(body, color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp)139- }140- }141-}142-143-/**144- * Camera capture surface. Requests CAMERA at first composition; on denial shows a145- * settings-deep-link error card. On grant, binds a CameraX preview + an146- * ImageAnalysis analyzer that hands each frame to [onFrame] (the VM decodes one147- * Aztec, accumulates it, and reports back whether a full payload reconstructed).148- *149- * A 10s no-detection timer flips to a retry overlay; [onTimeout] lets the VM150- * record the timeout, and [onRetry] restarts scanning (resets the timer).151- *152- * @param onFrame analyze one frame; returns true once decoding is complete so the153- * analyzer stops. The implementation MUST close the ImageProxy.154- */155-@Composable156-internal fun CodexCameraScan(157- accent: Color,158- timedOut: Boolean,159- codesFound: Int,160- onFrame: (androidx.camera.core.ImageProxy) -> Boolean,161- onTimeout: () -> Unit,162- onRetry: () -> Unit,163-) {164- val context = LocalContext.current165- var granted by remember {166- mutableStateOf(167- ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==168- PackageManager.PERMISSION_GRANTED,169- )170- }171- val permLauncher = rememberLauncherForActivityResult(172- ActivityResultContracts.RequestPermission(),173- ) { granted = it }174-175- LaunchedEffect(Unit) {176- if (!granted) permLauncher.launch(Manifest.permission.CAMERA)177- }178-179- if (!granted) {180- CameraDeniedCard(accent)181- return182- }183-184- Column(Modifier.fillMaxWidth()) {185- Box(186- Modifier187- .fillMaxWidth()188- .aspectRatio(4f / 3f)189- .clip(RoundedCornerShape(8.dp)),190- ) {191- CameraPreview(onFrame = onFrame)192- CornerGuides(accent)193- Text(194- if (codesFound == 0) "scanning…" else "$codesFound code${if (codesFound == 1) "" else "s"} read",195- color = accent,196- fontFamily = PeachType.Mono,197- fontSize = 10.sp,198- modifier = Modifier199- .align(Alignment.BottomCenter)200- .padding(bottom = 10.dp),201- )202- if (timedOut) NoDetectionOverlay(accent, onRetry)203- }204- }205-206- // Single 10s window per scan attempt; retry re-keys this effect via codesFound207- // reset + the parent re-entering the Scanning state. Cancel if a code arrives.208- LaunchedEffect(timedOut) {209- if (!timedOut) {210- kotlinx.coroutines.delay(10_000)211- onTimeout()212- }213- }214-}215-216-@Composable217-private fun CameraPreview(onFrame: (androidx.camera.core.ImageProxy) -> Boolean) {218- val context = LocalContext.current219- val lifecycleOwner = LocalLifecycleOwner.current220- val analysisExecutor = remember { Executors.newSingleThreadExecutor() }221-222- DisposableEffect(Unit) {223- onDispose { analysisExecutor.shutdown() }224- }225-226- AndroidView(227- modifier = Modifier.fillMaxSize(),228- factory = { ctx ->229- val previewView = PreviewView(ctx).apply {230- scaleType = PreviewView.ScaleType.FILL_CENTER231- }232- val providerFuture = ProcessCameraProvider.getInstance(ctx)233- providerFuture.addListener({234- val provider = providerFuture.get()235- val preview = Preview.Builder().build().also {236- it.setSurfaceProvider(previewView.surfaceProvider)237- }238- val analysis = ImageAnalysis.Builder()239- .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)240- .build()241- analysis.setAnalyzer(analysisExecutor) { proxy ->242- try {243- onFrame(proxy)244- } finally {245- proxy.close()246- }247- }248- try {249- provider.unbindAll()250- provider.bindToLifecycle(251- lifecycleOwner,252- CameraSelector.DEFAULT_BACK_CAMERA,253- preview,254- analysis,255- )256- } catch (_: Exception) {257- // bind can fail if the lifecycle is already stopped; the258- // preview simply stays blank — the timeout overlay covers it.259- }260- }, ContextCompat.getMainExecutor(ctx))261- previewView262- },263- )264-}265-266-/** Accent corner guides: 20dp arms, 2dp stroke, at each corner of the frame. */267-@Composable268-private fun CornerGuides(accent: Color) {269- Box(270- Modifier271- .fillMaxSize()272- .padding(10.dp)273- .drawBehind {274- val arm = 20.dp.toPx()275- val w = 2.dp.toPx()276- fun corner(ox: Float, oy: Float, dx: Float, dy: Float) {277- drawLine(accent, Offset(ox, oy), Offset(ox + dx * arm, oy), w, StrokeCap.Round)278- drawLine(accent, Offset(ox, oy), Offset(ox, oy + dy * arm), w, StrokeCap.Round)279- }280- corner(0f, 0f, 1f, 1f)281- corner(size.width, 0f, -1f, 1f)282- corner(0f, size.height, 1f, -1f)283- corner(size.width, size.height, -1f, -1f)284- },285- )286-}287-288-@Composable289-private fun NoDetectionOverlay(accent: Color, onRetry: () -> Unit) {290- Column(291- Modifier292- .fillMaxSize()293- .background(Color(0xCC0A0703))294- .padding(24.dp),295- verticalArrangement = Arrangement.Center,296- horizontalAlignment = Alignment.CenterHorizontally,297- ) {298- Text(299- "No Aztec codes detected — try better lighting",300- color = PeachColors.T1,301- fontFamily = PeachType.Mono,302- fontSize = 11.sp,303- )304- Spacer(Modifier.height(16.dp))305- Box(306- Modifier307- .clip(RoundedCornerShape(8.dp))308- .border(BorderStroke(1.dp, accent), RoundedCornerShape(8.dp))309- .clickable(onClick = onRetry)310- .padding(horizontal = 18.dp, vertical = 10.dp),311- ) {312- Text("Try again", color = accent, fontFamily = PeachType.Mono, fontSize = 11.sp)313- }314- }315-}316-317-@Composable318-private fun CameraDeniedCard(accent: Color) {319- val context = LocalContext.current320- Column(321- Modifier322- .fillMaxWidth()323- .clip(RoundedCornerShape(18.dp))324- .background(PeachColors.SurfaceElevated)325- .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))326- .padding(20.dp),327- horizontalAlignment = Alignment.CenterHorizontally,328- ) {329- Icon(330- Icons.Outlined.NoPhotography,331- contentDescription = null,332- tint = PeachColors.T2,333- modifier = Modifier.height(24.dp),334- )335- Spacer(Modifier.height(12.dp))336- Text(337- "Camera access needed",338- color = PeachColors.T0,339- fontFamily = PeachType.Display,340- fontStyle = FontStyle.Italic,341- fontSize = 19.sp,342- )343- Spacer(Modifier.height(6.dp))344- Text(345- "Grant camera permission in Settings to scan your Codex",346- color = PeachColors.T2,347- fontFamily = PeachType.Mono,348- fontSize = 10.sp,349- )350- Spacer(Modifier.height(18.dp))351- Box(352- Modifier353- .clip(RoundedCornerShape(8.dp))354- .border(BorderStroke(1.dp, accent), RoundedCornerShape(8.dp))355- .clickable {356- val intent = Intent(357- Settings.ACTION_APPLICATION_DETAILS_SETTINGS,358- Uri.fromParts("package", context.packageName, null),359- ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)360- context.startActivity(intent)361- }362- .padding(horizontal = 18.dp, vertical = 10.dp),363- ) {364- Text("Open Settings", color = accent, fontFamily = PeachType.Mono, fontSize = 11.sp)365- }366- }367-}app/src/main/AndroidManifest.xml+2 −0
@@ -9,6 +9,8 @@99 <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />1010 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />1111 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />12+ <uses-permission android:name="android.permission.CAMERA" />13+ <uses-feature android:name="android.hardware.camera.any" android:required="false" />1214 1315 <application1416 android:name=".PeachApplication"app/src/main/java/com/peachpasswords/codex/CodexAztecFrame.kt+69 −0
@@ -0,0 +1,69 @@1+package com.peachpasswords.codex2+3+import androidx.camera.core.ImageProxy4+import com.google.zxing.BinaryBitmap5+import com.google.zxing.DecodeHintType6+import com.google.zxing.PlanarYUVLuminanceSource7+import com.google.zxing.aztec.AztecReader8+import com.google.zxing.common.GlobalHistogramBinarizer9+import com.google.zxing.common.HybridBinarizer10+11+/**12+ * Live-camera Aztec decode for the Codex restore camera path (D10).13+ *14+ * Distinct from [CodexAztec.decode], which decodes a tightly-cropped render of a15+ * single PDF cell. A camera frame is a full scene that may contain one Aztec among16+ * the printed 6×6 grid, so we use the scene detector (no PURE_BARCODE) and read the17+ * Y plane directly — converting the YUV_420_888 frame to an ARGB bitmap every frame18+ * would be wasteful at preview frame rates.19+ */20+object CodexAztecFrame {21+22+ /**23+ * Decode the first readable Aztec code from a CameraX [ImageProxy]24+ * (YUV_420_888). Returns the raw text, or null if no code reads. Does NOT25+ * close the proxy — the caller owns its lifecycle.26+ */27+ fun decode(image: ImageProxy): String? {28+ val plane = image.planes.getOrNull(0) ?: return null29+ val buffer = plane.buffer30+ val data = ByteArray(buffer.remaining())31+ buffer.get(data)32+33+ val width = image.width34+ val height = image.height35+ val rowStride = plane.rowStride36+37+ // PlanarYUVLuminanceSource expects a tightly-packed Y plane; when the38+ // camera reports row padding (rowStride > width) we repack row by row.39+ val luma: ByteArray = if (rowStride == width) {40+ data41+ } else {42+ val packed = ByteArray(width * height)43+ for (row in 0 until height) {44+ System.arraycopy(data, row * rowStride, packed, row * width, width)45+ }46+ packed47+ }48+49+ val source = PlanarYUVLuminanceSource(50+ luma, width, height, 0, 0, width, height, false,51+ )52+ val hints = mapOf(DecodeHintType.TRY_HARDER to true)53+ // Cross both binarizers: Hybrid adapts to uneven lighting, Global handles54+ // flat well-lit prints. Rotating the source covers codes shot sideways.55+ val attempts = listOf(56+ BinaryBitmap(HybridBinarizer(source)),57+ BinaryBitmap(GlobalHistogramBinarizer(source)),58+ BinaryBitmap(HybridBinarizer(source.rotateCounterClockwise())),59+ )60+ for (binary in attempts) {61+ try {62+ return AztecReader().decode(binary, hints).text63+ } catch (_: Exception) {64+ // try next strategy65+ }66+ }67+ return null68+ }69+}app/src/main/java/com/peachpasswords/ui/codex/CodexRestoreChooseAndCamera.kt+367 −0
@@ -0,0 +1,367 @@1+// D10 — Codex restore "choose" surface + camera scan path.2+//3+// Drop-in composables for ui/codex/CodexRestoreScreen.kt. Self-contained: depends4+// only on what already exists in the module plus the camera additions drafted in5+// CodexViewModel.camera.kt (CameraScanState, chooseRestore/startCameraScan/6+// cameraTimedOut/onCameraFrame on CodexViewModel) and CodexAztecFrame (decode).7+//8+// Package is the real screen's package so these merge in with no import churn.9+// Required NEW imports for CodexRestoreScreen.kt are listed in INTEGRATION.md.10+//11+// CameraX deps must be added to app/build.gradle (see INTEGRATION.md). Until then12+// this file will not compile in isolation — that is expected; the orchestrator13+// adds the deps and the camera VM members in the same pass.14+15+package com.peachpasswords.ui.codex16+17+import android.Manifest18+import android.content.Intent19+import android.content.pm.PackageManager20+import android.net.Uri21+import android.provider.Settings22+import androidx.activity.compose.rememberLauncherForActivityResult23+import androidx.activity.result.contract.ActivityResultContracts24+import androidx.camera.core.CameraSelector25+import androidx.camera.core.ImageAnalysis26+import androidx.camera.core.Preview27+import androidx.camera.lifecycle.ProcessCameraProvider28+import androidx.camera.view.PreviewView29+import androidx.compose.foundation.BorderStroke30+import androidx.compose.foundation.background31+import androidx.compose.foundation.border32+import androidx.compose.foundation.clickable33+import androidx.compose.foundation.layout.Arrangement34+import androidx.compose.foundation.layout.Box35+import androidx.compose.foundation.layout.Column36+import androidx.compose.foundation.layout.Row37+import androidx.compose.foundation.layout.Spacer38+import androidx.compose.foundation.layout.aspectRatio39+import androidx.compose.foundation.layout.fillMaxSize40+import androidx.compose.foundation.layout.fillMaxWidth41+import androidx.compose.foundation.layout.height42+import androidx.compose.foundation.layout.padding43+import androidx.compose.foundation.shape.RoundedCornerShape44+import androidx.compose.material.icons.Icons45+import androidx.compose.material.icons.outlined.Description46+import androidx.compose.material.icons.outlined.NoPhotography47+import androidx.compose.material.icons.outlined.PhotoCamera48+import androidx.compose.material3.Icon49+import androidx.compose.material3.Text50+import androidx.compose.runtime.Composable51+import androidx.compose.runtime.DisposableEffect52+import androidx.compose.runtime.LaunchedEffect53+import androidx.compose.runtime.getValue54+import androidx.compose.runtime.mutableStateOf55+import androidx.compose.runtime.remember56+import androidx.compose.runtime.setValue57+import androidx.compose.ui.Alignment58+import androidx.compose.ui.Modifier59+import androidx.compose.ui.draw.clip60+import androidx.compose.ui.draw.drawBehind61+import androidx.compose.ui.geometry.Offset62+import androidx.compose.ui.graphics.Color63+import androidx.compose.ui.graphics.StrokeCap64+import androidx.compose.ui.platform.LocalContext65+import androidx.compose.ui.text.font.FontStyle66+import androidx.compose.ui.unit.dp67+import androidx.compose.ui.unit.sp68+import androidx.compose.ui.viewinterop.AndroidView69+import androidx.core.content.ContextCompat70+import androidx.lifecycle.compose.LocalLifecycleOwner71+import com.peachpasswords.ui.theme.PeachColors72+import com.peachpasswords.ui.theme.PeachType73+import java.util.concurrent.Executors74+75+/**76+ * The two-card "choose" surface shown before any restore work begins. Replaces77+ * the old straight-to-PDF-picker behaviour: the user explicitly picks scanning78+ * with the camera or importing the previously-saved PDF.79+ *80+ * Glass-panel cards mirror the OnboardingScreen / SurfaceElevated style.81+ */82+@Composable83+internal fun CodexRestoreChoose(84+ accent: Color,85+ onScanCamera: () -> Unit,86+ onImportPdf: () -> Unit,87+) {88+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {89+ ChooseCard(90+ icon = Icons.Outlined.PhotoCamera,91+ iconTint = accent,92+ title = "Scan with camera",93+ body = "Point your camera at the printed Aztec grid",94+ accent = accent,95+ onClick = onScanCamera,96+ )97+ ChooseCard(98+ icon = Icons.Outlined.Description,99+ iconTint = PeachColors.T2,100+ title = "Import PDF",101+ body = "Import the PDF you saved when generating your Codex",102+ accent = accent,103+ onClick = onImportPdf,104+ )105+ }106+}107+108+@Composable109+private fun ChooseCard(110+ icon: androidx.compose.ui.graphics.vector.ImageVector,111+ iconTint: Color,112+ title: String,113+ body: String,114+ accent: Color,115+ onClick: () -> Unit,116+) {117+ Row(118+ Modifier119+ .fillMaxWidth()120+ .clip(RoundedCornerShape(18.dp))121+ .background(PeachColors.SurfaceElevated)122+ .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))123+ .clickable(onClick = onClick)124+ .padding(horizontal = 18.dp, vertical = 18.dp),125+ verticalAlignment = Alignment.CenterVertically,126+ horizontalArrangement = Arrangement.spacedBy(16.dp),127+ ) {128+ Icon(icon, contentDescription = null, tint = iconTint, modifier = Modifier.height(24.dp))129+ Column(Modifier.fillMaxWidth()) {130+ Text(131+ title,132+ color = PeachColors.T0,133+ fontFamily = PeachType.Display,134+ fontStyle = FontStyle.Italic,135+ fontSize = 19.sp,136+ )137+ Spacer(Modifier.height(4.dp))138+ Text(body, color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp)139+ }140+ }141+}142+143+/**144+ * Camera capture surface. Requests CAMERA at first composition; on denial shows a145+ * settings-deep-link error card. On grant, binds a CameraX preview + an146+ * ImageAnalysis analyzer that hands each frame to [onFrame] (the VM decodes one147+ * Aztec, accumulates it, and reports back whether a full payload reconstructed).148+ *149+ * A 10s no-detection timer flips to a retry overlay; [onTimeout] lets the VM150+ * record the timeout, and [onRetry] restarts scanning (resets the timer).151+ *152+ * @param onFrame analyze one frame; returns true once decoding is complete so the153+ * analyzer stops. The implementation MUST close the ImageProxy.154+ */155+@Composable156+internal fun CodexCameraScan(157+ accent: Color,158+ timedOut: Boolean,159+ codesFound: Int,160+ onFrame: (androidx.camera.core.ImageProxy) -> Boolean,161+ onTimeout: () -> Unit,162+ onRetry: () -> Unit,163+) {164+ val context = LocalContext.current165+ var granted by remember {166+ mutableStateOf(167+ ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==168+ PackageManager.PERMISSION_GRANTED,169+ )170+ }171+ val permLauncher = rememberLauncherForActivityResult(172+ ActivityResultContracts.RequestPermission(),173+ ) { granted = it }174+175+ LaunchedEffect(Unit) {176+ if (!granted) permLauncher.launch(Manifest.permission.CAMERA)177+ }178+179+ if (!granted) {180+ CameraDeniedCard(accent)181+ return182+ }183+184+ Column(Modifier.fillMaxWidth()) {185+ Box(186+ Modifier187+ .fillMaxWidth()188+ .aspectRatio(4f / 3f)189+ .clip(RoundedCornerShape(8.dp)),190+ ) {191+ CameraPreview(onFrame = onFrame)192+ CornerGuides(accent)193+ Text(194+ if (codesFound == 0) "scanning…" else "$codesFound code${if (codesFound == 1) "" else "s"} read",195+ color = accent,196+ fontFamily = PeachType.Mono,197+ fontSize = 10.sp,198+ modifier = Modifier199+ .align(Alignment.BottomCenter)200+ .padding(bottom = 10.dp),201+ )202+ if (timedOut) NoDetectionOverlay(accent, onRetry)203+ }204+ }205+206+ // Single 10s window per scan attempt; retry re-keys this effect via codesFound207+ // reset + the parent re-entering the Scanning state. Cancel if a code arrives.208+ LaunchedEffect(timedOut) {209+ if (!timedOut) {210+ kotlinx.coroutines.delay(10_000)211+ onTimeout()212+ }213+ }214+}215+216+@Composable217+private fun CameraPreview(onFrame: (androidx.camera.core.ImageProxy) -> Boolean) {218+ val context = LocalContext.current219+ val lifecycleOwner = LocalLifecycleOwner.current220+ val analysisExecutor = remember { Executors.newSingleThreadExecutor() }221+222+ DisposableEffect(Unit) {223+ onDispose { analysisExecutor.shutdown() }224+ }225+226+ AndroidView(227+ modifier = Modifier.fillMaxSize(),228+ factory = { ctx ->229+ val previewView = PreviewView(ctx).apply {230+ scaleType = PreviewView.ScaleType.FILL_CENTER231+ }232+ val providerFuture = ProcessCameraProvider.getInstance(ctx)233+ providerFuture.addListener({234+ val provider = providerFuture.get()235+ val preview = Preview.Builder().build().also {236+ it.setSurfaceProvider(previewView.surfaceProvider)237+ }238+ val analysis = ImageAnalysis.Builder()239+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)240+ .build()241+ analysis.setAnalyzer(analysisExecutor) { proxy ->242+ try {243+ onFrame(proxy)244+ } finally {245+ proxy.close()246+ }247+ }248+ try {249+ provider.unbindAll()250+ provider.bindToLifecycle(251+ lifecycleOwner,252+ CameraSelector.DEFAULT_BACK_CAMERA,253+ preview,254+ analysis,255+ )256+ } catch (_: Exception) {257+ // bind can fail if the lifecycle is already stopped; the258+ // preview simply stays blank — the timeout overlay covers it.259+ }260+ }, ContextCompat.getMainExecutor(ctx))261+ previewView262+ },263+ )264+}265+266+/** Accent corner guides: 20dp arms, 2dp stroke, at each corner of the frame. */267+@Composable268+private fun CornerGuides(accent: Color) {269+ Box(270+ Modifier271+ .fillMaxSize()272+ .padding(10.dp)273+ .drawBehind {274+ val arm = 20.dp.toPx()275+ val w = 2.dp.toPx()276+ fun corner(ox: Float, oy: Float, dx: Float, dy: Float) {277+ drawLine(accent, Offset(ox, oy), Offset(ox + dx * arm, oy), w, StrokeCap.Round)278+ drawLine(accent, Offset(ox, oy), Offset(ox, oy + dy * arm), w, StrokeCap.Round)279+ }280+ corner(0f, 0f, 1f, 1f)281+ corner(size.width, 0f, -1f, 1f)282+ corner(0f, size.height, 1f, -1f)283+ corner(size.width, size.height, -1f, -1f)284+ },285+ )286+}287+288+@Composable289+private fun NoDetectionOverlay(accent: Color, onRetry: () -> Unit) {290+ Column(291+ Modifier292+ .fillMaxSize()293+ .background(Color(0xCC0A0703))294+ .padding(24.dp),295+ verticalArrangement = Arrangement.Center,296+ horizontalAlignment = Alignment.CenterHorizontally,297+ ) {298+ Text(299+ "No Aztec codes detected — try better lighting",300+ color = PeachColors.T1,301+ fontFamily = PeachType.Mono,302+ fontSize = 11.sp,303+ )304+ Spacer(Modifier.height(16.dp))305+ Box(306+ Modifier307+ .clip(RoundedCornerShape(8.dp))308+ .border(BorderStroke(1.dp, accent), RoundedCornerShape(8.dp))309+ .clickable(onClick = onRetry)310+ .padding(horizontal = 18.dp, vertical = 10.dp),311+ ) {312+ Text("Try again", color = accent, fontFamily = PeachType.Mono, fontSize = 11.sp)313+ }314+ }315+}316+317+@Composable318+private fun CameraDeniedCard(accent: Color) {319+ val context = LocalContext.current320+ Column(321+ Modifier322+ .fillMaxWidth()323+ .clip(RoundedCornerShape(18.dp))324+ .background(PeachColors.SurfaceElevated)325+ .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))326+ .padding(20.dp),327+ horizontalAlignment = Alignment.CenterHorizontally,328+ ) {329+ Icon(330+ Icons.Outlined.NoPhotography,331+ contentDescription = null,332+ tint = PeachColors.T2,333+ modifier = Modifier.height(24.dp),334+ )335+ Spacer(Modifier.height(12.dp))336+ Text(337+ "Camera access needed",338+ color = PeachColors.T0,339+ fontFamily = PeachType.Display,340+ fontStyle = FontStyle.Italic,341+ fontSize = 19.sp,342+ )343+ Spacer(Modifier.height(6.dp))344+ Text(345+ "Grant camera permission in Settings to scan your Codex",346+ color = PeachColors.T2,347+ fontFamily = PeachType.Mono,348+ fontSize = 10.sp,349+ )350+ Spacer(Modifier.height(18.dp))351+ Box(352+ Modifier353+ .clip(RoundedCornerShape(8.dp))354+ .border(BorderStroke(1.dp, accent), RoundedCornerShape(8.dp))355+ .clickable {356+ val intent = Intent(357+ Settings.ACTION_APPLICATION_DETAILS_SETTINGS,358+ Uri.fromParts("package", context.packageName, null),359+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)360+ context.startActivity(intent)361+ }362+ .padding(horizontal = 18.dp, vertical = 10.dp),363+ ) {364+ Text("Open Settings", color = accent, fontFamily = PeachType.Mono, fontSize = 11.sp)365+ }366+ }367+}app/src/main/java/com/peachpasswords/ui/codex/CodexRestoreScreen.kt+24 −2
@@ -34,6 +34,7 @@3434 @Composable3535 fun CodexRestoreScreen(onBack: () -> Unit, onRestored: () -> Unit, vm: CodexViewModel = hiltViewModel()) {3636 val state by vm.restore.collectAsStateWithLifecycle()37+ val cameraState by vm.camera.collectAsStateWithLifecycle()3738 val accent = LocalPeachAccent.current3839 val pickLauncher = rememberLauncherForActivityResult(3940 ActivityResultContracts.GetContent(),@@ -50,8 +51,29 @@5051 Spacer(Modifier.height(28.dp))5152 5253 when (val s = state) {53- is RestoreState.Idle ->54- CodexButton("Choose Codex PDF", accent, filled = true) { pickLauncher.launch("application/pdf") }54+ is RestoreState.Idle -> when (val cs = cameraState) {55+ is CameraScanState.Choosing -> CodexRestoreChoose(56+ accent = accent,57+ onScanCamera = { vm.startCameraScan() },58+ onImportPdf = { pickLauncher.launch("application/pdf") },59+ )60+ is CameraScanState.Scanning -> CodexCameraScan(61+ accent = accent,62+ timedOut = false,63+ codesFound = cs.codesFound,64+ onFrame = { vm.onCameraFrame(it) },65+ onTimeout = { vm.cameraTimedOut() },66+ onRetry = { vm.startCameraScan() },67+ )68+ is CameraScanState.Timeout -> CodexCameraScan(69+ accent = accent,70+ timedOut = true,71+ codesFound = cs.codesFound,72+ onFrame = { vm.onCameraFrame(it) },73+ onTimeout = { },74+ onRetry = { vm.startCameraScan() },75+ )76+ }5577 5678 is RestoreState.Scanning -> Text(5779 if (s.pages == 0) "Reading…" else "Reading page ${s.page} of ${s.pages}…",app/src/main/java/com/peachpasswords/ui/codex/CodexViewModel.kt+61 −0
@@ -4,6 +4,9 @@44 import android.net.Uri55 import androidx.lifecycle.ViewModel66 import androidx.lifecycle.viewModelScope7+import androidx.camera.core.ImageProxy8+import com.peachpasswords.codex.ChunkEnvelope9+import com.peachpasswords.codex.CodexAztecFrame710 import com.peachpasswords.codex.CodexException811 import com.peachpasswords.codex.CodexGenerator912 import com.peachpasswords.codex.CodexManifest@@ -38,6 +41,17 @@3841 data class Error(val message: String) : RestoreState3942 }4043 44+/**45+ * D10 camera-scan phase. `Choosing` is the restore landing (two option cards);46+ * `Scanning` runs while the camera analyzes frames; `Timeout` shows the47+ * no-detection overlay after 10s. The decode handoff reuses [RestoreState].48+ */49+sealed interface CameraScanState {50+ data object Choosing : CameraScanState51+ data class Scanning(val codesFound: Int) : CameraScanState52+ data class Timeout(val codesFound: Int) : CameraScanState53+}54+4155 @HiltViewModel4256 class CodexViewModel @Inject constructor(4357 @ApplicationContext private val context: Context,@@ -132,4 +146,51 @@132146 }133147 134148 fun resetRestore() { _restore.value = RestoreState.Idle }149+150+ // ---- D10 camera scan --------------------------------------------------151+ private val _camera = MutableStateFlow<CameraScanState>(CameraScanState.Choosing)152+ val camera: StateFlow<CameraScanState> = _camera.asStateFlow()153+154+ // Envelopes collected this session, deduped by stripe:index (mirrors decodeFromUri).155+ private val cameraEnvelopes = LinkedHashMap<String, ChunkEnvelope>()156+157+ /** Show the two-card choose surface (default restore landing). */158+ fun chooseRestore() {159+ cameraEnvelopes.clear()160+ _camera.value = CameraScanState.Choosing161+ _restore.value = RestoreState.Idle162+ }163+164+ /** Begin (or restart after a timeout) live camera scanning. */165+ fun startCameraScan() {166+ cameraEnvelopes.clear()167+ _camera.value = CameraScanState.Scanning(0)168+ }169+170+ /** UI reports 10s elapsed with no successful reconstruction. */171+ fun cameraTimedOut() {172+ val s = _camera.value173+ if (s is CameraScanState.Scanning) _camera.value = CameraScanState.Timeout(s.codesFound)174+ }175+176+ /**177+ * Analyze one camera frame: decode one Aztec, accumulate, and on a successful178+ * reconstruction transition to [RestoreState.Decoded] — the same entry point179+ * the PDF path uses. Returns true once decoded (caller stops analysis). The180+ * analyzer owns closing the [ImageProxy]; this does not close it.181+ */182+ fun onCameraFrame(image: ImageProxy): Boolean {183+ if (_camera.value !is CameraScanState.Scanning) return _restore.value is RestoreState.Decoded184+ val text = CodexAztecFrame.decode(image) ?: return false185+ val env = CodexRestore.parseEnvelope(text) ?: return false186+ cameraEnvelopes.putIfAbsent("${env.s}:${env.i}", env)187+ _camera.value = CameraScanState.Scanning(cameraEnvelopes.size)188+ return try {189+ val payload = CodexRestore.reconstructPayload(cameraEnvelopes.values.toList())190+ _restore.value = RestoreState.Decoded(payload, cameraEnvelopes.size)191+ true192+ } catch (_: Exception) {193+ false194+ }195+ }135196 }