feat(phase-1/m4.4c): editor to commonMain; intake/voice/back seams

NoteEditorScreen + its private helpers move to commonMain. New seams (§6.3/6.5):

- EditorIntake (interface + expect rememberEditorIntake): Android actual
  holds the verbatim launcher code (camera TakePicture + permission
  chain, SAF OpenDocument, RECORD_AUDIO dance, FileProvider/
  ACTION_VIEW open, Toasts, createTempCameraUri/queryDisplayName);
  JVM actual = AWT FileDialog picker + Desktop.open/xdg-open, with
  supportsCamera/supportsVoice=false so the editor HIDES camera + mic
  buttons instead of stubbing them (§6.5).
- VoiceNoteSlot expect composable: Android renders the untouched
  VoiceNoteSection (MediaStore recorder); JVM renders nothing.
- PlatformBackHandler: activity-compose BackHandler on Android, no-op
  on desktop (Esc routing is M5 polish).
- securityManager param became the neutral beginExternalActivity:
  (() -> Unit)? lambda (Android names the Android type only in its
  actual; call sites unchanged). VoiceNoteSection takes the same
  lambda now; App.kt adapts the one call site.

Verified: ./gradlew assembleDebug :desktopApp:build SUCCESSFUL
+ :composeApp:compileKotlinJvm :composeApp:compileDebugKotlinAndroid
+ :desktopApp:run --self-test (SELFTEST id=1 -> RENDER notes=1
selected=1) + :core:data-jvm:smoke (M1a PASS); models clean.
This commit is contained in:
Incido Developer committed 2026-10-06 18:51:47 +13:00
1 parent 56949c485f
commit 6b5c24e1bc
9 files changed
+644 -276

No files matched your search

