CodexRestoreChooseAndCamera.kt

13.4 KB · raw

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.1415package com.peachpasswords.ui.codex1617import android.Manifest18import android.content.Intent19import android.content.pm.PackageManager20import android.net.Uri21import android.provider.Settings22import androidx.activity.compose.rememberLauncherForActivityResult23import androidx.activity.result.contract.ActivityResultContracts24import androidx.camera.core.CameraSelector25import androidx.camera.core.ImageAnalysis26import androidx.camera.core.Preview27import androidx.camera.lifecycle.ProcessCameraProvider28import androidx.camera.view.PreviewView29import androidx.compose.foundation.BorderStroke30import androidx.compose.foundation.background31import androidx.compose.foundation.border32import androidx.compose.foundation.clickable33import androidx.compose.foundation.layout.Arrangement34import androidx.compose.foundation.layout.Box35import androidx.compose.foundation.layout.Column36import androidx.compose.foundation.layout.Row37import androidx.compose.foundation.layout.Spacer38import androidx.compose.foundation.layout.aspectRatio39import androidx.compose.foundation.layout.fillMaxSize40import androidx.compose.foundation.layout.fillMaxWidth41import androidx.compose.foundation.layout.height42import androidx.compose.foundation.layout.padding43import androidx.compose.foundation.shape.RoundedCornerShape44import androidx.compose.material.icons.Icons45import androidx.compose.material.icons.outlined.Description46import androidx.compose.material.icons.outlined.NoPhotography47import androidx.compose.material.icons.outlined.PhotoCamera48import androidx.compose.material3.Icon49import androidx.compose.material3.Text50import androidx.compose.runtime.Composable51import androidx.compose.runtime.DisposableEffect52import androidx.compose.runtime.LaunchedEffect53import androidx.compose.runtime.getValue54import androidx.compose.runtime.mutableStateOf55import androidx.compose.runtime.remember56import androidx.compose.runtime.setValue57import androidx.compose.ui.Alignment58import androidx.compose.ui.Modifier59import androidx.compose.ui.draw.clip60import androidx.compose.ui.draw.drawBehind61import androidx.compose.ui.geometry.Offset62import androidx.compose.ui.graphics.Color63import androidx.compose.ui.graphics.StrokeCap64import androidx.compose.ui.platform.LocalContext65import androidx.compose.ui.text.font.FontStyle66import androidx.compose.ui.unit.dp67import androidx.compose.ui.unit.sp68import androidx.compose.ui.viewinterop.AndroidView69import androidx.core.content.ContextCompat70import androidx.lifecycle.compose.LocalLifecycleOwner71import com.peachpasswords.ui.theme.PeachColors72import com.peachpasswords.ui.theme.PeachType73import java.util.concurrent.Executors7475/**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@Composable83internal 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}107108@Composable109private 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}142143/**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@Composable156internal 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 }174175    LaunchedEffect(Unit) {176        if (!granted) permLauncher.launch(Manifest.permission.CAMERA)177    }178179    if (!granted) {180        CameraDeniedCard(accent)181        return182    }183184    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    }205206    // 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}215216@Composable217private fun CameraPreview(onFrame: (androidx.camera.core.ImageProxy) -> Boolean) {218    val context = LocalContext.current219    val lifecycleOwner = LocalLifecycleOwner.current220    val analysisExecutor = remember { Executors.newSingleThreadExecutor() }221222    DisposableEffect(Unit) {223        onDispose { analysisExecutor.shutdown() }224    }225226    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}265266/** Accent corner guides: 20dp arms, 2dp stroke, at each corner of the frame. */267@Composable268private 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}287288@Composable289private 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}316317@Composable318private 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}