From f87ca17dedf8d9c113e53810f1e3cbf2c1ef283c Mon Sep 17 00:00:00 2001 From: Incido Developer Date: Wed, 23 Sep 2026 16:56:57 +1200 Subject: [PATCH] =?UTF-8?q?feat:=20v0.4.2.0=20=E2=80=94=20voice=20notes=20?= =?UTF-8?q?(Opus=2032=20kbps=20mono),=20toolbar=20reorder,=20backup-first?= =?UTF-8?q?=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Voice notes: record in-note via framework MediaRecorder; takes stored as compact Opus-in-Ogg (.opus, 32 kbps, single channel, 48 kHz) on API 29+ with AAC/.m4a fallback on API 26-28; MediaPlayer bar with Download to system Downloads. Editor toolbar reordered Photo / Voice / Attach / Tasks / Shopping list, hashtag justified flush right. Release notes across README / PREVIOUS_HISTORY / ReleaseNotes / CONTRIBUTING / Development Plan now open every release with a back-up-before-installing warning (standing convention). versionCode 38, versionName 0.4.2.0, APP_VERSION lockstep; assembleDebug + assembleRelease green. --- .gitignore | 1 + CONTRIBUTING.md | 8 +- Incido Development Plan.txt | 10 +- PREVIOUS_HISTORY.md | 14 +- README.md | 21 +- app/build.gradle.kts | 19 +- app/src/main/AndroidManifest.xml | 11 + .../incido/compose/data/backup/BackupCodec.kt | 4 +- .../compose/data/settings/ReleaseNotes.kt | 58 +- .../compose/ui/editor/NoteEditorScreen.kt | 120 +++- .../compose/ui/editor/NoteEditorViewModel.kt | 80 ++- .../compose/ui/editor/VoiceNoteSection.kt | 539 ++++++++++++++++++ .../incido/compose/ui/editor/VoiceRecorder.kt | 132 +++++ .../compose/ui/notelist/NoteListScreen.kt | 31 +- .../compose/ui/settings/SettingsViewModel.kt | 2 +- .../kotlin/org/incido/domain/model/Note.kt | 7 + .../org/incido/domain/model/NoteAttachment.kt | 3 + .../org/incido/domain/model/NoteType.kt | 11 +- 18 files changed, 1012 insertions(+), 59 deletions(-) create mode 100644 composeApp/src/main/kotlin/org/incido/compose/ui/editor/VoiceNoteSection.kt create mode 100644 composeApp/src/main/kotlin/org/incido/compose/ui/editor/VoiceRecorder.kt diff --git a/.gitignore b/.gitignore index 348648c..caadaaf 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,4 @@ Thumbs.db # Built APKs at the repo root (stamped with version — see Incido # Development Plan §11 for the release build procedure). incido-*.apk +Incido-*.apk diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 214ba14..98a9c2a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,7 +69,11 @@ Per-version user-facing notes live in `PREVIOUS_HISTORY.md` to each Gitea release automatically. Write each note (paragraph or bullet) as **one complete line — do not hard-wrap it**: the CI copies the section verbatim, so manual line breaks ship as premature returns, and the release -UI reflows the text for you. +UI reflows the text for you. **From v0.4.2.0 on, every new release section +must open with the standard backup-warning callout** — ask users to make +certain they have a current backup (Settings → Backup & Restore → Export, +plus the encryption-key export under Settings → Security) before +installing the new version. This reminder ships with every release. Commit types: @@ -149,7 +153,7 @@ under GPL-3.0 before opening the PR. > fails immediately — there's a validator in `app/build.gradle.kts`. 1. Bump `versionCode` (+1) and `versionName` in `app/build.gradle.kts`. -2. Update the Development Plan §10 history table with the new dot-name. +2. Update the Development Plan §10 history table with the new dot-name, and give the release its `PREVIOUS_HISTORY.md` section — opening, as every release does from v0.4.2.0 on, with the standard backup-warning callout (users must back up before installing). 3. Tag the commit: `git tag -s vX.Y.Z.W -m "vX.Y.Z.W — short summary"`. 4. `./gradlew assembleDebug assembleRelease` — confirm both green. 5. Upload `app/build/outputs/apk/release/app-release.apk` to Gitea Releases. diff --git a/Incido Development Plan.txt b/Incido Development Plan.txt index 13302d4..7083cbb 100644 --- a/Incido Development Plan.txt +++ b/Incido Development Plan.txt @@ -370,6 +370,7 @@ A short reference for AI assistants: | Version | Date | Notes | |---------|------|-------| +| 0.4.2.0 | 2026-09-23 | **Feature release — voice notes, with a maintenance pass folded in (Opus recording format + editor toolbar reorder).** **1. Voice notes.** New `NoteType.VOICE_NOTE` toggled by a mic button on the editor's bottom toolbar (`RECORD_AUDIO` requested on first tap into voice mode): `VoiceRecorder` (framework `MediaRecorder`) writes the take via `cacheDir/voice_rec/`; `VoiceNoteSection` pins a record/re-record card plus a `MediaPlayer`-backed player bar (play/pause, seek, elapsed/total) at the top of the body, with a Download action (MediaStore Downloads on API 29+, FileProvider share-sheet fallback on API 26–28). Takes ride the ordinary attachment pipeline (`PendingAttachment` → `NoteAttachment`) — encrypted at rest, included in backups, survive type changes; one take per note, re-recording replaces the old one. `Note.firstAudioAttachment` convenience; mic badge on cards; zero new dependencies. **2. Opus audio format (maintenance).** Takes record as Opus-in-Ogg (`.opus` — 32 kbps, single channel, 48 kHz) via `OutputFormat.OGG` + `AudioEncoder.OPUS` on API 29+ (the public-API floor for OGG output), keeping the previous AAC/MPEG-4 (`.m4a`, 96 kbps) path for API 26–28; `VoiceRecorder.recordedMimeType` propagates the actual container to the attachment mime (`audio/ogg`), display name (`Voice_*.opus`), playback cache file, MediaStore download mime and share-intent type. Opus frame size / encoder complexity are platform defaults — `MediaRecorder` exposes no knob (120 ms frames + complexity 10 would require bundled native libopus; deferred). Existing `.m4a` takes still play; no migration. **3. Editor toolbar reorder (maintenance).** Bottom action row is now Photo · Voice · Attach · Tasks · Shopping list, with the hashtag button justified flush right via a weighted `Spacer`, separated from the cluster; handlers, permission flows and tints unchanged. **4. Backup-warning convention.** From this version every release section opens with a ⚠️ back-up-before-installing callout (PREVIOUS_HISTORY.md header, §11.1, CONTRIBUTING release process, README upgrade callout). **Lockstep (§11.1).** versionCode 37→38, versionName 0.4.1.1→0.4.2.0, `SettingsViewModel.APP_VERSION` bumped, README intro + current-release line + smoke-test step, PREVIOUS_HISTORY.md section (backup callout first; feeds the release description + `Incido-0.4.2.0-changes.md` asset), `ReleaseNotes.RECENT` (v0.3.8.0 drops off the 5-entry tail). | | 0.4.1.1 | 2026-09-23 | **Emergency hotfix — two v0.4.1.0 editor regressions.** **1. Saved notes landed in Drafts.** `NoteEditorViewModel.save()` published the note but left `UiState.existing.isDraft = true`, so the editor's dispose-time `flushDraft()` immediately re-persisted the just-saved note as a draft — every confirmed note ended up in Drafts. The save path now adopts the published row into state (`isDraft = false`, current hashtags kept), letting `persistDraftNow()`'s already-published guard turn that flush into a no-op. **2. Enter on a shopping-list Price field wrapped the cursor to the Title.** A bare `ImeAction.Next` with no handler fell through to system focus traversal — price being the row's last field inside the LazyColumn wrapped focus all the way back to the Title; the field now passes `KeyboardActions(onNext = { onAddAfter() })`, matching Enter on the Product field (fresh row, cursor in its Product box). **Lockstep (§11.1).** versionCode 36→37, versionName "0.4.1.0"→"0.4.1.1", SettingsViewModel.APP_VERSION bumped, README current-release line + two smoke-test regression steps, PREVIOUS_HISTORY.md section (feeds the release description + `Incido-0.4.1.1-changes.md` asset), ReleaseNotes.RECENT (v0.3.8.1 drops off the 5-entry tail). | | 0.4.1.0 | 2026-09-23 | **Feature release — colour filters + auto-saved drafts, plus Trash & editor polish.** **1. Colour filters.** The drawer gains a horizontal five-swatch strip (Blue / Green / Amber / Red / Purple) between Favorites and Drafts — no labels, the colours are self-explanatory; selecting a swatch shows ONLY **active** notes of that colour (tagged and untagged eligible, trashed never — same rules as Favorites / Untagged), search narrows within the colour, re-tapping the selected swatch returns to Home. `NoteFilter` gains `ByColor` (+ `color:` route parsing in `App.kt`); the repository gains `observeByColor` / `searchByColor` reusing the shared `decorate()` / `matchingNoteIds()` trash-exclusion path. **2. Auto-saved drafts.** New notes persist as drafts while being written: `Note.isDraft` (indexed ObjectBox property; mirrored in `BackupNote`, defaulted false for older backups), `NoteFilter.Drafts` (+ `drafts` route + drawer row) with repository `observeDrafts` / `searchDrafts`; `NoteEditorViewModel` runs a debounced signature-driven autosave with `flushDraft()` on back-navigation / dispose; drafts appear ONLY in the Drafts view until saved (then Home) or trashed (then Trash); an untitled draft is labelled by kind — "Task List — (draft)", "Shopping List — (draft)" — on cards and the editor bar via `NoteType.displayName` + `Note.UNTITLED` (display-only; stored content untouched). **3. Empty Trash.** Trash view shows a `DeleteForever` top-bar action whenever it holds notes, gated by a confirmation `AlertDialog`; `deleteAllTrashed()` cascades note rows + hashtag xrefs + attachment rows exactly like `delete()`. **4. Editor row rebuild.** `EditorLineField` unified on one `BasicTextField` with a hand-drawn 2 dp underline — the old two-branch design mixed M3 `TextField`'s 56 dp min container with compact fields, producing double-height rows; `ChecklistItemRow` moved `Alignment.Top`→`Alignment.CenterVertically` so checkbox / delete / +/- controls ride centred beside wrapping labels. versionCode 35→36, versionName "0.4.0.0"→"0.4.1.0", SettingsViewModel.APP_VERSION bumped in lockstep, README current-release line, PREVIOUS_HISTORY.md section, and the in-app What's New dialog (ReleaseNotes.RECENT — v0.3.7.0 drops off the 5-entry tail). | | 0.4.0.0 | 2026-09-18 | **Feature release — in-app import of 3rd-party notes.** Settings → Backup & Restore gains an "Import 3rd Party Notes" button that reads a Carnet / QuickNote `.zip` export (a single archive bundling one `.sqd` per note, where each `.sqd` is itself a zip of index.html + metadata.json + optional data/ attachments) and imports every note directly on-device — no pre-conversion step. Rich-text bodies are flattened to plain text; colours, keywords (imported as tags) and links carry over; to-do lists become native checklists; image attachments are imported (auto-generated preview thumbnails are skipped). Import is additive with per-note fault isolation, and imported notes get fresh IDs. New `CarnetImporter` in `composeApp/data/backup` + entry point in the Settings screen/view model. versionCode 34→35, versionName "0.3.8.1"→"0.4.0.0", SettingsViewModel.APP_VERSION bumped in lockstep, README current-release line, PREVIOUS_HISTORY.md section, and the in-app What's New dialog (ReleaseNotes.RECENT — v0.3.6.0 drops off the 5-entry tail). | @@ -441,7 +442,14 @@ A small Gradle task called `copyReleaseApks` (registered in table). **Write each note (paragraph or bullet) as one complete line — do not hard-wrap it:** the CI copies the section verbatim into the release description and the `Incido--changes.md` asset, so a manual line - break ships as a premature return; the release UI reflows the text for you. + break ships as a premature return; the release UI reflows the text for you. **From v0.4.2.0 on, every new section + must open with the standard backup-warning callout** (blockquote + `> ⚠️ **Before installing:** ...`): ask users to make certain they + have a current backup — Settings → Backup & Restore → Export, plus + the encryption key export under Settings → Security — before + installing the new version. The same reminder leads the matching + ReleaseNotes.kt entry and repeats on the README front page; it ships + with EVERY release from now on. On tag push the release workflow runs `scripts/ci/release-notes.py` and attaches that section to the Gitea release as its description **and** as an `Incido--changes.md` diff --git a/PREVIOUS_HISTORY.md b/PREVIOUS_HISTORY.md index bf28635..5b2cfdf 100644 --- a/PREVIOUS_HISTORY.md +++ b/PREVIOUS_HISTORY.md @@ -4,10 +4,22 @@ Reference archive of Incido's user-facing release history (formerly the README c Current downloads ship **with their own notes**: every release on the [Releases page](https://git.trevena.info/nick/incido/releases) carries its version's changelog — rendered in the release description and also attached beside the APKs as `Incido--changes.md`. The CI generates both from the matching section below via `scripts/ci/release-notes.py` at tag-build time. -**Adding a release:** append a `## v — ` section at the top of this file (see Development Plan §11.1). Newest first; never delete or reorder older sections — the CI must find a section for whatever tag it builds, and hotfix retags can target any version. If a tag has no section, the release falls back to a plain "Release " description. +**Adding a release:** append a `## v — ` section at the top of this file (see Development Plan §11.1). Newest first; never delete or reorder older sections — the CI must find a section for whatever tag it builds, and hotfix retags can target any version. If a tag has no section, the release falls back to a plain "Release " description. **Every new section must open with the standard backup-warning callout** (from v0.4.2.0 onwards): ask users to back up their data — Settings → Backup & Restore, plus their encryption key under Settings → Security — before installing the new version. --- +## v0.4.2.0 — 2026-09-23 + +> ⚠️ **Before installing:** please make certain you have a current backup of your data — Settings → Backup & Restore → Export, plus your encryption key from Settings → Security if encryption is on — then install the new version and restore if you need to. Every Incido release from now on will carry this same reminder. + +New in this release: **voice notes**. + +- **Record right inside a note.** The editor's bottom toolbar gained a mic button — first in the row, right after the camera. The whole toolbar is now laid out Photo · Voice · Attach · Tasks · Shopping list, with the hashtag button moved to the far right, separated from the others. Tap the mic (Incido asks for microphone access the first time) and the note grows a recording card at the top of its body, right above the text. Tap to record, tap stop — your take gets a proper media player: play / pause, a seek bar, elapsed and total time. +- **Small, crisp recordings.** Takes are captured as Opus audio (`.opus` — 32 kbps, single channel): tiny files with clear speech. Devices on Android 8.x / 9 fall back to the previous AAC format automatically; playback and downloading work identically either way. +- **The recording is part of the note.** Takes are stored with the note like any other attachment — encrypted at rest when encryption is on, and included in backups — and a download button on the player copies the file out to your device's Downloads folder when you need it (older devices get the share sheet, which saves to the same places). +- **Still a normal note.** Voice notes keep the title, the text body, colours, tags, favourites, drafts and search; re-recording replaces the old take, tapping 🗑 removes it, and converting the note back to a plain text note leaves the recording in place as an ordinary attachment. Voice-note cards carry a small mic badge so you can spot them at a glance. +- **No new engines on board.** Recording and playback use the Android framework's own media APIs — no new libraries, no network access: recordings never leave your device. + ## v0.4.1.1 — 2026-09-23 Hotfix over v0.4.1.0 — two editor fixes, nothing else changed. Installing it over v0.4.1.0 is a normal in-place update. diff --git a/README.md b/README.md index 6be88eb..1fea8be 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,10 @@ Incido is a privacy-first, on-device note-taking application for Android. All data stays on your device by default — no accounts, no cloud, no trackers. -This repository contains the **v0.4.1.1** release: a single-user, offline +This repository contains the **v0.4.2.0** release: a single-user, offline note app with hashtags, favourites, task lists, shopping lists with a -running total, colour-coded notes with per-colour swatch filters, +running total, voice notes with an in-app media player and downloadable +recordings, colour-coded notes with per-colour swatch filters, auto-saved drafts, photo and file attachments, share-into from other apps and the web, importing notes from third-party apps (Carnet / QuickNote `.zip` exports) directly on-device, Trash (soft delete with @@ -18,11 +19,21 @@ encrypted backup and restore, and an exportable encryption key for device migrations. The architecture is multi-module Android today and is structured so iOS / Desktop ports can happen later without UI rewrites. -**Current release:** v0.4.1.1 (hotfix over v0.4.1.0: saved notes no -longer land in Drafts; Enter in a shopping-list price box adds a row) — +**Current release:** v0.4.2.0 (voice notes — a mic button turns any note +into a recordable voice note with a built-in media player; recordings are +compact Opus files (32 kbps, mono) stored with the note and downloadable +to the device; the editor toolbar is reordered Photo · Voice · Attach · +Tasks · Shopping list with the hashtag button flush right) — full release notes ship **on its entry on the [Releases page](https://git.trevena.info/nick/incido/releases)**. +> **Back up before every update:** from v0.4.2.0 onwards, every release +> asks the same of you — **export a backup first** (Settings → Backup & +> Restore → Export, plus your encryption key from Settings → Security if +> you use encryption) before installing a new version. Incido is offline +> by design and doesn't use Android's automatic backup, so a current +> backup is your only safety net for any update. + > **Upgrading from v0.3.8.0 or earlier?** Releases are signed with a **new CI > key introduced in v0.3.8.1**, so Android won't update an old install in place > — it reports a signature conflict. **Export a backup from Settings → Backup @@ -184,6 +195,8 @@ After the first push: [ ] Start a new note, type, then back out without saving → it lands under "Drafts"; an untitled draft is titled "Task List — (draft)" / "Shopping List — (draft)"; reopening it restores the content; saving it moves it to Home [ ] Save a note (new or draft) → it appears on Home and NOT in Drafts — saving exits draft mode for good (v0.4.1.1 regression) [ ] Shopping list: press Enter in a row's Price field → a fresh row appears below with the cursor in its Product field, not back in the Title (v0.4.1.1 fix) +[ ] Tap the mic button in a note's bottom toolbar → grant microphone access → a recording card appears above the text field; tap it, record, stop → a media player shows with play/pause, seek and elapsed/total time (v0.4.2.0) +[ ] Voice note: tap the download button on the player → the recording lands in the system Downloads folder; the card also appears in the attachment strip; converting the note back to text keeps the recording (v0.4.2.0) [ ] Tap a recent hashtag → list filters to that tag [ ] Tap "Trash" → list shows only soft-deleted notes [ ] Delete a note → it disappears from Home/search/tag/Favorites and appears in Trash diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 86ea0bb..9e4aa91 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -41,8 +41,23 @@ android { // field — Enter adds a fresh row with the cursor in its // Product box. // - versionCode monotonic +1 from v0.4.1.0 (36). - versionCode = 37 - versionName = "0.4.1.1" + // v0.4.2.0: FEATURE release — voice notes. New note type (mic + // button on the editor's bottom toolbar toggles it; the toolbar + // is reordered Photo · Voice · Attach · Tasks · Shopping list + // with the hashtag button pushed flush right): a record / + // re-record card plus a MediaPlayer-backed player bar (play/ + // pause, seek, elapsed/total) pinned at the top of the body, + // with a Download action copying the take to the system + // Downloads folder (share-sheet fallback on API 26–28). Takes + // record as Opus in Ogg (.opus, 32 kbps, mono, 48 kHz) on + // API 29+; API 26–28 keeps the AAC/MP4 fallback. Audio + // rides the ordinary attachment pipeline — encrypted at rest, + // in backups, survives type changes. RECORD_AUDIO permission + // added; zero new dependencies (framework MediaRecorder / + // MediaPlayer only). + // - versionCode monotonic +1 from v0.4.1.1 (37). + versionCode = 38 + versionName = "0.4.2.0" } // --- Signing --- diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d193299..3029120 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -11,6 +11,11 @@ database and are never uploaded anywhere. --> + + + 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 index 19f2499..aa2c13f 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt @@ -130,8 +130,8 @@ data class BackupNote( val isDraft: Boolean = false, /** * v0.3.8.0 — serialised as the [org.incido.domain.model.NoteType] - * enum name ("TEXT" / "TASK_LIST" / "SHOPPING_LIST"). Defaulted so - * pre-v0.3.8.0 backup files import as plain-text notes. + * enum name ("TEXT" / "TASK_LIST" / "SHOPPING_LIST" / "VOICE_NOTE"). + * Defaulted so pre-v0.3.8.0 backup files import as plain-text notes. */ val noteType: String = "TEXT", ) 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 index 351f59e..9679824 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/data/settings/ReleaseNotes.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/data/settings/ReleaseNotes.kt @@ -25,6 +25,43 @@ object ReleaseNotes { * Append a new entry on top each release. */ val RECENT: List = listOf( + ReleaseNote( + version = "0.4.2.0", + date = "2026-09-23", + bullets = listOf( + "Before you update: please make certain you have a " + + "current backup — Settings → Backup & Restore → " + + "Export (plus your encryption key under Settings → " + + "Security if encryption is on) — before installing " + + "this version. Every future release will remind " + + "you the same way.", + "Voice notes: the editor's bottom toolbar gained a mic " + + "button, right after the camera — the row is now " + + "Photo · Voice · Attach · Tasks · Shopping list, " + + "with the hashtag button moved to the far right. " + + "Tap it and the note grows a recording card " + + "at the top of its body — tap record, stop when " + + "you're done, and your take gets a media player with " + + "play / pause, a seek bar, and elapsed / total time.", + "Recordings are captured as compact Opus audio " + + "(.opus files \u2014 32 kbps, single channel): tiny " + + "files, clear speech. Phones on Android 8.x / 9 " + + "fall back to the old AAC format automatically.", + "Your recording is saved with the note like any other " + + "attachment — encrypted at rest when encryption " + + "is on, riding along in backups — and a download " + + "button copies it out to the system Downloads folder " + + "when you need the file itself.", + "Voice notes are still normal notes: title, text body, " + + "colours, tags, favourites, drafts, and search all " + + "work as before. Re-recording replaces the old take; " + + "converting back to a text note keeps the recording " + + "as an ordinary attachment.", + "Voice note cards carry a mic badge, and the microphone " + + "permission is only asked for on the first tap into " + + "voice mode — recordings never leave the device.", + ), + ), ReleaseNote( version = "0.4.1.1", date = "2026-09-23", @@ -119,25 +156,6 @@ object ReleaseNotes { "only \"+ Create\\u2026\" ever showed).", ), ), - ReleaseNote( - version = "0.3.7.1", - date = "2026-08-30", - bullets = listOf( - "Cleaner Add / Edit screen: camera, attach-file, and " + - "add-tag moved out of the crowded title bar into a " + - "bottom action row — the title and remaining buttons " + - "now fit comfortably on every screen.", - "Fixed a false error message that flashed whenever you " + - "opened a saved image in the full-screen viewer.", - "Search now focuses automatically when opened and shows " + - "a clear (✕) button while you type.", - "Long tag lists in the navigation drawer now scroll " + - "instead of being cut off at the bottom.", - "The add-tag sheet opens with the keyboard already up.", - "New app icon: a flatter, cleaner take on the shield " + - "and pen-nib artwork.", - ), - ), - // v0.4.1.1 push drops v0.3.8.1 off the "5 most recent" tail. + // v0.4.2.0 push drops v0.3.7.1 off the "5 most recent" tail. ) } 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 44a89d7..b722bee 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 @@ -3,6 +3,7 @@ package org.incido.compose.ui.editor import android.Manifest import android.content.Context import android.content.Intent +import android.content.pm.PackageManager import android.graphics.BitmapFactory import android.net.Uri import android.widget.Toast @@ -50,6 +51,7 @@ 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.Mic import androidx.compose.material.icons.filled.ShoppingBasket import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.filled.Tag @@ -107,6 +109,7 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel @@ -236,6 +239,39 @@ fun NoteEditorScreen( } } + // v0.4.2.0 — voice notes. RECORD_AUDIO is requested the first time + // the user toggles the mic mode; on grant the note converts. The + // grant state is checked LIVE on every tap (a revoke from Settings + // mid-session must not slip through a cached flag). + val micPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) { + viewModel.convertTo(NoteType.VOICE_NOTE) + } else { + Toast.makeText(ctx, "Microphone permission denied", Toast.LENGTH_SHORT).show() + } + } + fun micPermissionGranted(): Boolean = + ContextCompat.checkSelfPermission( + ctx, + Manifest.permission.RECORD_AUDIO, + ) == PackageManager.PERMISSION_GRANTED + + fun toggleVoiceMode() { + if (state.type == NoteType.VOICE_NOTE) { + // Toggling back needs no mic at all — the take survives as + // an ordinary attachment. + viewModel.convertTo(NoteType.VOICE_NOTE) + return + } + if (micPermissionGranted()) { + viewModel.convertTo(NoteType.VOICE_NOTE) + } else { + micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO) + } + } + fun launchCamera() { val (uri, _) = createTempCameraUri(ctx) if (uri == null) { @@ -414,7 +450,35 @@ fun NoteEditorScreen( // field whenever the note is a task / shopping list; the // rows live in NoteEditorUiState.items and the view-model // keeps `content` synchronised with their serialisation. - if (state.type == NoteType.TEXT) { + // v0.4.2.0 — voice recorder / media-player card pinned at + // the very top of the note body, directly above the text + // field (which keeps working exactly like the plain-text + // editor: title = first line). + if (state.type == NoteType.VOICE_NOTE) { + val voicePending = state.pendingAttachments + .lastOrNull { it.mimeType.startsWith("audio/") } + val voicePersisted = state.attachments.lastOrNull { it.isAudio } + VoiceNoteSection( + voicePending = voicePending, + voicePendingBytes = voicePending?.let { + state.pendingAttachmentBytes[it.tempId] + }, + voicePersisted = voicePersisted, + repository = repository, + hasMicPermission = { micPermissionGranted() }, + onRequestPermission = { + micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO) + }, + onTakeRecorded = viewModel::setVoiceRecording, + onDeleteTake = { + voicePending?.let { viewModel.removePendingAttachment(it.tempId) } + ?: voicePersisted?.let { viewModel.deletePersistedAttachment(it.id) } + }, + securityManager = securityManager, + modifier = Modifier.padding(horizontal = 16.dp), + ) + } + if (state.type == NoteType.TEXT || state.type == NoteType.VOICE_NOTE) { OutlinedTextField( value = state.content, onValueChange = viewModel::onContentChange, @@ -488,7 +552,9 @@ fun NoteEditorScreen( // into this bottom action row so the top bar always fits // (the six-action cluster used to crowd the title on narrow // screens). Keep-style placement, above the nav bar / - // keyboard. + // keyboard. Order: Photo · Voice · Attach · Tasks · Shopping + // list, then the hashtag button sits flush right — a + // weighted spacer separates it from the action cluster. HorizontalDivider() Row( modifier = Modifier @@ -503,6 +569,18 @@ fun NoteEditorScreen( tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } + // v0.4.2.0 — voice-note toggle, first after Photo: + // converts the note to / from voice mode (mic permission + // is requested on the first tap into the mode). + IconButton(onClick = { toggleVoiceMode() }) { + Icon( + Icons.Filled.Mic, + contentDescription = "Voice note", + tint = if (state.type == NoteType.VOICE_NOTE) + MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } IconButton(onClick = { // v0.3.4.0 hotfix: the SAF picker backgrounds // the app; with Auto-Lock = Immediate the return @@ -516,21 +594,9 @@ fun NoteEditorScreen( tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } - IconButton( - onClick = { viewModel.openAddTagSheet() }, - enabled = state.canAddMoreTags, - ) { - Icon( - Icons.Filled.Tag, - contentDescription = "Add tag", - tint = if (state.canAddMoreTags) - MaterialTheme.colorScheme.onSurfaceVariant - else MaterialTheme.colorScheme.outlineVariant, - ) - } - // v0.3.8.0 — task-list toggle next to the # button. - // Converts the body into editable checklist rows (and - // back); the active mode tints with the primary colour. + // v0.3.8.0 — task-list toggle: converts the body into + // editable checklist rows (and back); the active mode + // tints with the primary colour. IconButton(onClick = { viewModel.convertTo(NoteType.TASK_LIST) }) { Icon( Icons.Filled.Checklist, @@ -552,6 +618,21 @@ fun NoteEditorScreen( else MaterialTheme.colorScheme.onSurfaceVariant, ) } + // Push the hashtag button to the far right, visually + // separated from the action cluster above. + Spacer(Modifier.weight(1f)) + IconButton( + onClick = { viewModel.openAddTagSheet() }, + enabled = state.canAddMoreTags, + ) { + Icon( + Icons.Filled.Tag, + contentDescription = "Add tag", + tint = if (state.canAddMoreTags) + MaterialTheme.colorScheme.onSurfaceVariant + else MaterialTheme.colorScheme.outlineVariant, + ) + } } } } @@ -1252,8 +1333,11 @@ private fun editorFieldStyle(): TextStyle = * the "Draft" branch.) */ private fun draftBarTitle(state: NoteEditorUiState): String { + // v0.4.2.0: voice notes keep the plain content field (title = first + // line), so they read their title from `content` like TEXT does. val titleSource = - if (state.type == NoteType.TEXT) state.content else state.listHeader + if (state.type == NoteType.TEXT || state.type == NoteType.VOICE_NOTE) state.content + else state.listHeader val hasTitle = titleSource.lineSequence().any { it.isNotBlank() } return if (hasTitle) "Draft" else "${state.type.displayName} - (draft)" } 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 48aabad..ea55829 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 @@ -93,12 +93,26 @@ data class NoteEditorUiState( */ 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 + /** + * v0.4.2.0 — `true` once a voice take exists (staged pending or + * already persisted as an attachment). + */ + val hasVoiceTake: Boolean get() = + pendingAttachments.any { it.mimeType.startsWith("audio/") } || + attachments.any { it.mimeType.startsWith("audio/") } + + /** + * `true` while content is non-blank and not in the middle of + * saving. v0.4.2.0: a VOICE_NOTE may also save on the strength of + * its recording alone — the take IS the note's content. + */ + val canSave: Boolean get() = + (content.isNotBlank() || (type == NoteType.VOICE_NOTE && hasVoiceTake)) && + !isSaving + /** `true` while this note is an auto-saved draft (see Note.isDraft). */ val isDraft: Boolean get() = existing?.isDraft == true @@ -450,13 +464,28 @@ class NoteEditorViewModel( fun convertTo(target: NoteType) { _state.update { s -> val next = if (s.type == target) NoteType.TEXT else target - if (next == NoteType.TEXT) { + if (next == NoteType.VOICE_NOTE) { + // v0.4.2.0 — voice mode keeps the plain text field + // (title = first line) exactly like TEXT; a list body + // folds back to its plain form first. The recording is + // NOT body content — it's an ordinary audio attachment, + // so it also survives converting back to plain text. + val source = + if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) s.content + else Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT) + s.copy( + type = next, + listHeader = "", + items = emptyList(), + content = source, + ) + } else if (next == NoteType.TEXT) { // Content already holds the serialised `- [ ]` rows; // just drop out of the structured editor (the inline // GFM checklist rendering from v0.2.0.0 still applies). s.copy(type = NoteType.TEXT, listHeader = "", items = emptyList()) } else { - val source = if (s.type == NoteType.TEXT) { + val source = if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) { s.content } else { // Serialise through the FOLDED legacy form (plain @@ -483,6 +512,7 @@ class NoteEditorViewModel( snackbar = when (it.type) { NoteType.TASK_LIST -> "Task list mode — first line stays the title." NoteType.SHOPPING_LIST -> "Shopping list mode — check an item once it's in your basket." + NoteType.VOICE_NOTE -> "Voice note mode — record with the mic card above the text." else -> "Back to plain text." }, ) @@ -630,6 +660,46 @@ class NoteEditorViewModel( } } + /** + * v0.4.2.0 — stage/persist the finished take of a voice note. + * One take per note: any previous take (pending or already + * persisted) is discarded first. The bytes then ride the ordinary + * attachment pipeline — staged as a [PendingAttachment] while the + * note is unsaved, written straight to the DB afterwards — so + * encryption, backup/restore, and the trash cascade all apply + * without any voice-specific storage. + * + * [mimeType] is the container the recorder actually produced — + * `audio/ogg` (Opus, 32 kbps mono) on API 29+, `audio/mp4` (AAC) + * on API 26–28; the display-name extension follows suit. + */ + fun setVoiceRecording(bytes: ByteArray, mimeType: String = "audio/ogg") { + if (bytes.size < 2048) { + _state.update { it.copy(snackbar = "Recording too short \u2014 try again.") } + return + } + viewModelScope.launch { + _state.value.pendingAttachments + .filter { it.mimeType.startsWith("audio/") } + .forEach { removePendingAttachment(it.tempId) } + val stalePersisted = _state.value.attachments + .filter { it.mimeType.startsWith("audio/") } + if (stalePersisted.isNotEmpty()) { + withContext(Dispatchers.IO) { + stalePersisted.forEach { repository.removeAttachment(it.id) } + } + } + val stamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US) + .format(java.util.Date()) + val ext = if (mimeType == "audio/mp4") "m4a" else "opus" + importAttachmentBytes( + bytes = bytes, + mimeType = mimeType, + displayName = "Voice_$stamp.$ext", + ) + } + } + /** Open the full-screen image viewer for [viewerId]. */ fun openFullScreen(viewerId: ViewerAttachmentId) { _state.update { it.copy(fullScreenAttachmentId = viewerId) } diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/VoiceNoteSection.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/VoiceNoteSection.kt new file mode 100644 index 0000000..601cbd2 --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/VoiceNoteSection.kt @@ -0,0 +1,539 @@ +package org.incido.compose.ui.editor + +import android.content.ContentValues +import android.content.Context +import android.content.Intent +import android.media.MediaPlayer +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import android.widget.Toast +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Download +import androidx.compose.material.icons.filled.FiberManualRecord +import androidx.compose.material.icons.filled.Mic +import androidx.compose.material.icons.filled.Pause +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.Stop +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.core.content.FileProvider +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import org.incido.compose.data.security.SecurityManager +import org.incido.domain.model.NoteAttachment +import org.incido.domain.repository.NoteRepository +import java.io.File +import java.util.Locale + +/** + * v0.4.2.0 — the voice-note body section: sits at the very top of the + * note body (above the text field) whenever the editor is in + * [org.incido.domain.model.NoteType.VOICE_NOTE] mode. + * + * Three states: + * * **No take** — "tap to record" card. + * * **Recording** — live elapsed timer with stop / discard controls. + * * **Take ready** (pending *or* persisted) — media player bar with + * play/pause, seek, a **Download** action that copies the file to + * the system Downloads folder, and a delete action (re-record via + * the mic button — the ViewModel replaces the old take when a new + * recording lands). + * + * The take rides the existing attachment pipeline: while the note is + * unsaved it is a [PendingAttachment] whose bytes live in the UI + * state; after save it is an ordinary `audio/ogg` attachment row + * (encrypted at rest like every other attachment, backed up with the + * note, and still visible in the attachment strip below). + */ +@Composable +fun VoiceNoteSection( + /** Pending (unsaved) voice take, or null. */ + voicePending: PendingAttachment?, + /** Bytes of the pending take (null while still unrecorded). */ + voicePendingBytes: ByteArray?, + /** Persisted voice take of a saved note, or null. */ + voicePersisted: NoteAttachment?, + /** Source of persisted bytes (lazy-loaded by the player). */ + repository: NoteRepository?, + /** Checked on every record tap — reflects RECORD_AUDIO state. */ + hasMicPermission: () -> Boolean, + /** Launches the RECORD_AUDIO permission request. */ + onRequestPermission: () -> Unit, + /** A finished recording is ready to stage/persist (replaces any old take); + * second arg is the recorder's actual mime (`audio/ogg`, or `audio/mp4` on API 26–28). */ + onTakeRecorded: (ByteArray, String) -> Unit, + /** Remove the current take (pending or persisted). */ + onDeleteTake: () -> Unit, + /** Suppress auto-lock around the download share-sheet round-trip (API < 29). */ + securityManager: SecurityManager?, + modifier: Modifier = Modifier, +) { + val ctx = LocalContext.current + val recorder = remember { VoiceRecorder() } + var isRecording by remember { mutableStateOf(false) } + var elapsedMs by remember { mutableStateOf(0L) } + + // Abandon an in-flight take if the editor tears down mid-recording + // (back navigation, config change) — no orphan temp files. + DisposableEffect(Unit) { + onDispose { recorder.cancel() } + } + + // Live tick for the recording timer. + LaunchedEffect(isRecording) { + if (!isRecording) return@LaunchedEffect + val startedAt = android.os.SystemClock.elapsedRealtime() - elapsedMs + while (isRecording) { + elapsedMs = android.os.SystemClock.elapsedRealtime() - startedAt + delay(100) + } + } + + fun startRecording() { + if (!hasMicPermission()) { + onRequestPermission() + return + } + try { + recorder.start(ctx) + elapsedMs = 0L + isRecording = true + } catch (e: Exception) { + Toast.makeText(ctx, "Couldn't start recording", Toast.LENGTH_SHORT).show() + } + } + + fun stopRecording() { + val bytes = recorder.stopAndReadBytes() + isRecording = false + if (bytes == null) { + Toast.makeText(ctx, "Recording failed", Toast.LENGTH_SHORT).show() + } else { + onTakeRecorded(bytes, recorder.recordedMimeType) + } + } + + val hasTake = voicePending != null || voicePersisted != null + + // Persisted bytes lazy-load on demand (same pattern as the + // attachment thumbnails) so the StateFlow never holds the blob. + val lazyPersistedBytes by produceState( + initialValue = null, + key1 = voicePersisted?.id, + ) { + value = if (voicePersisted != null && repository != null) { + withContext(Dispatchers.IO) { repository.getAttachmentBytes(voicePersisted.id) } + } else { + null + } + } + + val takeBytes: ByteArray? = if (voicePending != null) voicePendingBytes else lazyPersistedBytes + val takeName: String = + voicePending?.displayName ?: voicePersisted?.displayName ?: "voice_note.opus" + val takeMime: String = + voicePending?.mimeType ?: voicePersisted?.mimeType ?: "audio/ogg" + val takeKey: Long = voicePending?.tempId ?: voicePersisted?.id ?: 0L + + Column( + modifier = modifier + .fillMaxWidth() + .padding(bottom = 8.dp) + .border( + 1.dp, + MaterialTheme.colorScheme.outlineVariant, + RoundedCornerShape(12.dp), + ) + .background( + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f), + RoundedCornerShape(12.dp), + ) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) { + when { + isRecording -> Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + Icons.Filled.FiberManualRecord, + contentDescription = null, + tint = Color(0xFFD32F2F), + modifier = Modifier.size(16.dp), + ) + Spacer(Modifier.width(8.dp)) + Text( + formatVoiceTime(elapsedMs), + style = MaterialTheme.typography.titleMedium, + ) + Spacer(Modifier.weight(1f)) + IconButton(onClick = { stopRecording() }) { + Icon( + Icons.Filled.Stop, + contentDescription = "Stop recording", + tint = MaterialTheme.colorScheme.primary, + ) + } + IconButton(onClick = { + recorder.cancel() + isRecording = false + }) { + Icon( + Icons.Filled.Close, + contentDescription = "Discard recording", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + hasTake && takeBytes == null -> Row( + modifier = Modifier + .fillMaxWidth() + .height(48.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + Text( + "Loading audio\u2026", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + hasTake && takeBytes != null -> VoicePlayerBar( + bytes = takeBytes, + mimeType = takeMime, + sourceKey = takeKey, + takeName = takeName, + onDelete = onDeleteTake, + onDownload = { saveVoiceTakeToDevice(ctx, securityManager, takeName, takeMime, takeBytes) }, + onRecordAgain = { startRecording() }, + ) + + else -> Row( + modifier = Modifier + .fillMaxWidth() + .clickable { startRecording() } + .padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Box( + modifier = Modifier + .size(40.dp) + .background( + MaterialTheme.colorScheme.primary.copy(alpha = 0.12f), + CircleShape, + ), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Filled.Mic, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp), + ) + } + Text( + "Tap to record a voice note", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +/** + * Media-player bar for a recorded take: play/pause + seek + elapsed / + * total, plus download, re-record and delete actions. Backed by the + * platform [MediaPlayer] — the bytes are written to a small cache file + * (`cacheDir/voice_play/`) because MediaPlayer plays paths, not + * in-memory blobs; the file is rewritten whenever a new take arrives + * and is disposable cache data. + */ +@Composable +private fun VoicePlayerBar( + bytes: ByteArray, + mimeType: String, + sourceKey: Long, + takeName: String, + onDelete: () -> Unit, + onDownload: () -> Unit, + onRecordAgain: () -> Unit, +) { + val ctx = LocalContext.current + + // Materialise the take into a playable cache file. + val playPath by produceState( + initialValue = null, + key1 = sourceKey, + key2 = bytes, + ) { + value = withContext(Dispatchers.IO) { + runCatching { + val dir = File(ctx.cacheDir, "voice_play").apply { mkdirs() } + val ext = if (mimeType == "audio/ogg") "opus" else "m4a" + val file = File(dir, "take_$sourceKey.$ext") + file.writeBytes(bytes) + file.absolutePath + }.getOrNull() + } + } + + var player by remember(sourceKey) { mutableStateOf(null) } + var prepared by remember(sourceKey) { mutableStateOf(false) } + var isPlaying by remember(sourceKey) { mutableStateOf(false) } + var positionMs by remember(sourceKey) { mutableStateOf(0L) } + var durationMs by remember(sourceKey) { mutableStateOf(0L) } + var dragMs by remember(sourceKey) { mutableStateOf(null) } + + DisposableEffect(playPath) { + val path = playPath + if (path == null) { + onDispose { } + } else { + val mp = MediaPlayer() + player = mp + mp.setOnPreparedListener { + durationMs = it.duration.toLong() + prepared = true + } + mp.setOnCompletionListener { + isPlaying = false + positionMs = durationMs + } + mp.setOnErrorListener { _, _, _ -> true } + runCatching { + mp.setDataSource(path) + mp.prepareAsync() + } + onDispose { + runCatching { mp.release() } + player = null + } + } + } + + // Keep the slider in step while playing. + LaunchedEffect(isPlaying, prepared) { + if (!isPlaying || !prepared) return@LaunchedEffect + while (isPlaying) { + player?.let { positionMs = it.currentPosition.toLong() } + delay(200) + } + } + + Column(modifier = Modifier.fillMaxWidth()) { + Row(verticalAlignment = Alignment.CenterVertically) { + IconButton( + onClick = { + val mp = player ?: return@IconButton + if (!prepared) return@IconButton + if (mp.isPlaying) { + mp.pause() + isPlaying = false + } else { + if (positionMs >= durationMs && durationMs > 0) { + mp.seekTo(0) + positionMs = 0 + } + mp.start() + isPlaying = true + } + }, + enabled = prepared, + ) { + Icon( + imageVector = if (isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow, + contentDescription = if (isPlaying) "Pause" else "Play", + tint = MaterialTheme.colorScheme.primary, + ) + } + Text( + text = formatVoiceTime((dragMs ?: positionMs.toFloat()).toLong()), + style = MaterialTheme.typography.labelMedium, + ) + Slider( + value = (dragMs ?: positionMs.toFloat()).coerceIn( + 0f, + durationMs.coerceAtLeast(1).toFloat(), + ), + onValueChange = { dragMs = it }, + onValueChangeFinished = { + val target = dragMs + if (target != null) { + dragMs = null + val seek = target.toInt() + player?.let { mp -> + if (prepared) { + mp.seekTo(seek) + positionMs = seek.toLong() + } + } + } + }, + valueRange = 0f..durationMs.coerceAtLeast(1).toFloat(), + enabled = prepared, + modifier = Modifier + .weight(1f) + .padding(horizontal = 4.dp), + ) + Text( + text = formatVoiceTime(durationMs), + style = MaterialTheme.typography.labelMedium, + ) + // Download = save a copy to the system Downloads folder + // (pre-Q devices get the share sheet, which reaches the + // same destinations). + IconButton(onClick = onDownload) { + Icon( + Icons.Filled.Download, + contentDescription = "Download recording", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton(onClick = onRecordAgain) { + Icon( + Icons.Filled.Mic, + contentDescription = "Re-record (replaces current take)", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton(onClick = onDelete) { + Icon( + Icons.Filled.Delete, + contentDescription = "Delete recording", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Text( + text = takeName, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +/** + * Save the take to the system Downloads folder via MediaStore (API 29+, + * no storage permission needed). On API 26–28 — where MediaStore + * Downloads doesn't exist — fall back to the v0.3.1.3 FileProvider + * outbox + share sheet, which reaches the same destinations plus + * "Save to device" handlers. + */ +private fun saveVoiceTakeToDevice( + ctx: Context, + securityManager: SecurityManager?, + displayName: String, + mimeType: String, + bytes: ByteArray, +) { + val safeName = displayName + .replace(Regex("[/\\\\:*?\"<>|]"), "_") + .ifEmpty { "voice_note.opus" } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val saved = runCatching { + val values = ContentValues().apply { + put(MediaStore.Downloads.DISPLAY_NAME, safeName) + put(MediaStore.Downloads.MIME_TYPE, mimeType) + put( + MediaStore.Downloads.RELATIVE_PATH, + Environment.DIRECTORY_DOWNLOADS, + ) + } + val uri = ctx.contentResolver.insert( + MediaStore.Downloads.EXTERNAL_CONTENT_URI, + values, + ) ?: return@runCatching false + ctx.contentResolver.openOutputStream(uri)?.use { out -> + out.write(bytes) + } ?: return@runCatching false + true + }.getOrDefault(false) + if (saved) { + Toast.makeText(ctx, "Saved to Downloads", Toast.LENGTH_SHORT).show() + return + } + // MediaStore refused (provider hiccup) — fall through to the + // share sheet as the last resort. + } + + runCatching { + val outbox = File(ctx.cacheDir, "open_outbox").apply { mkdirs() } + val tmp = File(outbox, "dl_${System.currentTimeMillis()}_$safeName") + tmp.writeBytes(bytes) + val uri = FileProvider.getUriForFile(ctx, "${ctx.packageName}.fileprovider", tmp) + val send = Intent(Intent.ACTION_SEND).apply { + type = mimeType + putExtra(Intent.EXTRA_STREAM, uri) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + // Auto-Lock = Immediate must not fire while the chooser is up + // (same v0.3.4.0 hotfix as the attachment viewer). + securityManager?.beginExternalActivity() + ctx.startActivity(Intent.createChooser(send, "Save recording")) + }.onFailure { + Toast.makeText(ctx, "Couldn't save recording", Toast.LENGTH_SHORT).show() + } +} + +/** ms → "m:ss" (or "h:mm:ss" past an hour). */ +internal fun formatVoiceTime(ms: Long): String { + val totalSec = ms / 1000 + val h = totalSec / 3600 + val m = (totalSec % 3600) / 60 + val s = totalSec % 60 + return if (h > 0) { + String.format(Locale.US, "%d:%02d:%02d", h, m, s) + } else { + String.format(Locale.US, "%d:%02d", m, s) + } +} + + + + + diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/VoiceRecorder.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/VoiceRecorder.kt new file mode 100644 index 0000000..79558dd --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/VoiceRecorder.kt @@ -0,0 +1,132 @@ +package org.incido.compose.ui.editor + +import android.content.Context +import android.media.MediaRecorder +import android.os.Build +import java.io.File +import java.io.IOException + +/** + * v0.4.2.0 — thin MediaRecorder wrapper for voice notes. + * + * Records Opus audio in an Ogg container (`.opus`, mime `audio/ogg`) + * at 32 kbps, single channel, 48 kHz — tiny files, excellent speech + * quality, and produced by the platform MediaRecorder with no extra + * dependencies (the app stays dependency-light per Development Plan + * privacy/offline rules). Opus-in-Ogg output via MediaRecorder is + * public API only from API 29, so API 26–28 devices keep the previous + * AAC/MP4 path (`.m4a`, mime `audio/mp4`); [recordedMimeType] reports + * which container [start] actually used. + * + * Note: the MediaRecorder surface exposes no encoder knobs for Opus + * frame size or complexity, so both stay at platform defaults (Opus + * on Android encodes 20 ms frames); hitting 120 ms frames / + * complexity 10 would require bundling native libopus — deferred. + * + * The take lands in a temp file under `cacheDir/voice_rec/`; the + * caller reads it back as a [ByteArray] on [stopAndReadBytes] and the + * temp file is deleted immediately — the bytes then ride the ordinary + * attachment pipeline into ObjectBox (same lifecycle as the camera + * outbox from v0.3.1.0). + * + * Not thread-safe: drive it from the main thread only. + */ +class VoiceRecorder { + + private var recorder: MediaRecorder? = null + private var outFile: File? = null + private var opus = false + + /** True between a successful [start] and the matching stop/cancel. */ + val isRecording: Boolean get() = recorder != null + + /** + * Mime type of the container [start] actually used — `audio/ogg` + * (Opus) on API 29+, `audio/mp4` (AAC) on API 26–28. Valid after + * any successful [start]; callers use it to tag the finished take. + */ + val recordedMimeType: String get() = if (opus) "audio/ogg" else "audio/mp4" + + /** + * Start capturing from the mic into a fresh temp file. + * Throws [IOException] / [RuntimeException] when the mic is busy, + * the permission was revoked mid-session, or the device has none — + * callers should catch and surface a snackbar. + */ + @Suppress("DEPRECATION") + fun start(context: Context) { + if (recorder != null) return + // Opus-in-Ogg via MediaRecorder is public API only from API 29 + // (minSdk is 26), so older devices keep the AAC/MP4 path. + val useOpus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q + val dir = File(context.cacheDir, "voice_rec").apply { mkdirs() } + val file = File( + dir, + "take_${System.currentTimeMillis()}" + if (useOpus) ".opus" else ".m4a", + ) + val rec = MediaRecorder() + try { + rec.apply { + setAudioSource(MediaRecorder.AudioSource.MIC) + if (useOpus) { + setOutputFormat(MediaRecorder.OutputFormat.OGG) + setAudioEncoder(MediaRecorder.AudioEncoder.OPUS) + setAudioEncodingBitRate(32_000) // 32 kbps + setAudioChannels(1) // single channel + setAudioSamplingRate(48_000) // Opus native rate + } else { + setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) + setAudioEncoder(MediaRecorder.AudioEncoder.AAC) + setAudioEncodingBitRate(96_000) + setAudioSamplingRate(44_100) + } + setOutputFile(file.absolutePath) + prepare() + start() + } + recorder = rec + outFile = file + opus = useOpus + } catch (e: Exception) { + rec.release() + file.delete() + throw e + } + } + + /** + * Stop the capture, read the recorded bytes, and delete the temp + * file. Returns `null` when nothing was recorded or the encoder + * failed. Always safe to call — a no-op while idle. + */ + fun stopAndReadBytes(): ByteArray? { + val rec = recorder ?: return null + recorder = null + val file = outFile + outFile = null + return try { + rec.stop() + val bytes = file?.readBytes() + bytes?.takeIf { it.isNotEmpty() } + } catch (e: RuntimeException) { + null + } finally { + rec.release() + file?.delete() + } + } + + /** + * Abandon the in-flight take without reading it (the ✕ while + * recording). Always safe to call — a no-op while idle. + */ + fun cancel() { + val rec = recorder ?: return + recorder = null + val file = outFile + outFile = null + runCatching { rec.stop() } // stop() throws if nothing was captured + rec.release() + file?.delete() + } +} 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 f9eb31b..4f8c70c 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 @@ -32,6 +32,7 @@ import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.DeleteForever import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Menu +import androidx.compose.material.icons.filled.Mic import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material.icons.filled.Restore @@ -444,8 +445,13 @@ private fun NoteCard( // v0.3.8.0: task / shopping lists render marker-free on cards — // header line becomes the title, items show as clean "Name ×qty @$X" // text. The checkbox state lives in the summary row below instead. - val (title, body) = if (note.type == NoteType.TEXT) Note.titleAndBody(note.content) - else Note.cardPresentation(note.content, note.type) + // v0.4.2.0: voice notes carry a plain prose body (title = first + // line), so they split like TEXT — the cardPresentation list parser + // would mangle their content. + val (title, body) = + if (note.type == NoteType.TEXT || note.type == NoteType.VOICE_NOTE) + Note.titleAndBody(note.content) + else Note.cardPresentation(note.content, note.type) // Drafts with no title introduce themselves by kind — "Shopping // List - (draft)" beats a bare "Untitled" in the Drafts view. The // stored content is untouched; this is display-only, so typing a @@ -606,6 +612,27 @@ private fun NoteCard( ) } } + if (note.type == NoteType.VOICE_NOTE) { + // v0.4.2.0: voice notes carry a mic badge so the + // kind is recognisable on the card even when the + // body is empty (the take itself is an audio + // attachment, not visible as a thumbnail). + Spacer(modifier = Modifier.padding(top = 4.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + Icons.Default.Mic, + contentDescription = null, + modifier = Modifier.size(14.dp), + tint = secondaryColor, + ) + Spacer(Modifier.size(6.dp)) + Text( + text = note.type.displayName, + style = MaterialTheme.typography.labelSmall, + color = secondaryColor, + ) + } + } if (note.hashtags.isNotEmpty()) { Spacer(modifier = Modifier.padding(top = 4.dp)) HashtagRow( 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 index 33d23cf..ca6fcee 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsViewModel.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsViewModel.kt @@ -354,7 +354,7 @@ class SettingsViewModel( /** The version string baked into backup payloads and shown on * the About card. Mirrors `app/build.gradle.kts` `versionName` * — if you bump one, bump both. */ - const val APP_VERSION = "0.4.1.1" + const val APP_VERSION = "0.4.2.0" val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { 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 727da44..b9b2180 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 @@ -38,6 +38,13 @@ data class Note( /** Convenience: the first image attachment, or `null` if none. */ val firstImageAttachment: NoteAttachment? get() = attachments.firstOrNull { it.isImage } + + /** + * v0.4.2.0 — Convenience: the first audio attachment (the note's + * voice take, see [NoteType.VOICE_NOTE]), or `null` if none. + */ + val firstAudioAttachment: NoteAttachment? + get() = attachments.firstOrNull { it.mimeType.startsWith("audio/") } companion object { /** Shown when a note's content has no usable first line. */ 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 index 01e541e..d1a744c 100644 --- a/core/domain/src/main/kotlin/org/incido/domain/model/NoteAttachment.kt +++ b/core/domain/src/main/kotlin/org/incido/domain/model/NoteAttachment.kt @@ -24,4 +24,7 @@ data class NoteAttachment( ) { /** Convenience: true for any image-prefixed mime type. */ val isImage: Boolean get() = mimeType.startsWith("image/") + + /** v0.4.2.0 — true for any audio-prefixed mime type (voice-note take). */ + val isAudio: Boolean get() = mimeType.startsWith("audio/") } diff --git a/core/domain/src/main/kotlin/org/incido/domain/model/NoteType.kt b/core/domain/src/main/kotlin/org/incido/domain/model/NoteType.kt index a555bcc..44e4250 100644 --- a/core/domain/src/main/kotlin/org/incido/domain/model/NoteType.kt +++ b/core/domain/src/main/kotlin/org/incido/domain/model/NoteType.kt @@ -21,7 +21,16 @@ enum class NoteType(val storageKey: Short, val displayName: String) { TASK_LIST(1, "Task List"), /** Checklist plus a per-item cost (number pad) and a running total. */ - SHOPPING_LIST(2, "Shopping List"); + SHOPPING_LIST(2, "Shopping List"), + + /** + * v0.4.2.0 — a note carrying a voice recording. The body stays a + * plain text field (title = first line, exactly like [TEXT]); the + * audio itself is an ordinary audio-prefixed attachment (see + * [Note.firstAudioAttachment]), rendered by the editor's audio + * player bar directly above the body. + */ + VOICE_NOTE(3, "Voice Note"); companion object { /** Convert from the stored [Short] back to the enum, defaulting to [TEXT]. */