@@ -240,8 +240,12 @@ fun IncidoApp(
repository = repository,
// v0.3.4.0 hotfix: suppress auto-lock around
// the editor's picker / camera / system-viewer
// round-trips.
securityManager = resolvedSecurity,
// round-trips. M4.4c: the editor lives in
// commonMain now and cannot name the Android
// SecurityManager — it takes this neutral
// lambda instead.
beginExternalActivity = resolvedSecurity
?.let { sec -> { sec.beginExternalActivity() } },
)
}
composable(Routes.SETTINGS) {
@@ -0,0 +1,312 @@
package org.incido.compose.ui.editor
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.domain.model.NoteAttachment
import org.incido.domain.repository.NoteRepository
/**
* M4.4c Android actual — the editor's Android intake code, moved from
* `NoteEditorScreen` essentially verbatim (camera + permission + file
* launchers, the FileProvider/ACTION_VIEW open path from
* `AttachmentThumbnail`, the Toasts, and the two private file helpers).
*
* The one spelling change: `securityManager?.beginExternalActivity()`
* is now the injected neutral `beginExternalActivity` lambda (the
* screen can no longer name the Android type in commonMain). Call sites
* (camera round-trip, picker, system viewer) are unchanged.
*/
@Composable
actual fun rememberEditorIntake(
onPickedBytes: suspend (bytes: ByteArray, mimeType: String, displayName: String) -> Unit,
onVoiceConvert: () -> Unit,
isVoiceMode: Boolean,
beginExternalActivity: (() -> Unit)?,
): EditorIntake {
val ctx = LocalContext.current
val scope = rememberCoroutineScope()
// v0.3.1.0: camera permission + capture. The camera launcher is
// declared FIRST so the permission callback (below) can forward to it
// without a Kotlin forward-reference error.
var pendingCameraUri by remember { mutableStateOf<Uri?>(null) }
val cameraLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.TakePicture()
) { success ->
val uri = pendingCameraUri
if (success && uri != null) {
scope.launch {
val bytes = withContext(Dispatchers.IO) {
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() }
}
// Always delete the temp file — its bytes are now in the DB.
runCatching { uri.path?.let { File(it).delete() } }
pendingCameraUri = null
if (bytes != null) {
onPickedBytes(
bytes,
"image/jpeg",
"IMG_${System.currentTimeMillis()}.jpg",
)
} else {
Toast.makeText(ctx, "Couldn't read captured photo", Toast.LENGTH_SHORT).show()
}
}
} else {
pendingCameraUri = null
}
}
// Now declared AFTER cameraLauncher so it can forward to it.
val cameraPermissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
pendingCameraUri?.let { uri ->
// v0.3.4.0 hotfix: the camera app takes us fully out of
// the process — with Auto-Lock = Immediate the return
// trip used to land on the lock screen (losing the
// unsaved note). Flag the round-trip so the re-lock is
// suppressed.
beginExternalActivity?.invoke()
cameraLauncher.launch(uri)
}
} else {
Toast.makeText(ctx, "Camera permission denied", Toast.LENGTH_SHORT).show()
}
}
val filePickerLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.OpenDocument()
) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
scope.launch {
val ctxForResolver = ctx
val (bytes, displayName, mime) = withContext(Dispatchers.IO) {
val resolver = ctxForResolver.contentResolver
val name = queryDisplayName(resolver, uri) ?: "Attachment_${System.currentTimeMillis()}"
val mimeType = resolver.getType(uri) ?: "application/octet-stream"
val data = resolver.openInputStream(uri)?.use { it.readBytes() }
Triple(data, name, mimeType)
}
if (bytes != null) {
onPickedBytes(bytes, mime, displayName)
} else {
Toast.makeText(ctx, "Couldn't read attachment", Toast.LENGTH_SHORT).show()
}
}
}
// v0.4.2.0 — voice notes. RECORD_AUDIO is requested the first time
// the user toggles the mic mode; on grant the note converts. The
// grant state is checked LIVE on every tap (a revoke from Settings
// mid-session must not slip through a cached flag).
val micPermissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
onVoiceConvert()
} else {
Toast.makeText(ctx, "Microphone permission denied", Toast.LENGTH_SHORT).show()
}
}
fun micPermissionGranted(): Boolean =
ContextCompat.checkSelfPermission(
ctx,
Manifest.permission.RECORD_AUDIO,
) == PackageManager.PERMISSION_GRANTED
return object : EditorIntake {
override val supportsCamera = true
override val supportsVoice = true
override fun takePhoto() {
val (uri, _) = createTempCameraUri(ctx)
if (uri == null) {
Toast.makeText(ctx, "Couldn't prepare camera outbox", Toast.LENGTH_SHORT).show()
return
}
pendingCameraUri = uri
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
override fun pickFiles() {
// v0.3.4.0 hotfix: the SAF picker backgrounds the app; with
// Auto-Lock = Immediate the return used to lock the app and
// wipe the unsaved note.
beginExternalActivity?.invoke()
filePickerLauncher.launch(arrayOf("*/*"))
}
override fun toggleVoiceMode() {
if (isVoiceMode) {
// Toggling back needs no mic at all — the take survives as
// an ordinary attachment.
onVoiceConvert()
return
}
if (micPermissionGranted()) {
onVoiceConvert()
} else {
micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
}
}
override fun checkMicPermission(): Boolean = micPermissionGranted()
override fun requestMicPermission() {
micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
}
override fun notify(msg: String) {
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show()
}
override fun openExternal(bytes: ByteArray, mimeType: String, displayName: String) {
// v0.3.1.2 path, verbatim from AttachmentThumbnail's tap
// handler: cache temp file → FileProvider Uri → ACTION_VIEW.
runCatching {
// Sanitise displayName for use as a filename —
// strip any path separators / chars the OS
// doesn't allow in filenames.
val safeName = displayName.replace(Regex("[/\\\\:*?\"<>|]"), "_")
// v0.3.1.3: write into a dedicated `open_outbox/`
// subdir under cacheDir so it falls inside the
// FileProvider's exposed path set (see
// app/src/main/res/xml/file_paths.xml). Previously
// this wrote straight to cacheDir which is NOT
// exposed, so FileProvider.getUriForFile threw
// IllegalArgumentException and the runCatching
// swallowed it as the misleading "No app can
// open …" toast.
val outbox = File(ctx.cacheDir, "open_outbox").apply { mkdirs() }
val tmp = File(
outbox,
"open_${System.currentTimeMillis()}_$safeName",
).apply { createNewFile() }
tmp.writeBytes(bytes)
val uri = FileProvider.getUriForFile(
ctx,
"${ctx.packageName}.fileprovider",
tmp,
)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, mimeType)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
// v0.3.4.0 hotfix: opening an attachment in the system
// viewer also leaves the app — suppress the auto-lock on
// return.
beginExternalActivity?.invoke()
ctx.startActivity(intent)
}.onFailure { err ->
// v0.3.1.3: distinguish "no handler" from "couldn't
// open". ActivityNotFoundException means the OS has no
// app registered for this mime type (e.g. no PDF viewer
// installed); anything else (typically
// IllegalArgumentException from FileProvider when
// file_paths.xml is misconfigured, or IOException from
// the cache write) gets a generic message.
val msg = if (err is android.content.ActivityNotFoundException) {
"No app can open $displayName"
} else {
"Couldn't open $displayName"
}
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show()
}
}
}
}
/**
* M4.4c Android actual: the voice recorder card — the same
* `VoiceNoteSection` the screen called directly, now reached through
* the common slot. The old `securityManager` argument becomes the
* neutral [beginExternalActivity] lambda (see VoiceNoteSection).
*/
@Composable
actual fun VoiceNoteSlot(
voicePending: PendingAttachment?,
voicePendingBytes: ByteArray?,
voicePersisted: NoteAttachment?,
repository: NoteRepository?,
hasMicPermission: () -> Boolean,
onRequestPermission: () -> Unit,
onTakeRecorded: (ByteArray, String) -> Unit,
onDeleteTake: () -> Unit,
beginExternalActivity: (() -> Unit)?,
modifier: Modifier,
) {
VoiceNoteSection(
voicePending = voicePending,
voicePendingBytes = voicePendingBytes,
voicePersisted = voicePersisted,
repository = repository,
hasMicPermission = hasMicPermission,
onRequestPermission = onRequestPermission,
onTakeRecorded = onTakeRecorded,
onDeleteTake = onDeleteTake,
beginExternalActivity = beginExternalActivity,
modifier = modifier,
)
}
// ---------------------------------------------------------------------
// helpers — moved verbatim from NoteEditorScreen.kt
// ---------------------------------------------------------------------
/**
* Create a temporary file in the app's cache and return a
* FileProvider-scoped Uri pointing at it. The camera app writes a JPEG
* there; we read the bytes and delete the temp file. Returns
* `(uri, file)` so the caller can clean up if reading fails.
*/
private fun createTempCameraUri(ctx: Context): Pair<Uri?, File?> {
return try {
val outbox = File(ctx.cacheDir, "camera_outbox").apply { mkdirs() }
val file = File(outbox, "cap_${System.currentTimeMillis()}.jpg")
file.createNewFile()
val authority = "${ctx.packageName}.fileprovider"
val uri = FileProvider.getUriForFile(ctx, authority, file)
uri to file
} catch (e: Exception) {
null to null
}
}
/**
* Read the Open Documents column DISPLAY_NAME for a content:// Uri,
* falling back to the last path segment. Returns null if neither
* works (which is fine — the caller uses a generated default).
*/
private fun queryDisplayName(resolver: android.content.ContentResolver, uri: Uri): String? {
return try {
resolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { cursor ->
if (cursor.moveToFirst()) {
val idx = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
if (idx >= 0) cursor.getString(idx) else null
} else null
}
} catch (_: Exception) {
null
}
}
File diff suppressed because it is too large. Load diff
@@ -56,7 +56,6 @@ import androidx.core.content.FileProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.incido.compose.data.security.SecurityManager
import org.incido.domain.model.NoteAttachment
import org.incido.domain.repository.NoteRepository
import java.io.File
@@ -102,7 +101,7 @@ fun VoiceNoteSection(
/** Remove the current take (pending or persisted). */
onDeleteTake: () -> Unit,
/** Suppress auto-lock around the download share-sheet round-trip (API < 29). */
securityManager: SecurityManager?,
beginExternalActivity: (() -> Unit)?,
modifier: Modifier = Modifier,
) {
val ctx = LocalContext.current
@@ -244,7 +243,7 @@ fun VoiceNoteSection(
sourceKey = takeKey,
takeName = takeName,
onDelete = onDeleteTake,
onDownload = { saveVoiceTakeToDevice(ctx, securityManager, takeName, takeMime, takeBytes) },
onDownload = { saveVoiceTakeToDevice(ctx, beginExternalActivity, takeName, takeMime, takeBytes) },
onRecordAgain = { startRecording() },
)
@@ -465,7 +464,7 @@ private fun VoicePlayerBar(
*/
private fun saveVoiceTakeToDevice(
ctx: Context,
securityManager: SecurityManager?,
beginExternalActivity: (() -> Unit)?,
displayName: String,
mimeType: String,
bytes: ByteArray,
@@ -513,7 +512,7 @@ private fun saveVoiceTakeToDevice(
}
// Auto-Lock = Immediate must not fire while the chooser is up
// (same v0.3.4.0 hotfix as the attachment viewer).
securityManager?.beginExternalActivity()
beginExternalActivity?.invoke()
ctx.startActivity(Intent.createChooser(send, "Save recording"))
}.onFailure {
Toast.makeText(ctx, "Couldn't save recording", Toast.LENGTH_SHORT).show()
@@ -0,0 +1,9 @@
package org.incido.compose.util
import androidx.compose.runtime.Composable
/** M4.4c Android actual — the verbatim `activity-compose` back handler. */
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
androidx.activity.compose.BackHandler(enabled = enabled, onBack = onBack)
}