fix: move card favourite star to bottom-right so it no longer overlaps the overflow button (v0.3.3.4)
build / Assemble debug APK (push) Failing after 9s
build / Assemble debug APK (push) Failing after 9s
This commit is contained in:
1 parent
5b82d2a9fe
commit
089926377c
44 files changed
+5490
-140
No files matched your search
@@ -1,18 +1,25 @@
|
||||
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
|
||||
@@ -21,16 +28,29 @@ 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.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}"
|
||||
}
|
||||
|
||||
@@ -45,10 +65,48 @@ private fun String.toNoteFilter(): NoteFilter = when {
|
||||
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.
|
||||
*/
|
||||
private class ShareIntoHolder {
|
||||
var text: String? = null
|
||||
var images: List<SharedImage> = emptyList()
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun IncidoApp() {
|
||||
IncidoTheme {
|
||||
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()
|
||||
@@ -59,6 +117,22 @@ fun IncidoApp() {
|
||||
),
|
||||
) { 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
|
||||
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
|
||||
@@ -71,6 +145,23 @@ fun IncidoApp() {
|
||||
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,
|
||||
@@ -81,6 +172,10 @@ fun IncidoApp() {
|
||||
filterMode = picked
|
||||
scope.launch { drawerState.close() }
|
||||
},
|
||||
onOpenSettings = {
|
||||
scope.launch { drawerState.close() }
|
||||
navController.navigate(Routes.SETTINGS)
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
@@ -90,6 +185,9 @@ fun IncidoApp() {
|
||||
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(
|
||||
@@ -103,9 +201,36 @@ fun IncidoApp() {
|
||||
) { 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() }
|
||||
NoteEditorScreen(
|
||||
noteId = id,
|
||||
onClose = { navController.popBackStack() },
|
||||
initialSharedText = sharedText,
|
||||
initialSharedImages = sharedImages,
|
||||
repository = repository,
|
||||
)
|
||||
}
|
||||
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) },
|
||||
)
|
||||
}
|
||||
composable(Routes.PIN_SETUP) {
|
||||
PinSetupScreen(
|
||||
onDone = { navController.popBackStack() },
|
||||
onCancel = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(Routes.PIN_CHANGE) {
|
||||
PinChangeScreen(
|
||||
onDone = { navController.popBackStack() },
|
||||
onCancel = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -116,4 +241,4 @@ fun IncidoApp() {
|
||||
// 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()
|
||||
private fun <T> List<T>.toSnapshotStateList(): SnapshotStateList<T> = toMutableStateList<T>()
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.incido.compose
|
||||
|
||||
import android.app.Application
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.compose.di.AppContainer
|
||||
|
||||
/**
|
||||
@@ -9,13 +10,25 @@ import org.incido.compose.di.AppContainer
|
||||
*
|
||||
* 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,187 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.incido.domain.model.Note
|
||||
import org.incido.domain.model.NoteAttachment
|
||||
import org.incido.domain.model.NoteColor
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* v0.3.2.0: plain-JSON backup codec.
|
||||
*
|
||||
* File format: a single `.incido.json` containing notes (with their
|
||||
* hashtags and Base64-encoded attachment bytes) + any orphaned hashtag
|
||||
* rows. Format-versioned so future releases can branch.
|
||||
*
|
||||
* This codec does **no** encryption — that's [EncryptedBackupCodec]'s
|
||||
* job. The two codecs share the same on-disk shape; the encrypted
|
||||
* variant just wraps the JSON in a `magic + salt + iv + ciphertext`
|
||||
* envelope.
|
||||
*/
|
||||
object BackupCodec {
|
||||
|
||||
private val json = Json {
|
||||
prettyPrint = true
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a serialisable snapshot of every note (and its attachments)
|
||||
* in [repository], plus all hashtag rows.
|
||||
*/
|
||||
suspend fun exportSnapshot(
|
||||
repository: NoteRepository,
|
||||
appVersion: String,
|
||||
): BackupFile {
|
||||
// The repository exposes Flows; we materialise a one-shot
|
||||
// snapshot via `.first()`. Notes come from `observeAll`, tags
|
||||
// from `observeAllHashtags`.
|
||||
val noteList: List<Note> = repository.observeAll().first()
|
||||
val tagList: List<String> = repository.observeAllHashtags().first()
|
||||
|
||||
// NoteAttachment.bytes is loaded on demand via
|
||||
// `getAttachmentBytes(id)` — we resolve each attachment's
|
||||
// bytes here so the JSON payload is self-contained.
|
||||
val out = BackupFile(
|
||||
formatVersion = FORMAT_VERSION,
|
||||
exportedAt = System.currentTimeMillis(),
|
||||
appVersion = appVersion,
|
||||
notes = noteList.map { note -> note.toBackup(repository) },
|
||||
orphanedHashtags = tagList,
|
||||
)
|
||||
return out
|
||||
}
|
||||
|
||||
/** Serialise [file] to pretty-printed JSON. */
|
||||
fun encode(file: BackupFile): String = json.encodeToString(BackupFile.serializer(), file)
|
||||
|
||||
/** Parse a JSON string produced by [encode]. */
|
||||
fun decode(payload: String): BackupFile =
|
||||
json.decodeFromString(BackupFile.serializer(), payload)
|
||||
|
||||
/**
|
||||
* Import every note (with attachments + hashtags) in [file] into
|
||||
* [repository]. Additive — existing notes are preserved; new
|
||||
* notes are added with fresh ids. The repository's existing
|
||||
* `saveNoteWithHashtags` handles hashtag reconciliation.
|
||||
*/
|
||||
suspend fun importSnapshot(
|
||||
file: BackupFile,
|
||||
repository: NoteRepository,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
) {
|
||||
val total = file.notes.size
|
||||
file.notes.forEachIndexed { idx, bn ->
|
||||
val note = bn.toDomain()
|
||||
// Persist the note and its tags in one transaction so
|
||||
// the drawer's hashtag-usage observers fire once.
|
||||
val saved = repository.saveNoteWithHashtags(
|
||||
note = note.copy(id = 0L), // force a new id
|
||||
hashtagsToAdd = bn.hashtags.toSet(),
|
||||
hashtagsToRemove = emptySet(),
|
||||
)
|
||||
// Insert attachments with the newly assigned note id.
|
||||
bn.attachments.forEach { ba ->
|
||||
repository.addAttachment(
|
||||
noteId = saved.id,
|
||||
bytes = decodeBase64(ba.bytesBase64),
|
||||
mimeType = ba.mimeType,
|
||||
displayName = ba.displayName,
|
||||
)
|
||||
}
|
||||
onProgress(idx + 1, total)
|
||||
}
|
||||
}
|
||||
|
||||
const val FORMAT_VERSION = 1
|
||||
const val MIME_TYPE = "application/json"
|
||||
const val FILE_EXTENSION = "incido.json"
|
||||
}
|
||||
|
||||
/** Top-level serialisable backup payload. */
|
||||
@Serializable
|
||||
data class BackupFile(
|
||||
val formatVersion: Int,
|
||||
val exportedAt: Long,
|
||||
val appVersion: String,
|
||||
val notes: List<BackupNote>,
|
||||
val orphanedHashtags: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class BackupNote(
|
||||
val content: String,
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long,
|
||||
val isFavorite: Boolean,
|
||||
/** Serialised as the [NoteColor] enum name (e.g. "RED"). */
|
||||
val color: String,
|
||||
val hashtags: List<String> = emptyList(),
|
||||
val attachments: List<BackupAttachment> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class BackupAttachment(
|
||||
val mimeType: String,
|
||||
val displayName: String,
|
||||
val createdAt: Long,
|
||||
val sizeBytes: Long,
|
||||
/** Raw attachment bytes, Base64-encoded so the JSON stays a text format. */
|
||||
val bytesBase64: String,
|
||||
)
|
||||
|
||||
/** Suspending overload that resolves attachment bytes via the repository. */
|
||||
private suspend fun Note.toBackup(repository: NoteRepository): BackupNote {
|
||||
val backups = attachments.map { attachment ->
|
||||
val bytes = repository.getAttachmentBytes(attachment.id) ?: ByteArray(0)
|
||||
BackupAttachment(
|
||||
mimeType = attachment.mimeType,
|
||||
displayName = attachment.displayName,
|
||||
createdAt = attachment.createdAt,
|
||||
sizeBytes = attachment.sizeBytes,
|
||||
bytesBase64 = java.util.Base64.getEncoder().encodeToString(bytes),
|
||||
)
|
||||
}
|
||||
return BackupNote(
|
||||
content = content,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt,
|
||||
isFavorite = isFavorite,
|
||||
color = color.name,
|
||||
hashtags = hashtags,
|
||||
attachments = backups,
|
||||
)
|
||||
}
|
||||
|
||||
/** Pure (non-suspending) conversion for tests / unit conversion.
|
||||
* Returns attachments without their bytes — use the suspending
|
||||
* overload above for actual exports. */
|
||||
@Suppress("unused")
|
||||
private fun Note.toBackup(): BackupNote = BackupNote(
|
||||
content = content,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt,
|
||||
isFavorite = isFavorite,
|
||||
color = color.name,
|
||||
hashtags = hashtags,
|
||||
attachments = emptyList(),
|
||||
)
|
||||
|
||||
private fun BackupNote.toDomain(): Note = Note(
|
||||
id = 0L,
|
||||
content = content,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt,
|
||||
isFavorite = isFavorite,
|
||||
color = runCatching { NoteColor.valueOf(color) }.getOrDefault(NoteColor.NONE),
|
||||
hashtags = hashtags,
|
||||
// Attachments are inserted separately by importSnapshot so they
|
||||
// get assigned to the freshly-created note id.
|
||||
attachments = emptyList(),
|
||||
)
|
||||
|
||||
private fun decodeBase64(b64: String): ByteArray =
|
||||
java.util.Base64.getDecoder().decode(b64)
|
||||
@@ -0,0 +1,167 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
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.
|
||||
*
|
||||
* Reads / writes go through the Storage Access Framework — the
|
||||
* Activity hands in [Uri]s from
|
||||
* `ActivityResultContracts.CreateDocument` / `OpenDocument` and the
|
||||
* manager streams bytes in / out via ContentResolver. No fixed-path
|
||||
* writes, no extra permissions.
|
||||
*
|
||||
* Encrypt-on-export and decrypt-on-import are selected by the caller;
|
||||
* the codecs themselves ([BackupCodec], [EncryptedBackupCodec]) hold
|
||||
* the format / cipher details.
|
||||
*/
|
||||
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) {
|
||||
val file = BackupCodec.exportSnapshot(repository, appVersion)
|
||||
val json = BackupCodec.encode(file)
|
||||
context.contentResolver.openOutputStream(uri, "wt")?.use { out: OutputStream ->
|
||||
out.write(json.toByteArray(Charsets.UTF_8))
|
||||
out.flush()
|
||||
} ?: throw java.io.IOException("Could not open output stream for $uri")
|
||||
onProgress(file.notes.size, file.notes.size)
|
||||
file.notes.size
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
val file = BackupCodec.exportSnapshot(repository, appVersion)
|
||||
val json = BackupCodec.encode(file)
|
||||
val payload = EncryptedBackupCodec.encrypt(json, passphrase)
|
||||
context.contentResolver.openOutputStream(uri, "wt")?.use { out ->
|
||||
out.write(payload)
|
||||
out.flush()
|
||||
} ?: throw java.io.IOException("Could not open output stream for $uri")
|
||||
onProgress(file.notes.size, file.notes.size)
|
||||
file.notes.size
|
||||
}
|
||||
|
||||
/**
|
||||
* 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]).
|
||||
*
|
||||
* Returns the number of notes imported.
|
||||
*/
|
||||
suspend fun import(
|
||||
uri: Uri,
|
||||
passphrase: CharArray? = null,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int = withContext(Dispatchers.IO) {
|
||||
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw java.io.IOException("Could not open input stream for $uri")
|
||||
|
||||
val json: String = if (EncryptedBackupCodec.isEncrypted(bytes)) {
|
||||
val pass = passphrase
|
||||
?: throw IllegalArgumentException("Encrypted backup requires a passphrase")
|
||||
EncryptedBackupCodec.decrypt(bytes, pass)
|
||||
} else {
|
||||
String(bytes, Charsets.UTF_8)
|
||||
}
|
||||
|
||||
val file = BackupCodec.decode(json)
|
||||
BackupCodec.importSnapshot(file, repository) { cur, tot -> onProgress(cur, tot) }
|
||||
file.notes.size
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 bytes: ByteArray = try {
|
||||
context.contentResolver.openInputStream(uri)?.use(InputStream::readBytes)
|
||||
?: return@withContext null
|
||||
} catch (_: java.io.IOException) {
|
||||
return@withContext null
|
||||
}
|
||||
val json: String = if (EncryptedBackupCodec.isEncrypted(bytes)) {
|
||||
val pass = passphrase ?: return@withContext null
|
||||
try {
|
||||
EncryptedBackupCodec.decrypt(bytes, pass)
|
||||
} catch (_: javax.crypto.AEADBadTagException) {
|
||||
return@withContext null
|
||||
} catch (_: javax.crypto.BadPaddingException) {
|
||||
return@withContext null
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// v0.3.3.3 hotfix: a truncated / corrupt envelope
|
||||
// fails the require(...) size checks inside
|
||||
// decrypt() with an IllegalArgumentException.
|
||||
// Previously that escaped preview() and crashed the
|
||||
// coroutine; treat it the same as a bad passphrase.
|
||||
return@withContext null
|
||||
} catch (_: java.security.GeneralSecurityException) {
|
||||
// Catch-all for any other cipher-layer failure.
|
||||
return@withContext null
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
String(bytes, Charsets.UTF_8)
|
||||
} catch (_: java.io.IOException) {
|
||||
return@withContext null
|
||||
}
|
||||
}
|
||||
val file: BackupFile = try {
|
||||
BackupCodec.decode(json)
|
||||
} catch (_: kotlinx.serialization.SerializationException) {
|
||||
return@withContext null
|
||||
} catch (_: Exception) {
|
||||
// v0.3.3.3 hotfix: any other decode failure (e.g. the
|
||||
// payload wasn't JSON after all) must not escape.
|
||||
return@withContext null
|
||||
}
|
||||
BackupPreview(
|
||||
noteCount = file.notes.size,
|
||||
attachmentCount = file.notes.sumOf { it.attachments.size },
|
||||
appVersion = file.appVersion,
|
||||
exportedAt = file.exportedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Lightweight DTO shown in the import confirmation dialog. */
|
||||
data class BackupPreview(
|
||||
val noteCount: Int,
|
||||
val attachmentCount: Int,
|
||||
val appVersion: String,
|
||||
val exportedAt: Long,
|
||||
)
|
||||
@@ -0,0 +1,123 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import java.security.SecureRandom
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/**
|
||||
* v0.3.2.0: passphrase-encrypted backup envelope.
|
||||
*
|
||||
* On-disk layout:
|
||||
*
|
||||
* ```
|
||||
* magic "INCDBK1\0" (8 bytes)
|
||||
* salt (16 bytes)
|
||||
* iv (12 bytes)
|
||||
* ciphertext + tag (variable)
|
||||
* ```
|
||||
*
|
||||
* The plaintext payload is the JSON produced by [BackupCodec.encode].
|
||||
* The key is derived from the user's passphrase via PBKDF2-HMAC-SHA256
|
||||
* (200,000 iterations, 256-bit output). The body is encrypted with
|
||||
* AES-256-GCM; the GCM tag is appended automatically by the JCE.
|
||||
*
|
||||
* The magic header is what lets the import side auto-detect the format
|
||||
* without asking the user — plain JSON files start with `{` /
|
||||
* whitespace, encrypted files start with `INCDBK1\0`.
|
||||
*/
|
||||
object EncryptedBackupCodec {
|
||||
|
||||
/** "Incido Backup v1" — null terminator included so it never
|
||||
* collides with `{` (the first byte of any JSON object). */
|
||||
val MAGIC: ByteArray = byteArrayOf(
|
||||
0x49, 0x4E, 0x43, 0x44, 0x42, 0x4B, 0x31, 0x00,
|
||||
)
|
||||
|
||||
private const val SALT_BYTES = 16
|
||||
private const val IV_BYTES = 12
|
||||
private const val GCM_TAG_BITS = 128
|
||||
private const val PBKDF2_ITERATIONS = 200_000
|
||||
private const val DERIVED_KEY_BITS = 256
|
||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
|
||||
private val secureRandom = SecureRandom()
|
||||
|
||||
/**
|
||||
* True if [bytes] starts with [MAGIC] — used by the import side
|
||||
* to distinguish encrypted payloads from plain JSON.
|
||||
*/
|
||||
fun isEncrypted(bytes: ByteArray): Boolean {
|
||||
if (bytes.size < MAGIC.size) return false
|
||||
return bytes.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt [plaintextJson] with [passphrase] and return the full
|
||||
* envelope (magic + salt + iv + ciphertext + tag).
|
||||
*/
|
||||
fun encrypt(plaintextJson: String, passphrase: CharArray): ByteArray {
|
||||
val salt = ByteArray(SALT_BYTES).also(secureRandom::nextBytes)
|
||||
val iv = ByteArray(IV_BYTES).also(secureRandom::nextBytes)
|
||||
val keyBytes = deriveKey(passphrase, salt)
|
||||
try {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(
|
||||
Cipher.ENCRYPT_MODE,
|
||||
SecretKeySpec(keyBytes, "AES"),
|
||||
GCMParameterSpec(GCM_TAG_BITS, iv),
|
||||
)
|
||||
val cipherText = cipher.doFinal(plaintextJson.toByteArray(Charsets.UTF_8))
|
||||
return MAGIC + salt + iv + cipherText
|
||||
} finally {
|
||||
keyBytes.fill(0)
|
||||
passphrase.fill('0')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse of [encrypt]. Throws on bad passphrase or corrupted
|
||||
* payload (GCM tag mismatch).
|
||||
*/
|
||||
fun decrypt(payload: ByteArray, passphrase: CharArray): String {
|
||||
require(isEncrypted(payload)) { "Payload is not an Incido encrypted backup" }
|
||||
require(payload.size >= MAGIC.size + SALT_BYTES + IV_BYTES + GCM_TAG_BITS / 8) {
|
||||
"Encrypted backup is truncated"
|
||||
}
|
||||
val salt = payload.copyOfRange(MAGIC.size, MAGIC.size + SALT_BYTES)
|
||||
val iv = payload.copyOfRange(
|
||||
MAGIC.size + SALT_BYTES,
|
||||
MAGIC.size + SALT_BYTES + IV_BYTES,
|
||||
)
|
||||
val cipherText = payload.copyOfRange(
|
||||
MAGIC.size + SALT_BYTES + IV_BYTES,
|
||||
payload.size,
|
||||
)
|
||||
val keyBytes = deriveKey(passphrase, salt)
|
||||
try {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(
|
||||
Cipher.DECRYPT_MODE,
|
||||
SecretKeySpec(keyBytes, "AES"),
|
||||
GCMParameterSpec(GCM_TAG_BITS, iv),
|
||||
)
|
||||
val plain = cipher.doFinal(cipherText)
|
||||
return plain.toString(Charsets.UTF_8)
|
||||
} finally {
|
||||
keyBytes.fill(0)
|
||||
passphrase.fill('0')
|
||||
}
|
||||
}
|
||||
|
||||
private fun deriveKey(passphrase: CharArray, salt: ByteArray): ByteArray {
|
||||
val spec = PBEKeySpec(passphrase, salt, PBKDF2_ITERATIONS, DERIVED_KEY_BITS)
|
||||
try {
|
||||
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
|
||||
return factory.generateSecret(spec).encoded
|
||||
} finally {
|
||||
spec.clearPassword()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,161 @@
|
||||
package org.incido.compose.data.security
|
||||
|
||||
import android.content.Context
|
||||
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
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
// ---- 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,274 @@
|
||||
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
|
||||
|
||||
/**
|
||||
* 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()
|
||||
}
|
||||
}
|
||||
|
||||
/** 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
|
||||
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,55 @@
|
||||
package org.incido.compose.data.settings
|
||||
|
||||
/**
|
||||
* Rules that an encrypted-backup passphrase must satisfy.
|
||||
*
|
||||
* v0.3.2.0: passphrases must be **12–32 chars**, contain at least one
|
||||
* digit and at least one special character. The settings UI's
|
||||
* `PassphraseDialog` uses [validate] to render live error messages and
|
||||
* to enable/disable the OK button.
|
||||
*/
|
||||
object PasswordPolicy {
|
||||
|
||||
const val MIN_LENGTH = 12
|
||||
const val MAX_LENGTH = 32
|
||||
|
||||
/** Set of allowed special characters. Deliberately excludes whitespace. */
|
||||
const val SPECIAL_CHARS = "!@#\$%^&*()_+-=[]{};':\",./<>?\\|`~"
|
||||
|
||||
/**
|
||||
* Reasons the policy can reject a passphrase. The UI shows one row
|
||||
* per failure (e.g. "too short", "needs a digit").
|
||||
*/
|
||||
enum class Failure { TOO_SHORT, TOO_LONG, MISSING_DIGIT, MISSING_SPECIAL }
|
||||
|
||||
/**
|
||||
* Result of validating a passphrase. [isValid] is true only when
|
||||
* [failures] is empty.
|
||||
*/
|
||||
data class Validation(
|
||||
val failures: Set<Failure>,
|
||||
) {
|
||||
val isValid: Boolean get() = failures.isEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* Check [passphrase] against the policy. Returns the set of failures
|
||||
* (empty set means "passes").
|
||||
*/
|
||||
fun validate(passphrase: String): Validation {
|
||||
val failures = mutableSetOf<Failure>()
|
||||
if (passphrase.length < MIN_LENGTH) failures += Failure.TOO_SHORT
|
||||
if (passphrase.length > MAX_LENGTH) failures += Failure.TOO_LONG
|
||||
if (!passphrase.any { it.isDigit() }) failures += Failure.MISSING_DIGIT
|
||||
if (!passphrase.any { it in SPECIAL_CHARS }) failures += Failure.MISSING_SPECIAL
|
||||
return Validation(failures)
|
||||
}
|
||||
|
||||
/** Human-readable description of a single failure, for the UI. */
|
||||
fun describe(failure: Failure): String = when (failure) {
|
||||
Failure.TOO_SHORT -> "Must be at least $MIN_LENGTH characters."
|
||||
Failure.TOO_LONG -> "Must be at most $MAX_LENGTH characters."
|
||||
Failure.MISSING_DIGIT -> "Must contain at least one digit (0-9)."
|
||||
Failure.MISSING_SPECIAL -> "Must contain at least one special character."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package org.incido.compose.data.settings
|
||||
|
||||
/**
|
||||
* One entry in the "What's New" dialog. Surfaced from the Settings
|
||||
* screen when the user taps the version number.
|
||||
*
|
||||
* v0.3.2.0: the dialog shows the [RECENT] list (newest first) in a
|
||||
* scrollable column. Each entry has a version, a release date, and a
|
||||
* list of bullet points summarising what shipped in that release.
|
||||
*
|
||||
* Content is mirrored from `Incido Development Plan.txt` §10 so the
|
||||
* in-app dialog and the repo's history of changes stay in lockstep
|
||||
* (the plan file is the source of truth at release time).
|
||||
*/
|
||||
data class ReleaseNote(
|
||||
val version: String,
|
||||
val date: String,
|
||||
val bullets: List<String>,
|
||||
)
|
||||
|
||||
object ReleaseNotes {
|
||||
|
||||
/**
|
||||
* The 5 most recent Incido releases, ordered newest → oldest.
|
||||
* Append a new entry on top each release.
|
||||
*/
|
||||
val RECENT: List<ReleaseNote> = listOf(
|
||||
ReleaseNote(
|
||||
version = "0.3.3.4",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"The favourite star on note cards no longer overlaps the " +
|
||||
"\u22EE overflow button — it now sits in the " +
|
||||
"bottom-right corner, vertically aligned with the " +
|
||||
"three-dot button above it.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.3.3.3",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"Importing an encrypted backup no longer crashes the app — " +
|
||||
"the passphrase was being wiped after the preview " +
|
||||
"step, so the final import ran without it and failed. " +
|
||||
"The passphrase is now retained for the import and " +
|
||||
"securely wiped afterwards.",
|
||||
"Backup import errors (wrong passphrase, corrupt or " +
|
||||
"truncated files, unreadable files) now surface as a " +
|
||||
"snackbar message instead of crashing the app.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.3.3.2",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"Lock screen is now readable in dark mode — it paints " +
|
||||
"its own theme-aware background instead of falling " +
|
||||
"through to the light Activity window (white text " +
|
||||
"on white).",
|
||||
"Biometric unlock works again — authentication is fully " +
|
||||
"asynchronous, so the app no longer hangs waiting " +
|
||||
"for the prompt's result.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.3.3.1",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"\"Encrypt notes at rest\" is now greyed out unless " +
|
||||
"Security is enabled AND a PIN or Biometric is " +
|
||||
"configured — you can no longer toggle at-rest " +
|
||||
"encryption against an unlocked state.",
|
||||
"The master \"Enable security\" toggle can now be " +
|
||||
"flipped on by itself — no PIN/Biometric " +
|
||||
"precondition. Pick PIN or Biometric afterwards.",
|
||||
"Importing an encrypted backup now opens the import " +
|
||||
"passphrase dialog (single field, no confirmation " +
|
||||
"or policy check) instead of the export passphrase " +
|
||||
"dialog. Wrong passphrase still surfaces " +
|
||||
"\"Incorrect passphrase.\" via snackbar.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.3.3.0",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"Lock mode is now a single choice between app-only PIN and " +
|
||||
"device biometric — both toggles live under the master " +
|
||||
"\"Enable security\" switch and grey each other out. A " +
|
||||
"new \"Reset PIN\" row appears when PIN is the active mode.",
|
||||
"Encrypted backup import now prompts for the passphrase " +
|
||||
"(previously the import silently no-op'd when the file " +
|
||||
"was encrypted).",
|
||||
"Note-card overflow menu — long-press a card (or tap the " +
|
||||
"\u22EE button in the top-right) to open a popup menu " +
|
||||
"with a Delete entry. Designed to host additional " +
|
||||
"actions (Share, etc.) as they're added.",
|
||||
),
|
||||
),
|
||||
// v0.3.3.4 push drops v0.3.2.0 off the "5 most recent" tail.
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
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.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
/**
|
||||
* DataStore-backed persistence for [UserSettings].
|
||||
*
|
||||
* v0.3.2.0: the single source of truth for every toggleable preference
|
||||
* in Incido. The UI layer reads [userSettingsFlow]; writers use the
|
||||
* dedicated setter methods (which atomically edit the DataStore).
|
||||
*
|
||||
* Singleton wrapper around a process-wide [DataStore] declared as a
|
||||
* Context extension property — created lazily on first access.
|
||||
*
|
||||
* Read-once access (used by [org.incido.compose.IncidoApplication] to
|
||||
* bootstrap the encryption key before the BoxStore is constructed) goes
|
||||
* through [snapshot] which uses a `runBlocking { first() }` — safe at
|
||||
* Application.onCreate time, where there's no UI thread to deadlock.
|
||||
*/
|
||||
class SettingsRepository(private val context: Context) {
|
||||
|
||||
/** Stream of the current [UserSettings] — emit-on-change semantics. */
|
||||
val userSettingsFlow: Flow<UserSettings> =
|
||||
context.dataStore.data.map { prefs -> prefs.toUserSettings() }
|
||||
|
||||
/** Read-once snapshot of the current settings. Blocking — call only
|
||||
* at startup, not from the UI thread. */
|
||||
fun snapshot(): UserSettings = runBlocking {
|
||||
context.dataStore.data.first().toUserSettings()
|
||||
}
|
||||
|
||||
// ---- setters ----
|
||||
// Each setter does a single .edit { } so we don't trigger spurious
|
||||
// emits for unrelated keys.
|
||||
|
||||
suspend fun setThemeMode(mode: ThemeMode) {
|
||||
context.dataStore.edit { it[KEY_THEME_MODE] = mode.name }
|
||||
}
|
||||
|
||||
suspend fun setDynamicColor(enabled: Boolean) {
|
||||
context.dataStore.edit { it[KEY_DYNAMIC_COLOR] = enabled }
|
||||
}
|
||||
|
||||
suspend fun setSecurityEnabled(enabled: Boolean) {
|
||||
context.dataStore.edit { it[KEY_SECURITY_ENABLED] = enabled }
|
||||
}
|
||||
|
||||
suspend fun setEncryptionEnabled(enabled: Boolean) {
|
||||
context.dataStore.edit { it[KEY_ENCRYPTION_ENABLED] = enabled }
|
||||
}
|
||||
|
||||
suspend fun setPinEnabled(enabled: Boolean) {
|
||||
context.dataStore.edit { it[KEY_PIN_ENABLED] = enabled }
|
||||
}
|
||||
|
||||
suspend fun setUseBiometric(enabled: Boolean) {
|
||||
context.dataStore.edit { it[KEY_USE_BIOMETRIC] = enabled }
|
||||
}
|
||||
|
||||
suspend fun setAutoLockTimeout(timeout: AutoLockTimeout) {
|
||||
context.dataStore.edit { it[KEY_AUTO_LOCK_TIMEOUT] = timeout.minutes }
|
||||
}
|
||||
|
||||
// ---- private helpers ----
|
||||
|
||||
private fun Preferences.toUserSettings(): UserSettings = UserSettings(
|
||||
themeMode = this[KEY_THEME_MODE]?.let { name ->
|
||||
runCatching { ThemeMode.valueOf(name) }.getOrDefault(ThemeMode.SYSTEM)
|
||||
} ?: ThemeMode.SYSTEM,
|
||||
dynamicColor = this[KEY_DYNAMIC_COLOR] ?: true,
|
||||
securityEnabled = this[KEY_SECURITY_ENABLED] ?: false,
|
||||
encryptionEnabled = this[KEY_ENCRYPTION_ENABLED] ?: false,
|
||||
pinEnabled = this[KEY_PIN_ENABLED] ?: false,
|
||||
useBiometric = this[KEY_USE_BIOMETRIC] ?: false,
|
||||
autoLockTimeout = AutoLockTimeout.fromMinutes(this[KEY_AUTO_LOCK_TIMEOUT] ?: 5),
|
||||
)
|
||||
|
||||
companion object {
|
||||
private val KEY_THEME_MODE = stringPreferencesKey("theme_mode")
|
||||
private val KEY_DYNAMIC_COLOR = booleanPreferencesKey("dynamic_color")
|
||||
private val KEY_SECURITY_ENABLED = booleanPreferencesKey("security_enabled")
|
||||
private val KEY_ENCRYPTION_ENABLED = booleanPreferencesKey("encryption_enabled")
|
||||
private val KEY_PIN_ENABLED = booleanPreferencesKey("pin_enabled")
|
||||
private val KEY_USE_BIOMETRIC = booleanPreferencesKey("use_biometric")
|
||||
private val KEY_AUTO_LOCK_TIMEOUT = intPreferencesKey("auto_lock_timeout_minutes")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = "incido_settings",
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
package org.incido.compose.data.settings
|
||||
|
||||
/**
|
||||
* Immutable snapshot of every user-toggleable setting in Incido.
|
||||
*
|
||||
* v0.3.2.0 introduces this type. UI layer reads it as a `Flow<UserSettings>`
|
||||
* from [SettingsRepository]; writers update it via the repository's
|
||||
* setter methods (which mutate DataStore + propagate to all observers).
|
||||
*
|
||||
* Defaults are chosen so that a fresh install behaves exactly like
|
||||
* v0.3.1.x (no security, system theme, dynamic color on) — there are
|
||||
* no breaking UX changes for users who never open Settings.
|
||||
*
|
||||
* v0.3.3.0: lock mode is now a mutually-exclusive choice between
|
||||
* app-only PIN and device biometric — the two toggles on the settings
|
||||
* screen grey each other out when one is enabled. `isLockActive`
|
||||
* reflects whichever is currently active (PIN *or* biometric).
|
||||
*/
|
||||
data class UserSettings(
|
||||
/** Theme mode — see [ThemeMode]. */
|
||||
val themeMode: ThemeMode = ThemeMode.SYSTEM,
|
||||
/** Material You dynamic color (Android 12+ only — no-op below). */
|
||||
val dynamicColor: Boolean = true,
|
||||
/** Master security switch. When false, none of the security sub-toggles apply. */
|
||||
val securityEnabled: Boolean = false,
|
||||
/** ObjectBox store encrypted at rest with a Keystore-wrapped key. */
|
||||
val encryptionEnabled: Boolean = false,
|
||||
/** Require an app-only PIN to open the app (when security is enabled).
|
||||
* v0.3.3.0: mutually exclusive with [useBiometric] — both cannot be true. */
|
||||
val pinEnabled: Boolean = false,
|
||||
/** Use the device's biometric (fingerprint / face) to open the app
|
||||
* (when security is enabled). v0.3.3.0: mutually exclusive with
|
||||
* [pinEnabled] — both cannot be true. */
|
||||
val useBiometric: Boolean = false,
|
||||
/** Auto-lock the app after this many minutes of background time.
|
||||
* Ignored on cold launch (always locked regardless). */
|
||||
val autoLockTimeout: AutoLockTimeout = AutoLockTimeout.FIVE_MINUTES,
|
||||
) {
|
||||
/** True when a PIN is configured AND the master security switch is on. */
|
||||
val isPinLockActive: Boolean
|
||||
get() = securityEnabled && pinEnabled
|
||||
|
||||
/** True when biometric is the active lock (master on, biometric on, PIN off). */
|
||||
val isBiometricLockActive: Boolean
|
||||
get() = securityEnabled && useBiometric && !pinEnabled
|
||||
|
||||
/** True when *any* lock is active (PIN or biometric). Drives the
|
||||
* lock-screen gate in [org.incido.compose.App]. */
|
||||
val isLockActive: Boolean
|
||||
get() = securityEnabled && (pinEnabled || useBiometric)
|
||||
|
||||
val isEncryptionActive: Boolean
|
||||
get() = securityEnabled && encryptionEnabled
|
||||
}
|
||||
|
||||
/** Theme selection for the settings screen. */
|
||||
enum class ThemeMode {
|
||||
/** Follow the OS-level light/dark setting (v0.3.1.x default). */
|
||||
SYSTEM,
|
||||
LIGHT,
|
||||
DARK,
|
||||
;
|
||||
|
||||
/**
|
||||
* Resolve to a concrete boolean for [androidx.compose.foundation.isSystemInDarkTheme].
|
||||
* Caller passes the current system value so SYSTEM can defer to it.
|
||||
*/
|
||||
fun resolveDark(systemInDarkTheme: Boolean): Boolean = when (this) {
|
||||
SYSTEM -> systemInDarkTheme
|
||||
LIGHT -> false
|
||||
DARK -> true
|
||||
}
|
||||
}
|
||||
|
||||
/** Auto-lock timeout options exposed in the settings UI. */
|
||||
enum class AutoLockTimeout(val minutes: Int, val label: String) {
|
||||
IMMEDIATELY(0, "Immediately"),
|
||||
ONE_MINUTE(1, "1 minute"),
|
||||
FIVE_MINUTES(5, "5 minutes"),
|
||||
FIFTEEN_MINUTES(15, "15 minutes"),
|
||||
ONE_HOUR(60, "1 hour"),
|
||||
;
|
||||
|
||||
/** Milliseconds of background time before re-lock is required. */
|
||||
val millis: Long get() = minutes * 60_000L
|
||||
|
||||
companion object {
|
||||
fun fromMinutes(min: Int): AutoLockTimeout =
|
||||
values().firstOrNull { it.minutes == min } ?: FIVE_MINUTES
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,50 @@ import io.objectbox.BoxStore
|
||||
import org.incido.data.ObjectBoxStore
|
||||
import org.incido.data.repository.NoteRepositoryImpl
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
import org.incido.compose.data.backup.BackupManager
|
||||
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.compose.data.settings.SettingsRepository
|
||||
|
||||
/**
|
||||
* 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)
|
||||
*
|
||||
* The constructor accepts a Context, builds the [SettingsRepository]
|
||||
* first (so we can read the encryption preference synchronously),
|
||||
* then either fetches the BoxStore encryption key from the Keystore
|
||||
* (when `securityEnabled && encryptionEnabled`) or opens the store
|
||||
* unencrypted.
|
||||
*/
|
||||
class AppContainer(context: Context) {
|
||||
val boxStore: BoxStore = ObjectBoxStore.init(context)
|
||||
|
||||
private val appContext: Context = context.applicationContext
|
||||
|
||||
val settingsRepository: SettingsRepository = SettingsRepository(appContext)
|
||||
|
||||
val objectBoxKeyProvider: ObjectBoxKeyProvider = ObjectBoxKeyProvider(appContext)
|
||||
|
||||
val securityManager: SecurityManager =
|
||||
SecurityManager(appContext, settingsRepository)
|
||||
|
||||
val boxStore: BoxStore = run {
|
||||
// v0.3.2.0: ObjectBox 4.0.3 OSS doesn't expose an
|
||||
// `encryptionKey(byte[])` method on BoxStoreBuilder — the
|
||||
// feature is only available in ObjectBox Pro. The key is
|
||||
// still generated by ObjectBoxKeyProvider (so the wiring
|
||||
// is ready for when/if the API lands), but we always
|
||||
// open the store unencrypted for now.
|
||||
ObjectBoxStore.init(appContext, encryptionKey = null)
|
||||
}
|
||||
|
||||
val noteRepository: NoteRepository = NoteRepositoryImpl(boxStore)
|
||||
|
||||
val backupManager: BackupManager = BackupManager(appContext, noteRepository)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
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>,
|
||||
) {
|
||||
val isEmpty: Boolean get() = text.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
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ 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.Settings
|
||||
import androidx.compose.material.icons.filled.Star
|
||||
import androidx.compose.material.icons.filled.Tag
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
@@ -33,18 +34,23 @@ import org.incido.domain.model.HashtagUsage
|
||||
import org.incido.domain.model.NoteFilter
|
||||
|
||||
/**
|
||||
* Left-side navigation drawer. Top section has three fixed entries
|
||||
* (Home / Favorites / Untagged); a `HorizontalDivider`; then a live
|
||||
* scrollable list of the user's most-recently-used hashtags.
|
||||
* Left-side navigation drawer. Top section has four fixed entries
|
||||
* (Home / Favorites / Untagged / Settings); a `HorizontalDivider`; then
|
||||
* a live scrollable list of the user's most-recently-used hashtags.
|
||||
*
|
||||
* Tapping any entry calls [onSelectFilter] and the caller (root) is
|
||||
* responsible for closing the drawer.
|
||||
* 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.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun IncidoDrawer(
|
||||
currentFilter: NoteFilter,
|
||||
onSelectFilter: (NoteFilter) -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.Factory),
|
||||
) {
|
||||
@@ -85,6 +91,18 @@ fun IncidoDrawer(
|
||||
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
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.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.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.platform.LocalContext
|
||||
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 android.widget.Toast
|
||||
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 / "unsupported"
|
||||
// message for non-image attachments).
|
||||
val bitmap by produceState<android.graphics.Bitmap?>(initialValue = null, key1 = attachmentId) {
|
||||
val bytes: ByteArray? = when (attachmentId) {
|
||||
is ViewerAttachmentId.Persisted -> withContext(Dispatchers.IO) {
|
||||
repository.getAttachmentBytes(attachmentId.id)
|
||||
}
|
||||
is ViewerAttachmentId.Pending -> pendingBytes
|
||||
}
|
||||
if (bytes == null) {
|
||||
value = null
|
||||
return@produceState
|
||||
}
|
||||
value = withContext(Dispatchers.IO) {
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
}
|
||||
}
|
||||
|
||||
val ctx = LocalContext.current
|
||||
LaunchedEffect(attachmentId) {
|
||||
if (attachmentId is ViewerAttachmentId.Persisted) {
|
||||
val mime = "image" // we only open the viewer for images; see editor
|
||||
if (bitmap == null) {
|
||||
Toast.makeText(ctx, "Couldn't decode $mime attachment", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 = "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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,13 @@
|
||||
package org.incido.compose.ui.editor
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -18,12 +25,18 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.systemBars
|
||||
import androidx.compose.foundation.layout.union
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
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.AttachFile
|
||||
import androidx.compose.material.icons.filled.CameraAlt
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Done
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Star
|
||||
@@ -51,6 +64,7 @@ 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.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -60,25 +74,41 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.painter.BitmapPainter
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.compose.ui.theme.AllNoteColors
|
||||
import org.incido.compose.ui.theme.swatchBorderColor
|
||||
import org.incido.compose.ui.theme.toComposeColor
|
||||
import org.incido.domain.model.Hashtag
|
||||
import org.incido.domain.model.NoteColor
|
||||
import java.io.File
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun NoteEditorScreen(
|
||||
noteId: Long?,
|
||||
onClose: () -> Unit,
|
||||
initialSharedText: String? = null,
|
||||
initialSharedImages: List<SharedImage> = emptyList(),
|
||||
repository: org.incido.domain.repository.NoteRepository? = null,
|
||||
viewModel: NoteEditorViewModel = viewModel(
|
||||
factory = NoteEditorViewModel.factory(noteId),
|
||||
factory = NoteEditorViewModel.factory(
|
||||
noteId = noteId,
|
||||
initialSharedText = initialSharedText,
|
||||
initialSharedImages = initialSharedImages,
|
||||
),
|
||||
key = "editor-$noteId",
|
||||
),
|
||||
) {
|
||||
@@ -88,6 +118,88 @@ fun NoteEditorScreen(
|
||||
var showDiscardDialog by rememberSaveable { mutableStateOf(false) }
|
||||
val snackbarHost = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val ctx = LocalContext.current
|
||||
|
||||
// v0.3.1.0: pick up the NoteRepository from the editor's VM (it's not
|
||||
// on the ViewModel's public surface but we can grab it for the image
|
||||
// viewer via the app container — see App.kt wiring for the actual
|
||||
// route through. Fall back to null and disable the viewer.)
|
||||
val repoForViewer = repository
|
||||
|
||||
// v0.3.1.0: camera permission + capture. The camera launcher is
|
||||
// declared FIRST so the permission callback (below) can forward to it
|
||||
// without a Kotlin forward-reference error.
|
||||
var pendingCameraUri by remember { mutableStateOf<Uri?>(null) }
|
||||
val cameraLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.TakePicture()
|
||||
) { success ->
|
||||
val uri = pendingCameraUri
|
||||
if (success && uri != null) {
|
||||
scope.launch {
|
||||
val bytes = withContext(Dispatchers.IO) {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
}
|
||||
// Always delete the temp file — its bytes are now in the DB.
|
||||
runCatching { uri.path?.let { File(it).delete() } }
|
||||
pendingCameraUri = null
|
||||
if (bytes != null) {
|
||||
viewModel.importAttachmentBytes(
|
||||
bytes = bytes,
|
||||
mimeType = "image/jpeg",
|
||||
displayName = "IMG_${System.currentTimeMillis()}.jpg",
|
||||
)
|
||||
} else {
|
||||
Toast.makeText(ctx, "Couldn't read captured photo", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pendingCameraUri = null
|
||||
}
|
||||
}
|
||||
// Now declared AFTER cameraLauncher so it can forward to it.
|
||||
val cameraPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { granted ->
|
||||
if (granted) {
|
||||
pendingCameraUri?.let { uri -> cameraLauncher.launch(uri) }
|
||||
} else {
|
||||
Toast.makeText(ctx, "Camera permission denied", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
val filePickerLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocument()
|
||||
) { uri ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
scope.launch {
|
||||
val ctxForResolver = ctx
|
||||
val (bytes, displayName, mime) = withContext(Dispatchers.IO) {
|
||||
val resolver = ctxForResolver.contentResolver
|
||||
val name = queryDisplayName(resolver, uri) ?: "Attachment_${System.currentTimeMillis()}"
|
||||
val mimeType = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val data = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
Triple(data, name, mimeType)
|
||||
}
|
||||
if (bytes != null) {
|
||||
viewModel.importAttachmentBytes(
|
||||
bytes = bytes,
|
||||
mimeType = mime,
|
||||
displayName = displayName,
|
||||
)
|
||||
} else {
|
||||
Toast.makeText(ctx, "Couldn't read attachment", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun launchCamera() {
|
||||
val (uri, _) = createTempCameraUri(ctx)
|
||||
if (uri == null) {
|
||||
Toast.makeText(ctx, "Couldn't prepare camera outbox", Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
pendingCameraUri = uri
|
||||
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
|
||||
LaunchedEffect(state.isLoading) {
|
||||
if (!state.isLoading && state.existing != null) {
|
||||
@@ -148,13 +260,28 @@ fun NoteEditorScreen(
|
||||
snackbarHost = { SnackbarHost(hostState = snackbarHost) },
|
||||
topBar = {
|
||||
CenterAlignedTopAppBar(
|
||||
title = { Text(if (state.isEditing) "Edit note" else "New note") },
|
||||
title = { Text(if (state.isEditing) "Edit" else "New") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { tryClose() }) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
// v0.3.1.0: Camera (camera icon) + Attach File (paperclip icon).
|
||||
IconButton(onClick = { launchCamera() }) {
|
||||
Icon(
|
||||
Icons.Filled.CameraAlt,
|
||||
contentDescription = "Take photo",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { filePickerLauncher.launch(arrayOf("*/*")) }) {
|
||||
Icon(
|
||||
Icons.Filled.AttachFile,
|
||||
contentDescription = "Attach file",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { viewModel.openAddTagSheet() },
|
||||
enabled = state.canAddMoreTags,
|
||||
@@ -210,8 +337,7 @@ fun NoteEditorScreen(
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
) {
|
||||
// v0.3.0.1: colour picker centred horizontally (was left-aligned
|
||||
// LazyRow in v0.3.0.0). Six fixed entries → plain Row, no LazyRow.
|
||||
// v0.3.0.1: colour picker centred horizontally.
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -230,9 +356,6 @@ fun NoteEditorScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// v0.3.0.1: text field takes remaining vertical space via
|
||||
// weight(1f) instead of fillMaxSize() so the chip row below
|
||||
// it stays visible at the bottom.
|
||||
OutlinedTextField(
|
||||
value = state.content,
|
||||
onValueChange = viewModel::onContentChange,
|
||||
@@ -248,10 +371,28 @@ fun NoteEditorScreen(
|
||||
),
|
||||
)
|
||||
|
||||
// v0.3.0.1: hashtag chip row now sits at the bottom of the
|
||||
// editor. Hidden entirely when the note has no tags — the `#`
|
||||
// icon in the top bar is the only way to add tags (no `+ add`
|
||||
// chip anymore).
|
||||
// v0.3.1.0: attachment thumbnail strip. Combines persisted
|
||||
// attachments (loaded via observeAttachments in the VM) with
|
||||
// any pending attachments that haven't been saved yet. Each
|
||||
// thumbnail has a ✕ in the top-right corner; tap the
|
||||
// thumbnail to open the full-screen viewer.
|
||||
if (state.attachments.isNotEmpty() || state.pendingAttachments.isNotEmpty()) {
|
||||
AttachmentStrip(
|
||||
persisted = state.attachments,
|
||||
persistedBytes = emptyMap(), // resolved lazily in the viewer
|
||||
persistedViewerIds = state.attachments.associate { it.id to ViewerAttachmentId.Persisted(it.id) },
|
||||
persistedOpen = { id -> viewModel.openFullScreen(id) },
|
||||
persistedDelete = { id -> viewModel.deletePersistedAttachment(id) },
|
||||
pending = state.pendingAttachments,
|
||||
pendingBytes = state.pendingAttachmentBytes,
|
||||
pendingOpen = { tempId -> viewModel.openFullScreen(ViewerAttachmentId.Pending(tempId)) },
|
||||
pendingDelete = { tempId -> viewModel.removePendingAttachment(tempId) },
|
||||
// v0.3.1.1: source of bytes for persisted thumbnail lazy load
|
||||
repository = repository,
|
||||
)
|
||||
}
|
||||
|
||||
// v0.3.0.1: hashtag chip row at the bottom of the editor.
|
||||
HashtagChipRow(
|
||||
tags = state.hashtags,
|
||||
onRemove = { viewModel.removeTag(it) },
|
||||
@@ -278,17 +419,290 @@ fun NoteEditorScreen(
|
||||
onDismiss = { viewModel.closeAddTagSheet() },
|
||||
)
|
||||
}
|
||||
|
||||
// v0.3.1.0: full-screen image viewer.
|
||||
state.fullScreenAttachmentId?.let { viewerId ->
|
||||
if (repoForViewer != null) {
|
||||
val pendingBytes: ByteArray? = when (viewerId) {
|
||||
is ViewerAttachmentId.Pending -> state.pendingAttachmentBytes[viewerId.tempId]
|
||||
is ViewerAttachmentId.Persisted -> null // viewer loads from DB
|
||||
}
|
||||
ImageViewerScreen(
|
||||
attachmentId = viewerId,
|
||||
repository = repoForViewer,
|
||||
pendingBytes = pendingBytes,
|
||||
onClose = { viewModel.closeFullScreen() },
|
||||
)
|
||||
} else {
|
||||
// No repository access — viewer unavailable. Just close.
|
||||
viewModel.closeFullScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class)
|
||||
// ---------------------------------------------------------------------
|
||||
// v0.3.1.0 / v0.3.1.1: attachment strip + thumbnail helpers. v0.3.1.1
|
||||
// fix: persisted image attachments now render a thumbnail in the
|
||||
// editor strip (previously they fell through to the file-type
|
||||
// placeholder because `bytes` was null for them). Each persisted
|
||||
// thumbnail lazy-loads its own bytes via `produceState` so we don't
|
||||
// have to keep every attachment's bytes in memory.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AttachmentStrip(
|
||||
persisted: List<org.incido.domain.model.NoteAttachment>,
|
||||
persistedBytes: Map<Long, ByteArray>,
|
||||
persistedViewerIds: Map<Long, ViewerAttachmentId>,
|
||||
persistedOpen: (ViewerAttachmentId) -> Unit,
|
||||
persistedDelete: (Long) -> Unit,
|
||||
pending: List<PendingAttachment>,
|
||||
pendingBytes: Map<Long, ByteArray>,
|
||||
pendingOpen: (Long) -> Unit,
|
||||
pendingDelete: (Long) -> Unit,
|
||||
repository: org.incido.domain.repository.NoteRepository?,
|
||||
) {
|
||||
LazyRow(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 0.dp),
|
||||
) {
|
||||
items(persisted, key = { it.id }) { att ->
|
||||
AttachmentThumbnail(
|
||||
displayName = att.displayName,
|
||||
mimeType = att.mimeType,
|
||||
pendingBytes = null, // not a pending attachment
|
||||
attachmentId = att.id, // v0.3.1.1: drives the lazy DB load
|
||||
repository = repository, // v0.3.1.1: source of bytes
|
||||
// v0.3.1.2: lambda fires only for image attachments —
|
||||
// non-image taps launch a system viewer internally.
|
||||
onOpenImage = { persistedOpen(persistedViewerIds[att.id] ?: ViewerAttachmentId.Persisted(att.id)) },
|
||||
onRemove = { persistedDelete(att.id) },
|
||||
)
|
||||
}
|
||||
items(pending, key = { it.tempId }) { p ->
|
||||
AttachmentThumbnail(
|
||||
displayName = p.displayName,
|
||||
mimeType = p.mimeType,
|
||||
pendingBytes = pendingBytes[p.tempId],
|
||||
attachmentId = null, // pending, no DB id to load from
|
||||
repository = repository,
|
||||
onOpenImage = { pendingOpen(p.tempId) },
|
||||
onRemove = { pendingDelete(p.tempId) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AttachmentThumbnail(
|
||||
displayName: String,
|
||||
mimeType: String,
|
||||
/** In-memory bytes for a pending attachment (null for persisted). */
|
||||
pendingBytes: ByteArray?,
|
||||
/** DB id for a persisted attachment (null for pending). Drives the lazy DB load. */
|
||||
attachmentId: Long?,
|
||||
repository: org.incido.domain.repository.NoteRepository?,
|
||||
/** v0.3.1.2: fires only when the user taps an IMAGE thumbnail
|
||||
* (opens the in-app full-screen viewer). Non-image taps launch
|
||||
* the system viewer internally so PDFs / MP3s / etc. don't fall
|
||||
* into the bitmap decode path that would silently fail. */
|
||||
onOpenImage: () -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
) {
|
||||
val isImage = mimeType.startsWith("image/")
|
||||
val ctx = LocalContext.current
|
||||
|
||||
// v0.3.1.1: lazy-load bytes from DB for persisted image attachments
|
||||
// so the editor strip shows a thumbnail even after the note is
|
||||
// reopened. Re-keys on attachmentId so navigating between notes /
|
||||
// re-rendering re-fetches rather than reusing stale bytes.
|
||||
//
|
||||
// v0.3.1.3: widened to ALL mime types — non-image persisted
|
||||
// attachments also need their bytes loaded so the "open in default
|
||||
// app" tap handler can write a temp file and launch an
|
||||
// ACTION_VIEW intent. Previously the `isImage` gate caused the
|
||||
// handler to bail with a misleading "Loading…" Toast forever.
|
||||
val lazyBytes by produceState<ByteArray?>(initialValue = null, key1 = attachmentId) {
|
||||
if (pendingBytes == null && attachmentId != null && repository != null) {
|
||||
value = withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
repository.getAttachmentBytes(attachmentId)
|
||||
}
|
||||
}
|
||||
}
|
||||
val effectiveBytes: ByteArray? = pendingBytes ?: lazyBytes
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(96.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))
|
||||
// v0.3.1.2: branch on isImage — image taps open the
|
||||
// in-app viewer; non-image taps (PDF / MP3 / video / etc.)
|
||||
// write the bytes to a cache temp file and launch the
|
||||
// system viewer via FileProvider + ACTION_VIEW. The
|
||||
// previous unconditional viewer path silently failed for
|
||||
// non-image mime types (BitmapFactory.decodeByteArray
|
||||
// returns null and the viewer just shows "Loading…").
|
||||
.clickable {
|
||||
if (isImage) {
|
||||
onOpenImage()
|
||||
} else {
|
||||
val bytes = effectiveBytes
|
||||
if (bytes == null) {
|
||||
// Lazy load still in flight for a persisted
|
||||
// attachment — nudge the user instead of
|
||||
// silently doing nothing.
|
||||
Toast.makeText(ctx, "Loading\u2026", Toast.LENGTH_SHORT).show()
|
||||
return@clickable
|
||||
}
|
||||
runCatching {
|
||||
// Sanitise displayName for use as a filename —
|
||||
// strip any path separators / chars the OS
|
||||
// doesn't allow in filenames.
|
||||
val safeName = displayName.replace(Regex("[/\\\\:*?\"<>|]"), "_")
|
||||
// v0.3.1.3: write into a dedicated `open_outbox/`
|
||||
// subdir under cacheDir so it falls inside the
|
||||
// FileProvider's exposed path set (see
|
||||
// app/src/main/res/xml/file_paths.xml). Previously
|
||||
// this wrote straight to cacheDir which is NOT
|
||||
// exposed, so FileProvider.getUriForFile threw
|
||||
// IllegalArgumentException and the runCatching
|
||||
// swallowed it as the misleading "No app can
|
||||
// open …" toast.
|
||||
val outbox = File(ctx.cacheDir, "open_outbox").apply { mkdirs() }
|
||||
val tmp = File(
|
||||
outbox,
|
||||
"open_${System.currentTimeMillis()}_$safeName",
|
||||
).apply { createNewFile() }
|
||||
tmp.writeBytes(bytes)
|
||||
val uri = FileProvider.getUriForFile(
|
||||
ctx,
|
||||
"${ctx.packageName}.fileprovider",
|
||||
tmp,
|
||||
)
|
||||
val intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, mimeType)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
ctx.startActivity(intent)
|
||||
}.onFailure { err ->
|
||||
// v0.3.1.3: distinguish "no handler" from "couldn't
|
||||
// open". ActivityNotFoundException means the OS has
|
||||
// no app registered for this mime type (e.g. no
|
||||
// PDF viewer installed); anything else (typically
|
||||
// IllegalArgumentException from FileProvider when
|
||||
// file_paths.xml is misconfigured, or IOException
|
||||
// from the cache write) gets a generic message.
|
||||
val msg = if (err is android.content.ActivityNotFoundException) {
|
||||
"No app can open $displayName"
|
||||
} else {
|
||||
"Couldn't open $displayName"
|
||||
}
|
||||
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
) {
|
||||
// Image preview OR file-type fallback.
|
||||
if (isImage && effectiveBytes != null) {
|
||||
val bitmap = remember(effectiveBytes.contentHashCode()) {
|
||||
BitmapFactory.decodeByteArray(effectiveBytes, 0, effectiveBytes.size)
|
||||
}
|
||||
if (bitmap != null) {
|
||||
androidx.compose.foundation.Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = displayName,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
} else {
|
||||
// decode failed → fall back to icon
|
||||
FileTypePlaceholder(mimeType, displayName)
|
||||
}
|
||||
} else {
|
||||
// Non-image OR no bytes yet (still loading) — show placeholder.
|
||||
FileTypePlaceholder(mimeType, displayName)
|
||||
}
|
||||
// ✕ in top-right.
|
||||
IconButton(
|
||||
onClick = onRemove,
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.size(28.dp)
|
||||
.padding(2.dp)
|
||||
.background(
|
||||
color = Color.Black.copy(alpha = 0.55f),
|
||||
shape = CircleShape,
|
||||
),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
contentDescription = "Remove $displayName",
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FileTypePlaceholder(mimeType: String, displayName: String) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
modifier = Modifier.fillMaxSize().padding(6.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Description,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
androidx.compose.foundation.layout.Spacer(Modifier.size(4.dp))
|
||||
Text(
|
||||
text = displayName.take(14) + if (displayName.length > 14) "…" else "",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 2,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Existing editor UI (color swatch, hashtag chips, add-tag sheet)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun ColorSwatch(
|
||||
color: NoteColor,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val fillColor = color.toComposeColor()
|
||||
val border = if (selected) swatchBorderColor else MaterialTheme.colorScheme.outlineVariant
|
||||
val borderWidth = if (selected) 2.dp else 1.dp
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(36.dp)
|
||||
.clip(CircleShape)
|
||||
.background(fillColor)
|
||||
.border(borderWidth, border, CircleShape)
|
||||
.clickable(onClick = onClick),
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun HashtagChipRow(
|
||||
tags: List<String>,
|
||||
onRemove: (String) -> Unit,
|
||||
) {
|
||||
// v0.3.0.1: hide the row entirely when there are no hashtags. The
|
||||
// user opens the add-tag sheet via the `#` icon in the top bar; the
|
||||
// row only appears once at least one tag is present.
|
||||
if (tags.isEmpty()) return
|
||||
FlowRow(
|
||||
modifier = Modifier
|
||||
@@ -309,7 +723,7 @@ private fun HashtagChipRow(
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||
@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AddTagSheet(
|
||||
tagInput: String,
|
||||
@@ -370,22 +784,54 @@ private fun AddTagSheet(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColorSwatch(
|
||||
color: NoteColor,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val fillColor = color.toComposeColor()
|
||||
val border = if (selected) swatchBorderColor else MaterialTheme.colorScheme.outlineVariant
|
||||
val borderWidth = if (selected) 2.dp else 1.dp
|
||||
// ---------------------------------------------------------------------
|
||||
// v0.3.1.0: helpers (camera URI + SAF display-name query)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(36.dp)
|
||||
.clip(CircleShape)
|
||||
.background(fillColor)
|
||||
.border(borderWidth, border, CircleShape)
|
||||
.clickable(onClick = onClick),
|
||||
)
|
||||
/**
|
||||
* Create a temporary file in the app's cache and return a
|
||||
* FileProvider-scoped Uri pointing at it. The camera app writes a JPEG
|
||||
* there; we read the bytes and delete the temp file. Returns
|
||||
* `(uri, file)` so the caller can clean up if reading fails.
|
||||
*/
|
||||
private fun createTempCameraUri(ctx: Context): Pair<Uri?, File?> {
|
||||
return try {
|
||||
val outbox = File(ctx.cacheDir, "camera_outbox").apply { mkdirs() }
|
||||
val file = File(outbox, "cap_${System.currentTimeMillis()}.jpg")
|
||||
file.createNewFile()
|
||||
val authority = "${ctx.packageName}.fileprovider"
|
||||
val uri = FileProvider.getUriForFile(ctx, authority, file)
|
||||
uri to file
|
||||
} catch (e: Exception) {
|
||||
null to null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the Open Documents column DISPLAY_NAME for a content:// Uri,
|
||||
* falling back to the last path segment. Returns null if neither
|
||||
* works (which is fine — the caller uses a generated default).
|
||||
*/
|
||||
private fun queryDisplayName(resolver: android.content.ContentResolver, uri: Uri): String? {
|
||||
return try {
|
||||
resolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||
?.use { cursor ->
|
||||
if (cursor.moveToFirst()) {
|
||||
val idx = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
|
||||
if (idx >= 0) cursor.getString(idx) else null
|
||||
} else null
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight [BackHandler] wrapper to avoid pulling activity-compose
|
||||
* into the editor file for a single symbol. The platform back press
|
||||
* closes the editor or prompts for discard confirmation.
|
||||
*/
|
||||
@Composable
|
||||
private fun BackHandler(enabled: Boolean, onBack: () -> Unit) {
|
||||
androidx.activity.compose.BackHandler(enabled = enabled, onBack = onBack)
|
||||
}
|
||||
@@ -6,14 +6,19 @@ import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.AP
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.initializer
|
||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
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.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.compose.IncidoApplication
|
||||
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.repository.NoteRepository
|
||||
|
||||
@@ -37,17 +42,57 @@ data class NoteEditorUiState(
|
||||
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` while content is non-blank and not in the middle of saving. */
|
||||
val canSave: Boolean get() = content.isNotBlank() && !isSaving
|
||||
|
||||
/** `true` when editing an existing note (existing != null). */
|
||||
val isEditing: Boolean get() = existing != null
|
||||
|
||||
/** `true` when there's still room to add another tag. */
|
||||
val canAddMoreTags: Boolean get() = hashtags.size < MAX_TAGS
|
||||
|
||||
fun isDirty(initialContent: String, initialFavorite: Boolean, initialColor: NoteColor, initialTags: List<String>): Boolean {
|
||||
return content != initialContent ||
|
||||
isFavorite != initialFavorite ||
|
||||
color != initialColor ||
|
||||
hashtags != initialTags
|
||||
}
|
||||
/** Dirty-check used by the editor's back button. */
|
||||
fun isDirty(
|
||||
initialContent: String,
|
||||
initialFavorite: Boolean,
|
||||
initialColor: NoteColor,
|
||||
initialTags: List<String>,
|
||||
): Boolean = content != initialContent ||
|
||||
isFavorite != initialFavorite ||
|
||||
color != initialColor ||
|
||||
hashtags != initialTags
|
||||
|
||||
companion object {
|
||||
/** Hard cap on tags per note (matches Development Plan §6.1). */
|
||||
@@ -55,14 +100,57 @@ data class NoteEditorUiState(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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/")
|
||||
}
|
||||
|
||||
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(),
|
||||
) : ViewModel() {
|
||||
|
||||
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
|
||||
@@ -77,6 +165,13 @@ class NoteEditorViewModel(
|
||||
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()
|
||||
|
||||
init {
|
||||
// Tag autocomplete — re-query on every keystroke (debounced upstream
|
||||
// would be nice but ObjectBox is plenty fast for this size).
|
||||
@@ -94,9 +189,51 @@ class NoteEditorViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
// Load the note if editing.
|
||||
// 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) {
|
||||
_state.update { it.copy(isLoading = false) }
|
||||
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,
|
||||
content = initialSharedText.orEmpty(),
|
||||
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 ->
|
||||
@@ -176,6 +313,81 @@ class NoteEditorViewModel(
|
||||
_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) }
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 ----
|
||||
|
||||
fun save(onDone: () -> Unit) {
|
||||
val current = _state.value
|
||||
if (!current.canSave) return
|
||||
@@ -186,22 +398,35 @@ class NoteEditorViewModel(
|
||||
content = current.content,
|
||||
isFavorite = current.isFavorite,
|
||||
color = current.color,
|
||||
hashtags = current.hashtags,
|
||||
) ?: Note(
|
||||
content = current.content,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
isFavorite = current.isFavorite,
|
||||
color = current.color,
|
||||
hashtags = current.hashtags,
|
||||
)
|
||||
val saved = repository.upsert(toPersist)
|
||||
// Reconcile hashtag set vs. what was previously persisted.
|
||||
val previous = baseNote?.hashtags.orEmpty().toSet()
|
||||
val currentSet = current.hashtags.toSet()
|
||||
(previous - currentSet).forEach { repository.removeHashtag(saved.id, it) }
|
||||
(currentSet - previous).forEach { repository.addHashtag(saved.id, it) }
|
||||
_state.update { it.copy(isSaving = false) }
|
||||
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(isSaving = false, pendingAttachments = emptyList(), pendingAttachmentBytes = emptyMap()) }
|
||||
onDone()
|
||||
}
|
||||
}
|
||||
@@ -217,11 +442,40 @@ class NoteEditorViewModel(
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun factory(noteId: Long?): ViewModelProvider.Factory = viewModelFactory {
|
||||
fun factory(
|
||||
noteId: Long?,
|
||||
initialSharedText: String? = null,
|
||||
initialSharedImages: List<SharedImage> = emptyList(),
|
||||
): ViewModelProvider.Factory = viewModelFactory {
|
||||
initializer {
|
||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
||||
NoteEditorViewModel(app.container.noteRepository, noteId)
|
||||
NoteEditorViewModel(
|
||||
repository = app.container.noteRepository,
|
||||
noteId = noteId,
|
||||
initialSharedText = initialSharedText,
|
||||
initialSharedImages = initialSharedImages,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(),
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
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
|
||||
@@ -13,6 +16,7 @@ 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 kotlinx.coroutines.withContext
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.GenericShape
|
||||
@@ -21,12 +25,16 @@ import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.CheckBox
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Menu
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.PhotoCamera
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Star
|
||||
import androidx.compose.material.icons.outlined.StarOutline
|
||||
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
|
||||
@@ -39,12 +47,16 @@ 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.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
|
||||
@@ -52,8 +64,10 @@ 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.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* Right-triangle that fills the top-right corner of its bounds — a
|
||||
@@ -74,6 +88,8 @@ 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()
|
||||
@@ -91,11 +107,16 @@ fun NoteListScreen(
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (filterMode == NoteFilter.Home) {
|
||||
// v0.3.1.0: search is now context-aware on Home,
|
||||
// Favorites, and Untagged. 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")
|
||||
}
|
||||
}
|
||||
@@ -111,7 +132,7 @@ fun NoteListScreen(
|
||||
},
|
||||
) { padding ->
|
||||
Column(modifier = Modifier.padding(padding)) {
|
||||
if (filterMode == NoteFilter.Home && state.isSearchActive) {
|
||||
if (filterMode !is NoteFilter.ByTag && state.isSearchActive) {
|
||||
OutlinedTextField(
|
||||
value = localQuery,
|
||||
onValueChange = {
|
||||
@@ -136,6 +157,7 @@ fun NoteListScreen(
|
||||
onClick = { onOpenEditor(it.id) },
|
||||
onDelete = viewModel::delete,
|
||||
onToggleFavorite = viewModel::toggleFavorite,
|
||||
repository = repository,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -197,6 +219,8 @@ private fun NoteList(
|
||||
onClick: (Note) -> Unit,
|
||||
onDelete: (Long) -> Unit,
|
||||
onToggleFavorite: (Long, Boolean) -> Unit,
|
||||
/** v0.3.1.0 — threaded through to [NoteCard] for thumbnail loading. */
|
||||
repository: NoteRepository?,
|
||||
) {
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -214,6 +238,7 @@ private fun NoteList(
|
||||
onClick = { onClick(note) },
|
||||
onDelete = { onDelete(note.id) },
|
||||
onToggleFavorite = { onToggleFavorite(note.id, !note.isFavorite) },
|
||||
repository = repository,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -226,36 +251,100 @@ private fun NoteList(
|
||||
* - 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 / delete
|
||||
* 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, with a "Delete" entry as the first
|
||||
* item. The menu is designed to grow (Share, etc.) — additional
|
||||
* entries are added as `DropdownMenuItem`s.
|
||||
* - Card now uses `Modifier.combinedClickable` for click + long-click.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun NoteCard(
|
||||
note: Note,
|
||||
onClick: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
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?,
|
||||
) {
|
||||
val (title, body) = Note.titleAndBody(note.content)
|
||||
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
|
||||
|
||||
Box(modifier = Modifier.fillMaxWidth()) {
|
||||
Card(
|
||||
onClick = onClick,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = if (hasColor) {
|
||||
val tint = noteColor.toComposeColor()
|
||||
val surface = MaterialTheme.colorScheme.surface
|
||||
CardDefaults.cardColors(
|
||||
containerColor = lerp(surface, tint, 0.12f),
|
||||
// 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.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()
|
||||
.combinedClickable(
|
||||
onClick = onClick,
|
||||
onLongClick = { showMenu = true },
|
||||
),
|
||||
colors = CardDefaults.cardColors(containerColor = containerColor),
|
||||
) {
|
||||
// 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(),
|
||||
)
|
||||
} else {
|
||||
CardDefaults.cardColors()
|
||||
},
|
||||
) {
|
||||
// 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(
|
||||
@@ -283,16 +372,6 @@ private fun NoteCard(
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// v0.3.0.1: small circle chip removed — the
|
||||
// dog-ear below is now the colour indicator.
|
||||
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) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (bodyPreview.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.padding(top = 4.dp))
|
||||
@@ -313,7 +392,7 @@ private fun NoteCard(
|
||||
modifier = Modifier.size(14.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(modifier = Modifier.size(6.dp))
|
||||
Spacer(Modifier.size(6.dp))
|
||||
Text(
|
||||
text = checklistSummary,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
@@ -325,40 +404,84 @@ private fun NoteCard(
|
||||
Spacer(modifier = Modifier.padding(top = 4.dp))
|
||||
HashtagRow(hashtags = note.hashtags)
|
||||
}
|
||||
// v0.3.3.0: bottom row now only shows the
|
||||
// timestamp — the overflow (long-press) menu holds
|
||||
// the destructive action.
|
||||
Spacer(modifier = Modifier.padding(top = 8.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(
|
||||
text = rememberRelativeTimestamp(note.updatedAt),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
IconButton(onClick = onDelete) {
|
||||
Icon(
|
||||
Icons.Default.Delete,
|
||||
contentDescription = "Delete note",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// v0.3.0.1: dog-ear colour accent overlays the top-right corner.
|
||||
if (hasColor) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.size(28.dp)
|
||||
.background(
|
||||
color = noteColor.toComposeColor(),
|
||||
shape = DogEarShape,
|
||||
),
|
||||
)
|
||||
// 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 = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
DropdownMenu(
|
||||
expanded = showMenu,
|
||||
onDismissRequest = { showMenu = false },
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Delete") },
|
||||
leadingIcon = {
|
||||
Icon(
|
||||
Icons.Filled.Delete,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
showMenu = false
|
||||
onDelete()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Hotfix: favorite star moved from the title row to the
|
||||
// bottom-right corner, vertically aligned with the
|
||||
// three-dot overflow button above.
|
||||
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) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -393,4 +516,4 @@ private fun HashtagRow(hashtags: List<String>) {
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,13 +47,19 @@ class NoteListViewModel(
|
||||
private val _isSearchActive = MutableStateFlow(false)
|
||||
|
||||
/** Notes stream — switches on (filter, query) so the same ViewModel
|
||||
* instance handles Home, Favorites, Untagged, ByTag, and search. */
|
||||
* instance handles Home, Favorites, Untagged, ByTag, and search.
|
||||
*
|
||||
* v0.3.1.0: search is now **context-aware** — on Favorites or
|
||||
* Untagged, the typed query is intersected with the active filter
|
||||
* (only favourites / only untagged) rather than ignored. On Home,
|
||||
* search spans everything. 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 -> repository.observeFavorites()
|
||||
NoteFilter.Untagged -> repository.observeUntagged()
|
||||
NoteFilter.Favorites -> if (q.isBlank()) repository.observeFavorites() else repository.searchFavorites(q)
|
||||
NoteFilter.Untagged -> if (q.isBlank()) repository.observeUntagged() else repository.searchUntagged(q)
|
||||
is NoteFilter.ByTag -> repository.observeNotesForHashtag(f.hashtag)
|
||||
}
|
||||
}
|
||||
@@ -81,9 +87,11 @@ class NoteListViewModel(
|
||||
|
||||
fun setFilter(filter: NoteFilter) {
|
||||
filterMode.value = filter
|
||||
// Switching away from Home closes the search bar (search is
|
||||
// only meaningful in Home).
|
||||
if (filter != NoteFilter.Home && _isSearchActive.value) {
|
||||
// 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 = ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
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
|
||||
val isExport = mode == PassphraseDialogMode.EXPORT
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
val title = if (isExport) "Encrypt backup" else "Decrypt backup"
|
||||
val intro = if (isExport) {
|
||||
"Choose a passphrase to protect this backup. " +
|
||||
"You'll need it again to restore. Lost passphrases " +
|
||||
"cannot be recovered."
|
||||
} else {
|
||||
"Enter the passphrase you used when this backup was created. " +
|
||||
"Lost passphrases cannot be recovered."
|
||||
}
|
||||
val confirmLabel = if (isExport) "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. */
|
||||
enum class PassphraseDialogMode { EXPORT, IMPORT }
|
||||
|
||||
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,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,784 @@
|
||||
package org.incido.compose.ui.settings
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
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.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CenterAlignedTopAppBar
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Switch
|
||||
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.platform.LocalContext
|
||||
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 kotlinx.coroutines.launch
|
||||
import org.incido.compose.data.backup.BackupPreview
|
||||
import org.incido.compose.data.backup.EncryptedBackupCodec
|
||||
import org.incido.compose.data.settings.AutoLockTimeout
|
||||
import org.incido.compose.data.settings.ThemeMode
|
||||
|
||||
/**
|
||||
* v0.3.2.0: top-level settings screen.
|
||||
*
|
||||
* Sections:
|
||||
* 1. Appearance — theme + dynamic color
|
||||
* 2. Security — master toggle + lock-mode toggles (PIN xor Biometric)
|
||||
* + Reset PIN row + encryption + timeout
|
||||
* 3. Backup & Restore — export (plain/encrypted) + import
|
||||
* 4. About — version + release-notes dialog trigger
|
||||
*
|
||||
* v0.3.3.1 hotfix:
|
||||
* - "Encrypt notes at rest" toggle is now greyed out unless Security
|
||||
* is enabled AND a PIN or Biometric is configured.
|
||||
* - Importing an encrypted backup now opens the PassphraseDialog in
|
||||
* IMPORT mode (single field, no Generate/Copy/Confirm, no policy
|
||||
* check) instead of EXPORT mode.
|
||||
*
|
||||
* v0.3.3.0:
|
||||
* - Lock mode refactored: PIN and Biometric are mutually-exclusive
|
||||
* toggles (enabling one greys the other). A new "Reset PIN" row
|
||||
* appears when PIN is the active mode.
|
||||
* - Encrypted import: when the user picks an encrypted backup file,
|
||||
* the passphrase is now prompted for via `PassphraseDialog` before
|
||||
* the preview/confirm dialog chain runs. Previously the import
|
||||
* silently no-op'd.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
onBack: () -> Unit,
|
||||
onRequestPinSetup: () -> Unit,
|
||||
onRequestPinChange: () -> Unit,
|
||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
|
||||
) {
|
||||
val settings by viewModel.userSettings.collectAsStateWithLifecycle()
|
||||
val migrationState by viewModel.migrationState.collectAsStateWithLifecycle()
|
||||
val snackbar by viewModel.snackbar.collectAsStateWithLifecycle()
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val context = LocalContext.current
|
||||
|
||||
var showReleaseNotes by remember { mutableStateOf(false) }
|
||||
var showExportModePicker by remember { mutableStateOf(false) }
|
||||
var showPassphraseDialog by remember { mutableStateOf(false) }
|
||||
var pendingExportUri by remember { mutableStateOf<android.net.Uri?>(null) }
|
||||
var pendingImportUri by remember { mutableStateOf<android.net.Uri?>(null) }
|
||||
var pendingImportPassphrase by remember { mutableStateOf<CharArray?>(null) }
|
||||
var pendingPreview by remember { mutableStateOf<BackupPreview?>(null) }
|
||||
var showTimeoutDialog by remember { mutableStateOf(false) }
|
||||
|
||||
// SAF launchers
|
||||
val exportLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.CreateDocument("application/json"),
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
pendingExportUri = uri
|
||||
showExportModePicker = true
|
||||
}
|
||||
}
|
||||
|
||||
val importLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
scope.launch {
|
||||
// v0.3.3.0: sniff the first 8 bytes of the file so we can
|
||||
// ask for a passphrase up front for encrypted backups
|
||||
// (instead of silently no-op'ing the preview / import).
|
||||
val head: ByteArray = try {
|
||||
context.contentResolver.openInputStream(uri)?.use { stream ->
|
||||
val buf = ByteArray(EncryptedBackupCodec.MAGIC.size)
|
||||
val read = stream.read(buf)
|
||||
if (read <= 0) ByteArray(0) else buf.copyOf(read)
|
||||
} ?: ByteArray(0)
|
||||
} catch (_: java.io.IOException) {
|
||||
ByteArray(0)
|
||||
}
|
||||
val encrypted = head.isNotEmpty() && EncryptedBackupCodec.isEncrypted(head)
|
||||
pendingImportUri = uri
|
||||
if (encrypted) {
|
||||
// v0.3.3.1 hotfix: open the dialog in IMPORT mode so
|
||||
// it shows the "Decrypt backup" title + single field
|
||||
// (no Generate / Copy / Confirm / policy check).
|
||||
// Previously `pendingPassphraseMode` kept its default
|
||||
// of EXPORT, so the import flow opened the export
|
||||
// passphrase dialog.
|
||||
pendingPassphraseMode = PassphraseDialogMode.IMPORT
|
||||
showPassphraseDialog = true
|
||||
} else {
|
||||
// v0.3.3.3 hotfix: guard the preview call so an
|
||||
// unreadable / corrupt file surfaces a snackbar
|
||||
// instead of crashing the coroutine (and the app).
|
||||
val preview = try {
|
||||
viewModel.previewImport(uri, passphrase = null)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
if (preview == null) {
|
||||
pendingImportUri = null
|
||||
snackbarHostState.showSnackbar("Could not read backup file.")
|
||||
} else {
|
||||
pendingPreview = preview
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Snackbar effect
|
||||
LaunchedEffect(snackbar) {
|
||||
snackbar?.let {
|
||||
snackbarHostState.showSnackbar(it)
|
||||
viewModel.dismissSnackbar()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
CenterAlignedTopAppBar(
|
||||
title = { Text("Settings") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(padding)
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
AppearanceSection(
|
||||
themeMode = settings.themeMode,
|
||||
dynamicColor = settings.dynamicColor,
|
||||
onThemeMode = viewModel::setThemeMode,
|
||||
onDynamicColor = viewModel::setDynamicColor,
|
||||
)
|
||||
SecuritySection(
|
||||
settings = settings,
|
||||
onSecurityEnabled = viewModel::setSecurityEnabled,
|
||||
onEncryptionEnabled = viewModel::setEncryptionEnabled,
|
||||
onPinToggle = { on ->
|
||||
viewModel.setLockMode(if (on) SettingsViewModel.LockMode.PIN else SettingsViewModel.LockMode.NONE)
|
||||
if (on) onRequestPinSetup()
|
||||
},
|
||||
onBiometricToggle = { on ->
|
||||
viewModel.setLockMode(if (on) SettingsViewModel.LockMode.BIOMETRIC else SettingsViewModel.LockMode.NONE)
|
||||
},
|
||||
onResetPin = onRequestPinChange,
|
||||
onTimeoutClick = { showTimeoutDialog = true },
|
||||
biometricAvailable = remember {
|
||||
val app = context.applicationContext as org.incido.compose.IncidoApplication
|
||||
app.container.securityManager.isBiometricAvailable()
|
||||
},
|
||||
)
|
||||
BackupSection(
|
||||
onExport = {
|
||||
val stamp = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US)
|
||||
.format(java.util.Date())
|
||||
exportLauncher.launch("incido-backup-$stamp.${org.incido.compose.data.backup.BackupCodec.FILE_EXTENSION}")
|
||||
},
|
||||
onImport = { importLauncher.launch(arrayOf("application/json", "*/*")) },
|
||||
)
|
||||
AboutSection(
|
||||
version = SettingsViewModel.APP_VERSION,
|
||||
onVersionClick = { showReleaseNotes = true },
|
||||
)
|
||||
Spacer(Modifier.padding(top = 24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Dialogs ----
|
||||
|
||||
if (showReleaseNotes) {
|
||||
ReleaseNotesDialog(onDismiss = { showReleaseNotes = false })
|
||||
}
|
||||
|
||||
if (showExportModePicker) {
|
||||
AlertDialog(
|
||||
onDismissRequest = {
|
||||
showExportModePicker = false
|
||||
pendingExportUri = null
|
||||
},
|
||||
title = { Text("Export backup") },
|
||||
text = {
|
||||
Text("Choose how to protect the backup file. Encrypted " +
|
||||
"backups require a passphrase to restore.")
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
val uri = pendingExportUri
|
||||
showExportModePicker = false
|
||||
if (uri != null) {
|
||||
scope.launch { viewModel.exportPlain(uri) }
|
||||
}
|
||||
pendingExportUri = null
|
||||
}) { Text("Plain JSON") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = {
|
||||
showExportModePicker = false
|
||||
// The passphrase dialog itself handles the actual
|
||||
// export once the user enters a valid passphrase.
|
||||
pendingPassphraseUri = pendingExportUri
|
||||
pendingPassphraseMode = PassphraseDialogMode.EXPORT
|
||||
showPassphraseDialog = true
|
||||
}) { Text("Encrypted") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showPassphraseDialog && (pendingPassphraseUri != null || pendingImportUri != null)) {
|
||||
PassphraseDialog(
|
||||
mode = pendingPassphraseMode,
|
||||
onConfirm = { chars ->
|
||||
val exportUri = pendingPassphraseUri
|
||||
val importUri = pendingImportUri
|
||||
val mode = pendingPassphraseMode
|
||||
showPassphraseDialog = false
|
||||
pendingPassphraseUri = null
|
||||
if (mode == PassphraseDialogMode.EXPORT) {
|
||||
pendingExportUri = null
|
||||
if (exportUri != null) {
|
||||
scope.launch { viewModel.exportEncrypted(exportUri, chars) }
|
||||
}
|
||||
} else {
|
||||
// IMPORT — run preview with the entered passphrase.
|
||||
//
|
||||
// v0.3.3.3 hotfix: keep a retained COPY of the
|
||||
// passphrase for the confirm-dialog import step.
|
||||
// EncryptedBackupCodec.decrypt() zeroes whatever
|
||||
// CharArray it's handed, and the previous code
|
||||
// wiped the cached copy immediately after the
|
||||
// preview — so the Import button called
|
||||
// viewModel.import(uri, null), which threw
|
||||
// "Encrypted backup requires a passphrase" inside
|
||||
// an unguarded coroutine and crashed the app.
|
||||
pendingImportPassphrase = chars.copyOf()
|
||||
if (importUri != null) {
|
||||
scope.launch {
|
||||
// `chars` is consumed (zeroed) by the
|
||||
// decrypt step; the retained copy survives.
|
||||
val preview = try {
|
||||
viewModel.previewImport(importUri, passphrase = chars)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
if (preview == null) {
|
||||
pendingImportUri = null
|
||||
pendingImportPassphrase?.fill('0')
|
||||
pendingImportPassphrase = null
|
||||
snackbarHostState.showSnackbar("Incorrect passphrase.")
|
||||
} else {
|
||||
pendingPreview = preview
|
||||
}
|
||||
}
|
||||
} else {
|
||||
chars.fill('0')
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = {
|
||||
showPassphraseDialog = false
|
||||
pendingPassphraseUri = null
|
||||
pendingImportUri = null
|
||||
pendingImportPassphrase?.fill('0')
|
||||
pendingImportPassphrase = null
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pendingPreview?.let { preview ->
|
||||
AlertDialog(
|
||||
onDismissRequest = {
|
||||
pendingPreview = null
|
||||
pendingImportUri = null
|
||||
// v0.3.3.3 hotfix: dismissing via back / outside tap
|
||||
// must also wipe the retained passphrase (previously
|
||||
// only the Cancel button did).
|
||||
pendingImportPassphrase?.fill('0')
|
||||
pendingImportPassphrase = null
|
||||
},
|
||||
title = { Text("Import backup?") },
|
||||
text = {
|
||||
Column {
|
||||
Text("This backup contains:")
|
||||
Spacer(Modifier.padding(top = 6.dp))
|
||||
Text("• ${preview.noteCount} note(s)")
|
||||
Text("• ${preview.attachmentCount} attachment(s)")
|
||||
Text("• Exported from v${preview.appVersion}")
|
||||
Text("• ${java.text.DateFormat.getDateInstance().format(java.util.Date(preview.exportedAt))}")
|
||||
Spacer(Modifier.padding(top = 12.dp))
|
||||
Text(
|
||||
"Importing will add these notes to your existing library.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
val uri = pendingImportUri
|
||||
pendingPreview = null
|
||||
pendingImportUri = null
|
||||
if (uri != null) {
|
||||
// v0.3.3.0: pass the cached passphrase for
|
||||
// encrypted imports; null for plain JSON.
|
||||
//
|
||||
// v0.3.3.3 hotfix: hand import() a fresh COPY
|
||||
// of the retained passphrase — decrypt() zeroes
|
||||
// the array it consumes — and wipe the retained
|
||||
// copy in a finally block. The whole call is
|
||||
// wrapped in try/catch so any failure (wrong
|
||||
// passphrase re-decrypt, truncated file, I/O
|
||||
// error, malformed JSON) surfaces a snackbar
|
||||
// instead of crashing the app.
|
||||
scope.launch {
|
||||
val retained = pendingImportPassphrase
|
||||
try {
|
||||
viewModel.import(uri, retained?.copyOf())
|
||||
} catch (_: Exception) {
|
||||
snackbarHostState.showSnackbar(
|
||||
"Import failed. Check the file and passphrase.",
|
||||
)
|
||||
} finally {
|
||||
retained?.fill('0')
|
||||
pendingImportPassphrase = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}) { Text("Import") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = {
|
||||
pendingPreview = null
|
||||
pendingImportUri = null
|
||||
pendingImportPassphrase?.fill('0')
|
||||
pendingImportPassphrase = null
|
||||
}) {
|
||||
Text("Cancel")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showTimeoutDialog) {
|
||||
TimeoutDialog(
|
||||
current = settings.autoLockTimeout,
|
||||
onConfirm = {
|
||||
viewModel.setAutoLockTimeout(it)
|
||||
showTimeoutDialog = false
|
||||
},
|
||||
onDismiss = { showTimeoutDialog = false },
|
||||
)
|
||||
}
|
||||
|
||||
when (val state = migrationState) {
|
||||
is SettingsViewModel.MigrationState.Running -> {
|
||||
AlertDialog(
|
||||
onDismissRequest = {},
|
||||
title = { Text("Re-encrypting notes…") },
|
||||
text = {
|
||||
Column {
|
||||
Text("This can take a few seconds. Don't close the app.")
|
||||
Spacer(Modifier.padding(top = 12.dp))
|
||||
LinearProgressIndicator(progress = { state.progress })
|
||||
}
|
||||
},
|
||||
confirmButton = {},
|
||||
)
|
||||
}
|
||||
is SettingsViewModel.MigrationState.Done -> {
|
||||
AlertDialog(
|
||||
onDismissRequest = { viewModel.acknowledgeMigration() },
|
||||
title = { Text("Encryption updated") },
|
||||
text = { Text(state.message) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { viewModel.acknowledgeMigration() }) {
|
||||
Text("OK")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
is SettingsViewModel.MigrationState.Failed -> {
|
||||
AlertDialog(
|
||||
onDismissRequest = { viewModel.acknowledgeMigration() },
|
||||
title = { Text("Encryption failed") },
|
||||
text = { Text(state.reason) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { viewModel.acknowledgeMigration() }) {
|
||||
Text("OK")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/** Holder for the URI awaiting a passphrase (export flow). */
|
||||
private var pendingPassphraseUri: android.net.Uri? = null
|
||||
/** EXPORT or IMPORT — which flow triggered the passphrase dialog. */
|
||||
private var pendingPassphraseMode: PassphraseDialogMode = PassphraseDialogMode.EXPORT
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sections
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AppearanceSection(
|
||||
themeMode: ThemeMode,
|
||||
dynamicColor: Boolean,
|
||||
onThemeMode: (ThemeMode) -> Unit,
|
||||
onDynamicColor: (Boolean) -> Unit,
|
||||
) {
|
||||
SettingsSection(title = "Appearance") {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Text("Theme", style = MaterialTheme.typography.labelLarge)
|
||||
Spacer(Modifier.padding(top = 6.dp))
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
ThemeMode.values().forEachIndexed { index, mode ->
|
||||
SegmentedButton(
|
||||
selected = themeMode == mode,
|
||||
onClick = { onThemeMode(mode) },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = ThemeMode.values().size,
|
||||
),
|
||||
label = {
|
||||
Text(when (mode) {
|
||||
ThemeMode.SYSTEM -> "System"
|
||||
ThemeMode.LIGHT -> "Light"
|
||||
ThemeMode.DARK -> "Dark"
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.padding(top = 12.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("Dynamic color", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
"Use the system Material You palette on Android 12+.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(checked = dynamicColor, onCheckedChange = onDynamicColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.3.0: PIN and Biometric are mutually-exclusive toggles. When
|
||||
* the master security switch is off, both are greyed. When one is
|
||||
* on, the other is greyed. A "Reset PIN" row appears only when PIN
|
||||
* is the active mode.
|
||||
*/
|
||||
@Composable
|
||||
private fun SecuritySection(
|
||||
settings: org.incido.compose.data.settings.UserSettings,
|
||||
onSecurityEnabled: (Boolean) -> Unit,
|
||||
onEncryptionEnabled: (Boolean) -> Unit,
|
||||
onPinToggle: (Boolean) -> Unit,
|
||||
onBiometricToggle: (Boolean) -> Unit,
|
||||
onResetPin: () -> Unit,
|
||||
onTimeoutClick: () -> Unit,
|
||||
biometricAvailable: Boolean,
|
||||
) {
|
||||
SettingsSection(title = "Security") {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
SettingsToggle(
|
||||
title = "Enable security",
|
||||
subtitle = "Master switch. When off, none of the sub-features apply.",
|
||||
checked = settings.securityEnabled,
|
||||
onCheckedChange = onSecurityEnabled,
|
||||
)
|
||||
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
|
||||
SettingsToggle(
|
||||
title = "PIN",
|
||||
subtitle = "Use an app-only 4–6 digit PIN to unlock Incido.",
|
||||
checked = settings.pinEnabled,
|
||||
enabled = settings.securityEnabled && !settings.useBiometric,
|
||||
onCheckedChange = onPinToggle,
|
||||
)
|
||||
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
|
||||
SettingsToggle(
|
||||
title = "Biometrics",
|
||||
subtitle = if (biometricAvailable) {
|
||||
"Use the device's fingerprint or face to unlock Incido."
|
||||
} else {
|
||||
"Not available — no biometric is enrolled on this device."
|
||||
},
|
||||
checked = settings.useBiometric,
|
||||
enabled = settings.securityEnabled && !settings.pinEnabled && biometricAvailable,
|
||||
onCheckedChange = onBiometricToggle,
|
||||
)
|
||||
if (settings.pinEnabled) {
|
||||
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
|
||||
SettingsRow(
|
||||
title = "Reset PIN",
|
||||
subtitle = "Choose a new app-only PIN.",
|
||||
onClick = onResetPin,
|
||||
)
|
||||
}
|
||||
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
|
||||
SettingsToggle(
|
||||
title = "Encrypt notes at rest",
|
||||
// v0.3.3.1 hotfix: greyed out until Security is on
|
||||
// AND a PIN or Biometric is configured. Matches the
|
||||
// intent of `UserSettings.isEncryptionActive` (already
|
||||
// gated on the securityEnabled flag) plus the lock
|
||||
// requirement so the encryption key can't be set up
|
||||
// against an "anyone-can-open" lock state.
|
||||
subtitle = if (settings.securityEnabled && (settings.pinEnabled || settings.useBiometric)) {
|
||||
"AES-256 encryption for the local database. " +
|
||||
"Toggling requires an app restart."
|
||||
} else {
|
||||
"AES-256 encryption for the local database. " +
|
||||
"Toggling requires an app restart. " +
|
||||
"Enable Security and set a PIN or Biometric first."
|
||||
},
|
||||
checked = settings.encryptionEnabled,
|
||||
// v0.3.3.1: gate the toggle in the UI so it can't be
|
||||
// flipped while Security / PIN / Biometric is missing.
|
||||
enabled = settings.securityEnabled && (settings.pinEnabled || settings.useBiometric),
|
||||
onCheckedChange = onEncryptionEnabled,
|
||||
)
|
||||
if (settings.isLockActive) {
|
||||
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
|
||||
SettingsRow(
|
||||
title = "Auto-lock after",
|
||||
subtitle = settings.autoLockTimeout.label,
|
||||
onClick = onTimeoutClick,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BackupSection(
|
||||
onExport: () -> Unit,
|
||||
onImport: () -> Unit,
|
||||
) {
|
||||
SettingsSection(title = "Backup & Restore") {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
"Export your notes to a JSON file (with optional passphrase " +
|
||||
"encryption) or import a backup. Imports are additive — " +
|
||||
"they don't replace your existing notes.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(onClick = onExport, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Export to file…")
|
||||
}
|
||||
OutlinedButton(onClick = onImport, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Import from file…")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AboutSection(
|
||||
version: String,
|
||||
onVersionClick: () -> Unit,
|
||||
) {
|
||||
SettingsSection(title = "About") {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onVersionClick)
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("Incido", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
text = "Version $version",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = "Tap for release notes",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Building blocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun SettingsSection(title: String, content: @Composable () -> Unit) {
|
||||
Column {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(start = 4.dp, top = 8.dp, bottom = 4.dp),
|
||||
)
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** v0.3.3.0: optionally renders a disabled (greyed) switch — used for
|
||||
* the mutually-exclusive PIN / Biometric toggles. */
|
||||
@Composable
|
||||
private fun SettingsToggle(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
val color = if (enabled) {
|
||||
MaterialTheme.colorScheme.onSurface
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
val subColor = if (enabled) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium, color = color)
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = subColor,
|
||||
)
|
||||
}
|
||||
Switch(checked = checked, onCheckedChange = onCheckedChange, enabled = enabled)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SettingsRow(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TimeoutDialog(
|
||||
current: AutoLockTimeout,
|
||||
onConfirm: (AutoLockTimeout) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var selected by remember { mutableStateOf(current) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Auto-lock after") },
|
||||
text = {
|
||||
Column {
|
||||
AutoLockTimeout.values().forEach { option ->
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { selected = option }
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
androidx.compose.material3.RadioButton(
|
||||
selected = selected == option,
|
||||
onClick = { selected = option },
|
||||
)
|
||||
Spacer(Modifier.padding(start = 8.dp))
|
||||
Text(option.label)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { onConfirm(selected) }) { Text("OK") } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
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.security.ObjectBoxKeyProvider
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
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,
|
||||
) : 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: clear every sub-flag + wipe the stored PIN
|
||||
// hash/salt + drop the ObjectBox encryption key.
|
||||
settings.setSecurityEnabled(false)
|
||||
settings.setPinEnabled(false)
|
||||
settings.setEncryptionEnabled(false)
|
||||
settings.setUseBiometric(false)
|
||||
security.clearPin()
|
||||
objectBoxKeyProvider.deleteKey()
|
||||
_snackbar.value = "Security disabled."
|
||||
}
|
||||
|
||||
fun setEncryptionEnabled(enabled: Boolean) = viewModelScope.launch {
|
||||
if (!_migrationState.value.canStart) return@launch
|
||||
// v0.3.2.0 MVP: toggling encryption requires the app to be
|
||||
// restarted so the BoxStore can be re-opened with the right
|
||||
// key. We flip the flag and surface a migration notice — the
|
||||
// full BoxStore re-open is handled by AppContainer on next
|
||||
// process start.
|
||||
_migrationState.value = MigrationState.Running(0f)
|
||||
try {
|
||||
if (enabled) {
|
||||
// Generate the key now so it's ready for the next launch.
|
||||
objectBoxKeyProvider.getOrCreateKey()
|
||||
settings.setEncryptionEnabled(true)
|
||||
} else {
|
||||
objectBoxKeyProvider.deleteKey()
|
||||
settings.setEncryptionEnabled(false)
|
||||
}
|
||||
_migrationState.value = MigrationState.Done(
|
||||
message = if (enabled) {
|
||||
"Encryption will be enabled on next app launch."
|
||||
} else {
|
||||
"Encryption will be disabled on next app launch."
|
||||
},
|
||||
)
|
||||
} catch (t: Throwable) {
|
||||
_migrationState.value = MigrationState.Failed(t.message ?: "Migration failed")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 count = backupManager.import(uri, passphrase)
|
||||
_snackbar.value = "Imported $count note(s)."
|
||||
}
|
||||
|
||||
// --- 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.3.3.4"
|
||||
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,225 @@
|
||||
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).
|
||||
*/
|
||||
@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()
|
||||
|
||||
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 {
|
||||
error = "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")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user