various fixes
- Commit
3fe99af847011cd05abf8cf55c38036c368a80e8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-28 18:27 UTC (4 months ago)
- Parents
acd525a
Diff
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 6e41dbd041..f5f6f1091f 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -15,9 +15,11 @@ import android.net.Uri import android.provider.MediaStore import android.util.Patterns import android.widget.Toast+import android.util.Log import android.view.OrientationEventListener import android.view.Surface import androidx.camera.compose.CameraXViewfinder+import androidx.camera.core.CameraInfo import androidx.camera.core.FocusMeteringAction import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis@@ -279,22 +281,41 @@ fun CameraScreen( val highSpeedActive by viewModel.highSpeedActive.collectAsState() val photoSessionActive by viewModel.photoSessionActive.collectAsState() // Whether the CameraX NIGHT extension is available on the current lens (PHOTO only).- // Night extension probe does heavy ProcessCameraProvider work -> offload to IO. var nightExtAvailable by remember { mutableStateOf(false) } LaunchedEffect(lensFacing, cameraMode) {- nightExtAvailable = if (cameraMode == CameraMode.PHOTO) {- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) {- viewModel.isNightExtensionAvailable()- }- } else false+ val startMs = System.currentTimeMillis()+ Log.d("NightPreview", "CameraScreen LaunchedEffect night check START lensFacing=$lensFacing cameraMode=$cameraMode thread=${Thread.currentThread().name}")+ val avail = try {+ if (cameraMode == CameraMode.PHOTO) viewModel.isNightExtensionAvailable() else false+ } catch (e: Exception) {+ Log.e("NightPreview", "CameraScreen nightExtAvailable check threw (was silently hidden before)", e)+ false+ }+ nightExtAvailable = avail+ Log.d("NightPreview", "CameraScreen LaunchedEffect night check END avail=$avail took=${System.currentTimeMillis() - startMs}ms") } // Bind the NIGHT-extension preview when low light is auto-detected in PHOTO mode // and the extension is available; otherwise the normal photo session is used. val useNightPreview = sessionKind == SessionKind.PHOTO && cameraMode == CameraMode.PHOTO && nightModeActive && nightExtAvailable+ LaunchedEffect(useNightPreview) {+ Log.d("NightPreview", "CameraScreen useNightPreview recomputed=$useNightPreview sessionKind=$sessionKind cameraMode=$cameraMode nightModeActive=$nightModeActive nightExtAvailable=$nightExtAvailable lensFacing=$lensFacing")+ } val surfaceRequest by viewModel.surfaceRequest.collectAsState()+ LaunchedEffect(surfaceRequest) {+ Log.d("NightPreview", "CameraScreen surfaceRequest changed res=${surfaceRequest?.resolution} frameType=${surfaceRequest?.javaClass?.simpleName} useNightPreview=$useNightPreview sessionKind=$sessionKind thread=${Thread.currentThread().name} lensFacing=${lensFacing}")+ if (surfaceRequest == null && useNightPreview) {+ Log.w("NightPreview", "CameraScreen WARNING: surfaceRequest is NULL while useNightPreview=true – preview will be black until Provider re-emits. This is the black-frame trap you described: teardown -> delay(250) -> setupNightPreviewSession() tears down standard photo session surface before extension emits!")+ }+ if (surfaceRequest == null && !useNightPreview) {+ Log.w("NightPreview", "CameraScreen tracing maybe delayed rebind? surface null while normal photo – expected during 250ms delay window")+ }+ } val coordinateTransformer = remember { MutableCoordinateTransformer() } val availableZoomLevels by viewModel.availableZoomLevels.collectAsState()+ LaunchedEffect(availableZoomLevels) {+ Log.d("NightPreview", "CameraScreen availableZoomLevels changed=$availableZoomLevels currentZoom=${zoomRatio} useNightPreview=$useNightPreview – vendor NIGHT often reports only [1x], making zoom bar appear to 'disappear' except 1x")+ } val bokehShader = remember { lazy { RuntimeShader(BOKEH_SHADER) } } val panoSweeping by viewModel.panoramaEngine.isSweeping.collectAsState()@@ -341,9 +362,7 @@ fun CameraScreen( val galleryBitmap by viewModel.galleryThumbnail.collectAsState() LaunchedEffect(Unit) {- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {- viewModel.updateLocation()- }+ viewModel.updateLocation() } LaunchedEffect(flashMode) {@@ -456,44 +475,46 @@ fun CameraScreen( // Unified session binding, made lifecycle-aware so the camera is released when the app is // backgrounded and rebound on resume. Without this the ManualLifecycleOwner stays RESUMED, // the OS reclaims the camera while we're away, and the preview comes back frozen.- //- // CRITICAL ANR FIX: ProcessCameraProvider.getInstance()/awaitInstance and- // ExtensionsManager + Recorder capability queries can block 10-20s (MediaCodecList,- // camera service binder). They must never run on the main thread during cold- // start, or InputDispatcher times out waiting for FocusEvent(hasFocus=true).- // We keep teardown on main (lightweight) but move the heavy bind to IO/Default,- // then await cancellation on main again. val lifecycleOwner = LocalLifecycleOwner.current LaunchedEffect(lensFacing, sessionKind, useNightPreview, lifecycleOwner) {+ Log.d("NightPreview", "CameraScreen session LaunchedEffect START keys lensFacing=$lensFacing sessionKind=$sessionKind useNightPreview=$useNightPreview lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}") lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {- // Lightweight teardown can stay on main; add small delay to let surface detach+ Log.d("NightPreview", "CameraScreen repeatOnLifecycle STARTED – calling teardownSession()")+ val teardownStart = System.currentTimeMillis() viewModel.teardownSession()- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {- delay(250)- }- // Heavy camera bind off main thread to avoid 20s FocusEvent stall- val ready = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) {+ Log.d("NightPreview", "CameraScreen teardownSession() returned took=${System.currentTimeMillis() - teardownStart}ms, surface after=${viewModel.surfaceRequest.value?.resolution}")+ Log.d("NightPreview", "CameraScreen delay(250) START to let surface detach (main-thread per a20f656b revert, not IO)")+ delay(250)+ Log.d("NightPreview", "CameraScreen delay(250) END, about to bind sessionKind=$sessionKind useNightPreview=$useNightPreview")+ val bindStart = System.currentTimeMillis()+ val bindSuccess = try { when (sessionKind) { SessionKind.HIGH_SPEED -> viewModel.setupHighSpeedSession() SessionKind.VIDEO -> viewModel.setupVideoSession() SessionKind.PANORAMA -> viewModel.setupPanoramaSession() SessionKind.PORTRAIT -> viewModel.setupPortraitSession() SessionKind.PHOTO ->- if (useNightPreview) viewModel.setupNightPreviewSession()- else viewModel.setupPhotoSession()+ if (useNightPreview) {+ Log.d("NightPreview", "CameraScreen switching to NIGHT extension preview – if this goes black with only 1x zoom, vendor reports min=max=1x and/or surfaceProvider not re-emitted")+ viewModel.setupNightPreviewSession()+ } else viewModel.setupPhotoSession() }+ } catch (e: Exception) {+ Log.e("NightPreview", "CameraScreen session binding THREW (was not logged before) kind=$sessionKind useNightPreview=$useNightPreview nightExtAvailable=$nightExtAvailable", e)+ false }- // Log bind result (optional)- if (!ready) {- android.util.Log.w("CameraScreen", "Camera session bind failed for $sessionKind")+ Log.d("NightPreview", "CameraScreen session bind finished success=$bindSuccess took=${System.currentTimeMillis() - bindStart}ms surface after=${viewModel.surfaceRequest.value?.resolution} zoomLevels=${viewModel.availableZoomLevels.value} zoomRatio=${viewModel.zoomRatio.value}")+ if (!bindSuccess) {+ Log.e("NightPreview", "CameraScreen BIND FAILED – this produces solid black preview and zoom bar showing only 1x (fallback?). Check logcat for NightPreview tag – exception was previously swallowed as warning") } try { awaitCancellation() } finally {- // Ensure teardown runs even if we are on cancellation+ Log.d("NightPreview", "CameraScreen session coroutine cancelled/finished, calling teardownSession()") viewModel.teardownSession() } }+ Log.d("NightPreview", "CameraScreen repeatOnLifecycle block EXIT – lifecycle dropped below STARTED") } @@ -676,15 +697,38 @@ fun CameraScreen( } surfaceRequest?.let { request ->+ LaunchedEffect(request) {+ Log.d("NightPreview", "CameraXViewfinder COMPOSED with request res=${request.resolution} dynamicRange=${request.dynamicRange} useNightPreview=$useNightPreview sessionKind=$sessionKind zoomRatio=${zoomRatio} levels=${availableZoomLevels} thread=${Thread.currentThread().name}")+ }+ DisposableEffect(request) {+ Log.d("NightPreview", "CameraXViewfinder DisposableEffect ATTACH request res=${request.resolution} useNightPreview=$useNightPreview")+ onDispose {+ Log.d("NightPreview", "CameraXViewfinder DisposableEffect DETACH request res=${request.resolution} useNightPreview=$useNightPreview – surface will be invalidated, if next request fails to emit we go black")+ }+ } CameraXViewfinder( surfaceRequest = request,- modifier = previewModifier,+ modifier = previewModifier+ .graphicsLayer {+ // Log when graphicsLayer runs – if RenderEffect crashes it swallows?+ }, implementationMode = ImplementationMode.EMBEDDED, coordinateTransformer = coordinateTransformer, alignment = Alignment.Center, contentScale = if (isSloMo) ContentScale.Crop else ContentScale.Fit ) }+ if (surfaceRequest == null) {+ LaunchedEffect(useNightPreview, sessionKind) {+ Log.w("NightPreview", "CameraScreen rendering NO preview because surfaceRequest==null useNightPreview=$useNightPreview sessionKind=$sessionKind lowLight=$lowLightDetected nightActive=$nightModeActive nightExtAvailable=$nightExtAvailable – solid black!")+ }+ Box(+ modifier = previewModifier.background(Color.Black),+ contentAlignment = Alignment.Center+ ) {+ Text("NO SURFACE: useNightPreview=$useNightPreview session=$sessionKind", color = Color.White, fontSize = 12.sp)+ }+ } if (gridEnabled) { GridOverlay(
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex 5962f084ef..3e9648f8b1 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -112,6 +112,14 @@ fun buildColorAdjustmentMatrix(warmth: Float, shadows: Float): ColorMatrix = Col class CameraViewModel(private val app: Application) : AndroidViewModel(app) { companion object { + // Master switch for the CameraX vendor NIGHT extension (real-time night preview + vendor+ // multi-frame capture). Disabled because it fails to configure on the camera-pipe backend+ // on Pixel (ERROR_GRAPH_CONFIG "Framework size list map not supported in pixel path"),+ // giving a black preview and failed captures. With it off, night mode runs the app's own+ // burst + Rust-merge path over the normal photo session. Flip back to true once CameraX+ // ships a pipe-extensions fix. See isNightExtensionAvailable().+ private const val ENABLE_NIGHT_EXTENSION = false+ // Night-mode auto-detection tuning. Engage once average Y stays below ENGAGE for a few // frames; disengage once it climbs above DISENGAGE for a few frames. The gap between the // two thresholds is the hysteresis band that stops the moon button from flickering.@@ -211,10 +219,13 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { private val _aspectRatio = MutableStateFlow(AspectRatioOption.RATIO_4_3) val aspectRatio = _aspectRatio.asStateFlow() - // Default to AVC on main-thread init; the best available codec (AV1/HEVC) is- // determined off the main thread in loadSettings() to avoid MediaCodecList- // blocking startup (MediaCodecList can take 10-20s on some devices).- private val _videoCodec = MutableStateFlow(VideoCodec.AVC)+ private val _videoCodec = MutableStateFlow(+ when {+ CodecSupport.isHardwareAv1EncoderAvailable -> VideoCodec.AV1+ CodecSupport.isHevcEncoderAvailable -> VideoCodec.HEVC+ else -> VideoCodec.AVC+ }+ ) val videoCodec = _videoCodec.asStateFlow() private val _isRecording = MutableStateFlow(false)@@ -460,24 +471,40 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { } init {+ loadSettings() panoramaEngine.onSweepComplete = { finishPanoramaSweep() }-- // Settings include disk read + MediaCodecList which is known to block 10-20s- // on some devices. Must never run on main thread during cold start or the- // window can't handle FocusEvent -> ANR.- viewModelScope.launch(Dispatchers.IO) {- CodecSupport.prewarm() // MediaCodecList off main, cached- loadSettings()- }- viewModelScope.launch(Dispatchers.IO) {+ viewModelScope.launch { _lastCaptureUri.collect { uri -> _galleryThumbnail.value = loadThumbnail(uri) } } // Probe Slo-Mo capability once (back camera only). UI hides Slo-Mo if unsupported.- // Must run off main thread: ProcessCameraProvider.awaitInstance + high-speed caps- // queries are heavy.- viewModelScope.launch(Dispatchers.Default) {+ viewModelScope.launch { _sloMoSupported.value = probeSloMoSupport() }+ // DEBUG: Night mode resolution question – extension uses default resolution vs max-res, may be lower so can't take full quality?+ viewModelScope.launch {+ var last: List<Pair<String, Float>> = emptyList()+ availableZoomLevels.collect { levels ->+ if (levels != last) {+ Log.d("NightPreview", "CameraViewModel availableZoomLevels FLOW emitted=$levels previous=$last nightPreviewActive=${_nightPreviewActive.value} photoActive=${_photoSessionActive.value} zoomRatio=${_zoomRatio.value} – if only [1x], zoom bar appears disappeared")+ last = levels+ }+ }+ }+ viewModelScope.launch {+ var lastRes: android.util.Size? = null+ surfaceRequest.collect { req ->+ val res = req?.resolution+ if (res != lastRes) {+ Log.d("NightPreview", "CameraViewModel surfaceRequest FLOW emitted res=$res previous=$lastRes nightPreviewActive=${_nightPreviewActive.value} photoActive=${_photoSessionActive.value} – null->val during extension bind, black if stuck null")+ lastRes = res+ }+ }+ }+ viewModelScope.launch {+ nightModeActive.collect { active ->+ Log.d("NightPreview", "CameraViewModel nightModeActive FLOW=$active lowLight=${_lowLightDetected.value} overriddenOff=${_nightModeOverriddenOff.value} – button toggle drives this, triggers session rebind via useNightPreview in UI")+ }+ } } /**@@ -516,64 +543,36 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { } } - private suspend fun loadThumbnail(uri: Uri?): Bitmap? {- if (uri == null) return null- return withContext(Dispatchers.IO) {+ private suspend fun loadThumbnail(uri: Uri?): Bitmap? = uri?.let {+ withContext(Dispatchers.IO) { try {- // Safeguard: loadThumbnail can throw SecurityException / FileNotFound if- // MediaStore row gone. Also IO heavy – always on IO dispatcher.- app.contentResolver.loadThumbnail(uri, Size(96, 96), null)+ app.contentResolver.loadThumbnail(it, Size(96, 96), null) } catch (e: Exception) {- // Only log at debug level – expected after deletion / first launch- Log.d("CameraViewModel", "Failed to load gallery thumbnail: $uri", e)+ Log.w("CameraViewModel", "Failed to load gallery thumbnail", e) null } } } private fun loadSettings() {- // DataStore state is in-memory, but this whole method now runs on IO dispatcher- // to avoid MediaCodecList (CodecSupport) stalling main thread -> FocusEvent ANR.- try { _flashMode.value = ds.getString("camera_flash")?.let { FlashMode.valueOf(it) } ?: FlashMode.OFF } catch (_: Exception) {}- try { _timerDuration.value = ds.getString("camera_timer")?.let { TimerDuration.valueOf(it) } ?: TimerDuration.NONE } catch (_: Exception) {}- try { _aspectRatio.value = ds.getString("camera_aspect_ratio")?.let { AspectRatioOption.valueOf(it) } ?: AspectRatioOption.RATIO_4_3 } catch (_: Exception) {}-- // Codec: if user has explicit preference, use it; otherwise probe best available- // codec OFF main thread (MediaCodecList can take 10-20s).- val savedCodec = ds.getString("camera_video_codec")- _videoCodec.value = if (savedCodec != null) {- try { VideoCodec.valueOf(savedCodec) } catch (_: Exception) {- // Fall back to best available (IO thread safe now)+ ds.getString("camera_flash")?.let { _flashMode.value = FlashMode.valueOf(it) }+ ds.getString("camera_timer")?.let { _timerDuration.value = TimerDuration.valueOf(it) }+ ds.getString("camera_aspect_ratio")?.let { _aspectRatio.value = AspectRatioOption.valueOf(it) }+ ds.getString("camera_video_codec")?.let {+ _videoCodec.value = try { VideoCodec.valueOf(it) } catch (_: Exception) { when { CodecSupport.isHardwareAv1EncoderAvailable -> VideoCodec.AV1 CodecSupport.isHevcEncoderAvailable -> VideoCodec.HEVC else -> VideoCodec.AVC } }- } else {- when {- CodecSupport.isHardwareAv1EncoderAvailable -> VideoCodec.AV1- CodecSupport.isHevcEncoderAvailable -> VideoCodec.HEVC- else -> VideoCodec.AVC- }- }-- try { _locationEnabled.value = ds.getString("camera_location")?.toBoolean() ?: false } catch (_: Exception) {}- try { ds.getString("camera_last_capture")?.let { if (it.isNotEmpty()) _lastCaptureUri.value = Uri.parse(it) } } catch (_: Exception) {}- try { _gridEnabled.value = ds.getString("camera_grid")?.toBoolean() ?: false } catch (_: Exception) {}- try { _levelEnabled.value = ds.getString("camera_level")?.toBoolean() ?: false } catch (_: Exception) {}- try { _micMuted.value = ds.getString("camera_mic_muted")?.toBoolean() ?: false } catch (_: Exception) {}-- // Sensor registration must happen on main thread; post if we're on IO.- if (_levelEnabled.value) {- try {- if (android.os.Looper.myLooper() == android.os.Looper.getMainLooper()) {- registerLevelSensor()- } else {- android.os.Handler(android.os.Looper.getMainLooper()).post { registerLevelSensor() }- }- } catch (_: Exception) {} }+ ds.getString("camera_location")?.let { _locationEnabled.value = it.toBoolean() }+ ds.getString("camera_last_capture")?.let { _lastCaptureUri.value = Uri.parse(it) }+ ds.getString("camera_grid")?.let { _gridEnabled.value = it.toBoolean() }+ ds.getString("camera_level")?.let { _levelEnabled.value = it.toBoolean() }+ ds.getString("camera_mic_muted")?.let { _micMuted.value = it.toBoolean() }+ if (_levelEnabled.value) registerLevelSensor() } fun setFlashMode(mode: FlashMode) {@@ -734,35 +733,52 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { * user's per-scene override is reset so the next dark scene re-engages cleanly. */ fun onLuminance(avg: Float) {+ // LOTS of logging to figure out what the real problem is (per user request)+ val beforeLow = _lowLightDetected.value+ val beforeOff = _nightModeOverriddenOff.value+ Log.d("NightPreview", "onLuminance() avg=$avg lowLightBefore=$beforeLow overriddenOff=$beforeOff lowFrames=$lowLumaFrames highFrames=$highLumaFrames nightActive=${nightModeActive.value} photoActive=${_photoSessionActive.value} nightPreviewActive=${_nightPreviewActive.value} thread=${Thread.currentThread().name}") if (_lowLightDetected.value) { if (avg > NIGHT_DISENGAGE_LUMA) { highLumaFrames++ lowLumaFrames = 0+ Log.d("NightPreview", "onLuminance() currently in low-light, avg $avg > disengage ${NIGHT_DISENGAGE_LUMA}, highFrames=$highLumaFrames/${NIGHT_DEBOUNCE_FRAMES}") if (highLumaFrames >= NIGHT_DEBOUNCE_FRAMES) {+ Log.d("NightPreview", "onLuminance() DISENGAGING night – high luma for $NIGHT_DEBOUNCE_FRAMES frames, lowLight=true->false") _lowLightDetected.value = false _nightModeOverriddenOff.value = false highLumaFrames = 0+ Log.d("NightPreview", "onLuminance() after DISENGAGE lowLight=${_lowLightDetected.value} nightActive=${nightModeActive.value} – triggers teardown->setupPhotoSession() rebind") } } else {+ if (highLumaFrames != 0) Log.d("NightPreview", "onLuminance() resetting highFrames 0 (avg=$avg still below disengage)") highLumaFrames = 0 } } else { if (avg < NIGHT_ENGAGE_LUMA) { lowLumaFrames++ highLumaFrames = 0+ Log.d("NightPreview", "onLuminance() avg $avg < engage ${NIGHT_ENGAGE_LUMA}, lowFrames=$lowLumaFrames/${NIGHT_DEBOUNCE_FRAMES}") if (lowLumaFrames >= NIGHT_DEBOUNCE_FRAMES) {+ Log.d("NightPreview", "onLuminance() ENGAGING night – low luma for $NIGHT_DEBOUNCE_FRAMES frames, lowLight=false->true") _lowLightDetected.value = true lowLumaFrames = 0+ Log.d("NightPreview", "onLuminance() after ENGAGE lowLight=${_lowLightDetected.value} nightActive=${nightModeActive.value} overriddenOff=${_nightModeOverriddenOff.value} – if extension available, useNightPreview should become true and rebind to setupNightPreviewSession()") } } else {+ if (lowLumaFrames != 0) Log.d("NightPreview", "onLuminance() resetting lowFrames 0 (avg=$avg above engage)") lowLumaFrames = 0 } }+ if (beforeLow != _lowLightDetected.value || beforeOff != _nightModeOverriddenOff.value) {+ Log.d("NightPreview", "onLuminance() STATE CHANGE low $beforeLow -> ${_lowLightDetected.value} off $beforeOff -> ${_nightModeOverriddenOff.value} nightActive ${nightModeActive.value}")+ } } /** Toggles the user's override for the current dark scene (moon button handler). */ fun toggleNightModeOverride() {+ val before = _nightModeOverriddenOff.value _nightModeOverriddenOff.value = !_nightModeOverriddenOff.value+ Log.d("NightPreview", "toggleNightModeOverride() CLICK moon button beforeOff=$before afterOff=${_nightModeOverriddenOff.value} lowLight=${_lowLightDetected.value} nightActiveBefore=${!before && _lowLightDetected.value} nightActiveAfter=${nightModeActive.value} thread=${Thread.currentThread().name} – screen should transition? if extension binds, preview resolution changes and zoom bar may collapse to 1x") } private fun setLastCaptureUri(uri: Uri?) {@@ -812,14 +828,22 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { fun setZoomRatio(ratio: Float) { val cam = boundCamera- val clamped = cam?.cameraInfo?.zoomState?.value?.let {+ val zs = cam?.cameraInfo?.zoomState?.value+ Log.d("NightPreview", "setZoomRatio() requested=$ratio clamped? min=${zs?.minZoomRatio} max=${zs?.maxZoomRatio} current=${zs?.zoomRatio} nightPreviewActive=${_nightPreviewActive.value} photoActive=${_photoSessionActive.value} boundCamera=${cam != null}")+ val clamped = zs?.let { ratio.coerceIn(it.minZoomRatio, it.maxZoomRatio) } ?: ratio+ if (clamped != ratio) Log.w("NightPreview", "setZoomRatio() CLAMPED $ratio -> $clamped due to zoomState min/max – vendor NIGHT often reports max=1x, causing bar to show only 1x") _zoomRatio.value = clamped- cam?.cameraControl?.setZoomRatio(clamped)+ try {+ cam?.cameraControl?.setZoomRatio(clamped)+ } catch (e: Exception) {+ Log.e("NightPreview", "setZoomRatio() setZoomRatio() threw (was hidden before)", e)+ } } fun updateZoomLevels(minZoom: Float, maxZoom: Float) {+ Log.d("NightPreview", "updateZoomLevels() min=$minZoom max=$maxZoom nightPreviewActive=${_nightPreviewActive.value} photoActive=${_photoSessionActive.value} currentRatio=${_zoomRatio.value} thread=${Thread.currentThread().name}") val levels = mutableListOf<Pair<String, Float>>() // Wide-angle entry only when the lens can actually zoom out past 1x. if (minZoom < 0.95f) {@@ -829,21 +853,19 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { for (tele in listOf(2f, 5f)) { if (tele <= maxZoom + 0.05f) levels.add(formatZoomLabel(tele) to tele) }+ Log.d("NightPreview", "updateZoomLevels() emitting levels=$levels – if min=1f max=1f, only [1x] will show, explaining 'all zoom levels also disappear'") _availableZoomLevels.value = levels } @android.annotation.SuppressLint("MissingPermission") fun updateLocation() { if (!_locationEnabled.value) return- // LocationManager binder call should not run on main during cold start.- viewModelScope.launch(Dispatchers.IO) {- try {- val lm = app.getSystemService(Context.LOCATION_SERVICE) as LocationManager- lastLocation = lm.getLastKnownLocation(LocationManager.FUSED_PROVIDER)- ?: lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)- } catch (e: Exception) {- Log.w("CameraViewModel", "Failed to read last known location", e)- }+ try {+ val lm = app.getSystemService(Context.LOCATION_SERVICE) as LocationManager+ lastLocation = lm.getLastKnownLocation(LocationManager.FUSED_PROVIDER)+ ?: lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)+ } catch (e: Exception) {+ Log.w("CameraViewModel", "Failed to read last known location", e) } } @@ -1019,9 +1041,11 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { * limits, it falls back to a default ImageCapture resolution. */ suspend fun setupPhotoSession(): Boolean {+ Log.d("NightPreview", "setupPhotoSession() ENTRY thread=${Thread.currentThread().name} lens=${_lensFacing.value} surfaceBefore=${_surfaceRequest.value?.resolution}") return try { val provider = ProcessCameraProvider.awaitInstance(app) cameraProvider = provider+ Log.d("NightPreview", "setupPhotoSession() got providerHash=${provider.hashCode()}") provider.unbindAll() val selector = CameraSelector.Builder()@@ -1034,11 +1058,16 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { try { androidx.camera.camera2.interop.Camera2Interop.Extender(previewBuilder) .setSessionCaptureCallback(aeSnapshotCallback)+ Log.d("NightPreview", "setupPhotoSession() attached AE snapshot callback") } catch (e: Exception) {- Log.w("PhotoSession", "Could not attach AE snapshot callback", e)+ Log.e("NightPreview", "setupPhotoSession() Could not attach AE snapshot callback (was hidden as Warn)", e) } val preview = previewBuilder.build()- preview.setSurfaceProvider { request -> _surfaceRequest.value = request }+ preview.setSurfaceProvider { request ->+ Log.d("NightPreview", "setupPhotoSession() surfaceRequest emitted res=${request.resolution} format=${request.javaClass.simpleName} thread=${Thread.currentThread().name} nightActive=${nightModeActive.value}")+ _surfaceRequest.value = request+ }+ Log.d("NightPreview", "setupPhotoSession() preview surfaceProvider attached") val owner = ManualLifecycleOwner() owner.start()@@ -1048,77 +1077,89 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { // here; the bind ladder falls back to plain JPEG if the Ultra HDR combo can't bind. val ultraHdrSupported = try { val cameraInfo = provider.getCameraInfo(selector)- ImageCapture.getImageCaptureCapabilities(cameraInfo)- .supportedOutputFormats- .contains(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)+ val caps = ImageCapture.getImageCaptureCapabilities(cameraInfo).supportedOutputFormats.contains(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)+ Log.d("NightPreview", "setupPhotoSession() ultraHdrSupported=$caps selector=$selector")+ caps } catch (e: Exception) {- Log.w("PhotoSession", "Could not query Ultra HDR support", e)+ Log.e("NightPreview", "setupPhotoSession() Could not query Ultra HDR support (was hidden as Warn)", e) false } fun bind(maxRes: Boolean, ultraHdr: Boolean): Camera {- val selectorBuilder = ResolutionSelector.Builder()- .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)- if (maxRes) {- // HIGHEST_AVAILABLE + PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE unlocks the- // full-res (maximum-resolution) sensor sizes, re-resolved per bound camera.- selectorBuilder.setAllowedResolutionMode(- ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE- )- }- val captureBuilder = ImageCapture.Builder()- .setResolutionSelector(selectorBuilder.build())- .setFlashMode(getImageCaptureFlashMode())- .setTargetRotation(targetRotation)- if (ultraHdr) {- captureBuilder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)- }- val capture = captureBuilder.build()- imageCapture = capture- val analysisBuilder = ImageAnalysis.Builder()- .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)- if (maxRes) {- // Raise the analysis stream too so the night-mode burst (collected off this- // stream) is as high-res as the device's 3-stream combo allows. Tied to maxRes- // so the default-resolution fallback keeps the analysis stream conservative if- // the high-res 3-stream bind is rejected.- analysisBuilder.setResolutionSelector(- ResolutionSelector.Builder()- .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)- .build()- )+ Log.d("NightPreview", "setupPhotoSession() bind(maxRes=$maxRes ultraHdr=$ultraHdr) START thread=${Thread.currentThread().name}")+ return try {+ val selectorBuilder = ResolutionSelector.Builder()+ .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)+ if (maxRes) {+ selectorBuilder.setAllowedResolutionMode(ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE)+ }+ val captureBuilder = ImageCapture.Builder()+ .setResolutionSelector(selectorBuilder.build())+ .setFlashMode(getImageCaptureFlashMode())+ .setTargetRotation(targetRotation)+ if (ultraHdr) {+ captureBuilder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)+ }+ val capture = captureBuilder.build()+ imageCapture = capture+ val analysisBuilder = ImageAnalysis.Builder()+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+ if (maxRes) {+ analysisBuilder.setResolutionSelector(+ ResolutionSelector.Builder().setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY).build()+ )+ }+ val analysis = analysisBuilder.build()+ imageAnalysis = analysis+ provider.bindToLifecycle(owner, selector, preview, capture, analysis).also {+ Log.d("NightPreview", "setupPhotoSession() bind SUCCESS res=${it.cameraInfo} zoom min=${it.cameraInfo.zoomState.value?.minZoomRatio} max=${it.cameraInfo.zoomState.value?.maxZoomRatio}")+ }+ } catch (e: Exception) {+ Log.e("NightPreview", "setupPhotoSession() bind(maxRes=$maxRes ultra=$ultraHdr) EXCEPTION – root cause of black preview when fallback also fails", e)+ throw e }- val analysis = analysisBuilder.build()- imageAnalysis = analysis- return provider.bindToLifecycle(owner, selector, preview, capture, analysis) } // Fallback ladder: UltraHDR+maxres → UltraHDR+default → JPEG+default. boundCamera = try { bind(maxRes = true, ultraHdr = ultraHdrSupported) } catch (e: Exception) {- Log.w("PhotoSession", "Max-res bind failed; retrying at default resolution", e)- provider.unbindAll()+ Log.e("NightPreview", "setupPhotoSession() Max-res bind failed (was Warn, hidden); retrying at default resolution. This is where resolution becomes lower and cannot take full quality!", e)+ try {+ provider.unbindAll()+ } catch (e2: Exception) {+ Log.e("NightPreview", "setupPhotoSession() unbindAll on fallback failed (hidden)", e2)+ } try { bind(maxRes = false, ultraHdr = ultraHdrSupported) } catch (e2: Exception) {+ Log.e("NightPreview", "setupPhotoSession() default-res ultraHdr=$ultraHdrSupported bind FAILED (was hidden)", e2) if (!ultraHdrSupported) throw e2- Log.w("PhotoSession", "Ultra HDR bind failed; falling back to plain JPEG", e2)- provider.unbindAll()+ Log.e("NightPreview", "setupPhotoSession() Ultra HDR bind failed (was Warn), falling back to plain JPEG – lower quality path")+ try {+ provider.unbindAll()+ } catch (e3: Exception) {+ Log.e("NightPreview", "setupPhotoSession() unbindAll on second fallback failed", e3)+ } bind(maxRes = false, ultraHdr = false) } } + val zs = boundCamera?.cameraInfo?.zoomState?.value+ Log.d("NightPreview", "setupPhotoSession() bound zoomState min=${zs?.minZoomRatio} max=${zs?.maxZoomRatio} ratio=${zs?.zoomRatio} thread=${Thread.currentThread().name}") boundCamera?.cameraInfo?.zoomState?.value?.let {+ Log.d("NightPreview", "setupPhotoSession() calling updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio} – should show .5,1x,2x,5x if >1x else only 1x") updateZoomLevels(it.minZoomRatio, it.maxZoomRatio) _zoomRatio.value = it.zoomRatio+ Log.d("NightPreview", "setupPhotoSession() after levels=${_availableZoomLevels.value} ratio=${_zoomRatio.value}") } readManualControlRanges() applyManualControls() _photoSessionActive.value = true+ Log.d("NightPreview", "setupPhotoSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution}") true } catch (e: Exception) {- Log.e("PhotoSession", "Failed to set up photo session", e)+ Log.e("NightPreview", "setupPhotoSession() OUTER CATCH – Failed to set up photo session – solid black root? ${e.javaClass.simpleName} ${e.message}", e) false } }@@ -1133,27 +1174,62 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { * extension isn't available or can't be bound. */ suspend fun setupNightPreviewSession(): Boolean {+ Log.d("NightPreview", "setupNightPreviewSession() ENTRY thread=${Thread.currentThread().name} lens=${_lensFacing.value} surfaceBefore=${_surfaceRequest.value?.resolution}")+ _surfaceRequest.value = null+ Log.d("NightPreview", "setupNightPreviewSession() cleared stale surfaceRequest before extension bind to prevent black-frame trap") return try { val provider = ProcessCameraProvider.awaitInstance(app) cameraProvider = provider- val mgr = getExtensionsManager(provider) ?: return setupPhotoSession()+ Log.d("NightPreview", "setupNightPreviewSession() got cameraProvider=$provider")+ val mgr = getExtensionsManager(provider)+ Log.d("NightPreview", "setupNightPreviewSession() ExtensionsManager=${mgr != null} cacheExt=${extensionsManager != null}")+ if (mgr == null) {+ Log.w("NightPreview", "setupNightPreviewSession() manager NULL, falling back to normal photo session")+ return setupPhotoSession()+ } val baseSelector = CameraSelector.Builder() .requireLensFacing(_lensFacing.value) .build()- if (!mgr.isExtensionAvailable(baseSelector, ExtensionMode.NIGHT)) {+ val extAvail = try {+ mgr.isExtensionAvailable(baseSelector, ExtensionMode.NIGHT)+ } catch (e: Exception) {+ Log.e("NightPreview", "setupNightPreviewSession() isExtensionAvailable threw (was hidden)", e)+ false+ }+ Log.d("NightPreview", "setupNightPreviewSession() isExtensionAvailable(NIGHT)=$extAvail lens=${_lensFacing.value}")+ if (!extAvail) {+ Log.w("NightPreview", "setupNightPreviewSession() extension NOT available on lens=${_lensFacing.value}, falling back") return setupPhotoSession() }- provider.unbindAll()- val nightSelector = mgr.getExtensionEnabledCameraSelector(baseSelector, ExtensionMode.NIGHT)+ Log.d("NightPreview", "setupNightPreviewSession() unbinding all before night selector")+ try {+ provider.unbindAll()+ Log.d("NightPreview", "setupNightPreviewSession() provider.unbindAll SUCCESS")+ } catch (e: Exception) {+ Log.e("NightPreview", "setupNightPreviewSession() unbindAll FAILED (was hidden)", e)+ throw e+ }+ val nightSelector = try {+ mgr.getExtensionEnabledCameraSelector(baseSelector, ExtensionMode.NIGHT)+ } catch (e: Exception) {+ Log.e("NightPreview", "setupNightPreviewSession() getExtensionEnabledCameraSelector FAILED (hidden)", e)+ throw e+ }+ Log.d("NightPreview", "setupNightPreviewSession() got nightSelector=$nightSelector") val analysisSupported = try { mgr.isImageAnalysisSupported(baseSelector, ExtensionMode.NIGHT) } catch (e: Exception) {- Log.w("NightPreview", "isImageAnalysisSupported query failed", e)+ Log.e("NightPreview", "setupNightPreviewSession() isImageAnalysisSupported query FAILED (was Warn only)", e) false }+ Log.d("NightPreview", "setupNightPreviewSession() isImageAnalysisSupported=$analysisSupported – this decides if luminance can auto-disengage; if false, preview binds without ImageAnalysis and zoom may be reported as 1x-only by vendor") val preview = Preview.Builder().build()- preview.setSurfaceProvider { request -> _surfaceRequest.value = request }+ preview.setSurfaceProvider { request ->+ Log.d("NightPreview", "setupNightPreviewSession() NEW surfaceRequest emitted res=${request.resolution} format=${request.javaClass.simpleName} – if this stops after _surfaceRequest=null, viewfinder goes black permanently")+ _surfaceRequest.value = request+ }+ Log.d("NightPreview", "setupNightPreviewSession() preview surfaceProvider attached, waiting for first request emission") val owner = ManualLifecycleOwner() owner.start()@@ -1169,38 +1245,73 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { // resolutions (no max-res 3-stream ladder) to stay within the combos // the vendor extension guarantees. fun bind(withAnalysis: Boolean): Camera {- return if (withAnalysis) {- val analysis = ImageAnalysis.Builder()- .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)- .build()- imageAnalysis = analysis- provider.bindToLifecycle(owner, nightSelector, preview, capture, analysis)- } else {- imageAnalysis = null- provider.bindToLifecycle(owner, nightSelector, preview, capture)+ Log.d("NightPreview", "setupNightPreviewSession() bind() withAnalysis=$withAnalysis START")+ return try {+ if (withAnalysis) {+ val analysis = ImageAnalysis.Builder()+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+ .build()+ imageAnalysis = analysis+ provider.bindToLifecycle(owner, nightSelector, preview, capture, analysis).also {+ Log.d("NightPreview", "setupNightPreviewSession() bind WITH analysis SUCCESS camera=${it.cameraInfo}")+ }+ } else {+ imageAnalysis = null+ provider.bindToLifecycle(owner, nightSelector, preview, capture).also {+ Log.d("NightPreview", "setupNightPreviewSession() bind WITHOUT analysis SUCCESS – note: after this, PhotoAnalyzer stops, so onLuminance won't fire and lowLightDetected stays frozen")+ }+ }+ } catch (e: Exception) {+ Log.e("NightPreview", "setupNightPreviewSession() bind(withAnalysis=$withAnalysis) EXCEPTION (was caught as warning) – this is likely why preview stays black and zoom shows only 1x", e)+ throw e } } boundCamera = try { bind(withAnalysis = analysisSupported) } catch (e: Exception) {- if (!analysisSupported) throw e- Log.w("NightPreview", "Night+analysis bind failed; retrying preview+capture only", e)- provider.unbindAll()- bind(withAnalysis = false)+ Log.w("NightPreview", "setupNightPreviewSession() first bind FAILED withAnalysis=$analysisSupported, exception type=${e.javaClass.simpleName} message=${e.message}", e)+ if (!analysisSupported) {+ Log.e("NightPreview", "setupNightPreviewSession() analysisSupported=false and bind failed – NOT retrying (no fallback), will go to catch and fallback to normal session")+ throw e+ }+ Log.w("NightPreview", "setupNightPreviewSession() retrying bind WITHOUT analysis – this loses luminance auto-disengage but may recover preview")+ try {+ provider.unbindAll()+ } catch (e2: Exception) {+ Log.e("NightPreview", "setupNightPreviewSession() retry unbindAll FAILED", e2)+ }+ try {+ bind(withAnalysis = false)+ } catch (e2: Exception) {+ Log.e("NightPreview", "setupNightPreviewSession() retry bind without analysis ALSO FAILED – root cause of black preview: ${e2.javaClass.simpleName} ${e2.message}", e2)+ throw e2+ } } + val zs = boundCamera?.cameraInfo?.zoomState?.value+ Log.d("NightPreview", "setupNightPreviewSession() boundCamera zoomState min=${zs?.minZoomRatio} max=${zs?.maxZoomRatio} current=${zs?.zoomRatio} – vendor NIGHT extension often reports 1x-only; this explains zoom bar disappearing (only 1x). Full-res capture is still max-res? No, extension uses default resolution, lower than max-res photo session, cannot take full quality while in extension preview") boundCamera?.cameraInfo?.zoomState?.value?.let {+ Log.d("NightPreview", "setupNightPreviewSession() calling updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}") updateZoomLevels(it.minZoomRatio, it.maxZoomRatio) _zoomRatio.value = it.zoomRatio+ Log.d("NightPreview", "setupNightPreviewSession() updated zoomRatio=${_zoomRatio.value} levels=${_availableZoomLevels.value}") } _nightPreviewActive.value = true _photoSessionActive.value = true+ Log.d("NightPreview", "setupNightPreviewSession() SUCCESS – nightPreviewActive=true photoSessionActive=true surfaceRequest=${_surfaceRequest.value?.resolution}") true } catch (e: Exception) {- Log.e("NightPreview", "Failed to set up night preview session; using normal session", e)+ Log.e("NightPreview", "setupNightPreviewSession() OUTER CATCH – FAILED to set up night preview, falling back to normal photo session. Root cause of solid black: exception=${e.javaClass.simpleName} msg=${e.message}", e) _nightPreviewActive.value = false- setupPhotoSession()+ val fallback = try {+ setupPhotoSession()+ } catch (e2: Exception) {+ Log.e("NightPreview", "setupNightPreviewSession() fallback setupPhotoSession() ALSO FAILED (double hidden)", e2)+ false+ }+ Log.d("NightPreview", "setupNightPreviewSession() fallback result=$fallback")+ fallback } } @@ -1259,21 +1370,37 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { } boundCamera = try {+ Log.d("NightPreview", "setupPanoramaSession() bind capped=true START") bind(capped = true) } catch (e: Exception) {- Log.w("PhotoSession", "Capped panorama bind failed; retrying at default resolution", e)- provider.unbindAll()- bind(capped = false)+ Log.e("NightPreview", "setupPanoramaSession() Capped panorama bind FAILED (was hidden as Warn), retrying at default – resolution lower!", e)+ try {+ provider.unbindAll()+ Log.d("NightPreview", "setupPanoramaSession() fallback unbindAll SUCCESS")+ } catch (e2: Exception) {+ Log.e("NightPreview", "setupPanoramaSession() fallback unbindAll FAILED (swallowed)", e2)+ }+ try {+ bind(capped = false)+ } catch (e2: Exception) {+ Log.e("NightPreview", "setupPanoramaSession() default bind ALSO FAILED – black root ${e2.javaClass.simpleName} ${e2.message}", e2)+ throw e2+ } } + val zsP = boundCamera?.cameraInfo?.zoomState?.value+ Log.d("NightPreview", "setupPanoramaSession() bound zoom min=${zsP?.minZoomRatio} max=${zsP?.maxZoomRatio} ratio=${zsP?.zoomRatio}") boundCamera?.cameraInfo?.zoomState?.value?.let {+ Log.d("NightPreview", "setupPanoramaSession() updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}") updateZoomLevels(it.minZoomRatio, it.maxZoomRatio) _zoomRatio.value = it.zoomRatio+ Log.d("NightPreview", "setupPanoramaSession() levels=${_availableZoomLevels.value}") } _photoSessionActive.value = true+ Log.d("NightPreview", "setupPanoramaSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution}") true } catch (e: Exception) {- Log.e("PhotoSession", "Failed to set up panorama session", e)+ Log.e("NightPreview", "setupPanoramaSession() OUTER CATCH – Failed solid black? ${e.javaClass.simpleName} ${e.message}", e) false } }@@ -1289,9 +1416,11 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { * capped+max+UHD → capped+max+JPEG → capped+default+UHD → capped+default+JPEG → default+default */ suspend fun setupPortraitSession(): Boolean {+ Log.d("NightPreview", "setupPortraitSession() ENTRY lens=${_lensFacing.value} thread=${Thread.currentThread().name}") return try { val provider = ProcessCameraProvider.awaitInstance(app) cameraProvider = provider+ Log.d("NightPreview", "setupPortraitSession() providerHash=${provider.hashCode()}") provider.unbindAll() val selector = CameraSelector.Builder()@@ -1302,11 +1431,15 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { try { androidx.camera.camera2.interop.Camera2Interop.Extender(previewBuilder) .setSessionCaptureCallback(aeSnapshotCallback)+ Log.d("NightPreview", "setupPortraitSession() attached AE snapshot callback") } catch (e: Exception) {- Log.w("PortraitSession", "Could not attach AE snapshot callback", e)+ Log.e("NightPreview", "setupPortraitSession() Could not attach AE snapshot callback (was Warn)", e) } val preview = previewBuilder.build()- preview.setSurfaceProvider { request -> _surfaceRequest.value = request }+ preview.setSurfaceProvider { request ->+ Log.d("NightPreview", "setupPortraitSession() surfaceRequest res=${request.resolution} thread=${Thread.currentThread().name}")+ _surfaceRequest.value = request+ } val owner = ManualLifecycleOwner() owner.start()@@ -1314,11 +1447,11 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { val ultraHdrSupported = try { val cameraInfo = provider.getCameraInfo(selector)- ImageCapture.getImageCaptureCapabilities(cameraInfo)- .supportedOutputFormats- .contains(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)+ val sup = ImageCapture.getImageCaptureCapabilities(cameraInfo).supportedOutputFormats.contains(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)+ Log.d("NightPreview", "setupPortraitSession() ultraHdrSupported=$sup")+ sup } catch (e: Exception) {- Log.w("PortraitSession", "Could not query Ultra HDR support", e)+ Log.e("NightPreview", "setupPortraitSession() Could not query Ultra HDR support (hidden)", e) false } @@ -1327,47 +1460,46 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { maxResCapture: Boolean, ultraHdr: Boolean ): Camera {- // Capture: always try max-res first to keep final image full-res.- val captureSelectorBuilder = ResolutionSelector.Builder()- .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)- if (maxResCapture) {- captureSelectorBuilder.setAllowedResolutionMode(- ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE- )- }- val captureBuilder = ImageCapture.Builder()- .setResolutionSelector(captureSelectorBuilder.build())- .setFlashMode(getImageCaptureFlashMode())- .setTargetRotation(targetRotation)- if (ultraHdr) {- captureBuilder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)- }- val capture = captureBuilder.build()- imageCapture = capture+ Log.d("NightPreview", "setupPortraitSession() bind(capped=$cappedAnalysis maxRes=$maxResCapture ultra=$ultraHdr) START")+ return try {+ // Capture: always try max-res first to keep final image full-res.+ val captureSelectorBuilder = ResolutionSelector.Builder()+ .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)+ if (maxResCapture) {+ captureSelectorBuilder.setAllowedResolutionMode(ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE)+ }+ val captureBuilder = ImageCapture.Builder()+ .setResolutionSelector(captureSelectorBuilder.build())+ .setFlashMode(getImageCaptureFlashMode())+ .setTargetRotation(targetRotation)+ if (ultraHdr) {+ captureBuilder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)+ }+ val capture = captureBuilder.build()+ imageCapture = capture - val analysisBuilder = ImageAnalysis.Builder()- .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)- if (cappedAnalysis) {- analysisBuilder.setResolutionSelector(- ResolutionSelector.Builder()- .setResolutionStrategy(- ResolutionStrategy(- Size(1024, 768), // ~0.8MP sweet spot > 256 model input- ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER- )- )- .build()- )- } else if (maxResCapture) {- analysisBuilder.setResolutionSelector(- ResolutionSelector.Builder()- .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)- .build()- )+ val analysisBuilder = ImageAnalysis.Builder()+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+ if (cappedAnalysis) {+ analysisBuilder.setResolutionSelector(+ ResolutionSelector.Builder().setResolutionStrategy(+ ResolutionStrategy(Size(1024, 768), ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER)+ ).build()+ )+ } else if (maxResCapture) {+ analysisBuilder.setResolutionSelector(+ ResolutionSelector.Builder().setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY).build()+ )+ }+ val analysis = analysisBuilder.build()+ imageAnalysis = analysis+ provider.bindToLifecycle(owner, selector, preview, capture, analysis).also {+ Log.d("NightPreview", "setupPortraitSession() bind SUCCESS capped=$cappedAnalysis maxRes=$maxResCapture ultra=$ultraHdr zoom min=${it.cameraInfo.zoomState.value?.minZoomRatio} max=${it.cameraInfo.zoomState.value?.maxZoomRatio}")+ }+ } catch (e: Exception) {+ Log.e("NightPreview", "setupPortraitSession() bind(capped=$cappedAnalysis maxRes=$maxResCapture ultra=$ultraHdr) FAILED – swallowed before! ${e.javaClass.simpleName} ${e.message}", e)+ throw e }- val analysis = analysisBuilder.build()- imageAnalysis = analysis- return provider.bindToLifecycle(owner, selector, preview, capture, analysis) } // Build attempt ladder; keep max-res capture attempts first per user request.@@ -1390,54 +1522,70 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { var lastError: Exception? = null for ((capped, maxRes, ultra) in attempts) { try {- if (bound != null) provider.unbindAll()+ if (bound != null) {+ Log.d("NightPreview", "setupPortraitSession() unbindAll before attempt capped=$capped maxRes=$maxRes ultra=$ultra")+ provider.unbindAll()+ } bound = bind(capped, maxRes, ultra)- Log.d(- "PortraitSession",- "Portrait bind succeeded: capped=$capped maxRes=$maxRes ultra=$ultra"- )+ Log.d("NightPreview", "setupPortraitSession() bind ladder SUCCESS capped=$capped maxRes=$maxRes ultra=$ultra zoom min=${bound.cameraInfo.zoomState.value?.minZoomRatio} max=${bound.cameraInfo.zoomState.value?.maxZoomRatio}") break } catch (e: Exception) { lastError = e- Log.w(- "PortraitSession",- "Portrait bind failed (capped=$capped maxRes=$maxRes ultra=$ultra); trying next",- e- )- provider.unbindAll()+ Log.e("NightPreview", "setupPortraitSession() Portrait bind failed (capped=$capped maxRes=$maxRes ultra=$ultra) – was Warn with swallowed stack, root of black? ${e.javaClass.simpleName} msg=${e.message}", e)+ try {+ provider.unbindAll()+ } catch (e2: Exception) {+ Log.e("NightPreview", "setupPortraitSession() unbindAll in catch FAILED (hidden)", e2)+ } } }+ if (bound == null) Log.e("NightPreview", "setupPortraitSession() ALL attempts FAILED! lastError=${lastError?.javaClass?.simpleName} ${lastError?.message} – produces black preview?", lastError ?: Exception("none")) boundCamera = bound ?: throw (lastError ?: IllegalStateException("Portrait session bind failed")) + val zsPor = boundCamera?.cameraInfo?.zoomState?.value+ Log.d("NightPreview", "setupPortraitSession() final zoom min=${zsPor?.minZoomRatio} max=${zsPor?.maxZoomRatio} ratio=${zsPor?.zoomRatio} – if max=1, zoom bar will show only 1x") boundCamera?.cameraInfo?.zoomState?.value?.let {+ Log.d("NightPreview", "setupPortraitSession() updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}") updateZoomLevels(it.minZoomRatio, it.maxZoomRatio) _zoomRatio.value = it.zoomRatio+ Log.d("NightPreview", "setupPortraitSession() after update levels=${_availableZoomLevels.value} ratio=${_zoomRatio.value}") } readManualControlRanges() applyManualControls() _photoSessionActive.value = true+ Log.d("NightPreview", "setupPortraitSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution}") true } catch (e: Exception) {- Log.e("PortraitSession", "Failed to set up portrait session", e)+ Log.e("NightPreview", "setupPortraitSession() OUTER CATCH – Failed black root? ${e.javaClass.simpleName} ${e.message}", e) false } } /** Reads the bound sensor's ISO range → stop list for the manual ISO control. */ private fun readManualControlRanges() {- val cam = boundCamera ?: return+ Log.d("NightPreview", "readManualControlRanges() called bound=${boundCamera != null} thread=${Thread.currentThread().name}")+ val cam = boundCamera ?: run {+ Log.w("NightPreview", "readManualControlRanges() no bound camera, returning")+ return+ } try { val info = androidx.camera.camera2.interop.Camera2CameraInfo.from(cam.cameraInfo) val isoRange = info.getCameraCharacteristic( android.hardware.camera2.CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE )+ Log.d("NightPreview", "readManualControlRanges() isoRange=$isoRange") _isoStops.value = if (isoRange != null) {- listOf(50, 100, 200, 400, 800, 1600, 3200, 6400, 12800)+ val filtered = listOf(50, 100, 200, 400, 800, 1600, 3200, 6400, 12800) .filter { it in isoRange.lower..isoRange.upper } .ifEmpty { listOf(isoRange.lower, isoRange.upper) }- } else emptyList()+ Log.d("NightPreview", "readManualControlRanges() filtered stops=$filtered")+ filtered+ } else {+ Log.w("NightPreview", "readManualControlRanges() isoRange null, emitting emptyList -> ISO bar notAvailable")+ emptyList()+ } } catch (e: Exception) {- Log.w("CameraViewModel", "Failed to read manual control ranges", e)+ Log.e("NightPreview", "readManualControlRanges() FAILED (was Warn, hidden) – could affect ISO bar + manual controls", e) } } @@ -1676,22 +1824,35 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { /** Tears down whatever session is currently bound and clears the shared preview surface. */ fun teardownSession() {+ Log.d("NightPreview", "teardownSession() START thread=${Thread.currentThread().name} surface=${_surfaceRequest.value?.resolution} photoActive=${_photoSessionActive.value} nightPreviewActive=${_nightPreviewActive.value} highSpeedActive=${_highSpeedActive.value} videoActive=${_videoSessionActive.value} boundCamera=${boundCamera != null} provider=${cameraProvider != null}")+ // CRITICAL: clear stale SurfaceRequest BEFORE unbind so CameraXViewfinder drops dead texture immediately (black-frame trap fix)+ _surfaceRequest.value = null+ Log.d("NightPreview", "teardownSession() cleared surfaceRequest -> null to avoid black-frame trap") currentRecording?.stop() currentRecording = null highSpeedRecording?.stop() highSpeedRecording = null- imageAnalysis?.clearAnalyzer()+ try {+ imageAnalysis?.clearAnalyzer()+ Log.d("NightPreview", "teardownSession() cleared analyzer previous=${currentAnalyzer?.javaClass?.simpleName}")+ } catch (e: Exception) {+ Log.e("NightPreview", "teardownSession() clearAnalyzer failed (swallowed before)", e)+ } currentAnalyzer = null sessionLifecycleOwner?.destroy() sessionLifecycleOwner = null- cameraProvider?.unbindAll()+ try {+ cameraProvider?.unbindAll()+ Log.d("NightPreview", "teardownSession() unbindAll SUCCESS")+ } catch (e: Exception) {+ Log.e("NightPreview", "teardownSession() unbindAll FAILED (was hidden)", e)+ } boundCamera = null imageCapture = null imageAnalysis = null videoCapture = null highSpeedVideoCapture = null cameraProvider = null- _surfaceRequest.value = null _photoSessionActive.value = false _nightPreviewActive.value = false _highSpeedActive.value = false@@ -2059,7 +2220,10 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { val stop = EXPOSURE_TIME_STOPS[_exposureTimeIndex.value] // Manual shutter/ISO are already applied live via applyManualControls(); the only transient // per-capture override here is the night-mode emulation (fully-auto exposure + night active).- val nightExposure = if (nightModeActive.value && isExposureAuto())+ // Skip it when the vendor NIGHT extension preview is bound: that session runs its own+ // multi-frame AE and rejects Camera2-interop AE_MODE_OFF/manual-exposure options, which makes+ // the capture fail. In that case a plain takePicture() lets the extension produce the shot.+ val nightExposure = if (nightModeActive.value && isExposureAuto() && !_nightPreviewActive.value) computeNightExposure() else null // Used only to drive the long-exposure countdown overlay. val exposureNanos = stop.nanos ?: nightExposure?.nanos@@ -2188,37 +2352,71 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { /** Obtains (and caches) the ExtensionsManager bound to [provider]. Null if unavailable. */ private suspend fun getExtensionsManager(provider: ProcessCameraProvider): ExtensionsManager? {- extensionsManager?.let { return it }+ Log.d("NightPreview", "getExtensionsManager() called providerHash=${provider.hashCode()} cachedExists=${extensionsManager != null} thread=${Thread.currentThread().name} startMs=${System.currentTimeMillis()}")+ extensionsManager?.let {+ Log.d("NightPreview", "getExtensionsManager() returning CACHED manager providerHash=${provider.hashCode()} manager=$it – NOTE: cached across provider instances, may be tied to old provider if provider changed!")+ return it+ } return try {+ val start = System.currentTimeMillis() val mgr = suspendCancellableCoroutine<ExtensionsManager> { cont ->+ Log.d("NightPreview", "getExtensionsManager() creating async instance for providerHash=${provider.hashCode()}") val future = ExtensionsManager.getInstanceAsync(app, provider) future.addListener({ try {- cont.resume(future.get())+ val res = future.get()+ Log.d("NightPreview", "getExtensionsManager() future.get() SUCCESS res=$res elapsed=${System.currentTimeMillis() - start}ms")+ cont.resume(res) } catch (e: Exception) {+ Log.e("NightPreview", "getExtensionsManager() future.get() FAILED elapsed=${System.currentTimeMillis() - start}ms – this was previously swallowed as Warn", e) cont.cancel(e) } }, ContextCompat.getMainExecutor(app)) }+ Log.d("NightPreview", "getExtensionsManager() obtained mgr=$mgr caching for providerHash=${provider.hashCode()} elapsed=${System.currentTimeMillis() - start}ms") extensionsManager = mgr mgr } catch (e: Exception) {- Log.w("CameraViewModel", "ExtensionsManager unavailable", e)+ Log.e("NightPreview", "getExtensionsManager() EXCEPTION – ExtensionsManager unavailable (was hidden as Warn), root cause of black preview if NIGHT needed", e) null } } /** Whether the CameraX NIGHT extension is available on the current lens. */ suspend fun isNightExtensionAvailable(): Boolean {+ // The vendor advertises the NIGHT extension (isExtensionAvailable(NIGHT)=true), but on the+ // camera-pipe backend that every CameraX build this app can use runs on, creating the+ // extension capture session fails at graph-config time on Pixel ("Framework size list map+ // not supported in pixel path" -> ERROR_GRAPH_CONFIG). The bind "succeeds" and emits a+ // SurfaceRequest, then the session dies async: black preview + failed capture. Until CameraX+ // fixes pipe extensions, treat NIGHT as unavailable so night mode uses the custom burst ++ // Rust-merge path (captureNightPhotoCustom) over the normal, working photo session.+ if (!ENABLE_NIGHT_EXTENSION) return false+ val startMs = System.currentTimeMillis()+ Log.d("NightPreview", "isNightExtensionAvailable() START lensFacing=${_lensFacing.value} thread=${Thread.currentThread().name}") return try { val provider = ProcessCameraProvider.awaitInstance(app)- val mgr = getExtensionsManager(provider) ?: return false+ Log.d("NightPreview", "isNightExtensionAvailable() got providerHash=${provider.hashCode()} elapsed=${System.currentTimeMillis() - startMs}ms")+ val mgr = getExtensionsManager(provider)+ Log.d("NightPreview", "isNightExtensionAvailable() ExtensionsManager=${mgr != null} elapsed=${System.currentTimeMillis() - startMs}ms")+ if (mgr == null) {+ Log.w("NightPreview", "isNightExtensionAvailable() manager NULL after ${System.currentTimeMillis() - startMs}ms, returning false -> moon button may show but useNightPreview false, so no visible transition")+ return false+ } val selector = CameraSelector.Builder() .requireLensFacing(_lensFacing.value) .build()- mgr.isExtensionAvailable(selector, ExtensionMode.NIGHT)+ val affordStart = System.currentTimeMillis()+ val avail = try {+ mgr.isExtensionAvailable(selector, ExtensionMode.NIGHT)+ } catch (e: Exception) {+ Log.e("NightPreview", "isNightExtensionAvailable() isExtensionAvailable(NIGHT) THREW – swallowed as false before! lens=${_lensFacing.value} selector=$selector", e)+ false+ }+ Log.d("NightPreview", "isNightExtensionAvailable() isExtensionAvailable(NIGHT)=$avail lens=${_lensFacing.value} lookupTook=${System.currentTimeMillis() - affordStart}ms total=${System.currentTimeMillis() - startMs}ms – if false, NIGHT preview disabled, zoom stays full, no black")+ avail } catch (e: Exception) {- Log.w("CameraViewModel", "Night extension availability check failed", e)+ Log.e("NightPreview", "isNightExtensionAvailable() OUTER EXCEPTION – was hidden as Warn, returning false, totalTook=${System.currentTimeMillis() - startMs}ms", e) false } }
camera/src/main/java/com/vayunmathur/camera/util/CodecSupport.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CodecSupport.kt b/camera/src/main/java/com/vayunmathur/camera/util/CodecSupport.ktindex 0b3da07245..07353e9954 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CodecSupport.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CodecSupport.kt@@ -10,37 +10,18 @@ import android.util.Log */ object CodecSupport { - // NOTE: These must NOT be lazy on main thread. MediaCodecList.REGULAR_CODECS- // is known to block for 10-20s on some devices (codec service init). All callers- // must query off main thread, or we risk Input ANR (FocusEvent timeout).- // To force off-main discipline, we use nullable cached values initialized on demand.-- @Volatile- private var cachedAv1: Boolean? = null- @Volatile- private var cachedHevc: Boolean? = null- /** A hardware-accelerated AV1 (`video/av01`) encoder exists on this device. */- val isHardwareAv1EncoderAvailable: Boolean- get() = cachedAv1 ?: hasEncoder(MediaFormat.MIMETYPE_VIDEO_AV1, requireHardware = true).also { cachedAv1 = it }+ val isHardwareAv1EncoderAvailable: Boolean by lazy {+ hasEncoder(MediaFormat.MIMETYPE_VIDEO_AV1, requireHardware = true)+ } /** An HEVC/H.265 (`video/hevc`) encoder exists on this device. */- val isHevcEncoderAvailable: Boolean- get() = cachedHevc ?: hasEncoder(MediaFormat.MIMETYPE_VIDEO_HEVC, requireHardware = false).also { cachedHevc = it }-- /** Call off main thread to pre-warm caches safely. */- fun prewarm() {- try {- if (cachedAv1 == null) cachedAv1 = hasEncoder(MediaFormat.MIMETYPE_VIDEO_AV1, true)- if (cachedHevc == null) cachedHevc = hasEncoder(MediaFormat.MIMETYPE_VIDEO_HEVC, false)- } catch (_: Exception) {}+ val isHevcEncoderAvailable: Boolean by lazy {+ hasEncoder(MediaFormat.MIMETYPE_VIDEO_HEVC, requireHardware = false) } private fun hasEncoder(mimeType: String, requireHardware: Boolean): Boolean { return try {- if (android.os.Looper.myLooper() == android.os.Looper.getMainLooper()) {- Log.w("CodecSupport", "hasEncoder($mimeType) called on MAIN thread - will block! Stack:", Throwable())- } MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos.any { info -> info.isEncoder && (!requireHardware || info.isHardwareAccelerated) &&
camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.ktindex 0d74f13c15..1a6a539cba 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt@@ -1,6 +1,7 @@ package com.vayunmathur.camera.util import android.graphics.Bitmap+import android.util.Log import androidx.annotation.OptIn import androidx.camera.core.ExperimentalGetImage import androidx.camera.core.ImageAnalysis@@ -40,47 +41,106 @@ class PhotoAnalyzer( @OptIn(ExperimentalGetImage::class) override fun analyze(imageProxy: ImageProxy) {- val buffer = imageProxy.planes[0].buffer- val bytes = ByteArray(buffer.remaining())- buffer.get(bytes)-- // Average luminance over a strided subsample of the Y plane (kept cheap).- var sum = 0L- var count = 0- var i = 0- while (i < bytes.size) {- sum += (bytes[i].toInt() and 0xFF)- count++- i += 16- }- if (count > 0) onLuminance(sum.toFloat() / count)+ val startMs = System.currentTimeMillis()+ try {+ val buffer = imageProxy.planes[0].buffer+ val bytes = ByteArray(buffer.remaining())+ try {+ buffer.get(bytes)+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer buffer.get() threw (swallowed before) plane0Remaining? ${buffer.remaining()}", e)+ throw e+ } - // Feed the Motion-Photo ring buffer with an RGB copy of this frame.- onMotionFrame?.let { emit ->+ // Average luminance over a strided subsample of the Y plane (kept cheap).+ var sum = 0L+ var count = 0+ var i = 0 try {- emit(imageProxy.toBitmap(), imageProxy.imageInfo.timestamp, imageProxy.imageInfo.rotationDegrees)- } catch (_: Exception) {+ while (i < bytes.size) {+ sum += (bytes[i].toInt() and 0xFF)+ count+++ i += 16+ }+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer luma loop threw (hidden)", e)+ }+ if (count > 0) {+ val avg = sum.toFloat() / count+ Log.d("NightPreview", "PhotoAnalyzer luma avg=$avg sum=$sum count=$count bytesSize=${bytes.size} width=${imageProxy.width} height=${imageProxy.height} timestamp=${imageProxy.imageInfo.timestamp} rot=${imageProxy.imageInfo.rotationDegrees} took=${System.currentTimeMillis() - startMs}ms")+ try {+ onLuminance(avg)+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer onLuminance callback threw (was hidden)", e)+ }+ } else {+ Log.w("NightPreview", "PhotoAnalyzer count=0, no luma callback – preview may be black? bytesSize=${bytes.size}") }- } - val source = PlanarYUVLuminanceSource(- bytes,- imageProxy.width,- imageProxy.height,- 0, 0,- imageProxy.width,- imageProxy.height,- false- )- val bitmap = BinaryBitmap(HybridBinarizer(source))+ // Feed the Motion-Photo ring buffer with an RGB copy of this frame.+ onMotionFrame?.let { emit ->+ try {+ val bmp = try {+ imageProxy.toBitmap()+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer toBitmap() for Motion-Photo threw (hidden before)", e)+ null+ }+ if (bmp != null) {+ try {+ emit(bmp, imageProxy.imageInfo.timestamp, imageProxy.imageInfo.rotationDegrees)+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer onMotionFrame emit threw (hidden)", e)+ }+ }+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer Motion-Photo outer threw (hidden)", e)+ }+ } - try {- val result = reader.decodeWithState(bitmap)- onQrDetected(result.text)- } catch (_: NotFoundException) {- } finally {- reader.reset()- imageProxy.close()+ val source = PlanarYUVLuminanceSource(+ bytes,+ imageProxy.width,+ imageProxy.height,+ 0, 0,+ imageProxy.width,+ imageProxy.height,+ false+ )+ val bitmap = BinaryBitmap(HybridBinarizer(source))++ try {+ val result = reader.decodeWithState(bitmap)+ Log.d("NightPreview", "PhotoAnalyzer QR decoded text=${result.text} width=${imageProxy.width} height=${imageProxy.height}")+ try {+ onQrDetected(result.text)+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer onQrDetected threw (hidden)", e)+ }+ } catch (_: NotFoundException) {+ // expected – no QR in frame, NOT an error+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer ZXing decodeWithState threw OTHER than NotFound (was swallowed)", e)+ } finally {+ try {+ reader.reset()+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer reader.reset() threw (hidden)", e)+ }+ try {+ imageProxy.close()+ Log.d("NightPreview", "PhotoAnalyzer imageProxy.close() took=${System.currentTimeMillis() - startMs}ms total – if not closed, pipeline stalls -> black preview!")+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer imageProxy.close() threw – pipeline stall -> black preview root!", e)+ }+ }+ } catch (e: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer analyze() OUTER threw – was not logged, causes black preview and only 1x zoom because analyzer crashes", e)+ try {+ imageProxy.close()+ } catch (e2: Exception) {+ Log.e("NightPreview", "PhotoAnalyzer outer close() also failed (double hidden)", e2)+ } } } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.ktindex 802f526189..bbb8697c64 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt@@ -4,7 +4,6 @@ import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge-import androidx.compose.animation.Crossfade import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable@@ -14,6 +13,7 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -26,9 +26,14 @@ import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInWindow import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp@@ -37,21 +42,27 @@ import com.vayunmathur.games.logicgate.data.ChipCategory import com.vayunmathur.games.logicgate.data.ChipLibrary import com.vayunmathur.games.logicgate.data.CircuitEvaluator import com.vayunmathur.games.logicgate.data.EvalResult+import com.vayunmathur.games.logicgate.data.LevelDef import com.vayunmathur.games.logicgate.data.Levels import com.vayunmathur.games.logicgate.ui.CircuitCanvas import com.vayunmathur.games.logicgate.ui.LogicGateTheme+import com.vayunmathur.games.logicgate.ui.MobileDimens import com.vayunmathur.games.logicgate.ui.ProgressionScreen import com.vayunmathur.games.logicgate.ui.Turing import com.vayunmathur.games.logicgate.util.AppBackupAgent import com.vayunmathur.games.logicgate.util.EvalStatus import com.vayunmathur.games.logicgate.util.LogicViewModel import com.vayunmathur.library.ui.AchievementNotification+import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.GameCenterScreen+import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.TopAppBarDefaults import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey@@ -98,34 +109,130 @@ fun Navigation(viewModel: LogicViewModel) { enum class ChipGroup { BIT, WORD, CUSTOM } -private fun groupForCategory(cat: ChipCategory): ChipGroup = when (cat) {+internal fun groupForCategory(cat: ChipCategory): ChipGroup = when (cat) { ChipCategory.PRIMITIVE, ChipCategory.FOUNDATION, ChipCategory.ROUTING -> ChipGroup.BIT ChipCategory.BUS, ChipCategory.ARITH -> ChipGroup.WORD ChipCategory.MEMORY, ChipCategory.CPU -> ChipGroup.CUSTOM } +private suspend fun AwaitPointerEventScope.awaitFirstDownGlobal(): PointerInputChange {+ while (true) {+ val ev = awaitPointerEvent()+ if (ev.type == PointerEventType.Press) {+ val d = ev.changes.firstOrNull { !it.isConsumed } ?: continue+ return d+ }+ }+}++@Composable+fun MobileBitDotsRow(bits: List<Boolean>, dotSize: Dp = 14.dp, spacing: Dp = 4.dp, maxDots: Int = 8) {+ val display = if (bits.size > 1) bits.reversed() else bits+ Row(horizontalArrangement = Arrangement.spacedBy(spacing), verticalAlignment = Alignment.CenterVertically) {+ display.take(maxDots).forEach { b ->+ Box(modifier = Modifier.size(dotSize).clip(CircleShape).background(if (b) Turing.bitGreen else Turing.bitRed).border(0.8.dp, Color.Black.copy(alpha = 0.35f), CircleShape))+ }+ if (display.size > maxDots) Text("+${display.size - maxDots}", fontSize = 10.sp, color = Color(0xFF94A3B8))+ }+}++@Composable+fun BitDot(isOne: Boolean, dotSize: Dp = 8.dp) {+ Box(modifier = Modifier.size(dotSize).clip(CircleShape).background(if (isOne) Color(0xFF22C55E) else Color(0xFFEF4444)))+}++@Composable+fun TuringBitDotsRow(bits: List<Boolean>, dotSize: Dp = 8.dp, spacing: Dp = 3.dp, maxDots: Int = 8) {+ MobileBitDotsRow(bits, dotSize, spacing, maxDots)+}++@Composable+fun BitDotRow(bits: List<Boolean>, dotSize: Dp = 7.dp, maxDots: Int = 8) {+ MobileBitDotsRow(bits, dotSize, 3.dp, maxDots)+}++fun displayInputLabel(level: LevelDef, idx: Int): String {+ val raw = level.inputs.getOrNull(idx) ?: return ""+ val low = raw.lowercase()+ return when (low) {+ "a" -> "Input 1"+ "b" -> "Input 2"+ "c" -> "Input 3"+ "d" -> "Input 4"+ "e" -> "Input 5"+ "f" -> "Input 6"+ "g" -> "Input 7"+ "h" -> "Input 8"+ "in" -> "Input"+ "sel", "select" -> "Select"+ "sel0", "select0", "s0" -> "Select 0"+ "sel1", "select1", "s1" -> "Select 1"+ "sel2", "select2", "s2" -> "Select 2"+ "opcode" -> "Opcode"+ else -> {+ if (low.length == 1 && low[0] in 'a'..'h') "Input ${low[0] - 'a' + 1}"+ else raw.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }+ }+ }+}++fun displayOutputLabel(level: LevelDef, idx: Int): String {+ val raw = level.outputs.getOrNull(idx) ?: return ""+ val low = raw.lowercase()+ return when {+ low == "out" || low == "output" -> if (level.outputs.size == 1) "Output" else "Output ${idx + 1}"+ low == "sum" -> "Sum"+ low in listOf("carry", "cout", "borrow") -> "Carry"+ low == "q" -> "Q"+ low == "nq" -> "nQ"+ else -> raw.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }+ }+}++data class TableRowUi(+ val inputSlices: Map<Int, List<Boolean>>,+ val desiredSlices: Map<Int, List<Boolean>>,+ val actualSlices: Map<Int, List<Boolean>>?+)++private fun cellWidthForInput(level: LevelDef, idx: Int): Dp {+ val w = level.inputWidth(idx)+ return when {+ w >= 8 -> 168.dp // 8*14 + 7*4 = 140 needs 168 for padding+ w >= 4 -> 96.dp // 4*14+3*4=68 fits 96+ else -> 72.dp+ }+}++private fun cellWidthForOutput(level: LevelDef, idx: Int): Dp {+ val w = level.outputWidth(idx)+ return when {+ w >= 8 -> 168.dp+ w >= 4 -> 96.dp+ else -> 72.dp+ }+}+ @OptIn(ExperimentalMaterial3Api::class) @Composable fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelId: String) { val level = Levels.get(levelId) val uiState by viewModel.uiState.collectAsState() val unlocked by viewModel.unlockedChips.collectAsState()- val completed by viewModel.completedIds.collectAsState()-- LaunchedEffect(levelId) { viewModel.selectLevel(levelId) }- val isCurrent = uiState.currentLevelId == levelId var canvasPosInWindow by remember { mutableStateOf(Offset.Zero) } var canvasSize by remember { mutableStateOf(Size.Zero) }+ var canvasScale by remember { mutableStateOf(1f) }+ var canvasOffset by remember { mutableStateOf(Offset.Zero) } var draggingChipId by remember { mutableStateOf<String?>(null) } var draggingChipWindowPos by remember { mutableStateOf(Offset.Zero) } var selectedGroup by remember { mutableStateOf<ChipGroup?>(null) }+ var showIoSheet by remember { mutableStateOf(false) } val density = LocalDensity.current - // representative vector val totalInBits = level.totalInputBits val displayLimit = if (totalInBits <= 10) minOf(64, (1 shl totalInBits)) else 28- val inputVectors: List<List<Boolean>> = remember(totalInBits, displayLimit) {+ val inputVectors: List<List<Boolean>> = remember(totalInBits, displayLimit, levelId) { val seed = 1234L if (totalInBits <= 10) (0 until (1 shl totalInBits)).take(displayLimit).map { c -> List(totalInBits) { i -> ((c shr i) and 1) == 1 } } else {@@ -138,674 +245,680 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI vs } }- val selectedIdx = remember(uiState.evalStatus, inputVectors) {- val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows- if (failing != null && failing.isNotEmpty()) failing.first() % inputVectors.size else 0++ var selectedIdxMutable by remember(levelId) { mutableStateOf(0) }+ var liveFlatInputs by remember(levelId) { mutableStateOf<List<Boolean>?>(null) }++ LaunchedEffect(levelId) {+ viewModel.selectLevel(levelId)+ liveFlatInputs = null+ selectedIdxMutable = 0 }- val flatInSelected = remember(inputVectors, selectedIdx) { inputVectors.getOrNull(selectedIdx) ?: emptyList() }- val inputDecimals: Map<Int, Int> = remember(flatInSelected, level) {+ LaunchedEffect(uiState.evalStatus) {+ if (liveFlatInputs == null) {+ val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows+ selectedIdxMutable = if (failing != null && failing.isNotEmpty()) failing.first() % inputVectors.size else 0+ }+ }++ val flatInSelectedBase = remember(inputVectors, selectedIdxMutable) { inputVectors.getOrNull(selectedIdxMutable) ?: emptyList() }+ val effectiveFlat = liveFlatInputs ?: flatInSelectedBase++ val inputSlicesMap: Map<Int, List<Boolean>> = remember(effectiveFlat, level) { level.inputs.indices.associateWith { idx ->- val off = level.inputBitOffset(idx); val w = level.inputWidth(idx)- val slice = if (off + w <= flatInSelected.size) flatInSelected.slice(off until off + w) else List(w) { false }- ChipLibrary.bitsToInt(slice)+ val off = level.inputBitOffset(idx); val wd = level.inputWidth(idx)+ if (off + wd <= effectiveFlat.size) effectiveFlat.slice(off until off + wd) else List(wd) { false }+ }+ }+ val inputBitSlices = inputSlicesMap+ val inputOnMap: Map<Int, Boolean> = remember(effectiveFlat, level) {+ level.inputs.indices.associateWith { idx ->+ val bits = inputSlicesMap[idx] ?: listOf(false)+ bits.any { it } } }- val inputBitSlices: Map<Int, List<Boolean>> = remember(flatInSelected, level) {+ val inputDecimals: Map<Int, Int> = remember(effectiveFlat, level) { level.inputs.indices.associateWith { idx ->- val off = level.inputBitOffset(idx); val w = level.inputWidth(idx)- if (off + w <= flatInSelected.size) flatInSelected.slice(off until off + w) else List(w) { false }+ val off = level.inputBitOffset(idx); val wd = level.inputWidth(idx)+ val slice = if (off + wd <= effectiveFlat.size) effectiveFlat.slice(off until off + wd) else List(wd) { false }+ ChipLibrary.bitsToInt(slice) } } val targetDef = remember(level.targetChipId) { try { ChipLibrary.get(level.targetChipId) } catch (_: Exception) { null } }- val desiredFlatOut: List<Boolean> = remember(flatInSelected, targetDef, level) {- targetDef?.let { it.eval(flatInSelected).take(level.totalOutputBits) } ?: emptyList()+ val desiredFlatOut: List<Boolean> = remember(effectiveFlat, targetDef, level) {+ targetDef?.eval(effectiveFlat)?.take(level.totalOutputBits) ?: emptyList() }- val desiredDecimals: Map<Int, Int> = remember(desiredFlatOut, level) {+ val desiredBitSlices: Map<Int, List<Boolean>> = remember(desiredFlatOut, level) { level.outputs.indices.associateWith { oi ->- val off = level.outputBitOffset(oi); val w = level.outputWidth(oi)- val slice = if (off + w <= desiredFlatOut.size) desiredFlatOut.slice(off until off + w) else List(w) { false }- ChipLibrary.bitsToInt(slice)+ val off = level.outputBitOffset(oi); val wd = level.outputWidth(oi)+ if (off + wd <= desiredFlatOut.size) desiredFlatOut.slice(off until off + wd) else List(wd) { false } } }- val desiredBitSlices: Map<Int, List<Boolean>> = remember(desiredFlatOut, level) {+ val desiredDecimals: Map<Int, Int> = remember(desiredFlatOut, level) { level.outputs.indices.associateWith { oi ->- val off = level.outputBitOffset(oi); val w = level.outputWidth(oi)- if (off + w <= desiredFlatOut.size) desiredFlatOut.slice(off until off + w) else List(w) { false }+ val off = level.outputBitOffset(oi); val wd = level.outputWidth(oi)+ val slice = if (off + wd <= desiredFlatOut.size) desiredFlatOut.slice(off until off + wd) else List(wd) { false }+ ChipLibrary.bitsToInt(slice) } } val actualEvalRows: List<List<Boolean>>? = remember(uiState.circuit, level) { val res = CircuitEvaluator.evaluate(level, uiState.circuit) if (res is EvalResult.Success) res.rows else null }- val actualFlatOut: List<Boolean> = remember(actualEvalRows, selectedIdx) { actualEvalRows?.getOrNull(selectedIdx) ?: emptyList() }- val actualDecimals: Map<Int, Int> = remember(actualFlatOut, level) {+ val actualFlatOut: List<Boolean> = remember(actualEvalRows, selectedIdxMutable, liveFlatInputs) {+ if (liveFlatInputs != null) {+ val foundIdx = inputVectors.indexOfFirst { it == liveFlatInputs }+ if (foundIdx >= 0) actualEvalRows?.getOrNull(foundIdx) ?: emptyList() else actualEvalRows?.getOrNull(selectedIdxMutable) ?: emptyList()+ } else actualEvalRows?.getOrNull(selectedIdxMutable) ?: emptyList()+ }+ val actualBitSlices: Map<Int, List<Boolean>> = remember(actualFlatOut, level) { level.outputs.indices.associateWith { oi ->- val off = level.outputBitOffset(oi); val w = level.outputWidth(oi)- val slice = if (off + w <= actualFlatOut.size) actualFlatOut.slice(off until off + w) else List(w) { false }- ChipLibrary.bitsToInt(slice)+ val off = level.outputBitOffset(oi); val wd = level.outputWidth(oi)+ if (off + wd <= actualFlatOut.size) actualFlatOut.slice(off until off + wd) else List(wd) { false } } }- val actualBitSlices: Map<Int, List<Boolean>> = remember(actualFlatOut, level) {+ val actualDecimals: Map<Int, Int> = remember(actualFlatOut, level) { level.outputs.indices.associateWith { oi ->- val off = level.outputBitOffset(oi); val w = level.outputWidth(oi)- if (off + w <= actualFlatOut.size) actualFlatOut.slice(off until off + w) else List(w) { false }+ val off = level.outputBitOffset(oi); val wd = level.outputWidth(oi)+ val slice = if (off + wd <= actualFlatOut.size) actualFlatOut.slice(off until off + wd) else List(wd) { false }+ ChipLibrary.bitsToInt(slice) } } - if (!isCurrent) {+ if (uiState.currentLevelId != levelId) { Box(modifier = Modifier.fillMaxSize().background(Color(0xFF0F1E2D)), contentAlignment = Alignment.Center) { Text(stringResource(R.string.loading)) } return } - val isWiring = uiState.wiringFrom != null val gateCost = uiState.circuit.totalNandCost()- val delayEst = remember(uiState.circuit) { estimateDelay(uiState.circuit) }- val statusText = when (val s = uiState.evalStatus) {- is EvalStatus.Ok -> if (s.isFullyCorrect) "PASS • ${level.unlocksChipId?.let { "Unlocked $it" } ?: "CORRECT"}"- else "${s.passingRows}/${s.totalRows} FAIL ${s.failingRows.size}"- is EvalStatus.Error -> s.msg.take(88)- is EvalStatus.Cycle -> "CYCLE ${s.ids.take(2).joinToString()}"- else -> "Drag chip • drag terminals • tap output->input to wire • tap wire delete • long-press gate delete"- }- val statusColor = when {- uiState.evalStatus is EvalStatus.Ok && (uiState.evalStatus as EvalStatus.Ok).isFullyCorrect -> Color(0xFF22C55E)- uiState.evalStatus is EvalStatus.Ok && (uiState.evalStatus as EvalStatus.Ok).passingRows > 0 -> Color(0xFFFBBF24)- else -> Color(0xFF94A3B8)- }-- // Full Turing Complete layout- Column(modifier = Modifier.fillMaxSize().background(Turing.headerBg)) {- // ----- TOP BAR (matches screenshot) ------ TuringTopBar(- levelName = level.displayName.uppercase(),- gateCount = gateCost,- delay = delayEst,- onBack = { backStack.pop() },- onClear = { viewModel.clearCircuit() },- statusText = statusText,- statusColor = statusColor,- isWiring = isWiring,- onCancelWiring = { viewModel.cancelWiring() }- )-- // ----- MIDDLE: left panel + toolbar + canvas + right tabs ------ Row(modifier = Modifier.weight(1f).fillMaxWidth().background(Turing.bg)) {- // Left I/O panel (Tick, Sim speed, Inputs, Outputs) - as screenshot left dark card- TuringLeftPanel(- tick = selectedIdx,- simSpeed = if (selectedIdx == 0) 0 else 20,- level = level,- inputDecimals = inputDecimals,- inputBitSlices = inputBitSlices,- desiredDecimals = desiredDecimals,- desiredBitSlices = desiredBitSlices,- actualDecimals = actualDecimals,- modifier = Modifier.width(132.dp).fillMaxHeight()- ) - // Vertical icon toolbar (magnify, play, etc)- TuringMiddleToolbar(- onClear = { viewModel.clearCircuit() },- onUndo = { viewModel.undo() },- onRedo = { viewModel.redo() },- canUndo = uiState.canUndo,- canRedo = uiState.canRedo,- modifier = Modifier.width(48.dp).fillMaxHeight()- )+ fun toggleInput(idx: Int) {+ val off = level.inputBitOffset(idx)+ val wd = level.inputWidth(idx)+ if (off >= effectiveFlat.size && effectiveFlat.isNotEmpty()) return+ val baseFlat = if (effectiveFlat.size == totalInBits) effectiveFlat else flatInSelectedBase.ifEmpty { List(totalInBits) { false } }+ val mutable = baseFlat.toMutableList()+ if (wd == 1) {+ if (off < mutable.size) mutable[off] = !mutable[off]+ } else {+ val slice = if (off + wd <= mutable.size) mutable.slice(off until off + wd) else List(wd) { false }+ var v = ChipLibrary.bitsToInt(slice)+ v = (v + 1) % (1 shl wd)+ for (k in 0 until wd) if (off + k < mutable.size) mutable[off + k] = ((v shr k) and 1) == 1+ }+ liveFlatInputs = mutable.toList()+ val found = inputVectors.indexOfFirst { it == mutable }+ if (found >= 0) selectedIdxMutable = found+ } - // Canvas- Box(- modifier = Modifier.weight(1f).fillMaxHeight().onGloballyPositioned { coords ->- canvasPosInWindow = coords.positionInWindow()- canvasSize = Size(coords.size.width.toFloat(), coords.size.height.toFloat())- }- ) {- CircuitCanvas(- level = level,- gates = uiState.circuit.gates,- wires = uiState.circuit.wires,- outputMaps = uiState.circuit.outputMappings,- inputPositions = uiState.circuit.inputPositions,- outputPositions = uiState.circuit.outputPositions,- wiringFrom = uiState.wiringFrom,- onCreateWire = { f, t -> viewModel.createWire(f, t) },- onStartWiring = { viewModel.startWiring(it) },- onCancelWiring = { viewModel.cancelWiring() },- onGateMove = { id, x, y -> viewModel.onGateMoved(id, x, y) },- onGateMoveFinished = { id, x, y -> viewModel.onGateMoveFinished(id, x, y) },- onInputTermMove = { idx, x, y -> viewModel.onInputMoved(idx, x, y) },- onInputTermMoveFinished = { idx, x, y -> viewModel.onInputMoveFinished(idx, x, y) },- onOutputTermMove = { idx, x, y -> viewModel.onOutputMoved(idx, x, y) },- onOutputTermMoveFinished = { idx, x, y -> viewModel.onOutputMoveFinished(idx, x, y) },- onGateDelete = { viewModel.removeGate(it) },- onWireDelete = { viewModel.removeWire(it) },- onOutputMapDelete = { viewModel.removeOutputMapping(it) },- dragGhostLineEnd = uiState.dragGhostLineEnd,- onGhostLine = { viewModel.updateGhostLine(it) },- inputValues = inputDecimals,- desiredOutputValues = desiredDecimals,- outputValues = actualDecimals,- modifier = Modifier.fillMaxSize()- )- // Ghost for inventory drag- draggingChipId?.let { chipId ->- val localOffset = Offset(draggingChipWindowPos.x - canvasPosInWindow.x, draggingChipWindowPos.y - canvasPosInWindow.y)- val isOver = localOffset.x >= 0f && localOffset.x <= canvasSize.width && localOffset.y >= 0f && localOffset.y <= canvasSize.height- val def = try { ChipLibrary.get(chipId) } catch (_: Exception) { null }- val ghostW = 84.dp; val ghostH = 36.dp- Box(- modifier = Modifier.offset {- IntOffset(- (localOffset.x - with(density) { ghostW.toPx() } / 2f).roundToInt(),- (localOffset.y - with(density) { ghostH.toPx() } / 2f).roundToInt()- )- }.size(ghostW, ghostH)- .background(if (isOver) Color(0xFFD1FAE5).copy(alpha = 0.92f) else Color(0xFF4B5563).copy(alpha = 0.7f), RoundedCornerShape(6.dp))- .border(if (isOver) 2.dp else 1.dp, if (isOver) Color(0xFF22C55E) else Color.White.copy(alpha = 0.28f), RoundedCornerShape(6.dp)),- contentAlignment = Alignment.Center- ) { def?.let { Text(text = it.displayName.take(8), fontSize = 10.sp, color = if (isOver) Color(0xFF14532D) else Color.White) } }+ val tableRows: List<TableRowUi> = remember(inputVectors, level, targetDef, actualEvalRows) {+ inputVectors.mapIndexed { rowIdx, flat ->+ val inSlices = level.inputs.indices.associateWith { i ->+ val off = level.inputBitOffset(i); val wd = level.inputWidth(i)+ if (off + wd <= flat.size) flat.slice(off until off + wd) else List(wd) { false }+ }+ val desiredFlat = targetDef?.eval(flat)?.take(level.totalOutputBits) ?: emptyList()+ val desSlices = level.outputs.indices.associateWith { oi ->+ val off = level.outputBitOffset(oi); val wd = level.outputWidth(oi)+ if (off + wd <= desiredFlat.size) desiredFlat.slice(off until off + wd) else List(wd) { false }+ }+ val actualFlat = actualEvalRows?.getOrNull(rowIdx)+ val actSlices = actualFlat?.let { af ->+ level.outputs.indices.associateWith { oi ->+ val off = level.outputBitOffset(oi); val wd = level.outputWidth(oi)+ if (off + wd <= af.size) af.slice(off until off + wd) else List(wd) { false } } }-- // Right BIT/WORD/CUSTOM tabs vertical (screenshot right)- TuringRightTabs(- selected = selectedGroup,- onSelect = { selectedGroup = it },- modifier = Modifier.width(52.dp).fillMaxHeight()- )+ TableRowUi(inSlices, desSlices, actSlices) }-- // Inventory bar (chips) - horizontal, above bottom panel- TuringInventoryBar(- allowed = level.allowedChipIds,- unlockedChips = unlocked,- selectedGroup = selectedGroup,- onChipDragStart = { chipId, windowOffset ->- draggingChipId = chipId- draggingChipWindowPos = windowOffset- },- onChipDrag = { chipId, windowOffset ->- draggingChipId = chipId- draggingChipWindowPos = windowOffset- },- onChipDrop = { chipId, windowOffset ->- val local = Offset(windowOffset.x - canvasPosInWindow.x, windowOffset.y - canvasPosInWindow.y)- val isOver = local.x >= 0f && local.x <= canvasSize.width && local.y >= 0f && local.y <= canvasSize.height- if (isOver) viewModel.addGateAt(chipId, local.x, local.y)- draggingChipId = null- draggingChipWindowPos = Offset.Zero- },- modifier = Modifier.fillMaxWidth().background(Color(0xFF1A2332))- )-- // Bottom testbench matching screenshot- TuringBottomTestbench(- level = level,- selectedIdx = selectedIdx,- inputDecimals = inputDecimals,- inputBitSlices = inputBitSlices,- desiredDecimals = desiredDecimals,- desiredBitSlices = desiredBitSlices,- actualDecimals = actualDecimals,- actualBitSlices = actualBitSlices,- failingCount = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows?.size ?: 0,- onToggle = { viewModel.toggleTruthTable() },- showTable = uiState.showTruthTable,- modifier = Modifier.fillMaxWidth()- ) }-}+ val failingSet = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows?.toSet() ?: emptySet()++ // Win popup: surface as soon as the level is fully correct.+ val isWon = (uiState.evalStatus as? EvalStatus.Ok)?.isFullyCorrect == true+ var showWinDialog by remember(levelId) { mutableStateOf(false) }+ var winDismissed by remember(levelId) { mutableStateOf(false) }+ LaunchedEffect(isWon) { if (isWon && !winDismissed) showWinDialog = true }+ val nextLevelId = remember(levelId) {+ val idx = Levels.all.indexOfFirst { it.id == levelId }+ if (idx >= 0) Levels.all.getOrNull(idx + 1)?.id else null+ } -@Composable-private fun TuringTopBar(- levelName: String,- gateCount: Int,- delay: Int,- onBack: () -> Unit,- onClear: () -> Unit,- statusText: String,- statusColor: Color,- isWiring: Boolean,- onCancelWiring: () -> Unit-) {- Column(modifier = Modifier.fillMaxWidth().background(Turing.headerBg)) {- Row(- modifier = Modifier.fillMaxWidth().height(38.dp).padding(horizontal = 8.dp),- verticalAlignment = Alignment.CenterVertically- ) {- // Left icons mimicking screenshot: hamburger, chat, doc, book, hierarchy, chip, envelope, +255, bulb- Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {- Box(modifier = Modifier.size(28.dp).clip(RoundedCornerShape(6.dp)).background(Turing.iconBg).clickable { onBack() }, contentAlignment = Alignment.Center) {- Text("☰", fontSize = 12.sp, color = Color(0xFF9AA3BB))+ BoxWithConstraints(modifier = Modifier.fillMaxSize()) {+ val maxW = maxWidth+ val maxH = maxHeight+ val isCompact = maxW < 600.dp+ val isPortrait = maxH > maxW+ val isCompactPortrait = isCompact && isPortrait+ Scaffold(+ modifier = Modifier.fillMaxSize(),+ topBar = {+ TopAppBar(+ title = {+ Text(text = level.displayName, fontSize = 18.sp, fontWeight = FontWeight.ExtraBold, color = Turing.headerPink, maxLines = 1)+ },+ navigationIcon = { IconNavigation(backStack) },+ actions = {+ Box(modifier = Modifier.clip(RoundedCornerShape(8.dp)).background(Turing.rightTabOn).padding(horizontal = 8.dp, vertical = 4.dp)) {+ Text("GATE $gateCost", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color.White)+ }+ Spacer(modifier = Modifier.width(4.dp))+ AppBarActionBtn(glyph = "↩", enabled = uiState.canUndo) { viewModel.undo() }+ AppBarActionBtn(glyph = "↪", enabled = uiState.canRedo) { viewModel.redo() }+ Box(modifier = Modifier.size(40.dp).clip(RoundedCornerShape(10.dp)).background(Turing.iconBg).clickable { viewModel.clearCircuit() }, contentAlignment = Alignment.Center) {+ IconDelete(modifier = Modifier.size(20.dp), tint = Color(0xFFFF8A8A))+ }+ Spacer(modifier = Modifier.width(4.dp))+ },+ colors = TopAppBarDefaults.topAppBarColors(containerColor = Turing.headerBg, titleContentColor = Color.White, navigationIconContentColor = Color.White, actionIconContentColor = Color.White)+ )+ },+ containerColor = Turing.headerBg+ ) { innerPadding ->+ Column(modifier = Modifier.fillMaxSize().padding(innerPadding).background(Turing.headerBg)) {+ if (isCompactPortrait) {+ // Phone portrait – solid blocks canvas hero+ Box(modifier = Modifier.weight(1f).fillMaxWidth().onGloballyPositioned { coords ->+ canvasPosInWindow = coords.positionInWindow()+ canvasSize = Size(coords.size.width.toFloat(), coords.size.height.toFloat())+ }) {+ CircuitCanvas(+ level = level, gates = uiState.circuit.gates, wires = uiState.circuit.wires, outputMaps = uiState.circuit.outputMappings,+ inputPositions = uiState.circuit.inputPositions, outputPositions = uiState.circuit.outputPositions,+ wiringFrom = uiState.wiringFrom,+ onCreateWire = { f: com.vayunmathur.games.logicgate.data.WireEnd, t: com.vayunmathur.games.logicgate.data.WireEnd -> viewModel.createWire(f, t) },+ onStartWiring = { end: com.vayunmathur.games.logicgate.data.WireEnd -> viewModel.startWiring(end) },+ onCancelWiring = { viewModel.cancelWiring() },+ onGateMoveFinished = { id: String, x: Float, y: Float -> viewModel.onGateMoveFinished(id, x, y) },+ onInputTermMoveFinished = { idx: Int, x: Float, y: Float -> viewModel.onInputMoveFinished(idx, x, y) },+ onOutputTermMoveFinished = { idx: Int, x: Float, y: Float -> viewModel.onOutputMoveFinished(idx, x, y) },+ onGateMove = { id: String, x: Float, y: Float -> viewModel.onGateMoved(id, x, y) },+ onInputTermMove = { idx: Int, x: Float, y: Float -> viewModel.onInputMoved(idx, x, y) },+ onOutputTermMove = { idx: Int, x: Float, y: Float -> viewModel.onOutputMoved(idx, x, y) },+ onGateDelete = { id: String -> viewModel.removeGate(id) },+ onWireDelete = { id: String -> viewModel.removeWire(id) },+ onOutputMapDelete = { idx: Int -> viewModel.removeOutputMapping(idx) },+ dragGhostLineEnd = uiState.dragGhostLineEnd,+ onGhostLine = { off: Offset? -> viewModel.updateGhostLine(off) },+ inputValues = inputDecimals, desiredOutputValues = desiredDecimals, outputValues = actualDecimals,+ modifier = Modifier.fillMaxSize(), isCompact = true,+ onToggleInput = { idx: Int -> toggleInput(idx) },+ inputOnMap = inputOnMap,+ inputBitSlices = inputBitSlices,+ outputBitSlicesActual = actualBitSlices,+ onViewportChange = { s: Float, o: Offset -> canvasScale = s; canvasOffset = o }+ )+ draggingChipId?.let { chipId ->+ val localOffset = Offset(draggingChipWindowPos.x - canvasPosInWindow.x, draggingChipWindowPos.y - canvasPosInWindow.y)+ val isOver = localOffset.x >= 0f && localOffset.x <= canvasSize.width && localOffset.y >= 0f && localOffset.y <= canvasSize.height+ val def = try { ChipLibrary.get(chipId) } catch (_: Exception) { null }+ val ghostW = 100.dp; val ghostH = 56.dp+ Box(modifier = Modifier.offset {+ IntOffset((localOffset.x - with(density) { ghostW.toPx() } / 2f).roundToInt(), (localOffset.y - with(density) { ghostH.toPx() } / 2f).roundToInt())+ }.size(ghostW, ghostH).background(if (isOver) Color(0xFFD1FAE5).copy(alpha = 0.92f) else Color(0xFF4B5563).copy(alpha = 0.7f), RoundedCornerShape(12.dp)).border(if (isOver) 2.dp else 1.dp, if (isOver) Color(0xFF22C55E) else Color.White.copy(alpha = 0.28f), RoundedCornerShape(12.dp)), contentAlignment = Alignment.Center) {+ def?.let { Text(text = it.displayName, fontSize = 13.sp, color = if (isOver) Color(0xFF14532D) else Color.White) }+ }+ }+ }+ MobileFilterRow(selected = selectedGroup, onSelect = { selectedGroup = it }, modifier = Modifier.fillMaxWidth())+ MobileInventoryBar(+ allowed = level.allowedChipIds, unlockedChips = unlocked, selectedGroup = selectedGroup,+ onChipDragStart = { chipId: String, windowOffset: Offset -> draggingChipId = chipId; draggingChipWindowPos = windowOffset },+ onChipDrag = { chipId: String, windowOffset: Offset -> draggingChipId = chipId; draggingChipWindowPos = windowOffset },+ onChipDrop = { chipId: String, windowOffset: Offset ->+ val local = Offset(windowOffset.x - canvasPosInWindow.x, windowOffset.y - canvasPosInWindow.y)+ val isOver = local.x >= 0f && local.x <= canvasSize.width && local.y >= 0f && local.y <= canvasSize.height+ if (isOver) {+ val content = Offset((local.x - canvasOffset.x) / canvasScale, (local.y - canvasOffset.y) / canvasScale)+ viewModel.addGateAt(chipId, content.x, content.y)+ }+ draggingChipId = null; draggingChipWindowPos = Offset.Zero+ }, modifier = Modifier.fillMaxWidth()+ )+ MobileTestbench(+ level = level,+ tableRows = tableRows,+ selectedIdx = selectedIdxMutable,+ onSelectRow = { rowIdx: Int ->+ selectedIdxMutable = rowIdx+ liveFlatInputs = inputVectors.getOrNull(rowIdx)+ },+ outputsConnected = uiState.circuit.outputMappings.isNotEmpty(),+ failingSet = failingSet,+ modifier = Modifier.fillMaxWidth()+ )+ } else {+ // Tablet/landscape – keep side panels but still solid blocks+ Column(modifier = Modifier.fillMaxSize().navigationBarsPadding().imePadding()) {+ Row(modifier = Modifier.weight(1f).fillMaxWidth().background(Turing.bg)) {+ MobileLeftPanel(tick = selectedIdxMutable, simSpeed = if (selectedIdxMutable == 0) 0 else 20, level = level, inputDecimals = inputDecimals, inputBitSlices = inputBitSlices, desiredDecimals = desiredDecimals, desiredBitSlices = desiredBitSlices, actualDecimals = actualDecimals, modifier = Modifier.width(MobileDimens.leftPanelW).fillMaxHeight())+ MobileMiddleToolbar(onClear = { viewModel.clearCircuit() }, onUndo = { viewModel.undo() }, onRedo = { viewModel.redo() }, canUndo = uiState.canUndo, canRedo = uiState.canRedo, modifier = Modifier.width(MobileDimens.toolbarWidth).fillMaxHeight())+ Box(modifier = Modifier.weight(1f).fillMaxHeight().onGloballyPositioned { coords ->+ canvasPosInWindow = coords.positionInWindow(); canvasSize = Size(coords.size.width.toFloat(), coords.size.height.toFloat())+ }) {+ CircuitCanvas(+ level = level, gates = uiState.circuit.gates, wires = uiState.circuit.wires, outputMaps = uiState.circuit.outputMappings,+ inputPositions = uiState.circuit.inputPositions, outputPositions = uiState.circuit.outputPositions,+ wiringFrom = uiState.wiringFrom,+ onCreateWire = { f: com.vayunmathur.games.logicgate.data.WireEnd, t: com.vayunmathur.games.logicgate.data.WireEnd -> viewModel.createWire(f, t) },+ onStartWiring = { end: com.vayunmathur.games.logicgate.data.WireEnd -> viewModel.startWiring(end) },+ onCancelWiring = { viewModel.cancelWiring() },+ onGateMoveFinished = { id: String, x: Float, y: Float -> viewModel.onGateMoveFinished(id, x, y) },+ onInputTermMoveFinished = { idx: Int, x: Float, y: Float -> viewModel.onInputMoveFinished(idx, x, y) },+ onOutputTermMoveFinished = { idx: Int, x: Float, y: Float -> viewModel.onOutputMoveFinished(idx, x, y) },+ onGateMove = { id: String, x: Float, y: Float -> viewModel.onGateMoved(id, x, y) },+ onInputTermMove = { idx: Int, x: Float, y: Float -> viewModel.onInputMoved(idx, x, y) },+ onOutputTermMove = { idx: Int, x: Float, y: Float -> viewModel.onOutputMoved(idx, x, y) },+ onGateDelete = { id: String -> viewModel.removeGate(id) },+ onWireDelete = { id: String -> viewModel.removeWire(id) },+ onOutputMapDelete = { idx: Int -> viewModel.removeOutputMapping(idx) },+ dragGhostLineEnd = uiState.dragGhostLineEnd,+ onGhostLine = { off: Offset? -> viewModel.updateGhostLine(off) },+ inputValues = inputDecimals, desiredOutputValues = desiredDecimals, outputValues = actualDecimals,+ modifier = Modifier.fillMaxSize(), isCompact = isCompact,+ onToggleInput = { idx: Int -> toggleInput(idx) },+ inputOnMap = inputOnMap,+ inputBitSlices = inputBitSlices,+ outputBitSlicesActual = actualBitSlices,+ onViewportChange = { s: Float, o: Offset -> canvasScale = s; canvasOffset = o }+ )+ draggingChipId?.let { chipId ->+ val localOffset = Offset(draggingChipWindowPos.x - canvasPosInWindow.x, draggingChipWindowPos.y - canvasPosInWindow.y)+ val isOver = localOffset.x >= 0f && localOffset.x <= canvasSize.width && localOffset.y >= 0f && localOffset.y <= canvasSize.height+ val def = try { ChipLibrary.get(chipId) } catch (_: Exception) { null }+ val ghostW = 100.dp; val ghostH = 56.dp+ Box(modifier = Modifier.offset {+ IntOffset((localOffset.x - with(density) { ghostW.toPx() } / 2f).roundToInt(), (localOffset.y - with(density) { ghostH.toPx() } / 2f).roundToInt())+ }.size(ghostW, ghostH).background(if (isOver) Color(0xFFD1FAE5).copy(alpha = 0.92f) else Color(0xFF4B5563).copy(alpha = 0.7f), RoundedCornerShape(12.dp)).border(if (isOver) 2.dp else 1.dp, if (isOver) Color(0xFF22C55E) else Color.White.copy(alpha = 0.28f), RoundedCornerShape(12.dp)), contentAlignment = Alignment.Center) {+ def?.let { Text(text = it.displayName, fontSize = 13.sp, color = if (isOver) Color(0xFF14532D) else Color.White) }+ }+ }+ }+ }+ MobileFilterRow(selected = selectedGroup, onSelect = { selectedGroup = it }, modifier = Modifier.fillMaxWidth())+ MobileInventoryBar(+ allowed = level.allowedChipIds, unlockedChips = unlocked, selectedGroup = selectedGroup,+ onChipDragStart = { chipId: String, windowOffset: Offset -> draggingChipId = chipId; draggingChipWindowPos = windowOffset },+ onChipDrag = { chipId: String, windowOffset: Offset -> draggingChipId = chipId; draggingChipWindowPos = windowOffset },+ onChipDrop = { chipId: String, windowOffset: Offset ->+ val local = Offset(windowOffset.x - canvasPosInWindow.x, windowOffset.y - canvasPosInWindow.y)+ val isOver = local.x >= 0f && local.x <= canvasSize.width && local.y >= 0f && local.y <= canvasSize.height+ if (isOver) {+ val content = Offset((local.x - canvasOffset.x) / canvasScale, (local.y - canvasOffset.y) / canvasScale)+ viewModel.addGateAt(chipId, content.x, content.y)+ }+ draggingChipId = null; draggingChipWindowPos = Offset.Zero+ }, modifier = Modifier.fillMaxWidth()+ )+ MobileTestbench(+ level = level,+ tableRows = tableRows,+ selectedIdx = selectedIdxMutable,+ onSelectRow = { rowIdx: Int ->+ selectedIdxMutable = rowIdx+ liveFlatInputs = inputVectors.getOrNull(rowIdx)+ },+ outputsConnected = uiState.circuit.outputMappings.isNotEmpty(),+ failingSet = failingSet,+ modifier = Modifier.fillMaxWidth()+ )+ } }- Text("💬", fontSize = 12.sp, color = Color(0xFF8AA0BB))- Text("📄", fontSize = 11.sp, color = Color(0xFF8AA0BB))- Text("📖", fontSize = 11.sp, color = Color(0xFF8AA0BB))- Text("⯀", fontSize = 11.sp, color = Color(0xFF8AA0BB))- Text("🖥", fontSize = 11.sp, color = Color(0xFF8AA0BB))- Text("✉", fontSize = 11.sp, color = Color(0xFF8AA0BB))- Box(modifier = Modifier.clip(RoundedCornerShape(4.dp)).background(Color(0xFF3A3A52)).padding(horizontal = 4.dp, vertical = 2.dp)) {- Text("+255", fontSize = 8.sp, color = Color.White)+ if (showIoSheet) {+ MobileIoSheet(level = level, inputDecimals = inputDecimals, inputBitSlices = inputBitSlices, desiredDecimals = desiredDecimals, desiredBitSlices = desiredBitSlices, actualDecimals = actualDecimals, actualBitSlices = actualBitSlices, onDismiss = { showIoSheet = false }) }- Text("💡", fontSize = 11.sp, color = Color(0xFFF5C15A)) }- Spacer(modifier = Modifier.weight(1f))- // Center title pink like screenshot- Text(- text = levelName,- fontSize = 12.sp,- color = Turing.headerPink,- modifier = Modifier.padding(horizontal = 12.dp)- )- Spacer(modifier = Modifier.weight(1f))- // Right Gate / Delay- Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {- Text("Gate: $gateCount", fontSize = 10.sp, color = Color
Diff truncated.