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
}
}
@@ -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)
}
@@ -0,0 +1,90 @@
package org.incido.compose.ui.editor
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import org.incido.domain.model.NoteAttachment
import org.incido.domain.repository.NoteRepository
/**
* Phase 1 (M4.4c) — the §6.3 file-intake seam for the editor.
*
* Everything the editor reaches outside Compose — camera capture, file
* picker, mic-permission dance, "open this attachment in another app"
* — lives behind this interface, provided per platform by
* [rememberEditorIntake]. Android's actual keeps the pre-M4 code
* (Activity result launchers, FileProvider, Toasts) verbatim; the JVM
* actual answers with AWT dialogs (file picker = `FileDialog`, the same
* mechanism M2's desktop Import/Export menu uses) and reports
* `supportsCamera = supportsVoice = false` so the editor HIDES those
* affordances rather than stubbing them (§6.5).
*
* `beginExternalActivity` is the neutral replacement for the editor's
* old `SecurityManager?` parameter: Android passes
* `{ securityManager?.beginExternalActivity() }` (auto-lock suppression
* around every round-trip that backgrounds the app), desktop passes
* null — there is no auto-lock on desktop (M3 decision).
*/
interface EditorIntake {
/** Camera capture available (Android yes, desktop no — §6.5). */
val supportsCamera: Boolean
/** Voice-note recording available (Android yes, desktop no — §6.5). */
val supportsVoice: Boolean
/** Permission-checked camera round-trip ending in `onPickedBytes`. */
fun takePhoto()
/** File picker ending in `onPickedBytes`. */
fun pickFiles()
/** Voice-mode toggle including the first-tap mic-permission ask. */
fun toggleVoiceMode()
/** Live-checked (never cached) RECORD_AUDIO state. */
fun checkMicPermission(): Boolean
/** Ask for RECORD_AUDIO; grants feed back into [toggleVoiceMode]. */
fun requestMicPermission()
/** Hand bytes to the platform's "open with" mechanism. */
fun openExternal(bytes: ByteArray, mimeType: String, displayName: String)
/**
* One-shot user nudge (the thumbnail "Loading…" hint that used to be
* a Toast on the tap path). Android actual = Toast (verbatim
* behaviour); JVM actual = no-op — a desktop window has no Toast
* surface and the hint concerns a transient lazy-load state.
*/
fun notify(msg: String)
}
/** Construction-time provider for [EditorIntake] (launchers are composables). */
@Composable
expect fun rememberEditorIntake(
onPickedBytes: suspend (bytes: ByteArray, mimeType: String, displayName: String) -> Unit,
onVoiceConvert: () -> Unit,
/** Whether the note is currently in voice mode — the mic toggle
* converts BACK without a permission ask (verbatim pre-M4 rule). */
isVoiceMode: Boolean,
beginExternalActivity: (() -> Unit)?,
): EditorIntake
/**
* The editor's voice-recorder card. Android actual renders
* `VoiceNoteSection` (MediaStore recorder, MediaPlayer); the JVM actual
* renders NOTHING (§6.5 — hidden, not stubbed: voice notes imported
* from a phone keep their audio attachment, there is just no desktop
* recorder UI).
*/
@Composable
expect fun VoiceNoteSlot(
voicePending: PendingAttachment?,
voicePendingBytes: ByteArray?,
voicePersisted: NoteAttachment?,
repository: NoteRepository?,
hasMicPermission: () -> Boolean,
onRequestPermission: () -> Unit,
onTakeRecorded: (ByteArray, String) -> Unit,
onDeleteTake: () -> Unit,
beginExternalActivity: (() -> Unit)?,
modifier: Modifier = Modifier,
)
@@ -1,14 +1,5 @@
package org.incido.compose.ui.editor
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -98,10 +89,8 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
@@ -109,15 +98,14 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.di.ioDispatcher
import org.incido.compose.di.requireAppGraph
import org.incido.compose.util.PlatformBackHandler
import org.incido.compose.util.decodeImageBytes
import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.swatchBorderColor
import org.incido.compose.ui.theme.toComposeColor
@@ -126,7 +114,6 @@ import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import java.io.File
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
@@ -147,8 +134,13 @@ fun NoteEditorScreen(
* inside an external activity we launched (file picker, camera,
* system attachment viewer). Null disables the suppression (the
* pre-0.3.4.0 behaviour).
*
* M4.4c: was `securityManager: SecurityManager?` — the Android type
* cannot be named in commonMain and the editor only ever used
* beginExternalActivity(), so the parameter became this neutral
* lambda; App.kt passes `{ securityManager?.beginExternalActivity() }`.
*/
securityManager: SecurityManager? = null,
beginExternalActivity: (() -> Unit)? = null,
viewModel: NoteEditorViewModel = viewModel(
factory = NoteEditorViewModel.factory(
graph = requireAppGraph(),
@@ -166,123 +158,19 @@ fun NoteEditorScreen(
var showDiscardDialog by rememberSaveable { mutableStateOf(false) }
val snackbarHost = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
val ctx = LocalContext.current
// 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) {
viewModel.importAttachmentBytes(
bytes = bytes,
mimeType = "image/jpeg",
displayName = "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.
securityManager?.beginExternalActivity()
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) {
viewModel.importAttachmentBytes(
bytes = bytes,
mimeType = mime,
displayName = 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) {
viewModel.convertTo(NoteType.VOICE_NOTE)
} else {
Toast.makeText(ctx, "Microphone permission denied", Toast.LENGTH_SHORT).show()
}
}
fun micPermissionGranted(): Boolean =
ContextCompat.checkSelfPermission(
ctx,
Manifest.permission.RECORD_AUDIO,
) == PackageManager.PERMISSION_GRANTED
fun toggleVoiceMode() {
if (state.type == NoteType.VOICE_NOTE) {
// Toggling back needs no mic at all — the take survives as
// an ordinary attachment.
viewModel.convertTo(NoteType.VOICE_NOTE)
return
}
if (micPermissionGranted()) {
viewModel.convertTo(NoteType.VOICE_NOTE)
} else {
micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
}
}
fun launchCamera() {
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)
}
// M4.4c: camera capture, file picking, the mic-permission dance and
// open-this-attachment-elsewhere now live behind the intake seam —
// the Android actual is the verbatim launcher code that used to sit
// here, the JVM actual answers with AWT dialogs and hides
// camera/voice (S6.5). See EditorIntake.kt.
val intake = rememberEditorIntake(
onPickedBytes = { bytes, mimeType, displayName ->
viewModel.importAttachmentBytes(bytes, mimeType, displayName)
},
onVoiceConvert = { viewModel.convertTo(NoteType.VOICE_NOTE) },
isVoiceMode = state.type == NoteType.VOICE_NOTE,
beginExternalActivity = beginExternalActivity,
)
LaunchedEffect(state.isLoading) {
if (!state.isLoading && state.existing != null) {
@@ -460,23 +348,21 @@ fun NoteEditorScreen(
val voicePending = state.pendingAttachments
.lastOrNull { it.mimeType.startsWith("audio/") }
val voicePersisted = state.attachments.lastOrNull { it.isAudio }
VoiceNoteSection(
VoiceNoteSlot(
voicePending = voicePending,
voicePendingBytes = voicePending?.let {
state.pendingAttachmentBytes[it.tempId]
},
voicePersisted = voicePersisted,
repository = repository,
hasMicPermission = { micPermissionGranted() },
onRequestPermission = {
micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
},
hasMicPermission = { intake.checkMicPermission() },
onRequestPermission = { intake.requestMicPermission() },
onTakeRecorded = viewModel::setVoiceRecording,
onDeleteTake = {
voicePending?.let { viewModel.removePendingAttachment(it.tempId) }
?: voicePersisted?.let { viewModel.deletePersistedAttachment(it.id) }
},
securityManager = securityManager,
beginExternalActivity = beginExternalActivity,
modifier = Modifier.padding(horizontal = 16.dp),
)
}
@@ -540,7 +426,7 @@ fun NoteEditorScreen(
// v0.3.4.0 hotfix: needed by the non-image tap
// handler so the system-viewer round-trip doesn't
// trigger an immediate re-lock.
securityManager = securityManager,
intake = intake,
)
}
@@ -564,31 +450,36 @@ fun NoteEditorScreen(
.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = { launchCamera() }) {
Icon(
Icons.Filled.CameraAlt,
contentDescription = "Take photo",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
// M4.4c §6.5: camera + voice affordances are HIDDEN where
// the platform has no capture stack (desktop), not stubbed.
if (intake.supportsCamera) {
IconButton(onClick = { intake.takePhoto() }) {
Icon(
Icons.Filled.CameraAlt,
contentDescription = "Take photo",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
// v0.4.2.0 — voice-note toggle, first after Photo:
// converts the note to / from voice mode (mic permission
// is requested on the first tap into the mode).
IconButton(onClick = { toggleVoiceMode() }) {
Icon(
Icons.Filled.Mic,
contentDescription = "Voice note",
tint = if (state.type == NoteType.VOICE_NOTE)
MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
if (intake.supportsVoice) {
IconButton(onClick = { intake.toggleVoiceMode() }) {
Icon(
Icons.Filled.Mic,
contentDescription = "Voice note",
tint = if (state.type == NoteType.VOICE_NOTE)
MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
IconButton(onClick = {
// 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.
securityManager?.beginExternalActivity()
filePickerLauncher.launch(arrayOf("*/*"))
// v0.3.4.0 hotfix kept: the picker round-trip's
// auto-lock suppression now happens inside
// intake.pickFiles() (Android actual).
intake.pickFiles()
}) {
Icon(
Icons.Filled.AttachFile,
@@ -700,9 +591,9 @@ private fun AttachmentStrip(
pendingOpen: (Long) -> Unit,
pendingDelete: (Long) -> Unit,
repository: org.incido.domain.repository.NoteRepository?,
/** v0.3.4.0 hotfix: forwarded to [AttachmentThumbnail] for the
* system-viewer auto-lock suppression. */
securityManager: SecurityManager?,
/** M4.4c: forwarded to [AttachmentThumbnail] — replaces the old
* SecurityManager parameter (open-external + auto-lock suppression). */
intake: EditorIntake,
) {
LazyRow(
modifier = Modifier
@@ -721,7 +612,7 @@ private fun AttachmentStrip(
// non-image taps launch a system viewer internally.
onOpenImage = { persistedOpen(persistedViewerIds[att.id] ?: ViewerAttachmentId.Persisted(att.id)) },
onRemove = { persistedDelete(att.id) },
securityManager = securityManager,
intake = intake,
)
}
items(pending, key = { it.tempId }) { p ->
@@ -733,7 +624,7 @@ private fun AttachmentStrip(
repository = repository,
onOpenImage = { pendingOpen(p.tempId) },
onRemove = { pendingDelete(p.tempId) },
securityManager = securityManager,
intake = intake,
)
}
}
@@ -755,12 +646,11 @@ private fun AttachmentThumbnail(
* into the bitmap decode path that would silently fail. */
onOpenImage: () -> Unit,
onRemove: () -> Unit,
/** v0.3.4.0 hotfix: suppress auto-lock around the external
* "open in system viewer" intent. */
securityManager: SecurityManager?,
/** M4.4c: platform intake — replaces the old SecurityManager
* parameter (open-external + auto-lock suppression + nudges). */
intake: EditorIntake,
) {
val isImage = mimeType.startsWith("image/")
val ctx = LocalContext.current
// v0.3.1.1: lazy-load bytes from DB for persisted image attachments
// so the editor strip shows a thumbnail even after the note is
@@ -774,7 +664,7 @@ private fun AttachmentThumbnail(
// handler to bail with a misleading "Loading…" Toast forever.
val lazyBytes by produceState<ByteArray?>(initialValue = null, key1 = attachmentId) {
if (pendingBytes == null && attachmentId != null && repository != null) {
value = withContext(Dispatchers.IO) {
value = withContext(ioDispatcher) {
repository.getAttachmentBytes(attachmentId)
}
}
@@ -788,11 +678,11 @@ private fun AttachmentThumbnail(
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))
// v0.3.1.2: branch on isImage — image taps open the
// in-app viewer; non-image taps (PDF / MP3 / video / etc.)
// write the bytes to a cache temp file and launch the
// system viewer via FileProvider + ACTION_VIEW. The
// hand the bytes to the platform's open-with mechanism
// (M4.4c: EditorIntake.openExternal — FileProvider +
// ACTION_VIEW on Android, Desktop.open on JVM). The
// previous unconditional viewer path silently failed for
// non-image mime types (BitmapFactory.decodeByteArray
// returns null and the viewer just shows "Loading…").
// non-image mime types.
.clickable {
if (isImage) {
onOpenImage()
@@ -802,57 +692,9 @@ private fun AttachmentThumbnail(
// Lazy load still in flight for a persisted
// attachment — nudge the user instead of
// silently doing nothing.
Toast.makeText(ctx, "Loading\u2026", Toast.LENGTH_SHORT).show()
return@clickable
}
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.
securityManager?.beginExternalActivity()
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()
intake.notify("Loading…")
} else {
intake.openExternal(bytes, mimeType, displayName)
}
}
}
@@ -861,11 +703,11 @@ private fun AttachmentThumbnail(
// Image preview OR file-type fallback.
if (isImage && effectiveBytes != null) {
val bitmap = remember(effectiveBytes.contentHashCode()) {
BitmapFactory.decodeByteArray(effectiveBytes, 0, effectiveBytes.size)
decodeImageBytes(effectiveBytes)
}
if (bitmap != null) {
Image(
bitmap = bitmap.asImageBitmap(),
bitmap = bitmap!!,
contentDescription = displayName,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
@@ -1440,49 +1282,12 @@ private fun EditorLineField(
// ---------------------------------------------------------------------
/**
* 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
}
}
/**
* Lightweight [BackHandler] wrapper to avoid pulling activity-compose
* into the editor file for a single symbol. The platform back press
* closes the editor or prompts for discard confirmation.
* Lightweight [BackHandler] wrapper — M4.4c: delegates to the
* [PlatformBackHandler] seam (activity-compose on Android, no-op on
* desktop). The platform back press closes the editor or prompts for
* discard confirmation.
*/
@Composable
private fun BackHandler(enabled: Boolean, onBack: () -> Unit) {
androidx.activity.compose.BackHandler(enabled = enabled, onBack = onBack)
PlatformBackHandler(enabled = enabled, onBack = onBack)
}
@@ -0,0 +1,15 @@
package org.incido.compose.util
import androidx.compose.runtime.Composable
/**
* Phase 1 (M4.4c) — platform back-press seam (was a private one-liner
* wrapper around `activity-compose` inside the editor file).
*
* Android actual = `androidx.activity.compose.BackHandler`, verbatim
* behaviour. The JVM actual is a no-op: a desktop window has no system
* back gesture, the editor's close button owns that path, and physical
* Esc/back-key routing is keyboard-shortcut polish on the M5 list.
*/
@Composable
expect fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit)
@@ -0,0 +1,126 @@
package org.incido.compose.ui.editor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import java.awt.Desktop
import java.io.File
import kotlinx.coroutines.CoroutineScope
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 JVM actual — desktop file intake per §6.3: AWT `FileDialog`
* (the native GTK dialog M2's Import/Export menu already proved out)
* instead of SAF, "open with" via `java.awt.Desktop` (falling back to
* `xdg-open`), and camera/voice HIDDEN (§6.5 — the editor asks
* `supportsCamera`/`supportsVoice` and does not render those buttons).
*/
@Composable
actual fun rememberEditorIntake(
onPickedBytes: suspend (bytes: ByteArray, mimeType: String, displayName: String) -> Unit,
onVoiceConvert: () -> Unit,
isVoiceMode: Boolean,
beginExternalActivity: (() -> Unit)?,
): EditorIntake {
val scope = rememberCoroutineScope()
return remember(scope) {
object : EditorIntake {
override val supportsCamera = false
override val supportsVoice = false
override fun takePhoto() = Unit // hidden: supportsCamera is false
override fun pickFiles() {
scope.launch {
val picked = withContext(Dispatchers.IO) {
val dialog = java.awt.FileDialog(null as java.awt.Frame?, "Attach file").apply {
mode = java.awt.FileDialog.LOAD
file = null // start with no preselected name
}
dialog.show()
val dir = dialog.directory ?: return@withContext null
val name = dialog.file ?: return@withContext null
val file = File(dir, name)
runCatching { file.readBytes() }.getOrNull()
?.let { it to file.name }
}
val (bytes, name) = picked ?: return@launch
onPickedBytes(bytes, guessMimeType(name), name)
}
}
override fun toggleVoiceMode() = Unit // hidden: supportsVoice is false
override fun checkMicPermission(): Boolean = false
override fun requestMicPermission() = Unit
override fun notify(msg: String) {
// No Toast surface on desktop; the lazy-load "Loading…"
// nudge is a no-op (the thumbnail resolves in ms locally).
}
override fun openExternal(bytes: ByteArray, mimeType: String, displayName: String) {
scope.launch {
withContext(Dispatchers.IO) {
runCatching {
val safeName = displayName.replace(Regex("[^A-Za-z0-9._-]"), "_")
val outbox = File(System.getProperty("java.io.tmpdir"), "incido-open-outbox")
.apply { mkdirs() }
val tmp = File(outbox, "open_${'$'}{System.currentTimeMillis()}_$safeName")
tmp.writeBytes(bytes)
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
Desktop.getDesktop().open(tmp)
} else {
ProcessBuilder("xdg-open", tmp.absolutePath).start()
}
}
}
}
}
}
}
}
/** Best-effort mime guess from the extension (the mime only labels the
* attachment row; the desktop open path dispatches on the file). */
private fun guessMimeType(name: String): String = when (name.substringAfterLast('.', "").lowercase()) {
"png" -> "image/png"
"jpg", "jpeg" -> "image/jpeg"
"gif" -> "image/gif"
"webp" -> "image/webp"
"svg" -> "image/svg+xml"
"txt", "md" -> "text/plain"
"pdf" -> "application/pdf"
"ogg", "oga" -> "audio/ogg"
"opus" -> "audio/opus"
"mp3" -> "audio/mpeg"
"m4a" -> "audio/mp4"
"wav" -> "audio/wav"
"zip" -> "application/zip"
else -> "application/octet-stream"
}
/**
* M4.4c JVM actual: the voice recorder card renders NOTHING (§6.5
* hide-don't-stub). Audio imported from a phone survives as a plain
* attachment row; there is simply no desktop recorder UI.
*/
@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,
) = Unit
@@ -0,0 +1,8 @@
package org.incido.compose.util
import androidx.compose.runtime.Composable
/** M4.4c JVM actual — no system back gesture on a desktop window; the
* editor's close button owns that path (Esc handling is M5 polish). */
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) = Unit