feat(phase-1/m4.1): :composeApp in-place → Kotlin Multiplatform (androidTarget + jvm)

Plan §6.1 step 1, the conservative shape: build converts, Android code
moves UNMODIFIED (git shows pure renames; behaviour diff = zero), and
commonMain starts with only the files that compile for both targets
today — theme Color/Type, PasswordPolicy, ReleaseNotes, LinkedShare-
Composer — behind two new expect/actual seams (justification per §9):

* platformDynamicColorScheme — Android actual keeps the pre-M4
  Build.VERSION + dynamicColorScheme branch verbatim; JVM actual
  returns null (desktop hides dynamic color, per M3's posture).
* relativeTimestamp — Android actual is DateUtils verbatim; JVM
  actual is a java.time approximation of the same format (English-
  only until M4 follow-up; desktop has no locale switch yet).

New friction found paying itself into §3/§2 (all fixed in-tree):
* kotlinMultiplatform must be registered at the ROOT with apply false
  like the other Kotlin markers — sibling modules' markers put KGP on
  the buildscript classpath and the subproject request then dies with
  the kapt-style 'already on classpath with unknown version' (§2.5).
* KMP source-set dependency handlers: platform(libs.x) returns raw
  notation, not a Dependency — use project.dependencies.platform(…);
  debugImplementation is not on the handler (moved to a project-level
  dependencies block); androidTestImplementation dropped (no tests).
* ColorScheme is androidx.compose.material3.ColorScheme, NOT
  ui.graphics — desktop ships it inside material3-desktop, no extra
  artifact needed.
* AGP 8.7.2 > KGP 2.0.21's tested max 8.5 — warning only, same as
  the kapt modules; assembleDebug green.

Deliberate deferrals (documented in the build file): :core:domain is
still kotlin("jvm") so commonMain can't see it — NoteColors moves
when domain converts (M4.2, per the Phase-0 recommendation); screens,
ViewModels and AppContainer move with the container seam (M4.3).

Verified: ./gradlew :composeApp:compileKotlinJvm + assembleDebug +
:core:data-jvm:smoke (M1a PASS) + :desktopApp:run --self-test
(SELFTEST wrote note, clean exit) + git status clean over
core/**/objectbox-models (ID model file unchanged, invariant 2).
This commit is contained in:
Incido Developer committed 2026-10-06 12:15:15 +13:00
1 parent 6b8db18cdf
commit fef8f9c2e9
43 files changed
+229 -83

No files matched your search

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,269 @@
package org.incido.compose
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.runtime.toMutableStateList
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import kotlinx.coroutines.launch
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.share.SharedIntentBuffer
import org.incido.compose.ui.drawer.IncidoDrawer
import org.incido.compose.ui.editor.NoteEditorScreen
import org.incido.compose.ui.editor.SharedImage
import org.incido.compose.ui.notelist.NoteListScreen
import org.incido.compose.ui.settings.SettingsScreen
import org.incido.compose.ui.settings.auth.PinChangeScreen
import org.incido.compose.ui.settings.auth.PinEntryScreen
import org.incido.compose.ui.settings.auth.PinSetupScreen
import org.incido.compose.ui.theme.IncidoTheme
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteFilter
import org.incido.domain.repository.NoteRepository
/** Top-level navigation destinations. */
private object Routes {
const val LIST = "list"
const val EDITOR = "editor/{noteId}"
const val SETTINGS = "settings"
const val PIN_SETUP = "pin_setup"
/** v0.3.3.0: three-step "Reset PIN" flow. */
const val PIN_CHANGE = "pin_change"
fun editor(noteId: Long?): String = "editor/${noteId ?: -1L}"
}
/** Stable serialisation for [NoteFilter] so `rememberSaveable` works. */
private fun NoteFilter.toSaveableKey(): String = key()
private fun String.toNoteFilter(): NoteFilter = when {
this == "home" -> NoteFilter.Home
this == "favorites" -> NoteFilter.Favorites
this == "untagged" -> NoteFilter.Untagged
this == "drafts" -> NoteFilter.Drafts
this == "trash" -> NoteFilter.Trash
startsWith("tag:") -> NoteFilter.ByTag(this.removePrefix("tag:"))
startsWith("color:") -> NoteColor.values()
.firstOrNull { it.name == this.removePrefix("color:") }
?.let { NoteFilter.ByColor(it) }
?: NoteFilter.Home
else -> NoteFilter.Home
}
/**
* v0.3.1.0: Holds the share-into payload (text + pre-loaded image
* bytes) so the [NoteEditorScreen] can read it on first composition.
* Cleared as soon as the editor is created.
*
* v0.3.6.0: also carries [subject] (`Intent.EXTRA_SUBJECT`) so the
* editor can put the page title on the note's first line for URL
* shares — still offline-only, no network fetch.
*/
private class ShareIntoHolder {
var text: String? = null
var images: List<SharedImage> = emptyList()
var subject: String? = null
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun IncidoApp(
repository: NoteRepository? = null,
securityManager: SecurityManager? = null,
settingsRepository: SettingsRepository? = null,
) {
val context = LocalContext.current
val app = context.applicationContext as IncidoApplication
// v0.3.2.0: prefer explicit params, fall back to the application
// container. Both hosts (`MainActivity` + tests) supply them in
// production — the fallback is just a robustness net.
val resolvedSecurity = securityManager ?: app.container.securityManager
val resolvedSettings = settingsRepository ?: app.container.settingsRepository
// v0.3.2.0: collect user settings to drive theme + the auth gate.
val settings by resolvedSettings.userSettingsFlow.collectAsStateWithLifecycle(
initialValue = org.incido.compose.data.settings.UserSettings(),
)
val lockState by resolvedSecurity.lockState.collectAsStateWithLifecycle()
IncidoTheme(
darkTheme = settings.themeMode.resolveDark(isSystemInDarkTheme()),
dynamicColor = settings.dynamicColor,
) {
// v0.3.2.0: hard lock gate. If the app is locked we render
// the PIN entry screen in place of the regular UI.
if (lockState is SecurityManager.LockState.Locked) {
PinEntryScreen()
return@IncidoTheme
}
val navController = rememberNavController()
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
var filterMode by rememberSaveable(
stateSaver = androidx.compose.runtime.saveable.Saver(
save = { it.toSaveableKey() },
restore = { it.toNoteFilter() },
),
) { mutableStateOf<NoteFilter>(NoteFilter.Home) }
// v0.3.1.0: consume any inbound share-into payload once at
// composition. The buffer is single-shot — first composition
// wins. If a payload is present, we open a fresh editor with
// the shared content pre-filled.
val shareHolder = remember { ShareIntoHolder() }
LaunchedEffect(Unit) {
val payload = SharedIntentBuffer.consume()
if (payload != null && !payload.isEmpty) {
shareHolder.text = payload.text
shareHolder.images = payload.images
shareHolder.subject = payload.subject
navController.navigate(Routes.editor(null)) {
popUpTo(Routes.LIST)
}
}
}
val currentBackStack by navController.currentBackStackEntryAsState()
val currentRoute = currentBackStack?.destination?.route?.substringBefore("/")
// Disable the drawer on the editor so back arrow / gesture do
// exactly what the user expects there.
val isListRoute = currentRoute == Routes.LIST
LaunchedEffect(currentRoute) {
// If we land on the editor via deep link without a list in
// the back stack, snap the drawer closed.
if (!isListRoute && drawerState.isOpen) drawerState.close()
}
// v0.3.2.0: forward app foreground/background transitions to
// the SecurityManager so it can re-lock when the timeout
// elapses. LifecycleEventObserver wires ON_RESUME / ON_STOP
// automatically.
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> resolvedSecurity.onAppForegrounded()
Lifecycle.Event.ON_STOP -> resolvedSecurity.onAppBackgrounded()
else -> Unit
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
ModalNavigationDrawer(
drawerState = drawerState,
gesturesEnabled = isListRoute,
drawerContent = {
IncidoDrawer(
currentFilter = filterMode,
onSelectFilter = { picked ->
filterMode = picked
scope.launch { drawerState.close() }
},
onOpenSettings = {
scope.launch { drawerState.close() }
navController.navigate(Routes.SETTINGS)
},
)
},
) {
NavHost(navController = navController, startDestination = Routes.LIST) {
composable(Routes.LIST) {
NoteListScreen(
filterMode = filterMode,
onOpenDrawer = { scope.launch { drawerState.open() } },
onOpenEditor = { id -> navController.navigate(Routes.editor(id)) },
// v0.3.1.0: thread the NoteRepository through so the
// card thumbnail composables can fetch image bytes.
repository = repository,
)
}
composable(
route = Routes.EDITOR,
arguments = listOf(
navArgument("noteId") {
type = NavType.LongType
defaultValue = -1L
},
),
) { entry ->
val raw = entry.arguments?.getLong("noteId") ?: -1L
val id = if (raw <= 0L) null else raw
// Read the share payload ONCE (consume) so back-then-reopen
// doesn't re-route us into the editor with stale data.
val sharedText = shareHolder.text.also { shareHolder.text = null }
val sharedImages = shareHolder.images.also { shareHolder.images = emptyList() }
// v0.3.6.0: also drain the page-title subject from the
// share intent so the editor can format the note
// with title on the first line.
val sharedSubject = shareHolder.subject.also { shareHolder.subject = null }
NoteEditorScreen(
noteId = id,
onClose = { navController.popBackStack() },
initialSharedText = sharedText,
initialSharedImages = sharedImages,
initialSharedSubject = sharedSubject,
repository = repository,
// v0.3.4.0 hotfix: suppress auto-lock around
// the editor's picker / camera / system-viewer
// round-trips.
securityManager = resolvedSecurity,
)
}
composable(Routes.SETTINGS) {
SettingsScreen(
onBack = { navController.popBackStack() },
onRequestPinSetup = { navController.navigate(Routes.PIN_SETUP) },
// v0.3.3.0: "Reset PIN" row navigates here.
onRequestPinChange = { navController.navigate(Routes.PIN_CHANGE) },
// v0.3.4.0 hotfix: suppress auto-lock around
// the backup export/import SAF pickers.
securityManager = resolvedSecurity,
)
}
composable(Routes.PIN_SETUP) {
PinSetupScreen(
onDone = { navController.popBackStack() },
onCancel = { navController.popBackStack() },
)
}
composable(Routes.PIN_CHANGE) {
PinChangeScreen(
onDone = { navController.popBackStack() },
onCancel = { navController.popBackStack() },
)
}
}
}
}
}
// Suppress unused-import lint for the snapshots helper that may be
// re-introduced in future filter-state extensions.
@Suppress("unused")
private fun <T> List<T>.toSnapshotStateList(): SnapshotStateList<T> = toMutableStateList<T>()
@@ -0,0 +1,34 @@
package org.incido.compose
import android.app.Application
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.di.AppContainer
/**
* Application class. Constructs the singleton [AppContainer] holding the
* ObjectBox store and the note repository.
*
* ViewModels reach the container via `(application as IncidoApplication).container`
* (see `NoteListViewModel.Factory` and `NoteEditorViewModel.factory`).
*
* v0.3.2.0 — initialises the [SecurityManager] lock state during
* `onCreate` so the first composition of the root Compose tree
* already knows whether to render `PinEntryScreen` or jump straight
* into the regular UI.
*/
class IncidoApplication : Application() {
lateinit var container: AppContainer
private set
val securityManager: SecurityManager
get() = container.securityManager
override fun onCreate() {
super.onCreate()
container = AppContainer(this)
// Decide whether to start locked based on the persisted
// security preferences. Safe here — no UI thread contention
// because we're on the main thread pre-Activity.
container.securityManager.start()
}
}
@@ -0,0 +1,103 @@
package org.incido.compose.data.backup
import android.content.Context
import android.net.Uri
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.incido.domain.repository.NoteRepository
/**
* v0.3.2.0: orchestration layer for Backup / Import / Export.
*
* Phase 1 (M2 task 1): this class is now a **thin Storage Access
* Framework shim**. It converts the [Uri]s that
* `ActivityResultContracts.CreateDocument` / `OpenDocument` hand back
* into streams and delegates everything else — format, crypto,
* snapshotting — to [BackupManager]'s former body, now the platform-
* neutral [BackupBridge] in `:core:backup`. The desktop app (M2 task 2)
* calls [BackupBridge] directly with file streams.
*
* Public API is unchanged: [SettingsViewModel] and the backup screens
* compile exactly as before.
*/
class BackupManager(
private val context: Context,
private val repository: NoteRepository,
) {
/**
* Snapshot every note in [repository] and stream it to [uri] as a
* plain JSON file. Throws on I/O failure.
*
* Returns the number of notes exported.
*/
suspend fun exportPlain(
uri: Uri,
appVersion: String,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int = withContext(Dispatchers.IO) {
BackupBridge.exportPlain(repository, openOutput(uri), appVersion, onProgress)
}
/**
* Snapshot every note and stream it to [uri] as a passphrase-
* encrypted envelope. [passphrase] is consumed (zeroed) inside
* [EncryptedBackupCodec.encrypt].
*/
suspend fun exportEncrypted(
uri: Uri,
passphrase: CharArray,
appVersion: String,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int = withContext(Dispatchers.IO) {
BackupBridge.exportEncrypted(repository, openOutput(uri), passphrase, appVersion, onProgress)
}
/**
* Read [uri] and import every note it contains. Auto-detects
* plain vs encrypted via the magic header. For encrypted files,
* [passphrase] is required (caller validates with
* [PasswordPolicy]).
*
* [skipExisting] (default true) dedupes on the bridge's
* (createdAt, updatedAt, sha256(content)) key — see
* [BackupBridge.import]. Returns what was imported vs skipped.
*/
suspend fun import(
uri: Uri,
passphrase: CharArray? = null,
skipExisting: Boolean = true,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): ImportSummary = withContext(Dispatchers.IO) {
BackupBridge.import(repository, openInput(uri), passphrase, skipExisting, onProgress)
}
/**
* Cheap metadata preview — used by the "Import from file…" flow
* to show the user how many notes / attachments they're about to
* bring in before they commit.
*
* Returns `null` if the file can't be read or the passphrase is
* wrong (so the UI can surface "wrong passphrase" cleanly).
*/
suspend fun preview(uri: Uri, passphrase: CharArray? = null): BackupPreview? =
withContext(Dispatchers.IO) {
val input: InputStream = try {
context.contentResolver.openInputStream(uri) ?: return@withContext null
} catch (_: IOException) {
return@withContext null
}
BackupBridge.preview(input, passphrase)
}
private fun openOutput(uri: Uri): OutputStream =
context.contentResolver.openOutputStream(uri, "wt")
?: throw IOException("Could not open output stream for $uri")
private fun openInput(uri: Uri): InputStream =
context.contentResolver.openInputStream(uri)
?: throw IOException("Could not open input stream for $uri")
}
@@ -0,0 +1,405 @@
package org.incido.compose.data.backup
import android.content.Context
import android.net.Uri
import java.io.ByteArrayInputStream
import java.util.zip.ZipInputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
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 org.incido.domain.repository.NoteRepository
/**
* v0.3.9.0 — imports notes from a **Carnet / QuickNote** archive.
*
* The source is a `.zip` whose top-level entries are `*.sqd` files (plus
* some metadata dirs we ignore). Each `.sqd` is *itself* a zip containing:
* * `index.html` — the note body inside `<div class="edit-zone">…</div>`
* * `metadata.json` — `creation_date`, `last_modification_date`,
* `keywords[]`, `rating`, `color`, `urls{}`, `todolists[]`
* * `data/<file>` — optional attachments (images etc). A companion
* `data/preview_` thumbnail is skipped so we don't
* import a low-res duplicate.
*
* Incido stores note bodies as **plain text**, so the rich-text HTML is
* flattened to text (block tags → newlines, entities decoded, tags stripped).
* The `.sqd` filename becomes the note's title line, which also gives
* image-only notes (no HTML body) a readable title.
*
* Import is **additive** — matching the existing backup-import behaviour:
* existing notes are preserved, every imported note gets a fresh id, and
* attachments are stored via [NoteRepository.addAttachment] (which applies
* EXIF normalisation + at-rest encryption transparently).
*
* Both archive shapes are accepted: a bundle of `*.sqd` files, or a single
* `.sqd` file picked directly (its zip entries are the note's own
* `index.html` / `metadata.json` / files under `data/`).
*/
class CarnetImporter(
private val context: Context,
private val repository: NoteRepository,
) {
private val json = Json {
ignoreUnknownKeys = true
isLenient = true
}
/**
* Read the archive at [uri] and import every Carnet note it contains.
* Returns the number of notes imported.
*/
suspend fun import(
uri: Uri,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int = withContext(Dispatchers.IO) {
val archiveBytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
?: throw java.io.IOException("Could not open input stream for $uri")
val topLevel = readZip(archiveBytes)
// The picked file is a single archive that bundles every note as a
// nested `.sqd` entry (each `.sqd` is itself a zip). Collect those.
val sqdNotes = topLevel.filter { (name, _) -> name.endsWith(".sqd", ignoreCase = true) }
.toList()
// Candidates as (title-file-name, raw-bytes). If no `.sqd` entries
// were found, the picked file is treated as a single `.sqd` (its own
// zip entries are index.html / metadata.json / data/…).
val candidates: List<Pair<String, ByteArray>> = if (sqdNotes.isNotEmpty()) {
sqdNotes
} else {
listOf((queryDisplayName(uri) ?: "Imported note.sqd") to archiveBytes)
}
// Parse phase — fault-isolated so one corrupt `.sqd` can't abort the
// rest of the archive.
val notes = candidates.mapNotNull { (name, bytes) ->
runCatching { parseSqd(name.substringAfterLast('/'), bytes) }.getOrNull()
}.filter { it.hasContent() }
// Persist phase — also per-note, so a single bad note doesn't lose the
// ones already written (the repository commits each note independently).
val total = notes.size
var imported = 0
notes.forEach { parsed ->
val ok = runCatching { persist(parsed) }.isSuccess
if (ok) imported++
onProgress(imported, total)
}
imported
}
// --- Persistence ---------------------------------------------------------
private suspend fun persist(parsed: ParsedSqd) {
val hashtags = parsed.keywords
.flatMap { raw ->
// Prefer the whole keyword as one tag; if it isn't a valid
// hashtag (Incido allows only [a-z0-9._-], 1–31 chars), split
// on whitespace/commas and keep the valid sub-tokens.
val one = Hashtag.normalise(raw)
if (Hashtag.parseOrNull(one) != null) {
listOf(one)
} else {
raw.split(Regex("[\\s,]+"))
.map { Hashtag.normalise(it) }
.filter { Hashtag.parseOrNull(it) != null }
}
}
.filter { it.isNotEmpty() }
.toSet()
val saved = repository.saveNoteWithHashtags(
note = Note(
id = 0L, // force a fresh id
content = parsed.content,
createdAt = parsed.createdAt,
updatedAt = parsed.updatedAt,
isFavorite = parsed.isFavorite,
color = parsed.color,
isTrashed = false,
type = parsed.type,
),
hashtagsToAdd = hashtags,
hashtagsToRemove = emptySet(),
)
for (att in parsed.attachments) {
repository.addAttachment(
noteId = saved.id,
bytes = att.bytes,
mimeType = sniffMimeType(att.bytes),
displayName = att.displayName,
)
}
}
// --- .sqd parsing --------------------------------------------------------
private fun parseSqd(fileName: String, sqdBytes: ByteArray): ParsedSqd {
val files = readZip(sqdBytes)
val title = fileName.substringBeforeLast('.')
.ifBlank { "Untitled" }
val html = files["index.html"]?.toString(Charsets.UTF_8).orEmpty()
val meta = files["metadata.json"]
?.let {
runCatching {
json.decodeFromString(CarnetMetadata.serializer(), it.toString(Charsets.UTF_8))
}.getOrNull()
}
?: CarnetMetadata()
val body = htmlToText(html)
// Attachments: anything under data/ that is a real file (not a dir
// entry) and not an auto-generated preview thumbnail.
val attachments = files
.filter { (name, bytes) ->
name.startsWith("data/") &&
!name.endsWith("/") &&
bytes.isNotEmpty() &&
!name.substringAfterLast('/').startsWith("preview_")
}
.map { (name, bytes) -> Attachment(name.substringAfterLast('/'), bytes) }
val type = if (meta.todolists.isNotEmpty()) NoteType.TASK_LIST else NoteType.TEXT
return ParsedSqd(
content = buildContent(title, body, meta),
createdAt = meta.creationDate.takeIf { it > 0 } ?: System.currentTimeMillis(),
updatedAt = meta.lastModificationDate.takeIf { it > 0 } ?: System.currentTimeMillis(),
isFavorite = meta.rating >= 5,
color = mapColor(meta.color),
type = type,
keywords = meta.keywords,
attachments = attachments,
)
}
/**
* Assemble the final plain-text body. The filename is used as the title
* (first non-blank line in Incido's title/body split); then the HTML
* body; then any URLs from the metadata; then any to-do lists rendered as
* GFM checkbox lines (`- [ ]` / `- [x]`) so [NoteType.TASK_LIST] renders.
*/
private fun buildContent(title: String, body: String, meta: CarnetMetadata): String {
val blocks = mutableListOf<String>()
blocks += title
if (body.isNotBlank()) blocks += body
if (meta.urls.isNotEmpty()) {
blocks += meta.urls.keys.filter { it.isNotBlank() }
}
for (todo in meta.todolists) {
val lines = buildList {
todo.done.forEach { if (it.isNotBlank()) add("- [x] ${it.trim()}") }
todo.todo.forEach { if (it.isNotBlank()) add("- [ ] ${it.trim()}") }
}
if (lines.isNotEmpty()) blocks += lines.joinToString("\n")
}
return blocks.filter { it.isNotBlank() }.joinToString("\n\n").trim()
}
// --- Helpers -------------------------------------------------------------
/** Read every file entry (name → bytes) from a zip, skipping dirs. */
private fun readZip(bytes: ByteArray): LinkedHashMap<String, ByteArray> {
val out = LinkedHashMap<String, ByteArray>()
ZipInputStream(ByteArrayInputStream(bytes)).use { zis ->
while (true) {
val entry = zis.nextEntry ?: break
if (entry.isDirectory) { zis.closeEntry(); continue }
val data = zis.readBytes()
out[entry.name] = data
zis.closeEntry()
}
}
return out
}
/** Query the user-visible name of a SAF [uri] (falls back to null). */
private fun queryDisplayName(uri: Uri): String? {
return try {
context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
val idx = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
}
} catch (_: Exception) {
null
}
}
companion object {
/** MIME type detected from magic bytes, falling back to a default. */
fun sniffMimeType(bytes: ByteArray): String {
fun b(i: Int) = if (i < bytes.size) bytes[i].toInt() and 0xFF else -1
if (b(0) == 0xFF && b(1) == 0xD8 && b(2) == 0xFF) return "image/jpeg"
if (b(0) == 0x89 && b(1) == 0x50 && b(2) == 0x4E && b(3) == 0x47) return "image/png"
if (b(0) == 0x47 && b(1) == 0x49 && b(2) == 0x46 && b(3) == 0x38) return "image/gif"
if (b(0) == 0x52 && b(1) == 0x49 && b(2) == 0x46 && b(3) == 0x46 &&
b(8) == 0x57 && b(9) == 0x45 && b(10) == 0x42 && b(11) == 0x50
) return "image/webp"
if (b(0) == 0x42 && b(1) == 0x4D) return "image/bmp"
return "application/octet-stream"
}
/** Carnet color string → Incido [NoteColor]. Unknown values → NONE. */
fun mapColor(raw: String): NoteColor = when (raw.trim().lowercase()) {
"red" -> NoteColor.RED
"green" -> NoteColor.GREEN
"blue" -> NoteColor.BLUE
"yellow", "amber" -> NoteColor.AMBER
"purple" -> NoteColor.PURPLE
else -> NoteColor.NONE
}
/**
* Flatten a Carnet `index.html` note body to plain text:
* strip comments, isolate the `.edit-zone` content, turn block
* boundaries into newlines, decode entities (incl. `&nbsp;`), then
* drop the remaining tags.
*/
fun htmlToText(html: String): String {
var s = html.replace(Regex("<!--.*?-->", RegexOption.DOT_MATCHES_ALL), " ")
// Keep only the edit-zone body (everything after its opening tag,
// up to the sibling `<div id="floating">` that follows it).
val zoneMatch = Regex("class=\"edit-zone\"[^>]*>").find(s)
if (zoneMatch != null) {
s = s.substring(zoneMatch.range.last + 1)
val floatIdx = s.indexOf("<div id=\"floating\"")
if (floatIdx >= 0) s = s.substring(0, floatIdx)
}
s = s.replace(Regex("<br\\s*/?>", RegexOption.IGNORE_CASE), "\n")
s = s.replace(Regex("</(div|p|li|ul|ol|tr|h[1-6])>", RegexOption.IGNORE_CASE), "\n")
s = s.replace(Regex("<[^>]+>"), "")
s = decodeEntities(s)
// Normalise whitespace: drop trailing spaces per line, collapse
// runs of 2+ blank lines to a single blank line.
val lines = s.replace("\r", "").split('\n').map { it.trimEnd() }
val collapsed = StringBuilder()
var blanks = 0
for (line in lines) {
if (line.isEmpty()) {
blanks++
if (blanks <= 1) collapsed.append('\n')
} else {
blanks = 0
collapsed.append(line).append('\n')
}
}
return collapsed.toString().trim()
}
/** Decode the named + numeric HTML entities a Carnet body can contain. */
private fun decodeEntities(input: String): String {
if (!input.contains('&')) return input
val sb = StringBuilder(input.length)
var i = 0
while (i < input.length) {
val c = input[i]
if (c == '&') {
val semi = input.indexOf(';', i + 1)
if (semi in (i + 1)..(i + 12)) {
val entity = input.substring(i, semi + 1)
val decoded = NAMED_ENTITIES[entity] ?: numericEntity(entity)
if (decoded != null) {
sb.append(decoded)
i = semi + 1
continue
}
}
}
sb.append(c)
i++
}
return sb.toString()
}
private fun numericEntity(entity: String): String? {
if (!entity.startsWith("&#") || !entity.endsWith(";")) return null
val body = entity.substring(2, entity.length - 1)
return try {
val code = if (body.startsWith("x") || body.startsWith("X")) {
body.substring(1).toLong(16)
} else {
body.toLong()
}
if (code in 0..0x10FFFF) String(Character.toChars(code.toInt())) else null
} catch (_: NumberFormatException) {
null
}
}
private val NAMED_ENTITIES = mapOf(
"&nbsp;" to " ",
"&amp;" to "&",
"&lt;" to "<",
"&gt;" to ">",
"&quot;" to "\"",
"&#39;" to "'",
"&apos;" to "'",
"&copy;" to "\u00A9",
"&reg;" to "\u00AE",
"&trade;" to "\u2122",
"&hellip;" to "\u2026",
"&mdash;" to "\u2014",
"&ndash;" to "\u2013",
"&rsquo;" to "\u2019",
"&lsquo;" to "\u2018",
"&rdquo;" to "\u201D",
"&ldquo;" to "\u201C",
)
}
// --- Data ----------------------------------------------------------------
/** A parsed, ready-to-persist Carnet note. */
data class ParsedSqd(
val content: String,
val createdAt: Long,
val updatedAt: Long,
val isFavorite: Boolean,
val color: NoteColor,
val type: NoteType,
val keywords: List<String>,
val attachments: List<Attachment>,
) {
fun hasContent(): Boolean = content.isNotBlank() || attachments.isNotEmpty()
}
/** A single attachment (file name + raw bytes) inside a `.sqd`'s `data/`. */
data class Attachment(val displayName: String, val bytes: ByteArray)
@Serializable
private data class CarnetMetadata(
@SerialName("creation_date") val creationDate: Long = 0,
@SerialName("last_modification_date") val lastModificationDate: Long = 0,
val keywords: List<String> = emptyList(),
val rating: Int = -1,
val color: String = "none",
val urls: Map<String, JsonElement> = emptyMap(),
val todolists: List<CarnetTodo> = emptyList(),
)
@Serializable
private data class CarnetTodo(
val id: String = "",
val todo: List<String> = emptyList(),
val done: List<String> = emptyList(),
)
}
@@ -0,0 +1,63 @@
package org.incido.compose.data.backup
import org.incido.compose.data.settings.PasswordPolicy
import java.security.SecureRandom
/**
* v0.3.2.0: SecureRandom-based passphrase generator for encrypted
* backups.
*
* The output is guaranteed to satisfy [PasswordPolicy]:
* - length in [MIN, MAX]
* - at least one digit
* - at least one special character
*
* If a freshly-generated passphrase fails validation (rare — only if
* the random draw happens to miss both a digit and a special) we
* regenerate, so the return type is non-nullable.
*/
object PassphraseGenerator {
private const val DEFAULT_LENGTH = 20
/**
* Pool of characters the generator picks from. Carefully built so
* every character is ASCII-printable, no whitespace, no ambiguous
* glyphs (we exclude `0`, `O`, `1`, `l`, `I` to keep the value
* copy-paste friendly).
*/
private val ALPHABET = (
"abcdefghijkmnopqrstuvwxyz" + // no 'l'
"ABCDEFGHJKLMNPQRSTUVWXYZ" + // no 'I', 'O'
"23456789" + // no '0', '1'
PasswordPolicy.SPECIAL_CHARS
).toCharArray()
private val secureRandom = SecureRandom()
/**
* Generate a passphrase of [length] characters (clamped to the
* policy's [PasswordPolicy.MIN_LENGTH] / [PasswordPolicy.MAX_LENGTH]
* bounds). The result is guaranteed to satisfy the policy.
*/
fun generate(length: Int = DEFAULT_LENGTH): String {
val clamped = length.coerceIn(PasswordPolicy.MIN_LENGTH, PasswordPolicy.MAX_LENGTH)
repeat(MAX_ATTEMPTS) {
val candidate = buildRandom(clamped)
if (PasswordPolicy.validate(candidate).isValid) return candidate
}
// Statistically unreachable — the alphabet guarantees a digit
// and a special in any draw of >= 12 chars. Fall back to a
// hand-crafted compliant value so we never throw from a UI
// button tap.
return "IncidoBackup!" + secureRandom.nextInt(10_000).toString().padStart(4, '0')
}
private fun buildRandom(length: Int): String {
val out = StringBuilder(length)
repeat(length) { out.append(ALPHABET[secureRandom.nextInt(ALPHABET.size)]) }
return out.toString()
}
private const val MAX_ATTEMPTS = 16
}
@@ -0,0 +1,282 @@
package org.incido.compose.data.security
import android.content.Context
import android.net.Uri
import android.util.Base64
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import android.security.keystore.KeyProperties
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import org.incido.compose.data.backup.EncryptedKeyCodec
/**
* v0.3.2.0: generates, wraps, and unwraps the 32-byte key used to
* encrypt the ObjectBox database at rest.
*
* The key itself lives in the **Android Keystore** (AES-256-GCM,
* `setUserAuthenticationRequired(false)` — the PIN/biometric prompt
* is what gates UI access; the key is freely usable by the app
* process once it exists). The Keystore wraps the key; the wrapped
* ciphertext + IV are persisted to DataStore Preferences so they
* survive app restarts. Each call to [getOrCreateKey] unwraps it.
*
* Wrapping flow:
* 1. Generate a 32-byte random BoxStore key (`SecureRandom`).
* 2. Generate / load the Keystore-resident master key.
* 3. Encrypt the BoxStore key with the master key (AES-256-GCM).
* 4. Persist `iv | ciphertext` (Base64) in DataStore.
*
* Unwrapping flow:
* 1. Load the persisted ciphertext blob from DataStore.
* 2. Decrypt with the Keystore master key.
* 3. Return the 32-byte BoxStore key.
*/
class ObjectBoxKeyProvider(private val context: Context) {
/**
* Return the 32-byte ObjectBox encryption key, generating + storing
* one if this is the first call. Idempotent.
*
* Blocking — safe to call from `Application.onCreate` (the IO is
* tiny: a single Keystore unwrap + a DataStore read).
*/
fun getOrCreateKey(): ByteArray = runBlocking {
val existing = readPersistedKey()
if (existing != null) return@runBlocking existing
val fresh = generateRandomKey(KEY_BYTES)
val (iv, cipherText) = wrap(fresh)
persistWrapped(iv, cipherText)
fresh
}
/**
* Permanently delete the encryption key from DataStore. Used when
* the user disables encryption or disables security altogether —
* subsequent app launches will open ObjectBox unencrypted.
*/
suspend fun deleteKey() {
context.keyDataStore.edit { it.remove(KEY_WRAPPED) }
}
/** True when a wrapped key has been persisted (i.e. encryption is configured). */
suspend fun hasKey(): Boolean = readPersistedKey() != null
/**
* Blocking variant of [hasKey] for use at `Application.onCreate`
* (AppContainer needs the answer synchronously before constructing
* the repository). Cheap: one DataStore read + one Keystore unwrap.
*/
fun hasKeyBlocking(): Boolean = runBlocking { hasKey() }
// ---- v0.3.6.0 recovery-key export / import ----
/**
* Thrown by [exportRecoveryKey] / [importRecoveryKey] when the
* underlying envelope codec rejects the payload (wrong magic,
* truncated file, GCM tag mismatch = bad passphrase).
*/
class RecoveryKeyException(message: String, cause: Throwable? = null) :
java.io.IOException(message, cause)
/**
* Write the current 32-byte field key to [outputUri], wrapped with
* [passphrase]. The destination is user-chosen via SAF — caller
* should pre-suppress auto-lock via `beginExternalActivity()`
* because the SAF picker backgrounds the app.
*
* Throws [RecoveryKeyException] (wrapping the cause) on any I/O
* failure, and `IllegalStateException` if there's no key to back
* up (caller should disable the export row until encryption is on).
*/
suspend fun exportRecoveryKey(outputUri: Uri, passphrase: CharArray) {
val raw = getOrCreateKey()
try {
val envelope = EncryptedKeyCodec.encrypt(raw, passphrase)
context.contentResolver.openOutputStream(outputUri, "w")?.use { stream ->
stream.write(envelope)
stream.flush()
} ?: throw RecoveryKeyException("Couldn't open output stream for $outputUri")
} catch (e: java.io.IOException) {
throw RecoveryKeyException("Failed to write recovery key: ${e.message}", e)
} finally {
// getOrCreateKey returns the cached unwrapped key bytes — clear them.
raw.fill(0)
passphrase.fill('0')
}
}
/**
* Read a recovery envelope from [inputUri], unwrap it with
* [passphrase], and install it as the current field key
* (overwriting any previously-persisted key).
*
* The 32 unwrapped bytes are self-verified by a roundtrip through
* [AesGcmFieldCipher] before the new wrapped blob is persisted, so
* a tampered or wrong-length payload never lands on disk.
*
* The caller is responsible for swapping the [CipherHolder.cipher]
* slot afterwards — [ObjectBoxKeyProvider] deliberately stays
* unaware of the holder to keep the dependency direction
* one-way. See [org.incido.compose.ui.settings.SettingsViewModel]
* for the install + refresh sequence.
*
* @return `true` if a brand-new key was installed (an existing key
* was overwritten), `false` if there was no previous key
* (this was the first install).
*/
suspend fun importRecoveryKey(inputUri: Uri, passphrase: CharArray): Boolean {
val payload: ByteArray = try {
context.contentResolver.openInputStream(inputUri)?.use { it.readBytes() }
?: throw RecoveryKeyException("Couldn't open input stream for $inputUri")
} catch (e: java.io.IOException) {
throw RecoveryKeyException("Failed to read recovery key: ${e.message}", e)
}
val raw = try {
EncryptedKeyCodec.decrypt(payload, passphrase)
} catch (e: IllegalArgumentException) {
// Wrong magic / wrong size / truncated file.
throw RecoveryKeyException("Not a valid Incido recovery key file.", e)
} catch (e: java.security.GeneralSecurityException) {
// AEADBadTagException — bad passphrase.
throw RecoveryKeyException("Incorrect passphrase.", e)
} finally {
payload.fill(0)
passphrase.fill('0')
}
try {
return installKey(raw)
} finally {
raw.fill(0)
}
}
/**
* Wrap [rawKey] (must be exactly [KEY_BYTES]) with the Keystore
* master key, overwrite the persisted blob, and self-verify with a
* roundtrip through [AesGcmFieldCipher].
*
* @return `true` if an existing key was overwritten, `false` if
* this is the first install.
*/
suspend fun installKey(rawKey: ByteArray): Boolean {
require(rawKey.size == KEY_BYTES) {
"Key must be $KEY_BYTES bytes (got ${rawKey.size})"
}
val hadExisting = hasKey()
// Self-verify BEFORE we touch the persisted blob — if the
// cipher roundtrip fails we want to leave the existing key
// alone. We need a transient Keystore wrap to exercise the
// install path; that's effectively what persistWrapped does.
val (iv, cipherText) = wrap(rawKey.copyOf())
// Round-trip through unwrap to prove the cipher actually
// round-trips with these bytes (catches things like passing a
// garbage buffer that happens to be 32 bytes long).
val verified = runCatching { unwrap(iv, cipherText) }.getOrNull()
if (verified == null || !verified.contentEquals(rawKey)) {
throw RecoveryKeyException("Key self-verification failed.")
}
verified.fill(0)
persistWrapped(iv, cipherText)
return hadExisting
}
// ---- internals ----
private suspend fun readPersistedKey(): ByteArray? {
val blob: String? = context.keyDataStore.data
.map { it[KEY_WRAPPED] }
.first()
if (blob.isNullOrEmpty()) return null
val raw = runCatching { Base64.decode(blob, Base64.NO_WRAP) }.getOrNull()
?: return null
// Layout: [12-byte IV][ciphertext + 16-byte tag]
if (raw.size <= IV_BYTES + GCM_TAG_BYTES) return null
val iv = raw.copyOfRange(0, IV_BYTES)
val cipherText = raw.copyOfRange(IV_BYTES, raw.size)
return runCatching { unwrap(iv, cipherText) }.getOrNull()
}
private suspend fun persistWrapped(iv: ByteArray, cipherText: ByteArray) {
val combined = iv + cipherText
val encoded = Base64.encodeToString(combined, Base64.NO_WRAP)
context.keyDataStore.edit { it[KEY_WRAPPED] = encoded }
}
private fun wrap(plaintext: ByteArray): Pair<ByteArray, ByteArray> {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, masterKey())
val iv = cipher.iv.copyOf(IV_BYTES) // GCM IV is exactly 12 bytes
val cipherText = cipher.doFinal(plaintext)
return iv to cipherText
}
private fun unwrap(iv: ByteArray, cipherText: ByteArray): ByteArray {
val cipher = Cipher.getInstance(TRANSFORMATION)
val spec = GCMParameterSpec(GCM_TAG_BYTES * 8, iv)
cipher.init(Cipher.DECRYPT_MODE, masterKey(), spec)
return cipher.doFinal(cipherText)
}
/** Lazy / cached access to the Keystore master key. */
private fun masterKey(): SecretKey = cachedMasterKey
?: synchronized(this) {
cachedMasterKey ?: loadOrCreateMasterKey().also { cachedMasterKey = it }
}
@Synchronized
private fun loadOrCreateMasterKey(): SecretKey {
val ks = java.security.KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
val existing: SecretKey? = ks.getKey(MASTER_KEY_ALIAS, null) as? SecretKey
if (existing != null) return existing
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
val spec = android.security.keystore.KeyGenParameterSpec.Builder(
MASTER_KEY_ALIAS,
android.security.keystore.KeyProperties.PURPOSE_ENCRYPT or
android.security.keystore.KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(android.security.keystore.KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(android.security.keystore.KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(KEY_SIZE_BITS)
// PIN/biometric gate the UI; the BoxStore key itself is free to use.
.setUserAuthenticationRequired(false)
.build()
generator.init(spec)
return generator.generateKey()
}
private fun generateRandomKey(sizeBytes: Int): ByteArray {
val out = ByteArray(sizeBytes)
SecureRandom().nextBytes(out)
return out
}
companion object {
private const val KEY_BYTES = 32 // 256-bit ObjectBox key
private const val KEY_SIZE_BITS = 256 // matches KEY_BYTES
private const val IV_BYTES = 12 // GCM IV
private const val GCM_TAG_BYTES = 16 // GCM auth tag
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val ANDROID_KEYSTORE = "AndroidKeyStore"
private const val MASTER_KEY_ALIAS = "incido_objectbox_master"
@Volatile
private var cachedMasterKey: SecretKey? = null
private val KEY_WRAPPED = stringPreferencesKey("objectbox_wrapped_key")
}
}
/** Dedicated DataStore for the wrapped key blob. Separate from
* `SettingsRepository` so we don't tangle raw key material into the
* same Preferences file as the user-facing toggles. */
private val Context.keyDataStore: androidx.datastore.core.DataStore<androidx.datastore.preferences.core.Preferences>
by preferencesDataStore(name = "incido_security_keys")
@@ -0,0 +1,74 @@
package org.incido.compose.data.security
import android.util.Base64
import java.security.SecureRandom
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
/**
* v0.3.2.0: PBKDF2-HMAC-SHA256 PIN hashing.
*
* - 100,000 iterations (OWASP 2023 recommendation for PBKDF2-SHA256)
* - 256-bit (32-byte) derived key
* - Per-install random 16-byte salt (regenerated only when the user
* changes their PIN)
*
* The hash output is stored Base64-encoded in [SettingsRepository]
* via the `SecurityManager`. The salt is stored alongside it. The
* cleartext PIN is **never** persisted.
*/
object PinHasher {
private const val ITERATIONS = 100_000
private const val KEY_LENGTH_BITS = 256
private const val SALT_BYTES = 16
private const val PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA256"
private val secureRandom = SecureRandom()
/** Generate a fresh random salt for a new PIN. */
fun newSalt(): ByteArray {
val salt = ByteArray(SALT_BYTES)
secureRandom.nextBytes(salt)
return salt
}
/**
* Hash [pin] with [salt]. Returns a 32-byte derived key.
*
* Throws on PBKDF2 mis-configuration (impossible on Android — the
* algorithm is in the platform's default provider list).
*/
fun hash(pin: CharArray, salt: ByteArray): ByteArray {
require(pin.isNotEmpty()) { "PIN must not be empty" }
require(salt.size == SALT_BYTES) { "Salt must be $SALT_BYTES bytes" }
val spec = PBEKeySpec(pin, salt, ITERATIONS, KEY_LENGTH_BITS)
try {
val factory = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM)
return factory.generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
}
/**
* Constant-time comparison of two byte arrays. Returns true if both
* have the same length and identical contents.
*
* Use this when verifying a PIN to avoid leaking length-mismatches
* via timing.
*/
fun constantTimeEquals(a: ByteArray, b: ByteArray): Boolean {
if (a.size != b.size) return false
var diff = 0
for (i in a.indices) {
diff = diff or (a[i].toInt() xor b[i].toInt())
}
return diff == 0
}
/** Base64 (no-wrap) helpers for storing the hash + salt in DataStore. */
fun encode(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)
fun decode(text: String): ByteArray = Base64.decode(text, Base64.NO_WRAP)
}
@@ -0,0 +1,312 @@
package org.incido.compose.data.security
import android.content.Context
import androidx.biometric.BiometricManager
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.fragment.app.FragmentActivity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.incido.compose.data.settings.SettingsRepository
/**
* v0.3.2.0: App-lock state machine + PIN / biometric orchestration.
*
* Owns:
* - The current [LockState] (Unlocked / Locked(reason)).
* - The PIN hash + salt (persisted in DataStore Preferences).
* - The biometric-availability flag.
*
* Drives the UI gate: when [lockState] is `Locked`, `IncidoApp` hides
* the regular UI and shows `PinEntryScreen` instead.
*
* Lifecycle:
* - `MainActivity.onCreate` → `start()` (initial lock decision).
* - `MainActivity.onStop` → `onAppBackgrounded()` (records timestamp).
* - App root on `ON_RESUME` → `onAppForegrounded()` (checks timeout,
* transitions to `Locked` if needed). Cold launch is always locked.
*
* v0.3.3.0: lock mode is now a mutually-exclusive choice between PIN
* and device biometric. The gate flips when *either* is active (see
* [org.incido.compose.data.settings.UserSettings.isLockActive]).
*/
class SecurityManager(
private val context: Context,
private val settings: SettingsRepository,
) {
private val _lockState = MutableStateFlow<LockState>(LockState.Locked(LockReason.ColdLaunch))
val lockState: StateFlow<LockState> = _lockState.asStateFlow()
/** Timestamp (System.currentTimeMillis) when the app was last
* backgrounded. Null while the app is in the foreground. */
@Volatile
private var backgroundedAt: Long? = null
/**
* v0.3.4.0 hotfix: true while the user is inside an external
* activity WE launched (SAF file picker, camera, system viewer).
* The app legitimately backgrounds/foregrounds during those
* round-trips, which must NOT count as "leaving the app" for
* auto-lock purposes — otherwise Auto-Lock = Immediate locks the
* screen the moment the picker returns, tearing down the NavHost
* (and the unsaved editor state) from under the result callback.
*
* Set by [beginExternalActivity] just before launching; consumed
* exactly once by [onAppForegrounded]. Cold launch is unaffected —
* a fresh process always starts with the flag false.
*/
@Volatile
private var externalActivityInFlight: Boolean = false
/**
* Decide the initial lock state at app launch. Called from
* [org.incido.compose.IncidoApplication.onCreate]. Reads the
* security preferences synchronously so we know immediately
* whether to render the lock screen or jump straight into the app.
*/
fun start() {
val s = settings.snapshot()
// v0.3.3.0: gate on the general "any lock active" flag, not
// just "PIN lock active" — biometric-only is also a lock.
if (!s.isLockActive) {
// No lock configured (master off, or neither PIN nor
// biometric enabled) — never lock.
_lockState.value = LockState.Unlocked
return
}
// Lock configured (PIN or biometric) → always locked at cold
// launch.
_lockState.value = LockState.Locked(LockReason.ColdLaunch)
}
/** Called from `MainActivity.onStop`. */
fun onAppBackgrounded() {
if (_lockState.value is LockState.Unlocked) {
backgroundedAt = System.currentTimeMillis()
}
}
/**
* v0.3.4.0 hotfix: call immediately before launching an activity
* that takes the user OUT of Incido but is part of an in-app flow
* (file picker, camera capture, system viewer for an attachment).
* Suppresses the auto-lock that would otherwise fire on return —
* see [externalActivityInFlight].
*/
fun beginExternalActivity() {
externalActivityInFlight = true
}
/** Called from the root Compose tree on `ON_RESUME`. */
fun onAppForegrounded() {
val s = settings.snapshot()
// v0.3.3.0: same broadened gate as [start] — any lock mode
// (PIN or biometric) re-locks after the timeout.
if (!s.isLockActive) {
_lockState.value = LockState.Unlocked
externalActivityInFlight = false
return
}
// v0.3.4.0 hotfix: returning from an external activity WE
// launched (picker / camera / system viewer) never re-locks,
// regardless of the auto-lock timeout. Consume the flag so
// subsequent genuine background/foreground cycles lock as
// configured.
if (externalActivityInFlight) {
externalActivityInFlight = false
backgroundedAt = null
return
}
val bg = backgroundedAt ?: return // already in foreground
backgroundedAt = null
val elapsed = System.currentTimeMillis() - bg
if (elapsed >= s.autoLockTimeout.millis) {
_lockState.value = LockState.Locked(LockReason.BackgroundTimeout)
}
}
/**
* First-time PIN setup. Writes the hash + salt to DataStore and
* flips `pinEnabled`. Caller should walk the user through a
* confirm-PIN step before calling.
*
* Throws if a PIN is already set — call [changePin] instead.
*/
suspend fun setupPin(pin: CharArray) {
check(!hasPin()) { "PIN already set — use changePin to rotate" }
val salt = PinHasher.newSalt()
val hash = PinHasher.hash(pin, salt)
context.pinDataStore.edit {
it[KEY_PIN_SALT] = PinHasher.encode(salt)
it[KEY_PIN_HASH] = PinHasher.encode(hash)
}
settings.setPinEnabled(true)
pin.fill('0')
}
/** Replace the existing PIN (requires the old PIN to verify). */
suspend fun changePin(oldPin: CharArray, newPin: CharArray) {
check(verifyPin(oldPin)) { "Old PIN is incorrect" }
oldPin.fill('0')
val salt = PinHasher.newSalt()
val hash = PinHasher.hash(newPin, salt)
context.pinDataStore.edit {
it[KEY_PIN_SALT] = PinHasher.encode(salt)
it[KEY_PIN_HASH] = PinHasher.encode(hash)
}
newPin.fill('0')
}
/**
* Check [pin] against the stored hash. Constant-time compare to
* avoid leaking length-mismatches. Returns false if no PIN is set.
*/
suspend fun verifyPin(pin: CharArray): Boolean {
val prefs = context.pinDataStore.data.first()
val saltB64 = prefs[KEY_PIN_SALT] ?: return false
val hashB64 = prefs[KEY_PIN_HASH] ?: return false
val salt = runCatching { PinHasher.decode(saltB64) }.getOrNull() ?: return false
val expected = runCatching { PinHasher.decode(hashB64) }.getOrNull() ?: return false
val actual = PinHasher.hash(pin, salt)
val ok = PinHasher.constantTimeEquals(expected, actual)
pin.fill('0')
// Zero out the just-hashed PIN to keep memory tidy.
actual.fill(0)
return ok
}
/** True when a PIN hash + salt have been persisted. */
suspend fun hasPin(): Boolean {
val prefs = context.pinDataStore.data.first()
return prefs[KEY_PIN_HASH] != null && prefs[KEY_PIN_SALT] != null
}
/**
* Clear the stored PIN (used when the user disables security or
* switches to biometric). Does NOT delete the ObjectBox key —
* the encryption sub-toggle is independent.
*/
suspend fun clearPin() {
context.pinDataStore.edit {
it.remove(KEY_PIN_SALT)
it.remove(KEY_PIN_HASH)
}
settings.setPinEnabled(false)
}
/**
* Try to authenticate via device biometric. Requires a
* [FragmentActivity] (so [androidx.biometric.BiometricPrompt] can
* attach). Invokes [onResult] with `true` on success, `false` on
* any failure (cancellation, no enrolment, hardware error). The
* callback is always delivered on the main thread.
*
* The PIN fallback is the existing [verifyPin] path — this method
* only handles the "use fingerprint / face" button.
*
* v0.3.3.0: also the **only** unlock path when the user chose
* biometric-only lock mode (no Incido PIN stored). DEVICE_CREDENTIAL
* is kept as a fallback inside the prompt so the user's device PIN
* / pattern / password is a graceful fallback when biometric is
* unavailable or fails.
*
* v0.3.3.2 (hotfix): the result is delivered via [onResult] instead
* of being spun on. The previous implementation busy-waited on the
* main thread while the prompt's callbacks were also posted to the
* main executor, so the callbacks could never fire and the app
* never unlocked (ANR). Authentication is inherently asynchronous;
* callers must handle the result in the callback.
*/
fun authenticateWithBiometric(
activity: FragmentActivity,
onResult: (Boolean) -> Unit,
) {
val manager = BiometricManager.from(activity)
val canAuth = manager.canAuthenticate(
BiometricManager.Authenticators.BIOMETRIC_WEAK or
BiometricManager.Authenticators.DEVICE_CREDENTIAL,
)
if (canAuth != BiometricManager.BIOMETRIC_SUCCESS) {
onResult(false)
return
}
// Callbacks are posted on the main executor, so [onResult] runs
// on the main thread — safe for Compose state mutations.
val executor = androidx.core.content.ContextCompat.getMainExecutor(activity)
val prompt = androidx.biometric.BiometricPrompt(
activity,
executor,
object : androidx.biometric.BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: androidx.biometric.BiometricPrompt.AuthenticationResult) {
onResult(true)
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
onResult(false)
}
override fun onAuthenticationFailed() {
// Keep the prompt open; user can retry. No result yet.
}
},
)
val info = androidx.biometric.BiometricPrompt.PromptInfo.Builder()
.setTitle("Unlock Incido")
.setSubtitle("Authenticate to access your notes")
.setAllowedAuthenticators(
BiometricManager.Authenticators.BIOMETRIC_WEAK or
BiometricManager.Authenticators.DEVICE_CREDENTIAL,
)
.build()
prompt.authenticate(info)
}
/** True if the device can perform biometric auth (fingerprint / face). */
fun isBiometricAvailable(): Boolean = runCatching {
val mgr = BiometricManager.from(context)
mgr.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) ==
BiometricManager.BIOMETRIC_SUCCESS
}.getOrDefault(false)
/**
* Called when the user has successfully authenticated. Transitions
* the lock state to [LockState.Unlocked]. The UI gate's collector
* reacts and renders the normal app.
*/
fun onUnlocked() {
_lockState.value = LockState.Unlocked
backgroundedAt = null
}
/**
* One-shot accessor used at startup to determine whether a PIN
* was previously configured. Reads DataStore synchronously —
* safe at Application.onCreate.
*/
fun hasPinBlocking(): Boolean = runBlocking {
hasPin()
}
/** The state machine exposed to the UI. */
sealed class LockState {
object Unlocked : LockState()
data class Locked(val reason: LockReason) : LockState()
}
enum class LockReason { ColdLaunch, BackgroundTimeout, Manual }
companion object {
private val KEY_PIN_HASH = stringPreferencesKey("pin_hash_b64")
private val KEY_PIN_SALT = stringPreferencesKey("pin_salt_b64")
}
}
/** Dedicated DataStore for PIN credentials. Separate from
* `SettingsRepository` so the credential bytes never sit in the
* same Preferences file as the toggles. */
private val Context.pinDataStore: androidx.datastore.core.DataStore<androidx.datastore.preferences.core.Preferences>
by preferencesDataStore(name = "incido_pin")
@@ -0,0 +1,22 @@
package org.incido.compose.data.settings
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
/**
* Phase 1 (M3 task 1): the Android half of the settings seam.
*
* v0.3.2.0: Application-wide DataStore Preferences instance. Declared
* as a Context extension property so the same backing file is shared
* by every call site. Backed by `incido_settings.preferences_pb` in
* the app's `noBackupFiles` directory.
*
* Lives on the Android side now that [SettingsRepository] is platform
* neutral (it takes an injected DataStore); the desktop build creates the
* same-format store from a file path instead of a Context.
*/
val Context.settingsDataStore: DataStore<Preferences> by preferencesDataStore(
name = "incido_settings",
)
@@ -0,0 +1,110 @@
package org.incido.compose.di
import android.content.Context
import io.objectbox.BoxStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import org.incido.data.AndroidImageOrientationNormalizer
import org.incido.data.ObjectBoxStore
import org.incido.data.crypto.AesGcmFieldCipher
import org.incido.data.crypto.CipherHolder
import org.incido.data.crypto.EncryptionVerifier
import org.incido.data.crypto.NoteCryptoService
import org.incido.data.repository.NoteRepositoryImpl
import org.incido.domain.repository.NoteRepository
import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.backup.CarnetImporter
import org.incido.compose.data.security.ObjectBoxKeyProvider
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.data.settings.settingsDataStore
/**
* Hand-rolled DI container. Replaces Hilt/Dagger for v0.1 — keeps the
* build simple. Constructed once from `Application.onCreate()` and
* stored as a singleton (see `IncidoApp` in the `:app` module).
*
* v0.3.2.0 — adds:
* - [SettingsRepository] (DataStore-backed user preferences)
* - [ObjectBoxKeyProvider] (Keystore-backed at-rest encryption key)
* - [SecurityManager] (PIN / biometric / app-lock state)
* - [BackupManager] (JSON + encrypted backup import / export)
*
* v0.3.5.0 — real at-rest encryption. The constructor reads the
* security preferences synchronously; when `securityEnabled &&
* encryptionEnabled` it installs an [AesGcmFieldCipher] into the
* shared [cipherHolder] so every repository read/write encrypts or
* decrypts note content + attachment bytes in place. The ObjectBox
* store file itself is still opened unencrypted (OSS ObjectBox has no
* page-level encryption) — the field-level layer IS the encryption.
* After startup the [encryptionVerifier] re-checks every encrypted row
* by trial-decrypting it; only rows that pass earn the "Encrypted"
* badge on the note cards.
*/
class AppContainer(context: Context) {
private val appContext: Context = context.applicationContext
/** Process-wide scope for fire-and-forget background work
* (verification sweeps, etc.). SupervisorJob isolates failures. */
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
// Phase 1 (M3 task 1): the store is injected — SettingsRepository moved
// to :core:settings so the desktop build can share it. Android supplies
// the Context-backed `incido_settings.preferences_pb` store here.
val settingsRepository: SettingsRepository =
SettingsRepository(appContext.settingsDataStore)
val objectBoxKeyProvider: ObjectBoxKeyProvider = ObjectBoxKeyProvider(appContext)
val securityManager: SecurityManager =
SecurityManager(appContext, settingsRepository)
/** Shared cipher slot consulted by the repository on every I/O. */
val cipherHolder = CipherHolder()
val boxStore: BoxStore = run {
ObjectBoxStore.init(appContext, encryptionKey = null)
}
/**
* v0.3.5.0: install the field cipher BEFORE the repository is
* constructed, so the very first snapshot already reads encrypted
* rows correctly. Key unwrap is a single Keystore operation — safe
* to do synchronously at Application.onCreate.
*/
init {
val s = settingsRepository.snapshot()
if (s.isEncryptionActive && objectBoxKeyProvider.hasKeyBlocking()) {
// M3 task 2 seam: the cipher only needs the key bytes; the
// Keystore-wrapped provider is passed as a plain function.
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
}
}
val noteRepository: NoteRepository = NoteRepositoryImpl(
boxStore,
cipherHolder,
// Phase 1 (M1a) platform seam: EXIF rotation needs a bitmap decoder,
// which Android owns and the desktop build has yet to grow.
AndroidImageOrientationNormalizer(),
)
val backupManager: BackupManager = BackupManager(appContext, noteRepository)
/** v0.3.9.0 — Carnet / QuickNote `.sqd` archive importer. */
val carnetImporter: CarnetImporter = CarnetImporter(appContext, noteRepository)
/** Migration sweep + startup integrity checker for the note store. */
val noteCryptoService = NoteCryptoService(boxStore, cipherHolder)
/** Runs on every app open — feeds the verified-encryption badge. */
val encryptionVerifier = EncryptionVerifier(noteCryptoService, appScope)
/** Kick the startup verification off immediately. */
init {
encryptionVerifier.checkNow()
}
}
@@ -0,0 +1,56 @@
package org.incido.compose.share
import org.incido.compose.ui.editor.SharedImage
/**
* v0.3.1.0 — Process-singleton handoff between [MainActivity] (which
* reads the inbound [android.content.Intent.ACTION_SEND] /
* ACTION_SEND_MULTIPLE] and decodes the bytes) and the Compose tree
* (which reads the bytes once via [consume] when [IncidoApp] is first
* composed and routes them into the new-note editor).
*
* The alternative — passing everything through Intent extras or a
* Navigation back-stack arg — doesn't work cleanly for image bytes
* (too large) or for a multi-image SEND_MULTIPLE payload. We copy the
* bytes into memory once at MainActivity.onCreate, leave them here
* for the Compose layer to pick up, and clear them after consumption.
*/
object SharedIntentBuffer {
/** What the activity just saw on its incoming intent. */
data class Payload(
val text: String?,
val images: List<SharedImage>,
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the inbound share. Most
* browsers (Chrome, Firefox, Brave, Samsung Internet, …) fill
* this with the page title when the user shares a URL. The
* editor uses [org.incido.compose.share.LinkedShareComposer]
* to format this as the note title (first line) without ever
* making a network call. Null for image-only shares.
*/
val subject: String? = null,
) {
val isEmpty: Boolean
get() = text.isNullOrBlank() && subject.isNullOrBlank() && images.isEmpty()
}
@Volatile
private var pending: Payload? = null
/** Set by [MainActivity.onCreate] / [MainActivity.onNewIntent]. */
fun put(payload: Payload) {
pending = payload
}
/**
* Read the pending payload once. Subsequent calls return `null`
* until something is [put] again, so the same payload doesn't get
* routed into the editor twice across configuration changes.
*/
fun consume(): Payload? {
val value = pending
pending = null
return value
}
}
@@ -0,0 +1,42 @@
package org.incido.compose.ui.drawer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import org.incido.compose.IncidoApplication
import org.incido.domain.model.HashtagUsage
import org.incido.domain.repository.NoteRepository
/**
* Tiny ViewModel the navigation drawer uses to source its "Recent
* tags" list. Kept separate from [NoteListViewModel] because the
* drawer may render even before the list screen is created (and
* vice-versa).
*/
class DrawerViewModel(
repository: NoteRepository,
) : ViewModel() {
val recentHashtags: StateFlow<List<HashtagUsage>> =
repository.observeHashtagsByRecentUse()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = emptyList(),
)
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
DrawerViewModel(app.container.noteRepository)
}
}
}
}
@@ -0,0 +1,254 @@
package org.incido.compose.ui.drawer
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.LabelOff
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Drafts
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Tag
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.toComposeColor
import org.incido.domain.model.HashtagUsage
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteFilter
/**
* Left-side navigation drawer. Top section has the fixed entries
* (Home / Favorites / the colour-swatch strip / Drafts / Untagged /
* Trash / Settings); a `HorizontalDivider`; then
* a live scrollable list of the user's most-recently-used hashtags.
*
* Tapping a filter entry calls [onSelectFilter]; tapping Settings
* calls [onOpenSettings]. The caller (root) is responsible for closing
* the drawer.
*
* v0.3.2.0 — Settings is a new entry directly underneath "Untagged"
* with its own divider for visual separation.
*
* Colour filters sit between "Favorites" and "Drafts" as one
* horizontal strip of swatches — the colours are self-explanatory, so
* there are no labels. Selecting one shows ONLY active notes of that
* colour — trashed notes never appear, untagged ones do (see
* NoteFilter.ByColor); tapping the selected swatch again returns to
* Home.
*
* "Drafts" lists auto-saved new notes (see Note.isDraft) — a new note
* is persisted automatically while it is being written.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun IncidoDrawer(
currentFilter: NoteFilter,
onSelectFilter: (NoteFilter) -> Unit,
onOpenSettings: () -> Unit,
modifier: Modifier = Modifier,
viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.Factory),
) {
val recent by viewModel.recentHashtags.collectAsStateWithLifecycle()
ModalDrawerSheet(modifier = modifier) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
) {
Text(
text = "Incido",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(start = 12.dp, top = 4.dp, bottom = 16.dp),
)
NavigationDrawerItem(
label = { Text("Home") },
selected = currentFilter == NoteFilter.Home,
onClick = { onSelectFilter(NoteFilter.Home) },
icon = { Icon(Icons.Filled.Home, contentDescription = null) },
)
NavigationDrawerItem(
label = { Text("Favorites") },
selected = currentFilter == NoteFilter.Favorites,
onClick = { onSelectFilter(NoteFilter.Favorites) },
icon = { Icon(Icons.Filled.Star, contentDescription = null) },
)
// Colour filters: one horizontal strip of swatches under
// Favorites (NONE is not offered; the colours are
// self-explanatory, so there are no labels). Each shows
// ONLY active notes of that colour — trashed notes never
// appear, untagged ones do. Tapping the selected swatch
// again returns to Home.
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(
space = 14.dp,
alignment = Alignment.CenterHorizontally,
),
) {
AllNoteColors.filter { it != NoteColor.NONE }.forEach { color ->
val selected = currentFilter == NoteFilter.ByColor(color)
Box(
modifier = Modifier
.size(30.dp)
.clip(CircleShape)
.background(color.toComposeColor())
.then(
if (selected) {
Modifier.border(
width = 3.dp,
color = MaterialTheme.colorScheme.onSurface,
shape = CircleShape,
)
} else {
Modifier
},
)
.clickable {
onSelectFilter(
if (selected) NoteFilter.Home
else NoteFilter.ByColor(color),
)
},
contentAlignment = Alignment.Center,
) {
if (selected) {
Icon(
Icons.Filled.Check,
contentDescription = "${color.label} filter selected",
modifier = Modifier.size(16.dp),
tint = Color.White,
)
}
}
}
}
NavigationDrawerItem(
label = { Text("Drafts") },
selected = currentFilter == NoteFilter.Drafts,
onClick = { onSelectFilter(NoteFilter.Drafts) },
icon = { Icon(Icons.Filled.Drafts, contentDescription = null) },
)
NavigationDrawerItem(
label = { Text("Untagged") },
selected = currentFilter == NoteFilter.Untagged,
onClick = { onSelectFilter(NoteFilter.Untagged) },
icon = { Icon(Icons.Filled.LabelOff, contentDescription = null) },
)
NavigationDrawerItem(
label = { Text("Trash") },
selected = currentFilter == NoteFilter.Trash,
onClick = { onSelectFilter(NoteFilter.Trash) },
icon = { Icon(Icons.Filled.Delete, contentDescription = null) },
)
HorizontalDivider(modifier = Modifier.padding(vertical = 12.dp))
// v0.3.2.0: Settings lives directly underneath Untagged,
// separated by its own divider so the recent-tags section
// below stays grouped.
NavigationDrawerItem(
label = { Text("Settings") },
selected = false,
onClick = onOpenSettings,
icon = { Icon(Icons.Filled.Settings, contentDescription = null) },
)
HorizontalDivider(modifier = Modifier.padding(vertical = 12.dp))
Text(
text = "Recent tags",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 12.dp, bottom = 4.dp),
)
if (recent.isEmpty()) {
Text(
text = "No tags yet — add some from the editor.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
)
} else {
Column(
modifier = Modifier
.fillMaxWidth()
// weight(1f) caps this list at the remaining
// sheet height so long tag lists scroll inside
// the drawer instead of overflowing the bottom.
.weight(1f)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
recent.forEach { usage ->
DrawerHashtagEntry(
usage = usage,
selected = currentFilter == NoteFilter.ByTag(usage.name),
onClick = { onSelectFilter(NoteFilter.ByTag(usage.name)) },
)
}
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun DrawerHashtagEntry(
usage: HashtagUsage,
selected: Boolean,
onClick: () -> Unit,
) {
NavigationDrawerItem(
label = { Text("#${usage.name}") },
badge = {
val n = usage.noteCount
val label = if (n == 1) "1 note" else "$n notes"
Text(label, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
},
selected = selected,
onClick = onClick,
icon = { Icon(Icons.Filled.Tag, contentDescription = null) },
)
}
@@ -0,0 +1,169 @@
package org.incido.compose.ui.editor
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import android.graphics.BitmapFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.incido.domain.repository.NoteRepository
/**
* v0.3.1.0 — Full-screen image viewer with pinch-to-zoom and pan.
* Opened from the editor (or any future surface) when the user taps
* an attachment thumbnail. Dismissed by tapping the close button,
* tapping the scrim, or pressing back (the platform handles back via
* the `Dialog`'s default dismiss behaviour).
*
* [attachmentId] is either a persisted [NoteAttachment.id] (loaded via
* [NoteRepository.getAttachmentBytes]) or a pending temp id (loaded
* from [NoteEditorUiState.pendingAttachmentBytes]).
*
* The [onClose] lambda is invoked on any dismiss path. The screen
* itself is rendered inside a [Dialog] so it sits above all
* Scaffold content with a guaranteed black backdrop.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageViewerScreen(
attachmentId: ViewerAttachmentId,
repository: NoteRepository,
pendingBytes: ByteArray?,
onClose: () -> Unit,
) {
// Full-screen black backdrop, ignore system bars so we get the
// full window.
Dialog(
onDismissRequest = onClose,
properties = DialogProperties(
usePlatformDefaultWidth = false,
dismissOnBackPress = true,
dismissOnClickOutside = true,
),
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black),
) {
// Pinch-zoom + pan state. Pan & zoom compose nicely via
// rememberTransformableState + transformable; no new dep.
var scale by remember { mutableStateOf(1f) }
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
val transformState = rememberTransformableState { zoomChange, panChange, _ ->
scale = (scale * zoomChange).coerceIn(1f, 6f)
offsetX += panChange.x
offsetY += panChange.y
}
// Decode the image (or display an error message when the
// bytes can't be loaded / decoded).
var loadFailed by remember { mutableStateOf(false) }
val bitmap by produceState<android.graphics.Bitmap?>(initialValue = null, key1 = attachmentId) {
loadFailed = false
val bytes: ByteArray? = when (attachmentId) {
is ViewerAttachmentId.Persisted -> withContext(Dispatchers.IO) {
repository.getAttachmentBytes(attachmentId.id)
}
is ViewerAttachmentId.Pending -> pendingBytes
}
if (bytes == null) {
loadFailed = true
return@produceState
}
val decoded = withContext(Dispatchers.IO) {
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
value = decoded
if (decoded == null) loadFailed = true
}
if (bitmap != null) {
Image(
bitmap = bitmap!!.asImageBitmap(),
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTapGestures(
onTap = { onClose() },
onDoubleTap = {
// Double-tap to reset zoom + pan.
scale = 1f
offsetX = 0f
offsetY = 0f
},
)
}
.graphicsLayer(
scaleX = scale,
scaleY = scale,
translationX = offsetX,
translationY = offsetY,
)
.transformable(state = transformState, lockRotationOnZoomPan = false),
)
} else {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = if (loadFailed) "Couldn't load image" else "Loading…",
color = Color.White,
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.SemiBold,
)
}
}
// Close button — top-right, always visible.
IconButton(
onClick = onClose,
modifier = Modifier
.align(Alignment.TopEnd)
.padding(12.dp),
) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "Close image",
tint = Color.White,
)
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,892 @@
package org.incido.compose.ui.editor
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.IncidoApplication
import org.incido.compose.share.LinkedShareComposer
import org.incido.domain.model.ChecklistItem
import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository
/**
* Immutable UI state for [NoteEditorScreen].
*/
data class NoteEditorUiState(
val existing: Note? = null,
val content: String = "",
val isFavorite: Boolean = false,
val color: NoteColor = NoteColor.NONE,
/** Normalised, sorted ascending. */
val hashtags: List<String> = emptyList(),
/** v0.3.8.0 — which editor surface the body uses (see [NoteType]). */
val type: NoteType = NoteType.TEXT,
/** v0.3.8.0 — title / preamble kept above the rows in list modes. */
val listHeader: String = "",
/** v0.3.8.0 — parsed checklist rows; always empty for [NoteType.TEXT]. */
val items: List<ChecklistItem> = emptyList(),
/** True while the add-tag sheet is open. */
val isAddingTag: Boolean = false,
/** Latest typing in the add-tag sheet (raw, before normalisation). */
val tagInput: String = "",
/** Autocomplete suggestions for the add-tag sheet. */
val tagSuggestions: List<String> = emptyList(),
val isLoading: Boolean = true,
val isSaving: Boolean = false,
val isDeleted: Boolean = false,
val snackbar: String? = null,
/**
* v0.3.1.0 — attachments already persisted in the DB for this note.
* For new notes (no [existing] id yet), the editor shows these
* empty until save; in-flight attachments live in [pendingAttachments].
*/
val attachments: List<NoteAttachment> = emptyList(),
/**
* v0.3.1.0 — attachments staged for a not-yet-saved new note.
* Bytes are kept in [pendingAttachmentBytes] keyed by [PendingAttachment.tempId]
* so the UI can render thumbnails without the StateFlow holding large
* blobs. On save, each pending attachment is persisted via
* [NoteRepository.addAttachment] using the new note id.
*/
val pendingAttachments: List<PendingAttachment> = emptyList(),
/**
* v0.3.1.0 — bytes for each pending attachment. Stored outside
* [NoteEditorUiState] so the StateFlow doesn't keep large blobs
* alive; queried by the editor's thumbnail composables on demand.
*/
val pendingAttachmentBytes: Map<Long, ByteArray> = emptyMap(),
/**
* v0.3.1.0 — non-null while a single-attachment viewer is on screen.
* Tap a thumbnail in the editor to open; the editor passes the
* [PendingAttachment.tempId] for pending items or the persisted
* [NoteAttachment.id] for stored items.
*/
val fullScreenAttachmentId: ViewerAttachmentId? = null,
) {
/** `true` when editing an existing note (existing != null). */
val isEditing: Boolean get() = existing != null
/**
* v0.4.2.0 — `true` once a voice take exists (staged pending or
* already persisted as an attachment).
*/
val hasVoiceTake: Boolean get() =
pendingAttachments.any { it.mimeType.startsWith("audio/") } ||
attachments.any { it.mimeType.startsWith("audio/") }
/**
* `true` while content is non-blank and not in the middle of
* saving. v0.4.2.0: a VOICE_NOTE may also save on the strength of
* its recording alone — the take IS the note's content.
*/
val canSave: Boolean get() =
(content.isNotBlank() || (type == NoteType.VOICE_NOTE && hasVoiceTake)) &&
!isSaving
/** `true` while this note is an auto-saved draft (see Note.isDraft). */
val isDraft: Boolean get() = existing?.isDraft == true
/** `true` when there's still room to add another tag. */
val canAddMoreTags: Boolean get() = hashtags.size < MAX_TAGS
/** Dirty-check used by the editor's back button. */
fun isDirty(
initialContent: String,
initialFavorite: Boolean,
initialColor: NoteColor,
initialTags: List<String>,
initialType: NoteType,
): Boolean = content != initialContent ||
isFavorite != initialFavorite ||
color != initialColor ||
hashtags != initialTags ||
type != initialType
companion object {
/** Hard cap on tags per note (matches Development Plan §6.1). */
const val MAX_TAGS = 5
}
}
/**
* v0.3.1.0 — sealed id for the full-screen viewer. Lets the editor
* open either a persisted attachment or a pending (not-yet-saved)
* one through the same UI.
*/
sealed interface ViewerAttachmentId {
/** Open the persisted attachment with this DB id. */
data class Persisted(val id: Long) : ViewerAttachmentId
/** Open the pending attachment with this local temp id. */
data class Pending(val tempId: Long) : ViewerAttachmentId
}
/**
* v0.3.1.0 — metadata for an attachment that's been imported but
* not yet persisted (because we don't have a note id yet — the note
* is still being composed). Bytes for this row live in
* [NoteEditorUiState.pendingAttachmentBytes] keyed by [tempId].
*/
data class PendingAttachment(
val tempId: Long,
val mimeType: String,
val displayName: String,
val createdAt: Long,
val sizeBytes: Long,
) {
val isImage: Boolean get() = mimeType.startsWith("image/")
}
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class NoteEditorViewModel(
private val repository: NoteRepository,
private val noteId: Long?,
/** v0.3.1.0 — pre-filled content from a share-into intent (nullable). */
initialSharedText: String? = null,
/** v0.3.1.0 — pre-loaded image bytes from a share-into intent. */
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the share-into. Most
* browsers fill this with the page title for share-URL intents.
* Threaded through [LinkedShareComposer] so the note seeds with
* the title on its first line and the URL below. Null for plain
* text / image shares that have no subject.
*/
initialSharedSubject: String? = null,
) : ViewModel() {
/**
* v0.3.6.0 — the actual seed text used when there is no existing
* note. Composed from (subject, text) by the offline-only
* [LinkedShareComposer] so the resulting layout matches the rest
* of the app (title = first line, body = everything after).
*/
private val initialSeedContent: String =
LinkedShareComposer.compose(initialSharedSubject, initialSharedText)
private val _state = MutableStateFlow(NoteEditorUiState())
val state: StateFlow<NoteEditorUiState> = _state.asStateFlow()
/**
* Live stream of persisted attachments for an existing note.
* Empty until the note is saved (no note id → nothing to query).
*/
private val attachmentsFlow: StateFlow<List<NoteAttachment>> = if (noteId == null || noteId == 0L) {
MutableStateFlow(emptyList())
} else {
repository.observeAttachments(noteId)
.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
}
/** Snapshot of initial values for the dirty predicate (see [NoteEditorScreen]). */
var initialContent: String = ""
private set
var initialFavorite: Boolean = false
private set
var initialColor: NoteColor = NoteColor.NONE
private set
var initialHashtags: List<String> = emptyList()
private set
var initialType: NoteType = NoteType.TEXT
private set
/** Internal: re-emits suggestions whenever the tag input changes. */
private val tagInputFlow = MutableStateFlow("")
private val tagSuggestionsFlow = MutableStateFlow<List<String>>(emptyList())
/**
* v0.3.1.0 — local temp-id counter for pending attachments.
* Starts at `-now` so generated ids never collide with real
* ObjectBox ids (which are positive).
*/
private var nextPendingTempId: Long = -System.currentTimeMillis()
/**
* Draft autosave. A NEW note (or one still flagged as a draft) is
* persisted automatically: every edit lands in the DB ~400 ms after
* the last keystroke (coalesced so typing doesn't write per char),
* and [flushDraft] forces an immediate write whenever the editor
* closes or disposes. A crash can therefore only ever lose the last
* few keystrokes — never a whole draft.
*/
private val draftAutosave = noteId == null || noteId == 0L
/** True while this session autosaves: brand-new notes and draft editing. */
val isDraftFlow: Boolean
get() = draftAutosave || _state.value.isDraft
private var draftPersistInProgress = false
init {
// Signature-driven debounced autosave: whenever anything a draft
// persists changes, write the draft row shortly after.
viewModelScope.launch {
_state
.map { s ->
listOf(s.content, s.isFavorite, s.color, s.type, s.hashtags)
}
.distinctUntilChanged()
.debounce(DRAFT_AUTOSAVE_DEBOUNCE_MS)
.collect { persistDraftNow() }
}
}
init {
// Tag autocomplete — re-query on every keystroke (debounced upstream
// would be nice but ObjectBox is plenty fast for this size).
// Tag autocomplete. v0.3.8.0 FIX: the previous nested
// `tagInputFlow.collect { pool.collect { … } }` never resumed
// past the first keystroke — observeAllHashtags()/searchHashtags()
// are infinite callbackFlows, so the outer lambda suspended in
// the inner collect forever and typing never re-queried (the
// sheet only ever showed "+ Create"). flatMapLatest cancels the
// previous subscription per keystroke, and each fresh flow
// try-sends its snapshot immediately ⇒ live filtering.
viewModelScope.launch {
tagInputFlow
.flatMapLatest { raw ->
val prefix = Hashtag.normalise(raw)
if (prefix.isEmpty()) {
repository.observeAllHashtags()
} else {
repository.searchHashtags(prefix)
}
}
.collect { suggestions ->
_state.update { it.copy(tagSuggestions = suggestions) }
}
}
// Live attachments: pump persisted rows into state.attachments.
viewModelScope.launch {
attachmentsFlow.collect { rows ->
_state.update { it.copy(attachments = rows) }
}
}
// Load the note if editing; otherwise seed with shared content.
if (noteId == null || noteId == 0L) {
val (pendingList, pendingBytes) = if (initialSharedImages.isNotEmpty()) {
val list = mutableListOf<PendingAttachment>()
val map = mutableMapOf<Long, ByteArray>()
initialSharedImages.forEach { img ->
// Use the same tempId generator as importAttachmentBytes so
// the pending list and the bytes map line up.
val tempId = nextPendingTempId--
list += PendingAttachment(
tempId = tempId,
mimeType = img.mimeType,
displayName = img.displayName,
createdAt = System.currentTimeMillis(),
sizeBytes = img.bytes.size.toLong(),
)
map[tempId] = img.bytes
}
list to map
} else {
emptyList<PendingAttachment>() to emptyMap<Long, ByteArray>()
}
val seed = NoteEditorUiState(
existing = null,
// v0.3.6.0: run the seed text through the LinkedShareComposer
// so a share-into URL seeds with the page title on the
// first line and the URL below (titleAndBody-friendly).
content = initialSeedContent,
isFavorite = false,
color = NoteColor.NONE,
hashtags = emptyList(),
isLoading = false,
isSaving = false,
pendingAttachments = pendingList,
pendingAttachmentBytes = pendingBytes,
)
_state.value = seed
initialContent = seed.content
initialFavorite = false
initialColor = NoteColor.NONE
initialHashtags = emptyList()
} else {
viewModelScope.launch {
repository.observeById(noteId).collect { note ->
val firstLoad = _state.value.isLoading
if (note != null && firstLoad) {
initialContent = note.content
initialFavorite = note.isFavorite
initialColor = note.color
initialHashtags = note.hashtags
initialType = note.type
}
// Draft echoes: emissions caused by our own autosave
// must not clobber in-progress edits mid-typing —
// the local state is authoritative while drafting.
if (note != null && note.isDraft && !firstLoad) return@collect
// Parse list rows once on first load; later DB
// emissions must not clobber in-progress edits.
val listSeed: Pair<String, List<ChecklistItem>>? =
if (note != null && firstLoad && note.type != NoteType.TEXT) {
Note.splitListContent(
note.content,
interpretCosts = note.type == NoteType.SHOPPING_LIST,
)
} else {
null
}
_state.update {
it.copy(
existing = note,
content = note?.content ?: it.content,
isFavorite = note?.isFavorite ?: it.isFavorite,
color = note?.color ?: it.color,
hashtags = note?.hashtags ?: it.hashtags,
type = note?.type ?: it.type,
listHeader = listSeed?.first ?: it.listHeader,
items = listSeed?.second ?: it.items,
isLoading = false,
)
}
}
}
}
}
fun onContentChange(newContent: String) {
_state.update { it.copy(content = newContent) }
}
fun toggleFavorite() {
_state.update { it.copy(isFavorite = !it.isFavorite) }
}
fun setColor(color: NoteColor) {
_state.update { it.copy(color = color) }
}
fun openAddTagSheet() {
// v0.3.8.0 FIX: push the empty query through the suggestion
// pipeline FIRST so the flatMapLatest collector re-emits every
// existing tag (most-used first) while the sheet opens — the
// old code just cleared the list to emptyList() here and the
// stuck collector never refilled it.
tagInputFlow.value = ""
_state.update { it.copy(isAddingTag = true, tagInput = "") }
}
fun closeAddTagSheet() {
tagInputFlow.value = ""
_state.update { it.copy(isAddingTag = false, tagInput = "") }
}
fun onTagInputChange(raw: String) {
tagInputFlow.value = raw
_state.update { it.copy(tagInput = raw) }
}
/** Add an existing tag to the note (idempotent). Returns false if the cap is hit. */
fun addTag(name: String): Boolean {
val normalised = Hashtag.normalise(name)
if (normalised.isEmpty()) return false
if (!normalised.matches(Regex("^[a-z0-9][a-z0-9._-]{0,30}$"))) return false
val current = _state.value
if (normalised in current.hashtags) return true // already there
if (current.hashtags.size >= NoteEditorUiState.MAX_TAGS) {
_state.update { it.copy(snackbar = "Maximum ${NoteEditorUiState.MAX_TAGS} tags reached.") }
return false
}
_state.update { it.copy(hashtags = (it.hashtags + normalised).sorted()) }
return true
}
fun removeTag(name: String) {
val normalised = Hashtag.normalise(name)
_state.update { it.copy(hashtags = it.hashtags.filterNot { tag -> tag == normalised }) }
}
// ---- v0.3.8.0 task / shopping list editing ----
/**
* Keep the [NoteEditorUiState.items] / [NoteEditorUiState.listHeader]
* rows and the derived [NoteEditorUiState.content] in step, so the
* save path, dirty-check, search preview, and `canSave` gate all
* keep working off the single content string.
*/
private fun NoteEditorUiState.withListEdits(
header: String = this.listHeader,
items: List<ChecklistItem>,
): NoteEditorUiState = copy(
listHeader = header,
items = items,
content = Note.serializeListContent(header, items, type),
)
private fun List<ChecklistItem>.patched(
index: Int,
transform: (ChecklistItem) -> ChecklistItem,
): List<ChecklistItem> = mapIndexed { i, item ->
if (i == index) transform(item) else item
}
/**
* Convert the body to [target]; tapping the already-active mode
* converts back to [NoteType.TEXT]. Text moves losslessly between
* the plain editor and the checkbox serialisation — costs are only
* stored while the note is a shopping list (converting to a task
* list folds each cost back into the item text).
*/
fun convertTo(target: NoteType) {
_state.update { s ->
val next = if (s.type == target) NoteType.TEXT else target
if (next == NoteType.VOICE_NOTE) {
// v0.4.2.0 — voice mode keeps the plain text field
// (title = first line) exactly like TEXT; a list body
// folds back to its plain form first. The recording is
// NOT body content — it's an ordinary audio attachment,
// so it also survives converting back to plain text.
val source =
if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) s.content
else Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
s.copy(
type = next,
listHeader = "",
items = emptyList(),
content = source,
)
} else if (next == NoteType.TEXT) {
// Content already holds the serialised `- [ ]` rows;
// just drop out of the structured editor (the inline
// GFM checklist rendering from v0.2.0.0 still applies).
s.copy(type = NoteType.TEXT, listHeader = "", items = emptyList())
} else {
val source = if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) {
s.content
} else {
// Serialise through the FOLDED legacy form (plain
// "Milk 2 x 3.90" lines, never `{q…p…}` markers) so
// structured values survive the trip and re-parse
// cleanly under the target mode's rules.
Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
}
val (header, parsedRaw) = Note.splitListContent(
source,
interpretCosts = next == NoteType.SHOPPING_LIST,
)
val parsed = if (parsedRaw.isEmpty()) listOf(ChecklistItem("")) else parsedRaw
s.copy(
type = next,
listHeader = header,
items = parsed,
content = Note.serializeListContent(header, parsed, next),
)
}
}
_state.update {
it.copy(
snackbar = when (it.type) {
NoteType.TASK_LIST -> "Task list mode — first line stays the title."
NoteType.SHOPPING_LIST -> "Shopping list mode — check an item once it's in your basket."
NoteType.VOICE_NOTE -> "Voice note mode — record with the mic card above the text."
else -> "Back to plain text."
},
)
}
}
fun onHeaderChange(value: String) {
_state.update { it.withListEdits(header = value, items = it.items) }
}
fun addListItem() {
_state.update { s ->
if (s.type == NoteType.TEXT) return@update s
s.withListEdits(items = s.items + ChecklistItem(""))
}
}
/**
* Insert a blank row right after [index] (or append it on the last
* row). Driven by Enter/Return in the task/product field so the
* writer flows downward into a fresh row instead of tabbing sideways.
*/
fun addListItemAfter(index: Int) {
_state.update { s ->
if (s.type == NoteType.TEXT) return@update s
if (index !in s.items.indices) return@update s
val updated = s.items.toMutableList().also { it.add(index + 1, ChecklistItem("")) }
s.withListEdits(items = updated)
}
}
fun removeListItem(index: Int) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.filterIndexed { i, _ -> i != index })
}
}
fun setItemChecked(index: Int, checked: Boolean) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(checked = checked) })
}
}
fun setItemText(index: Int, text: String) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(text = text) })
}
}
/**
* Price field input — POS style: everything is reduced to cents
* digits ("199" ⇒ $1.99, separators typed or pasted are stripped).
*/
fun setItemCost(index: Int, rawCost: String) {
val sanitized = Note.normalisePriceInput(rawCost)
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(cost = sanitized) })
}
}
/**
* Quantity line input (free-text digits); blank means the default 1.
*
* v0.3.8.0: "1" now stays stored as "1" — the field is free text, so
* the typed digit must remain visible. The serialiser already omits
* `{q1}` and cards only show "×qty" when the quantity is > 1, so this
* is storage-neutral. "0" / blank normalise to "" (meaning 1).
*/
fun setItemQuantity(index: Int, rawQty: String) {
val stored = Note.normaliseQuantity(rawQty)
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(quantity = stored) })
}
}
fun consumeSnackbar() {
_state.update { it.copy(snackbar = null) }
}
// ---- v0.3.1.0 attachment + share-into actions ----
/**
* Import bytes from an arbitrary content Uri (file picker or
* share-into). Reads bytes on the IO dispatcher, then either:
* - persists immediately if the note already has an id, or
* - adds a [PendingAttachment] entry if this is a not-yet-saved note.
*/
fun importAttachmentBytes(
bytes: ByteArray,
mimeType: String,
displayName: String,
) {
viewModelScope.launch {
val existingId = _state.value.existing?.id
if (existingId != null && existingId > 0L) {
// Persist straight to the DB; observeAttachments will surface it.
withContext(Dispatchers.IO) {
repository.addAttachment(
noteId = existingId,
bytes = bytes,
mimeType = mimeType,
displayName = displayName,
)
}
} else {
// Stage as pending — bytes live in pendingAttachmentBytes
// until the user saves the note.
val tempId = nextPendingTempId--
val pending = PendingAttachment(
tempId = tempId,
mimeType = mimeType,
displayName = displayName,
createdAt = System.currentTimeMillis(),
sizeBytes = bytes.size.toLong(),
)
_state.update { ui ->
ui.copy(
pendingAttachments = ui.pendingAttachments + pending,
pendingAttachmentBytes = ui.pendingAttachmentBytes + (tempId to bytes),
)
}
}
}
}
fun removePendingAttachment(tempId: Long) {
_state.update { ui ->
val newBytes = ui.pendingAttachmentBytes.toMutableMap().apply { remove(tempId) }
ui.copy(
pendingAttachments = ui.pendingAttachments.filterNot { it.tempId == tempId },
pendingAttachmentBytes = newBytes,
)
}
}
/** Delete a persisted attachment by id (used by the ✕ on the thumbnail strip). */
fun deletePersistedAttachment(id: Long) {
viewModelScope.launch {
withContext(Dispatchers.IO) { repository.removeAttachment(id) }
}
}
/**
* v0.4.2.0 — stage/persist the finished take of a voice note.
* One take per note: any previous take (pending or already
* persisted) is discarded first. The bytes then ride the ordinary
* attachment pipeline — staged as a [PendingAttachment] while the
* note is unsaved, written straight to the DB afterwards — so
* encryption, backup/restore, and the trash cascade all apply
* without any voice-specific storage.
*
* [mimeType] is the container the recorder actually produced —
* `audio/ogg` (Opus, 32 kbps mono) on API 29+, `audio/mp4` (AAC)
* on API 26–28; the display-name extension follows suit.
*/
fun setVoiceRecording(bytes: ByteArray, mimeType: String = "audio/ogg") {
if (bytes.size < 2048) {
_state.update { it.copy(snackbar = "Recording too short \u2014 try again.") }
return
}
viewModelScope.launch {
_state.value.pendingAttachments
.filter { it.mimeType.startsWith("audio/") }
.forEach { removePendingAttachment(it.tempId) }
val stalePersisted = _state.value.attachments
.filter { it.mimeType.startsWith("audio/") }
if (stalePersisted.isNotEmpty()) {
withContext(Dispatchers.IO) {
stalePersisted.forEach { repository.removeAttachment(it.id) }
}
}
val stamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US)
.format(java.util.Date())
val ext = if (mimeType == "audio/mp4") "m4a" else "opus"
importAttachmentBytes(
bytes = bytes,
mimeType = mimeType,
displayName = "Voice_$stamp.$ext",
)
}
}
/** Open the full-screen image viewer for [viewerId]. */
fun openFullScreen(viewerId: ViewerAttachmentId) {
_state.update { it.copy(fullScreenAttachmentId = viewerId) }
}
/** Close the full-screen image viewer. */
fun closeFullScreen() {
_state.update { it.copy(fullScreenAttachmentId = null) }
}
// ---- save ----
/**
* Force-write the current draft state to the DB right now — used
* when the editor closes / disposes so pending edits never sit in
* the debounce window. No-op for non-draft sessions and blank
* content (see [persistDraftNow]).
*/
fun flushDraft() {
viewModelScope.launch { persistDraftNow() }
}
/** Write the draft row if this session is in the draft lifecycle. */
private suspend fun persistDraftNow() {
val current = _state.value
if (current.isLoading || current.isSaving) return
if (draftPersistInProgress) return
val baseNote = current.existing
if (baseNote != null && !baseNote.isDraft) return // already published
if (!draftAutosave && baseNote?.isDraft != true) return
if (current.content.isBlank()) return
draftPersistInProgress = true
try {
val now = System.currentTimeMillis()
val draft = baseNote?.copy(
content = current.content,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
isDraft = true,
) ?: Note(
content = current.content,
createdAt = now,
updatedAt = now,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
isDraft = true,
)
val previous = baseNote?.hashtags.orEmpty().toSet()
val currentSet = current.hashtags.toSet()
val saved = repository.saveNoteWithHashtags(
note = draft,
hashtagsToAdd = currentSet - previous,
hashtagsToRemove = previous - currentSet,
)
// Adopt the persisted row so every later write updates the
// SAME note — one draft per editing session.
_state.update {
it.copy(existing = saved.copy(isDraft = true, hashtags = current.hashtags))
}
} finally {
draftPersistInProgress = false
}
}
fun save(onDone: () -> Unit) {
val current = _state.value
if (!current.canSave) return
_state.update { it.copy(isSaving = true) }
viewModelScope.launch {
val baseNote = current.existing
// An explicit Save PUBLISHES the note: a draft row loses
// its flag here and joins the normal views for good.
val toPersist = baseNote?.copy(
content = current.content,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
isDraft = false,
) ?: Note(
content = current.content,
createdAt = System.currentTimeMillis(),
updatedAt = System.currentTimeMillis(),
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
)
val previous = baseNote?.hashtags.orEmpty().toSet()
val currentSet = current.hashtags.toSet()
val saved = repository.saveNoteWithHashtags(
note = toPersist,
hashtagsToAdd = currentSet - previous,
hashtagsToRemove = previous - currentSet,
)
// Persist any pending attachments against the now-known id.
current.pendingAttachments.forEach { pending ->
val bytes = current.pendingAttachmentBytes[pending.tempId]
if (bytes != null) {
withContext(Dispatchers.IO) {
repository.addAttachment(
noteId = saved.id,
bytes = bytes,
mimeType = pending.mimeType,
displayName = pending.displayName,
)
}
}
}
_state.update {
it.copy(
// v0.4.x FIX: adopt the PUBLISHED row into the UI
// state. Without this the state still reported
// isDraft = true, and the flushDraft() fired by the
// editor's disposal immediately re-persisted the
// note as a draft — every confirmed note landed in
// Drafts. With the published row adopted, the
// already-published guard in persistDraftNow() turns
// that flush into a no-op.
existing = saved.copy(
isDraft = false,
hashtags = current.hashtags,
),
isSaving = false,
pendingAttachments = emptyList(),
pendingAttachmentBytes = emptyMap(),
)
}
onDone()
}
}
fun delete(onDone: () -> Unit) {
val id = _state.value.existing?.id ?: return
_state.update { it.copy(isSaving = true) }
viewModelScope.launch {
repository.softDelete(id)
_state.update { it.copy(isSaving = false, isDeleted = true) }
onDone()
}
}
companion object {
/** Typing-pause before a draft autosave fires (ms). */
const val DRAFT_AUTOSAVE_DEBOUNCE_MS = 400L
fun factory(
noteId: Long?,
initialSharedText: String? = null,
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the share-into.
* Threaded through [LinkedShareComposer] so a shared URL
* seeds the note with the page title on the first line.
*/
initialSharedSubject: String? = null,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
NoteEditorViewModel(
repository = app.container.noteRepository,
noteId = noteId,
initialSharedText = initialSharedText,
initialSharedImages = initialSharedImages,
initialSharedSubject = initialSharedSubject,
)
}
}
}
}
/**
* v0.3.1.0 — bytes + metadata for an image passed in via share-into.
* Constructed by [org.incido.compose.share.SharedIntentBuffer.consume]
* after the [MainActivity] reads the incoming Intent.
*/
data class SharedImage(
val bytes: ByteArray,
val mimeType: String,
val displayName: String,
) {
/** Build a [PendingAttachment] for these bytes. */
fun toPending(): PendingAttachment = PendingAttachment(
tempId = -System.currentTimeMillis(), // overwritten by ViewModel on import
mimeType = mimeType,
displayName = displayName,
createdAt = System.currentTimeMillis(),
sizeBytes = bytes.size.toLong(),
)
}
@@ -0,0 +1,539 @@
package org.incido.compose.ui.editor
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.FiberManualRecord
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
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
import java.util.Locale
/**
* v0.4.2.0 — the voice-note body section: sits at the very top of the
* note body (above the text field) whenever the editor is in
* [org.incido.domain.model.NoteType.VOICE_NOTE] mode.
*
* Three states:
* * **No take** — "tap to record" card.
* * **Recording** — live elapsed timer with stop / discard controls.
* * **Take ready** (pending *or* persisted) — media player bar with
* play/pause, seek, a **Download** action that copies the file to
* the system Downloads folder, and a delete action (re-record via
* the mic button — the ViewModel replaces the old take when a new
* recording lands).
*
* The take rides the existing attachment pipeline: while the note is
* unsaved it is a [PendingAttachment] whose bytes live in the UI
* state; after save it is an ordinary `audio/ogg` attachment row
* (encrypted at rest like every other attachment, backed up with the
* note, and still visible in the attachment strip below).
*/
@Composable
fun VoiceNoteSection(
/** Pending (unsaved) voice take, or null. */
voicePending: PendingAttachment?,
/** Bytes of the pending take (null while still unrecorded). */
voicePendingBytes: ByteArray?,
/** Persisted voice take of a saved note, or null. */
voicePersisted: NoteAttachment?,
/** Source of persisted bytes (lazy-loaded by the player). */
repository: NoteRepository?,
/** Checked on every record tap — reflects RECORD_AUDIO state. */
hasMicPermission: () -> Boolean,
/** Launches the RECORD_AUDIO permission request. */
onRequestPermission: () -> Unit,
/** A finished recording is ready to stage/persist (replaces any old take);
* second arg is the recorder's actual mime (`audio/ogg`, or `audio/mp4` on API 26–28). */
onTakeRecorded: (ByteArray, String) -> Unit,
/** Remove the current take (pending or persisted). */
onDeleteTake: () -> Unit,
/** Suppress auto-lock around the download share-sheet round-trip (API < 29). */
securityManager: SecurityManager?,
modifier: Modifier = Modifier,
) {
val ctx = LocalContext.current
val recorder = remember { VoiceRecorder() }
var isRecording by remember { mutableStateOf(false) }
var elapsedMs by remember { mutableStateOf(0L) }
// Abandon an in-flight take if the editor tears down mid-recording
// (back navigation, config change) — no orphan temp files.
DisposableEffect(Unit) {
onDispose { recorder.cancel() }
}
// Live tick for the recording timer.
LaunchedEffect(isRecording) {
if (!isRecording) return@LaunchedEffect
val startedAt = android.os.SystemClock.elapsedRealtime() - elapsedMs
while (isRecording) {
elapsedMs = android.os.SystemClock.elapsedRealtime() - startedAt
delay(100)
}
}
fun startRecording() {
if (!hasMicPermission()) {
onRequestPermission()
return
}
try {
recorder.start(ctx)
elapsedMs = 0L
isRecording = true
} catch (e: Exception) {
Toast.makeText(ctx, "Couldn't start recording", Toast.LENGTH_SHORT).show()
}
}
fun stopRecording() {
val bytes = recorder.stopAndReadBytes()
isRecording = false
if (bytes == null) {
Toast.makeText(ctx, "Recording failed", Toast.LENGTH_SHORT).show()
} else {
onTakeRecorded(bytes, recorder.recordedMimeType)
}
}
val hasTake = voicePending != null || voicePersisted != null
// Persisted bytes lazy-load on demand (same pattern as the
// attachment thumbnails) so the StateFlow never holds the blob.
val lazyPersistedBytes by produceState<ByteArray?>(
initialValue = null,
key1 = voicePersisted?.id,
) {
value = if (voicePersisted != null && repository != null) {
withContext(Dispatchers.IO) { repository.getAttachmentBytes(voicePersisted.id) }
} else {
null
}
}
val takeBytes: ByteArray? = if (voicePending != null) voicePendingBytes else lazyPersistedBytes
val takeName: String =
voicePending?.displayName ?: voicePersisted?.displayName ?: "voice_note.opus"
val takeMime: String =
voicePending?.mimeType ?: voicePersisted?.mimeType ?: "audio/ogg"
val takeKey: Long = voicePending?.tempId ?: voicePersisted?.id ?: 0L
Column(
modifier = modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
.border(
1.dp,
MaterialTheme.colorScheme.outlineVariant,
RoundedCornerShape(12.dp),
)
.background(
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
RoundedCornerShape(12.dp),
)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
when {
isRecording -> Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
Icons.Filled.FiberManualRecord,
contentDescription = null,
tint = Color(0xFFD32F2F),
modifier = Modifier.size(16.dp),
)
Spacer(Modifier.width(8.dp))
Text(
formatVoiceTime(elapsedMs),
style = MaterialTheme.typography.titleMedium,
)
Spacer(Modifier.weight(1f))
IconButton(onClick = { stopRecording() }) {
Icon(
Icons.Filled.Stop,
contentDescription = "Stop recording",
tint = MaterialTheme.colorScheme.primary,
)
}
IconButton(onClick = {
recorder.cancel()
isRecording = false
}) {
Icon(
Icons.Filled.Close,
contentDescription = "Discard recording",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
hasTake && takeBytes == null -> Row(
modifier = Modifier
.fillMaxWidth()
.height(48.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
Text(
"Loading audio\u2026",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
hasTake && takeBytes != null -> VoicePlayerBar(
bytes = takeBytes,
mimeType = takeMime,
sourceKey = takeKey,
takeName = takeName,
onDelete = onDeleteTake,
onDownload = { saveVoiceTakeToDevice(ctx, securityManager, takeName, takeMime, takeBytes) },
onRecordAgain = { startRecording() },
)
else -> Row(
modifier = Modifier
.fillMaxWidth()
.clickable { startRecording() }
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Box(
modifier = Modifier
.size(40.dp)
.background(
MaterialTheme.colorScheme.primary.copy(alpha = 0.12f),
CircleShape,
),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.Mic,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(22.dp),
)
}
Text(
"Tap to record a voice note",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
/**
* Media-player bar for a recorded take: play/pause + seek + elapsed /
* total, plus download, re-record and delete actions. Backed by the
* platform [MediaPlayer] — the bytes are written to a small cache file
* (`cacheDir/voice_play/`) because MediaPlayer plays paths, not
* in-memory blobs; the file is rewritten whenever a new take arrives
* and is disposable cache data.
*/
@Composable
private fun VoicePlayerBar(
bytes: ByteArray,
mimeType: String,
sourceKey: Long,
takeName: String,
onDelete: () -> Unit,
onDownload: () -> Unit,
onRecordAgain: () -> Unit,
) {
val ctx = LocalContext.current
// Materialise the take into a playable cache file.
val playPath by produceState<String?>(
initialValue = null,
key1 = sourceKey,
key2 = bytes,
) {
value = withContext(Dispatchers.IO) {
runCatching {
val dir = File(ctx.cacheDir, "voice_play").apply { mkdirs() }
val ext = if (mimeType == "audio/ogg") "opus" else "m4a"
val file = File(dir, "take_$sourceKey.$ext")
file.writeBytes(bytes)
file.absolutePath
}.getOrNull()
}
}
var player by remember(sourceKey) { mutableStateOf<MediaPlayer?>(null) }
var prepared by remember(sourceKey) { mutableStateOf(false) }
var isPlaying by remember(sourceKey) { mutableStateOf(false) }
var positionMs by remember(sourceKey) { mutableStateOf(0L) }
var durationMs by remember(sourceKey) { mutableStateOf(0L) }
var dragMs by remember(sourceKey) { mutableStateOf<Float?>(null) }
DisposableEffect(playPath) {
val path = playPath
if (path == null) {
onDispose { }
} else {
val mp = MediaPlayer()
player = mp
mp.setOnPreparedListener {
durationMs = it.duration.toLong()
prepared = true
}
mp.setOnCompletionListener {
isPlaying = false
positionMs = durationMs
}
mp.setOnErrorListener { _, _, _ -> true }
runCatching {
mp.setDataSource(path)
mp.prepareAsync()
}
onDispose {
runCatching { mp.release() }
player = null
}
}
}
// Keep the slider in step while playing.
LaunchedEffect(isPlaying, prepared) {
if (!isPlaying || !prepared) return@LaunchedEffect
while (isPlaying) {
player?.let { positionMs = it.currentPosition.toLong() }
delay(200)
}
}
Column(modifier = Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = {
val mp = player ?: return@IconButton
if (!prepared) return@IconButton
if (mp.isPlaying) {
mp.pause()
isPlaying = false
} else {
if (positionMs >= durationMs && durationMs > 0) {
mp.seekTo(0)
positionMs = 0
}
mp.start()
isPlaying = true
}
},
enabled = prepared,
) {
Icon(
imageVector = if (isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow,
contentDescription = if (isPlaying) "Pause" else "Play",
tint = MaterialTheme.colorScheme.primary,
)
}
Text(
text = formatVoiceTime((dragMs ?: positionMs.toFloat()).toLong()),
style = MaterialTheme.typography.labelMedium,
)
Slider(
value = (dragMs ?: positionMs.toFloat()).coerceIn(
0f,
durationMs.coerceAtLeast(1).toFloat(),
),
onValueChange = { dragMs = it },
onValueChangeFinished = {
val target = dragMs
if (target != null) {
dragMs = null
val seek = target.toInt()
player?.let { mp ->
if (prepared) {
mp.seekTo(seek)
positionMs = seek.toLong()
}
}
}
},
valueRange = 0f..durationMs.coerceAtLeast(1).toFloat(),
enabled = prepared,
modifier = Modifier
.weight(1f)
.padding(horizontal = 4.dp),
)
Text(
text = formatVoiceTime(durationMs),
style = MaterialTheme.typography.labelMedium,
)
// Download = save a copy to the system Downloads folder
// (pre-Q devices get the share sheet, which reaches the
// same destinations).
IconButton(onClick = onDownload) {
Icon(
Icons.Filled.Download,
contentDescription = "Download recording",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = onRecordAgain) {
Icon(
Icons.Filled.Mic,
contentDescription = "Re-record (replaces current take)",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = onDelete) {
Icon(
Icons.Filled.Delete,
contentDescription = "Delete recording",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Text(
text = takeName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
/**
* Save the take to the system Downloads folder via MediaStore (API 29+,
* no storage permission needed). On API 26–28 — where MediaStore
* Downloads doesn't exist — fall back to the v0.3.1.3 FileProvider
* outbox + share sheet, which reaches the same destinations plus
* "Save to device" handlers.
*/
private fun saveVoiceTakeToDevice(
ctx: Context,
securityManager: SecurityManager?,
displayName: String,
mimeType: String,
bytes: ByteArray,
) {
val safeName = displayName
.replace(Regex("[/\\\\:*?\"<>|]"), "_")
.ifEmpty { "voice_note.opus" }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val saved = runCatching {
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, safeName)
put(MediaStore.Downloads.MIME_TYPE, mimeType)
put(
MediaStore.Downloads.RELATIVE_PATH,
Environment.DIRECTORY_DOWNLOADS,
)
}
val uri = ctx.contentResolver.insert(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
values,
) ?: return@runCatching false
ctx.contentResolver.openOutputStream(uri)?.use { out ->
out.write(bytes)
} ?: return@runCatching false
true
}.getOrDefault(false)
if (saved) {
Toast.makeText(ctx, "Saved to Downloads", Toast.LENGTH_SHORT).show()
return
}
// MediaStore refused (provider hiccup) — fall through to the
// share sheet as the last resort.
}
runCatching {
val outbox = File(ctx.cacheDir, "open_outbox").apply { mkdirs() }
val tmp = File(outbox, "dl_${System.currentTimeMillis()}_$safeName")
tmp.writeBytes(bytes)
val uri = FileProvider.getUriForFile(ctx, "${ctx.packageName}.fileprovider", tmp)
val send = Intent(Intent.ACTION_SEND).apply {
type = mimeType
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
// Auto-Lock = Immediate must not fire while the chooser is up
// (same v0.3.4.0 hotfix as the attachment viewer).
securityManager?.beginExternalActivity()
ctx.startActivity(Intent.createChooser(send, "Save recording"))
}.onFailure {
Toast.makeText(ctx, "Couldn't save recording", Toast.LENGTH_SHORT).show()
}
}
/** ms → "m:ss" (or "h:mm:ss" past an hour). */
internal fun formatVoiceTime(ms: Long): String {
val totalSec = ms / 1000
val h = totalSec / 3600
val m = (totalSec % 3600) / 60
val s = totalSec % 60
return if (h > 0) {
String.format(Locale.US, "%d:%02d:%02d", h, m, s)
} else {
String.format(Locale.US, "%d:%02d", m, s)
}
}
@@ -0,0 +1,132 @@
package org.incido.compose.ui.editor
import android.content.Context
import android.media.MediaRecorder
import android.os.Build
import java.io.File
import java.io.IOException
/**
* v0.4.2.0 — thin MediaRecorder wrapper for voice notes.
*
* Records Opus audio in an Ogg container (`.opus`, mime `audio/ogg`)
* at 32 kbps, single channel, 48 kHz — tiny files, excellent speech
* quality, and produced by the platform MediaRecorder with no extra
* dependencies (the app stays dependency-light per Development Plan
* privacy/offline rules). Opus-in-Ogg output via MediaRecorder is
* public API only from API 29, so API 26–28 devices keep the previous
* AAC/MP4 path (`.m4a`, mime `audio/mp4`); [recordedMimeType] reports
* which container [start] actually used.
*
* Note: the MediaRecorder surface exposes no encoder knobs for Opus
* frame size or complexity, so both stay at platform defaults (Opus
* on Android encodes 20 ms frames); hitting 120 ms frames /
* complexity 10 would require bundling native libopus — deferred.
*
* The take lands in a temp file under `cacheDir/voice_rec/`; the
* caller reads it back as a [ByteArray] on [stopAndReadBytes] and the
* temp file is deleted immediately — the bytes then ride the ordinary
* attachment pipeline into ObjectBox (same lifecycle as the camera
* outbox from v0.3.1.0).
*
* Not thread-safe: drive it from the main thread only.
*/
class VoiceRecorder {
private var recorder: MediaRecorder? = null
private var outFile: File? = null
private var opus = false
/** True between a successful [start] and the matching stop/cancel. */
val isRecording: Boolean get() = recorder != null
/**
* Mime type of the container [start] actually used — `audio/ogg`
* (Opus) on API 29+, `audio/mp4` (AAC) on API 26–28. Valid after
* any successful [start]; callers use it to tag the finished take.
*/
val recordedMimeType: String get() = if (opus) "audio/ogg" else "audio/mp4"
/**
* Start capturing from the mic into a fresh temp file.
* Throws [IOException] / [RuntimeException] when the mic is busy,
* the permission was revoked mid-session, or the device has none —
* callers should catch and surface a snackbar.
*/
@Suppress("DEPRECATION")
fun start(context: Context) {
if (recorder != null) return
// Opus-in-Ogg via MediaRecorder is public API only from API 29
// (minSdk is 26), so older devices keep the AAC/MP4 path.
val useOpus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
val dir = File(context.cacheDir, "voice_rec").apply { mkdirs() }
val file = File(
dir,
"take_${System.currentTimeMillis()}" + if (useOpus) ".opus" else ".m4a",
)
val rec = MediaRecorder()
try {
rec.apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
if (useOpus) {
setOutputFormat(MediaRecorder.OutputFormat.OGG)
setAudioEncoder(MediaRecorder.AudioEncoder.OPUS)
setAudioEncodingBitRate(32_000) // 32 kbps
setAudioChannels(1) // single channel
setAudioSamplingRate(48_000) // Opus native rate
} else {
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setAudioEncodingBitRate(96_000)
setAudioSamplingRate(44_100)
}
setOutputFile(file.absolutePath)
prepare()
start()
}
recorder = rec
outFile = file
opus = useOpus
} catch (e: Exception) {
rec.release()
file.delete()
throw e
}
}
/**
* Stop the capture, read the recorded bytes, and delete the temp
* file. Returns `null` when nothing was recorded or the encoder
* failed. Always safe to call — a no-op while idle.
*/
fun stopAndReadBytes(): ByteArray? {
val rec = recorder ?: return null
recorder = null
val file = outFile
outFile = null
return try {
rec.stop()
val bytes = file?.readBytes()
bytes?.takeIf { it.isNotEmpty() }
} catch (e: RuntimeException) {
null
} finally {
rec.release()
file?.delete()
}
}
/**
* Abandon the in-flight take without reading it (the ✕ while
* recording). Always safe to call — a no-op while idle.
*/
fun cancel() {
val rec = recorder ?: return
recorder = null
val file = outFile
outFile = null
runCatching { rec.stop() } // stop() throws if nothing was captured
rec.release()
file?.delete()
}
}
@@ -0,0 +1,836 @@
package org.incido.compose.ui.notelist
import android.graphics.BitmapFactory
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import kotlinx.coroutines.withContext
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PhotoCamera
import androidx.compose.material.icons.filled.Restore
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.ShoppingBasket
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import org.incido.compose.ui.theme.toComposeColor
import org.incido.compose.util.rememberRelativeTimestamp
import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteFilter
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository
/**
* Right-triangle that fills the top-right corner of its bounds — a
* "dog-ear" / folded-page effect used to mark the note's colour.
*/
private val DogEarShape = GenericShape { size, _ ->
// Right-triangle anchored to the top-right corner: vertices at
// (0, 0), (size.width, 0), (size.width, size.height).
moveTo(0f, 0f)
lineTo(size.width, 0f)
lineTo(size.width, size.height)
close()
}
/**
* v0.3.3.5: fixed height for every note card on the list (originally
* 168.dp). v0.3.3.6: tuned down to 143.dp after feedback that 168.dp
* was too tall — ~15 % taller than the pre-0.3.3.5 wrap-content
* typical height (~124 dp for a title + 2-line body preview).
* Identical for every card whether or not the note carries hashtags,
* a body preview, or a checklist summary.
*/
private val CARD_HEIGHT_DP = 143.dp
/**
* v0.3.4.0: overlay palette for cards carrying an image thumbnail.
* The dark scrim (0.45 alpha black) always renders the card background
* dark, so every overlay (title, previews, timestamp, icons) must be
* light regardless of the active theme — in Light mode the default
* `onSurface` / `onSurfaceVariant` are dark and used to render all
* but invisible on dark photos.
*/
private val ThumbTitleColor = Color.White
private val ThumbSecondaryColor = Color.White.copy(alpha = 0.85f)
private val ThumbFavActiveColor = Color(0xFFFFD54F) // light amber — "favourited" stays distinguishable on dark images
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NoteListScreen(
filterMode: NoteFilter,
onOpenDrawer: () -> Unit,
onOpenEditor: (Long?) -> Unit,
/** v0.3.1.0 — used to fetch image bytes for card thumbnails. */
repository: NoteRepository? = null,
viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.Factory),
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
var localQuery by remember { mutableStateOf("") }
var showEmptyTrashDialog by remember { mutableStateOf(false) }
val searchFocusRequester = remember { FocusRequester() }
LaunchedEffect(filterMode) { viewModel.setFilter(filterMode) }
// Auto-focus the search field when it opens so typing can start
// immediately.
LaunchedEffect(state.isSearchActive) {
if (state.isSearchActive) {
runCatching { searchFocusRequester.requestFocus() }
}
}
// "Empty Trash" confirmation. The whole trash goes, attachments
// included — say so plainly before the one tap that does it.
if (showEmptyTrashDialog) {
AlertDialog(
onDismissRequest = { showEmptyTrashDialog = false },
title = { Text("Empty Trash?") },
text = {
Text(
"Every note in the Trash, including attachments, will be " +
"permanently deleted. This cannot be undone.",
)
},
confirmButton = {
TextButton(
onClick = {
showEmptyTrashDialog = false
viewModel.emptyTrash()
},
) {
Text("Empty Trash", color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { showEmptyTrashDialog = false }) {
Text("Cancel")
}
},
)
}
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text(screenTitle(filterMode)) },
navigationIcon = {
IconButton(onClick = onOpenDrawer) {
Icon(Icons.Filled.Menu, contentDescription = "Open menu")
}
},
actions = {
// v0.3.1.0: search is now context-aware on Home,
// Favorites, Untagged, and Trash. ByTag filters already
// narrow by a single tag so the additional text
// query would be ambiguous.
if (filterMode !is NoteFilter.ByTag) {
IconButton(onClick = {
if (state.isSearchActive) viewModel.closeSearch() else viewModel.openSearch()
localQuery = ""
}
) {
Icon(Icons.Default.Search, contentDescription = "Search notes")
}
}
// Trash view gains an "Empty Trash" button whenever it
// holds something; the destructive action is confirmed
// through a dialog before anything is touched.
if (filterMode == NoteFilter.Trash && state.notes.isNotEmpty()) {
IconButton(onClick = { showEmptyTrashDialog = true }) {
Icon(
Icons.Default.DeleteForever,
contentDescription = "Empty trash",
)
}
}
},
)
},
floatingActionButton = {
if (filterMode == NoteFilter.Home) {
FloatingActionButton(onClick = { onOpenEditor(null) }) {
Icon(Icons.Default.Add, contentDescription = "New note")
}
}
},
) { padding ->
Column(modifier = Modifier.padding(padding)) {
if (filterMode !is NoteFilter.ByTag && state.isSearchActive) {
OutlinedTextField(
value = localQuery,
onValueChange = {
localQuery = it
viewModel.onQueryChange(it)
},
placeholder = {
Text(if (filterMode == NoteFilter.Trash) "Search trash…" else "Search notes…")
},
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
trailingIcon = {
if (localQuery.isNotEmpty()) {
IconButton(onClick = {
localQuery = ""
viewModel.onQueryChange("")
}) {
Icon(Icons.Default.Close, contentDescription = "Clear search")
}
}
},
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
.focusRequester(searchFocusRequester),
)
}
when {
state.isLoading -> Unit
state.isEmpty -> EmptyState(filterMode = filterMode)
state.noResults -> NoResultsState(filterMode = filterMode)
else -> NoteList(
notes = state.notes,
onClick = { onOpenEditor(it.id) },
onDelete = {
if (filterMode == NoteFilter.Trash) {
viewModel.permanentlyDelete(it)
} else {
viewModel.softDelete(it)
}
},
onRestore = viewModel::restore,
isTrash = filterMode == NoteFilter.Trash,
onToggleFavorite = viewModel::toggleFavorite,
repository = repository,
// v0.3.5.0: ONLY notes whose ciphertext passed the
// startup trial-decrypt check earn the badge.
verifiedEncryptedIds = state.verifiedEncryptedNoteIds,
)
}
}
}
}
private fun screenTitle(filter: NoteFilter): String = when (filter) {
NoteFilter.Home -> "Incido"
NoteFilter.Favorites -> "Favorites"
NoteFilter.Untagged -> "Untagged"
NoteFilter.Drafts -> "Drafts"
NoteFilter.Trash -> "Trash"
is NoteFilter.ByTag -> "#${filter.hashtag}"
is NoteFilter.ByColor -> filter.color.label
}
@Composable
private fun EmptyState(filterMode: NoteFilter) {
val message = when (filterMode) {
NoteFilter.Home -> "No notes yet. Tap + to start."
NoteFilter.Favorites -> "No favourites yet. Tap ⭐ on a card to add one."
NoteFilter.Untagged -> "All notes are tagged. 🎉"
NoteFilter.Drafts -> "No drafts yet. Start typing a new note and it lands here."
NoteFilter.Trash -> "Trash is empty."
is NoteFilter.ByTag -> "No notes tagged #${filterMode.hashtag} yet."
is NoteFilter.ByColor -> "No " + filterMode.color.label.lowercase() + " notes yet. Pick a colour in the editor."
}
Box(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
contentAlignment = Alignment.Center,
) {
Text(
text = message,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun NoResultsState(filterMode: NoteFilter) {
val message = when (filterMode) {
NoteFilter.Home -> "No matching notes."
NoteFilter.Drafts -> "No drafts match your search."
NoteFilter.Trash -> "No notes in Trash match your search."
is NoteFilter.ByColor -> "No matching notes of this colour."
else -> "Nothing here."
}
Box(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
contentAlignment = Alignment.Center,
) {
Text(
text = message,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun NoteList(
notes: List<Note>,
onClick: (Note) -> Unit,
onDelete: (Long) -> Unit,
onRestore: (Long) -> Unit,
isTrash: Boolean,
onToggleFavorite: (Long, Boolean) -> Unit,
/** v0.3.1.0 — threaded through to [NoteCard] for thumbnail loading. */
repository: NoteRepository?,
/**
* v0.3.5.0 — ids of notes that were double-checked (trial GCM
* decrypt succeeded) by the startup / post-migration verification
* pass. Drives the "Encrypted" badge — nothing else does.
*/
verifiedEncryptedIds: Set<Long>,
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(
top = 8.dp,
bottom = 88.dp, // FAB clearance
start = 16.dp,
end = 16.dp,
),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
items(items = notes, key = { it.id }) { note ->
NoteCard(
note = note,
onClick = { if (!isTrash) onClick(note) },
onDelete = { onDelete(note.id) },
onRestore = { onRestore(note.id) },
isTrash = isTrash,
onToggleFavorite = { onToggleFavorite(note.id, !note.isFavorite) },
repository = repository,
showEncryptionBadge = note.id in verifiedEncryptedIds,
)
}
}
}
/**
* v0.3.0.1 card layout:
* - 14 dp vertical gradient stripe down the left edge
* - Tinted card surface (12 % colour blend over the M3 surface)
* - Dog-ear colour accent in the top-right corner (replaces the old
* circle chip next to the star)
* - Title + body preview + checklist summary + hashtag row +
* timestamp
* - Hashtag row is hidden entirely when the note has no tags.
*
* v0.3.3.0:
* - The bottom-right delete `IconButton` is gone.
* - A long-press anywhere on the card opens a `DropdownMenu` anchored on
* the card itself. Active cards offer "Delete"; Trash cards offer
* "Restore" and permanent "Delete" without opening the editor.
* - Card now uses `Modifier.combinedClickable` for click + long-click.
*
* v0.3.3.5:
* - Cards now have a FIXED height ([CARD_HEIGHT_DP]) so every card
* is the same size regardless of whether the note has tags, a body
* preview, or a checklist summary. Shipped at 168 dp.
* - A `Spacer(weight(1f))` pushes the timestamp row to the bottom of
* the fixed-height card so the layout stays visually consistent.
* - The left colour stripe now spans the full card height instead of
* a hardcoded 110 dp.
*
* v0.3.3.6:
* - [CARD_HEIGHT_DP] reduced 168 dp → 143 dp (~15 % shorter) after
* feedback that the v0.3.3.5 cards were too tall; still ~15 %
* taller than the pre-0.3.3.5 wrap-content typical.
*
* v0.3.4.0:
* - Attachment indicator: a paperclip icon appears on the right edge
* whenever the note carries at least one attachment (image, PDF,
* audio…). It sits in the same vertical column as the ⋮ overflow
* button (top) and the favourite star (bottom), exactly halfway
* between them via `Alignment.CenterEnd` on the fixed-height card.
* - Thumbnail readability: when an image thumbnail is present the
* scrim guarantees a dark background, so all overlay text/icons
* switch to a light palette regardless of theme (fixes invisible
* dark-on-dark text in Light mode).
*/
@OptIn(ExperimentalLayoutApi::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun NoteCard(
note: Note,
onClick: () -> Unit,
onDelete: () -> Unit,
onRestore: () -> Unit,
isTrash: Boolean,
onToggleFavorite: () -> Unit,
/** v0.3.1.0 — used to load the first image attachment as a
* thumbnail background. Null disables the feature (still works). */
repository: NoteRepository?,
/**
* v0.3.5.0 — true only when this note's ciphertext was verified
* decryptable by the startup integrity check (never inferred from
* the settings flag alone).
*
* v0.3.5.1 — renders a small lock icon immediately to the LEFT of
* the timestamp in the card's bottom row (vertically centred with
* the date/time). Replaces the previous lock-plus-"Encrypted"-label
* Row that was centred at the card's bottom edge.
*/
showEncryptionBadge: Boolean = false,
) {
// v0.3.8.0: task / shopping lists render marker-free on cards —
// header line becomes the title, items show as clean "Name ×qty @$X"
// text. The checkbox state lives in the summary row below instead.
// v0.4.2.0: voice notes carry a plain prose body (title = first
// line), so they split like TEXT — the cardPresentation list parser
// would mangle their content.
val (title, body) =
if (note.type == NoteType.TEXT || note.type == NoteType.VOICE_NOTE)
Note.titleAndBody(note.content)
else Note.cardPresentation(note.content, note.type)
// Drafts with no title introduce themselves by kind — "Shopping
// List - (draft)" beats a bare "Untitled" in the Drafts view. The
// stored content is untouched; this is display-only, so typing a
// real title (or publishing) reverts the card to normal instantly.
val displayTitle =
if (note.isDraft && title == Note.UNTITLED)
"${note.type.displayName} - (draft)"
else title
val bodyPreview = Note.bodyPreview(body)
val checklistSummary = Note.checklistSummary(note.content)
val noteColor = note.color
val hasColor = noteColor != NoteColor.NONE
val firstImage: NoteAttachment? = note.firstImageAttachment
// v0.3.1.0: load the first image attachment's bytes + decode
// a downsampled bitmap for the card background. The produceState
// scopes the work to the card's lifetime, so off-screen cards
// don't keep their bitmaps alive.
val thumbnailBitmap by produceState<android.graphics.Bitmap?>(initialValue = null, key1 = firstImage?.id) {
if (firstImage == null || repository == null) {
value = null
} else {
value = withContext(kotlinx.coroutines.Dispatchers.IO) {
val bytes = repository.getAttachmentBytes(firstImage.id) ?: return@withContext null
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
}
}
// v0.3.1.2: when a thumbnail is present the Card's container goes
// transparent so the image (rendered INSIDE the card below) shows
// through, and the dark scrim provides the contrast for the text
// overlay. When there's no image, fall back to the existing
// tinted/surface behaviour so plain notes look unchanged.
val containerColor = when {
thumbnailBitmap != null -> Color.Transparent
hasColor -> lerp(MaterialTheme.colorScheme.surface, noteColor.toComposeColor(), 0.12f)
else -> MaterialTheme.colorScheme.surface
}
// v0.3.4.0: overlay colours resolved once. With a thumbnail the
// scrim makes the background dark → force the light palette; plain
// cards keep the theme defaults.
val hasThumbnail = thumbnailBitmap != null
val titleColor = if (hasThumbnail) ThumbTitleColor else MaterialTheme.colorScheme.onSurface
val secondaryColor = if (hasThumbnail) ThumbSecondaryColor else MaterialTheme.colorScheme.onSurfaceVariant
val hashtagColor = if (hasThumbnail) ThumbTitleColor else MaterialTheme.colorScheme.primary
val favoriteActiveColor = if (hasThumbnail) ThumbFavActiveColor else MaterialTheme.colorScheme.primary
// v0.3.3.0: per-card menu visibility. Long-press opens; tapping
// outside the menu (or selecting an item) closes it.
var showMenu by remember { mutableStateOf(false) }
Card(
modifier = Modifier
.fillMaxWidth()
// v0.3.3.5: fixed card height — consistent size for every
// card, with or without tags / body preview / checklist.
.height(CARD_HEIGHT_DP)
.combinedClickable(
onClick = onClick,
onLongClick = { showMenu = true },
),
colors = CardDefaults.cardColors(
containerColor = containerColor,
// v0.3.4.0: on an image thumbnail the scrim darkens the
// background — default the content colour to light so any
// inheriting composables stay readable.
contentColor = if (hasThumbnail) Color.White else MaterialTheme.colorScheme.onSurface,
),
) {
// Inner Box hosts the (optional) thumbnail + scrim behind the
// existing Row of text content, with the dog-ear overlay
// sitting on top of everything. The Card itself clips to its
// rounded corners, so the thumbnail can't bleed past the
// card's rounded shape.
Box(modifier = Modifier.fillMaxWidth()) {
// v0.3.1.2: thumbnail + dark scrim live INSIDE the card so
// they're not hidden behind an opaque container surface
// (the v0.3.1.0 / v0.3.1.1 layout had them as siblings of
// the Card, which is why the image looked invisible — the
// Card's opaque containerColor was drawn on top of them).
if (thumbnailBitmap != null) {
Image(
bitmap = thumbnailBitmap!!.asImageBitmap(),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.matchParentSize(),
)
// Dark scrim — the "fill color, like an overlay" —
// keeps the text readable on bright photos.
Box(
modifier = Modifier
.matchParentSize()
.background(Color.Black.copy(alpha = 0.45f)),
)
}
Row(modifier = Modifier.fillMaxWidth()) {
if (hasColor) {
Box(
modifier = Modifier
// v0.3.3.5: stripe spans the full height of
// the now-fixed-height card.
.fillMaxHeight()
.width(14.dp)
.background(
Brush.verticalGradient(
colors = listOf(
noteColor.toComposeColor().copy(alpha = 0.95f),
noteColor.toComposeColor().copy(alpha = 0.05f),
),
)
),
)
}
Column(modifier = Modifier.padding(16.dp).fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = displayTitle,
style = MaterialTheme.typography.titleMedium,
color = titleColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
}
if (bodyPreview.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp))
Text(
text = bodyPreview,
style = MaterialTheme.typography.bodyMedium,
color = secondaryColor,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
if (checklistSummary.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
// v0.3.8.0: shopping lists carry a basket
// on the card instead of the plain check box.
imageVector = if (note.type == NoteType.SHOPPING_LIST)
Icons.Default.ShoppingBasket
else Icons.Default.CheckBox,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = secondaryColor,
)
Spacer(Modifier.size(6.dp))
Text(
text = checklistSummary,
style = MaterialTheme.typography.labelSmall,
color = secondaryColor,
)
}
}
if (note.type == NoteType.VOICE_NOTE) {
// v0.4.2.0: voice notes carry a mic badge so the
// kind is recognisable on the card even when the
// body is empty (the take itself is an audio
// attachment, not visible as a thumbnail).
Spacer(modifier = Modifier.padding(top = 4.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Default.Mic,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = secondaryColor,
)
Spacer(Modifier.size(6.dp))
Text(
text = note.type.displayName,
style = MaterialTheme.typography.labelSmall,
color = secondaryColor,
)
}
}
if (note.hashtags.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp))
HashtagRow(
hashtags = note.hashtags,
tagColor = hashtagColor,
overflowColor = secondaryColor,
)
}
// v0.3.3.5: flexible spacer pushes the timestamp to
// the bottom of the fixed-height card so every card
// has a consistent layout.
Spacer(modifier = Modifier.weight(1f))
// v0.3.3.0: bottom row now only shows the
// timestamp — the overflow (long-press) menu holds
// the destructive action.
//
// v0.3.5.1: when the note is verified-encrypted a
// 14 dp lock icon sits immediately to the LEFT of
// the timestamp in this same row, vertically
// centred via the row's Alignment.CenterVertically
// — consistent placement on every card.
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
if (showEncryptionBadge) {
Icon(
Icons.Filled.Lock,
contentDescription = "Encrypted",
tint = secondaryColor,
modifier = Modifier.size(14.dp),
)
Spacer(Modifier.size(4.dp))
}
Text(
text = rememberRelativeTimestamp(note.updatedAt),
style = MaterialTheme.typography.labelSmall,
color = secondaryColor,
)
}
}
}
// v0.3.0.1: dog-ear colour accent overlays the top-right
// corner. Now sits INSIDE the card's inner Box so it stacks
// on top of the thumbnail + scrim + content correctly.
if (hasColor) {
Box(
modifier = Modifier
.align(Alignment.TopEnd)
.size(28.dp)
.background(
color = noteColor.toComposeColor(),
shape = DogEarShape,
),
)
}
// v0.3.3.0: overflow menu anchored to the card's top-right
// corner. Long-press anywhere on the card pops it open.
// Designed to host additional entries (Share, etc.) as we
// add them.
Box(modifier = Modifier.align(Alignment.TopEnd).padding(end = 4.dp, top = 4.dp)) {
IconButton(onClick = { showMenu = true }) {
Icon(
Icons.Filled.MoreVert,
contentDescription = "More actions",
tint = secondaryColor,
)
}
DropdownMenu(
expanded = showMenu,
onDismissRequest = { showMenu = false },
) {
if (isTrash) {
DropdownMenuItem(
text = { Text("Restore") },
leadingIcon = {
Icon(
Icons.Filled.Restore,
contentDescription = null,
)
},
onClick = {
showMenu = false
onRestore()
},
)
}
DropdownMenuItem(
text = { Text(if (isTrash) "Delete permanently" else "Delete") },
leadingIcon = {
Icon(
Icons.Filled.Delete,
contentDescription = null,
tint = MaterialTheme.colorScheme.error,
)
},
onClick = {
showMenu = false
onDelete()
},
)
}
}
// v0.3.5.1: the "Encrypted" indicator moved from a
// bottom-centre Row (lock icon + "Encrypted" label) to a
// lock icon sitting immediately to the left of the
// timestamp inside the card's bottom row, so its position
// stays consistent on every card. Rendered ONLY when the
// note passed the verification pass (trial GCM decrypt
// with the current Keystore key); re-checked on every app
// open, so a corrupted or re-keyed row silently drops it
// until it verifies again.
// Hotfix: favorite star moved from the title row to the
// bottom-right corner, vertically aligned with the
// three-dot overflow button above.
if (!isTrash) {
Box(modifier = Modifier.align(Alignment.BottomEnd).padding(end = 4.dp, bottom = 4.dp)) {
IconButton(onClick = onToggleFavorite) {
Icon(
imageVector = if (note.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
contentDescription = if (note.isFavorite) "Unfavorite" else "Favorite",
tint = if (note.isFavorite) favoriteActiveColor
else secondaryColor,
)
}
}
}
// v0.3.4.0: attachment indicator — a paperclip shown
// whenever the note carries at least one attachment (any
// type: image, PDF, audio…). Aligned CenterEnd so it sits
// in the same vertical column as the ⋮ overflow button
// above and the favourite star below, exactly halfway
// between them: the card has a fixed height and both
// neighbours are anchored symmetrically in the top / bottom
// corners (their 24 dp glyphs centred in 48 dp IconButtons
// with end = 4.dp padding ⇒ glyph centres at 28 dp from the
// right edge; the midpoint of those two centres IS the card
// centre). The `end = 16.dp` offset places this bare 24 dp
// Icon's glyph centre at the same 28 dp column. Rendered as
// a plain Icon (not an IconButton) so it never intercepts
// the whole-card tap that opens the editor.
if (note.attachments.isNotEmpty()) {
Icon(
Icons.Filled.AttachFile,
contentDescription = "Has attachments",
tint = secondaryColor,
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = 16.dp)
.size(24.dp),
)
}
}
}
}
/**
* v0.3.0.1: hashtag list on the card. Shows up to three tags as a
* compact FlowRow of label-styled text; if there are more, renders a
* "+N" abbreviation indicator. Hidden entirely by the caller when
* [hashtags] is empty.
*
* v0.3.4.0: colours are supplied by the caller — light palette on
* image-thumbnail cards, theme defaults elsewhere.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun HashtagRow(
hashtags: List<String>,
/** Colour for the visible "#tag" chips. */
tagColor: Color,
/** Colour for the "+N" overflow indicator. */
overflowColor: Color,
) {
val visible = hashtags.take(3)
val overflow = hashtags.size - visible.size
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
visible.forEach { tag ->
Text(
text = "#$tag",
style = MaterialTheme.typography.labelSmall,
color = tagColor,
)
}
if (overflow > 0) {
Text(
text = "+$overflow",
style = MaterialTheme.typography.labelSmall,
color = overflowColor,
)
}
}
}
@@ -0,0 +1,188 @@
package org.incido.compose.ui.notelist
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication
import org.incido.domain.model.HashtagUsage
import org.incido.domain.model.Note
import org.incido.domain.model.NoteFilter
import org.incido.domain.repository.NoteRepository
/**
* Immutable UI state for [NoteListScreen].
*/
data class NoteListUiState(
val notes: List<Note> = emptyList(),
val isLoading: Boolean = true,
val searchQuery: String = "",
val isSearchActive: Boolean = false,
val filter: NoteFilter = NoteFilter.Home,
val recentHashtags: List<HashtagUsage> = emptyList(),
/**
* v0.3.5.0 — note ids whose ciphertext was **verified** (trial
* GCM-decrypt succeeded) by the startup / post-migration check.
* This — and ONLY this — drives the "Encrypted" badge on cards.
* Re-populated on every app open.
*/
val verifiedEncryptedNoteIds: Set<Long> = emptySet(),
/** Encrypted rows that FAILED verification (corrupted / wrong key). */
val unverifiedEncryptedNoteCount: Int = 0,
) {
val isEmpty: Boolean
get() = !isLoading && notes.isEmpty() && !isSearchActive &&
(filter == NoteFilter.Home || filter == NoteFilter.Trash ||
filter == NoteFilter.Drafts)
val noResults: Boolean get() = !isLoading && notes.isEmpty() && !isEmpty
}
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class NoteListViewModel(
private val repository: NoteRepository,
/** v0.3.5.0 — source of the verified-encryption badge set. */
private val encryptionVerifier: org.incido.data.crypto.EncryptionVerifier? = null,
) : ViewModel() {
private val filterMode = MutableStateFlow<NoteFilter>(NoteFilter.Home)
private val rawQuery = MutableStateFlow("")
private val _isSearchActive = MutableStateFlow(false)
/** Notes stream — switches on (filter, query) so the same ViewModel
* instance handles Home, Favorites, Untagged, ByTag, and search.
*
* v0.3.1.0: search is now **context-aware** — on Favorites,
* Untagged, and Trash, the typed query is intersected with the
* active filter rather than ignored. On Home, search spans all
* active notes. ByTag keeps the same behaviour (the tag itself is
* already the filter). */
private val notesFlow = combine(filterMode, rawQuery) { f, q -> f to q }
.flatMapLatest { (f, q) ->
when (f) {
NoteFilter.Home -> if (q.isBlank()) repository.observeAll() else repository.search(q)
NoteFilter.Favorites -> if (q.isBlank()) repository.observeFavorites() else repository.searchFavorites(q)
NoteFilter.Untagged -> if (q.isBlank()) repository.observeUntagged() else repository.searchUntagged(q)
NoteFilter.Drafts -> if (q.isBlank()) repository.observeDrafts() else repository.searchDrafts(q)
NoteFilter.Trash -> if (q.isBlank()) repository.observeTrashed() else repository.searchTrashed(q)
is NoteFilter.ByTag -> repository.observeNotesForHashtag(f.hashtag)
is NoteFilter.ByColor ->
if (q.isBlank()) repository.observeByColor(f.color) else repository.searchByColor(q, f.color)
}
}
private val baseUiState: StateFlow<NoteListUiState> = combine(
notesFlow,
_isSearchActive,
filterMode,
rawQuery,
repository.observeHashtagsByRecentUse(),
) { notes, searchActive, filter, query, recent ->
NoteListUiState(
notes = notes,
isLoading = false,
searchQuery = query,
isSearchActive = searchActive,
filter = filter,
recentHashtags = recent,
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NoteListUiState(),
)
/**
* v0.3.5.0 — merge the verification results into the UI state. The
* verifier re-checks every encrypted row on every app open (and
* after each encryption migration), so a card's badge always
* reflects a fresh proof-of-decryptability, never just the
* settings flag.
*/
val uiState: StateFlow<NoteListUiState> = combine(
baseUiState,
encryptionVerifier?.verification
?: kotlinx.coroutines.flow.flowOf(null),
) { state, verification ->
state.copy(
verifiedEncryptedNoteIds = verification?.verifiedNoteIds ?: emptySet(),
unverifiedEncryptedNoteCount = verification?.failedNoteIds?.size ?: 0,
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NoteListUiState(),
)
fun setFilter(filter: NoteFilter) {
filterMode.value = filter
// v0.3.1.0: search is now context-aware on Home / Favorites /
// Untagged. Closing the search bar only makes sense when
// switching to a ByTag filter (the tag itself is the filter,
// so an additional text query would be ambiguous).
if (filter is NoteFilter.ByTag && _isSearchActive.value) {
_isSearchActive.value = false
rawQuery.value = ""
}
}
fun onQueryChange(q: String) {
rawQuery.value = q
}
fun openSearch() {
_isSearchActive.value = true
}
fun closeSearch() {
_isSearchActive.value = false
rawQuery.value = ""
}
/** Move an active note to Trash. */
fun softDelete(id: Long) {
viewModelScope.launch { repository.softDelete(id) }
}
/** Permanently destroy a note from the Trash view. */
fun permanentlyDelete(id: Long) {
viewModelScope.launch { repository.delete(id) }
}
/** "Empty Trash": permanently destroy every note in the Trash. */
fun emptyTrash() {
viewModelScope.launch { repository.deleteAllTrashed() }
}
/** Restore a note from Trash. */
fun restore(id: Long) {
viewModelScope.launch { repository.restore(id) }
}
fun toggleFavorite(id: Long, isFavorite: Boolean) {
viewModelScope.launch { repository.setFavorite(id, isFavorite) }
}
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
NoteListViewModel(
repository = app.container.noteRepository,
encryptionVerifier = app.container.encryptionVerifier,
)
}
}
}
}
@@ -0,0 +1,278 @@
package org.incido.compose.ui.settings
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.text.KeyboardOptions
import org.incido.compose.data.backup.PassphraseGenerator
import org.incido.compose.data.settings.PasswordPolicy
/**
* v0.3.2.0: passphrase entry / generation / copy dialog for encrypted
* backups.
*
* Two text fields — passphrase + confirm — with live validation
* feedback. The "Generate" button fills both fields with a fresh
* SecureRandom passphrase that satisfies [PasswordPolicy]. The
* "Copy" button pushes the current value onto the system clipboard.
*
* The OK button is enabled only when both fields match **and** the
* value passes the policy. The user can dismiss at any time.
*
* v0.3.3.0: [mode] switches between EXPORT (creating a new passphrase)
* and IMPORT (decrypting an existing backup). The title, supporting
* copy, and confirm-button label adapt accordingly.
*
* v0.3.3.1 hotfix: the IMPORT flow now also drops the EXPORT-only
* chrome — the second "Confirm passphrase" field, the "Generate" /
* "Copy" trailing-icon buttons, and the live password-policy check
* are all suppressed in IMPORT mode. An existing passphrase may
* have been created before the current policy was tightened, so
* the encryption round-trip (decrypt-on-preview) is the source of
* truth for "is this passphrase correct", surfaced as
* "Incorrect passphrase." via snackbar on mismatch.
*/
@Composable
fun PassphraseDialog(
onConfirm: (CharArray) -> Unit,
onDismiss: () -> Unit,
mode: PassphraseDialogMode = PassphraseDialogMode.EXPORT,
) {
val context = LocalContext.current
// v0.3.6.0: use the enum helper so RECOVERY_EXPORT shares the
// EXPORT chrome (policy check, Generate/Copy, Confirm field).
val isExport = mode.isExport
var passphrase by remember { mutableStateOf("") }
var confirm by remember { mutableStateOf("") }
var revealed by remember { mutableStateOf(false) }
var copied by remember { mutableStateOf(false) }
// v0.3.3.1 hotfix: IMPORT mode only needs a single passphrase
// field — skip the password policy check because an existing
// passphrase (created before the policy was tightened) might
// not satisfy it. The encryption round-trip is the source of
// truth: if the passphrase is wrong, the decrypt / preview step
// surfaces "Incorrect passphrase." via the snackbar.
val validation = remember(passphrase, isExport) {
if (isExport) {
PasswordPolicy.validate(passphrase)
} else {
// Empty failure set — `isValid == true`, but the UI
// never enters this branch for IMPORT (we don't render
// the policy failure list / isError state there).
PasswordPolicy.Validation(failures = emptySet())
}
}
val matches = passphrase.isNotEmpty() && passphrase == confirm
val canConfirm = if (isExport) {
validation.isValid && matches
} else {
passphrase.isNotEmpty()
}
// Reset the "copied" hint after a few seconds.
LaunchedEffect(copied) {
if (copied) {
kotlinx.coroutines.delay(2000)
copied = false
}
}
// v0.3.6.0: the recovery-key flows reuse this dialog but get
// their own titles / copy so the user knows they're protecting
// the encryption key, not a note backup.
val title = when (mode) {
PassphraseDialogMode.EXPORT -> "Encrypt backup"
PassphraseDialogMode.IMPORT -> "Decrypt backup"
PassphraseDialogMode.RECOVERY_EXPORT -> "Protect recovery key"
PassphraseDialogMode.RECOVERY_IMPORT -> "Unlock recovery key"
}
val intro = when (mode) {
PassphraseDialogMode.EXPORT ->
"Choose a passphrase to protect this backup. " +
"You'll need it again to restore. Lost passphrases " +
"cannot be recovered."
PassphraseDialogMode.IMPORT ->
"Enter the passphrase you used when this backup was created. " +
"Lost passphrases cannot be recovered."
PassphraseDialogMode.RECOVERY_EXPORT ->
"Choose a passphrase to protect your encryption key. " +
"You'll need this passphrase AND the exported file to " +
"restore the key on another device. Store them in " +
"separate safe places."
PassphraseDialogMode.RECOVERY_IMPORT ->
"Enter the passphrase you used when you exported this " +
"recovery key. Lost passphrases cannot be recovered."
}
val confirmLabel = when (mode) {
PassphraseDialogMode.EXPORT -> "Encrypt & export"
PassphraseDialogMode.RECOVERY_EXPORT -> "Encrypt & export"
else -> "Continue"
}
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
Column(modifier = Modifier.fillMaxWidth()) {
Text(
text = intro,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.padding(top = 12.dp))
OutlinedTextField(
value = passphrase,
onValueChange = { passphrase = it; confirm = "" },
label = { Text("Passphrase") },
singleLine = true,
visualTransformation = if (revealed) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
// v0.3.3.1 hotfix: IMPORT mode renders only the
// visibility toggle — Generate / Copy are
// nonsensical for an existing passphrase.
trailingIcon = {
Row {
IconButton(onClick = { revealed = !revealed }) {
Icon(
imageVector = if (revealed) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = if (revealed) "Hide" else "Show",
)
}
if (isExport) {
IconButton(onClick = {
passphrase = PassphraseGenerator.generate()
confirm = passphrase
copied = false
}) {
Icon(Icons.Filled.Refresh, contentDescription = "Generate")
}
IconButton(onClick = {
copyToClipboard(context, passphrase)
copied = true
}) {
Icon(Icons.Filled.ContentCopy, contentDescription = "Copy")
}
}
}
},
isError = passphrase.isNotEmpty() && !validation.isValid,
modifier = Modifier.fillMaxWidth(),
)
if (isExport && passphrase.isNotEmpty() && !validation.isValid) {
Spacer(Modifier.padding(top = 4.dp))
validation.failures.forEach { failure ->
Text(
text = PasswordPolicy.describe(failure),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error,
)
}
}
if (copied) {
Spacer(Modifier.padding(top = 4.dp))
Text(
text = "Copied to clipboard.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
if (isExport) {
// v0.3.3.1 hotfix: Confirm passphrase field is
// EXPORT-only — IMPORT only needs a single field.
Spacer(Modifier.padding(top = 12.dp))
OutlinedTextField(
value = confirm,
onValueChange = { confirm = it },
label = { Text("Confirm passphrase") },
singleLine = true,
visualTransformation = if (revealed) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
isError = confirm.isNotEmpty() && !matches,
supportingText = {
if (confirm.isNotEmpty() && !matches) {
Text("Passphrases don't match.")
} else {
Text(
"${PasswordPolicy.MIN_LENGTH}–${PasswordPolicy.MAX_LENGTH} chars, " +
"with at least one digit and one special character.",
style = MaterialTheme.typography.labelSmall,
)
}
},
modifier = Modifier.fillMaxWidth(),
)
}
}
},
confirmButton = {
TextButton(
onClick = {
onConfirm(passphrase.toCharArray())
passphrase = ""
confirm = ""
},
enabled = canConfirm,
) { Text(confirmLabel) }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text("Cancel") }
},
)
}
/**
* v0.3.3.0: which flow is requesting a passphrase. The EXPORT /
* IMPORT pair covers the encrypted backup flows; v0.3.6.0 adds the
* RECOVERY_EXPORT / RECOVERY_IMPORT pair for the at-rest key
* recovery file (UI is the same — [PassphraseDialog] just looks at
* the EXPORT vs IMPORT flag and shows the policy / Generate / Copy
* chrome accordingly).
*/
enum class PassphraseDialogMode {
EXPORT, IMPORT,
RECOVERY_EXPORT, RECOVERY_IMPORT,
;
/** True for the EXPORT-mode chrome (Generate / Copy / Confirm /
* password-policy check). Import variants skip those because
* an existing passphrase may predate the current policy. */
val isExport: Boolean get() = this == EXPORT || this == RECOVERY_EXPORT
}
private fun copyToClipboard(context: Context, value: String) {
if (value.isEmpty()) return
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cm.setPrimaryClip(ClipData.newPlainText("Incido backup passphrase", value))
}
@@ -0,0 +1,87 @@
package org.incido.compose.ui.settings
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.incido.compose.data.settings.ReleaseNote
import org.incido.compose.data.settings.ReleaseNotes
/**
* v0.3.2.0: scrollable list of the 5 most recent release notes.
*
* Shown when the user taps the version number on the settings screen.
* The dialog body is a vertical scroll so a future bump to 10 entries
* still fits comfortably on small screens.
*/
@Composable
fun ReleaseNotesDialog(onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("What's new") },
text = {
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 480.dp)
.verticalScroll(rememberScrollState()),
) {
ReleaseNotes.RECENT.forEachIndexed { index, note ->
ReleaseNoteCard(note)
if (index < ReleaseNotes.RECENT.lastIndex) {
HorizontalDivider(modifier = Modifier.padding(vertical = 12.dp))
}
}
}
},
confirmButton = {
TextButton(onClick = onDismiss) { Text("Close") }
},
)
}
@Composable
private fun ReleaseNoteCard(note: ReleaseNote) {
Column(modifier = Modifier.fillMaxWidth()) {
Text(
text = "v${note.version}",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
Text(
text = note.date,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.padding(top = 6.dp))
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
note.bullets.forEach { bullet ->
BulletRow(bullet)
}
}
}
}
@Composable
private fun BulletRow(text: String) {
// Plain Text with manual bullet glyph — keeps it lightweight and
// avoids a nested Row + Icon for every entry.
Text(
text = "• $text",
style = MaterialTheme.typography.bodyMedium,
)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,382 @@
package org.incido.compose.ui.settings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication
import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.backup.CarnetImporter
import org.incido.compose.data.security.ObjectBoxKeyProvider
import org.incido.compose.data.security.SecurityManager
import org.incido.data.crypto.AesGcmFieldCipher
import org.incido.data.crypto.CipherHolder
import org.incido.data.crypto.EncryptionVerifier
import org.incido.data.crypto.NoteCryptoService
import org.incido.compose.data.settings.AutoLockTimeout
import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.data.settings.ThemeMode
import org.incido.compose.data.settings.UserSettings
/**
* v0.3.2.0: ViewModel for the Settings screen.
*
* - Reads the current [UserSettings] as a [StateFlow] so the UI
* recomposes on toggle changes.
* - Exposes a single [migrationState] flow that the UI binds to a
* modal "Re-encrypting notes…" dialog.
* - Surfaces high-level intent functions (`setThemeMode`,
* `setSecurityEnabled`, …) that the screen's switch / segmented
* button callbacks delegate to.
*
* v0.3.3.0: lock mode is now a mutually-exclusive choice between PIN
* and biometric. [setLockMode] is the single entry point — it writes
* the matching DataStore flags atomically and wipes the stored PIN
* when switching to biometric.
*/
class SettingsViewModel(
private val settings: SettingsRepository,
private val security: SecurityManager,
private val objectBoxKeyProvider: ObjectBoxKeyProvider,
private val backupManager: BackupManager,
private val carnetImporter: CarnetImporter,
private val noteCryptoService: NoteCryptoService,
private val cipherHolder: CipherHolder,
private val encryptionVerifier: EncryptionVerifier,
) : ViewModel() {
val userSettings: StateFlow<UserSettings> = settings.userSettingsFlow.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = UserSettings(),
)
private val _migrationState = MutableStateFlow<MigrationState>(MigrationState.Idle)
val migrationState: StateFlow<MigrationState> = _migrationState.asStateFlow()
private val _snackbar = MutableStateFlow<String?>(null)
val snackbar: StateFlow<String?> = _snackbar.asStateFlow()
fun dismissSnackbar() { _snackbar.value = null }
// --- Appearance ---
fun setThemeMode(mode: ThemeMode) = viewModelScope.launch {
settings.setThemeMode(mode)
}
fun setDynamicColor(enabled: Boolean) = viewModelScope.launch {
settings.setDynamicColor(enabled)
}
// --- Security ---
fun setSecurityEnabled(enabled: Boolean) = viewModelScope.launch {
if (enabled) {
// v0.3.3.1 hotfix: flipping the master switch on no longer
// requires a PIN/Biometric to be configured first. The
// sub-toggles (PIN / Biometric / Encrypt) are greyed in the
// UI until Security is on; the user can then pick one of
// them at their leisure. Previously this branch forced
// securityEnabled=false and surfaced a snackbar, which
// created a chicken-and-egg with the PIN toggle being
// greyed while Security was off.
settings.setSecurityEnabled(true)
return@launch
}
// Disabling: decrypt any encrypted rows first (so the notes
// remain readable once the key goes), then clear every sub-flag
// + wipe the stored PIN hash/salt + drop the encryption key.
// v0.3.5.0: real decrypt sweep instead of the old no-op.
_migrationState.value = MigrationState.Running(0f)
try {
if (cipherHolder.cipher != null) {
noteCryptoService.decryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
cipherHolder.cipher = null
}
settings.setSecurityEnabled(false)
settings.setPinEnabled(false)
settings.setEncryptionEnabled(false)
settings.setUseBiometric(false)
security.clearPin()
objectBoxKeyProvider.deleteKey()
_migrationState.value = MigrationState.Idle
encryptionVerifier.checkNow()
_snackbar.value = "Security disabled."
} catch (t: Throwable) {
_migrationState.value = MigrationState.Failed(t.message ?: "Decryption failed")
}
}
/**
* v0.3.5.0 — the toggle now performs a REAL in-place migration and
* takes effect immediately (no app restart):
*
* - ENABLE: generate/unwrap the Keystore key, install the cipher
* into the shared [CipherHolder] (so every concurrent write is
* already encrypted), then sweep every plaintext note +
* attachment row into ciphertext with live progress.
* - DISABLE: decrypt every row back to plaintext first, then
* remove the cipher from the holder and delete the key.
*
* Either way the startup verifier re-checks afterwards, so the
* "Encrypted" badge on the cards always reflects rows that are
* provably decryptable.
*/
fun setEncryptionEnabled(enabled: Boolean) = viewModelScope.launch {
if (!_migrationState.value.canStart) return@launch
_migrationState.value = MigrationState.Running(0f)
try {
if (enabled) {
// Key first (idempotent), cipher into the holder, sweep.
objectBoxKeyProvider.getOrCreateKey()
cipherHolder.cipher =
AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
noteCryptoService.encryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
settings.setEncryptionEnabled(true)
_migrationState.value = MigrationState.Done(
message = "Notes are now encrypted on this device.",
)
} else {
noteCryptoService.decryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
cipherHolder.cipher = null
objectBoxKeyProvider.deleteKey()
settings.setEncryptionEnabled(false)
_migrationState.value = MigrationState.Done(
message = "Notes are now stored unencrypted.",
)
}
// Re-verify so the badge set matches the new on-disk state.
encryptionVerifier.checkNow()
} catch (t: Throwable) {
_migrationState.value = MigrationState.Failed(t.message ?: "Migration failed")
}
}
/** v0.3.5.0 — FLAG_SECURE screenshot / recording blocking. */
fun setBlockScreenshots(enabled: Boolean) = viewModelScope.launch {
settings.setBlockScreenshots(enabled)
}
/**
* v0.3.3.0: switch the lock mode. Mutually exclusive — enabling
* one wipes the other. Switching to [LockMode.NONE] disables both
* flags and clears the stored PIN.
*
* If the caller enables [LockMode.PIN] for the first time, the
* PIN itself is not set here (caller routes to PinSetupScreen).
* Subsequent calls just flip the flag back on if needed.
*/
fun setLockMode(mode: LockMode) = viewModelScope.launch {
when (mode) {
LockMode.NONE -> {
settings.setPinEnabled(false)
settings.setUseBiometric(false)
security.clearPin()
}
LockMode.PIN -> {
settings.setUseBiometric(false)
// Don't overwrite the stored hash if one exists — just
// make sure the flag reflects it. setNewPin() handles
// the actual write when the user confirms a new PIN.
if (security.hasPinBlocking()) {
settings.setPinEnabled(true)
} else {
settings.setPinEnabled(true)
}
}
LockMode.BIOMETRIC -> {
settings.setPinEnabled(false)
settings.setUseBiometric(true)
security.clearPin()
}
}
}
fun setAutoLockTimeout(timeout: AutoLockTimeout) = viewModelScope.launch {
settings.setAutoLockTimeout(timeout)
}
// --- PIN management (called from PinSetupScreen / PinChangeScreen) ---
suspend fun setNewPin(pin: CharArray) {
security.setupPin(pin)
}
suspend fun changePin(oldPin: CharArray, newPin: CharArray) {
security.changePin(oldPin, newPin)
}
suspend fun hasPin(): Boolean = security.hasPin()
// --- Backup ---
suspend fun exportPlain(uri: android.net.Uri) {
backupManager.exportPlain(uri, appVersion = APP_VERSION)
_snackbar.value = "Backup exported."
}
suspend fun exportEncrypted(uri: android.net.Uri, passphrase: CharArray) {
backupManager.exportEncrypted(uri, passphrase, appVersion = APP_VERSION)
_snackbar.value = "Encrypted backup exported. Store the passphrase safely."
}
suspend fun previewImport(uri: android.net.Uri, passphrase: CharArray? = null) =
backupManager.preview(uri, passphrase)
suspend fun import(uri: android.net.Uri, passphrase: CharArray? = null) {
val result = backupManager.import(uri, passphrase)
_snackbar.value = if (result.skipped > 0) {
"Imported ${result.imported} note(s), skipped ${result.skipped} already imported."
} else {
"Imported ${result.imported} note(s)."
}
}
/**
* v0.3.9.0 — import a Carnet / QuickNote archive (`.zip` of `*.sqd`, or a
* single `.sqd`) picked via SAF. Additive — existing notes are kept.
* Failures are caught and surfaced via the snackbar so a bad file never
* crashes the app.
*/
suspend fun importCarnet(uri: android.net.Uri) {
try {
val count = carnetImporter.import(uri)
_snackbar.value = if (count > 0) {
"Imported $count Carnet note(s)."
} else {
"No Carnet notes found in that file."
}
} catch (e: Exception) {
_snackbar.value = "Carnet import failed: ${e.message ?: "unreadable file"}"
}
}
// --- v0.3.6.0 recovery key ---
/**
* Write the at-rest encryption key to a user-chosen SAF uri,
* wrapped with [passphrase]. Caller is responsible for calling
* `securityManager.beginExternalActivity()` before launching the
* picker so the SAF round-trip doesn't trigger an auto-lock.
*
* @param uri The destination content uri.
* @param passphrase The passphrase the user entered in the
* export flow (zeroed by this method on completion).
* @return `true` on success, `false` if there is no encryption
* key to export (the caller should disable the export
* row until encryption is active — see SettingsScreen).
*/
suspend fun exportRecoveryKey(uri: android.net.Uri, passphrase: CharArray): Boolean {
if (!objectBoxKeyProvider.hasKey()) {
_snackbar.value = "Encryption isn't active — nothing to back up."
return false
}
try {
objectBoxKeyProvider.exportRecoveryKey(uri, passphrase)
_snackbar.value =
"Recovery key exported. Store the file and passphrase in separate safe places."
return true
} catch (e: org.incido.compose.data.security.ObjectBoxKeyProvider.RecoveryKeyException) {
_snackbar.value = "Couldn't write recovery key: ${e.message}"
return false
}
}
/**
* Read a recovery envelope from [uri] with [passphrase] and
* install it as the current field key. After install we swap in a
* fresh [AesGcmFieldCipher] that wraps the new key, and re-run
* the encryption verifier so the "Encrypted" badge reflects the
* new state.
*
* If the user already had encrypted rows the new key makes those
* rows unreadable (GCM tag fail → row enters [failedNoteIds] in
* the verifier). That's expected — a recovery key only matches
* when the user is moving to a fresh install (or intentionally
* rotating). The UI surfaces a warning dialog before this call.
*/
suspend fun importRecoveryKey(uri: android.net.Uri, passphrase: CharArray): Boolean {
try {
val overwroteExisting = objectBoxKeyProvider.importRecoveryKey(uri, passphrase)
// Swap the live cipher to point at the freshly-installed key.
// We build a new wrapper that re-reads the (just-persisted)
// wrapped blob — no need to re-implement the unwrap here.
cipherHolder.cipher =
AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
encryptionVerifier.checkNow()
_snackbar.value = if (overwroteExisting) {
"Recovery key installed. Previously-encrypted notes will appear as unverified."
} else {
"Recovery key installed."
}
return true
} catch (e: org.incido.compose.data.security.ObjectBoxKeyProvider.RecoveryKeyException) {
_snackbar.value = e.message ?: "Couldn't import recovery key."
return false
}
}
// --- Migration dialog ---
fun acknowledgeMigration() {
_migrationState.value = MigrationState.Idle
}
sealed class MigrationState {
val canStart: Boolean get() = this is Idle || this is Done || this is Failed
object Idle : MigrationState()
data class Running(val progress: Float) : MigrationState()
data class Done(val message: String) : MigrationState()
data class Failed(val reason: String) : MigrationState()
}
/**
* v0.3.3.0: lock-mode selection for the settings screen.
* Mutually exclusive — see [setLockMode].
*/
enum class LockMode { NONE, PIN, BIOMETRIC }
companion object {
/** The version string baked into backup payloads and shown on
* the About card. Mirrors `app/build.gradle.kts` `versionName`
* — if you bump one, bump both. */
const val APP_VERSION = "0.4.2.0"
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
val c = app.container
SettingsViewModel(
settings = c.settingsRepository,
security = c.securityManager,
objectBoxKeyProvider = c.objectBoxKeyProvider,
backupManager = c.backupManager,
carnetImporter = c.carnetImporter,
noteCryptoService = c.noteCryptoService,
cipherHolder = c.cipherHolder,
encryptionVerifier = c.encryptionVerifier,
)
}
}
}
}
@@ -0,0 +1,231 @@
package org.incido.compose.ui.settings.auth
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.launch
import org.incido.compose.ui.settings.SettingsViewModel
/**
* v0.3.3.0: three-step PIN reset flow.
*
* Step 1. **Verify current PIN** — the user types the existing PIN.
* Wrong PIN keeps the user on this step with an inline error.
* Step 2. **Choose a new PIN** — 4–6 numeric digits.
* Step 3. **Confirm new PIN** — must match step 2.
*
* On step 3 success we call
* [SettingsViewModel.changePin] which delegates to
* [org.incido.compose.data.security.SecurityManager.changePin] — that
* method re-verifies the old PIN internally and atomically rotates the
* stored hash + salt. The screen pops on success and surfaces a
* "PIN updated." snackbar via the existing viewModel.snackbar flow.
*
* Reuses the existing [SettingsViewModel.Factory] — the new screen
* doesn't need its own ViewModel because every operation goes through
* the existing security manager.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PinChangeScreen(
onDone: () -> Unit,
onCancel: () -> Unit,
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
) {
val scope = rememberCoroutineScope()
var step by remember { mutableStateOf(Step.VerifyOld) }
var oldPin by remember { mutableStateOf("") }
var first by remember { mutableStateOf("") }
var confirm by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
LaunchedEffect(step) {
// Refocus the field whenever we change step.
focusRequester.requestFocus()
}
fun isValidPin(s: String) = s.length in 4..6 && s.all { it.isDigit() }
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text("Reset PIN") },
navigationIcon = {
IconButton(onClick = onCancel) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel")
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.fillMaxSize()
.padding(horizontal = 24.dp, vertical = 24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Box(modifier = Modifier.size(64.dp), contentAlignment = Alignment.Center) {
Icon(
Icons.Filled.Lock,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(48.dp),
)
}
Text(
text = when (step) {
Step.VerifyOld -> "Enter your current PIN to continue."
Step.ChooseNew -> "Choose a new 4 to 6 digit PIN."
Step.ConfirmNew -> "Re-enter your new PIN to confirm."
},
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
value = when (step) {
Step.VerifyOld -> oldPin
Step.ChooseNew -> first
Step.ConfirmNew -> confirm
},
onValueChange = { v ->
error = null
val filtered = v.filter { it.isDigit() }.take(6)
when (step) {
Step.VerifyOld -> oldPin = filtered
Step.ChooseNew -> first = filtered
Step.ConfirmNew -> confirm = filtered
}
},
label = {
Text(
when (step) {
Step.VerifyOld -> "Current PIN"
Step.ChooseNew -> "New PIN"
Step.ConfirmNew -> "Confirm new PIN"
},
)
},
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.NumberPassword,
imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(
onDone = { /* advance via the button below */ },
),
isError = error != null,
supportingText = {
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
},
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
Button(
onClick = {
when (step) {
Step.VerifyOld -> {
if (!isValidPin(oldPin)) {
error = "PIN must be 4–6 digits."
} else {
step = Step.ChooseNew
}
}
Step.ChooseNew -> {
if (!isValidPin(first)) {
error = "PIN must be 4–6 digits."
} else {
step = Step.ConfirmNew
}
}
Step.ConfirmNew -> {
if (confirm != first) {
error = "PINs don't match."
confirm = ""
} else {
busy = true
scope.launch {
try {
viewModel.changePin(oldPin.toCharArray(), first.toCharArray())
onDone()
} catch (t: IllegalStateException) {
// Wrong old PIN — bounce back to step 1.
error = "Incorrect current PIN."
oldPin = ""
step = Step.VerifyOld
} finally {
busy = false
}
}
}
}
}
},
enabled = !busy && when (step) {
Step.VerifyOld -> oldPin.length in 4..6
Step.ChooseNew -> first.length in 4..6
Step.ConfirmNew -> confirm.length in 4..6
},
modifier = Modifier.fillMaxWidth(),
) {
Text(
when (step) {
Step.VerifyOld -> "Continue"
Step.ChooseNew -> "Continue"
Step.ConfirmNew -> "Save PIN"
},
)
}
TextButton(onClick = onCancel) {
Text("Cancel")
}
}
}
}
private enum class Step { VerifyOld, ChooseNew, ConfirmNew }
@@ -0,0 +1,272 @@
package org.incido.compose.ui.settings.auth
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Fingerprint
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.UserSettings
/**
* v0.3.2.0: lock-screen gate shown whenever
* [SecurityManager.lockState] is [SecurityManager.LockState.Locked].
*
* Renders a single masked PIN field plus an optional biometric button
* (when [UserSettings.useBiometric] is on AND the device can
* authenticate). On successful verify the manager's lock state flips
* to [SecurityManager.LockState.Unlocked] and the host recomposes.
*
* Biometric requires a [FragmentActivity] reference, which we pull
* from the [LocalContext] (the host Activity is a `ComponentActivity`
* subclass; we downcast here for the prompt API).
*
* v0.3.3.0: biometric-only mode — when neither an Incido PIN nor the
* "Use fingerprint / face alongside PIN" toggle apply (just
* [UserSettings.useBiometric] is on), the masked PIN field and
* Unlock button are hidden. Only the biometric button is rendered.
*
* v0.3.3.2 (hotfix): the screen is wrapped in a themed [Surface] so it
* always paints its own background — previously the bare Column fell
* through to the Activity's permanently-light window background,
* producing white-on-white text in dark mode. Biometric unlock now
* uses the callback-based [SecurityManager.authenticateWithBiometric]
* (the old synchronous busy-wait deadlocked the main thread).
*
* v0.3.3.7 (hotfix): in **biometric-only** mode the biometric prompt is
* launched automatically the moment the lock screen appears — previously
* the user had to tap the "Authenticate" button first, adding an extra
* tap of friction to every unlock (cold launch + every auto-lock). The
* auto-launch fires at most once per lock-screen appearance; if the user
* cancels (or the prompt errors), the lock screen stays and the
* "Authenticate" button remains as the manual-retry path. PIN mode is
* untouched — [UserSettings.isBiometricLockActive] is false there, so
* the auto-launch effect never runs and the PIN field keeps its
* auto-focus behaviour.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PinEntryScreen() {
val context = LocalContext.current
val app = context.applicationContext as IncidoApplication
val securityManager = remember { app.securityManager }
val settingsRepository = remember { app.container.settingsRepository }
val lockState by securityManager.lockState.collectAsStateWithLifecycle()
val settings by settingsRepository.userSettingsFlow.collectAsStateWithLifecycle(initialValue = UserSettings())
// v0.3.3.0: derive the active lock mode up front. PIN field only
// renders for the PIN mode; biometric button always renders when
// the device can do biometric and the relevant flag is on.
val biometricOnly = settings.isBiometricLockActive
var pin by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
val scope = rememberCoroutineScope()
// v0.3.3.7: guard flag — the biometric prompt must auto-launch at
// most once per lock-screen appearance so a cancelled prompt can't
// re-trigger in a loop.
var autoLaunched by remember { mutableStateOf(false) }
// v0.3.3.7: in biometric-only mode, open the BiometricPrompt as
// soon as the lock screen composes instead of waiting for the user
// to tap "Authenticate". Keyed on [biometricOnly] so the effect
// re-runs when the real (non-default) settings arrive — the initial
// composition sees the default UserSettings() (biometricOnly=false)
// and is intentionally skipped.
LaunchedEffect(biometricOnly) {
if (!biometricOnly) return@LaunchedEffect
if (autoLaunched) return@LaunchedEffect
if (!securityManager.isBiometricAvailable()) return@LaunchedEffect
val activity = context as? FragmentActivity ?: return@LaunchedEffect
autoLaunched = true
busy = true
error = null
securityManager.authenticateWithBiometric(activity) { ok ->
busy = false
if (ok) {
securityManager.onUnlocked()
} else {
error = "Authentication failed. Tap Authenticate to try again."
}
}
}
LaunchedEffect(Unit) {
// Only request focus on the PIN field when we're showing one.
if (!biometricOnly) focusRequester.requestFocus()
}
fun submit() {
if (pin.length !in 4..6) {
error = "PIN must be 4–6 digits."
return
}
busy = true
error = null
scope.launch {
val ok = securityManager.verifyPin(pin.toCharArray())
busy = false
pin = ""
if (ok) {
securityManager.onUnlocked()
} else {
error = "Incorrect PIN."
focusRequester.requestFocus()
}
}
}
// v0.3.3.2: Surface gives the lock screen a real theme-aware
// background; without it the Column is transparent and the light
// Activity window shows through under dark-theme text.
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
contentColor = MaterialTheme.colorScheme.onBackground,
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 24.dp, vertical = 48.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Spacer(Modifier.size(48.dp))
Box(modifier = Modifier.size(80.dp), contentAlignment = Alignment.Center) {
Icon(
Icons.Filled.Lock,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(64.dp),
)
}
Text(
text = when (lockState) {
is SecurityManager.LockState.Locked -> "Incido is locked"
SecurityManager.LockState.Unlocked -> "Unlocked"
},
style = MaterialTheme.typography.headlineSmall,
)
Text(
text = when {
biometricOnly -> "Authenticate to continue."
else -> "Enter your PIN to continue."
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (!biometricOnly) {
OutlinedTextField(
value = pin,
onValueChange = { v ->
pin = v.filter { it.isDigit() }.take(6)
error = null
},
label = { Text("PIN") },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.NumberPassword,
imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(onDone = { submit() }),
isError = error != null,
supportingText = {
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
},
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
Button(
onClick = { submit() },
enabled = !busy && pin.length in 4..6,
modifier = Modifier.fillMaxWidth(),
) {
Text("Unlock")
}
}
// Biometric button — visible for both PIN mode (fast path) and
// biometric-only mode (the only path).
if (securityManager.isBiometricAvailable() && (settings.useBiometric || biometricOnly)) {
OutlinedButton(
onClick = {
val activity = (context as? FragmentActivity)
if (activity != null) {
busy = true
error = null
// v0.3.3.2: async result callback (main
// thread) instead of the old blocking call.
securityManager.authenticateWithBiometric(activity) { ok ->
busy = false
if (ok) {
securityManager.onUnlocked()
} else {
// v0.3.3.7: biometric-only mode has no
// Incido PIN to fall back to, so don't
// mention one.
error = if (biometricOnly) {
"Authentication failed. Tap Authenticate to try again."
} else {
"Authentication failed. Try again or use your PIN."
}
}
}
} else {
error = "Biometric requires a FragmentActivity host."
}
},
enabled = !busy,
modifier = Modifier.fillMaxWidth(),
) {
Icon(Icons.Filled.Fingerprint, contentDescription = null)
Spacer(Modifier.size(8.dp))
Text(if (biometricOnly) "Authenticate" else "Use fingerprint / face")
}
}
}
}
}
@@ -0,0 +1,170 @@
package org.incido.compose.ui.settings.auth
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.launch
import org.incido.compose.ui.settings.SettingsViewModel
/**
* v0.3.2.0: 4–6-digit PIN setup screen.
*
* Two steps:
* 1. User types the PIN.
* 2. User re-types it for confirmation.
*
* When both steps succeed we call [SettingsViewModel.setNewPin] which
* delegates to [org.incido.compose.data.security.SecurityManager.setupPin].
* On success the screen pops itself.
*
* Validation:
* - Length must be 4–6 numeric digits.
* - Confirmation must match.
*
* Errors render under the field in red.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PinSetupScreen(
onDone: () -> Unit,
onCancel: () -> Unit,
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
) {
val scope = rememberCoroutineScope()
// Stage machine: true = first entry, false = confirm.
var awaitingConfirm by remember { mutableStateOf(false) }
var first by remember { mutableStateOf("") }
var confirm by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
fun isValidPin(s: String) = s.length in 4..6 && s.all { it.isDigit() }
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text("Set a PIN") },
navigationIcon = {
IconButton(onClick = onCancel) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel")
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.fillMaxSize()
.padding(horizontal = 24.dp, vertical = 24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Box(modifier = Modifier.size(64.dp), contentAlignment = Alignment.Center) {
Icon(
Icons.Filled.Lock,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(48.dp),
)
}
Text(
text = if (!awaitingConfirm)
"Choose a 4 to 6 digit PIN. You'll use this to unlock Incido."
else
"Re-enter your PIN to confirm.",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
value = if (!awaitingConfirm) first else confirm,
onValueChange = { v ->
error = null
if (!awaitingConfirm) first = v.filter { it.isDigit() }.take(6)
else confirm = v.filter { it.isDigit() }.take(6)
},
label = { Text(if (!awaitingConfirm) "New PIN" else "Confirm PIN") },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.NumberPassword,
imeAction = ImeAction.Done,
),
isError = error != null,
supportingText = {
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
},
modifier = Modifier.fillMaxWidth(),
)
Button(
onClick = {
if (!awaitingConfirm) {
if (!isValidPin(first)) {
error = "PIN must be 4–6 digits."
} else {
awaitingConfirm = true
}
} else {
if (confirm != first) {
error = "PINs don't match."
confirm = ""
} else {
busy = true
scope.launch {
viewModel.setNewPin(confirm.toCharArray())
busy = false
onDone()
}
}
}
},
enabled = !busy && (
if (!awaitingConfirm) first.length in 4..6
else confirm.length in 4..6
),
modifier = Modifier.fillMaxWidth(),
) {
Text(if (!awaitingConfirm) "Continue" else "Save PIN")
}
TextButton(onClick = onCancel) {
Text("Cancel")
}
}
}
}
@@ -0,0 +1,38 @@
package org.incido.compose.ui.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.graphics.Color
import org.incido.domain.model.NoteColor
/**
* Maps a [NoteColor] enum to a Compose [Color]. Values are chosen to
* stay readable against both light and dark surfaces.
*/
@Composable
@ReadOnlyComposable
fun NoteColor.toComposeColor(): Color = when (this) {
NoteColor.NONE -> Color.Transparent
NoteColor.BLUE -> Color(0xFF4A6FA5)
NoteColor.GREEN -> Color(0xFF4F8A5B)
NoteColor.AMBER -> Color(0xFFB8862B)
NoteColor.RED -> Color(0xFFB14B4B)
NoteColor.PURPLE -> Color(0xFF7B5BA6)
}
/** All selectable colours, including [NoteColor.NONE]. */
val AllNoteColors: List<NoteColor> = listOf(
NoteColor.NONE,
NoteColor.BLUE,
NoteColor.GREEN,
NoteColor.AMBER,
NoteColor.RED,
NoteColor.PURPLE,
)
/** Outline colour used to highlight the selected swatch. */
val swatchBorderColor: Color
@Composable
@ReadOnlyComposable
get() = MaterialTheme.colorScheme.outline
@@ -0,0 +1,18 @@
package org.incido.compose.ui.theme
import android.os.Build
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
/** Android actual — the verbatim pre-M4 dynamic-colour branch: a real
* Material You scheme on API 31+ (S), null below that. */
@Composable
actual fun platformDynamicColorScheme(darkTheme: Boolean): ColorScheme? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return null
val context = LocalContext.current
return if (darkTheme) dynamicDarkColorScheme(context)
else dynamicLightColorScheme(context)
}
@@ -0,0 +1,13 @@
package org.incido.compose.util
import android.text.format.DateUtils
/** Android actual — verbatim pre-M4 formatting: Android's own
* localised relative-time helper, unchanged. */
actual fun relativeTimestamp(epochMillis: Long, nowMillis: Long): String =
DateUtils.getRelativeTimeSpanString(
epochMillis,
nowMillis,
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE,
).toString()