19 Commits
Author SHA1 Message Date
Incido Developer f87ca17ded feat: v0.4.2.0 — voice notes (Opus 32 kbps mono), toolbar reorder, backup-first release notes
dev / Build debug APK (push) Successful in 57s
release / Build & attach release APK (push) Successful in 1m31s
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.
2026-09-23 16:56:57 +12:00
Incido Developer 1d97376aef fix: v0.4.1.1 — saved notes leave Drafts; Enter adds row in price box
dev / Build debug APK (push) Successful in 47s
release / Build & attach release APK (push) Successful in 1m20s
Two editor regressions shipped in v0.4.1.0, both fixed here:

- Saving a note published it but left UiState.existing.isDraft = true,
  so the editor's dispose-time flushDraft() re-persisted the note as a
  draft and it reappeared under Drafts. The save path now adopts the
  published row into state (isDraft = false, current hashtags kept),
  letting persistDraftNow()'s already-published guard make that flush
  a no-op; saved notes stay on Home.
- Enter on a shopping-list Price field had no keyboard handler, so the
  bare ImeAction.Next fell through to system focus traversal and — the
  price being the row's last field inside the LazyColumn — wrapped the
  cursor back to the Title. The field now wires
  KeyboardActions(onNext = onAddAfter) like the Product field: Enter
  adds a fresh row with the cursor in its Product box.

Version lockstep per §11.1: versionCode 37, versionName 0.4.1.1,
APP_VERSION, README intro + current-release line + smoke-test
regression steps, PREVIOUS_HISTORY.md section, ReleaseNotes.RECENT
(v0.3.8.1 drops off the 5-entry tail), Dev Plan §10 row.

assembleDebug + assembleRelease both green (CONTRIBUTING step 4).
2026-09-23 06:14:36 +12:00
Incido Developer d9043db857 feat: v0.4.1.0 — colour filters, drafts, empty trash, editor polish
dev / Build debug APK (push) Successful in 58s
release / Build & attach release APK (push) Successful in 1m27s
Ships everything staged since v0.4.0.0 as v0.4.1.0:

- Colour filters: a five-swatch strip under the drawer's Favorites
  narrows the list to active notes of that colour (NoteFilter
  ByColor, observeByColor/searchByColor, color:<NAME> route).
- Auto-saved drafts: new notes persist as drafts while typed
  (Note.isDraft, Drafts filter + drawer row, debounced autosave
  with flush-on-exit) and ride along in encrypted backups.
- Empty Trash: a DeleteForever button + confirmation dialog in the
  Trash view; deleteAllTrashed() cascades hashtag xrefs and
  attachments exactly like delete().
- Editor row rebuild: EditorLineField unified on one underlined
  BasicTextField (M3 TextField's 56 dp min container was the root
  of the double-height rows); checklist controls centre vertically
  beside wrapping labels.
- Untitled drafts read "Shopping List — (draft)" on cards and in
  the editor bar via NoteType.displayName (display-only; stored
  content untouched).

Version lockstep per §11.1: versionCode 36, versionName 0.4.1.0,
APP_VERSION, README intro + smoke-test checklist, PREVIOUS_HISTORY.md
section, ReleaseNotes.RECENT (v0.3.7.0 drops off the tail), Dev Plan
§10 row.
2026-09-23 05:24:23 +12:00
Incido Developer d45cb7c31e docs(release-notes): drop stray trailing rule from v0.4.0.0 section
dev / Build debug APK (push) Successful in 3m16s
v0.4.0.0 was the only per-version section ending with its own '---', which combined with the CI footer divider rendered as a doubled rule on the published release. Removing it matches every other section (heading separated by a blank line) and is part of the same single-line-consistency cleanup.
2026-09-18 18:13:46 +12:00
Incido Developer 3d234f307e docs(release-notes): unwrap PREVIOUS_HISTORY notes to single lines
dev / Build debug APK (push) Successful in 3m21s
release-notes.py copies each version section verbatim, so the hard-wrapping in the v0.4.0.0 and v0.3.8.1 sections (and the file preamble) shipped as premature returns in the Gitea release description and Incido-<version>-changes.md asset. Unwrap them to one line per note, matching every section from v0.3.8.0 down. Also normalise the redundant '- **Title.** — desc' bullet heads to the house '- **Title.** desc' style across the file. Record the rule (write each note as one complete line; the release UI reflows it) in Development Plan 11.1 and CONTRIBUTING 5 so it does not recur.
2026-09-18 17:58:21 +12:00
Incido Developer ffa821bf28 docs(readme): sync README with the v0.4.0.0 release
dev / Build debug APK (push) Successful in 37s
Bump the intro + 'Current release' to v0.4.0.0 and add the new in-app Carnet/QuickNote (.zip) import to the feature list. Reframe the reinstall note: the new CI signing key dates from v0.3.8.1 and is reused on every release, so only installs from v0.3.8.0 or earlier need a clean reinstall; v0.3.8.1 onwards upgrades in place. Drop the now-wrong 'identical to v0.3.8.0' line, which predates the import feature.
2026-09-18 17:27:14 +12:00
Incido Developer f337e162f7 chore(release): v0.4.0.0
dev / Build debug APK (push) Successful in 1m58s
release / Build & attach release APK (push) Successful in 3m11s
Bump versionName 0.3.8.1 -> 0.4.0.0 (versionCode 34 -> 35) and mirror it in SettingsViewModel.APP_VERSION. Add the v0.4.0.0 'What's New' entry (drops v0.3.6.0 off the 5-recent tail) and a PREVIOUS_HISTORY.md section for the CI release description. Marks the in-app Carnet/QuickNote import as a minor feature release.
2026-09-18 16:09:24 +12:00
Incido Developer cbe015839b feat(import): import Carnet/QuickNote (.sqd) archives in-app
Adds an 'Import 3rd Party Notes' button to Settings > Backup & Restore that reads a Carnet/QuickNote .zip export (a single archive bundling one .sqd per note) and imports every note directly on-device, no pre-conversion step. Each .sqd is itself a zip (index.html + metadata.json + optional data/ attachments); the importer does a nested-zip read. Rich-text bodies are flattened to plain text, colours/keywords/links carry over, to-do lists become native checklists, and image attachments are imported (auto-generated preview thumbnails skipped). Additive import with per-note fault isolation.
2026-09-18 16:04:53 +12:00
Incido Developer 7e335d14ef docs(plan): add 11.5 - how to re-run a failed release
dev / Build debug APK (push) Successful in 19s
Records why re-running a red release run replays the tag's old workflow (and wipes assets on the way down), the dispatch-from-main retry path, and the task-id-vs-run-number / script-echo log gotchas.
2026-09-17 19:09:04 +12:00
Incido Developer c8c2c98c8e ci(release): add a workflow_dispatch retry path for releases
dev / Build debug APK (push) Successful in 21s
A tag push pins the workflow file to the tag's own commit, so re-running a red release run replays the OLD workflow even when main is already fixed - that is precisely why run 78 kept dying on the cp bug after the fix landed, and each retry deleted the changelog asset before failing to re-upload it.

Adds workflow_dispatch with a required 'tag' input plus a RELEASE_TAG env (input on dispatch, tag name on push) used by both checkouts and the release step, so a release can be re-published from main's current workflow against any existing tag. The checkout also gains a targeted shallow fetch of the tag, since a --depth=1 default-branch clone may not carry the tag's commit when dispatched from main.
2026-09-17 19:04:34 +12:00
Incido Developer cbebac3254 fix(release): stop copying the notes file onto itself before upload
dev / Build debug APK (push) Successful in 22s
release / Build & attach release APK (push) Successful in 26s
NOTES_FILE is already /tmp/Incido-<version>-changes.md, so 'cp $NOTES_FILE /tmp/$NOTES_ASSET' was a self-copy: cp exits 1 and set -e aborted the step AFTER both APKs had uploaded. That is what turned run 78 (tag v0.3.8.1) red - the LAN API change itself worked, the release and both APK assets landed first. Upload $NOTES_FILE directly instead.
2026-09-17 18:24:12 +12:00
Incido Developer ab26fe5f98 fix(release): v0.3.8.1 emergency rebuild, reinstall required
dev / Build debug APK (push) Successful in 46s
release / Build & attach release APK (push) Failing after 28s
Re-release v0.3.8.0 unchanged so the repaired pipeline can actually publish it: the v0.3.8.0 run was cancelled and never produced a release or APKs.

The build ran on a runner with an empty keystore cache, so CI minted a NEW signing key: installs cannot be upgraded in place (signature conflict), and with allowBackup=false an uninstall takes the user's notes. The release notes, README, and in-app What's New now all lead with export-a-backup-first.

Lockstep per Dev Plan 11.1: versionCode 33->34, versionName -> 0.3.8.1, APP_VERSION, README, PREVIOUS_HISTORY section, ReleaseNotes.RECENT (0.3.5.1 drops off the tail), Dev Plan 10 row.
2026-09-17 18:07:41 +12:00
Incido Developer dee20bf0f4 ci(release): point release API at LAN Gitea instance
dev / Build debug APK (push) Successful in 21s
Target http://192.168.8.17:3000 instead of https://git.trevena.info for the release create/asset-upload calls, so the release job talks to the instance over the LAN.
2026-09-17 17:35:47 +12:00
Incido Developer a5b5d334c1 ci: move runner toolchain cache from /tmp to /var/lib/gitea-runner/work
dev / Build debug APK (push) Successful in 2m18s
release / Build & attach release APK (push) Canceled after 7m28s
/tmp is wiped on every reboot, forcing re-download of the JDK and
Android SDK (~700 MB) and, worse, re-minting the release signing
keystore. Persist the cache under /var/lib/gitea-runner/work so it
survives reboots. Genuine per-run scratch files stay in /tmp.
2026-09-17 16:40:31 +12:00
Incido Developer 32166a3100 feat(lists): task and shopping-list note types with running total
dev / Build debug APK (push) Canceled after 15m52s
NoteType (TEXT / TASK_LIST / SHOPPING_LIST) persists in an additive
NoteEntity.typeKey column (ObjectBox auto-migrates; old rows = TEXT).
List bodies stay GitHub-flavoured '- [ ]' lines so search, field
encryption, backups (defaulted noteType) and Trash keep working.

Editor: checklist + basket buttons convert any note; rows are uniform
underlined line fields (13sp) - product, 'Quan.' quantity (defaults to
1 on blur), and POS-style price showing raw cents while focused and
$1.23 on focus loss. Sticky total bar sums qty x price of checked
rows in integer cents via an explicit {q.. p..} end-of-line marker so
product text is never scanned for numbers.

Fixes found in device testing: cards rendered raw markdown for list
notes stranded as TEXT by partial builds - read-time Note.inferListType
now heals them; quantity field was clipped invisible (64dp vs the 48dp
icon target) - replaced by the free-text line; the serializer emitted
a bare 'q' slot (broken '{q p1.23}' markers, stray ' x' folds) - now
null-when-default. Add-tag suggestions rebuilt on flatMapLatest so the
autocomplete re-queries per keystroke.

versionCode 32->33, versionName 0.3.8.0, APP_VERSION in lockstep.
2026-09-17 15:43:43 +12:00
Incido Developer 7b6187f99a ci(release): attach per-version notes from PREVIOUS_HISTORY.md to releases
Per-version user-facing changelog moved out of the README table into
PREVIOUS_HISTORY.md (newest-first sections, Development Plan §11.1).
On tag push the workflow now harvests the matching section via
scripts/ci/release-notes.py and uses it as the release description,
uploading an Incido-<version>-changes.md beside the APKs; a missing
section falls back to the plain default description. CONTRIBUTING §5
documents the new release-notes maintenance step.
2026-09-17 15:43:20 +12:00
Incido Developer 576080c8b5 ci(release): persist signing keystore in runner cache for stable signatures
dev / Build debug APK (push) Successful in 36s
release / Build & attach release APK (push) Successful in 6m50s
The build step minted a fresh keystore inside the checkout on every
run, so each CI release was signed with a different key. Upgrading
from any previous release then failed with a signature conflict
(INSTALL_FAILED_UPDATE_INCOMPATIBLE) — and with allowBackup=false,
the only workaround was uninstalling, which destroys the user's
notes.

The keystore is now minted once in /tmp/gitea-runner-work (the same
persistent cache that already holds the JDK and Android SDK) and
copied into the checkout before building. Every release from now on
shares one signing key, so in-place upgrades work. Only a runner-host
rebuild would mint a new key (breaking exactly one upgrade).

Note: v0.3.7.0 was signed with an ephemeral key that no longer
exists, so the v0.3.7.0 -> v0.3.7.1 upgrade still requires a one-time
uninstall (export a backup first).
2026-08-30 11:02:50 +12:00
Incido Developer 4a28f4f52b ci(release): tolerate Cloudflare 524 timeouts on APK uploads
dev / Build debug APK (push) Successful in 36s
The v0.3.7.1 release run failed in the attach step: the 28.7 MB debug
APK upload took ~126s through the Cloudflare proxy, which returned
"error code: 524" (origin timeout, ~100s limit). The step then crashed
parsing the non-JSON error page as JSON, and the release APK was never
attempted — leaving release 36 with zero assets.

upload_asset() now:
- retries with --retry-all-errors so HTTP error responses (524) are
  retried, not just connection failures;
- verifies success server-side by listing the release assets after
  each attempt (a 524 often means the origin saved the file before
  Cloudflare gave up, so the response body is not trusted);
- only fails after 5 attempts with the asset still missing.
2026-08-30 10:41:04 +12:00
Incido Developer 37e9c14d1e release: v0.3.7.1 — UI polish, image-viewer fix, new flat icon
dev / Build debug APK (push) Successful in 1m52s
release / Build & attach release APK (push) Failing after 6m30s
Maintenance release.

UI polish:
- Editor top bar decluttered: camera / attach-file / add-tag moved out of
  the title bar into a Keep-style bottom action row, so the title and
  remaining buttons (favourite, save, overflow) always fit, even on
  narrow screens. Title is now "New note" / "Edit note" with ellipsis.
- Search auto-focuses when opened and shows a clear button while typing.
- Long tag lists in the navigation drawer now scroll within the sheet
  instead of overflowing the bottom (weight(1f) on the scroll column).
- Add-tag sheet opens with the keyboard already up.

Bug fix:
- Image viewer no longer flashes a false "couldn't decode" error on
  every persisted image open (the old LaunchedEffect checked the bitmap
  before the async load finished); genuine failures now show
  "Couldn't load image" in place of "Loading…".

New flat app icon:
- incido_flat_icon.png replaces the v0.3.3.8 artwork: adaptive
  foregrounds (108-432px) + legacy mipmaps (48-192px) regenerated;
  ic_launcher_background re-tinted #010435 -> #352999 to match.

Hygiene:
- Unused persistedBytes param dropped from AttachmentStrip; redundant
  repoForViewer alias and dead _ignored val removed; fully-qualified
  Spacer/Image/Column/Dispatchers references replaced with imports.

versionCode 31->32, versionName "0.3.7.0"->"0.3.7.1",
SettingsViewModel.APP_VERSION bumped in lockstep.
2026-08-30 10:19:49 +12:00
54 changed files with 3840 additions and 356 deletions

No files matched your search

