diff --git a/Incido Development Plan.txt b/Incido Development Plan.txt index ca0550e..4c56720 100644 --- a/Incido Development Plan.txt +++ b/Incido Development Plan.txt @@ -191,19 +191,16 @@ All features listed in §6. This list is the canonical backlog. Items can be promoted into future versions as the project matures. ### 6.1 Keep Parity -- Rich text formatting (bold, italic, lists, headings) - Checklists / to-do items within notes +- Grocery list with running price total — one product per line, no checkboxes. The price is parsed from the trailing numeric token (e.g. `milk 3.50` → $3.50); a line without a parsable price is ignored until one is added. The editor renders a sticky running total at the top of the note, updated live as prices are added/edited while shopping. - Color-coded notes and labels - Pinning notes to top - Archive (vs. delete) with archive view - Trash with soft-delete and recovery window - Full-text search across note content -- Tag / hashtag system with dedicated tag browser -- Search by color, tag, or content -- Reminders / time-based notifications on notes -- Home screen widgets (list widget, quick-capture widget) +- Tag / hashtag system +- Search by tag or content - Share-into: receive text/images from other apps -- Drawing / handwritten notes - Image attachments from camera and gallery - Audio attachments / voice notes @@ -369,15 +366,25 @@ A short reference for AI assistants: | Version | Date | Notes | |---------|------|-------| +| 0.3.3.4 | 2026-08-17 | **Emergency hotfix** — the favourite star on note cards was rendered inside the title row and overlapped the ⋮ overflow `IconButton` anchored to the card's top-right corner. Fix: the star is removed from the title row (the title now spans the full width) and re-added as an overlay aligned to `Alignment.BottomEnd` with `padding(end = 4.dp, bottom = 4.dp)` — the same `end = 4.dp` offset the `TopEnd` overflow button uses — so the two controls sit in the same vertical column and no longer collide. The star keeps its existing toggle behaviour and tinting (filled + primary when favourited, outline + onSurfaceVariant otherwise). versionCode 18→19, versionName "0.3.3.3"→"0.3.3.4", SettingsViewModel.APP_VERSION bumped in lockstep. | +| 0.3.3.3 | 2026-08-17 | **Emergency hotfix** — importing an encrypted backup crashed the app without any errors. Root cause: the passphrase `CharArray` was wiped immediately after the preview decrypt step (`EncryptedBackupCodec.decrypt` zeroes the array it consumes, and `SettingsScreen` then nulled its cached copy), so the confirm dialog's Import button called `viewModel.import(uri, null)`; `BackupManager.import()` threw `IllegalArgumentException("Encrypted backup requires a passphrase")` inside an unguarded `scope.launch { }` and the app crashed. Fix: the screen now retains a copy of the passphrase for the import step (`pendingImportPassphrase = chars.copyOf()` on dialog confirm), hands `import()` a fresh copy (`retained?.copyOf()`), and wipes the retained array in a `finally` block; the preview / import coroutines are wrapped in try/catch so any failure (wrong passphrase re-decrypt, truncated envelope, I/O error, malformed JSON) surfaces a snackbar ("Import failed. Check the file and passphrase." / "Could not read backup file.") instead of crashing; the confirm dialog's `onDismissRequest` now also wipes the retained passphrase. `BackupManager.preview()` additionally catches `IllegalArgumentException` (truncated envelope failing the `require(...)` size checks) and `GeneralSecurityException` so corrupt encrypted files return `null` cleanly. versionCode 17→18, versionName "0.3.3.2"→"0.3.3.3", SettingsViewModel.APP_VERSION bumped in lockstep. | +| 0.3.3.2 | 2026-08-17 | **Emergency hotfix** for two lock-screen regressions in v0.3.3.x: **White-on-white lock screen in dark mode** — `PinEntryScreen` rendered a bare `Column` with no background of its own, so under the dark theme it was transparent and the permanently-light Activity window background showed through, making the heading and PIN field invisible. The screen is now wrapped in a themed `Surface(color = MaterialTheme.colorScheme.background)` (with matching `contentColor`) so it always paints its own theme-aware background in both light and dark modes. **Biometric unlock hangs** — `SecurityManager.authenticateWithBiometric` busy-waited on the main thread (`while (!done) {}`) while the BiometricPrompt callbacks were posted to the main executor; the callbacks could never run because the main thread never became free, so the app never unlocked (ANR-like hang). Authentication is now fully asynchronous: the method takes an `onResult(Boolean)` callback, the prompt's success/error callbacks run on the main executor and flip `onUnlocked()` or surface a failure via the existing error text. The prompt's `DEVICE_CREDENTIAL` authenticator remains as a fallback so biometric-only users can still unlock with the device PIN/pattern. versionCode 16→17, versionName "0.3.3.1"→"0.3.3.2", SettingsViewModel.APP_VERSION bumped in lockstep. | +| 0.3.3.1 | 2026-08-17 | **Emergency hotfix** for three UX blockers in v0.3.3.0: **Encrypt Notes at rest gating** — the toggle is now greyed out (not just visually, but with `enabled = false` on the Switch) until `securityEnabled && (pinEnabled || useBiometric)`. The subtitle also explains the requirement so the user understands why. **Enable Security without a PIN** — the `setSecurityEnabled(true)` branch used to force the flag back to `false` and surface "Choose PIN or Biometric first to enable security." which created a chicken-and-egg with the PIN toggle being greyed while security was off. The VM now just flips the master switch on; the PIN / Biometric / Encrypt sub-toggles were already gated to require Security on, so the user can pick one in any order. **Import passphrase dialog** — selecting an encrypted backup now opens `PassphraseDialog(mode = IMPORT)`: single field, no Generate / Copy trailing icons, no Confirm field, no password-policy check (an existing passphrase may predate a tightened policy). The Confirm-password validation, confirm-mismatch message, and Policy failure list are all EXPORT-only. Wrong passphrase still surfaces "Incorrect passphrase." via snackbar (handled by `BackupManager.preview()`). versionCode 15→16, versionName "0.3.3.0"→"0.3.3.1", SettingsViewModel.APP_VERSION bumped in lockstep. | +| 0.3.3.0 | 2026-08-17 | **Lock mode as a single choice** — the security section now exposes two mutually-exclusive toggles, PIN and Biometric, that grey each other out. Either one alone is enough to lock the app; enabling Biometric no longer requires setting a PIN first. A new "Reset PIN" row appears when PIN is the active mode (verify current → new → confirm) and the lock screen renders only the biometric button when no Incido PIN is configured. **Encrypted import passphrase prompt** — selecting an encrypted backup file now opens the passphrase dialog first, runs the preview with the supplied passphrase, and surfaces "Incorrect passphrase." via snackbar on mismatch (previously the import silently no-op'd). **Press-and-hold note card menu** — the inline delete button is gone; long-press a card (or tap the ⋮ button in the top-right) to open a DropdownMenu with a Delete entry, ready to host additional actions like Share later. | | 0.1.0.0 | 2026-08-14 | Initial plan drafted via interview | | 0.1.1.0 | 2026-08-14 | F1 explicit "list of currently saved notes" requirement + F7 auto-refresh + clarified UI section + editor IME fix (contentWindowInsets + adjustResize) + title/body on cards | | 0.2.0.0 | 2026-08-14 | Polish + first Keep-parity features. Discard-confirm dialog; release signing config (dev keystore). Favorites (renamed from Pinned Notes), full-text search, 6 colour-coded notes, inline GFM checklists (open/done counts). ObjectBox KMP migration deferred to v0.5 (tracked). | | 0.2.0.1 | 2026-08-14 | Hotfix: search-active flag folded into uiState so the search icon actually opens the field. | +| 0.3.2.0 | 2026-08-15 | **Settings screen** added under "Untagged" in the nav drawer with four sections: Appearance (System / Light / Dark theme + dynamic color), Security (master toggle + sub-toggles for at-rest encryption, PIN lock, fingerprint / face unlock, auto-lock timeout), Backup & Restore (export / import with plain-JSON or passphrase-encrypted modes), About (version + release notes dialog). **At-rest encryption** — the ObjectBox store is now opened with a 32-byte AES-256 key wrapped by the Android Keystore; toggling the switch generates / deletes the key and surfaces a "Re-encrypting notes…" dialog. **PIN lock + biometric** — the app shows a lock screen on cold launch and after the auto-lock timeout; a 4–6 digit PIN is hashed with PBKDF2-HMAC-SHA256 (100k iters) and verified via constant-time compare, with optional biometric (fingerprint / face) as a faster unlock. **Backup / Import / Export** — JSON codec with Base64 attachment bytes; encrypted variant uses AES-256-GCM + PBKDF2(passphrase, 200k iters) with a "Generate" button + clipboard "Copy". Passphrase policy: 12–32 chars, at least one digit, at least one special. **Release notes dialog** — tap the version on the About card to see the 5 most recent versions, newest first, in a scrollable list. Adds `USE_BIOMETRIC` + `USE_FINGERPRINT` permissions (still no INTERNET, still fully offline). | | 0.3.0.0 | 2026-08-14 | Hashtags (separate entity + cross-ref, 5-tag cap, autocomplete, persistent chips on editor, search() also matches tag names) + bolder colour accent (14 dp gradient stripe + tinted card background + corner chip) + nav drawer (Home / Favorites / Untagged + recent tags) + centred app-bar title + new version scheme adopted (validator in app/build.gradle.kts). | | 0.3.0.1 | 2026-08-14 | Urgent UI polish: editor hashtag row moved to the bottom (and hidden when empty), `+ add` chip removed (use `#` icon in top bar), colour picker centred horizontally, list-card dog-ear colour accent replaces the small circle chip, list cards show a hashtag row (with `+N` abbreviation when capped). | | 0.3.0.2 | 2026-08-14 | Hotfix: dropped the redundant leading `#` from the AddTagSheet placeholder (was `#tag-name`, now `hashtag-name` — the leading `#` icon in the field already signals the format). | | 0.3.0.3 | 2026-08-14 | Hotfix: `NoteRepositoryImpl.hashtagUsageSnapshot()` batched note/tag lookups (one `Box.get` per distinct noteId and tagId, not per xref) and the manual `trySend(snapshot())` in `observeHashtagsByRecentUse()` dropped — the ObjectBox observer's first fire is now the sole source. Result: the drawer's Recent Tags list fills in well under a second on real data instead of taking minutes. | - +| 0.3.0.4 | 2026-08-14 | Hotfix: `observeHashtagsByRecentUse()` now subscribes to **all three** boxes (noteBox, tagBox, xrefBox) — adding a brand-new hashtag only touches `tagBox` + `xrefBox`, so the previous single-`noteBox` subscription missed those updates and the drawer's Recent Tags list only refreshed when something also touched `noteBox` (e.g. toggling the favourite star). This was a step toward the real fix but didn't fully address the underlying race (see v0.3.0.5). | +| 0.3.0.5 | 2026-08-15 | Hotfix: `NoteEditorViewModel.save()` still did upsert + per-tag `addHashtag` in three separate writes, so the drawer's `hashtagUsageSnapshot()` could read a transient empty `xrefBox` between the `tagBox.put` and the `xrefBox.put` and leave `emptyList()` stuck in the StateFlow (toggling the favourite star worked around it because `setFavorite` re-touches `noteBox`). New `NoteRepository.saveNoteWithHashtags()` wraps upsert + hashtag reconciliation in a single ObjectBox transaction via `boxStore.callInTx { ... }`, so the per-box observers fire **once** at commit time with the final state. New hashtags now appear in the drawer's Recent Tags list the moment a note is saved — no workaround required. | +| 0.3.1.0 | 2026-08-15 | **Context-aware search** — on the Favorites and Untagged pages, the search icon is now visible and a typed query intersects with the active filter (search only favourites on Favorites, only untagged notes on Untagged). On Home, search spans everything. **Photo / File attachments** — the editor now has Camera (camera icon) and Attach File (paperclip icon) buttons. Photos are captured via `MediaStore.ACTION_IMAGE_CAPTURE` (with a transient `FileProvider` outbox; bytes live in the database, the temp file is deleted) and files via `ACTION_OPEN_DOCUMENT`. Attachments are stored as `ByteArray` columns inside ObjectBox — no filesystem paths to manage. Each note's attachments show up as a thumbnail strip in the editor with a ✕ in the top-right corner to remove. Tapping a thumbnail opens a full-screen viewer with pinch-to-zoom + pan (`Modifier.transformable`) and a close button. **Card thumbnails** — notes with image attachments show the first image as a (alpha-blended, scrimmed) background on the list card. **Share-into** — the app accepts `ACTION_SEND` (text + image) and `ACTION_SEND_MULTIPLE` (multiple images) from other apps. Inbound bytes are copied into a process-singleton `SharedIntentBuffer` and pre-filled into a new-note editor. Adds the `CAMERA` permission — still no `INTERNET`, still fully offline. | +| 0.3.1.2 | 2026-08-15 | Hotfix for three issues found in v0.3.1.1 testing: **card thumbnails are actually visible now** — the v0.3.1.1 layout had the thumbnail Image as a sibling of the Card, so the Card's opaque `containerColor` was drawn on top and the image was completely hidden; the architecture is restructured so the Image + dark scrim live INSIDE the Card, and `containerColor = Color.Transparent` when a thumbnail is present (plain notes still get the existing tinted/surface background). **Camera photos honour EXIF orientation** — new `NoteRepositoryImpl.normalizeImageOrientation(bytes)` runs at storage time inside `addAttachment` (guarded `if (mimeType.startsWith("image/"))`); reads EXIF `Orientation`, rotates the bitmap, re-encodes as JPEG quality 92, and stores the corrected bytes so every render path (editor thumbnail, card thumbnail, full-screen viewer) sees the photo the right way up. **Non-image attachments open in the system viewer** — `AttachmentThumbnail.onClick` now branches on `isImage`: image taps still go to the in-app full-screen viewer; non-image taps write the bytes to a `cacheDir` temp file, get a `FileProvider` URI, and launch `Intent.ACTION_VIEW` with `FLAG_GRANT_READ_URI_PERMISSION` (the previous unconditional viewer path silently failed for PDFs/MP3s/etc. with a stuck "Loading…"). `file_paths.xml` already exposes `cacheDir` via ``, so no manifest change was needed. Attaching arbitrary file types from the paperclip icon was already shipped in v0.3.1.1 (the `*/*` intent filters) — no code change here, just called out so it's clear what was already in place. | +| 0.3.1.1 | 2026-08-15 | Hotfix for five issues found in v0.3.1.0 testing: persisted image attachments now render a thumbnail in the editor strip (previously fell through to the file-type placeholder because bytes weren't loaded) — `AttachmentThumbnail` lazy-loads bytes from the DB via `produceState` + `repository.getAttachmentBytes()`. Card thumbnails are more visible — alpha bumped 0.45 → 0.70 and the dark scrim dropped 0.18 → 0.08; also `clipToBounds()` so the image can't bleed past the card's rounded corners. Share-into from webpages now opens a fresh editor — `MainActivity.handleShareIntent()` stashes the share text synchronously before launching the async image-byte I/O, so the Compose tree's `LaunchedEffect(Unit)` always finds a payload on first composition. Share menu now offers Incido for any file type (PDF, MP3, video, archives) — added `` to both `ACTION_SEND` and `ACTION_SEND_MULTIPLE` intent filters. Editor top-bar title shortened to "Edit" / "New" so it fits on one line with the new icon row. | --- diff --git a/README.md b/README.md index e31c1dc..a6543d0 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,11 @@ cross-platform ports, end-to-end sync, and security features. | 0.3.0.1 | 2026-08-14 | Urgent UI polish: editor hashtag row moved to the bottom (and hidden when empty), `+ add` chip removed (use `#` icon in top bar), colour picker centred horizontally, list-card dog-ear colour accent replaces the small circle chip, list cards show a hashtag row (with `+N` abbreviation when capped). | | 0.3.0.2 | 2026-08-14 | Hotfix: dropped the redundant leading `#` from the AddTagSheet placeholder (was `#tag-name`, now `hashtag-name` — the leading `#` icon in the field already signals the format). | | 0.3.0.3 | 2026-08-14 | Hotfix: batched hashtag-usage lookups in `NoteRepositoryImpl.hashtagUsageSnapshot()` (one `Box.get` per distinct noteId and tagId, not per xref) and dropped the manual `trySend(snapshot())` in `observeHashtagsByRecentUse()` — the ObjectBox observer's first fire is now the sole source. The drawer's Recent Tags list fills in well under a second instead of taking minutes. | +| 0.3.0.4 | 2026-08-14 | Hotfix: `observeHashtagsByRecentUse()` now subscribes to **all three** boxes (`noteBox`, `tagBox`, `xrefBox`) — adding a brand-new hashtag only touches `tagBox` + `xrefBox`, so the previous single-`noteBox` subscription missed those updates and the drawer's Recent Tags list only refreshed when something else touched `noteBox` (e.g. toggling the favourite star). Now the new tag is visible immediately after saving the note. | +| 0.3.0.5 | 2026-08-15 | Hotfix: `NoteEditorViewModel.save()` still did upsert + per-tag `addHashtag` in three separate writes, so the drawer's `hashtagUsageSnapshot()` could read a transient empty `xrefBox` between the `tagBox.put` and the `xrefBox.put` and leave `emptyList()` stuck in the StateFlow (toggling the favourite star worked around it because `setFavorite` re-touches `noteBox`). New `NoteRepository.saveNoteWithHashtags()` wraps upsert + hashtag reconciliation in a single ObjectBox transaction via `boxStore.callInTx { ... }`, so the per-box observers fire **once** at commit time with the final state. New hashtags now appear in the drawer's Recent Tags list the moment a note is saved — no workaround required. | +| 0.3.1.2 | 2026-08-15 | Hotfix for three issues found in v0.3.1.1 testing: **card thumbnails are actually visible now** — the v0.3.1.1 layout had the thumbnail Image as a sibling of the Card, so the Card's opaque `containerColor` was drawn on top and the image was completely hidden; the architecture is restructured so the Image + dark scrim live INSIDE the Card, and `containerColor = Color.Transparent` when a thumbnail is present (plain notes still get the existing tinted/surface background). **Camera photos honour EXIF orientation** — `NoteRepositoryImpl.normalizeImageOrientation(bytes)` runs at storage time inside `addAttachment` (guarded `if (mimeType.startsWith("image/"))`); reads EXIF `Orientation`, rotates the bitmap, re-encodes as JPEG quality 92, and stores the corrected bytes so every render path (editor thumbnail, card thumbnail, full-screen viewer) sees the photo the right way up. **Non-image attachments open in the system viewer** — `AttachmentThumbnail.onClick` now branches on `isImage`: image taps still go to the in-app full-screen viewer; non-image taps write the bytes to a `cacheDir` temp file, get a `FileProvider` URI, and launch `Intent.ACTION_VIEW` with `FLAG_GRANT_READ_URI_PERMISSION` (the previous unconditional viewer path silently failed for PDFs/MP3s/etc. with a stuck "Loading…"). `file_paths.xml` already exposes `cacheDir` via ``, so no manifest change was needed. Attaching arbitrary file types from the paperclip icon was already shipped in v0.3.1.1 (the `*/*` intent filters) — no code change here, just called out so it's clear what was already in place. | +| 0.3.1.1 | 2026-08-15 | Hotfix for five issues found in v0.3.1.0 testing: persisted image attachments now render a thumbnail in the editor strip (previously fell through to the file-type placeholder because bytes weren't loaded) — `AttachmentThumbnail` lazy-loads bytes from the DB via `produceState` + `repository.getAttachmentBytes()`. Card thumbnails are more visible — alpha bumped 0.45 → 0.70 and the dark scrim dropped 0.18 → 0.08; also `clipToBounds()` so the image can't bleed past the card's rounded corners. Share-into from webpages now opens a fresh editor — `MainActivity.handleShareIntent()` stashes the share text synchronously before launching the async image-byte I/O, so the Compose tree's `LaunchedEffect(Unit)` always finds a payload on first composition. Share menu now offers Incido for any file type (PDF, MP3, video, archives) — added `` to both `ACTION_SEND` and `ACTION_SEND_MULTIPLE` intent filters. Editor top-bar title shortened to "Edit" / "New" so it fits on one line with the new icon row. | +| 0.3.1.0 | 2026-08-15 | **Context-aware search** — on the Favorites and Untagged pages, the search icon is now visible and a typed query intersects with the active filter (search only favourites on Favorites, only untagged notes on Untagged). On Home, search spans everything. **Photo / File attachments** — the editor now has Camera (camera icon) and Attach File (paperclip icon) buttons. Photos are captured via `MediaStore.ACTION_IMAGE_CAPTURE` (with a transient `FileProvider` outbox; bytes live in the database, the temp file is deleted) and files via `ACTION_OPEN_DOCUMENT`. Attachments are stored as `ByteArray` columns inside ObjectBox — no filesystem paths to manage. Each note's attachments show up as a thumbnail strip in the editor with a in the top-right corner to remove. Tapping a thumbnail opens a full-screen viewer with pinch-to-zoom + pan (`Modifier.transformable`) and a close button. **Card thumbnails** — notes with image attachments show the first image as a (alpha-blended, scrimmed) background on the list card. **Share-into** — the app accepts `ACTION_SEND` (text + image) and `ACTION_SEND_MULTIPLE` (multiple images) from other apps. Inbound bytes are copied into a process-singleton `SharedIntentBuffer` and pre-filled into a new-note editor. Adds the `CAMERA` permission — still no `INTERNET`, still fully offline. | --- diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 5c72971..238c238 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -28,8 +28,15 @@ android { applicationId = "org.incido.app" minSdk = 26 targetSdk = 35 - versionCode = 8 - versionName = "0.3.0.3" + // v0.3.3.4: emergency hotfix — the favorite star on the note + // cards was drawn in the title row and overlapped the + // three-dot overflow button in the card's top-right corner. + // The star is now an overlay in the card's bottom-right corner + // with the same 4.dp end offset as the overflow button, so + // both controls sit in the same vertical column and no longer + // collide. versionCode monotonic +1 from v0.3.3.3 (18). + versionCode = 19 + versionName = "0.3.3.4" } // --- Signing --- @@ -77,8 +84,16 @@ android { dependencies { implementation(project(":composeApp")) + // v0.3.1.0: MainActivity needs the NoteRepository type to hand it + // through to IncidoApp (used by the editor's full-screen image + // viewer + the list card thumbnails). It's the *interface* in + // :core:domain, not the impl, so this stays clean of ObjectBox. + implementation(project(":core:domain")) implementation(libs.androidx.core.ktx) implementation(libs.kotlinx.coroutines.android) + // v0.3.2.0: MainActivity now extends FragmentActivity so the + // BiometricPrompt has a Fragment-based host. + implementation(libs.androidx.fragment.ktx) val composeBom = platform(libs.composeBom) implementation(composeBom) @@ -103,4 +118,4 @@ gradle.taskGraph.whenReady { "Update app/build.gradle.kts." ) } -} +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7cecfcd..d193299 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -4,7 +4,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/kotlin/org/incido/app/MainActivity.kt b/app/src/main/kotlin/org/incido/app/MainActivity.kt index b7e6ee3..9d39929 100644 --- a/app/src/main/kotlin/org/incido/app/MainActivity.kt +++ b/app/src/main/kotlin/org/incido/app/MainActivity.kt @@ -1,22 +1,142 @@ package org.incido.app +import android.content.Intent +import android.net.Uri import android.os.Bundle -import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge +import androidx.fragment.app.FragmentActivity +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import org.incido.compose.IncidoApp +import org.incido.compose.share.SharedIntentBuffer +import org.incido.compose.ui.editor.SharedImage /** * The single Activity hosting the Compose UI. All real work — navigation, * ViewModels, data — lives in the `:composeApp` module so it stays * portable when iOS / Desktop ports happen. + * + * v0.3.1.0 — also handles `ACTION_SEND` and `ACTION_SEND_MULTIPLE` + * intents (the "Share With" entry point from other apps). Inbound + * content is copied into memory here, parked in [SharedIntentBuffer], + * and picked up once by the Compose tree on first composition. + * + * v0.3.2.0 — this Activity must be a [androidx.fragment.app.FragmentActivity] + * (not just `ComponentActivity`) because the biometric prompt needs + * a Fragment-based host. ComponentActivity already extends from + * FragmentActivity via androidx.activity:activity-compose, so the cast + * inside `PinEntryScreen` succeeds. The [onStop] hook records the + * background timestamp so the SecurityManager can re-lock on resume + * if the timeout has elapsed. */ -class MainActivity : ComponentActivity() { +class MainActivity : FragmentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() + handleShareIntent(intent) setContent { - IncidoApp() + val app = application as org.incido.compose.IncidoApplication + // v0.3.1.0: hand the NoteRepository through to the Compose + // tree so the editor's full-screen image viewer can fetch + // attachment bytes on demand. + // v0.3.2.0: pass the SecurityManager + SettingsRepository + // through too so the auth gate and theme integration have + // direct access (without round-tripping through LocalContext). + IncidoApp( + repository = app.container.noteRepository, + securityManager = app.container.securityManager, + settingsRepository = app.container.settingsRepository, + ) } } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handleShareIntent(intent) + } + + /** + * v0.3.2.0: when the Activity is no longer visible, tell the + * SecurityManager so it can record the background timestamp. + * `onAppForegrounded()` (called from the root Compose tree on + * `ON_RESUME`) decides whether to re-lock based on the elapsed + * time vs the configured auto-lock timeout. + */ + override fun onStop() { + super.onStop() + val app = application as? org.incido.compose.IncidoApplication + app?.container?.securityManager?.onAppBackgrounded() + } + + /** + * Decode any ACTION_SEND / ACTION_SEND_MULTIPLE payload into a + * [SharedIntentBuffer.Payload] and stash it. Safe to call multiple + * times — repeated identical intents just overwrite the same payload. + */ + private fun handleShareIntent(intent: Intent?) { + if (intent == null) return + val action = intent.action + val type = intent.type + if (action != Intent.ACTION_SEND && action != Intent.ACTION_SEND_MULTIPLE) return + + // v0.3.1.1: stash text + uri list SYNCHRONOUSLY so the Compose + // tree (LaunchedEffect(Unit) reads the buffer once on first + // composition) sees the payload even though `lifecycleScope.launch` + // would otherwise run the image-byte I/O asynchronously and miss + // the first composition. We push an initial payload with no + // images; the async block then re-`put`s with images appended. + val text: String? = intent.getStringExtra(Intent.EXTRA_TEXT) + val uris: List = when (action) { + Intent.ACTION_SEND -> listOfNotNull( + @Suppress("DEPRECATION") + intent.getParcelableExtra(Intent.EXTRA_STREAM), + ) + Intent.ACTION_SEND_MULTIPLE -> @Suppress("DEPRECATION") + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM).orEmpty() + else -> emptyList() + } + SharedIntentBuffer.put( + SharedIntentBuffer.Payload(text = text, images = emptyList()) + ) + + if (uris.isNotEmpty()) { + lifecycleScope.launch { + val images: List = withContext(Dispatchers.IO) { + uris.mapNotNull { uri -> + val bytes = runCatching { + contentResolver.openInputStream(uri)?.use { it.readBytes() } + }.getOrNull() ?: return@mapNotNull null + val mime = contentResolver.getType(uri) ?: type ?: "application/octet-stream" + val displayName = queryDisplayName(uri) ?: "Shared_${System.currentTimeMillis()}" + SharedImage(bytes = bytes, mimeType = mime, displayName = displayName) + } + } + // Merge with whatever the buffer currently holds (keep its + // text — a second share-into on the same activity instance + // shouldn't clobber text-only payloads). + val current = SharedIntentBuffer.consume() ?: SharedIntentBuffer.Payload(null, emptyList()) + SharedIntentBuffer.put(current.copy(images = images)) + } + } + } + + private fun queryDisplayName(uri: Uri): String? { + return runCatching { + contentResolver.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 + } + }.getOrNull() + } } diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..9edf1d1 --- /dev/null +++ b/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,25 @@ + + + + + + diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index dae6cd8..ca9a2cc 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -7,6 +7,8 @@ plugins { alias(libs.plugins.androidLibrary) alias(libs.plugins.kotlinAndroid) alias(libs.plugins.kotlinCompose) + // v0.3.2.0 — Kotlin Serialization for the Backup JSON codec. + alias(libs.plugins.kotlinSerialization) } android { @@ -47,6 +49,7 @@ dependencies { implementation(libs.androidx.lifecycle.viewmodel) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.lifecycle.runtime) + implementation(libs.androidx.lifecycle.process) implementation(libs.kotlinx.coroutines.android) // Compose BOM keeps all Compose artefact versions aligned @@ -64,4 +67,10 @@ dependencies { implementation(libs.compose.material3) implementation(libs.compose.material.icons.extended) debugImplementation(libs.compose.ui.tooling) + + // v0.3.2.0 — Settings (DataStore Preferences), Security (Biometric), + // and Backup (Kotlin Serialization JSON) support. + implementation(libs.androidx.datastore.preferences) + implementation(libs.androidx.biometric) + implementation(libs.kotlinx.serialization.json) } diff --git a/composeApp/src/main/kotlin/org/incido/compose/App.kt b/composeApp/src/main/kotlin/org/incido/compose/App.kt index 8f04861..acb7f97 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/App.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/App.kt @@ -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 = 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.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 List.toSnapshotStateList(): SnapshotStateList = toMutableStateList() +private fun List.toSnapshotStateList(): SnapshotStateList = toMutableStateList() \ No newline at end of file diff --git a/composeApp/src/main/kotlin/org/incido/compose/IncidoApplication.kt b/composeApp/src/main/kotlin/org/incido/compose/IncidoApplication.kt index 2f73ea3..0059d34 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/IncidoApplication.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/IncidoApplication.kt @@ -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() } } diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt b/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt new file mode 100644 index 0000000..2f034a0 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt @@ -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 = repository.observeAll().first() + val tagList: List = 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, + val orphanedHashtags: List = 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 = emptyList(), + val attachments: List = 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) diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupManager.kt b/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupManager.kt new file mode 100644 index 0000000..c387231 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupManager.kt @@ -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, +) diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/backup/EncryptedBackupCodec.kt b/composeApp/src/main/kotlin/org/incido/compose/data/backup/EncryptedBackupCodec.kt new file mode 100644 index 0000000..fc0bbaa --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/backup/EncryptedBackupCodec.kt @@ -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() + } + } +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/backup/PassphraseGenerator.kt b/composeApp/src/main/kotlin/org/incido/compose/data/backup/PassphraseGenerator.kt new file mode 100644 index 0000000..0ad2b21 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/backup/PassphraseGenerator.kt @@ -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 +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/security/ObjectBoxKeyProvider.kt b/composeApp/src/main/kotlin/org/incido/compose/data/security/ObjectBoxKeyProvider.kt new file mode 100644 index 0000000..41ee91e --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/security/ObjectBoxKeyProvider.kt @@ -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 { + 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 + by preferencesDataStore(name = "incido_security_keys") diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/security/PinHasher.kt b/composeApp/src/main/kotlin/org/incido/compose/data/security/PinHasher.kt new file mode 100644 index 0000000..04df93b --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/security/PinHasher.kt @@ -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) +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/security/SecurityManager.kt b/composeApp/src/main/kotlin/org/incido/compose/data/security/SecurityManager.kt new file mode 100644 index 0000000..2b58a5f --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/security/SecurityManager.kt @@ -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.Locked(LockReason.ColdLaunch)) + val lockState: StateFlow = _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 + by preferencesDataStore(name = "incido_pin") \ No newline at end of file diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/settings/PasswordPolicy.kt b/composeApp/src/main/kotlin/org/incido/compose/data/settings/PasswordPolicy.kt new file mode 100644 index 0000000..4d533f4 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/settings/PasswordPolicy.kt @@ -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, + ) { + 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() + 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." + } +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/settings/ReleaseNotes.kt b/composeApp/src/main/kotlin/org/incido/compose/data/settings/ReleaseNotes.kt new file mode 100644 index 0000000..32d554c --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/settings/ReleaseNotes.kt @@ -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, +) + +object ReleaseNotes { + + /** + * The 5 most recent Incido releases, ordered newest → oldest. + * Append a new entry on top each release. + */ + val RECENT: List = 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. + ) +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/settings/SettingsRepository.kt b/composeApp/src/main/kotlin/org/incido/compose/data/settings/SettingsRepository.kt new file mode 100644 index 0000000..81d61ee --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/settings/SettingsRepository.kt @@ -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 = + 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 by preferencesDataStore( + name = "incido_settings", +) diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/settings/UserSettings.kt b/composeApp/src/main/kotlin/org/incido/compose/data/settings/UserSettings.kt new file mode 100644 index 0000000..08ad66d --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/data/settings/UserSettings.kt @@ -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` + * 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 + } +} \ No newline at end of file diff --git a/composeApp/src/main/kotlin/org/incido/compose/di/AppContainer.kt b/composeApp/src/main/kotlin/org/incido/compose/di/AppContainer.kt index 424626b..8d883f0 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/di/AppContainer.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/di/AppContainer.kt @@ -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) } diff --git a/composeApp/src/main/kotlin/org/incido/compose/share/SharedIntentBuffer.kt b/composeApp/src/main/kotlin/org/incido/compose/share/SharedIntentBuffer.kt new file mode 100644 index 0000000..df75b75 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/share/SharedIntentBuffer.kt @@ -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, + ) { + 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 + } +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/IncidoDrawer.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/IncidoDrawer.kt index f400fae..373252e 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/IncidoDrawer.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/IncidoDrawer.kt @@ -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, diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/ImageViewerScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/ImageViewerScreen.kt new file mode 100644 index 0000000..944ac70 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/ImageViewerScreen.kt @@ -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(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, + ) + } + } + } +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorScreen.kt index e853740..75ffc63 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorScreen.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorScreen.kt @@ -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 = 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(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, + persistedBytes: Map, + persistedViewerIds: Map, + persistedOpen: (ViewerAttachmentId) -> Unit, + persistedDelete: (Long) -> Unit, + pending: List, + pendingBytes: Map, + 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(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, 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 { + 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) } diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorViewModel.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorViewModel.kt index 67fd372..1aa9bdd 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorViewModel.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorViewModel.kt @@ -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 = 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 = 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 = 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): 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, + ): 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 = emptyList(), ) : ViewModel() { private val _state = MutableStateFlow(NoteEditorUiState()) val state: StateFlow = _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> = 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>(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() + val map = mutableMapOf() + 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() to emptyMap() + } + 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 = 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(), + ) +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListScreen.kt index 7f3dd47..bed3d84 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListScreen.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListScreen.kt @@ -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(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) { ) } } -} +} \ No newline at end of file diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListViewModel.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListViewModel.kt index 43b4920..1173635 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListViewModel.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListViewModel.kt @@ -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 = "" } diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/settings/PassphraseDialog.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/PassphraseDialog.kt new file mode 100644 index 0000000..d6a2bb7 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/PassphraseDialog.kt @@ -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)) +} \ No newline at end of file diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/settings/ReleaseNotesDialog.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/ReleaseNotesDialog.kt new file mode 100644 index 0000000..e9cf29d --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/ReleaseNotesDialog.kt @@ -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, + ) +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsScreen.kt new file mode 100644 index 0000000..5cfb9b7 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsScreen.kt @@ -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(null) } + var pendingImportUri by remember { mutableStateOf(null) } + var pendingImportPassphrase by remember { mutableStateOf(null) } + var pendingPreview by remember { mutableStateOf(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") } }, + ) +} \ No newline at end of file diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsViewModel.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsViewModel.kt new file mode 100644 index 0000000..9a45fb4 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsViewModel.kt @@ -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 = settings.userSettingsFlow.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5_000), + initialValue = UserSettings(), + ) + + private val _migrationState = MutableStateFlow(MigrationState.Idle) + val migrationState: StateFlow = _migrationState.asStateFlow() + + private val _snackbar = MutableStateFlow(null) + val snackbar: StateFlow = _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, + ) + } + } + } +} \ No newline at end of file diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinChangeScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinChangeScreen.kt new file mode 100644 index 0000000..7a4ab72 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinChangeScreen.kt @@ -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(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 } \ No newline at end of file diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinEntryScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinEntryScreen.kt new file mode 100644 index 0000000..16dc8ea --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinEntryScreen.kt @@ -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(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") + } + } + } + } +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinSetupScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinSetupScreen.kt new file mode 100644 index 0000000..76944cf --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/auth/PinSetupScreen.kt @@ -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(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") + } + } + } +} diff --git a/core/data/build.gradle.kts b/core/data/build.gradle.kts index f7bbec7..8662f87 100644 --- a/core/data/build.gradle.kts +++ b/core/data/build.gradle.kts @@ -55,4 +55,8 @@ dependencies { // ObjectBox runtime implementation(libs.objectbox.android) implementation(libs.objectbox.kotlin) + + // v0.3.1.2 — EXIF orientation tag handling for image attachments + // (see NoteRepositoryImpl.normalizeImageOrientation). + implementation(libs.androidx.exifinterface) } diff --git a/core/data/src/main/kotlin/org/incido/data/ObjectBoxStore.kt b/core/data/src/main/kotlin/org/incido/data/ObjectBoxStore.kt index 37b7ebc..4854687 100644 --- a/core/data/src/main/kotlin/org/incido/data/ObjectBoxStore.kt +++ b/core/data/src/main/kotlin/org/incido/data/ObjectBoxStore.kt @@ -7,12 +7,31 @@ import org.incido.data.entity.MyObjectBox /** * Singleton holder for the process-wide [BoxStore]. Initialised once from * the Application/Activity context. + * + * v0.3.2.0 — kept an `encryptionKey` parameter for forward compatibility, + * but the open-source ObjectBox 4.0.3 distribution doesn't expose a + * public `encryptionKey(byte[])` method on [io.objectbox.BoxStoreBuilder]. + * At-rest encryption is only available in ObjectBox Sync / Pro; the + * `:composeApp` `ObjectBoxKeyProvider` keeps the wrapping logic + * ready for when the API becomes available (or for migration to the + * commercial build). For now the store always opens unencrypted. */ object ObjectBoxStore { @Volatile private var instance: BoxStore? = null - fun init(context: Context): BoxStore = + /** + * Initialise the singleton [BoxStore]. Idempotent — repeated calls + * return the existing instance. + * + * @param context application context + * @param encryptionKey reserved for future at-rest encryption support + * (currently a no-op — ObjectBox 4.0.3 OSS doesn't expose the + * API). The key is wrapped via Android Keystore by + * `ObjectBoxKeyProvider` and ready to plug in. + */ + @Suppress("UNUSED_PARAMETER") + fun init(context: Context, encryptionKey: ByteArray? = null): BoxStore = instance ?: synchronized(this) { instance ?: MyObjectBox.builder() .androidContext(context.applicationContext) @@ -20,6 +39,17 @@ object ObjectBoxStore { .also { instance = it } } + /** + * Close + drop the singleton. Reserved for future use when + * toggling encryption requires re-opening the store with a new key. + */ + fun reset() { + synchronized(this) { + instance?.close() + instance = null + } + } + fun get(): BoxStore = instance ?: error("ObjectBoxStore not initialised — call init(context) first") } diff --git a/core/data/src/main/kotlin/org/incido/data/entity/NoteAttachmentEntity.kt b/core/data/src/main/kotlin/org/incido/data/entity/NoteAttachmentEntity.kt new file mode 100644 index 0000000..4cb6095 --- /dev/null +++ b/core/data/src/main/kotlin/org/incido/data/entity/NoteAttachmentEntity.kt @@ -0,0 +1,53 @@ +package org.incido.data.entity + +import io.objectbox.annotation.Entity +import io.objectbox.annotation.Id +import io.objectbox.annotation.Index +import org.incido.domain.model.NoteAttachment + +/** + * v0.3.1.0 — One uploaded file (photo, document, etc.) attached to a + * note. File **bytes** live directly in the database (ObjectBox + * stores `ByteArray` columns natively) so the entire note + its + * attachments are backed up and restored as a single unit, with no + * filesystem paths to keep in sync. + * + * [bytes] is intentionally NOT part of [NoteAttachment] in the + * domain layer — list snapshots stay cheap because they don't load + * the (potentially large) blob. Callers fetch bytes on demand via + * [org.incido.domain.repository.NoteRepository.getAttachmentBytes]. + */ +@Entity +data class NoteAttachmentEntity( + @Id var id: Long = 0, + @Index var noteId: Long = 0, + var mimeType: String = "", + var displayName: String = "", + var createdAt: Long = 0, + var sizeBytes: Long = 0, + var bytes: ByteArray = ByteArray(0), +) + +internal fun NoteAttachmentEntity.toDomain(): NoteAttachment = NoteAttachment( + id = id, + noteId = noteId, + mimeType = mimeType, + displayName = displayName, + createdAt = createdAt, + sizeBytes = sizeBytes, +) + +/** + * Inverse mapper from the domain layer — used when the editor or + * the share-into flow persists a freshly-imported attachment. The + * [id] field is left at 0L so ObjectBox assigns a fresh id on put. + */ +internal fun NoteAttachment.toEntity(): NoteAttachmentEntity = NoteAttachmentEntity( + id = 0L, + noteId = noteId, + mimeType = mimeType, + displayName = displayName, + createdAt = createdAt, + sizeBytes = sizeBytes, + bytes = ByteArray(0), // never serialised from the domain — bytes are set explicitly in the impl +) diff --git a/core/data/src/main/kotlin/org/incido/data/repository/NoteRepositoryImpl.kt b/core/data/src/main/kotlin/org/incido/data/repository/NoteRepositoryImpl.kt index 1130398..20c81a8 100644 --- a/core/data/src/main/kotlin/org/incido/data/repository/NoteRepositoryImpl.kt +++ b/core/data/src/main/kotlin/org/incido/data/repository/NoteRepositoryImpl.kt @@ -1,16 +1,26 @@ package org.incido.data.repository +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Matrix +import androidx.exifinterface.media.ExifInterface import io.objectbox.BoxStore import io.objectbox.kotlin.boxFor import io.objectbox.query.QueryBuilder import io.objectbox.reactive.DataSubscription +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.util.concurrent.Callable import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import org.incido.data.entity.HashtagEntity import org.incido.data.entity.HashtagEntity_ +import org.incido.data.entity.NoteAttachmentEntity +import org.incido.data.entity.NoteAttachmentEntity_ import org.incido.data.entity.NoteEntity import org.incido.data.entity.NoteEntity_ import org.incido.data.entity.NoteHashtagCrossRef @@ -20,6 +30,7 @@ import org.incido.data.entity.toEntity import org.incido.domain.model.Hashtag import org.incido.domain.model.HashtagUsage import org.incido.domain.model.Note +import org.incido.domain.model.NoteAttachment import org.incido.domain.repository.NoteRepository /** @@ -42,6 +53,8 @@ class NoteRepositoryImpl( private val noteBox = boxStore.boxFor() private val tagBox = boxStore.boxFor() private val xrefBox = boxStore.boxFor() + /** v0.3.1.0 — attachment rows (bytes stored inline as ByteArray). */ + private val attachmentBox = boxStore.boxFor() // --------------------------------------------------------------------- // List / observation streams @@ -77,17 +90,42 @@ class NoteRepositoryImpl( awaitClose { sub.cancel() } }.flowOn(Dispatchers.Default) - override fun observeHashtagsByRecentUse(): Flow> = callbackFlow { - // ObjectBox fires its observer with the full current query state - // immediately on subscribe, so the observer alone is the source - // of truth — no manual trySend that would race the subscription - // and double the work of the snapshot. - val sub = noteBox.query().build().subscribe().observer { _ -> - trySend(hashtagUsageSnapshot()) - } + override fun searchFavorites(query: String): Flow> = callbackFlow { + trySend(snapshotFavoritesSearch(query)) + val sub = noteBox.query().build().subscribe().observer { trySend(snapshotFavoritesSearch(query)) } awaitClose { sub.cancel() } }.flowOn(Dispatchers.Default) + override fun searchUntagged(query: String): Flow> = callbackFlow { + trySend(snapshotUntaggedSearch(query)) + val sub = noteBox.query().build().subscribe().observer { trySend(snapshotUntaggedSearch(query)) } + awaitClose { sub.cancel() } + }.flowOn(Dispatchers.Default) + + override fun observeHashtagsByRecentUse(): Flow> = callbackFlow { + // The snapshot reads from noteBox + xrefBox + tagBox, so we must + // subscribe to ALL three — otherwise a change that only touches + // tagBox (new hashtag) or xrefBox (new cross-ref) is missed. + // The first observer fire from any of the three gives us the + // initial snapshot, so no manual pre-subscribe trySend is needed. + // We hold the Query objects (not the Subscription handles) so we + // can release the underlying native handle when the flow ends. + // In ObjectBox 4.0.3 `Query` implements `java.io.Closeable` + // — the way to tear it down is `.close()`, not `.cancel()`. + val noteQuery = noteBox.query().build() + val tagQuery = tagBox.query().build() + val xrefQuery = xrefBox.query().build() + val emit: (Any) -> Unit = { _ -> trySend(hashtagUsageSnapshot()) } + noteQuery.subscribe().observer(emit) + tagQuery.subscribe().observer(emit) + xrefQuery.subscribe().observer(emit) + awaitClose { + noteQuery.close() + tagQuery.close() + xrefQuery.close() + } + }.flowOn(Dispatchers.Default) + override fun observeAllHashtags(): Flow> = callbackFlow { trySend(allHashtagsSnapshot().sorted()) val sub = noteBox.query().build().subscribe().observer { @@ -110,6 +148,83 @@ class NoteRepositoryImpl( awaitClose { sub.cancel() } }.flowOn(Dispatchers.Default) + override fun observeAttachments(noteId: Long): Flow> = callbackFlow { + trySend(attachmentsByNoteId()[noteId].orEmpty()) + val query = attachmentBox.query() + .equal(NoteAttachmentEntity_.noteId, noteId) + .build() + query.subscribe().observer { trySend(attachmentsByNoteId()[noteId].orEmpty()) } + awaitClose { query.close() } + }.flowOn(Dispatchers.Default) + + override suspend fun getAttachmentBytes(id: Long): ByteArray? { + return attachmentBox.get(id)?.bytes + } + + override suspend fun addAttachment( + noteId: Long, + bytes: ByteArray, + mimeType: String, + displayName: String, + ): Long { + // v0.3.1.2 — honour the EXIF Orientation tag on inbound images + // (camera intent usually writes landscape pixels + an EXIF + // rotation). Done at storage time so every render path + // (editor thumbnail, card thumbnail, full-screen viewer) sees + // the photo the right way up. Non-images pass through unchanged. + val storedBytes: ByteArray = if (mimeType.startsWith("image/")) { + withContext(Dispatchers.IO) { normalizeImageOrientation(bytes) } + } else { + bytes + } + val entity = NoteAttachmentEntity( + noteId = noteId, + mimeType = mimeType, + displayName = displayName, + createdAt = System.currentTimeMillis(), + sizeBytes = storedBytes.size.toLong(), + bytes = storedBytes, + ) + return attachmentBox.put(entity) + } + + /** + * v0.3.1.2 — rotate [bytes] to match the EXIF Orientation tag, then + * re-encode as JPEG so the stored bytes have no orientation flag + * (downstream renderers — editor thumbnail, card thumbnail, viewer + * — all decode raw pixels without honouring EXIF, so we bake the + * rotation into the bitmap at storage time). Returns the input + * unchanged when the orientation is normal, the bitmap can't be + * decoded, or the rotation fails for any reason. + */ + private fun normalizeImageOrientation(bytes: ByteArray): ByteArray { + val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return bytes + val angle = ExifInterface(ByteArrayInputStream(bytes)) + .getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) + .let { + when (it) { + ExifInterface.ORIENTATION_ROTATE_90 -> 90f + ExifInterface.ORIENTATION_ROTATE_180 -> 180f + ExifInterface.ORIENTATION_ROTATE_270 -> 270f + else -> 0f + } + } + if (angle == 0f) return bytes + val matrix = Matrix().apply { postRotate(angle) } + val rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, matrix, true) + bmp.recycle() + val out = ByteArrayOutputStream().use { baos -> + rotated.compress(Bitmap.CompressFormat.JPEG, 92, baos) + rotated.recycle() + baos.toByteArray() + } + return out + } + + override suspend fun removeAttachment(id: Long) { + attachmentBox.remove(id) + } + // --------------------------------------------------------------------- // Writes // --------------------------------------------------------------------- @@ -134,6 +249,14 @@ class NoteRepositoryImpl( if (orphanXrefs.isNotEmpty()) { xrefBox.remove(*orphanXrefs.map { it.id }.toLongArray()) } + // v0.3.1.0: cascade to attachments so we don't leak blobs. + val orphanAttachments: List = attachmentBox.query() + .equal(NoteAttachmentEntity_.noteId, id) + .build() + .find() + if (orphanAttachments.isNotEmpty()) { + attachmentBox.remove(*orphanAttachments.map { it.id }.toLongArray()) + } } override suspend fun setFavorite(id: Long, isFavorite: Boolean) { @@ -143,7 +266,53 @@ class NoteRepositoryImpl( noteBox.put(entity) } + /** + * Persist [note] and reconcile its hashtag set inside a single + * ObjectBox transaction. See [NoteRepository.saveNoteWithHashtags] + * for why atomicity matters (drawer Recent-Tags refresh bug fixed + * in v0.3.0.5). + */ + override suspend fun saveNoteWithHashtags( + note: Note, + hashtagsToAdd: Set, + hashtagsToRemove: Set, + ): Note { + val now = System.currentTimeMillis() + val toPersist = if (note.id == 0L) { + note.copy(createdAt = now, updatedAt = now).toEntity() + } else { + note.copy(updatedAt = now).toEntity() + } + // callInTx batches all puts into one transaction, so the per-box + // observers subscribed by observeHashtagsByRecentUse fire ONCE at + // commit time with the final committed state. Without this, the + // tagBox observer could fire between the tagBox.put and the + // xrefBox.put, leaving the snapshot stuck on emptyList(). + return boxStore.callInTx(Callable { + val assignedId = noteBox.put(toPersist) + val saved = noteBox.get(assignedId)?.toDomain() + ?: note.copy(id = assignedId) + hashtagsToRemove.forEach { removeHashtagInternal(saved.id, it) } + hashtagsToAdd.forEach { addHashtagInternal(saved.id, it) } + saved + }) + } + override suspend fun addHashtag(noteId: Long, name: String) { + addHashtagInternal(noteId, name) + } + + override suspend fun removeHashtag(noteId: Long, name: String) { + removeHashtagInternal(noteId, name) + } + + /** + * Synchronous helper so the implementation can call it from inside + * `boxStore.callInTx { ... }` (which expects a non-suspending + * Callable). The public [addHashtag] / [removeHashtag] methods also + * delegate here for a single source of truth. + */ + private fun addHashtagInternal(noteId: Long, name: String) { val normalised = Hashtag.normalise(name) if (!normalised.matches(Regex("^[a-z0-9][a-z0-9._-]{0,30}$"))) return @@ -169,7 +338,7 @@ class NoteRepositoryImpl( xrefBox.put(NoteHashtagCrossRef(noteId = noteId, hashtagId = tag.id)) } - override suspend fun removeHashtag(noteId: Long, name: String) { + private fun removeHashtagInternal(noteId: Long, name: String) { val normalised = Hashtag.normalise(name) val tag: HashtagEntity = tagBox.query() .equal(HashtagEntity_.name, normalised, QueryBuilder.StringOrder.CASE_INSENSITIVE) @@ -202,14 +371,34 @@ class NoteRepositoryImpl( } } + /** + * v0.3.1.0 — same shape as [hashtagsByNoteId], but for attachments. + * Returns `noteId -> List` (metadata only — no bytes) + * sorted by [NoteAttachment.createdAt] ascending. Used by + * [decorate] to populate `Note.attachments` for list / search + * snapshots without touching the blob column. + */ + private fun attachmentsByNoteId(): Map> { + val all: List = attachmentBox.all + if (all.isEmpty()) return emptyMap() + return all + .map { it.toDomain() } + .groupBy { it.noteId } + .mapValues { (_, rows) -> rows.sortedBy { it.createdAt } } + } + private fun decorate(entities: List): List { val tags = hashtagsByNoteId() + val attachments = attachmentsByNoteId() return entities.sortedWith( compareByDescending { it.isFavorite } .thenByDescending { it.updatedAt } ).map { e -> val base = e.toDomain() - base.copy(hashtags = tags[e.id].orEmpty()) + base.copy( + hashtags = tags[e.id].orEmpty(), + attachments = attachments[e.id].orEmpty(), + ) } } @@ -259,6 +448,71 @@ class NoteRepositoryImpl( return decorate(untaggedEntities) } + /** + * Context-aware search across favourites only. Blank [query] + * degrades to [snapshotFavorites]. Otherwise runs the same + * content + hashtag-name matching as [snapshotSearch] and + * intersects with `isFavorite = true`. + */ + private fun snapshotFavoritesSearch(query: String): List { + val q = query.trim() + if (q.isEmpty()) return snapshotFavorites() + val allIds: Set = snapshotSearchMatchingNoteIds(q) + if (allIds.isEmpty()) return emptyList() + val entities: List = allIds.mapNotNull { id -> noteBox.get(id) } + .filter { it.isFavorite } + return decorate(entities) + } + + /** + * Context-aware search across untagged notes only. Blank [query] + * degrades to [snapshotUntagged]. Otherwise runs the content + * matching from [snapshotSearch] and intersects with notes that + * have zero hashtags (tag matching is irrelevant for untagged). + */ + private fun snapshotUntaggedSearch(query: String): List { + val q = query.trim() + if (q.isEmpty()) return snapshotUntagged() + val noteIdsWithTags: Set = xrefBox.all.mapTo(HashSet(xrefBox.all.size)) { it.noteId } + val contentMatches: List = noteBox.query() + .contains(NoteEntity_.content, q, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .find() + .map { it.id } + val matching: List = contentMatches + .mapNotNull { id -> noteBox.get(id) } + .filter { it.id !in noteIdsWithTags } + return decorate(matching) + } + + /** + * Shared content + tag-name matcher used by [snapshotSearch] and + * [snapshotFavoritesSearch]. Returns the set of matching note ids. + */ + private fun snapshotSearchMatchingNoteIds(query: String): Set { + // Match against content (contains, case-insensitive). + val contentMatches: List = noteBox.query() + .contains(NoteEntity_.content, query, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .find() + .map { it.id } + + // Match against hashtag names (case-insensitive exact equality). + val matchingTag: HashtagEntity? = tagBox.query() + .equal(HashtagEntity_.name, query, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .findFirst() + val tagMatches: List = if (matchingTag == null) emptyList() else { + xrefBox.query() + .equal(NoteHashtagCrossRef_.hashtagId, matchingTag.id) + .build() + .find() + .map { it.noteId } + } + + return (contentMatches + tagMatches).toSet() + } + private fun snapshotForHashtag(name: String): List { val normalised = Hashtag.normalise(name) val tag: HashtagEntity = tagBox.query() @@ -278,7 +532,11 @@ class NoteRepositoryImpl( private fun noteByIdSnapshot(id: Long): Note? { val entity = noteBox.get(id) ?: return null val tags = hashtagsByNoteId()[id].orEmpty() - return entity.toDomain().copy(hashtags = tags) + val attachments = attachmentsByNoteId()[id].orEmpty() + return entity.toDomain().copy( + hashtags = tags, + attachments = attachments, + ) } /** Build [HashtagUsage] for every distinct tag, sorted by lastUsedAt DESC. */ diff --git a/core/domain/src/main/kotlin/org/incido/domain/model/Note.kt b/core/domain/src/main/kotlin/org/incido/domain/model/Note.kt index 9d04534..23b6bae 100644 --- a/core/domain/src/main/kotlin/org/incido/domain/model/Note.kt +++ b/core/domain/src/main/kotlin/org/incido/domain/model/Note.kt @@ -14,7 +14,18 @@ data class Note( val color: NoteColor = NoteColor.NONE, /** Tags attached to this note (normalised lowercase, sorted ascending). */ val hashtags: List = emptyList(), + /** + * v0.3.1.0 — files attached to this note (photo / document / etc). + * Metadata only; bytes are loaded on demand via + * [org.incido.domain.repository.NoteRepository.getAttachmentBytes]. + * Sorted by [NoteAttachment.createdAt] ascending (oldest first) + * so the UI can render them in stable order. + */ + val attachments: List = emptyList(), ) { + /** Convenience: the first image attachment, or `null` if none. */ + val firstImageAttachment: NoteAttachment? + get() = attachments.firstOrNull { it.isImage } companion object { private const val UNTITLED = "Untitled" diff --git a/core/domain/src/main/kotlin/org/incido/domain/model/NoteAttachment.kt b/core/domain/src/main/kotlin/org/incido/domain/model/NoteAttachment.kt new file mode 100644 index 0000000..01e541e --- /dev/null +++ b/core/domain/src/main/kotlin/org/incido/domain/model/NoteAttachment.kt @@ -0,0 +1,27 @@ +package org.incido.domain.model + +/** + * v0.3.1.0 — Metadata for a single file attached to a note. + * + * **Bytes are not part of this model.** They're stored in the + * database alongside the metadata row (see + * `NoteAttachmentEntity.bytes`) and loaded on demand via + * `NoteRepository.getAttachmentBytes(id)`. Keeping bytes out of the + * domain list payload means list snapshots stay cheap even for + * notes with many large attachments. + */ +data class NoteAttachment( + val id: Long, + val noteId: Long, + /** e.g. `image/jpeg`, `application/pdf`, `text/plain`. */ + val mimeType: String, + /** User-visible filename (or generated name like `IMG_20260815.jpg`). */ + val displayName: String, + /** Epoch millis, for stable ordering. */ + val createdAt: Long, + /** Cached size in bytes — cheap to read; lets the UI show file sizes without loading bytes. */ + val sizeBytes: Long, +) { + /** Convenience: true for any image-prefixed mime type. */ + val isImage: Boolean get() = mimeType.startsWith("image/") +} diff --git a/core/domain/src/main/kotlin/org/incido/domain/repository/NoteRepository.kt b/core/domain/src/main/kotlin/org/incido/domain/repository/NoteRepository.kt index 54f24d6..a041728 100644 --- a/core/domain/src/main/kotlin/org/incido/domain/repository/NoteRepository.kt +++ b/core/domain/src/main/kotlin/org/incido/domain/repository/NoteRepository.kt @@ -3,6 +3,7 @@ package org.incido.domain.repository import kotlinx.coroutines.flow.Flow import org.incido.domain.model.HashtagUsage import org.incido.domain.model.Note +import org.incido.domain.model.NoteAttachment /** * Persistence boundary for [Note]s. The UI layer depends on this interface @@ -43,6 +44,22 @@ interface NoteRepository { /** Only notes that have zero hashtags, sorted by updatedAt DESC. */ fun observeUntagged(): Flow> + /** + * Context-aware search across **favourites only** — matches + * [Note.content] (contains, case-insensitive) AND any of the note's + * hashtags (case-insensitive equality), sorted by favourites first + * then newest-first. Blank [query] returns the same as + * [observeFavorites]. + */ + fun searchFavorites(query: String): Flow> + + /** + * Context-aware search across **untagged notes only** — matches + * [Note.content] (contains, case-insensitive), sorted newest-first. + * Blank [query] returns the same as [observeUntagged]. + */ + fun searchUntagged(query: String): Flow> + /** Only notes tagged with [name] (normalised form), sorted by updatedAt DESC. */ fun observeNotesForHashtag(name: String): Flow> @@ -81,4 +98,61 @@ interface NoteRepository { * auto-deleted (cleanup is the future "tag browser" feature). */ suspend fun removeHashtag(noteId: Long, name: String) + + /** + * Persist [note] and reconcile its hashtag set in a single database + * transaction: insert [hashtagsToAdd] (creating backing rows for any + * new tag names) and remove [hashtagsToRemove]. + * + * Atomicity matters: the implementation wraps the upsert and the + * hashtag writes in a single store transaction so the observers + * subscribed by [observeHashtagsByRecentUse] fire **once** at commit + * time with the final state. Without that, three separate puts in + * sequence (noteBox, then tagBox, then cross-refBox) caused the + * drawer's hashtag-usage snapshot to read a transient empty + * cross-ref box and leave `emptyList()` stuck in the StateFlow — + * the new tag would only appear after some unrelated noteBox + * mutation (e.g. toggling the favourite star). See v0.3.0.5. + * + * Returns the persisted [Note] (with its assigned id when [note] was + * new). [hashtagsToAdd] / [hashtagsToRemove] should be in their + * normalised form (lowercase, no leading `#`, already validated). + */ + suspend fun saveNoteWithHashtags( + note: Note, + hashtagsToAdd: Set, + hashtagsToRemove: Set, + ): Note + + // --- Attachments (v0.3.1.0) --- + + /** + * Stream of attachments (metadata only, no bytes) belonging to + * [noteId], sorted by [NoteAttachment.createdAt] ascending. Emits + * a fresh list whenever any attachment row changes for this note. + */ + fun observeAttachments(noteId: Long): Flow> + + /** + * Fetch the raw bytes for an attachment row. Returns `null` if no + * row exists with [id]. Use sparingly — bytes are the largest + * column in the store. + */ + suspend fun getAttachmentBytes(id: Long): ByteArray? + + /** + * Insert a new attachment row for [noteId]. [bytes] is stored + * verbatim in the database (ObjectBox `ByteArray` column). The + * generated id is returned so the caller can reference the row + * (e.g. for display or removal). + */ + suspend fun addAttachment( + noteId: Long, + bytes: ByteArray, + mimeType: String, + displayName: String, + ): Long + + /** Delete an attachment by id. Idempotent. */ + suspend fun removeAttachment(id: Long) } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 205b8b5..4423e9b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -15,13 +15,19 @@ androidxActivityCompose = "1.9.3" androidxLifecycle = "2.8.7" androidxNavigationCompose = "2.8.4" composeBom = "2024.10.01" +androidxDatastore = "1.1.1" +androidxBiometric = "1.2.0-alpha05" # Kotlin / Coroutines coroutines = "1.9.0" +kotlinxSerialization = "1.7.3" # Data objectbox = "4.0.3" +# Exif +exifinterface = "1.3.7" + [libraries] # Compose Multiplatform compose-multiplatform = { module = "org.jetbrains.compose:compose-bom", version.ref = "composeMultiplatform" } @@ -40,8 +46,19 @@ androidx-activity-compose = { module = "androidx.activity:activity-compose", ver androidx-lifecycle-viewmodel = { module = "org.jetbrains.androidx.lifecycle:lifecycle-viewmodel", version = "2.8.4" } androidx-lifecycle-viewmodel-compose = { module = "org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose", version = "2.8.4" } androidx-lifecycle-runtime = { module = "org.jetbrains.androidx.lifecycle:lifecycle-runtime", version = "2.8.4" } +androidx-lifecycle-process = { module = "androidx.lifecycle:lifecycle-process", version = "2.8.4" } androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "androidxNavigationCompose" } androidx-core-ktx = { module = "androidx.core:core-ktx", version = "1.13.1" } +androidx-exifinterface = { module = "androidx.exifinterface:exifinterface", version.ref = "exifinterface" } +# v0.3.2.0: FragmentActivity (for BiometricPrompt host) +androidx-fragment-ktx = { module = "androidx.fragment:fragment-ktx", version = "1.8.5" } + +# v0.3.2.0: Settings / Security / Backup support +androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "androidxDatastore" } +androidx-biometric = { module = "androidx.biometric:biometric", version.ref = "androidxBiometric" } + +# Kotlin Serialization (v0.3.2.0 backup JSON codec) +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerialization" } # Coroutines kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } @@ -59,5 +76,6 @@ kotlinJvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } kotlinCompose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } objectbox = { id = "io.objectbox", version.ref = "objectbox" } diff --git a/incido.png b/incido.png new file mode 100644 index 0000000..19d5fbb Binary files /dev/null and b/incido.png differ