+4 -4
View File
@@ -19,7 +19,7 @@ jobs:
- name: Set up JDK 17 - name: Set up JDK 17
run: | run: |
WORKDIR=/tmp/gitea-runner-work WORKDIR=/var/lib/gitea-runner/work
if [ ! -d "$WORKDIR/jdk" ]; then if [ ! -d "$WORKDIR/jdk" ]; then
wget -q 'https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.13%2B11/OpenJDK17U-jdk_x64_linux_hotspot_17.0.13_11.tar.gz' -O /tmp/jdk.tar.gz wget -q 'https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.13%2B11/OpenJDK17U-jdk_x64_linux_hotspot_17.0.13_11.tar.gz' -O /tmp/jdk.tar.gz
mkdir -p "$WORKDIR/jdk" mkdir -p "$WORKDIR/jdk"
@@ -31,7 +31,7 @@ jobs:
- name: Set up Android SDK - name: Set up Android SDK
run: | run: |
WORKDIR=/tmp/gitea-runner-work WORKDIR=/var/lib/gitea-runner/work
SDK=$WORKDIR/android-sdk SDK=$WORKDIR/android-sdk
if [ ! -d "$SDK/cmdline-tools/latest" ]; then if [ ! -d "$SDK/cmdline-tools/latest" ]; then
mkdir -p "$SDK" mkdir -p "$SDK"
@@ -55,7 +55,7 @@ jobs:
run: | run: |
cd repo cd repo
chmod +x gradlew chmod +x gradlew
export JAVA_HOME=/tmp/gitea-runner-work/jdk export JAVA_HOME=/var/lib/gitea-runner/work/jdk
export ANDROID_HOME=/tmp/gitea-runner-work/android-sdk export ANDROID_HOME=/var/lib/gitea-runner/work/android-sdk
export PATH=$JAVA_HOME/bin:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH export PATH=$JAVA_HOME/bin:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH
./gradlew assembleDebug --no-daemon ./gradlew assembleDebug --no-daemon
+112 -19
View File
@@ -4,23 +4,42 @@ on:
push: push:
tags: tags:
- 'v*.*.*' - 'v*.*.*'
# Retry path: a tag push pins the workflow file to that tag's commit, so a
# re-run of a red release run replays the OLD workflow even after main is
# fixed (that is exactly how run 78 kept failing post-fix). Dispatching
# against main runs main's current workflow against any already-published
# tag, so a release can be re-published without moving a tag.
workflow_dispatch:
inputs:
tag:
description: 'Existing tag to rebuild and re-publish, e.g. v0.3.8.1'
required: true
type: string
jobs: jobs:
build-release: build-release:
name: Build & attach release APK name: Build & attach release APK
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 30 timeout-minutes: 30
env:
# The tag this run publishes: the tag itself on a push, or the typed
# input on a manual retry (where github.ref_name is just the branch).
RELEASE_TAG: ${{ github.event.inputs.tag || github.ref_name }}
steps: steps:
- name: Checkout - name: Checkout
run: | run: |
git clone --depth=1 https://git.trevena.info/nick/incido.git repo git clone --depth=1 https://git.trevena.info/nick/incido.git repo
cd repo cd repo
# Targeted shallow fetch of the exact tag: the clone above is shallow
# off the default branch, so --tags alone may not carry the tag's
# commit when the run is dispatched from main instead of pushed.
git fetch --depth=1 origin tag "$RELEASE_TAG" || true
git fetch --tags origin git fetch --tags origin
git checkout ${{ github.ref_name }} git checkout "$RELEASE_TAG"
- name: Set up JDK 17 - name: Set up JDK 17
run: | run: |
WORKDIR=/tmp/gitea-runner-work WORKDIR=/var/lib/gitea-runner/work
if [ ! -d "$WORKDIR/jdk" ]; then if [ ! -d "$WORKDIR/jdk" ]; then
wget -q 'https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.13%2B11/OpenJDK17U-jdk_x64_linux_hotspot_17.0.13_11.tar.gz' -O /tmp/jdk.tar.gz wget -q 'https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.13%2B11/OpenJDK17U-jdk_x64_linux_hotspot_17.0.13_11.tar.gz' -O /tmp/jdk.tar.gz
mkdir -p "$WORKDIR/jdk" mkdir -p "$WORKDIR/jdk"
@@ -32,7 +51,7 @@ jobs:
- name: Set up Android SDK - name: Set up Android SDK
run: | run: |
WORKDIR=/tmp/gitea-runner-work WORKDIR=/var/lib/gitea-runner/work
SDK=$WORKDIR/android-sdk SDK=$WORKDIR/android-sdk
if [ ! -d "$SDK/cmdline-tools/latest" ]; then if [ ! -d "$SDK/cmdline-tools/latest" ]; then
mkdir -p "$SDK" mkdir -p "$SDK"
@@ -57,19 +76,31 @@ jobs:
timeout-minutes: 25 timeout-minutes: 25
run: | run: |
cd repo cd repo
git checkout ${{ github.ref_name }} git checkout "$RELEASE_TAG"
# Persistent signing keystore: minted ONCE in the runner's
# cache dir (which survives across runs, same place the JDK
# and SDK live) and copied into the checkout. Every release
# is therefore signed with the SAME key, so users can
# upgrade in place instead of hitting a signature conflict
# (and, with allowBackup=false, losing their notes).
# A runner-host rebuild would mint a fresh key — the only
# scenario that breaks one upgrade.
mkdir -p keystore mkdir -p keystore
if [ ! -f keystore/release.jks ]; then if [ ! -f /var/lib/gitea-runner/work/release.jks ]; then
echo "Minting new persistent CI keystore"
keytool -genkey -noprompt -v \ keytool -genkey -noprompt -v \
-keystore keystore/release.jks \ -keystore /var/lib/gitea-runner/work/release.jks \
-keyalg RSA -keysize 2048 -validity 10000 \ -keyalg RSA -keysize 2048 -validity 10000 \
-alias incido \ -alias incido \
-storepass incido_dev_keystore \ -storepass incido_dev_keystore \
-keypass incido_dev_keystore \ -keypass incido_dev_keystore \
-dname "CN=Incido Dev, OU=Local, O=Incido, L=Local, ST=Local, C=NZ" -dname "CN=Incido Dev, OU=Local, O=Incido, L=Local, ST=Local, C=NZ"
else
echo "Reusing persistent CI keystore from runner cache"
fi fi
export JAVA_HOME=/tmp/gitea-runner-work/jdk cp /var/lib/gitea-runner/work/release.jks keystore/release.jks
export ANDROID_HOME=/tmp/gitea-runner-work/android-sdk export JAVA_HOME=/var/lib/gitea-runner/work/jdk
export ANDROID_HOME=/var/lib/gitea-runner/work/android-sdk
export PATH=$JAVA_HOME/bin:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH export PATH=$JAVA_HOME/bin:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH
chmod +x ./gradlew chmod +x ./gradlew
./gradlew --stop 2>/dev/null || true ./gradlew --stop 2>/dev/null || true
@@ -89,14 +120,28 @@ jobs:
run: | run: |
set -e set -e
cd repo cd repo
TAG="${{ github.ref_name }}" TAG="$RELEASE_TAG"
VERSION="${TAG#v}" VERSION="${TAG#v}"
API="https://git.trevena.info/api/v1/repos/nick/incido" API="http://192.168.8.17:3000/api/v1/repos/nick/incido"
APK_DEBUG="Incido-$VERSION-debug.apk" APK_DEBUG="Incido-$VERSION-debug.apk"
APK_RELEASE="Incido-$VERSION-release.apk" APK_RELEASE="Incido-$VERSION-release.apk"
echo "Tag: $TAG Version: $VERSION" echo "Tag: $TAG Version: $VERSION"
# User-facing release notes: harvest this version's section from
# PREVIOUS_HISTORY.md (maintained per Development Plan §11.1).
# Used as the release description and uploaded beside the APKs.
NOTES_FILE="/tmp/Incido-$VERSION-changes.md"
if python3 scripts/ci/release-notes.py "$VERSION" --out "$NOTES_FILE"; then
HAS_NOTES=1
echo "--- Release notes preview (v$VERSION) ---"
head -12 "$NOTES_FILE"
echo "---"
else
HAS_NOTES=0
echo "No PREVIOUS_HISTORY.md section for v$VERSION - falling back to the default description."
fi
echo "--- Check for existing release ---" echo "--- Check for existing release ---"
RELEASE_ID=$(curl -s "$API/releases/tags/$TAG" \ RELEASE_ID=$(curl -s "$API/releases/tags/$TAG" \
-H "Authorization: token $GH_TOKEN" \ -H "Authorization: token $GH_TOKEN" \
@@ -104,7 +149,7 @@ jobs:
if [ -z "$RELEASE_ID" ]; then if [ -z "$RELEASE_ID" ]; then
echo "--- Create release ---" echo "--- Create release ---"
python3 -c "import sys,json; sys.stdout.write(json.dumps({'tag_name': '$TAG', 'name': '$TAG', 'body': 'Release $TAG', 'draft': False, 'prerelease': False}))" \ REL_TAG="$TAG" REL_NOTES_FILE="$NOTES_FILE" python3 -c "import json,os; nf=os.environ.get('REL_NOTES_FILE',''); body=(open(nf,encoding='utf-8').read() if nf and os.path.exists(nf) else 'Release '+os.environ['REL_TAG']); print(json.dumps({'tag_name':os.environ['REL_TAG'],'name':os.environ['REL_TAG'],'body':body,'draft':False,'prerelease':False}))" \
> /tmp/release_payload.json > /tmp/release_payload.json
RELEASE_ID=$(curl -s -X POST "$API/releases" \ RELEASE_ID=$(curl -s -X POST "$API/releases" \
-H "Authorization: token $GH_TOKEN" \ -H "Authorization: token $GH_TOKEN" \
@@ -113,6 +158,17 @@ jobs:
| python3 -c "import sys,json; print(json.load(sys.stdin).get('id','') or '')") | python3 -c "import sys,json; print(json.load(sys.stdin).get('id','') or '')")
else else
echo "--- Reusing existing release $RELEASE_ID ---" echo "--- Reusing existing release $RELEASE_ID ---"
# Refresh the description even on a rerun, so backfills and
# retried asset uploads always match PREVIOUS_HISTORY.md.
if [ "$HAS_NOTES" = "1" ]; then
echo "--- Patching release description from PREVIOUS_HISTORY.md ---"
REL_NOTES_FILE="$NOTES_FILE" python3 -c "import json,os; print(json.dumps({'body': open(os.environ['REL_NOTES_FILE'],encoding='utf-8').read()}))" \
> /tmp/body_patch.json
curl -s -X PATCH "$API/releases/$RELEASE_ID" \
-H "Authorization: token $GH_TOKEN" \
-H "Content-Type: application/json" \
-d @/tmp/body_patch.json > /dev/null
fi
fi fi
echo "Release ID: $RELEASE_ID" echo "Release ID: $RELEASE_ID"
@@ -120,6 +176,37 @@ jobs:
echo "aW1wb3J0IHN5cywganNvbiwgdXJsbGliLnJlcXVlc3QKYXBpID0gc3lzLmFyZ3ZbMV0KcmVsZWFzZV9pZCA9IHN5cy5hcmd2WzJdCmFwayA9IHN5cy5hcmd2WzNdCnRva2VuID0gc3lzLmFyZ3ZbNF0KcmVxID0gdXJsbGliLnJlcXVlc3QuUmVxdWVzdCgKICAgIGYie2FwaX0vcmVsZWFzZXMve3JlbGVhc2VfaWR9L2Fzc2V0cyIsCiAgICBoZWFkZXJzPXsiQXV0aG9yaXphdGlvbiI6IGYidG9rZW4ge3Rva2VufSJ9CikKcmVzcCA9IHVybGxpYi5yZXF1ZXN0LnVybG9wZW4ocmVxKQpmb3IgYSBpbiBqc29uLmxvYWRzKHJlc3AucmVhZCgpKToKICAgIGlmIGFbIm5hbWUiXSA9PSBhcGs6CiAgICAgICAgZGVsZXRlX3JlcSA9IHVybGxpYi5yZXF1ZXN0LlJlcXVlc3QoCiAgICAgICAgICAgIGYie2FwaX0vcmVsZWFzZXMve3JlbGVhc2VfaWR9L2Fzc2V0cy97YVsnaWQnXX0iLAogICAgICAgICAgICBtZXRob2Q9IkRFTEVURSIsCiAgICAgICAgICAgIGhlYWRlcnM9eyJBdXRob3JpemF0aW9uIjogZiJ0b2tlbiB7dG9rZW59In0KICAgICAgICApCiAgICAgICAgdXJsbGliLnJlcXVlc3QudXJsb3BlbihkZWxldGVfcmVxKQogICAgICAgIHByaW50KGYiRGVsZXRlZCB7YVsnaWQnXX0iLCBmbHVzaD1UcnVlKQo=" | base64 -d > /tmp/delete_asset.py echo "aW1wb3J0IHN5cywganNvbiwgdXJsbGliLnJlcXVlc3QKYXBpID0gc3lzLmFyZ3ZbMV0KcmVsZWFzZV9pZCA9IHN5cy5hcmd2WzJdCmFwayA9IHN5cy5hcmd2WzNdCnRva2VuID0gc3lzLmFyZ3ZbNF0KcmVxID0gdXJsbGliLnJlcXVlc3QuUmVxdWVzdCgKICAgIGYie2FwaX0vcmVsZWFzZXMve3JlbGVhc2VfaWR9L2Fzc2V0cyIsCiAgICBoZWFkZXJzPXsiQXV0aG9yaXphdGlvbiI6IGYidG9rZW4ge3Rva2VufSJ9CikKcmVzcCA9IHVybGxpYi5yZXF1ZXN0LnVybG9wZW4ocmVxKQpmb3IgYSBpbiBqc29uLmxvYWRzKHJlc3AucmVhZCgpKToKICAgIGlmIGFbIm5hbWUiXSA9PSBhcGs6CiAgICAgICAgZGVsZXRlX3JlcSA9IHVybGxpYi5yZXF1ZXN0LlJlcXVlc3QoCiAgICAgICAgICAgIGYie2FwaX0vcmVsZWFzZXMve3JlbGVhc2VfaWR9L2Fzc2V0cy97YVsnaWQnXX0iLAogICAgICAgICAgICBtZXRob2Q9IkRFTEVURSIsCiAgICAgICAgICAgIGhlYWRlcnM9eyJBdXRob3JpemF0aW9uIjogZiJ0b2tlbiB7dG9rZW59In0KICAgICAgICApCiAgICAgICAgdXJsbGliLnJlcXVlc3QudXJsb3BlbihkZWxldGVfcmVxKQogICAgICAgIHByaW50KGYiRGVsZXRlZCB7YVsnaWQnXX0iLCBmbHVzaD1UcnVlKQo=" | base64 -d > /tmp/delete_asset.py
# Upload one asset with retries, then verify server-side.
# Cloudflare sits in front of the origin and returns
# "error code: 524" (origin timeout, ~100s) on large/slow
# uploads — the file frequently lands on the origin anyway,
# so success is decided by listing the release's assets
# rather than trusting the upload response body (which may
# be a non-JSON Cloudflare error page).
upload_asset() {
local apk_name="$1" apk_path="$2"
local attempt
for attempt in 1 2 3 4 5; do
echo "--- Uploading $apk_name (attempt $attempt/5) ---"
ls -la "$apk_path"
UPLOAD=$(curl -s -f -X POST "$API/releases/$RELEASE_ID/assets?name=$apk_name" \
-H "Authorization: token $GH_TOKEN" \
-F "attachment=@$apk_path" \
--max-time 600 --retry 2 --retry-all-errors --retry-delay 15 || true)
echo "Upload response: ${UPLOAD:0:200}"
if curl -s "$API/releases/$RELEASE_ID" \
-H "Authorization: token $GH_TOKEN" \
| python3 -c "import sys,json; d=json.load(sys.stdin); sys.exit(0 if any(a['name']=='$apk_name' for a in d['assets']) else 1)"; then
echo "Verified: $apk_name is attached to the release."
return 0
fi
echo "Asset not on the server yet — retrying in 15s..."
sleep 15
done
echo "ERROR: $apk_name failed to attach after 5 attempts."
return 1
}
for APK in "$APK_DEBUG" "$APK_RELEASE"; do for APK in "$APK_DEBUG" "$APK_RELEASE"; do
if echo "$APK" | grep -q "debug"; then if echo "$APK" | grep -q "debug"; then
APK_PATH="app/build/outputs/apk/debug/app-debug.apk" APK_PATH="app/build/outputs/apk/debug/app-debug.apk"
@@ -134,15 +221,21 @@ jobs:
echo "--- Deleting stale assets for $APK ---" echo "--- Deleting stale assets for $APK ---"
python3 /tmp/delete_asset.py "$API" "$RELEASE_ID" "$APK" "$GH_TOKEN" python3 /tmp/delete_asset.py "$API" "$RELEASE_ID" "$APK" "$GH_TOKEN"
echo "--- Uploading $APK ---" upload_asset "$APK" "$APK_PATH" || exit 1
ls -la "$APK_PATH"
UPLOAD=$(curl -s -X POST "$API/releases/$RELEASE_ID/assets?name=$APK" \
-H "Authorization: token $GH_TOKEN" \
-F "attachment=@$APK_PATH" \
--max-time 600 --retry 3 --retry-delay 10)
echo "Upload response: $UPLOAD"
echo "$UPLOAD" | python3 -c "import sys,json; d=json.loads(sys.stdin.read()); print('Asset uploaded:', d.get('name','?'), d.get('id','?'))"
done done
# Ship the changelog beside the binaries: people skimming the
# downloads get the notes for exactly this version as a file,
# generated from PREVIOUS_HISTORY.md at the top of this run.
if [ "$HAS_NOTES" = "1" ]; then
NOTES_ASSET="Incido-$VERSION-changes.md"
echo "--- Deleting stale asset for $NOTES_ASSET ---"
python3 /tmp/delete_asset.py "$API" "$RELEASE_ID" "$NOTES_ASSET" "$GH_TOKEN"
# Upload $NOTES_FILE directly: it already IS /tmp/<asset name>, so
# copying it onto itself made cp fail with exit 1 and killed the
# whole step (set -e) after the APKs had uploaded fine.
upload_asset "$NOTES_ASSET" "$NOTES_FILE" || exit 1
fi
echo "--- Final release state ---" echo "--- Final release state ---"
curl -s "$API/releases/$RELEASE_ID" -H "Authorization: token $GH_TOKEN" | python3 -c "import sys,json; d=json.load(sys.stdin); print('Release ' + d['tag_name'] + ' has ' + str(len(d['assets'])) + ' assets')" curl -s "$API/releases/$RELEASE_ID" -H "Authorization: token $GH_TOKEN" | python3 -c "import sys,json; d=json.load(sys.stdin); print('Release ' + d['tag_name'] + ' has ' + str(len(d['assets'])) + ' assets')"
+1
View File
@@ -38,3 +38,4 @@ Thumbs.db
# Built APKs at the repo root (stamped with version — see Incido # Built APKs at the repo root (stamped with version — see Incido
# Development Plan §11 for the release build procedure). # Development Plan §11 for the release build procedure).
incido-*.apk incido-*.apk
Incido-*.apk
+14 -3
View File
@@ -63,8 +63,19 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
or your feature's manual verification steps. or your feature's manual verification steps.
### 5. Commit ### 5. Commit
We use [Conventional Commits](https://www.conventionalcommits.org/) so We use [Conventional Commits](https://www.conventionalcommits.org/).
the changelog can be generated automatically later: Per-version user-facing notes live in `PREVIOUS_HISTORY.md`
(Development Plan §11.1) — the release CI attaches the matching section
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. **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:
| Type | Use for | | Type | Use for |
|------|---------| |------|---------|
@@ -142,7 +153,7 @@ under GPL-3.0 before opening the PR.
> fails immediately — there's a validator in `app/build.gradle.kts`. > fails immediately — there's a validator in `app/build.gradle.kts`.
1. Bump `versionCode` (+1) and `versionName` 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"`. 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. 4. `./gradlew assembleDebug assembleRelease` — confirm both green.
5. Upload `app/build/outputs/apk/release/app-release.apk` to Gitea Releases. 5. Upload `app/build/outputs/apk/release/app-release.apk` to Gitea Releases.
+61 -3
View File
@@ -370,6 +370,13 @@ A short reference for AI assistants:
| Version | Date | Notes | | 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:<NAME>` 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). |
| 0.3.8.1 | 2026-09-17 | **Emergency hotfix — rebuild / re-release of v0.3.8.0. Zero app-code changes; release-pipeline fix only.** **1. Why.** The release job had been failing to publish reliably. `.gitea/workflows/release.yml` now addresses the Gitea API as `http://192.168.8.17:3000/api/v1/repos/nick/incido` (LAN, direct) instead of the Cloudflare-fronted `https://git.trevena.info/...`, which was the source of the mid-upload 524 origin timeouts that 4a28f4f could only retry around. **2. Signing key rotated — INSTALLED BUILDS CANNOT UPDATE IN PLACE.** The job ran on a runner whose `/var/lib/gitea-runner/work` cache held no `release.jks`, so the mint-if-absent branch (release.yml) generated a NEW certificate; Android rejects an APK whose signing cert differs from the installed one, so v0.3.8.1 must be uninstalled before it will install. Because `allowBackup="false"` (AndroidManifest) keeps notes out of Android's cloud/D2D restore, an uninstall DESTROYS the user's notes — so the release notes lead with "export a backup first" (Settings → Backup → Export, plus Settings → Security → Export encryption key when encryption is on), then uninstall → install → restore. **Follow-up worth doing:** copy the original `release.jks` onto the runner at `/var/lib/gitea-runner/work/release.jks` to restore in-place upgrades and stop the rotation; until then every release repeats this. **3. Lockstep (§11.1).** versionCode 33→34, versionName "0.3.8.0"→"0.3.8.1", SettingsViewModel.APP_VERSION bumped, README current-release line + reinstall warning, PREVIOUS_HISTORY.md section (feeds the release description + `Incido-0.3.8.1-changes.md` asset), and the in-app What's New dialog (ReleaseNotes.RECENT — v0.3.5.1 drops off the 5-entry tail). |
| 0.3.8.0 | 2026-09-16 | **Feature release — task lists, shopping lists, hashtag-autocomplete fix** (closes §6.1 "Checklists / to-do items within notes" + "Grocery list with running price total"). **1. Note types.** New `NoteType` enum in `:core/domain` (TEXT / TASK_LIST / SHOPPING_LIST) carried by `Note.type` and an additive `NoteEntity.typeKey` Short column (ObjectBox auto-migrates; old rows = TEXT). List bodies persist as GitHub-flavoured `- [ ] item` lines (`Note.splitListContent` / `serializeListContent`), so content stays the single source of truth: full-text search, AES-GCM field encryption, share-into, the v0.2 inline checklist card summaries, and Trash all keep working untouched. **2. Task-list editor.** Checklist button next to the # tag button in the editor's bottom action row converts the note into editable rows (Checkbox + item text + remove, "+ Add item", first non-checkbox line kept as the title field); tapping the active button reverts to plain text. Active mode tints primary. Cards already showed "- [ ]" open/done counts; shopping cards now show a basket icon instead of the checkbox glyph. **3. Shopping list + running total.** Same mechanism with two structured fields per row: a read-only **quantity picker (1–9)** (`ExposedDropdownMenuBox` — no keyboard ever opens) and a **POS-style price field** (`KeyboardType.Number`; every digit typed is a cent — the field stores the RAW digits verbatim (e.g. `199` = $1.99) so mid-field cursor placement behaves like a normal text field and can never scramble the amount, with a non-editable `$` prefix; the total bar renders dollars). A sticky `ShoppingTotalBar` stays pinned above the rows — always visible, updated live — summing `qty × price` of CHECKED (= in-basket) items in **integer cents** (no binary-float drift). Storage puts both values in an explicit end-of-line marker `- [x] Eggs {q12 p2.40}`, so the PRODUCT TEXT IS NEVER SCANNED FOR NUMBERS ("Battery AA 3", "Poster 50 x 60" stay pure product names); hand-typed §6.1 shapes (`Milk 3.50`, `Eggs 12 x 2.40`) still import once into the structured fields on conversion (decimals required on the legacy forms to avoid exactly that ambiguity). Converting to a task list folds values back into plain text tokens (`Eggs 12 x 2.40`) so nothing is lost across mode switches. **4. Add-tag suggestions repaired.** The autocomplete collector in `NoteEditorViewModel.init` was `tagInputFlow.collect { pool.collect { … } }` over infinite ObjectBox callbackFlows — the outer lambda suspended in the inner collect forever, keystrokes never re-queried, and `openAddTagSheet()` zeroed the list, so the sheet only ever offered "+ Create". Rebuilt on `flatMapLatest` over `tagInputFlow` (sheet opens showing every existing tag most-used-first, filters live per keystroke). **5. Backups** round-trip the new type via defaulted `BackupNote.noteType` ("TEXT") — pre-v0.3.8.0 files import unchanged, `ignoreUnknownKeys` covers older readers; encrypted backups reuse the same shape. ViewModel: `isDirty` gains the type axis; list edits keep `content` synchronised with the row serialisation so save/preview/canSave gates need no changes. versionCode 32→33, versionName "0.3.7.1"→"0.3.8.0", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.7.1 | 2026-08-30 | **Maintenance release — UI polish + one bug fix.** **1. Editor top bar decluttered.** The Add/Edit `TopAppBar` carried six right-side actions (camera, attach, tag, favourite, save, overflow), which crowded the title on narrow screens. Camera / Attach file / Add tag move to a Keep-style bottom action row (hairline `HorizontalDivider` above it; rides above the nav bar / keyboard via the existing IME insets). The top bar is now back + "New note" / "Edit note" title (`maxLines = 1`, ellipsis) + favourite + save + overflow (Move to Trash when editing) — always fits, and matches the §5.2 spec. **2. Image-viewer false failure fixed.** `ImageViewerScreen` checked `bitmap == null` in a `LaunchedEffect` before the async load finished, so a "Couldn't decode image attachment" toast fired on every persisted image open. Replaced with a `loadFailed` state set only after the byte load / decode genuinely fails; the placeholder switches from "Loading…" to "Couldn't load image" (toast removed). **3. Search QoL.** The list search field auto-focuses on open (`FocusRequester` + `LaunchedEffect(state.isSearchActive)`) and gains a trailing clear (✕) button while the query is non-empty. **4. Drawer tag-list overflow fixed.** The scrollable "Recent tags" column in `IncidoDrawer` had no height cap, so long tag lists could overflow the sheet bottom; it now takes `weight(1f)` and scrolls within the remaining height. Dead `_ignored` workaround val removed. **5. Add-tag sheet autofocus.** The sheet's input field is focused on open so the keyboard is already up. Also small hygiene: unused `persistedBytes` param dropped from `AttachmentStrip`; fully-qualified `Spacer` / `Image` / `Column` / `Dispatchers` references replaced with imports. **6. New flat app icon.** `incido_flat_icon.png` (1024×1024, squircle + shield + pen nib, transparent corners) replaces the v0.3.3.8 artwork: LANCZOS-downscaled into `drawable-{mdpi…xxxhdpi}/ic_launcher_foreground.png` (108/162/216/324/432 px, full 108dp canvas — the artwork's fill colour matches the background layer so the squircle edges blend seamlessly) and legacy `mipmap-{mdpi…xxxhdpi}/ic_launcher{,_round}.png` (48/72/96/144/192 px); `ic_launcher_background` re-tinted `#010435` → `#352999`. versionCode 31→32, versionName "0.3.7.0"→"0.3.7.1", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.7.0 | 2026-08-20 | **Feature release — Trash / soft delete.** Deleting a note (long-press card → ⋮ menu → Delete, or the editor's delete action) now soft-deletes it instead of destroying it: the note is flagged as trashed and hidden from Home, Favorites, Untagged, tag views, and ordinary search. A new **Trash** entry in the nav drawer lists only soft-deleted notes; each Trash card's overflow menu exposes **Restore** (returns the note to its previous views) and **Delete permanently** (destroys the row + attachments for good). `NoteEntity` gains a `trashed` flag (additive schema, auto-migrated); `NoteFilter` gains a `Trash` case; the repository gains `moveToTrash` / `restoreFromTrash` / `deletePermanently`; the drawer, list, and editor ViewModels + screens wire the new actions. Backups round-trip the trashed state. No automatic purge window yet — permanent deletion is immediate (see §6.1 "Trash status" note). versionCode 30→31, versionName "0.3.6.3"→"0.3.7.0", SettingsViewModel.APP_VERSION bumped in lockstep. | | 0.3.7.0 | 2026-08-20 | **Feature release — Trash / soft delete.** Deleting a note (long-press card → ⋮ menu → Delete, or the editor's delete action) now soft-deletes it instead of destroying it: the note is flagged as trashed and hidden from Home, Favorites, Untagged, tag views, and ordinary search. A new **Trash** entry in the nav drawer lists only soft-deleted notes; each Trash card's overflow menu exposes **Restore** (returns the note to its previous views) and **Delete permanently** (destroys the row + attachments for good). `NoteEntity` gains a `trashed` flag (additive schema, auto-migrated); `NoteFilter` gains a `Trash` case; the repository gains `moveToTrash` / `restoreFromTrash` / `deletePermanently`; the drawer, list, and editor ViewModels + screens wire the new actions. Backups round-trip the trashed state. No automatic purge window yet — permanent deletion is immediate (see §6.1 "Trash status" note). versionCode 30→31, versionName "0.3.6.3"→"0.3.7.0", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.6.3 | 2026-08-20 | **Emergency hotfix — actionable missing-keystore failure.** On a fresh clone, `./gradlew assembleRelease` previously died late inside `packageRelease` with the cryptic `SigningConfig "release" is missing required property "storeFile"`. It now fails with a clear `GradleException` quoting the exact `keytool` command from `keystore/README.md` to generate `keystore/release.jks`, implemented as a `validateReleaseKeystore` task whose existence check runs in `doFirst` (so `assembleDebug` still works without a keystore). CI unaffected — `.gitea/workflows/release.yml` mints the dev keystore on release runners before `assembleRelease`. No app/Compose code changes. versionCode 29→30, versionName "0.3.6.2"→"0.3.6.3", SettingsViewModel.APP_VERSION bumped in lockstep. | | 0.3.6.3 | 2026-08-20 | **Emergency hotfix — actionable missing-keystore failure.** On a fresh clone, `./gradlew assembleRelease` previously died late inside `packageRelease` with the cryptic `SigningConfig "release" is missing required property "storeFile"`. It now fails with a clear `GradleException` quoting the exact `keytool` command from `keystore/README.md` to generate `keystore/release.jks`, implemented as a `validateReleaseKeystore` task whose existence check runs in `doFirst` (so `assembleDebug` still works without a keystore). CI unaffected — `.gitea/workflows/release.yml` mints the dev keystore on release runners before `assembleRelease`. No app/Compose code changes. versionCode 29→30, versionName "0.3.6.2"→"0.3.6.3", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.6.2 | 2026-08-19 | **CI / release-pipeline tag.** v0.3.6.2 is a re-tag of the v0.3.6.1 commit used to exercise the Gitea Actions release workflow (minting the dev keystore on the release runner and attaching the version-stamped debug + release APKs to the Gitea release). No app code or version-string changes landed under this tag — the tagged commit still reads versionName "0.3.6.1" / versionCode 28. | | 0.3.6.2 | 2026-08-19 | **CI / release-pipeline tag.** v0.3.6.2 is a re-tag of the v0.3.6.1 commit used to exercise the Gitea Actions release workflow (minting the dev keystore on the release runner and attaching the version-stamped debug + release APKs to the Gitea release). No app code or version-string changes landed under this tag — the tagged commit still reads versionName "0.3.6.1" / versionCode 28. |
@@ -429,9 +436,27 @@ A small Gradle task called `copyReleaseApks` (registered in
Settings displays the new version and the in-app release-notes Settings displays the new version and the in-app release-notes
dialog recognises it. dialog recognises it.
3. **`README.md`** — bump the intro paragraph and "Current release" 3. **`README.md`** — bump the intro paragraph and "Current release"
line, and add a new row at the top of the Changelog table (the table line. **`PREVIOUS_HISTORY.md`** — append a new
is the user-facing changelog — §10 keeps the historical release `## v<NEW_VERSION> — <DATE>` section at the top: friendly user-facing
notes). bullets, newest first (this file replaced the old README Changelog
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-<version>-changes.md` asset, so a manual line
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-<version>-changes.md`
asset beside the APKs — so keep one section per released version and
never reorder or delete old ones (§10 stays the developer-facing
history). For pre-existing releases created before this pipeline,
`scripts/ci/backfill-release-notes.sh` patches them retroactively.
### 11.2 Build both APKs (and stamp them) ### 11.2 Build both APKs (and stamp them)
@@ -512,6 +537,39 @@ adb install -r incido-<versionName>-debug.apk
have to type it — `./gradlew assembleRelease` has already deposited have to type it — `./gradlew assembleRelease` has already deposited
both stamped APKs at the repo root by the time you reach it.) both stamped APKs at the repo root by the time you reach it.)
### 11.5 Re-running a failed release
**Never "Re-run" a red release run.** A tag push pins the workflow file to
that tag's own commit, so a re-run replays the workflow as it was when the
tag was cut — even after `main` has been fixed. It is also destructive: the
release step deletes each stale asset before re-uploading it, so a retry that
dies mid-step leaves the release with *fewer* assets than it started with.
(This is exactly what happened to v0.3.8.1 run 78, twice, over a `cp` bug
already patched on `main`.)
Instead, dispatch the workflow from `main`, which runs `main`'s current
workflow against an existing tag:
```bash
# Gitea: POST .../actions/workflows/release.yml/dispatches (expect 204)
curl -s -X POST \
-H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
-d '{"ref":"main","inputs":{"tag":"v0.3.8.1"}}' \
http://192.168.8.17:3000/api/v1/repos/nick/incido/actions/workflows/release.yml/dispatches
```
Equivalently: Actions → "release" → Run workflow → branch `main` → tag input.
The job reuses the existing release entry, refreshes its description, and
re-attaches both APKs and `Incido-<version>-changes.md`.
Two API gotchas found the hard way: a run's **task id is not its run number**
(`GET /actions/runs/<n>/logs` 404s; logs live at
`GET /actions/jobs/<task-id>/logs`), and job logs echo the whole script before
executing it, so grep below the last `::endgroup::` to see real output.
If CI cannot attach the changelog file at all, `scripts/ci/backfill-release-notes.sh <version>`
patches description + notes asset after the fact (idempotent, never touches the APKs).
--- ---
## Appendix A — Key Library Versions (for the version catalog) ## Appendix A — Key Library Versions (for the version catalog)
+205
View File
@@ -0,0 +1,205 @@
# Incido — Previous Release History
Reference archive of Incido's user-facing release history (formerly the README changelog table).
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-<version>-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<VERSION> — <DATE>` 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 <tag>" 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.
- **Saved notes stay put.** In v0.4.1.0 every note you saved ended up in Drafts instead of Home — the editor still believed the note was a draft and quietly re-saved it as one when you left the screen. Saving now publishes the note properly: it goes to Home and leaves Drafts for good.
- **Enter behaves in the price box.** In a shopping list, pressing Enter in a row's Price field jumped the cursor all the way back to the note title. It now works exactly like Enter in the product field: a fresh item row appears below, with the cursor ready in its Product box.
## v0.4.1.0 — 2026-09-23
New in this release: **colour filters**, **auto-saved drafts** and an **Empty Trash** button — plus a steadier editor.
- **Colour filters in the drawer.** A horizontal strip of five swatches — Blue, Green, Amber, Red and Purple — sits right under Favorites. Tap a swatch and the list shows ONLY your notes in that colour: untagged colour notes appear, tagged ones appear too, and a trashed note of that colour is never shown — the filter follows the same rules as Favorites and Untagged. Tap the selected swatch again to return to Home.
- Search works inside colour views as well: whatever you type narrows the selected colour's notes, exactly like search does on Favorites.
- **Auto-saved drafts.** A brand-new note now saves itself as a draft while you type — no save button needed, no lost work. If you back out or close the app before finishing, the note waits in the new Drafts row in the navigation drawer; open it again and you are exactly where you left off.
- A draft never gets in your way: it stays out of Home, Favorites, tag views and search until you save the note, and an untitled draft introduces itself by its kind — "Task List — (draft)", "Shopping List — (draft)" — on its card and in the editor's title bar. Drafts ride along in encrypted backups, so a restore brings them back too.
- **Empty Trash.** The Trash view gains an Empty Trash button whenever it holds notes. One tap — confirmed by a dialog first — permanently deletes every trashed note, attachments included.
- **Steadier editor rows.** The to-do and shopping-list editors now render title, item and quantity fields at one even, underlined row height, so rows sit evenly instead of the tall/short mix before. Long task labels wrap inside their row instead of stretching it, and the checkbox, delete and +/- controls stay centred alongside however many lines the label takes.
## v0.4.0.0 — 2026-09-18
New in this release: **Import 3rd Party Notes**. Settings → Backup & Restore now has an "Import 3rd Party Notes" button that ingests a Carnet / QuickNote `.zip` export — a single archive bundling one `.sqd` per note — straight on-device, with no pre-conversion step. Rich-text bodies are flattened to plain text; note colours, keywords (imported as tags) and links carry over; to-do lists become native checklists; and image attachments are imported (auto-generated preview thumbnails are skipped). Import is additive — existing notes are preserved and imported notes get fresh IDs.
## v0.3.8.1 — 2026-09-17
> **⚠️ Reinstall required — please export a backup first.** This build is signed with a **new CI signing key** (the previous key lived in the old build runner's cache and was not carried over), so Android will refuse to install it over an existing Incido — it reports a signature conflict. Incido deliberately doesn't participate in Android's automatic backup/restore, so **uninstalling deletes your notes**. To update safely: **Settings → Backup → Export** (and **Settings → Security → Export encryption key** if you use encryption), then uninstall Incido, install this APK, and restore from your backup. If you'd rather keep using v0.3.8.0, that's fine — nothing in it is broken.
- **No app changes.** v0.3.8.1 is a re-release of v0.3.8.0: same task lists, shopping lists with the running total, and add-tag suggestions fix. Only the build number and the release pipeline changed.
- **Why the rebuild.** The release pipeline had been failing to publish builds reliably. Release uploads now go to the Gitea API over the local network instead of the proxied public address, which is where the upload timeouts were coming from — so this is the first build in a while to ship with its APKs and notes attached the way §11.1 intends.
## v0.3.8.0 — 2026-09-16
- **Task lists + shopping lists (Development Plan §6.1).** New checklist button in the editor's bottom action row (next to the `#` tag button) converts any note into an editable task list — real checkboxes, add / remove item rows; tap the button again to return to plain text (`NoteType`, additive `typeKey` column, auto-migrated). New shopping-basket button works the same way but gives every row a tap-to-pick **quantity (1–9) dropdown** and a supermarket-style price field where the number pad types cents — enter `199` and it counts as **$1.99** in the maths (the price box keeps exactly the digits you typed, so cursor placement can never scramble them, while the total bar speaks real dollars). An always-visible running total sits above the list, adding quantity × price for everything checked (= in the basket). The three values are strictly separate fields saved with an explicit end-of-line marker (`- [x] Eggs {q12 p2.40}`), so numbers inside a product name (like "Battery AA 3") can never leak into the money maths; hand-typed classic lines (`Milk 3.50`, `Eggs 12 x 2.40`) are still recognised when converting older notes. Lists persist as GitHub-flavoured `- [ ]` lines, so search, encryption, backups (new defaulted `noteType` field — old files still import), and card "N open · M done" summaries keep working; shopping cards show a basket icon.
- **Add-tag sheet suggestions fixed.** The nested-collect autocomplete pipeline never resumed past the first keystroke, so only "+ Create…" ever showed; rebuilt on `flatMapLatest`, existing tags now list immediately when the sheet opens and filter live per keystroke.
## v0.3.7.1 — 2026-08-30
- **UI polish.** Add/Edit screen tidied up: camera, attach-file, and add-tag moved out of the top bar into a bottom action row, so the title and remaining buttons always fit. Fixed a false "couldn't load image" error that flashed whenever you opened a saved image. Search auto-focuses on open and shows a clear (✕) button. Long tag lists in the drawer now scroll instead of being cut off. The add-tag sheet opens with the keyboard ready. New flat app icon (same shield + pen-nib motif, cleaner squircle design).
## v0.3.7.0 — 2026-08-20
- **Trash / soft delete.** Add a Trash drawer item; deleting a note soft-deletes it, hiding it from every active view and ordinary search. Trash-only cards expose Restore and permanent Delete.
## v0.3.6.3 — 2026-08-20
- **Missing-keystore failure is now actionable on a fresh clone.** `./gradlew assembleRelease` now fails at configuration time with a clear `GradleException` quoting the exact `keytool` command from `keystore/README.md` if `keystore/release.jks` is missing, instead of dying much later inside `packageRelease` with the cryptic `SigningConfig "release" is missing required property "storeFile"`. CI is unchanged: `.gitea/workflows/release.yml` already mints the dev keystore on the runner before `assembleRelease`.
## v0.3.6.2 — 2026-08-19
- **CI / release-pipeline tag.** Re-tag of v0.3.6.1 used to exercise the Gitea Actions release workflow (keystore minted on the release runner; debug + release APKs attached to the Gitea release). No app changes.
## v0.3.6.1 — 2026-08-19
- **Editor top-bar title is now left-aligned.** On the New / Edit screen the title ("New" / "Edit") now sits next to the back arrow, away from the six action icons that crowd the right edge — it was previously centred via `CenterAlignedTopAppBar` and visually pushed toward the action cluster.
- **Colour picker is now symmetric between the title bar and the note top.** The picker is flanked by 12dp gaps above and below (was 4dp top + 4dp bottom) so the visual distance to the title bar matches the distance to the `OutlinedTextField`'s top edge, instead of being dwarfed by the field's intrinsic top inset.
## v0.3.6.0 — 2026-08-19
- **Share webpages to Incido.** Sharing a page from your browser (Share → Incido) now creates a note with the page title on the first line and the URL below — fully offline (the title comes from the browser's share data, Incido never touches the network).
- **Export encryption key.** Settings → Security gains "Export encryption key" — saves the AES-256 key that protects your encrypted notes to a passphrase-protected `.inckey` file for device migrations.
- **Import encryption key** restores that key on a fresh install, with a clear warning before the current key is replaced.
## v0.3.5.1 — 2026-08-17
- **"Encrypted" badge now appears the moment you flip the switch.** A race in `EncryptionVerifier.checkNow()` could silently drop the post-migration verification, leaving cards without the badge until a second toggle; replaced with a serializing Mutex so every check runs in invocation order.
- **"Encrypted" indicator is now a single lock icon next to the date.** Consistent position on every card instead of a centred "lock + label" group at the bottom.
## v0.3.5.0 — 2026-08-17
- **Real at-rest encryption.** Note text and attachment bytes are now AES-256-GCM encrypted in place the moment you toggle "Encrypt notes at rest" — no restart required; keyed by the Keystore-wrapped 32-byte key.
- **Verified "Encrypted" badge.** Every encrypted note is trial-decrypted on app open and after each migration; only verified notes get the lock badge.
- **Block screenshots (default ON).** New toggle in Settings → Security prevents screenshots, screen recording, and app-switcher previews while Incido is open.
## v0.3.4.0 — 2026-08-17
- **Attachment indicator on note cards.** A paperclip icon now appears on the right edge of every card that carries an attachment.
- **Light-theme readability over image thumbnails.** Cards with a dark photo background now force light text/icon colours over the image so notes stay readable in Light mode.
- **Auto-Lock "Immediately" no longer locks during file pickers.** Attaching a file, taking a photo, viewing an attachment, or exporting/importing a backup no longer destroys your in-progress note.
## v0.3.3.8 — 2026-08-17
- **Designed Incido artwork is now the app icon.** The glass shield + fountain-pen nib replaces the placeholder glyph on the home screen, app drawer, and adaptive-icon layers.
## v0.3.3.7 — 2026-08-17
- **Biometric auto-launch.** When Biometric is your active lock method, the fingerprint / face reader now opens automatically when the lock screen appears — no extra tap on "Authenticate" needed.
## v0.3.3.6 — 2026-08-17
- **Card height tuned for real devices.** The fixed card height from v0.3.3.5 proved too tall on real devices; reduced by ~15% (now 143.dp).
## v0.3.3.5 — 2026-08-17
- **Fixed card height.** All note cards now have a single fixed height (168.dp), so untagged notes no longer look shorter than tagged ones; timestamp pinned to the bottom via a weighted spacer; hashtag row still hidden when empty; left colour stripe spans the full card height.
## v0.3.3.4 — 2026-08-17
- **Favourite star no longer overlaps the overflow button.** Star is now anchored to the card's bottom-right corner (same column as the top-right ⋮), so the two controls no longer collide.
## v0.3.3.3 — 2026-08-17
- **Importing an encrypted backup no longer crashes.** The passphrase was being wiped between the preview step and the confirm dialog's Import button; now retained across the confirmation step, with proper try/catch around preview/import so failures surface a snackbar ("Import failed. Check the file and passphrase." / "Could not read backup file.") instead of crashing.
## v0.3.3.2 — 2026-08-17
- **White-on-white lock screen in dark mode fixed.** `PinEntryScreen` is now wrapped in a themed Surface so it always paints its own theme-aware background.
- **Biometric unlock hang fixed.** Authentication is now fully asynchronous (BiometricPrompt callbacks run on the main executor) instead of busy-waiting on the main thread. Device-credential fallback preserved.
## v0.3.3.1 — 2026-08-17
- **"Encrypt notes at rest" toggle now correctly greyed out.** Until Security is on and you've chosen either PIN or Biometric — with a subtitle explaining the requirement.
- **"Enable Security" no longer requires a PIN first.** The master switch just flips on; PIN / Biometric / Encrypt sub-toggles were already gated.
- **Importing an encrypted backup now opens a dedicated passphrase dialog.** (single field, no policy check) — wrong passphrase surfaces "Incorrect passphrase." via snackbar.
## v0.3.3.0 — 2026-08-17
- **Lock mode as a single choice.** Security now exposes two mutually-exclusive toggles (PIN and Biometric) — either alone is enough to lock; Biometric no longer requires PIN first. New "Reset PIN" row appears when PIN is active; lock screen shows only the biometric button when no Incido PIN is set.
- **Encrypted-import passphrase prompt.** Selecting an encrypted backup opens the passphrase dialog first and surfaces "Incorrect passphrase." on mismatch.
- **Press-and-hold note card menu.** The inline delete button is gone; long-press a card (or tap the ⋮ button) to open a DropdownMenu with Delete — ready for future actions like Share.
## v0.3.2.0 — 2026-08-15
- **New Settings screen.** (Untagged → Settings in the nav drawer) with Appearance, Security, Backup & Restore, and About sections.
- **At-rest encryption.** ObjectBox store is 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.** 4–6 digit PIN (PBKDF2-hashed, 100k iters, constant-time compare) with optional fingerprint / face unlock; cold launch + auto-lock timeout gate.
- **Backup / Import / Export.** JSON codec with Base64 attachment bytes; encrypted variant uses AES-256-GCM + PBKDF2(passphrase, 200k iters) with a Generate button + Copy to clipboard. Passphrase policy: 12–32 chars, ≥1 digit, ≥1 special.
- **Release notes dialog.** Tap the version number on the About card. Adds `USE_BIOMETRIC` + `USE_FINGERPRINT` permissions (still no INTERNET).
## v0.3.1.2 — 2026-08-15
- **Three v0.3.1.1 issues fixed.** **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 `<cache-path>`, 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.
## v0.3.1.1 — 2026-08-15
- **Five v0.3.1.0 issues fixed.** 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 `<data android:mimeType="*/*" />` 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.
## v0.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.
## v0.3.0.5 — 2026-08-15
- **Hashtag reconciliation is now a single transaction.** `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.
## v0.3.0.4 — 2026-08-14
- **Recent Tags now subscribes to all three boxes.** `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.
## v0.3.0.3 — 2026-08-14
- **Batched hashtag-usage lookups.** `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.
## v0.3.0.2 — 2026-08-14
- **AddTagSheet placeholder cleaned up.** Dropped the redundant leading `#` from the AddTagSheet placeholder (was `#tag-name`, now `hashtag-name` — the leading `#` icon in the field already signals the format).
## v0.3.0.1 — 2026-08-14
- **Editor + list-card 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).
## v0.3.0.0 — 2026-08-14
- **Hashtags + bolder colour accent + nav drawer + new version scheme.** Hashtags (visible chips on editor, 5-tag cap, autocomplete) + bolder colour accent + nav drawer (Home / Favorites / Untagged + recent tags) + centred app-bar title + new version scheme
## v0.2.0.1 — 2026-08-14
- **Search icon now opens the search bar.** Search icon now actually opens the search bar
## v0.2.0.0 — 2026-08-14
- **Polish + favourites, search, colours, checklists, discard dialog, release signing.**
## v0.1.1.0 — 2026-08-14
- **Editor IME fix + title/body on list cards.**
## v0.1.0.0 — 2026-08-14
- **First MVP: list + editor, ObjectBox, Material 3.**
+49 -114
View File
@@ -6,17 +6,41 @@ 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 All data stays on your device by default — no accounts, no cloud, no
trackers. trackers.
This repository contains the **v0.3.7.0** release: a single-user, offline This repository contains the **v0.4.2.0** release: a single-user, offline
note app with hashtags, favourites, full-text search, colour-coded note app with hashtags, favourites, task lists, shopping lists with a
notes, photo and file attachments, share-into from other apps and the running total, voice notes with an in-app media player and downloadable
web, Trash (soft delete with Restore / permanent delete), at-rest 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
Restore / permanent delete / one-tap Empty Trash), at-rest
AES-256-GCM encryption with screenshot blocking, PIN / biometric lock, AES-256-GCM encryption with screenshot blocking, PIN / biometric lock,
encrypted backup and restore, and an exportable encryption key for encrypted backup and restore, and an exportable encryption key for
device migrations. The architecture is multi-module Android today and device migrations. The architecture is multi-module Android today and is
is structured so iOS / Desktop ports can happen later without UI structured so iOS / Desktop ports can happen later without UI rewrites.
rewrites.
**Current release:** v0.3.7.0 (see [Changelog](#changelog) below). **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
> first** (and your encryption key from Settings → Security if you use
> encryption), then uninstall and install fresh — Incido doesn't use Android's
> automatic backup, so uninstalling deletes your notes. **Upgrading from
> v0.3.8.1 onwards is a normal in-place update.**
> **Version scheme (from v0.3.0.0 onwards):** `MAJOR.MINOR.MAINTENANCE.EMERGENCY` — > **Version scheme (from v0.3.0.0 onwards):** `MAJOR.MINOR.MAINTENANCE.EMERGENCY` —
> e.g. `0.3.0.0`. `MAJOR.MINOR.MAINTENANCE` are normal release numbers; > e.g. `0.3.0.0`. `MAJOR.MINOR.MAINTENANCE` are normal release numbers;
@@ -27,78 +51,6 @@ rewrites.
--- ---
## Features
### v0.3.0.0 highlights
- **Hashtags.** Tag any note with up to 5 hashtags. Tags are always
visible as chips above the editor text field; tap ✕ to remove. Tap
`#` (or `+ add`) to open a sheet with autocomplete suggestions from
your existing tags. Hashtags are searchable from the list (typing
`work` finds notes containing the word *and* notes tagged `#work`).
- **Bolder colour accent on list cards.** Each colour-tagged note now
gets a 14 dp vertical gradient stripe on the left, a subtle 12 %
tinted card background, and a 10 dp solid colour chip in the
top-right — so different-coloured notes are visually distinct at a
glance without you needing to focus on the stripe.
- **Navigation drawer.** Hamburger top-left opens a drawer with
**Home**, **Favorites**, **Untagged**, **Trash**, a divider, then a live
scrollable list of the most-recently-used hashtags. Tap any entry to
filter the list to just those notes.
- **Trash / soft delete.** Deleting a note moves it out of Home, Favorites,
Untagged, tag views, and ordinary search. The Trash view contains only
soft-deleted notes; its overflow menu can restore a note, while permanent
deletion destroys its row and attachments.
- **Centred app-bar title.** Both the list screen (`Incido`) and the
editor (`Edit note` / `New note`) now centre their titles via
Material 3's `CenterAlignedTopAppBar`.
- **New version scheme.** All version bumps from now on follow the
`MAJOR.MINOR.MAINTENANCE.EMERGENCY` pattern; the build refuses anything
that doesn't match.
### v0.2.0.0
- **Favourites.** Tap the star icon on any card to pin it to the top of
the list.
- **Full-text search.** Tap the search icon in the top app bar; the list
filters live as you type.
- **Color-coded notes.** Pick from six preset accent colours in the
editor; each list card gets a 4 dp vertical stripe.
- **Inline checklists.** Lines beginning with `- [ ]` or `- [x]` show
open/done counts on the card preview.
- **Discard-confirm dialog.** Closing the editor with unsaved changes
prompts `Discard changes?` (works for both Back arrow and hardware
back gesture).
- **Release signing** — dev keystore in `keystore/`, `assembleRelease`
produces a v2-signed APK out of the box.
### v0.2.0.1 (hotfix)
- **Search icon actually opens the search bar.** v0.2.0.0's
search-active flag was on a separate `StateFlow` the composable never
observed; folded into `uiState` so tapping the icon now lights up the
field.
### v0.1.1.0
- **Editor respects the soft keyboard.** `Scaffold` unions
`WindowInsets.systemBars` with `WindowInsets.ime` so the text field
shrinks above the keyboard. `adjustResize` set as pre-Android-15
fallback.
- **List cards now show a title + body preview.** First non-empty line
= title; remainder = body preview (max 2 lines, ellipsised).
Empty notes display as "Untitled".
### v0.1.0.0
- Create, edit, and delete plain-text notes
- ObjectBox-backed persistence ([objectbox.io](https://objectbox.io/))
- Material 3 UI with dynamic color (Android 12+), dark/light follows system
- Fully offline — no `INTERNET` permission
- Multi-module Android project (Android today, iOS/Desktop-ready later)
---
## Roadmap ## Roadmap
See [`Incido Development Plan.txt`](./Incido%20Development%20Plan.txt) at See [`Incido Development Plan.txt`](./Incido%20Development%20Plan.txt) at
@@ -109,39 +61,13 @@ cross-platform ports, end-to-end sync, and security features.
## Changelog ## Changelog
| Version | Date | Highlights | Release notes now live **on the Releases page**: every Incido release entry
| 0.3.7.0 | 2026-08-20 | **Trash / soft delete.** Add a Trash drawer item; deleting a note soft-deletes it, hiding it from every active view and ordinary search. Trash-only cards expose Restore and permanent Delete. | ships the full changelog for exactly that version — rendered in the
|-----------|------------|------------| release description and attached beside the APKs as
| 0.3.6.3 | 2026-08-20 | **Missing-keystore failure is now actionable on a fresh clone.** `./gradlew assembleRelease` now fails at configuration time with a clear `GradleException` quoting the exact `keytool` command from `keystore/README.md` if `keystore/release.jks` is missing, instead of dying much later inside `packageRelease` with the cryptic `SigningConfig "release" is missing required property "storeFile"`. CI is unchanged: `.gitea/workflows/release.yml` already mints the dev keystore on the runner before `assembleRelease`. | `Incido-<version>-changes.md` (generated from `PREVIOUS_HISTORY.md` by the
| 0.3.6.2 | 2026-08-19 | **CI / release-pipeline tag** — re-tag of v0.3.6.1 used to exercise the Gitea Actions release workflow (keystore minted on the release runner; debug + release APKs attached to the Gitea release). No app changes. | release workflow).
| 0.3.6.1 | 2026-08-19 | **Editor top-bar title is now left-aligned.** On the New / Edit screen the title ("New" / "Edit") now sits next to the back arrow, away from the six action icons that crowd the right edge — it was previously centred via `CenterAlignedTopAppBar` and visually pushed toward the action cluster. **Colour picker is now symmetric between the title bar and the note top.** The picker is flanked by 12dp gaps above and below (was 4dp top + 4dp bottom) so the visual distance to the title bar matches the distance to the `OutlinedTextField`'s top edge, instead of being dwarfed by the field's intrinsic top inset. | → [Releases](https://git.trevena.info/nick/incido/releases)
| 0.3.6.0 | 2026-08-19 | **Share webpages to Incido.** Sharing a page from your browser (Share → Incido) now creates a note with the page title on the first line and the URL below — fully offline (the title comes from the browser's share data, Incido never touches the network). **Export encryption key.** Settings → Security gains "Export encryption key" — saves the AES-256 key that protects your encrypted notes to a passphrase-protected `.inckey` file for device migrations. **Import encryption key** restores that key on a fresh install, with a clear warning before the current key is replaced. | · [Previous release history (archive)](./PREVIOUS_HISTORY.md)
| 0.3.5.1 | 2026-08-17 | **"Encrypted" badge now appears the moment you flip the switch.** A race in `EncryptionVerifier.checkNow()` could silently drop the post-migration verification, leaving cards without the badge until a second toggle; replaced with a serializing Mutex so every check runs in invocation order. **"Encrypted" indicator is now a single lock icon next to the date** — consistent position on every card instead of a centred "lock + label" group at the bottom. |
| 0.3.5.0 | 2026-08-17 | **Real at-rest encryption.** Note text and attachment bytes are now AES-256-GCM encrypted in place the moment you toggle "Encrypt notes at rest" — no restart required; keyed by the Keystore-wrapped 32-byte key. **Verified "Encrypted" badge.** Every encrypted note is trial-decrypted on app open and after each migration; only verified notes get the lock badge. **Block screenshots (default ON).** New toggle in Settings → Security prevents screenshots, screen recording, and app-switcher previews while Incido is open. |
| 0.3.4.0 | 2026-08-17 | **Attachment indicator on note cards** — a paperclip icon now appears on the right edge of every card that carries an attachment. **Light-theme readability over image thumbnails** — cards with a dark photo background now force light text/icon colours over the image so notes stay readable in Light mode. **Auto-Lock "Immediately" no longer locks during file pickers** — attaching a file, taking a photo, viewing an attachment, or exporting/importing a backup no longer destroys your in-progress note. |
| 0.3.3.8 | 2026-08-17 | **Designed Incido artwork is now the app icon.** The glass shield + fountain-pen nib replaces the placeholder glyph on the home screen, app drawer, and adaptive-icon layers. |
| 0.3.3.7 | 2026-08-17 | **Biometric auto-launch.** When Biometric is your active lock method, the fingerprint / face reader now opens automatically when the lock screen appears — no extra tap on "Authenticate" needed. |
| 0.3.3.6 | 2026-08-17 | **Card height tuned for real devices.** The fixed card height from v0.3.3.5 proved too tall on real devices; reduced by ~15% (now 143.dp). |
| 0.3.3.5 | 2026-08-17 | **Fixed card height.** All note cards now have a single fixed height (168.dp), so untagged notes no longer look shorter than tagged ones; timestamp pinned to the bottom via a weighted spacer; hashtag row still hidden when empty; left colour stripe spans the full card height. |
| 0.3.3.4 | 2026-08-17 | **Favourite star no longer overlaps the overflow button.** Star is now anchored to the card's bottom-right corner (same column as the top-right ⋮), so the two controls no longer collide. |
| 0.3.3.3 | 2026-08-17 | **Importing an encrypted backup no longer crashes.** The passphrase was being wiped between the preview step and the confirm dialog's Import button; now retained across the confirmation step, with proper try/catch around preview/import so failures surface a snackbar ("Import failed. Check the file and passphrase." / "Could not read backup file.") instead of crashing. |
| 0.3.3.2 | 2026-08-17 | **White-on-white lock screen in dark mode fixed.** `PinEntryScreen` is now wrapped in a themed Surface so it always paints its own theme-aware background. **Biometric unlock hang fixed.** Authentication is now fully asynchronous (BiometricPrompt callbacks run on the main executor) instead of busy-waiting on the main thread. Device-credential fallback preserved. |
| 0.3.3.1 | 2026-08-17 | **"Encrypt notes at rest" toggle now correctly greyed out** until Security is on and you've chosen either PIN or Biometric — with a subtitle explaining the requirement. **"Enable Security" no longer requires a PIN first.** The master switch just flips on; PIN / Biometric / Encrypt sub-toggles were already gated. **Importing an encrypted backup now opens a dedicated passphrase dialog** (single field, no policy check) — wrong passphrase surfaces "Incorrect passphrase." via snackbar. |
| 0.3.3.0 | 2026-08-17 | **Lock mode as a single choice.** Security now exposes two mutually-exclusive toggles (PIN and Biometric) — either alone is enough to lock; Biometric no longer requires PIN first. New "Reset PIN" row appears when PIN is active; lock screen shows only the biometric button when no Incido PIN is set. **Encrypted-import passphrase prompt.** Selecting an encrypted backup opens the passphrase dialog first and surfaces "Incorrect passphrase." on mismatch. **Press-and-hold note card menu.** The inline delete button is gone; long-press a card (or tap the ⋮ button) to open a DropdownMenu with Delete — ready for future actions like Share. |
| 0.3.2.0 | 2026-08-15 | **New Settings screen** (Untagged → Settings in the nav drawer) with Appearance, Security, Backup & Restore, and About sections. **At-rest encryption.** ObjectBox store is 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.** 4–6 digit PIN (PBKDF2-hashed, 100k iters, constant-time compare) with optional fingerprint / face unlock; cold launch + auto-lock timeout gate. **Backup / Import / Export.** JSON codec with Base64 attachment bytes; encrypted variant uses AES-256-GCM + PBKDF2(passphrase, 200k iters) with a Generate button + Copy to clipboard. Passphrase policy: 12–32 chars, ≥1 digit, ≥1 special. **Release notes dialog** — tap the version number on the About card. Adds `USE_BIOMETRIC` + `USE_FINGERPRINT` permissions (still no INTERNET). |
| 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 `<cache-path>`, 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 `<data android:mimeType="*/*" />` 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. |
| 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.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.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.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.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.0 | 2026-08-14 | Hashtags (visible chips on editor, 5-tag cap, autocomplete) + bolder colour accent + nav drawer (Home / Favorites / Untagged + recent tags) + centred app-bar title + new version scheme |
| 0.2.0.1 | 2026-08-14 | Hotfix: search icon now actually opens the search bar |
| 0.2.0.0 | 2026-08-14 | Polish + favourites, search, colours, checklists, discard dialog, release signing |
| 0.1.1.0 | 2026-08-14 | Editor IME fix + title/body on list cards |
| 0.1.0.0 | 2026-08-14 | First MVP: list + editor, ObjectBox, Material 3 |
--- ---
@@ -164,8 +90,10 @@ incido/
│ └── data/ # ObjectBox-backed repository implementation │ └── data/ # ObjectBox-backed repository implementation
├── gradle/ # Version catalog (libs.versions.toml) + wrapper ├── gradle/ # Version catalog (libs.versions.toml) + wrapper
├── keystore/ # Release signing (gitignored *.jks, README kept) ├── keystore/ # Release signing (gitignored *.jks, README kept)
├── scripts/ci/ # Release tooling (changelog extractor for the CI)
├── .gitea/ # Gitea Actions workflow + issue/PR templates ├── .gitea/ # Gitea Actions workflow + issue/PR templates
├── CONTRIBUTING.md ├── CONTRIBUTING.md
├── PREVIOUS_HISTORY.md # Archived user-facing release history
└── LICENSE └── LICENSE
``` ```
@@ -260,13 +188,20 @@ After the first push:
``` ```
[ ] Launch app — "Incido" title centred, hamburger top-left [ ] Launch app — "Incido" title centred, hamburger top-left
[ ] Tap hamburger → drawer slides in with Home / Favorites / Untagged + divider + Recent tags [ ] Tap hamburger → drawer slides in with Home / Favorites / colour-swatch strip (Blue·Green·Amber·Red·Purple) / Drafts / Untagged / Trash / Settings + divider + Recent tags
[ ] Tap "Favorites" → list shows only starred notes [ ] Tap "Favorites" → list shows only starred notes
[ ] Tap "Untagged" → list shows only notes with zero hashtags [ ] Tap "Untagged" → list shows only notes with zero hashtags
[ ] Tap a colour swatch (e.g. Blue) → list shows only ACTIVE notes of that colour; untagged ones appear, trashed ones never; search narrows within the colour; tapping the selected swatch again returns to Home
[ ] 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 a recent hashtag → list filters to that tag
[ ] Tap "Trash" → list shows only soft-deleted notes [ ] Tap "Trash" → list shows only soft-deleted notes
[ ] Delete a note → it disappears from Home/search/tag/Favorites and appears in Trash [ ] Delete a note → it disappears from Home/search/tag/Favorites and appears in Trash
[ ] Trash card overflow → "Restore" returns the note; "Delete permanently" destroys it [ ] Trash card overflow → "Restore" returns the note; "Delete permanently" destroys it
[ ] Trash holds notes → "Empty Trash" (∞-forever icon) appears in the top bar → confirm dialog → everything in Trash is permanently deleted
[ ] Tap "Home" → back to all active notes [ ] Tap "Home" → back to all active notes
[ ] Open a note → chip row above text field shows current tags (empty placeholder if none) [ ] Open a note → chip row above text field shows current tags (empty placeholder if none)
[ ] Tap "#" icon → sheet opens, type "wo" → suggestions filter [ ] Tap "#" icon → sheet opens, type "wo" → suggestions filter
+30 -11
View File
@@ -28,17 +28,36 @@ android {
applicationId = "org.incido.app" applicationId = "org.incido.app"
minSdk = 26 minSdk = 26
targetSdk = 35 targetSdk = 35
// v0.3.7.0: Trash / soft delete — deleting a note now flags it // v0.4.1.1: EMERGENCY hotfix — two editor regressions shipped
// trashed (hidden from every active view and ordinary search); // in v0.4.1.0. (1) Saving a note landed it in Drafts: the save
// a Trash drawer entry exposes Restore and permanent Delete. // path published the note but left UiState.existing.isDraft =
// - NoteEntity gains `trashed` (additive schema, auto-migrated); // true, so the editor's dispose-time flushDraft() immediately
// NoteFilter gains a Trash case; the repository gains // re-persisted it as a draft; the state now adopts the
// moveToTrash / restoreFromTrash / deletePermanently; drawer, // published row (isDraft = false), letting persistDraftNow()'s
// list, and editor ViewModels + screens wire the actions; // already-published guard make the flush a no-op. (2) Enter on
// backups round-trip the trashed state. // a shopping-list Price field fell through to system focus
// - versionCode monotonic +1 from v0.3.6.3 (30). // traversal and wrapped the cursor back to the Title; it now
versionCode = 31 // wires KeyboardActions(onNext = onAddAfter) like the Product
versionName = "0.3.7.0" // field — Enter adds a fresh row with the cursor in its
// Product box.
// - versionCode monotonic +1 from v0.4.1.0 (36).
// 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 --- // --- Signing ---
+11
View File
@@ -11,6 +11,11 @@
database and are never uploaded anywhere. database and are never uploaded anywhere.
--> -->
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAMERA" />
<!-- v0.4.2.0: RECORD_AUDIO for voice notes. Recordings are stored
as ordinary audio attachments inside the ObjectBox database
(at-rest encryption applies) and never leave the device —
still no INTERNET, no analytics, no cloud. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- v0.3.2.0: biometric (fingerprint / face) unlock for the <!-- v0.3.2.0: biometric (fingerprint / face) unlock for the
app-lock PIN alternative. USE_BIOMETRIC is the modern app-lock PIN alternative. USE_BIOMETRIC is the modern
permission; USE_FINGERPRINT is the pre-Android-10 alias and permission; USE_FINGERPRINT is the pre-Android-10 alias and
@@ -21,6 +26,12 @@
<uses-feature <uses-feature
android:name="android.hardware.camera" android:name="android.hardware.camera"
android:required="false" /> android:required="false" />
<!-- v0.4.2.0: voice notes need a mic; devices without one simply
never see the recorder UI light up (the permission request
fails gracefully). -->
<uses-feature
android:name="android.hardware.microphone"
android:required="false" />
<uses-feature <uses-feature
android:name="android.hardware.fingerprint" android:name="android.hardware.fingerprint"
android:required="false" /> android:required="false" />
Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 KiB

After

Width:  |  Height:  |  Size: 139 KiB

@@ -1,10 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
v0.3.3.8: designed icon replaces the v0.1 placeholder glyph. v0.3.3.8: designed icon replaces the v0.1 placeholder glyph.
The foreground is the density-bucketed incido.png artwork v0.3.7.1: foreground is now the new flat icon artwork
(drawable-<density>/ic_launcher_foreground.png, sized for the (incido_flat_icon.png, downscaled into drawable-<density>/
108dp adaptive canvas); the background matches the artwork's ic_launcher_foreground.png at the 108dp adaptive canvas sizes);
edge colour so parallax exposure is seamless. the background colour matches the artwork's fill so parallax
exposure is seamless.
--> -->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" /> <background android:drawable="@color/ic_launcher_background" />
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
v0.3.3.8: designed icon replaces the v0.1 placeholder glyph. v0.3.3.8: designed icon replaces the v0.1 placeholder glyph.
v0.3.7.1: new flat icon artwork (see ic_launcher.xml).
Round launcher variant of the adaptive icon; same artwork Round launcher variant of the adaptive icon; same artwork
layers as ic_launcher.xml. layers as ic_launcher.xml.
--> -->
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.5 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 38 KiB

+5 -3
View File
@@ -1,7 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<!-- v0.3.3.8: background for the adaptive launcher icon, matched to <!-- v0.3.3.8: background for the adaptive launcher icon, matched to
the edge colour of the incido.png artwork so parallax exposure the artwork's edge colour so parallax exposure is seamless.
of the background layer is seamless. --> v0.3.7.1: re-tinted from #010435 to the new flat icon's fill
<color name="ic_launcher_background">#010435</color> colour (#352999) so the foreground's squircle edges blend
invisibly into the background layer. -->
<color name="ic_launcher_background">#352999</color>
</resources> </resources>
@@ -40,6 +40,7 @@ import org.incido.compose.ui.settings.auth.PinChangeScreen
import org.incido.compose.ui.settings.auth.PinEntryScreen import org.incido.compose.ui.settings.auth.PinEntryScreen
import org.incido.compose.ui.settings.auth.PinSetupScreen import org.incido.compose.ui.settings.auth.PinSetupScreen
import org.incido.compose.ui.theme.IncidoTheme import org.incido.compose.ui.theme.IncidoTheme
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteFilter import org.incido.domain.model.NoteFilter
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
@@ -61,8 +62,13 @@ private fun String.toNoteFilter(): NoteFilter = when {
this == "home" -> NoteFilter.Home this == "home" -> NoteFilter.Home
this == "favorites" -> NoteFilter.Favorites this == "favorites" -> NoteFilter.Favorites
this == "untagged" -> NoteFilter.Untagged this == "untagged" -> NoteFilter.Untagged
this == "drafts" -> NoteFilter.Drafts
this == "trash" -> NoteFilter.Trash this == "trash" -> NoteFilter.Trash
startsWith("tag:") -> NoteFilter.ByTag(this.removePrefix("tag:")) startsWith("tag:") -> NoteFilter.ByTag(this.removePrefix("tag:"))
startsWith("color:") -> NoteColor.values()
.firstOrNull { it.name == this.removePrefix("color:") }
?.let { NoteFilter.ByColor(it) }
?: NoteFilter.Home
else -> NoteFilter.Home else -> NoteFilter.Home
} }
@@ -6,6 +6,7 @@ import kotlinx.serialization.json.Json
import org.incido.domain.model.Note import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
/** /**
@@ -125,6 +126,14 @@ data class BackupNote(
val attachments: List<BackupAttachment> = emptyList(), val attachments: List<BackupAttachment> = emptyList(),
/** Preserve soft-delete state; defaults to false for older backups. */ /** Preserve soft-delete state; defaults to false for older backups. */
val isTrashed: Boolean = false, val isTrashed: Boolean = false,
/** Preserve draft state; defaults to false for older backups. */
val isDraft: Boolean = false,
/**
* v0.3.8.0 — serialised as the [org.incido.domain.model.NoteType]
* 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",
) )
@Serializable @Serializable
@@ -156,6 +165,8 @@ private suspend fun Note.toBackup(repository: NoteRepository): BackupNote {
isFavorite = isFavorite, isFavorite = isFavorite,
color = color.name, color = color.name,
isTrashed = isTrashed, isTrashed = isTrashed,
isDraft = isDraft,
noteType = type.name,
hashtags = hashtags, hashtags = hashtags,
attachments = backups, attachments = backups,
) )
@@ -172,6 +183,8 @@ private fun Note.toBackup(): BackupNote = BackupNote(
isFavorite = isFavorite, isFavorite = isFavorite,
color = color.name, color = color.name,
isTrashed = isTrashed, isTrashed = isTrashed,
isDraft = isDraft,
noteType = type.name,
hashtags = hashtags, hashtags = hashtags,
attachments = emptyList(), attachments = emptyList(),
) )
@@ -184,6 +197,8 @@ private fun BackupNote.toDomain(): Note = Note(
isFavorite = isFavorite, isFavorite = isFavorite,
color = runCatching { NoteColor.valueOf(color) }.getOrDefault(NoteColor.NONE), color = runCatching { NoteColor.valueOf(color) }.getOrDefault(NoteColor.NONE),
isTrashed = isTrashed, isTrashed = isTrashed,
isDraft = isDraft,
type = runCatching { NoteType.valueOf(noteType) }.getOrDefault(NoteType.TEXT),
hashtags = hashtags, hashtags = hashtags,
// Attachments are inserted separately by importSnapshot so they // Attachments are inserted separately by importSnapshot so they
// get assigned to the freshly-created note id. // get assigned to the freshly-created note id.
@@ -0,0 +1,405 @@
package org.incido.compose.data.backup
import android.content.Context
import android.net.Uri
import java.io.ByteArrayInputStream
import java.util.zip.ZipInputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository
/**
* v0.3.9.0 — imports notes from a **Carnet / QuickNote** archive.
*
* The source is a `.zip` whose top-level entries are `*.sqd` files (plus
* some metadata dirs we ignore). Each `.sqd` is *itself* a zip containing:
* * `index.html` — the note body inside `<div class="edit-zone">…</div>`
* * `metadata.json` — `creation_date`, `last_modification_date`,
* `keywords[]`, `rating`, `color`, `urls{}`, `todolists[]`
* * `data/<file>` — optional attachments (images etc). A companion
* `data/preview_` thumbnail is skipped so we don't
* import a low-res duplicate.
*
* Incido stores note bodies as **plain text**, so the rich-text HTML is
* flattened to text (block tags → newlines, entities decoded, tags stripped).
* The `.sqd` filename becomes the note's title line, which also gives
* image-only notes (no HTML body) a readable title.
*
* Import is **additive** — matching the existing backup-import behaviour:
* existing notes are preserved, every imported note gets a fresh id, and
* attachments are stored via [NoteRepository.addAttachment] (which applies
* EXIF normalisation + at-rest encryption transparently).
*
* Both archive shapes are accepted: a bundle of `*.sqd` files, or a single
* `.sqd` file picked directly (its zip entries are the note's own
* `index.html` / `metadata.json` / files under `data/`).
*/
class CarnetImporter(
private val context: Context,
private val repository: NoteRepository,
) {
private val json = Json {
ignoreUnknownKeys = true
isLenient = true
}
/**
* Read the archive at [uri] and import every Carnet note it contains.
* Returns the number of notes imported.
*/
suspend fun import(
uri: Uri,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int = withContext(Dispatchers.IO) {
val archiveBytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
?: throw java.io.IOException("Could not open input stream for $uri")
val topLevel = readZip(archiveBytes)
// The picked file is a single archive that bundles every note as a
// nested `.sqd` entry (each `.sqd` is itself a zip). Collect those.
val sqdNotes = topLevel.filter { (name, _) -> name.endsWith(".sqd", ignoreCase = true) }
.toList()
// Candidates as (title-file-name, raw-bytes). If no `.sqd` entries
// were found, the picked file is treated as a single `.sqd` (its own
// zip entries are index.html / metadata.json / data/…).
val candidates: List<Pair<String, ByteArray>> = if (sqdNotes.isNotEmpty()) {
sqdNotes
} else {
listOf((queryDisplayName(uri) ?: "Imported note.sqd") to archiveBytes)
}
// Parse phase — fault-isolated so one corrupt `.sqd` can't abort the
// rest of the archive.
val notes = candidates.mapNotNull { (name, bytes) ->
runCatching { parseSqd(name.substringAfterLast('/'), bytes) }.getOrNull()
}.filter { it.hasContent() }
// Persist phase — also per-note, so a single bad note doesn't lose the
// ones already written (the repository commits each note independently).
val total = notes.size
var imported = 0
notes.forEach { parsed ->
val ok = runCatching { persist(parsed) }.isSuccess
if (ok) imported++
onProgress(imported, total)
}
imported
}
// --- Persistence ---------------------------------------------------------
private suspend fun persist(parsed: ParsedSqd) {
val hashtags = parsed.keywords
.flatMap { raw ->
// Prefer the whole keyword as one tag; if it isn't a valid
// hashtag (Incido allows only [a-z0-9._-], 1–31 chars), split
// on whitespace/commas and keep the valid sub-tokens.
val one = Hashtag.normalise(raw)
if (Hashtag.parseOrNull(one) != null) {
listOf(one)
} else {
raw.split(Regex("[\\s,]+"))
.map { Hashtag.normalise(it) }
.filter { Hashtag.parseOrNull(it) != null }
}
}
.filter { it.isNotEmpty() }
.toSet()
val saved = repository.saveNoteWithHashtags(
note = Note(
id = 0L, // force a fresh id
content = parsed.content,
createdAt = parsed.createdAt,
updatedAt = parsed.updatedAt,
isFavorite = parsed.isFavorite,
color = parsed.color,
isTrashed = false,
type = parsed.type,
),
hashtagsToAdd = hashtags,
hashtagsToRemove = emptySet(),
)
for (att in parsed.attachments) {
repository.addAttachment(
noteId = saved.id,
bytes = att.bytes,
mimeType = sniffMimeType(att.bytes),
displayName = att.displayName,
)
}
}
// --- .sqd parsing --------------------------------------------------------
private fun parseSqd(fileName: String, sqdBytes: ByteArray): ParsedSqd {
val files = readZip(sqdBytes)
val title = fileName.substringBeforeLast('.')
.ifBlank { "Untitled" }
val html = files["index.html"]?.toString(Charsets.UTF_8).orEmpty()
val meta = files["metadata.json"]
?.let {
runCatching {
json.decodeFromString(CarnetMetadata.serializer(), it.toString(Charsets.UTF_8))
}.getOrNull()
}
?: CarnetMetadata()
val body = htmlToText(html)
// Attachments: anything under data/ that is a real file (not a dir
// entry) and not an auto-generated preview thumbnail.
val attachments = files
.filter { (name, bytes) ->
name.startsWith("data/") &&
!name.endsWith("/") &&
bytes.isNotEmpty() &&
!name.substringAfterLast('/').startsWith("preview_")
}
.map { (name, bytes) -> Attachment(name.substringAfterLast('/'), bytes) }
val type = if (meta.todolists.isNotEmpty()) NoteType.TASK_LIST else NoteType.TEXT
return ParsedSqd(
content = buildContent(title, body, meta),
createdAt = meta.creationDate.takeIf { it > 0 } ?: System.currentTimeMillis(),
updatedAt = meta.lastModificationDate.takeIf { it > 0 } ?: System.currentTimeMillis(),
isFavorite = meta.rating >= 5,
color = mapColor(meta.color),
type = type,
keywords = meta.keywords,
attachments = attachments,
)
}
/**
* Assemble the final plain-text body. The filename is used as the title
* (first non-blank line in Incido's title/body split); then the HTML
* body; then any URLs from the metadata; then any to-do lists rendered as
* GFM checkbox lines (`- [ ]` / `- [x]`) so [NoteType.TASK_LIST] renders.
*/
private fun buildContent(title: String, body: String, meta: CarnetMetadata): String {
val blocks = mutableListOf<String>()
blocks += title
if (body.isNotBlank()) blocks += body
if (meta.urls.isNotEmpty()) {
blocks += meta.urls.keys.filter { it.isNotBlank() }
}
for (todo in meta.todolists) {
val lines = buildList {
todo.done.forEach { if (it.isNotBlank()) add("- [x] ${it.trim()}") }
todo.todo.forEach { if (it.isNotBlank()) add("- [ ] ${it.trim()}") }
}
if (lines.isNotEmpty()) blocks += lines.joinToString("\n")
}
return blocks.filter { it.isNotBlank() }.joinToString("\n\n").trim()
}
// --- Helpers -------------------------------------------------------------
/** Read every file entry (name → bytes) from a zip, skipping dirs. */
private fun readZip(bytes: ByteArray): LinkedHashMap<String, ByteArray> {
val out = LinkedHashMap<String, ByteArray>()
ZipInputStream(ByteArrayInputStream(bytes)).use { zis ->
while (true) {
val entry = zis.nextEntry ?: break
if (entry.isDirectory) { zis.closeEntry(); continue }
val data = zis.readBytes()
out[entry.name] = data
zis.closeEntry()
}
}
return out
}
/** Query the user-visible name of a SAF [uri] (falls back to null). */
private fun queryDisplayName(uri: Uri): String? {
return try {
context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
val idx = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
}
} catch (_: Exception) {
null
}
}
companion object {
/** MIME type detected from magic bytes, falling back to a default. */
fun sniffMimeType(bytes: ByteArray): String {
fun b(i: Int) = if (i < bytes.size) bytes[i].toInt() and 0xFF else -1
if (b(0) == 0xFF && b(1) == 0xD8 && b(2) == 0xFF) return "image/jpeg"
if (b(0) == 0x89 && b(1) == 0x50 && b(2) == 0x4E && b(3) == 0x47) return "image/png"
if (b(0) == 0x47 && b(1) == 0x49 && b(2) == 0x46 && b(3) == 0x38) return "image/gif"
if (b(0) == 0x52 && b(1) == 0x49 && b(2) == 0x46 && b(3) == 0x46 &&
b(8) == 0x57 && b(9) == 0x45 && b(10) == 0x42 && b(11) == 0x50
) return "image/webp"
if (b(0) == 0x42 && b(1) == 0x4D) return "image/bmp"
return "application/octet-stream"
}
/** Carnet color string → Incido [NoteColor]. Unknown values → NONE. */
fun mapColor(raw: String): NoteColor = when (raw.trim().lowercase()) {
"red" -> NoteColor.RED
"green" -> NoteColor.GREEN
"blue" -> NoteColor.BLUE
"yellow", "amber" -> NoteColor.AMBER
"purple" -> NoteColor.PURPLE
else -> NoteColor.NONE
}
/**
* Flatten a Carnet `index.html` note body to plain text:
* strip comments, isolate the `.edit-zone` content, turn block
* boundaries into newlines, decode entities (incl. `&nbsp;`), then
* drop the remaining tags.
*/
fun htmlToText(html: String): String {
var s = html.replace(Regex("<!--.*?-->", RegexOption.DOT_MATCHES_ALL), " ")
// Keep only the edit-zone body (everything after its opening tag,
// up to the sibling `<div id="floating">` that follows it).
val zoneMatch = Regex("class=\"edit-zone\"[^>]*>").find(s)
if (zoneMatch != null) {
s = s.substring(zoneMatch.range.last + 1)
val floatIdx = s.indexOf("<div id=\"floating\"")
if (floatIdx >= 0) s = s.substring(0, floatIdx)
}
s = s.replace(Regex("<br\\s*/?>", RegexOption.IGNORE_CASE), "\n")
s = s.replace(Regex("</(div|p|li|ul|ol|tr|h[1-6])>", RegexOption.IGNORE_CASE), "\n")
s = s.replace(Regex("<[^>]+>"), "")
s = decodeEntities(s)
// Normalise whitespace: drop trailing spaces per line, collapse
// runs of 2+ blank lines to a single blank line.
val lines = s.replace("\r", "").split('\n').map { it.trimEnd() }
val collapsed = StringBuilder()
var blanks = 0
for (line in lines) {
if (line.isEmpty()) {
blanks++
if (blanks <= 1) collapsed.append('\n')
} else {
blanks = 0
collapsed.append(line).append('\n')
}
}
return collapsed.toString().trim()
}
/** Decode the named + numeric HTML entities a Carnet body can contain. */
private fun decodeEntities(input: String): String {
if (!input.contains('&')) return input
val sb = StringBuilder(input.length)
var i = 0
while (i < input.length) {
val c = input[i]
if (c == '&') {
val semi = input.indexOf(';', i + 1)
if (semi in (i + 1)..(i + 12)) {
val entity = input.substring(i, semi + 1)
val decoded = NAMED_ENTITIES[entity] ?: numericEntity(entity)
if (decoded != null) {
sb.append(decoded)
i = semi + 1
continue
}
}
}
sb.append(c)
i++
}
return sb.toString()
}
private fun numericEntity(entity: String): String? {
if (!entity.startsWith("&#") || !entity.endsWith(";")) return null
val body = entity.substring(2, entity.length - 1)
return try {
val code = if (body.startsWith("x") || body.startsWith("X")) {
body.substring(1).toLong(16)
} else {
body.toLong()
}
if (code in 0..0x10FFFF) String(Character.toChars(code.toInt())) else null
} catch (_: NumberFormatException) {
null
}
}
private val NAMED_ENTITIES = mapOf(
"&nbsp;" to " ",
"&amp;" to "&",
"&lt;" to "<",
"&gt;" to ">",
"&quot;" to "\"",
"&#39;" to "'",
"&apos;" to "'",
"&copy;" to "\u00A9",
"&reg;" to "\u00AE",
"&trade;" to "\u2122",
"&hellip;" to "\u2026",
"&mdash;" to "\u2014",
"&ndash;" to "\u2013",
"&rsquo;" to "\u2019",
"&lsquo;" to "\u2018",
"&rdquo;" to "\u201D",
"&ldquo;" to "\u201C",
)
}
// --- Data ----------------------------------------------------------------
/** A parsed, ready-to-persist Carnet note. */
data class ParsedSqd(
val content: String,
val createdAt: Long,
val updatedAt: Long,
val isFavorite: Boolean,
val color: NoteColor,
val type: NoteType,
val keywords: List<String>,
val attachments: List<Attachment>,
) {
fun hasContent(): Boolean = content.isNotBlank() || attachments.isNotEmpty()
}
/** A single attachment (file name + raw bytes) inside a `.sqd`'s `data/`. */
data class Attachment(val displayName: String, val bytes: ByteArray)
@Serializable
private data class CarnetMetadata(
@SerialName("creation_date") val creationDate: Long = 0,
@SerialName("last_modification_date") val lastModificationDate: Long = 0,
val keywords: List<String> = emptyList(),
val rating: Int = -1,
val color: String = "none",
val urls: Map<String, JsonElement> = emptyMap(),
val todolists: List<CarnetTodo> = emptyList(),
)
@Serializable
private data class CarnetTodo(
val id: String = "",
val todo: List<String> = emptyList(),
val done: List<String> = emptyList(),
)
}
@@ -26,84 +26,136 @@ object ReleaseNotes {
*/ */
val RECENT: List<ReleaseNote> = listOf( val RECENT: List<ReleaseNote> = listOf(
ReleaseNote( ReleaseNote(
version = "0.3.7.0", version = "0.4.2.0",
date = "2026-08-20", date = "2026-09-23",
bullets = listOf( bullets = listOf(
"Trash / soft delete. Deleting a note now moves it to a new " + "Before you update: please make certain you have a " +
"Trash section in the navigation drawer instead of " + "current backup — Settings → Backup & Restore → " +
"destroying it immediately \u2014 it disappears from Home, " + "Export (plus your encryption key under Settings → " +
"Favorites, Untagged, tag views, and ordinary search.", "Security if encryption is on) — before installing " +
"Inside Trash, each note's menu offers Restore (puts it back " + "this version. Every future release will remind " +
"where it was) or Delete permanently (destroys it for " + "you the same way.",
"good, including attachments).", "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( ReleaseNote(
version = "0.3.6.0", version = "0.4.1.1",
date = "2026-08-19", date = "2026-09-23",
bullets = listOf( bullets = listOf(
"Sharing a webpage to Incido (browser \u2192 Share \u2192 Incido) now " + "Saved notes stay put: in v0.4.1.0 every note you " +
"creates a note with the page title on the first line and " + "saved ended up in Drafts instead of Home \u2014 " +
"the URL below it \u2014 ready to save as-is. Fully offline: " + "the editor still believed it was a draft and " +
"the title comes from the browser's share data, so Incido " + "quietly re-saved it as one when you left the " +
"still never touches the network.", "screen. Saving now publishes properly: the note " +
"New in Settings \u2192 Security: \"Export encryption key\" saves " + "goes to Home and leaves Drafts for good.",
"the AES-256 key that protects your encrypted notes to a " + "Enter behaves in the price box: in a shopping list, " +
"passphrase-protected .inckey file \u2014 your backup for " + "Enter in a row's Price field used to jump the " +
"device migrations.", "cursor back to the note title \u2014 it now works " +
"\"Import encryption key\" restores that key on a fresh " + "like Enter in the product field: a fresh row " +
"install, with a clear warning before the current key is " + "appears below, cursor ready in its Product box.",
"replaced.",
), ),
), ),
ReleaseNote( ReleaseNote(
version = "0.3.5.1", version = "0.4.1.0",
date = "2026-08-17", date = "2026-09-23",
bullets = listOf( bullets = listOf(
"Cards now update their \"Encrypted\" indicator the moment " + "Colour filters in the drawer: a strip of five swatches " +
"you flip the Encrypt-at-rest switch on — no need to " + "\u2014 Blue, Green, Amber, Red, Purple \u2014 sits " +
"toggle off+on or restart the app to see the badge " + "right under Favorites. Tap one and the list shows " +
"appear.", "ONLY notes of that colour; tap it again for Home.",
"The \"Encrypted\" indicator on each note card is now " + "Colour views follow the Favorites / Untagged rules: " +
"just a small lock icon, sitting immediately to the " + "trashed notes never show, untagged ones do, and " +
"left of the date/time on the bottom row (consistent " + "search narrows within the selected colour.",
"position on every card, instead of a centred \"lock + " + "Auto-saved drafts: a new note saves itself while you " +
"label\" group at the bottom of the card).", "type, so nothing is ever lost \u2014 an unfinished " +
"note waits in the new Drafts drawer row, and opening " +
"it again picks up exactly where you stopped.",
"An untitled draft names itself after its kind \u2014 " +
"\"Task List \u2014 (draft)\", \"Shopping List \u2014 " +
"(draft)\" \u2014 on its card and in the editor bar. " +
"Drafts survive encrypted backup and restore too.",
"Empty Trash: a one-tap button appears whenever the " +
"Trash holds notes \u2014 a confirmation dialog " +
"stands between that tap and permanently deleting " +
"every trashed note, attachments included.",
"Editor rows rebuilt: title, item and quantity fields " +
"share one even underlined height, long checklist " +
"labels wrap instead of stretching the row, and " +
"checkbox / +/- controls stay centred alongside.",
), ),
), ),
ReleaseNote( ReleaseNote(
version = "0.3.5.0", version = "0.4.0.0",
date = "2026-08-17", date = "2026-09-18",
bullets = listOf( bullets = listOf(
"\"Encrypt notes at rest\" now really works: your note text " + "Import 3rd-party notes: Settings \u2192 Backup & Restore now " +
"and attachment files are AES-256-GCM encrypted in place " + "has an \u201cImport 3rd Party Notes\u201d button that reads a " +
"the moment you flip the switch (no restart), using the " + "Carnet / QuickNote .zip export (a single archive bundling " +
"Android Keystore key.", "one .sqd per note) and brings every note in \u2014 directly " +
"Every time the app opens, each encrypted note is " + "on-device, with no pre-conversion step.",
"double-checked by decrypting it — a card only earns the " + "Formatting is preserved as plain text: rich-text bodies are " +
"\"Encrypted\" badge at the bottom of the card if that " + "flattened, and note colours, keywords (imported as tags) " +
"check passes.", "and links carry over. To-do lists become native " +
"New \"Block screenshots\" toggle (on by default): prevents " + "checklists you can tick off.",
"screenshots, screen recording, and app-switcher previews " + "Images come across too \u2014 photo attachments inside each " +
"while Incido is open.", "note are imported; auto-generated preview thumbnails are " +
"skipped, so you get one clean image per photo.",
"Import is additive: your existing notes are untouched and " +
"imported notes get fresh IDs, so you can safely pull in " +
"an archive at any time.",
), ),
), ),
ReleaseNote( ReleaseNote(
version = "0.3.4.0", version = "0.3.8.0",
date = "2026-08-17", date = "2026-09-16",
bullets = listOf( bullets = listOf(
"Note cards now show a paperclip icon on the right edge " + "Task lists: a checklist button next to the # button in the " +
"whenever a note has an attachment — lined up between " + "editor turns any note into an editable task list — add, " +
"the favourite star and the \u22EE menu.", "remove, and tick off items with real checkboxes.",
"Cards with a dark image background are now readable in " + "Shopping lists with a running total: each row gets a " +
"Light theme — the title, preview text, timestamp and " + "quantity dropdown (1\u20139) and a supermarket-style " +
"icons switch to light colours over the photo.", "price field \u2014 every digit you tap on the number pad " +
"Auto-Lock set to \"Immediately\" no longer locks the app " + "is a cent, so entering 199 means $1.99 (the price box " +
"while you're picking a file to attach (or exporting / " + "shows your raw entry beside its $ sign; the running " +
"importing a backup), so your in-progress note and the " + "total speaks real dollars). Tick an " +
"attachment survive the trip to the file manager.", "item once it's in your basket and the always-visible " +
"total at the top adds quantity \u00d7 price. Product, " +
"quantity, and price are strictly separate fields, so a " +
"product called \"Battery AA 3\" can never mess up your " +
"money maths.",
"Tapping the active list button again returns the note to " +
"plain text — nothing is lost, the items just become " +
"\"- [ ]\" lines you can also edit by hand.",
"Add-tag sheet fixed: existing hashtags now appear as a " +
"selectable suggestion list again, narrowing to matches " +
"live as you type (the suggestion pipeline was frozen, so " +
"only \"+ Create\\u2026\" ever showed).",
), ),
), ),
// v0.3.7.0 push drops v0.3.3.8 off the "5 most recent" tail. // v0.4.2.0 push drops v0.3.7.1 off the "5 most recent" tail.
) )
} }
@@ -11,6 +11,7 @@ import org.incido.data.crypto.NoteCryptoService
import org.incido.data.repository.NoteRepositoryImpl import org.incido.data.repository.NoteRepositoryImpl
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
import org.incido.compose.data.backup.BackupManager import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.backup.CarnetImporter
import org.incido.compose.data.security.AesGcmFieldCipher import org.incido.compose.data.security.AesGcmFieldCipher
import org.incido.compose.data.security.EncryptionVerifier import org.incido.compose.data.security.EncryptionVerifier
import org.incido.compose.data.security.ObjectBoxKeyProvider import org.incido.compose.data.security.ObjectBoxKeyProvider
@@ -78,6 +79,10 @@ class AppContainer(context: Context) {
val backupManager: BackupManager = BackupManager(appContext, noteRepository) val backupManager: BackupManager = BackupManager(appContext, noteRepository)
/** v0.3.9.0 — Carnet / QuickNote `.sqd` archive importer. */
val carnetImporter: CarnetImporter = CarnetImporter(appContext, noteRepository)
/** Migration sweep + startup integrity checker for the note store. */ /** Migration sweep + startup integrity checker for the note store. */
val noteCryptoService = NoteCryptoService(boxStore, cipherHolder) val noteCryptoService = NoteCryptoService(boxStore, cipherHolder)
@@ -1,8 +1,15 @@
package org.incido.compose.ui.drawer package org.incido.compose.ui.drawer
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
@@ -11,7 +18,9 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.LabelOff import androidx.compose.material.icons.filled.LabelOff
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Drafts
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Tag import androidx.compose.material.icons.filled.Tag
@@ -25,18 +34,24 @@ import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.compose.viewModel
import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.toComposeColor
import org.incido.domain.model.HashtagUsage import org.incido.domain.model.HashtagUsage
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteFilter import org.incido.domain.model.NoteFilter
/** /**
* Left-side navigation drawer. Top section has five fixed entries * Left-side navigation drawer. Top section has the fixed entries
* (Home / Favorites / Untagged / Trash / Settings); a `HorizontalDivider`; then * (Home / Favorites / the colour-swatch strip / Drafts / Untagged /
* Trash / Settings); a `HorizontalDivider`; then
* a live scrollable list of the user's most-recently-used hashtags. * a live scrollable list of the user's most-recently-used hashtags.
* *
* Tapping a filter entry calls [onSelectFilter]; tapping Settings * Tapping a filter entry calls [onSelectFilter]; tapping Settings
@@ -45,6 +60,16 @@ import org.incido.domain.model.NoteFilter
* *
* v0.3.2.0 — Settings is a new entry directly underneath "Untagged" * v0.3.2.0 — Settings is a new entry directly underneath "Untagged"
* with its own divider for visual separation. * with its own divider for visual separation.
*
* Colour filters sit between "Favorites" and "Drafts" as one
* horizontal strip of swatches — the colours are self-explanatory, so
* there are no labels. Selecting one shows ONLY active notes of that
* colour — trashed notes never appear, untagged ones do (see
* NoteFilter.ByColor); tapping the selected swatch again returns to
* Home.
*
* "Drafts" lists auto-saved new notes (see Note.isDraft) — a new note
* is persisted automatically while it is being written.
*/ */
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -83,6 +108,64 @@ fun IncidoDrawer(
onClick = { onSelectFilter(NoteFilter.Favorites) }, onClick = { onSelectFilter(NoteFilter.Favorites) },
icon = { Icon(Icons.Filled.Star, contentDescription = null) }, icon = { Icon(Icons.Filled.Star, contentDescription = null) },
) )
// Colour filters: one horizontal strip of swatches under
// Favorites (NONE is not offered; the colours are
// self-explanatory, so there are no labels). Each shows
// ONLY active notes of that colour — trashed notes never
// appear, untagged ones do. Tapping the selected swatch
// again returns to Home.
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(
space = 14.dp,
alignment = Alignment.CenterHorizontally,
),
) {
AllNoteColors.filter { it != NoteColor.NONE }.forEach { color ->
val selected = currentFilter == NoteFilter.ByColor(color)
Box(
modifier = Modifier
.size(30.dp)
.clip(CircleShape)
.background(color.toComposeColor())
.then(
if (selected) {
Modifier.border(
width = 3.dp,
color = MaterialTheme.colorScheme.onSurface,
shape = CircleShape,
)
} else {
Modifier
},
)
.clickable {
onSelectFilter(
if (selected) NoteFilter.Home
else NoteFilter.ByColor(color),
)
},
contentAlignment = Alignment.Center,
) {
if (selected) {
Icon(
Icons.Filled.Check,
contentDescription = "${color.label} filter selected",
modifier = Modifier.size(16.dp),
tint = Color.White,
)
}
}
}
}
NavigationDrawerItem(
label = { Text("Drafts") },
selected = currentFilter == NoteFilter.Drafts,
onClick = { onSelectFilter(NoteFilter.Drafts) },
icon = { Icon(Icons.Filled.Drafts, contentDescription = null) },
)
NavigationDrawerItem( NavigationDrawerItem(
label = { Text("Untagged") }, label = { Text("Untagged") },
selected = currentFilter == NoteFilter.Untagged, selected = currentFilter == NoteFilter.Untagged,
@@ -128,6 +211,10 @@ fun IncidoDrawer(
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
// weight(1f) caps this list at the remaining
// sheet height so long tag lists scroll inside
// the drawer instead of overflowing the bottom.
.weight(1f)
.verticalScroll(rememberScrollState()), .verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(2.dp), verticalArrangement = Arrangement.spacedBy(2.dp),
) { ) {
@@ -165,6 +252,3 @@ private fun DrawerHashtagEntry(
icon = { Icon(Icons.Filled.Tag, contentDescription = null) }, icon = { Icon(Icons.Filled.Tag, contentDescription = null) },
) )
} }
@Suppress("unused")
private val _ignored: Color = Color.Unspecified
@@ -18,7 +18,6 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState import androidx.compose.runtime.produceState
@@ -31,13 +30,11 @@ import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogProperties
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import android.widget.Toast
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
@@ -91,9 +88,11 @@ fun ImageViewerScreen(
offsetY += panChange.y offsetY += panChange.y
} }
// Decode the image (or display an error / "unsupported" // Decode the image (or display an error message when the
// message for non-image attachments). // bytes can't be loaded / decoded).
var loadFailed by remember { mutableStateOf(false) }
val bitmap by produceState<android.graphics.Bitmap?>(initialValue = null, key1 = attachmentId) { val bitmap by produceState<android.graphics.Bitmap?>(initialValue = null, key1 = attachmentId) {
loadFailed = false
val bytes: ByteArray? = when (attachmentId) { val bytes: ByteArray? = when (attachmentId) {
is ViewerAttachmentId.Persisted -> withContext(Dispatchers.IO) { is ViewerAttachmentId.Persisted -> withContext(Dispatchers.IO) {
repository.getAttachmentBytes(attachmentId.id) repository.getAttachmentBytes(attachmentId.id)
@@ -101,22 +100,14 @@ fun ImageViewerScreen(
is ViewerAttachmentId.Pending -> pendingBytes is ViewerAttachmentId.Pending -> pendingBytes
} }
if (bytes == null) { if (bytes == null) {
value = null loadFailed = true
return@produceState return@produceState
} }
value = withContext(Dispatchers.IO) { val decoded = withContext(Dispatchers.IO) {
BitmapFactory.decodeByteArray(bytes, 0, bytes.size) BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
} }
} value = decoded
if (decoded == null) loadFailed = true
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) { if (bitmap != null) {
@@ -152,7 +143,7 @@ fun ImageViewerScreen(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
Text( Text(
text = "Loading…", text = if (loadFailed) "Couldn't load image" else "Loading…",
color = Color.White, color = Color.White,
style = MaterialTheme.typography.bodyLarge, style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
@@ -3,13 +3,16 @@ package org.incido.compose.ui.editor
import android.Manifest import android.Manifest
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import android.net.Uri import android.net.Uri
import android.widget.Toast import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border import androidx.compose.foundation.border
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
@@ -27,28 +30,39 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.union import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AttachFile import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.CameraAlt import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Description import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.Done import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.MoreVert 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.Star
import androidx.compose.material.icons.filled.Tag import androidx.compose.material.icons.filled.Tag
import androidx.compose.material.icons.outlined.StarOutline import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AssistChip import androidx.compose.material3.AssistChip
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -58,11 +72,13 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SuggestionChip import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
@@ -74,16 +90,26 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusEvent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider import androidx.core.content.FileProvider
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.compose.viewModel
@@ -94,8 +120,11 @@ import org.incido.compose.data.security.SecurityManager
import org.incido.compose.ui.theme.AllNoteColors import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.swatchBorderColor import org.incido.compose.ui.theme.swatchBorderColor
import org.incido.compose.ui.theme.toComposeColor import org.incido.compose.ui.theme.toComposeColor
import org.incido.domain.model.ChecklistItem
import org.incido.domain.model.Hashtag import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import java.io.File import java.io.File
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@@ -137,12 +166,6 @@ fun NoteEditorScreen(
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val ctx = LocalContext.current 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 // v0.3.1.0: camera permission + capture. The camera launcher is
// declared FIRST so the permission callback (below) can forward to it // declared FIRST so the permission callback (below) can forward to it
// without a Kotlin forward-reference error. // without a Kotlin forward-reference error.
@@ -216,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() { fun launchCamera() {
val (uri, _) = createTempCameraUri(ctx) val (uri, _) = createTempCameraUri(ctx)
if (uri == null) { if (uri == null) {
@@ -250,15 +306,30 @@ fun NoteEditorScreen(
initialFavorite = viewModel.initialFavorite, initialFavorite = viewModel.initialFavorite,
initialColor = viewModel.initialColor, initialColor = viewModel.initialColor,
initialTags = viewModel.initialHashtags, initialTags = viewModel.initialHashtags,
initialType = viewModel.initialType,
) )
} }
fun tryClose() { fun tryClose() {
// Drafts (new notes and draft editing) autosave every edit, so
// leaving is always lossless: flush any in-flight change and pop
// — no "Discard changes?" prompt.
if (viewModel.isDraftFlow) {
viewModel.flushDraft()
onClose()
return
}
if (isDirty()) showDiscardDialog = true else onClose() if (isDirty()) showDiscardDialog = true else onClose()
} }
BackHandler(enabled = true) { tryClose() } BackHandler(enabled = true) { tryClose() }
// Any other exit path (rotation, nav teardown) also flushes pending
// draft edits immediately.
DisposableEffect(viewModel) {
onDispose { viewModel.flushDraft() }
}
if (showDiscardDialog) { if (showDiscardDialog) {
AlertDialog( AlertDialog(
onDismissRequest = { showDiscardDialog = false }, onDismissRequest = { showDiscardDialog = false },
@@ -284,49 +355,28 @@ fun NoteEditorScreen(
contentWindowInsets = WindowInsets.systemBars.union(WindowInsets.ime), contentWindowInsets = WindowInsets.systemBars.union(WindowInsets.ime),
snackbarHost = { SnackbarHost(hostState = snackbarHost) }, snackbarHost = { SnackbarHost(hostState = snackbarHost) },
topBar = { topBar = {
// v0.3.6.1 Emergency Patch: left-anchored title sits against the back arrow // Left-anchored title (v0.3.6.1). Camera / attach-file / add-tag
// (CenterAlignedTopAppBar was crowded by the six right-side actions). // now live in the bottom action row below, so the remaining
// actions (favourite, save, overflow) always fit beside the
// title, even on narrow screens.
TopAppBar( TopAppBar(
title = { Text(if (state.isEditing) "Edit" else "New") }, title = {
Text(
text = when {
state.isDraft -> draftBarTitle(state)
state.isEditing -> "Edit note"
else -> "New note"
},
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
},
navigationIcon = { navigationIcon = {
IconButton(onClick = { tryClose() }) { IconButton(onClick = { tryClose() }) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
} }
}, },
actions = { 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 = {
// v0.3.4.0 hotfix: the SAF picker backgrounds
// the app; with Auto-Lock = Immediate the return
// used to lock the app and wipe the unsaved note.
securityManager?.beginExternalActivity()
filePickerLauncher.launch(arrayOf("*/*"))
}) {
Icon(
Icons.Filled.AttachFile,
contentDescription = "Attach file",
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,
)
}
IconButton(onClick = { viewModel.toggleFavorite() }) { IconButton(onClick = { viewModel.toggleFavorite() }) {
Icon( Icon(
imageVector = if (state.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline, imageVector = if (state.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
@@ -376,7 +426,7 @@ fun NoteEditorScreen(
// top edge of the note content (previously the row's // top edge of the note content (previously the row's
// `vertical = 4.dp` padding was dwarfed by the OutlinedTextField's // `vertical = 4.dp` padding was dwarfed by the OutlinedTextField's
// intrinsic top inset, making the lower gap appear far larger). // intrinsic top inset, making the lower gap appear far larger).
androidx.compose.foundation.layout.Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@@ -394,22 +444,79 @@ fun NoteEditorScreen(
) )
} }
} }
androidx.compose.foundation.layout.Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
OutlinedTextField( // v0.3.8.0 — structured list editors replace the free-text
value = state.content, // field whenever the note is a task / shopping list; the
onValueChange = viewModel::onContentChange, // rows live in NoteEditorUiState.items and the view-model
modifier = Modifier // keeps `content` synchronised with their serialisation.
.weight(1f) // v0.4.2.0 — voice recorder / media-player card pinned at
.fillMaxWidth() // the very top of the note body, directly above the text
.padding(horizontal = 16.dp) // field (which keeps working exactly like the plain-text
.focusRequester(focusRequester), // editor: title = first line).
placeholder = { Text("Write something…") }, if (state.type == NoteType.VOICE_NOTE) {
keyboardOptions = KeyboardOptions( val voicePending = state.pendingAttachments
capitalization = KeyboardCapitalization.Sentences, .lastOrNull { it.mimeType.startsWith("audio/") }
imeAction = ImeAction.Default, 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,
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.padding(horizontal = 16.dp)
.focusRequester(focusRequester),
placeholder = { Text("Write something…", style = editorFieldStyle()) },
textStyle = editorFieldStyle(),
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Default,
),
)
} else {
// Sticky running total — always visible above the rows
// while shopping (per Development Plan §6.1), summing
// the costs of checked (= in-basket) items.
if (state.type == NoteType.SHOPPING_LIST) {
ShoppingTotalBar(totalCents = Note.shoppingTotalCents(state.items))
}
ChecklistEditorBody(
modifier = Modifier.weight(1f),
header = state.listHeader,
items = state.items,
isShopping = state.type == NoteType.SHOPPING_LIST,
focusRequester = focusRequester,
onHeaderChange = viewModel::onHeaderChange,
onToggleItem = viewModel::setItemChecked,
onItemTextChange = viewModel::setItemText,
onItemQuantityChange = viewModel::setItemQuantity,
onItemCostChange = viewModel::setItemCost,
onRemoveItem = viewModel::removeListItem,
onAddItem = viewModel::addListItem,
onAddItemAfter = viewModel::addListItemAfter,
)
}
// v0.3.1.0: attachment thumbnail strip. Combines persisted // v0.3.1.0: attachment thumbnail strip. Combines persisted
// attachments (loaded via observeAttachments in the VM) with // attachments (loaded via observeAttachments in the VM) with
@@ -419,7 +526,6 @@ fun NoteEditorScreen(
if (state.attachments.isNotEmpty() || state.pendingAttachments.isNotEmpty()) { if (state.attachments.isNotEmpty() || state.pendingAttachments.isNotEmpty()) {
AttachmentStrip( AttachmentStrip(
persisted = state.attachments, persisted = state.attachments,
persistedBytes = emptyMap(), // resolved lazily in the viewer
persistedViewerIds = state.attachments.associate { it.id to ViewerAttachmentId.Persisted(it.id) }, persistedViewerIds = state.attachments.associate { it.id to ViewerAttachmentId.Persisted(it.id) },
persistedOpen = { id -> viewModel.openFullScreen(id) }, persistedOpen = { id -> viewModel.openFullScreen(id) },
persistedDelete = { id -> viewModel.deletePersistedAttachment(id) }, persistedDelete = { id -> viewModel.deletePersistedAttachment(id) },
@@ -441,6 +547,93 @@ fun NoteEditorScreen(
tags = state.hashtags, tags = state.hashtags,
onRemove = { viewModel.removeTag(it) }, onRemove = { viewModel.removeTag(it) },
) )
// Camera / attach-file / add-tag moved out of the title bar
// 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. 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
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = { launchCamera() }) {
Icon(
Icons.Filled.CameraAlt,
contentDescription = "Take photo",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
// v0.4.2.0 — voice-note toggle, first after Photo:
// converts the note to / from voice mode (mic permission
// is requested on the first tap into the mode).
IconButton(onClick = { toggleVoiceMode() }) {
Icon(
Icons.Filled.Mic,
contentDescription = "Voice note",
tint = if (state.type == NoteType.VOICE_NOTE)
MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = {
// v0.3.4.0 hotfix: the SAF picker backgrounds
// the app; with Auto-Lock = Immediate the return
// used to lock the app and wipe the unsaved note.
securityManager?.beginExternalActivity()
filePickerLauncher.launch(arrayOf("*/*"))
}) {
Icon(
Icons.Filled.AttachFile,
contentDescription = "Attach file",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
// 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,
contentDescription = "Task list",
tint = if (state.type == NoteType.TASK_LIST)
MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
// v0.3.8.0 — shopping-list toggle: like the task list
// but each row gains a number-pad Cost field and a
// sticky running total of checked items sits on top.
IconButton(onClick = { viewModel.convertTo(NoteType.SHOPPING_LIST) }) {
Icon(
Icons.Filled.ShoppingBasket,
contentDescription = "Shopping list",
tint = if (state.type == NoteType.SHOPPING_LIST)
MaterialTheme.colorScheme.primary
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,
)
}
}
} }
} }
@@ -466,14 +659,14 @@ fun NoteEditorScreen(
// v0.3.1.0: full-screen image viewer. // v0.3.1.0: full-screen image viewer.
state.fullScreenAttachmentId?.let { viewerId -> state.fullScreenAttachmentId?.let { viewerId ->
if (repoForViewer != null) { if (repository != null) {
val pendingBytes: ByteArray? = when (viewerId) { val pendingBytes: ByteArray? = when (viewerId) {
is ViewerAttachmentId.Pending -> state.pendingAttachmentBytes[viewerId.tempId] is ViewerAttachmentId.Pending -> state.pendingAttachmentBytes[viewerId.tempId]
is ViewerAttachmentId.Persisted -> null // viewer loads from DB is ViewerAttachmentId.Persisted -> null // viewer loads from DB
} }
ImageViewerScreen( ImageViewerScreen(
attachmentId = viewerId, attachmentId = viewerId,
repository = repoForViewer, repository = repository,
pendingBytes = pendingBytes, pendingBytes = pendingBytes,
onClose = { viewModel.closeFullScreen() }, onClose = { viewModel.closeFullScreen() },
) )
@@ -497,7 +690,6 @@ fun NoteEditorScreen(
@Composable @Composable
private fun AttachmentStrip( private fun AttachmentStrip(
persisted: List<org.incido.domain.model.NoteAttachment>, persisted: List<org.incido.domain.model.NoteAttachment>,
persistedBytes: Map<Long, ByteArray>,
persistedViewerIds: Map<Long, ViewerAttachmentId>, persistedViewerIds: Map<Long, ViewerAttachmentId>,
persistedOpen: (ViewerAttachmentId) -> Unit, persistedOpen: (ViewerAttachmentId) -> Unit,
persistedDelete: (Long) -> Unit, persistedDelete: (Long) -> Unit,
@@ -515,7 +707,6 @@ private fun AttachmentStrip(
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp), .padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 0.dp),
) { ) {
items(persisted, key = { it.id }) { att -> items(persisted, key = { it.id }) { att ->
AttachmentThumbnail( AttachmentThumbnail(
@@ -581,7 +772,7 @@ private fun AttachmentThumbnail(
// handler to bail with a misleading "Loading…" Toast forever. // handler to bail with a misleading "Loading…" Toast forever.
val lazyBytes by produceState<ByteArray?>(initialValue = null, key1 = attachmentId) { val lazyBytes by produceState<ByteArray?>(initialValue = null, key1 = attachmentId) {
if (pendingBytes == null && attachmentId != null && repository != null) { if (pendingBytes == null && attachmentId != null && repository != null) {
value = withContext(kotlinx.coroutines.Dispatchers.IO) { value = withContext(Dispatchers.IO) {
repository.getAttachmentBytes(attachmentId) repository.getAttachmentBytes(attachmentId)
} }
} }
@@ -671,7 +862,7 @@ private fun AttachmentThumbnail(
BitmapFactory.decodeByteArray(effectiveBytes, 0, effectiveBytes.size) BitmapFactory.decodeByteArray(effectiveBytes, 0, effectiveBytes.size)
} }
if (bitmap != null) { if (bitmap != null) {
androidx.compose.foundation.Image( Image(
bitmap = bitmap.asImageBitmap(), bitmap = bitmap.asImageBitmap(),
contentDescription = displayName, contentDescription = displayName,
contentScale = ContentScale.Crop, contentScale = ContentScale.Crop,
@@ -709,7 +900,7 @@ private fun AttachmentThumbnail(
@Composable @Composable
private fun FileTypePlaceholder(mimeType: String, displayName: String) { private fun FileTypePlaceholder(mimeType: String, displayName: String) {
androidx.compose.foundation.layout.Column( Column(
modifier = Modifier.fillMaxSize().padding(6.dp), modifier = Modifier.fillMaxSize().padding(6.dp),
verticalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
@@ -720,7 +911,7 @@ private fun FileTypePlaceholder(mimeType: String, displayName: String) {
tint = MaterialTheme.colorScheme.onSurfaceVariant, tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(28.dp), modifier = Modifier.size(28.dp),
) )
androidx.compose.foundation.layout.Spacer(Modifier.size(4.dp)) Spacer(Modifier.size(4.dp))
Text( Text(
text = displayName.take(14) + if (displayName.length > 14) "…" else "", text = displayName.take(14) + if (displayName.length > 14) "…" else "",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
@@ -791,6 +982,12 @@ private fun AddTagSheet(
onDismiss: () -> Unit, onDismiss: () -> Unit,
) { ) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
// Auto-focus the field so the keyboard is already up by the time
// the sheet settles — one less tap to add a tag.
val tagFocusRequester = remember { FocusRequester() }
LaunchedEffect(Unit) {
runCatching { tagFocusRequester.requestFocus() }
}
ModalBottomSheet( ModalBottomSheet(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
sheetState = sheetState, sheetState = sheetState,
@@ -809,7 +1006,9 @@ private fun AddTagSheet(
singleLine = true, singleLine = true,
leadingIcon = { Icon(Icons.Filled.Tag, contentDescription = null) }, leadingIcon = { Icon(Icons.Filled.Tag, contentDescription = null) },
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None), keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None),
modifier = Modifier.fillMaxWidth(), modifier = Modifier
.fillMaxWidth()
.focusRequester(tagFocusRequester),
) )
if (suggestions.isNotEmpty()) { if (suggestions.isNotEmpty()) {
Text( Text(
@@ -840,6 +1039,400 @@ private fun AddTagSheet(
} }
} }
// ---------------------------------------------------------------------
// v0.3.8.0: task / shopping list editor body
// ---------------------------------------------------------------------
/**
* Sticky running total for shopping lists — pinned above the rows so
* it stays visible at all times (Development Plan §6.1: "renders a
* sticky running total … updated live as prices are added/edited
* while shopping"). Sums the costs of CHECKED (= in-basket) items.
*/
@Composable
private fun ShoppingTotalBar(totalCents: Long) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceVariant)
.padding(horizontal = 16.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
Icons.Filled.ShoppingBasket,
contentDescription = null,
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.size(8.dp))
Text(
"Running total (qty × price, checked items)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.weight(1f))
Text(
text = Note.formatMoney(totalCents.toString()),
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary,
)
}
HorizontalDivider()
}
/**
* Structured body for task / shopping list notes: the title/preamble
* field, one [ChecklistItemRow] per item, and an "+ Add item" button.
* All mutations route through the view-model, which re-serialises the
* rows back into [NoteEditorUiState.content].
*/
@Composable
private fun ChecklistEditorBody(
modifier: Modifier = Modifier,
header: String,
items: List<ChecklistItem>,
isShopping: Boolean,
focusRequester: FocusRequester,
onHeaderChange: (String) -> Unit,
onToggleItem: (Int, Boolean) -> Unit,
onItemTextChange: (Int, String) -> Unit,
onItemQuantityChange: (Int, String) -> Unit,
onItemCostChange: (Int, String) -> Unit,
onRemoveItem: (Int) -> Unit,
onAddItem: () -> Unit,
onAddItemAfter: (Int) -> Unit,
) {
// Enter/Return in a task/product row inserts the next row and moves
// the cursor into it. The nonce re-fires the new row's focus effect
// even when the same index is targeted repeatedly.
var focusTarget by remember { mutableStateOf(-1 to 0L) }
LazyColumn(modifier = modifier.fillMaxWidth()) {
item {
// Title / preamble. Kept as plain lines above the checkbox
// rows so the list cards' title+body split keeps working.
EditorLineField(
value = header,
onValueChange = onHeaderChange,
placeholder = "Title",
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Next,
),
fieldModifier = Modifier.focusRequester(focusRequester),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 4.dp),
)
}
if (isShopping) {
item { ShoppingColumnHeader() }
}
itemsIndexed(items) { index, item ->
ChecklistItemRow(
item = item,
isShopping = isShopping,
focusOnCompose = focusTarget.first == index,
focusNonce = focusTarget.second,
onAddAfter = {
onAddItemAfter(index)
focusTarget = (index + 1) to focusTarget.second + 1
},
onToggle = { checked -> onToggleItem(index, checked) },
onTextChange = { text -> onItemTextChange(index, text) },
onQuantityChange = { qty -> onItemQuantityChange(index, qty) },
onCostChange = { cost -> onItemCostChange(index, cost) },
onRemove = { onRemoveItem(index) },
)
}
item {
TextButton(onClick = onAddItem) {
Icon(
Icons.Filled.Add,
contentDescription = null,
modifier = Modifier.size(18.dp),
)
Spacer(Modifier.size(6.dp))
Text("+ Add item")
}
}
}
}
/**
* Small "Product / Amnt. / Price" label line above the shopping rows.
* Mirrors [ChecklistItemRow]'s column geometry (checkbox spacer +
* weighted product + fixed qty/price widths) so the labels sit over
* their columns and the fields themselves stay uncluttered.
*/
@Composable
private fun ShoppingColumnHeader() {
val labelStyle = MaterialTheme.typography.labelSmall
val labelColor = MaterialTheme.colorScheme.onSurfaceVariant
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp),
) {
Spacer(Modifier.size(48.dp)) // checkbox column
Text(
"Product",
style = labelStyle,
color = labelColor,
modifier = Modifier
.weight(1f)
.padding(start = 16.dp, top = 16.dp),
)
Spacer(Modifier.size(6.dp))
Text(
"Amnt.",
style = labelStyle,
color = labelColor,
modifier = Modifier
.width(44.dp)
.padding(start = 4.dp, top = 16.dp),
)
Spacer(Modifier.size(6.dp))
Text(
"Price",
style = labelStyle,
color = labelColor,
modifier = Modifier
.width(56.dp)
.padding(start = 4.dp, top = 16.dp),
)
Spacer(Modifier.size(48.dp)) // remove-button column
}
}
/** One row: `[ ]` · Product (grows multi-line) · Qty · price · remove. */
@Composable
private fun ChecklistItemRow(
item: ChecklistItem,
isShopping: Boolean,
focusOnCompose: Boolean,
focusNonce: Long,
onAddAfter: () -> Unit,
onToggle: (Boolean) -> Unit,
onTextChange: (String) -> Unit,
onQuantityChange: (String) -> Unit,
onCostChange: (String) -> Unit,
onRemove: () -> Unit,
) {
// Enter on the row above lands the cursor here (see [focusOnCompose]
// in ChecklistEditorBody — the target is always a freshly inserted
// row, so focusing on first composition is enough).
val textFocus = remember { FocusRequester() }
LaunchedEffect(focusNonce) {
if (focusOnCompose) textFocus.requestFocus()
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp),
// Controls hug the field's vertical centre, so the checkbox,
// quantity / price columns and the remove ✕ travel with the
// row as a long entry wraps onto extra lines.
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(checked = item.checked, onCheckedChange = onToggle)
// The product field holds ANY text — numbers included. Quantity /
// price live in their own controls and an explicit `{q… p…}`
// storage marker, so a product called "Battery AA 3" can never
// bleed into the money fields.
EditorLineField(
value = item.text,
onValueChange = onTextChange,
// Shopping rows are labelled by the ShoppingColumnHeader
// above, so the fields stay empty-clean; plain task rows keep
// their single "Task" hint.
placeholder = if (isShopping) "" else "Task",
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Next,
),
// Enter/Return (IME "Next") creates the following row and
// moves the cursor there instead of tabbing sideways.
keyboardActions = KeyboardActions(onNext = { onAddAfter() }),
// Long text wraps onto more lines (field grows downward)
// instead of scrolling sideways out of view.
singleLine = false,
maxLines = 6,
fieldModifier = Modifier.focusRequester(textFocus),
modifier = Modifier.weight(1f),
)
if (isShopping) {
Spacer(Modifier.size(6.dp))
// Free-text quantity line. Blank means quantity 1: on focus
// loss it settles on "1" — display-only, storage keeps the
// blank default so {q1} never enters the saved text.
EditorLineField(
value = item.quantity,
onValueChange = onQuantityChange,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next,
),
formatUnfocused = { digits ->
if (digits.isEmpty()) "1" else digits
},
compact = true,
modifier = Modifier.width(44.dp),
)
Spacer(Modifier.size(6.dp))
// Supermarket-style cents entry: while focused the line shows
// the RAW digits typed ("123"); on focus loss it switches to
// the parsed money form ("$1.23"). Storage always keeps the
// raw cent digits, so totals / serialisation are unaffected.
EditorLineField(
value = item.cost,
onValueChange = onCostChange,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next,
),
// v0.4.x FIX: Enter/Return on Price now behaves exactly
// like Enter on the product field — a fresh row appears
// below and the cursor lands directly in its Product
// field. (A bare ImeAction.Next with no handler fell
// through to system focus traversal, which — the price
// being the row's last field inside a LazyColumn —
// wrapped the cursor all the way back to the Title.)
keyboardActions = KeyboardActions(onNext = { onAddAfter() }),
formatUnfocused = { digits ->
if (digits.isEmpty()) "" else "$" + Note.amountFromPriceDigits(digits)
},
compact = true,
modifier = Modifier.width(56.dp),
)
}
IconButton(onClick = onRemove) {
Icon(
Icons.Filled.Close,
contentDescription = "Remove item",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
/**
* v0.3.8.0 — the ~20 % smaller text style every editor surface uses
* (plain body, list header, task/product/quantity/price lines). The 16sp
* bodyLarge default made rows look squashed inside their fields.
*/
@Composable
private fun editorFieldStyle(): TextStyle =
MaterialTheme.typography.bodyMedium.copy(fontSize = 13.sp, lineHeight = 18.sp)
/**
* Top-bar label while a draft session is live. A draft that already
* carries a title just says "Draft"; one with NO title names itself
* after its kind — "Task List - (draft)", "Shopping List - (draft)" —
* mirroring the Drafts card title so both surfaces agree. (TEXT drafts
* take their title from the first content line, so they always land in
* 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.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)"
}
/**
* v0.3.8.0 — one plain underlined editing line, shared by every editable
* field in the editor (title, task/product, quantity, price). Replaces
* the mismatched outlined boxes with a single visual rhythm: same
* minimum height, same 13sp text, and a 2 dp bottom rule that brightens
* while the field has focus.
*
* [formatUnfocused] swaps in a parsed display ("$1.23") while the field
* has no focus — editing always shows the raw stored value ("123").
* [fieldModifier] targets the inner text field itself (focus requester).
*/
@Composable
private fun EditorLineField(
value: String,
onValueChange: (String) -> Unit,
placeholder: String = "",
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: KeyboardActions = KeyboardActions.Default,
formatUnfocused: ((String) -> String)? = null,
singleLine: Boolean = true,
maxLines: Int = 1,
compact: Boolean = false,
fieldModifier: Modifier = Modifier,
modifier: Modifier = Modifier,
) {
val fieldStyle = editorFieldStyle()
val hintColor = MaterialTheme.colorScheme.onSurfaceVariant
var focused by remember { mutableStateOf(false) }
val displayed =
if (focused || formatUnfocused == null) value else formatUnfocused(value)
// v0.4.x: EVERY field — product/task text, quantity, price, header —
// is one content-hugging BasicTextField with a hand-drawn 2 dp
// bottom rule (the [compact] flag no longer changes rendering). The
// Material 3 TextField's baked-in 56 dp minimum container made even
// an empty field look double-height and pinned the row's checkbox /
// price controls to the top edge; now a single line of text is a
// single line of field, and singleLine = false fields grow
// line-by-line up to [maxLines] as the entry wraps.
val indicatorColor = if (focused) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.outlineVariant
}
BasicTextField(
value = displayed,
onValueChange = onValueChange,
singleLine = singleLine,
maxLines = maxLines,
textStyle = fieldStyle.copy(color = MaterialTheme.colorScheme.onSurface),
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions,
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
decorationBox = { innerTextField ->
// The 10 / 4 dp block gives a slim underlined line a comfy
// tap target; the rule below lands on the block's bottom
// edge, so it always sits 4 dp under the LAST text line —
// one line or six.
Box(
modifier = Modifier.padding(top = 10.dp, bottom = 4.dp),
contentAlignment = Alignment.CenterStart,
) {
if (displayed.isEmpty() && placeholder.isNotEmpty()) {
Text(
text = placeholder,
style = fieldStyle,
color = hintColor,
maxLines = 1,
)
}
innerTextField()
}
},
// NOTE: the caller's [modifier] (weight(1f) for the product
// column, fixed 44/56.dp for quantity/price) MUST stay in the
// chain — dropping it lets fillMaxWidth() win the Row and
// swallow the neighbouring columns.
modifier = fieldModifier
.then(modifier)
.fillMaxWidth()
.padding(bottom = 2.dp)
.drawBehind {
drawRect(
color = indicatorColor,
topLeft = Offset(0f, size.height - 2.dp.toPx()),
size = Size(size.width, 2.dp.toPx()),
)
}
.onFocusEvent { focused = it.isFocused },
)
}
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// v0.3.1.0: helpers (camera URI + SAF display-name query) // v0.3.1.0: helpers (camera URI + SAF display-name query)
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
@@ -7,20 +7,28 @@ import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.incido.compose.IncidoApplication import org.incido.compose.IncidoApplication
import org.incido.compose.share.LinkedShareComposer import org.incido.compose.share.LinkedShareComposer
import org.incido.domain.model.ChecklistItem
import org.incido.domain.model.Hashtag import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
/** /**
@@ -33,6 +41,16 @@ data class NoteEditorUiState(
val color: NoteColor = NoteColor.NONE, val color: NoteColor = NoteColor.NONE,
/** Normalised, sorted ascending. */ /** Normalised, sorted ascending. */
val hashtags: List<String> = emptyList(), val hashtags: List<String> = emptyList(),
/** v0.3.8.0 — which editor surface the body uses (see [NoteType]). */
val type: NoteType = NoteType.TEXT,
/** v0.3.8.0 — title / preamble kept above the rows in list modes. */
val listHeader: String = "",
/** v0.3.8.0 — parsed checklist rows; always empty for [NoteType.TEXT]. */
val items: List<ChecklistItem> = emptyList(),
/** True while the add-tag sheet is open. */ /** True while the add-tag sheet is open. */
val isAddingTag: Boolean = false, val isAddingTag: Boolean = false,
/** Latest typing in the add-tag sheet (raw, before normalisation). */ /** Latest typing in the add-tag sheet (raw, before normalisation). */
@@ -75,12 +93,29 @@ data class NoteEditorUiState(
*/ */
val fullScreenAttachmentId: ViewerAttachmentId? = null, 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). */ /** `true` when editing an existing note (existing != null). */
val isEditing: Boolean get() = existing != null val isEditing: Boolean get() = existing != null
/**
* v0.4.2.0 — `true` once a voice take exists (staged pending or
* already persisted as an attachment).
*/
val hasVoiceTake: Boolean get() =
pendingAttachments.any { it.mimeType.startsWith("audio/") } ||
attachments.any { it.mimeType.startsWith("audio/") }
/**
* `true` while content is non-blank and not in the middle of
* saving. v0.4.2.0: a VOICE_NOTE may also save on the strength of
* its recording alone — the take IS the note's content.
*/
val canSave: Boolean get() =
(content.isNotBlank() || (type == NoteType.VOICE_NOTE && hasVoiceTake)) &&
!isSaving
/** `true` while this note is an auto-saved draft (see Note.isDraft). */
val isDraft: Boolean get() = existing?.isDraft == true
/** `true` when there's still room to add another tag. */ /** `true` when there's still room to add another tag. */
val canAddMoreTags: Boolean get() = hashtags.size < MAX_TAGS val canAddMoreTags: Boolean get() = hashtags.size < MAX_TAGS
@@ -90,10 +125,12 @@ data class NoteEditorUiState(
initialFavorite: Boolean, initialFavorite: Boolean,
initialColor: NoteColor, initialColor: NoteColor,
initialTags: List<String>, initialTags: List<String>,
initialType: NoteType,
): Boolean = content != initialContent || ): Boolean = content != initialContent ||
isFavorite != initialFavorite || isFavorite != initialFavorite ||
color != initialColor || color != initialColor ||
hashtags != initialTags hashtags != initialTags ||
type != initialType
companion object { companion object {
/** Hard cap on tags per note (matches Development Plan §6.1). */ /** Hard cap on tags per note (matches Development Plan §6.1). */
@@ -129,6 +166,7 @@ data class PendingAttachment(
val isImage: Boolean get() = mimeType.startsWith("image/") val isImage: Boolean get() = mimeType.startsWith("image/")
} }
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class NoteEditorViewModel( class NoteEditorViewModel(
private val repository: NoteRepository, private val repository: NoteRepository,
private val noteId: Long?, private val noteId: Long?,
@@ -178,6 +216,8 @@ class NoteEditorViewModel(
private set private set
var initialHashtags: List<String> = emptyList() var initialHashtags: List<String> = emptyList()
private set private set
var initialType: NoteType = NoteType.TEXT
private set
/** Internal: re-emits suggestions whenever the tag input changes. */ /** Internal: re-emits suggestions whenever the tag input changes. */
private val tagInputFlow = MutableStateFlow("") private val tagInputFlow = MutableStateFlow("")
@@ -190,21 +230,60 @@ class NoteEditorViewModel(
*/ */
private var nextPendingTempId: Long = -System.currentTimeMillis() private var nextPendingTempId: Long = -System.currentTimeMillis()
/**
* Draft autosave. A NEW note (or one still flagged as a draft) is
* persisted automatically: every edit lands in the DB ~400 ms after
* the last keystroke (coalesced so typing doesn't write per char),
* and [flushDraft] forces an immediate write whenever the editor
* closes or disposes. A crash can therefore only ever lose the last
* few keystrokes — never a whole draft.
*/
private val draftAutosave = noteId == null || noteId == 0L
/** True while this session autosaves: brand-new notes and draft editing. */
val isDraftFlow: Boolean
get() = draftAutosave || _state.value.isDraft
private var draftPersistInProgress = false
init {
// Signature-driven debounced autosave: whenever anything a draft
// persists changes, write the draft row shortly after.
viewModelScope.launch {
_state
.map { s ->
listOf(s.content, s.isFavorite, s.color, s.type, s.hashtags)
}
.distinctUntilChanged()
.debounce(DRAFT_AUTOSAVE_DEBOUNCE_MS)
.collect { persistDraftNow() }
}
}
init { init {
// Tag autocomplete — re-query on every keystroke (debounced upstream // Tag autocomplete — re-query on every keystroke (debounced upstream
// would be nice but ObjectBox is plenty fast for this size). // would be nice but ObjectBox is plenty fast for this size).
// Tag autocomplete. v0.3.8.0 FIX: the previous nested
// `tagInputFlow.collect { pool.collect { … } }` never resumed
// past the first keystroke — observeAllHashtags()/searchHashtags()
// are infinite callbackFlows, so the outer lambda suspended in
// the inner collect forever and typing never re-queried (the
// sheet only ever showed "+ Create"). flatMapLatest cancels the
// previous subscription per keystroke, and each fresh flow
// try-sends its snapshot immediately ⇒ live filtering.
viewModelScope.launch { viewModelScope.launch {
tagInputFlow.collect { raw -> tagInputFlow
val prefix = Hashtag.normalise(raw) .flatMapLatest { raw ->
val pool = if (prefix.isEmpty()) { val prefix = Hashtag.normalise(raw)
repository.observeAllHashtags() if (prefix.isEmpty()) {
} else { repository.observeAllHashtags()
repository.searchHashtags(prefix) } else {
repository.searchHashtags(prefix)
}
} }
pool.collect { suggestions -> .collect { suggestions ->
_state.update { it.copy(tagSuggestions = suggestions) } _state.update { it.copy(tagSuggestions = suggestions) }
} }
}
} }
// Live attachments: pump persisted rows into state.attachments. // Live attachments: pump persisted rows into state.attachments.
@@ -258,12 +337,29 @@ class NoteEditorViewModel(
} else { } else {
viewModelScope.launch { viewModelScope.launch {
repository.observeById(noteId).collect { note -> repository.observeById(noteId).collect { note ->
if (note != null && _state.value.isLoading) { val firstLoad = _state.value.isLoading
if (note != null && firstLoad) {
initialContent = note.content initialContent = note.content
initialFavorite = note.isFavorite initialFavorite = note.isFavorite
initialColor = note.color initialColor = note.color
initialHashtags = note.hashtags initialHashtags = note.hashtags
initialType = note.type
} }
// Draft echoes: emissions caused by our own autosave
// must not clobber in-progress edits mid-typing —
// the local state is authoritative while drafting.
if (note != null && note.isDraft && !firstLoad) return@collect
// Parse list rows once on first load; later DB
// emissions must not clobber in-progress edits.
val listSeed: Pair<String, List<ChecklistItem>>? =
if (note != null && firstLoad && note.type != NoteType.TEXT) {
Note.splitListContent(
note.content,
interpretCosts = note.type == NoteType.SHOPPING_LIST,
)
} else {
null
}
_state.update { _state.update {
it.copy( it.copy(
existing = note, existing = note,
@@ -271,6 +367,9 @@ class NoteEditorViewModel(
isFavorite = note?.isFavorite ?: it.isFavorite, isFavorite = note?.isFavorite ?: it.isFavorite,
color = note?.color ?: it.color, color = note?.color ?: it.color,
hashtags = note?.hashtags ?: it.hashtags, hashtags = note?.hashtags ?: it.hashtags,
type = note?.type ?: it.type,
listHeader = listSeed?.first ?: it.listHeader,
items = listSeed?.second ?: it.items,
isLoading = false, isLoading = false,
) )
} }
@@ -292,17 +391,18 @@ class NoteEditorViewModel(
} }
fun openAddTagSheet() { fun openAddTagSheet() {
_state.update { // v0.3.8.0 FIX: push the empty query through the suggestion
it.copy( // pipeline FIRST so the flatMapLatest collector re-emits every
isAddingTag = true, // existing tag (most-used first) while the sheet opens — the
tagInput = "", // old code just cleared the list to emptyList() here and the
tagSuggestions = emptyList(), // stuck collector never refilled it.
) tagInputFlow.value = ""
} _state.update { it.copy(isAddingTag = true, tagInput = "") }
} }
fun closeAddTagSheet() { fun closeAddTagSheet() {
_state.update { it.copy(isAddingTag = false, tagInput = "", tagSuggestions = emptyList()) } tagInputFlow.value = ""
_state.update { it.copy(isAddingTag = false, tagInput = "") }
} }
fun onTagInputChange(raw: String) { fun onTagInputChange(raw: String) {
@@ -330,6 +430,169 @@ class NoteEditorViewModel(
_state.update { it.copy(hashtags = it.hashtags.filterNot { tag -> tag == normalised }) } _state.update { it.copy(hashtags = it.hashtags.filterNot { tag -> tag == normalised }) }
} }
// ---- v0.3.8.0 task / shopping list editing ----
/**
* Keep the [NoteEditorUiState.items] / [NoteEditorUiState.listHeader]
* rows and the derived [NoteEditorUiState.content] in step, so the
* save path, dirty-check, search preview, and `canSave` gate all
* keep working off the single content string.
*/
private fun NoteEditorUiState.withListEdits(
header: String = this.listHeader,
items: List<ChecklistItem>,
): NoteEditorUiState = copy(
listHeader = header,
items = items,
content = Note.serializeListContent(header, items, type),
)
private fun List<ChecklistItem>.patched(
index: Int,
transform: (ChecklistItem) -> ChecklistItem,
): List<ChecklistItem> = mapIndexed { i, item ->
if (i == index) transform(item) else item
}
/**
* Convert the body to [target]; tapping the already-active mode
* converts back to [NoteType.TEXT]. Text moves losslessly between
* the plain editor and the checkbox serialisation — costs are only
* stored while the note is a shopping list (converting to a task
* list folds each cost back into the item text).
*/
fun convertTo(target: NoteType) {
_state.update { s ->
val next = if (s.type == target) NoteType.TEXT else target
if (next == NoteType.VOICE_NOTE) {
// v0.4.2.0 — voice mode keeps the plain text field
// (title = first line) exactly like TEXT; a list body
// folds back to its plain form first. The recording is
// NOT body content — it's an ordinary audio attachment,
// so it also survives converting back to plain text.
val source =
if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) s.content
else Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
s.copy(
type = next,
listHeader = "",
items = emptyList(),
content = source,
)
} else if (next == NoteType.TEXT) {
// Content already holds the serialised `- [ ]` rows;
// just drop out of the structured editor (the inline
// GFM checklist rendering from v0.2.0.0 still applies).
s.copy(type = NoteType.TEXT, listHeader = "", items = emptyList())
} else {
val source = if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) {
s.content
} else {
// Serialise through the FOLDED legacy form (plain
// "Milk 2 x 3.90" lines, never `{q…p…}` markers) so
// structured values survive the trip and re-parse
// cleanly under the target mode's rules.
Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
}
val (header, parsedRaw) = Note.splitListContent(
source,
interpretCosts = next == NoteType.SHOPPING_LIST,
)
val parsed = if (parsedRaw.isEmpty()) listOf(ChecklistItem("")) else parsedRaw
s.copy(
type = next,
listHeader = header,
items = parsed,
content = Note.serializeListContent(header, parsed, next),
)
}
}
_state.update {
it.copy(
snackbar = when (it.type) {
NoteType.TASK_LIST -> "Task list mode — first line stays the title."
NoteType.SHOPPING_LIST -> "Shopping list mode — check an item once it's in your basket."
NoteType.VOICE_NOTE -> "Voice note mode — record with the mic card above the text."
else -> "Back to plain text."
},
)
}
}
fun onHeaderChange(value: String) {
_state.update { it.withListEdits(header = value, items = it.items) }
}
fun addListItem() {
_state.update { s ->
if (s.type == NoteType.TEXT) return@update s
s.withListEdits(items = s.items + ChecklistItem(""))
}
}
/**
* Insert a blank row right after [index] (or append it on the last
* row). Driven by Enter/Return in the task/product field so the
* writer flows downward into a fresh row instead of tabbing sideways.
*/
fun addListItemAfter(index: Int) {
_state.update { s ->
if (s.type == NoteType.TEXT) return@update s
if (index !in s.items.indices) return@update s
val updated = s.items.toMutableList().also { it.add(index + 1, ChecklistItem("")) }
s.withListEdits(items = updated)
}
}
fun removeListItem(index: Int) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.filterIndexed { i, _ -> i != index })
}
}
fun setItemChecked(index: Int, checked: Boolean) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(checked = checked) })
}
}
fun setItemText(index: Int, text: String) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(text = text) })
}
}
/**
* Price field input — POS style: everything is reduced to cents
* digits ("199" ⇒ $1.99, separators typed or pasted are stripped).
*/
fun setItemCost(index: Int, rawCost: String) {
val sanitized = Note.normalisePriceInput(rawCost)
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(cost = sanitized) })
}
}
/**
* Quantity line input (free-text digits); blank means the default 1.
*
* v0.3.8.0: "1" now stays stored as "1" — the field is free text, so
* the typed digit must remain visible. The serialiser already omits
* `{q1}` and cards only show "×qty" when the quantity is > 1, so this
* is storage-neutral. "0" / blank normalise to "" (meaning 1).
*/
fun setItemQuantity(index: Int, rawQty: String) {
val stored = Note.normaliseQuantity(rawQty)
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(quantity = stored) })
}
}
fun consumeSnackbar() { fun consumeSnackbar() {
_state.update { it.copy(snackbar = null) } _state.update { it.copy(snackbar = null) }
} }
@@ -397,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]. */ /** Open the full-screen image viewer for [viewerId]. */
fun openFullScreen(viewerId: ViewerAttachmentId) { fun openFullScreen(viewerId: ViewerAttachmentId) {
_state.update { it.copy(fullScreenAttachmentId = viewerId) } _state.update { it.copy(fullScreenAttachmentId = viewerId) }
@@ -409,22 +712,81 @@ class NoteEditorViewModel(
// ---- save ---- // ---- save ----
/**
* Force-write the current draft state to the DB right now — used
* when the editor closes / disposes so pending edits never sit in
* the debounce window. No-op for non-draft sessions and blank
* content (see [persistDraftNow]).
*/
fun flushDraft() {
viewModelScope.launch { persistDraftNow() }
}
/** Write the draft row if this session is in the draft lifecycle. */
private suspend fun persistDraftNow() {
val current = _state.value
if (current.isLoading || current.isSaving) return
if (draftPersistInProgress) return
val baseNote = current.existing
if (baseNote != null && !baseNote.isDraft) return // already published
if (!draftAutosave && baseNote?.isDraft != true) return
if (current.content.isBlank()) return
draftPersistInProgress = true
try {
val now = System.currentTimeMillis()
val draft = baseNote?.copy(
content = current.content,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
isDraft = true,
) ?: Note(
content = current.content,
createdAt = now,
updatedAt = now,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
isDraft = true,
)
val previous = baseNote?.hashtags.orEmpty().toSet()
val currentSet = current.hashtags.toSet()
val saved = repository.saveNoteWithHashtags(
note = draft,
hashtagsToAdd = currentSet - previous,
hashtagsToRemove = previous - currentSet,
)
// Adopt the persisted row so every later write updates the
// SAME note — one draft per editing session.
_state.update {
it.copy(existing = saved.copy(isDraft = true, hashtags = current.hashtags))
}
} finally {
draftPersistInProgress = false
}
}
fun save(onDone: () -> Unit) { fun save(onDone: () -> Unit) {
val current = _state.value val current = _state.value
if (!current.canSave) return if (!current.canSave) return
_state.update { it.copy(isSaving = true) } _state.update { it.copy(isSaving = true) }
viewModelScope.launch { viewModelScope.launch {
val baseNote = current.existing val baseNote = current.existing
// An explicit Save PUBLISHES the note: a draft row loses
// its flag here and joins the normal views for good.
val toPersist = baseNote?.copy( val toPersist = baseNote?.copy(
content = current.content, content = current.content,
isFavorite = current.isFavorite, isFavorite = current.isFavorite,
color = current.color, color = current.color,
type = current.type,
isDraft = false,
) ?: Note( ) ?: Note(
content = current.content, content = current.content,
createdAt = System.currentTimeMillis(), createdAt = System.currentTimeMillis(),
updatedAt = System.currentTimeMillis(), updatedAt = System.currentTimeMillis(),
isFavorite = current.isFavorite, isFavorite = current.isFavorite,
color = current.color, color = current.color,
type = current.type,
) )
val previous = baseNote?.hashtags.orEmpty().toSet() val previous = baseNote?.hashtags.orEmpty().toSet()
val currentSet = current.hashtags.toSet() val currentSet = current.hashtags.toSet()
@@ -447,7 +809,25 @@ class NoteEditorViewModel(
} }
} }
} }
_state.update { it.copy(isSaving = false, pendingAttachments = emptyList(), pendingAttachmentBytes = emptyMap()) } _state.update {
it.copy(
// v0.4.x FIX: adopt the PUBLISHED row into the UI
// state. Without this the state still reported
// isDraft = true, and the flushDraft() fired by the
// editor's disposal immediately re-persisted the
// note as a draft — every confirmed note landed in
// Drafts. With the published row adopted, the
// already-published guard in persistDraftNow() turns
// that flush into a no-op.
existing = saved.copy(
isDraft = false,
hashtags = current.hashtags,
),
isSaving = false,
pendingAttachments = emptyList(),
pendingAttachmentBytes = emptyMap(),
)
}
onDone() onDone()
} }
} }
@@ -463,6 +843,9 @@ class NoteEditorViewModel(
} }
companion object { companion object {
/** Typing-pause before a draft autosave fires (ms). */
const val DRAFT_AUTOSAVE_DEBOUNCE_MS = 400L
fun factory( fun factory(
noteId: Long?, noteId: Long?,
initialSharedText: String? = null, initialSharedText: String? = null,
@@ -0,0 +1,539 @@
package org.incido.compose.ui.editor
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.FiberManualRecord
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.incido.compose.data.security.SecurityManager
import org.incido.domain.model.NoteAttachment
import org.incido.domain.repository.NoteRepository
import java.io.File
import java.util.Locale
/**
* v0.4.2.0 — the voice-note body section: sits at the very top of the
* note body (above the text field) whenever the editor is in
* [org.incido.domain.model.NoteType.VOICE_NOTE] mode.
*
* Three states:
* * **No take** — "tap to record" card.
* * **Recording** — live elapsed timer with stop / discard controls.
* * **Take ready** (pending *or* persisted) — media player bar with
* play/pause, seek, a **Download** action that copies the file to
* the system Downloads folder, and a delete action (re-record via
* the mic button — the ViewModel replaces the old take when a new
* recording lands).
*
* The take rides the existing attachment pipeline: while the note is
* unsaved it is a [PendingAttachment] whose bytes live in the UI
* state; after save it is an ordinary `audio/ogg` attachment row
* (encrypted at rest like every other attachment, backed up with the
* note, and still visible in the attachment strip below).
*/
@Composable
fun VoiceNoteSection(
/** Pending (unsaved) voice take, or null. */
voicePending: PendingAttachment?,
/** Bytes of the pending take (null while still unrecorded). */
voicePendingBytes: ByteArray?,
/** Persisted voice take of a saved note, or null. */
voicePersisted: NoteAttachment?,
/** Source of persisted bytes (lazy-loaded by the player). */
repository: NoteRepository?,
/** Checked on every record tap — reflects RECORD_AUDIO state. */
hasMicPermission: () -> Boolean,
/** Launches the RECORD_AUDIO permission request. */
onRequestPermission: () -> Unit,
/** A finished recording is ready to stage/persist (replaces any old take);
* second arg is the recorder's actual mime (`audio/ogg`, or `audio/mp4` on API 26–28). */
onTakeRecorded: (ByteArray, String) -> Unit,
/** Remove the current take (pending or persisted). */
onDeleteTake: () -> Unit,
/** Suppress auto-lock around the download share-sheet round-trip (API < 29). */
securityManager: SecurityManager?,
modifier: Modifier = Modifier,
) {
val ctx = LocalContext.current
val recorder = remember { VoiceRecorder() }
var isRecording by remember { mutableStateOf(false) }
var elapsedMs by remember { mutableStateOf(0L) }
// Abandon an in-flight take if the editor tears down mid-recording
// (back navigation, config change) — no orphan temp files.
DisposableEffect(Unit) {
onDispose { recorder.cancel() }
}
// Live tick for the recording timer.
LaunchedEffect(isRecording) {
if (!isRecording) return@LaunchedEffect
val startedAt = android.os.SystemClock.elapsedRealtime() - elapsedMs
while (isRecording) {
elapsedMs = android.os.SystemClock.elapsedRealtime() - startedAt
delay(100)
}
}
fun startRecording() {
if (!hasMicPermission()) {
onRequestPermission()
return
}
try {
recorder.start(ctx)
elapsedMs = 0L
isRecording = true
} catch (e: Exception) {
Toast.makeText(ctx, "Couldn't start recording", Toast.LENGTH_SHORT).show()
}
}
fun stopRecording() {
val bytes = recorder.stopAndReadBytes()
isRecording = false
if (bytes == null) {
Toast.makeText(ctx, "Recording failed", Toast.LENGTH_SHORT).show()
} else {
onTakeRecorded(bytes, recorder.recordedMimeType)
}
}
val hasTake = voicePending != null || voicePersisted != null
// Persisted bytes lazy-load on demand (same pattern as the
// attachment thumbnails) so the StateFlow never holds the blob.
val lazyPersistedBytes by produceState<ByteArray?>(
initialValue = null,
key1 = voicePersisted?.id,
) {
value = if (voicePersisted != null && repository != null) {
withContext(Dispatchers.IO) { repository.getAttachmentBytes(voicePersisted.id) }
} else {
null
}
}
val takeBytes: ByteArray? = if (voicePending != null) voicePendingBytes else lazyPersistedBytes
val takeName: String =
voicePending?.displayName ?: voicePersisted?.displayName ?: "voice_note.opus"
val takeMime: String =
voicePending?.mimeType ?: voicePersisted?.mimeType ?: "audio/ogg"
val takeKey: Long = voicePending?.tempId ?: voicePersisted?.id ?: 0L
Column(
modifier = modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
.border(
1.dp,
MaterialTheme.colorScheme.outlineVariant,
RoundedCornerShape(12.dp),
)
.background(
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
RoundedCornerShape(12.dp),
)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
when {
isRecording -> Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
Icons.Filled.FiberManualRecord,
contentDescription = null,
tint = Color(0xFFD32F2F),
modifier = Modifier.size(16.dp),
)
Spacer(Modifier.width(8.dp))
Text(
formatVoiceTime(elapsedMs),
style = MaterialTheme.typography.titleMedium,
)
Spacer(Modifier.weight(1f))
IconButton(onClick = { stopRecording() }) {
Icon(
Icons.Filled.Stop,
contentDescription = "Stop recording",
tint = MaterialTheme.colorScheme.primary,
)
}
IconButton(onClick = {
recorder.cancel()
isRecording = false
}) {
Icon(
Icons.Filled.Close,
contentDescription = "Discard recording",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
hasTake && takeBytes == null -> Row(
modifier = Modifier
.fillMaxWidth()
.height(48.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
Text(
"Loading audio\u2026",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
hasTake && takeBytes != null -> VoicePlayerBar(
bytes = takeBytes,
mimeType = takeMime,
sourceKey = takeKey,
takeName = takeName,
onDelete = onDeleteTake,
onDownload = { saveVoiceTakeToDevice(ctx, securityManager, takeName, takeMime, takeBytes) },
onRecordAgain = { startRecording() },
)
else -> Row(
modifier = Modifier
.fillMaxWidth()
.clickable { startRecording() }
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Box(
modifier = Modifier
.size(40.dp)
.background(
MaterialTheme.colorScheme.primary.copy(alpha = 0.12f),
CircleShape,
),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.Mic,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(22.dp),
)
}
Text(
"Tap to record a voice note",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
/**
* Media-player bar for a recorded take: play/pause + seek + elapsed /
* total, plus download, re-record and delete actions. Backed by the
* platform [MediaPlayer] — the bytes are written to a small cache file
* (`cacheDir/voice_play/`) because MediaPlayer plays paths, not
* in-memory blobs; the file is rewritten whenever a new take arrives
* and is disposable cache data.
*/
@Composable
private fun VoicePlayerBar(
bytes: ByteArray,
mimeType: String,
sourceKey: Long,
takeName: String,
onDelete: () -> Unit,
onDownload: () -> Unit,
onRecordAgain: () -> Unit,
) {
val ctx = LocalContext.current
// Materialise the take into a playable cache file.
val playPath by produceState<String?>(
initialValue = null,
key1 = sourceKey,
key2 = bytes,
) {
value = withContext(Dispatchers.IO) {
runCatching {
val dir = File(ctx.cacheDir, "voice_play").apply { mkdirs() }
val ext = if (mimeType == "audio/ogg") "opus" else "m4a"
val file = File(dir, "take_$sourceKey.$ext")
file.writeBytes(bytes)
file.absolutePath
}.getOrNull()
}
}
var player by remember(sourceKey) { mutableStateOf<MediaPlayer?>(null) }
var prepared by remember(sourceKey) { mutableStateOf(false) }
var isPlaying by remember(sourceKey) { mutableStateOf(false) }
var positionMs by remember(sourceKey) { mutableStateOf(0L) }
var durationMs by remember(sourceKey) { mutableStateOf(0L) }
var dragMs by remember(sourceKey) { mutableStateOf<Float?>(null) }
DisposableEffect(playPath) {
val path = playPath
if (path == null) {
onDispose { }
} else {
val mp = MediaPlayer()
player = mp
mp.setOnPreparedListener {
durationMs = it.duration.toLong()
prepared = true
}
mp.setOnCompletionListener {
isPlaying = false
positionMs = durationMs
}
mp.setOnErrorListener { _, _, _ -> true }
runCatching {
mp.setDataSource(path)
mp.prepareAsync()
}
onDispose {
runCatching { mp.release() }
player = null
}
}
}
// Keep the slider in step while playing.
LaunchedEffect(isPlaying, prepared) {
if (!isPlaying || !prepared) return@LaunchedEffect
while (isPlaying) {
player?.let { positionMs = it.currentPosition.toLong() }
delay(200)
}
}
Column(modifier = Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = {
val mp = player ?: return@IconButton
if (!prepared) return@IconButton
if (mp.isPlaying) {
mp.pause()
isPlaying = false
} else {
if (positionMs >= durationMs && durationMs > 0) {
mp.seekTo(0)
positionMs = 0
}
mp.start()
isPlaying = true
}
},
enabled = prepared,
) {
Icon(
imageVector = if (isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow,
contentDescription = if (isPlaying) "Pause" else "Play",
tint = MaterialTheme.colorScheme.primary,
)
}
Text(
text = formatVoiceTime((dragMs ?: positionMs.toFloat()).toLong()),
style = MaterialTheme.typography.labelMedium,
)
Slider(
value = (dragMs ?: positionMs.toFloat()).coerceIn(
0f,
durationMs.coerceAtLeast(1).toFloat(),
),
onValueChange = { dragMs = it },
onValueChangeFinished = {
val target = dragMs
if (target != null) {
dragMs = null
val seek = target.toInt()
player?.let { mp ->
if (prepared) {
mp.seekTo(seek)
positionMs = seek.toLong()
}
}
}
},
valueRange = 0f..durationMs.coerceAtLeast(1).toFloat(),
enabled = prepared,
modifier = Modifier
.weight(1f)
.padding(horizontal = 4.dp),
)
Text(
text = formatVoiceTime(durationMs),
style = MaterialTheme.typography.labelMedium,
)
// Download = save a copy to the system Downloads folder
// (pre-Q devices get the share sheet, which reaches the
// same destinations).
IconButton(onClick = onDownload) {
Icon(
Icons.Filled.Download,
contentDescription = "Download recording",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = onRecordAgain) {
Icon(
Icons.Filled.Mic,
contentDescription = "Re-record (replaces current take)",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = onDelete) {
Icon(
Icons.Filled.Delete,
contentDescription = "Delete recording",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Text(
text = takeName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
/**
* Save the take to the system Downloads folder via MediaStore (API 29+,
* no storage permission needed). On API 26–28 — where MediaStore
* Downloads doesn't exist — fall back to the v0.3.1.3 FileProvider
* outbox + share sheet, which reaches the same destinations plus
* "Save to device" handlers.
*/
private fun saveVoiceTakeToDevice(
ctx: Context,
securityManager: SecurityManager?,
displayName: String,
mimeType: String,
bytes: ByteArray,
) {
val safeName = displayName
.replace(Regex("[/\\\\:*?\"<>|]"), "_")
.ifEmpty { "voice_note.opus" }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val saved = runCatching {
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, safeName)
put(MediaStore.Downloads.MIME_TYPE, mimeType)
put(
MediaStore.Downloads.RELATIVE_PATH,
Environment.DIRECTORY_DOWNLOADS,
)
}
val uri = ctx.contentResolver.insert(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
values,
) ?: return@runCatching false
ctx.contentResolver.openOutputStream(uri)?.use { out ->
out.write(bytes)
} ?: return@runCatching false
true
}.getOrDefault(false)
if (saved) {
Toast.makeText(ctx, "Saved to Downloads", Toast.LENGTH_SHORT).show()
return
}
// MediaStore refused (provider hiccup) — fall through to the
// share sheet as the last resort.
}
runCatching {
val outbox = File(ctx.cacheDir, "open_outbox").apply { mkdirs() }
val tmp = File(outbox, "dl_${System.currentTimeMillis()}_$safeName")
tmp.writeBytes(bytes)
val uri = FileProvider.getUriForFile(ctx, "${ctx.packageName}.fileprovider", tmp)
val send = Intent(Intent.ACTION_SEND).apply {
type = mimeType
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
// Auto-Lock = Immediate must not fire while the chooser is up
// (same v0.3.4.0 hotfix as the attachment viewer).
securityManager?.beginExternalActivity()
ctx.startActivity(Intent.createChooser(send, "Save recording"))
}.onFailure {
Toast.makeText(ctx, "Couldn't save recording", Toast.LENGTH_SHORT).show()
}
}
/** ms → "m:ss" (or "h:mm:ss" past an hour). */
internal fun formatVoiceTime(ms: Long): String {
val totalSec = ms / 1000
val h = totalSec / 3600
val m = (totalSec % 3600) / 60
val s = totalSec % 60
return if (h > 0) {
String.format(Locale.US, "%d:%02d:%02d", h, m, s)
} else {
String.format(Locale.US, "%d:%02d", m, s)
}
}
@@ -0,0 +1,132 @@
package org.incido.compose.ui.editor
import android.content.Context
import android.media.MediaRecorder
import android.os.Build
import java.io.File
import java.io.IOException
/**
* v0.4.2.0 — thin MediaRecorder wrapper for voice notes.
*
* Records Opus audio in an Ogg container (`.opus`, mime `audio/ogg`)
* at 32 kbps, single channel, 48 kHz — tiny files, excellent speech
* quality, and produced by the platform MediaRecorder with no extra
* dependencies (the app stays dependency-light per Development Plan
* privacy/offline rules). Opus-in-Ogg output via MediaRecorder is
* public API only from API 29, so API 26–28 devices keep the previous
* AAC/MP4 path (`.m4a`, mime `audio/mp4`); [recordedMimeType] reports
* which container [start] actually used.
*
* Note: the MediaRecorder surface exposes no encoder knobs for Opus
* frame size or complexity, so both stay at platform defaults (Opus
* on Android encodes 20 ms frames); hitting 120 ms frames /
* complexity 10 would require bundling native libopus — deferred.
*
* The take lands in a temp file under `cacheDir/voice_rec/`; the
* caller reads it back as a [ByteArray] on [stopAndReadBytes] and the
* temp file is deleted immediately — the bytes then ride the ordinary
* attachment pipeline into ObjectBox (same lifecycle as the camera
* outbox from v0.3.1.0).
*
* Not thread-safe: drive it from the main thread only.
*/
class VoiceRecorder {
private var recorder: MediaRecorder? = null
private var outFile: File? = null
private var opus = false
/** True between a successful [start] and the matching stop/cancel. */
val isRecording: Boolean get() = recorder != null
/**
* Mime type of the container [start] actually used — `audio/ogg`
* (Opus) on API 29+, `audio/mp4` (AAC) on API 26–28. Valid after
* any successful [start]; callers use it to tag the finished take.
*/
val recordedMimeType: String get() = if (opus) "audio/ogg" else "audio/mp4"
/**
* Start capturing from the mic into a fresh temp file.
* Throws [IOException] / [RuntimeException] when the mic is busy,
* the permission was revoked mid-session, or the device has none —
* callers should catch and surface a snackbar.
*/
@Suppress("DEPRECATION")
fun start(context: Context) {
if (recorder != null) return
// Opus-in-Ogg via MediaRecorder is public API only from API 29
// (minSdk is 26), so older devices keep the AAC/MP4 path.
val useOpus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
val dir = File(context.cacheDir, "voice_rec").apply { mkdirs() }
val file = File(
dir,
"take_${System.currentTimeMillis()}" + if (useOpus) ".opus" else ".m4a",
)
val rec = MediaRecorder()
try {
rec.apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
if (useOpus) {
setOutputFormat(MediaRecorder.OutputFormat.OGG)
setAudioEncoder(MediaRecorder.AudioEncoder.OPUS)
setAudioEncodingBitRate(32_000) // 32 kbps
setAudioChannels(1) // single channel
setAudioSamplingRate(48_000) // Opus native rate
} else {
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setAudioEncodingBitRate(96_000)
setAudioSamplingRate(44_100)
}
setOutputFile(file.absolutePath)
prepare()
start()
}
recorder = rec
outFile = file
opus = useOpus
} catch (e: Exception) {
rec.release()
file.delete()
throw e
}
}
/**
* Stop the capture, read the recorded bytes, and delete the temp
* file. Returns `null` when nothing was recorded or the encoder
* failed. Always safe to call — a no-op while idle.
*/
fun stopAndReadBytes(): ByteArray? {
val rec = recorder ?: return null
recorder = null
val file = outFile
outFile = null
return try {
rec.stop()
val bytes = file?.readBytes()
bytes?.takeIf { it.isNotEmpty() }
} catch (e: RuntimeException) {
null
} finally {
rec.release()
file?.delete()
}
}
/**
* Abandon the in-flight take without reading it (the ✕ while
* recording). Always safe to call — a no-op while idle.
*/
fun cancel() {
val rec = recorder ?: return
recorder = null
val file = outFile
outFile = null
runCatching { rec.stop() } // stop() throws if nothing was captured
rec.release()
file?.delete()
}
}
@@ -27,15 +27,20 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AttachFile import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.CheckBox import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Menu 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.MoreVert
import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material.icons.filled.PhotoCamera
import androidx.compose.material.icons.filled.Restore import androidx.compose.material.icons.filled.Restore
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.ShoppingBasket
import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.outlined.StarOutline import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.CenterAlignedTopAppBar
@@ -49,6 +54,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -58,6 +64,8 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
@@ -73,6 +81,7 @@ import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteFilter import org.incido.domain.model.NoteFilter
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
/** /**
@@ -122,9 +131,49 @@ fun NoteListScreen(
) { ) {
val state by viewModel.uiState.collectAsStateWithLifecycle() val state by viewModel.uiState.collectAsStateWithLifecycle()
var localQuery by remember { mutableStateOf("") } var localQuery by remember { mutableStateOf("") }
var showEmptyTrashDialog by remember { mutableStateOf(false) }
val searchFocusRequester = remember { FocusRequester() }
LaunchedEffect(filterMode) { viewModel.setFilter(filterMode) } LaunchedEffect(filterMode) { viewModel.setFilter(filterMode) }
// Auto-focus the search field when it opens so typing can start
// immediately.
LaunchedEffect(state.isSearchActive) {
if (state.isSearchActive) {
runCatching { searchFocusRequester.requestFocus() }
}
}
// "Empty Trash" confirmation. The whole trash goes, attachments
// included — say so plainly before the one tap that does it.
if (showEmptyTrashDialog) {
AlertDialog(
onDismissRequest = { showEmptyTrashDialog = false },
title = { Text("Empty Trash?") },
text = {
Text(
"Every note in the Trash, including attachments, will be " +
"permanently deleted. This cannot be undone.",
)
},
confirmButton = {
TextButton(
onClick = {
showEmptyTrashDialog = false
viewModel.emptyTrash()
},
) {
Text("Empty Trash", color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { showEmptyTrashDialog = false }) {
Text("Cancel")
}
},
)
}
Scaffold( Scaffold(
topBar = { topBar = {
CenterAlignedTopAppBar( CenterAlignedTopAppBar(
@@ -148,6 +197,17 @@ fun NoteListScreen(
Icon(Icons.Default.Search, contentDescription = "Search notes") Icon(Icons.Default.Search, contentDescription = "Search notes")
} }
} }
// Trash view gains an "Empty Trash" button whenever it
// holds something; the destructive action is confirmed
// through a dialog before anything is touched.
if (filterMode == NoteFilter.Trash && state.notes.isNotEmpty()) {
IconButton(onClick = { showEmptyTrashDialog = true }) {
Icon(
Icons.Default.DeleteForever,
contentDescription = "Empty trash",
)
}
}
}, },
) )
}, },
@@ -171,10 +231,21 @@ fun NoteListScreen(
Text(if (filterMode == NoteFilter.Trash) "Search trash…" else "Search notes…") Text(if (filterMode == NoteFilter.Trash) "Search trash…" else "Search notes…")
}, },
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) }, leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
trailingIcon = {
if (localQuery.isNotEmpty()) {
IconButton(onClick = {
localQuery = ""
viewModel.onQueryChange("")
}) {
Icon(Icons.Default.Close, contentDescription = "Clear search")
}
}
},
singleLine = true, singleLine = true,
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp), .padding(horizontal = 16.dp, vertical = 8.dp)
.focusRequester(searchFocusRequester),
) )
} }
@@ -209,8 +280,10 @@ private fun screenTitle(filter: NoteFilter): String = when (filter) {
NoteFilter.Home -> "Incido" NoteFilter.Home -> "Incido"
NoteFilter.Favorites -> "Favorites" NoteFilter.Favorites -> "Favorites"
NoteFilter.Untagged -> "Untagged" NoteFilter.Untagged -> "Untagged"
NoteFilter.Drafts -> "Drafts"
NoteFilter.Trash -> "Trash" NoteFilter.Trash -> "Trash"
is NoteFilter.ByTag -> "#${filter.hashtag}" is NoteFilter.ByTag -> "#${filter.hashtag}"
is NoteFilter.ByColor -> filter.color.label
} }
@Composable @Composable
@@ -219,8 +292,10 @@ private fun EmptyState(filterMode: NoteFilter) {
NoteFilter.Home -> "No notes yet. Tap + to start." NoteFilter.Home -> "No notes yet. Tap + to start."
NoteFilter.Favorites -> "No favourites yet. Tap ⭐ on a card to add one." NoteFilter.Favorites -> "No favourites yet. Tap ⭐ on a card to add one."
NoteFilter.Untagged -> "All notes are tagged. 🎉" NoteFilter.Untagged -> "All notes are tagged. 🎉"
NoteFilter.Drafts -> "No drafts yet. Start typing a new note and it lands here."
NoteFilter.Trash -> "Trash is empty." NoteFilter.Trash -> "Trash is empty."
is NoteFilter.ByTag -> "No notes tagged #${filterMode.hashtag} yet." is NoteFilter.ByTag -> "No notes tagged #${filterMode.hashtag} yet."
is NoteFilter.ByColor -> "No " + filterMode.color.label.lowercase() + " notes yet. Pick a colour in the editor."
} }
Box( Box(
modifier = Modifier modifier = Modifier
@@ -240,7 +315,9 @@ private fun EmptyState(filterMode: NoteFilter) {
private fun NoResultsState(filterMode: NoteFilter) { private fun NoResultsState(filterMode: NoteFilter) {
val message = when (filterMode) { val message = when (filterMode) {
NoteFilter.Home -> "No matching notes." NoteFilter.Home -> "No matching notes."
NoteFilter.Drafts -> "No drafts match your search."
NoteFilter.Trash -> "No notes in Trash match your search." NoteFilter.Trash -> "No notes in Trash match your search."
is NoteFilter.ByColor -> "No matching notes of this colour."
else -> "Nothing here." else -> "Nothing here."
} }
Box( Box(
@@ -365,7 +442,24 @@ private fun NoteCard(
*/ */
showEncryptionBadge: Boolean = false, showEncryptionBadge: Boolean = false,
) { ) {
val (title, body) = Note.titleAndBody(note.content) // v0.3.8.0: task / shopping lists render marker-free on cards —
// header line becomes the title, items show as clean "Name ×qty @$X"
// text. The checkbox state lives in the summary row below instead.
// v0.4.2.0: voice notes carry a plain prose body (title = first
// line), so they split like TEXT — the cardPresentation list parser
// would mangle their content.
val (title, body) =
if (note.type == NoteType.TEXT || note.type == NoteType.VOICE_NOTE)
Note.titleAndBody(note.content)
else Note.cardPresentation(note.content, note.type)
// Drafts with no title introduce themselves by kind — "Shopping
// List - (draft)" beats a bare "Untitled" in the Drafts view. The
// stored content is untouched; this is display-only, so typing a
// real title (or publishing) reverts the card to normal instantly.
val displayTitle =
if (note.isDraft && title == Note.UNTITLED)
"${note.type.displayName} - (draft)"
else title
val bodyPreview = Note.bodyPreview(body) val bodyPreview = Note.bodyPreview(body)
val checklistSummary = Note.checklistSummary(note.content) val checklistSummary = Note.checklistSummary(note.content)
val noteColor = note.color val noteColor = note.color
@@ -479,7 +573,7 @@ private fun NoteCard(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
Text( Text(
text = title, text = displayTitle,
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
color = titleColor, color = titleColor,
maxLines = 1, maxLines = 1,
@@ -501,7 +595,11 @@ private fun NoteCard(
Spacer(modifier = Modifier.padding(top = 4.dp)) Spacer(modifier = Modifier.padding(top = 4.dp))
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Icon( Icon(
Icons.Default.CheckBox, // v0.3.8.0: shopping lists carry a basket
// on the card instead of the plain check box.
imageVector = if (note.type == NoteType.SHOPPING_LIST)
Icons.Default.ShoppingBasket
else Icons.Default.CheckBox,
contentDescription = null, contentDescription = null,
modifier = Modifier.size(14.dp), modifier = Modifier.size(14.dp),
tint = secondaryColor, tint = secondaryColor,
@@ -514,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()) { if (note.hashtags.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp)) Spacer(modifier = Modifier.padding(top = 4.dp))
HashtagRow( HashtagRow(
@@ -44,7 +44,8 @@ data class NoteListUiState(
) { ) {
val isEmpty: Boolean val isEmpty: Boolean
get() = !isLoading && notes.isEmpty() && !isSearchActive && get() = !isLoading && notes.isEmpty() && !isSearchActive &&
(filter == NoteFilter.Home || filter == NoteFilter.Trash) (filter == NoteFilter.Home || filter == NoteFilter.Trash ||
filter == NoteFilter.Drafts)
val noResults: Boolean get() = !isLoading && notes.isEmpty() && !isEmpty val noResults: Boolean get() = !isLoading && notes.isEmpty() && !isEmpty
} }
@@ -73,8 +74,11 @@ class NoteListViewModel(
NoteFilter.Home -> if (q.isBlank()) repository.observeAll() else repository.search(q) NoteFilter.Home -> if (q.isBlank()) repository.observeAll() else repository.search(q)
NoteFilter.Favorites -> if (q.isBlank()) repository.observeFavorites() else repository.searchFavorites(q) NoteFilter.Favorites -> if (q.isBlank()) repository.observeFavorites() else repository.searchFavorites(q)
NoteFilter.Untagged -> if (q.isBlank()) repository.observeUntagged() else repository.searchUntagged(q) NoteFilter.Untagged -> if (q.isBlank()) repository.observeUntagged() else repository.searchUntagged(q)
NoteFilter.Drafts -> if (q.isBlank()) repository.observeDrafts() else repository.searchDrafts(q)
NoteFilter.Trash -> if (q.isBlank()) repository.observeTrashed() else repository.searchTrashed(q) NoteFilter.Trash -> if (q.isBlank()) repository.observeTrashed() else repository.searchTrashed(q)
is NoteFilter.ByTag -> repository.observeNotesForHashtag(f.hashtag) is NoteFilter.ByTag -> repository.observeNotesForHashtag(f.hashtag)
is NoteFilter.ByColor ->
if (q.isBlank()) repository.observeByColor(f.color) else repository.searchByColor(q, f.color)
} }
} }
@@ -156,6 +160,11 @@ class NoteListViewModel(
viewModelScope.launch { repository.delete(id) } viewModelScope.launch { repository.delete(id) }
} }
/** "Empty Trash": permanently destroy every note in the Trash. */
fun emptyTrash() {
viewModelScope.launch { repository.deleteAllTrashed() }
}
/** Restore a note from Trash. */ /** Restore a note from Trash. */
fun restore(id: Long) { fun restore(id: Long) {
viewModelScope.launch { repository.restore(id) } viewModelScope.launch { repository.restore(id) }
@@ -122,6 +122,15 @@ fun SettingsScreen(
var showRecoveryImportWarning by remember { mutableStateOf(false) } var showRecoveryImportWarning by remember { mutableStateOf(false) }
// SAF launchers // SAF launchers
// v0.3.9.0 — Carnet / QuickNote archive importer. Picks a .zip (or a
// lone .sqd) and imports it directly; no passphrase, additive.
val carnetImportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument(),
) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
scope.launch { viewModel.importCarnet(uri) }
}
val exportLauncher = rememberLauncherForActivityResult( val exportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.CreateDocument("application/json"), contract = ActivityResultContracts.CreateDocument("application/json"),
) { uri -> ) { uri ->
@@ -296,6 +305,12 @@ fun SettingsScreen(
securityManager?.beginExternalActivity() securityManager?.beginExternalActivity()
importLauncher.launch(arrayOf("application/json", "*/*")) importLauncher.launch(arrayOf("application/json", "*/*"))
}, },
onImportCarnet = {
securityManager?.beginExternalActivity()
carnetImportLauncher.launch(
arrayOf("application/zip", "application/x-zip-compressed", "application/octet-stream", "*/*"),
)
},
) )
AboutSection( AboutSection(
version = SettingsViewModel.APP_VERSION, version = SettingsViewModel.APP_VERSION,
@@ -825,6 +840,7 @@ private fun SecuritySection(
private fun BackupSection( private fun BackupSection(
onExport: () -> Unit, onExport: () -> Unit,
onImport: () -> Unit, onImport: () -> Unit,
onImportCarnet: () -> Unit,
) { ) {
SettingsSection(title = "Backup & Restore") { SettingsSection(title = "Backup & Restore") {
Column( Column(
@@ -846,6 +862,9 @@ private fun BackupSection(
OutlinedButton(onClick = onImport, modifier = Modifier.fillMaxWidth()) { OutlinedButton(onClick = onImport, modifier = Modifier.fillMaxWidth()) {
Text("Import from file…") Text("Import from file…")
} }
OutlinedButton(onClick = onImportCarnet, modifier = Modifier.fillMaxWidth()) {
Text("Import 3rd Party Notes")
}
} }
} }
} }
@@ -14,6 +14,7 @@ import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication import org.incido.compose.IncidoApplication
import org.incido.compose.data.backup.BackupManager import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.backup.CarnetImporter
import org.incido.compose.data.security.AesGcmFieldCipher import org.incido.compose.data.security.AesGcmFieldCipher
import org.incido.compose.data.security.EncryptionVerifier import org.incido.compose.data.security.EncryptionVerifier
import org.incido.compose.data.security.ObjectBoxKeyProvider import org.incido.compose.data.security.ObjectBoxKeyProvider
@@ -46,6 +47,7 @@ class SettingsViewModel(
private val security: SecurityManager, private val security: SecurityManager,
private val objectBoxKeyProvider: ObjectBoxKeyProvider, private val objectBoxKeyProvider: ObjectBoxKeyProvider,
private val backupManager: BackupManager, private val backupManager: BackupManager,
private val carnetImporter: CarnetImporter,
private val noteCryptoService: NoteCryptoService, private val noteCryptoService: NoteCryptoService,
private val cipherHolder: CipherHolder, private val cipherHolder: CipherHolder,
private val encryptionVerifier: EncryptionVerifier, private val encryptionVerifier: EncryptionVerifier,
@@ -245,6 +247,25 @@ class SettingsViewModel(
_snackbar.value = "Imported $count note(s)." _snackbar.value = "Imported $count note(s)."
} }
/**
* v0.3.9.0 — import a Carnet / QuickNote archive (`.zip` of `*.sqd`, or a
* single `.sqd`) picked via SAF. Additive — existing notes are kept.
* Failures are caught and surfaced via the snackbar so a bad file never
* crashes the app.
*/
suspend fun importCarnet(uri: android.net.Uri) {
try {
val count = carnetImporter.import(uri)
_snackbar.value = if (count > 0) {
"Imported $count Carnet note(s)."
} else {
"No Carnet notes found in that file."
}
} catch (e: Exception) {
_snackbar.value = "Carnet import failed: ${e.message ?: "unreadable file"}"
}
}
// --- v0.3.6.0 recovery key --- // --- v0.3.6.0 recovery key ---
/** /**
@@ -333,7 +354,7 @@ class SettingsViewModel(
/** The version string baked into backup payloads and shown on /** The version string baked into backup payloads and shown on
* the About card. Mirrors `app/build.gradle.kts` `versionName` * the About card. Mirrors `app/build.gradle.kts` `versionName`
* — if you bump one, bump both. */ * — if you bump one, bump both. */
const val APP_VERSION = "0.3.7.0" const val APP_VERSION = "0.4.2.0"
val Factory: ViewModelProvider.Factory = viewModelFactory { val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer { initializer {
@@ -344,6 +365,7 @@ class SettingsViewModel(
security = c.securityManager, security = c.securityManager,
objectBoxKeyProvider = c.objectBoxKeyProvider, objectBoxKeyProvider = c.objectBoxKeyProvider,
backupManager = c.backupManager, backupManager = c.backupManager,
carnetImporter = c.carnetImporter,
noteCryptoService = c.noteCryptoService, noteCryptoService = c.noteCryptoService,
cipherHolder = c.cipherHolder, cipherHolder = c.cipherHolder,
encryptionVerifier = c.encryptionVerifier, encryptionVerifier = c.encryptionVerifier,
@@ -5,6 +5,7 @@ import io.objectbox.annotation.Id
import io.objectbox.annotation.Index import io.objectbox.annotation.Index
import org.incido.domain.model.Note import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
/** /**
* ObjectBox entity. The plugin generates a corresponding property mirror * ObjectBox entity. The plugin generates a corresponding property mirror
@@ -20,6 +21,11 @@ import org.incido.domain.model.NoteColor
* existing stores auto-migrate. The repository transparently * existing stores auto-migrate. The repository transparently
* encrypts/decrypts on write/read when a [org.incido.data.crypto.FieldCipher] * encrypts/decrypts on write/read when a [org.incido.data.crypto.FieldCipher]
* is supplied. * is supplied.
*
* v0.3.8.0 — [typeKey] records the note editor mode
* ([org.incido.domain.model.NoteType]: 0 text, 1 task list, 2 shopping
* list). Additive column — existing stores auto-migrate and old rows
* default to plain text.
*/ */
@Entity @Entity
data class NoteEntity( data class NoteEntity(
@@ -35,6 +41,10 @@ data class NoteEntity(
var contentBlob: ByteArray = ByteArray(0), var contentBlob: ByteArray = ByteArray(0),
/** True only for notes moved to the Trash view; active-note queries exclude these rows. */ /** True only for notes moved to the Trash view; active-note queries exclude these rows. */
@Index var isTrashed: Boolean = false, @Index var isTrashed: Boolean = false,
/** v0.3.8.0 — [org.incido.domain.model.NoteType] storage key (0 text, 1 task, 2 shopping). */
var typeKey: Short = 0,
/** True while a new note is being drafted; only the Drafts view shows these rows. */
@Index var isDraft: Boolean = false,
) { ) {
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (this === other) return true if (this === other) return true
@@ -48,6 +58,8 @@ data class NoteEntity(
if (isTrashed != other.isTrashed) return false if (isTrashed != other.isTrashed) return false
if (cipherVersion != other.cipherVersion) return false if (cipherVersion != other.cipherVersion) return false
if (!contentBlob.contentEquals(other.contentBlob)) return false if (!contentBlob.contentEquals(other.contentBlob)) return false
if (typeKey != other.typeKey) return false
if (isDraft != other.isDraft) return false
return true return true
} }
@@ -61,6 +73,8 @@ data class NoteEntity(
result = 31 * result + isTrashed.hashCode() result = 31 * result + isTrashed.hashCode()
result = 31 * result + cipherVersion.hashCode() result = 31 * result + cipherVersion.hashCode()
result = 31 * result + contentBlob.contentHashCode() result = 31 * result + contentBlob.contentHashCode()
result = 31 * result + typeKey.hashCode()
result = 31 * result + isDraft.hashCode()
return result return result
} }
} }
@@ -73,6 +87,8 @@ internal fun NoteEntity.toDomain(): Note = Note(
isFavorite = isFavorite, isFavorite = isFavorite,
color = NoteColor.fromStorageKey(colorKey), color = NoteColor.fromStorageKey(colorKey),
isTrashed = isTrashed, isTrashed = isTrashed,
type = NoteType.fromStorageKey(typeKey),
isDraft = isDraft,
) )
internal fun Note.toEntity(): NoteEntity = NoteEntity( internal fun Note.toEntity(): NoteEntity = NoteEntity(
@@ -83,4 +99,6 @@ internal fun Note.toEntity(): NoteEntity = NoteEntity(
isFavorite = isFavorite, isFavorite = isFavorite,
colorKey = color.storageKey, colorKey = color.storageKey,
isTrashed = isTrashed, isTrashed = isTrashed,
typeKey = type.storageKey,
isDraft = isDraft,
) )
@@ -34,6 +34,8 @@ import org.incido.domain.model.Hashtag
import org.incido.domain.model.HashtagUsage import org.incido.domain.model.HashtagUsage
import org.incido.domain.model.Note import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
/** /**
@@ -118,6 +120,45 @@ class NoteRepositoryImpl(
awaitClose { sub.cancel() } awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default) }.flowOn(Dispatchers.Default)
override fun observeDrafts(): Flow<List<Note>> = callbackFlow {
trySend(snapshotDrafts())
val sub = noteBox.query()
.equal(NoteEntity_.isDraft, true)
.build()
.subscribe()
.observer { trySend(snapshotDrafts()) }
awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default)
override fun searchDrafts(query: String): Flow<List<Note>> = callbackFlow {
trySend(snapshotDraftsSearch(query))
val sub = noteBox.query().build().subscribe().observer {
trySend(snapshotDraftsSearch(query))
}
awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default)
override fun observeByColor(color: NoteColor): Flow<List<Note>> = callbackFlow {
trySend(snapshotByColor(color))
// Kotlin stubs expose only equal(Property, Long) for integer
// columns — widen the Short storage key (ObjectBox integer
// columns are width-agnostic, so the match is exact).
val sub = noteBox.query()
.equal(NoteEntity_.colorKey, color.storageKey.toLong())
.build()
.subscribe()
.observer { trySend(snapshotByColor(color)) }
awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default)
override fun searchByColor(query: String, color: NoteColor): Flow<List<Note>> = callbackFlow {
trySend(snapshotByColorSearch(query, color))
val sub = noteBox.query().build().subscribe().observer {
trySend(snapshotByColorSearch(query, color))
}
awaitClose { sub.cancel() }
}.flowOn(Dispatchers.Default)
override fun observeNotesForHashtag(name: String): Flow<List<Note>> = callbackFlow { override fun observeNotesForHashtag(name: String): Flow<List<Note>> = callbackFlow {
trySend(snapshotForHashtag(name)) trySend(snapshotForHashtag(name))
val sub = noteBox.query().build().subscribe().observer { trySend(snapshotForHashtag(name)) } val sub = noteBox.query().build().subscribe().observer { trySend(snapshotForHashtag(name)) }
@@ -317,6 +358,7 @@ class NoteRepositoryImpl(
private fun contentMatchingNoteIds( private fun contentMatchingNoteIds(
query: String, query: String,
includeTrashed: Boolean = false, includeTrashed: Boolean = false,
includeDrafts: Boolean = false,
): List<Long> { ): List<Long> {
val q = query.trim() val q = query.trim()
if (q.isEmpty()) return emptyList() if (q.isEmpty()) return emptyList()
@@ -331,13 +373,15 @@ class NoteRepositoryImpl(
noteBox.all.filter { toReadable(it).content.lowercase().contains(needle) } noteBox.all.filter { toReadable(it).content.lowercase().contains(needle) }
} }
return candidates return candidates
.filter { it.isTrashed == includeTrashed } .filter {
it.isTrashed == includeTrashed && (includeDrafts || !it.isDraft)
}
.map { it.id } .map { it.id }
} }
/** IDs of rows eligible for all active-note queries. */ /** IDs of rows eligible for all active-note queries (never trashed, never drafts). */
private fun activeNoteIds(): Set<Long> = private fun activeNoteIds(): Set<Long> =
noteBox.all.filter { !it.isTrashed }.mapTo(HashSet()) { it.id } noteBox.all.filter { !it.isTrashed && !it.isDraft }.mapTo(HashSet()) { it.id }
/** IDs of tags currently used by at least one active note. */ /** IDs of tags currently used by at least one active note. */
private fun activeTagIds(): Set<Long> { private fun activeTagIds(): Set<Long> {
@@ -373,7 +417,7 @@ class NoteRepositoryImpl(
.build() .build()
.find() .find()
.mapNotNull { ref -> noteBox.get(ref.noteId) } .mapNotNull { ref -> noteBox.get(ref.noteId) }
.filter { it.isTrashed == includeTrashed } .filter { it.isTrashed == includeTrashed && !it.isDraft }
.map { it.id } .map { it.id }
} }
@@ -452,11 +496,47 @@ class NoteRepositoryImpl(
} }
} }
/**
* "Empty Trash": permanently delete every trashed row with the
* exact same cascade as [delete] — note row, hashtag cross-links,
* and attachment rows (their blobs live inside the attachment
* entities, so removing the row frees them too).
*/
override suspend fun deleteAllTrashed() {
val trashedIds: LongArray = noteBox.query()
.equal(NoteEntity_.isTrashed, true)
.build()
.find()
.map { it.id }
.toLongArray()
if (trashedIds.isEmpty()) return
noteBox.remove(*trashedIds)
trashedIds.forEach { id ->
val orphanXrefs: List<NoteHashtagCrossRef> = xrefBox.query()
.equal(NoteHashtagCrossRef_.noteId, id)
.build()
.find()
if (orphanXrefs.isNotEmpty()) {
xrefBox.remove(*orphanXrefs.map { it.id }.toLongArray())
}
val orphanAttachments: List<NoteAttachmentEntity> = attachmentBox.query()
.equal(NoteAttachmentEntity_.noteId, id)
.build()
.find()
if (orphanAttachments.isNotEmpty()) {
attachmentBox.remove(*orphanAttachments.map { it.id }.toLongArray())
}
}
}
/** Soft-delete only changes state; the row, links, and blobs remain intact. */ /** Soft-delete only changes state; the row, links, and blobs remain intact. */
override suspend fun softDelete(id: Long) { override suspend fun softDelete(id: Long) {
val entity = noteBox.get(id) ?: return val entity = noteBox.get(id) ?: return
if (entity.isTrashed) return if (entity.isTrashed) return
entity.isTrashed = true entity.isTrashed = true
// A trashed draft comes back as a normal note on Restore — the
// draft lifecycle ends the moment it moves to Trash.
entity.isDraft = false
// `put` is intentional here: content may be ciphertext already, // `put` is intentional here: content may be ciphertext already,
// so do not pass it through toWritable and encrypt the ciphertext a // so do not pass it through toWritable and encrypt the ciphertext a
// second time. Only the additive flag is changing. // second time. Only the additive flag is changing.
@@ -602,16 +682,20 @@ class NoteRepositoryImpl(
private fun decorate( private fun decorate(
entities: List<NoteEntity>, entities: List<NoteEntity>,
includeTrashed: Boolean? = false, includeTrashed: Boolean? = false,
includeDrafts: Boolean = false,
): List<Note> { ): List<Note> {
val tags = hashtagsByNoteId() val tags = hashtagsByNoteId()
val attachments = attachmentsByNoteId() val attachments = attachmentsByNoteId()
return entities return entities
.filter { includeTrashed == null || it.isTrashed == includeTrashed } .filter {
(includeTrashed == null || it.isTrashed == includeTrashed) &&
(includeDrafts || !it.isDraft)
}
.sortedWith( .sortedWith(
compareByDescending<NoteEntity> { it.isFavorite } compareByDescending<NoteEntity> { it.isFavorite }
.thenByDescending { it.updatedAt }, .thenByDescending { it.updatedAt },
).map { e -> ).map { e ->
val base = toReadable(e).toDomain() val base = toReadable(e).toDomain().withHealedListType()
base.copy( base.copy(
hashtags = tags[e.id].orEmpty(), hashtags = tags[e.id].orEmpty(),
attachments = attachments[e.id].orEmpty(), attachments = attachments[e.id].orEmpty(),
@@ -619,9 +703,24 @@ class NoteRepositoryImpl(
} }
} }
/**
* v0.3.8.0 FIX — notes whose bodies ARE checklist lines but which
* persisted with `typeKey = 0` (written by a build predating the
* column, or by a partial save of the list feature) would render as
* raw `- [ ] …` markdown on cards and open in the plain editor.
* Infer the list type from the content itself at READ time; the next
* save from the editor then persists the healed `typeKey` for good.
* TEXT notes containing only occasional hand-typed `- [ ]` lines in
* prose are left untouched (see [Note.inferListType]).
*/
private fun Note.withHealedListType(): Note =
if (type != NoteType.TEXT) this
else Note.inferListType(content)?.let { copy(type = it) } ?: this
private fun snapshotAll(): List<Note> = decorate(noteBox.all) private fun snapshotAll(): List<Note> = decorate(noteBox.all)
private fun snapshotAllIncludingTrashed(): List<Note> = decorate(noteBox.all, includeTrashed = null) private fun snapshotAllIncludingTrashed(): List<Note> =
decorate(noteBox.all, includeTrashed = null, includeDrafts = true)
private fun snapshotSearch(query: String): List<Note> { private fun snapshotSearch(query: String): List<Note> {
val allIds = matchingNoteIds(query, includeTrashed = false) val allIds = matchingNoteIds(query, includeTrashed = false)
@@ -646,6 +745,66 @@ class NoteRepositoryImpl(
return decorate(trashedEntities, includeTrashed = true) return decorate(trashedEntities, includeTrashed = true)
} }
private fun snapshotDrafts(): List<Note> {
val draftEntities: List<NoteEntity> = noteBox.query()
.equal(NoteEntity_.isDraft, true)
.build()
.find()
return decorate(draftEntities, includeTrashed = null, includeDrafts = true)
}
/**
* Content search restricted to drafts (tag-name matches are not
* folded in, mirroring the plain-text scope of the Drafts view).
*/
private fun snapshotDraftsSearch(query: String): List<Note> {
val q = query.trim()
if (q.isEmpty()) return snapshotDrafts()
val draftIds: Set<Long> = noteBox.query()
.equal(NoteEntity_.isDraft, true)
.build()
.find()
.mapTo(HashSet()) { it.id }
val matches: List<Long> = contentMatchingNoteIds(
q,
includeTrashed = false,
includeDrafts = true,
).filter { it in draftIds }
val entities: List<NoteEntity> = matches.mapNotNull { noteBox.get(it) }
return decorate(entities, includeTrashed = null, includeDrafts = true)
}
/**
* Active notes of one accent colour. The colour query already
* excludes nothing on trash state, so `decorate` (default
* `includeTrashed = false`) drops trashed rows exactly like
* [snapshotFavorites] / [snapshotUntagged] do.
*/
private fun snapshotByColor(color: NoteColor): List<Note> {
val colorEntities: List<NoteEntity> = noteBox.query()
.equal(NoteEntity_.colorKey, color.storageKey.toLong())
.build()
.find()
return decorate(colorEntities)
}
/**
* Context-aware search across notes of [color] only. Blank [query]
* degrades to [snapshotByColor]. Otherwise runs the same content +
* hashtag-name matching as [snapshotFavoritesSearch] and intersects
* with the colour (never trashed rows — matchingNoteIds already
* excludes them via includeTrashed = false).
*/
private fun snapshotByColorSearch(query: String, color: NoteColor): List<Note> {
val q = query.trim()
if (q.isEmpty()) return snapshotByColor(color)
val allIds: Set<Long> = matchingNoteIds(q, includeTrashed = false)
if (allIds.isEmpty()) return emptyList()
val entities: List<NoteEntity> = allIds.mapNotNull { id -> noteBox.get(id) }
.filter { it.colorKey == color.storageKey }
return decorate(entities)
}
private fun snapshotUntagged(): List<Note> { private fun snapshotUntagged(): List<Note> {
val activeIds = activeNoteIds() val activeIds = activeNoteIds()
val noteIdsWithTags: Set<Long> = xrefBox.all val noteIdsWithTags: Set<Long> = xrefBox.all
@@ -728,7 +887,7 @@ class NoteRepositoryImpl(
val entity = noteBox.get(id) ?: return null val entity = noteBox.get(id) ?: return null
val tags = hashtagsByNoteId()[id].orEmpty() val tags = hashtagsByNoteId()[id].orEmpty()
val attachments = attachmentsByNoteId()[id].orEmpty() val attachments = attachmentsByNoteId()[id].orEmpty()
return toReadable(entity).toDomain().copy( return toReadable(entity).toDomain().withHealedListType().copy(
hashtags = tags, hashtags = tags,
attachments = attachments, attachments = attachments,
) )
@@ -0,0 +1,27 @@
package org.incido.domain.model
/**
* v0.3.8.0 — one row of a [NoteType.TASK_LIST] / [NoteType.SHOPPING_LIST]
* note while it is being edited. Rows live in the editor's UI state and
* are serialised back into `- [ ]` / `- [x]` content lines on every edit
* (see [Note.serializeListContent] / [Note.splitListContent]).
*/
data class ChecklistItem(
/** Item label; blank rows are skipped when serialising. */
val text: String,
/** Checkbox state — for shopping lists: "in the basket". */
val checked: Boolean = false,
/**
* Quantity as typed/picked (`""` = 1). Only meaningful for
* [NoteType.SHOPPING_LIST]; shopping rows offer a 1–9 picker so
* this stays tiny, but the parser accepts any small positive int.
*/
val quantity: String = "",
/**
* Price as entered, in CENTS DIGITS (`""` = none, `"199"` = $1.99 —
* supermarket-terminal style where the last two digits are cents).
* Only meaningful for [NoteType.SHOPPING_LIST]. Money maths runs
* on these integers so there is never binary-float drift.
*/
val cost: String = "",
)
@@ -24,12 +24,30 @@ data class Note(
val attachments: List<NoteAttachment> = emptyList(), val attachments: List<NoteAttachment> = emptyList(),
/** True only for notes moved to the Trash view; active-note queries exclude these rows. */ /** True only for notes moved to the Trash view; active-note queries exclude these rows. */
val isTrashed: Boolean = false, val isTrashed: Boolean = false,
/**
* True while a new note is being drafted. Drafts auto-save every
* edit and are visible only in the Drafts view — Home / Favorites /
* Untagged / tag / colour views / ordinary search / Trash all
* exclude them. Saving from the editor (or moving to Trash) clears
* the flag.
*/
val isDraft: Boolean = false,
/** v0.3.8.0 — which editor surface opens this note (see [NoteType]). */
val type: NoteType = NoteType.TEXT,
) { ) {
/** Convenience: the first image attachment, or `null` if none. */ /** Convenience: the first image attachment, or `null` if none. */
val firstImageAttachment: NoteAttachment? val firstImageAttachment: NoteAttachment?
get() = attachments.firstOrNull { it.isImage } 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 { companion object {
private const val UNTITLED = "Untitled" /** Shown when a note's content has no usable first line. */
const val UNTITLED = "Untitled"
/** /**
* Splits [content] into a (title, body) pair. The title is the first * Splits [content] into a (title, body) pair. The title is the first
@@ -107,5 +125,326 @@ data class Note(
else -> "$open open · $done done" else -> "$open open · $done done"
} }
} }
// -----------------------------------------------------------------
// v0.3.8.0 — task / shopping list parsing + serialisation.
//
// A list note's content is an optional header block (the title /
// preamble kept as plain lines) followed by GitHub-style checkbox
// lines. Shopping-list rows carry quantity + per-item price in an
// explicit end-of-line marker so the PRODUCT TEXT IS NEVER
// SCANNED FOR NUMBERS (a product called "Battery AA 3" or
// "Poster 50 x 60" is safe):
//
// - [ ] Milk no qty / price yet
// - [ ] Ham {p12.99} price only (qty 1)
// - [ ] Eggs {q12 p2.40} 12 × $2.40
//
// Hand-typed / legacy lines stay importable (Development Plan
// §6.1's trailing-numeric-token idea): `Milk 3.50` reads as a
// price, `Eggs 12 x 2.40` as qty × price. Those forms survive in
// task lists, where each row is just `- [ ] <text>`.
// -----------------------------------------------------------------
private val CHECKLIST_LINE: Regex = Regex("""^\s*-\s+\[([ xX])]\s*(.*)$""")
/** `Product {q12 p2.40}` / `{p2.40}` / `{q12}` (anchored, greedy-safe). */
private val BRACED_QP: Regex =
Regex("""^(.*?)\s*\{\s*(?:q(\d{1,3}))?\s*(?:p([\d.,]{1,12}))?\s*\}$""")
/** Legacy: `Product 12 x 2.40` (also `12x2.40`, `×`). A decimal on
* the price keeps lookalikes like "Poster 50 x 60" as plain text. */
private val LEGACY_QTY_PRICE: Regex =
Regex("""^(.+?)\s+(\d{1,3})\s*[xX×]\s*(\d{1,9}[.,]\d{1,2})$""")
/** Legacy (§6.1): `Product 3.50`. Decimal point REQUIRED, so a
* product named "Battery AA 3" is never mistaken for a price. */
private val TRAILING_COST: Regex = Regex("""^(.*\S)\s+(\d{1,9}[.,]\d{1,2})$""")
private val COST_PATTERN: Regex = Regex("""\d{1,9}(?:\.\d{1,2})?""")
/**
* Canonicalise a raw monetary amount token: trims, accepts `,` as
* decimal separator, tolerates a trailing `.` mid-typing, and
* returns `""` for anything that isn't a plain positive number
* with at most two decimals.
*/
fun normaliseCost(raw: String): String {
val trimmed = raw.trim().replace(',', '.')
if (trimmed.isEmpty()) return ""
val candidate = if (trimmed.endsWith(".")) trimmed.dropLast(1) else trimmed
return if (candidate.matches(COST_PATTERN)) candidate else ""
}
/**
* Convert a canonical amount ("2.40", "5", "0.05") into CENTS
* DIGITS ("240", "500", "5"). Returns `""` for invalid input.
*/
fun priceDigitsFromAmount(amount: String): String {
val canonical = normaliseCost(amount)
if (canonical.isEmpty()) return ""
val parts = canonical.split('.')
val units = parts[0].toLongOrNull() ?: return ""
val cents = if (parts.size > 1) parts[1].padEnd(2, '0').toLongOrNull() ?: return "" else 0L
val total = units * 100 + cents
if (total <= 0L) return ""
return total.toString()
}
/** Inverse: cents digits ("199") → canonical amount ("1.99"); "" → "". */
fun amountFromPriceDigits(digits: String): String {
val clean = digits.filter { it.isDigit() }.trimStart('0')
if (clean.isEmpty()) return ""
return clean.padStart(3, '0').let { "${it.dropLast(2)}.${it.takeLast(2)}" }
}
/** Digit-only normalisation of the quantity picker/keypad input. */
fun normaliseQuantity(raw: String): String =
raw.filter { it.isDigit() }.take(3).trimStart('0')
/** Digit-only normalisation of the price input ("2.4" → "24"). */
fun normalisePriceInput(raw: String): String =
raw.filter { it.isDigit() }.take(9).trimStart('0')
/** Numeric quantity of a row (blank ⇒ 1). */
fun quantityOf(item: ChecklistItem): Int =
item.quantity.toIntOrNull()?.coerceIn(1, 999) ?: 1
/** Per-line total in cents: quantity × unit price. */
fun lineTotalCents(item: ChecklistItem): Long =
quantityOf(item) * (item.cost.toLongOrNull() ?: 0L)
/**
* Split [content] into (header, items) for the structured list
* editors.
*
* When marker lines (`- [ ] …`) exist, the header is everything
* before the first one and every marker line becomes an item;
* other non-blank lines below the first marker become unchecked
* items so nothing is silently dropped. Without any marker line
* (a plain note being converted), the first non-blank line is
* kept as the title/header and the remaining non-blank lines
* become unchecked items.
*
* [interpretCosts] (shopping lists only) strips a trailing
* numeric token off each item text into [ChecklistItem.cost].
*/
fun splitListContent(
content: String,
interpretCosts: Boolean,
): Pair<String, List<ChecklistItem>> {
val lines = content.split('\n')
val firstMarker = lines.indexOfFirst { CHECKLIST_LINE.matches(it) }
val headerLines: List<String>
val itemLines: List<String>
if (firstMarker >= 0) {
headerLines = lines.take(firstMarker)
itemLines = lines.drop(firstMarker)
} else {
val titleIdx = lines.indexOfFirst { it.isNotBlank() }
headerLines = if (titleIdx >= 0) listOf(lines[titleIdx]) else emptyList()
itemLines = if (titleIdx >= 0) lines.drop(titleIdx + 1) else lines
}
val items = itemLines
.filter { it.isNotBlank() }
.map { line ->
val match = CHECKLIST_LINE.matchEntire(line)
var text: String
val checked: Boolean
if (match != null) {
checked = match.groupValues[1].equals("x", ignoreCase = true)
text = match.groupValues[2].trim()
} else {
checked = false
text = line.trim()
}
var quantity = ""
var cost = "" // cents digits
if (interpretCosts) {
val braced = BRACED_QP.matchEntire(text)
val legacyQtyPrice = if (braced == null) LEGACY_QTY_PRICE.matchEntire(text) else null
val legacyPrice = if (braced == null && legacyQtyPrice == null)
TRAILING_COST.matchEntire(text) else null
when {
braced != null -> {
// Structured form: everything before the
// marker is PRODUCT TEXT, unexamined.
val q = parsedQuantity(braced.groupValues[2])
val p = parsedPrice(braced.groupValues[3])
if (q.isEmpty() && p.isEmpty()) {
// "{}" or invalid slots — not a marker after all.
} else {
text = braced.groupValues[1].trim()
quantity = q
cost = p
}
}
legacyQtyPrice != null -> {
text = legacyQtyPrice.groupValues[1].trim()
quantity = parsedQuantity(legacyQtyPrice.groupValues[2])
cost = parsedPrice(legacyQtyPrice.groupValues[3])
}
legacyPrice != null -> {
text = legacyPrice.groupValues[1].trim()
cost = parsedPrice(legacyPrice.groupValues[2])
}
}
}
ChecklistItem(text = text, checked = checked, quantity = quantity, cost = cost)
}
return headerLines.joinToString("\n").trim() to items
}
/** Normalise a parsed quantity token (blank / 1 ⇒ default ""). */
private fun parsedQuantity(raw: String): String {
val n = normaliseQuantity(raw)
return if (n == "1" || n.isEmpty()) "" else n
}
/** Normalise a parsed amount token into cents digits. */
private fun parsedPrice(raw: String): String = priceDigitsFromAmount(raw)
/**
* Inverse of [splitListContent]: rebuild the note content from a
* header + item rows. Blank rows are skipped. Shopping rows
* serialise quantity + price into the `{q… p…}` marker (qty 1 is
* omitted); converting BACK to a task list folds the values into
* legacy text tokens (`Milk 2 x 3.90`) so they survive a
* round-trip through plain-text mode.
*/
fun serializeListContent(
header: String,
items: List<ChecklistItem>,
type: NoteType,
): String {
val isShopping = type == NoteType.SHOPPING_LIST
val bodyLines = items.mapNotNull { item ->
val amount = amountFromPriceDigits(item.cost)
// v0.3.8.0 FIX: parsedQuantity folds the default (1) to
// "" — a plain String, never null. Without takeIf, the
// shopping branch emitted a bare "q" slot (broken
// "{q p1.23}" markers) and the task branch folded a
// stray " x" onto every row. Null means "no quantity".
val qtyDigits = parsedQuantity(item.quantity).takeIf { it.isNotEmpty() }
val rawText = item.text.trim()
val rowText: String
if (isShopping) {
val slots = listOfNotNull(
qtyDigits?.let { "q$it" },
amount.ifEmpty { null }?.let { "p$it" },
)
rowText = if (slots.isEmpty()) rawText
else "$rawText {${slots.joinToString(" ")}}"
} else {
// Task list: fold structured values back into text so
// switching modes never silently drops them.
rowText = when {
rawText.isEmpty() && qtyDigits != null && amount.isNotEmpty() ->
"$qtyDigits x $amount"
rawText.isEmpty() && amount.isNotEmpty() -> amount
qtyDigits != null && amount.isNotEmpty() -> "$rawText $qtyDigits x $amount"
qtyDigits != null -> "$rawText $qtyDigits x"
amount.isNotEmpty() -> "$rawText $amount"
else -> rawText
}
}
when {
rowText.isBlank() -> null
else -> "- [" + (if (item.checked) "x" else " ") + "] " + rowText
}
}
val headerTrimmed = header.trimEnd()
return when {
bodyLines.isEmpty() -> headerTrimmed
headerTrimmed.isEmpty() -> bodyLines.joinToString("\n")
else -> headerTrimmed + "\n" + bodyLines.joinToString("\n")
}
}
/** Running shopping total in cents: quantity × price, CHECKED rows only. */
fun shoppingTotalCents(items: List<ChecklistItem>): Long =
items.filter { it.checked }.sumOf { lineTotalCents(it) }
/** Running shopping total as dollars (display helper). */
fun shoppingTotal(items: List<ChecklistItem>): Double =
shoppingTotalCents(items) / 100.0
/** "$0.00"-style display string for entered cents digits. */
fun formatMoney(centsDigits: String): String {
val clean = centsDigits.filter { it.isDigit() }.trimStart('0')
return "$" + if (clean.isEmpty()) "0.00" else amountFromPriceDigits(clean)
}
/**
* Card-friendly rendering for structured note types: (title, body)
* WITHOUT any markdown syntax. Title is the list header's first
* non-blank line (or "Untitled"); body is the item names joined
* with " · ", shopping rows carrying " ×qty" (when ≠ 1) and
* " @$price" suffixes. Plain-text notes keep using
* [titleAndBody] untouched.
*/
fun cardPresentation(content: String, type: NoteType): Pair<String, String> {
val isShopping = type == NoteType.SHOPPING_LIST
val (header, items) = splitListContent(
content,
interpretCosts = isShopping,
)
val title = header.lineSequence()
.firstOrNull { it.isNotBlank() }?.trim() ?: UNTITLED
val parts = items.mapNotNull { item ->
val text = item.text.trim()
if (text.isEmpty()) return@mapNotNull null
val qty = quantityOf(item)
val amount = if (isShopping) amountFromPriceDigits(item.cost) else ""
buildString {
append(text)
if (isShopping && qty > 1) append(" \u00d7$qty")
if (isShopping && amount.isNotEmpty()) {
append(" @")
append(amount)
}
}
}
return title to parts.joinToString(" \u00b7 ")
}
/**
* v0.3.8.0 FIX — heal notes stranded as [NoteType.TEXT] by builds
* that saved list content before the `typeKey` column existed (or
* by a partial write of the new feature). Returns the list type
* implied by [content], or null when the body is NOT unambiguously
* a checklist:
*
* * The first non-blank line is a header ONLY if it is not itself
* a checkbox line (headerless lists start straight at `- [ ]`).
* * EVERY remaining non-blank line must match [CHECKLIST_LINE]
* and at least one must exist — prose + an occasional hand-typed
* `- [ ]` stays plain TEXT.
* * Any line carrying a `{q…/p…}` marker implies SHOPPING_LIST.
*/
fun inferListType(content: String): NoteType? {
val lines = content.lines()
val firstNonBlank = lines.indexOfFirst { it.isNotBlank() }
if (firstNonBlank < 0) return null
val startIdx = if (CHECKLIST_LINE.matches(lines[firstNonBlank])) {
firstNonBlank // headerless list
} else {
firstNonBlank + 1 // first line is the header
}
var sawMarker = false
var sawBrace = false
for (i in startIdx until lines.size) {
val line = lines[i]
if (line.isBlank()) continue
val match = CHECKLIST_LINE.matchEntire(line) ?: return null
sawMarker = true
if (BRACED_QP.containsMatchIn(match.groupValues[2])) sawBrace = true
}
return when {
!sawMarker -> null
sawBrace -> NoteType.SHOPPING_LIST
else -> NoteType.TASK_LIST
}
}
} }
} }
@@ -24,4 +24,7 @@ data class NoteAttachment(
) { ) {
/** Convenience: true for any image-prefixed mime type. */ /** Convenience: true for any image-prefixed mime type. */
val isImage: Boolean get() = mimeType.startsWith("image/") 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/")
} }
@@ -5,13 +5,13 @@ package org.incido.domain.model
* Stored as a short (`SHORT`) in ObjectBox — additive-safe migration from * Stored as a short (`SHORT`) in ObjectBox — additive-safe migration from
* the v0.1 schema. * the v0.1 schema.
*/ */
enum class NoteColor(val storageKey: Short) { enum class NoteColor(val storageKey: Short, val label: String) {
NONE(0), NONE(0, "None"),
BLUE(1), BLUE(1, "Blue"),
GREEN(2), GREEN(2, "Green"),
AMBER(3), AMBER(3, "Amber"),
RED(4), RED(4, "Red"),
PURPLE(5); PURPLE(5, "Purple");
companion object { companion object {
/** Convert from the stored [Short] back to the enum, defaulting to [NONE]. */ /** Convert from the stored [Short] back to the enum, defaulting to [NONE]. */
@@ -9,21 +9,29 @@ package org.incido.domain.model
* - [Favorites] — only notes with `isFavorite = true`; ordinary search is enabled. * - [Favorites] — only notes with `isFavorite = true`; ordinary search is enabled.
* - [Untagged] — only notes that have zero hashtags; ordinary search is enabled. * - [Untagged] — only notes that have zero hashtags; ordinary search is enabled.
* - [ByTag] — only notes tagged with [hashtag]; text search is not offered. * - [ByTag] — only notes tagged with [hashtag]; text search is not offered.
* - [ByColor] — active notes with accent colour [color]; ordinary search is
* enabled and narrows within the colour (like Favorites).
* - [Drafts] — auto-saved new notes; visible nowhere else until saved
* or trashed. Ordinary search is enabled.
* - [Trash] — only notes moved out of the active list; no edit actions. * - [Trash] — only notes moved out of the active list; no edit actions.
*/ */
sealed class NoteFilter { sealed class NoteFilter {
object Home : NoteFilter() object Home : NoteFilter()
object Favorites : NoteFilter() object Favorites : NoteFilter()
object Untagged : NoteFilter() object Untagged : NoteFilter()
object Drafts : NoteFilter()
object Trash : NoteFilter() object Trash : NoteFilter()
data class ByTag(val hashtag: String) : NoteFilter() data class ByTag(val hashtag: String) : NoteFilter()
data class ByColor(val color: NoteColor) : NoteFilter()
/** Stable identifier used by the drawer for `selected` matching. */ /** Stable identifier used by the drawer for `selected` matching. */
fun key(): String = when (this) { fun key(): String = when (this) {
Home -> "home" Home -> "home"
Favorites -> "favorites" Favorites -> "favorites"
Untagged -> "untagged" Untagged -> "untagged"
Drafts -> "drafts"
Trash -> "trash" Trash -> "trash"
is ByTag -> "tag:$hashtag" is ByTag -> "tag:$hashtag"
is ByColor -> "color:${color.name}"
} }
} }
@@ -0,0 +1,40 @@
package org.incido.domain.model
/**
* v0.3.8.0 — which editor surface a note body uses.
*
* The note text itself stays the single source of truth: task and
* shopping lists are persisted as GitHub-flavoured checkbox lines
* (`- [ ] item` / `- [x] item`, with an optional trailing numeric
* cost token on shopping lists), so free-text search, at-rest
* encryption, backups, and the inline `- [ ]` markdown already
* supported in [Note.checklistCounts] keep working untouched.
*
* Stored as a `Short` in ObjectBox — additive-safe migration from
* the pre-v0.3.8.0 schema (rows without the column default to [TEXT]).
*/
enum class NoteType(val storageKey: Short, val displayName: String) {
/** Free-form body edited in the plain multi-line field. */
TEXT(0, "Text Note"),
/** Editable checklist: checkbox + item text rows. */
TASK_LIST(1, "Task List"),
/** Checklist plus a per-item cost (number pad) and a running total. */
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]. */
fun fromStorageKey(key: Short): NoteType =
values().firstOrNull { it.storageKey == key } ?: TEXT
}
}
@@ -3,6 +3,7 @@ package org.incido.domain.repository
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import org.incido.domain.model.HashtagUsage import org.incido.domain.model.HashtagUsage
import org.incido.domain.model.Note import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteAttachment import org.incido.domain.model.NoteAttachment
/** /**
@@ -37,6 +38,13 @@ interface NoteRepository {
/** Permanently delete a note by id. No-op if it doesn't exist. */ /** Permanently delete a note by id. No-op if it doesn't exist. */
suspend fun delete(id: Long) suspend fun delete(id: Long)
/**
* "Empty Trash": permanently delete EVERY trashed note in one go,
* with the same cascade as [delete] (row + hashtag links +
* attachment blobs). No-op when the Trash is already empty.
*/
suspend fun deleteAllTrashed()
/** Move a note to Trash without removing its row, tags, or attachments. */ /** Move a note to Trash without removing its row, tags, or attachments. */
suspend fun softDelete(id: Long) suspend fun softDelete(id: Long)
@@ -56,6 +64,35 @@ interface NoteRepository {
/** Only notes in Trash, sorted by updatedAt DESC. */ /** Only notes in Trash, sorted by updatedAt DESC. */
fun observeTrashed(): Flow<List<Note>> fun observeTrashed(): Flow<List<Note>>
/**
* Only auto-saved draft notes (new notes the user hasn't saved yet),
* sorted favourites-first then newest-first. Drafts appear in no
* other view — see [Note.isDraft].
*/
fun observeDrafts(): Flow<List<Note>>
/**
* Context-aware content search across drafts only; blank [query]
* returns the same as [observeDrafts].
*/
fun searchDrafts(query: String): Flow<List<Note>>
/**
* Only **active** notes (never trashed) whose accent colour is
* [color], sorted favourites-first then newest-first. Tagged and
* untagged notes are both eligible — only the colour matters.
*/
fun observeByColor(color: NoteColor): Flow<List<Note>>
/**
* Context-aware search across notes of [color] only — matches
* [Note.content] (contains, case-insensitive) AND any of the
* note's hashtags (case-insensitive equality), intersected with
* the colour and the active (non-trashed) set. Blank [query]
* returns the same as [observeByColor].
*/
fun searchByColor(query: String, color: NoteColor): Flow<List<Note>>
/** /**
* Context-aware search across **favourites only** — matches * Context-aware search across **favourites only** — matches
* [Note.content] (contains, case-insensitive) AND any of the note's * [Note.content] (contains, case-insensitive) AND any of the note's
Binary file not shown.

After

Width:  |  Height:  |  Size: 502 KiB

+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# One-off helper: attach PREVIOUS_HISTORY.md notes to EXISTING Gitea
# releases that were published before the automatic pipeline existed.
#
# TOKEN=<gitea-token-with-release-write> ./backfill-release-notes.sh [version ...]
#
# With no arguments it walks every section of PREVIOUS_HISTORY.md and
# silently skips versions that have no release entry / no section.
# Idempotent: replaces both the description and the changes-file asset.
set -euo pipefail
API="${GITEA_API:-https://git.trevena.info/api/v1/repos/nick/incido}"
: "${TOKEN:?Set TOKEN to a Gitea token with release write access}"
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
NOTES_PY="$ROOT/scripts/ci/release-notes.py"
if [ "$#" -gt 0 ]; then
VERSIONS=("$@")
else
mapfile -t VERSIONS < <(grep -oE '^## v[0-9]+(\.[0-9]+)+' "$ROOT/PREVIOUS_HISTORY.md" | sed 's/^## v//')
fi
for V in "${VERSIONS[@]}"; do
TAG="v$V"
RID=$(curl -s "$API/releases/tags/$TAG" \
-H "Authorization: token $TOKEN" \
| python3 -c "import sys,json; print(json.load(sys.stdin).get('id','') or '')")
if [ -z "$RID" ]; then echo "skip $TAG (no release entry)"; continue; fi
NOTES="/tmp/Incido-$V-changes.md"
if ! python3 "$NOTES_PY" "$V" --out "$NOTES"; then
echo "skip $TAG (no PREVIOUS_HISTORY.md section)"; continue
fi
# Refresh the description.
REL_NOTES_FILE="$NOTES" python3 -c "import json,os; print(json.dumps({'body': open(os.environ['REL_NOTES_FILE'],encoding='utf-8').read()}))" \
> /tmp/body_patch.json
curl -s -X PATCH "$API/releases/$RID" \
-H "Authorization: token $TOKEN" \
-H "Content-Type: application/json" \
-d @/tmp/body_patch.json > /dev/null
# Replace a stale changes-file asset, then upload the fresh one.
curl -s "$API/releases/$RID/assets" -H "Authorization: token $TOKEN" \
| REL_ASSET_NAME="Incido-$V-changes.md" python3 -c "import sys,json,os; [print(a['id']) for a in json.load(sys.stdin) if a['name']==os.environ['REL_ASSET_NAME']]" \
| while read -r AID; do
curl -s -X DELETE "$API/releases/$RID/assets/$AID" -H "Authorization: token $TOKEN" > /dev/null
done
curl -s -f -X POST "$API/releases/$RID/assets?name=Incido-$V-changes.md" \
-H "Authorization: token $TOKEN" \
-F "attachment=@$NOTES" --max-time 600 > /dev/null \
|| echo "WARN $TAG: description patched, but the changes-file upload failed"
echo "done $TAG"
done
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Extract the release-notes section for one version from PREVIOUS_HISTORY.md.
Incido publishes its user-facing changelog through the Gitea Releases page:
for every tag push, `.gitea/workflows/release.yml` calls this script with
the released version. The matching `## v<VERSION> — <DATE>` section of
PREVIOUS_HISTORY.md becomes the release description and is also uploaded
next to the APKs as `Incido-<VERSION>-changes.md`.
Usage:
release-notes.py <version> [--out FILE] [--history FILE] [--no-footer]
Exits 0 and prints the Markdown (to --out FILE or stdout) when the section
exists; exits 1 (message on stderr) when it doesn't — the workflow then
falls back to its generic "Release <tag>" body.
"""
import argparse
import re
import sys
from pathlib import Path
# "## v0.3.8.0 — 2026-09-16" -> group(1) = "0.3.8.0"
HEADING = re.compile(r"^##\s+v?([0-9]+(?:\.[0-9]+)*)\b")
FOOTER = (
"\n\n---\n\n"
"_Full history: PREVIOUS_HISTORY.md at the repository root. "
"In-depth developer notes: Incido Development Plan \u00a710._\n"
)
def extract(history_text: str, version: str, footer: bool) -> str | None:
wanted = version.lstrip("vV").strip()
collected: list[str] = []
in_section = False
for line in history_text.splitlines():
match = HEADING.match(line)
if match:
in_section = match.group(1) == wanted
if in_section:
collected.append(line)
if not collected:
return None
body = "\n".join(collected).rstrip()
if not body:
return None
return body + (FOOTER if footer else "")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("version", help="Version or tag, e.g. 0.3.8.0 or v0.3.8.0")
parser.add_argument("--out", type=Path, default=None,
help="Write the notes to this file instead of stdout")
parser.add_argument("--history", type=Path, default=None,
help="Path to PREVIOUS_HISTORY.md "
"(default: repo root, two levels above scripts/ci/)")
parser.add_argument("--no-footer", action="store_true",
help="Omit the standard cross-reference footer")
args = parser.parse_args()
history_path = args.history or (
Path(__file__).resolve().parents[2] / "PREVIOUS_HISTORY.md"
)
if not history_path.is_file():
print(f"release-notes: history file not found: {history_path}",
file=sys.stderr)
return 1
notes = extract(history_path.read_text(encoding="utf-8"),
args.version, footer=not args.no_footer)
if notes is None:
print(f"release-notes: no changelog section for {args.version} "
f"in {history_path.name}", file=sys.stderr)
return 1
if args.out:
args.out.write_text(notes, encoding="utf-8")
print(f"Wrote {len(notes)} chars for v{args.version.lstrip('vV')} "
f"to {args.out}")
else:
sys.stdout.write(notes)
return 0
if __name__ == "__main__":
sys.exit(main())