Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
765191ac8e | ||
|
|
9f6124a501 | ||
|
|
6f16e87ec0 | ||
|
|
c894321fdf | ||
|
|
0cad7729aa | ||
|
|
639f39d187 | ||
|
|
faab0cde98 | ||
|
|
cce35587fc | ||
|
|
d264238640 | ||
|
|
0dc5935d1d | ||
|
|
018db4819c | ||
|
|
6b5c24e1bc | ||
|
|
56949c485f | ||
|
|
bdb3d7157d | ||
|
|
31408172df | ||
|
|
59bd6e106b | ||
|
|
cd363c7aa5 | ||
|
|
5bce1934c1 | ||
|
|
b774a1feb6 | ||
|
|
9ad7c60537 | ||
|
|
bce8e9a0dc | ||
|
|
fef8f9c2e9 | ||
|
|
6b8db18cdf | ||
|
|
000f4095cc | ||
|
|
40e2b9ff52 | ||
|
|
8db835640e | ||
|
|
561d16eb0c | ||
|
|
29288b0370 | ||
|
|
9cb7fdbf58 | ||
|
|
52ccceb732 | ||
|
|
031d8570b4 | ||
|
|
cf0e74b68d | ||
|
|
8facbe718b | ||
|
|
7cc4eda90d | ||
|
|
b11c02e1b4 | ||
|
|
5f45b0921b | ||
|
|
9fe4763aa7 | ||
|
|
8b66e82acb | ||
|
|
f87ca17ded | ||
|
|
1d97376aef | ||
|
|
d9043db857 | ||
|
|
d45cb7c31e | ||
|
|
3d234f307e | ||
|
|
ffa821bf28 | ||
|
|
f337e162f7 | ||
|
|
cbe015839b | ||
|
|
7e335d14ef | ||
|
|
c8c2c98c8e | ||
|
|
cbebac3254 | ||
|
|
ab26fe5f98 | ||
|
|
dee20bf0f4 | ||
|
|
a5b5d334c1 | ||
|
|
32166a3100 | ||
|
|
7b6187f99a | ||
|
|
576080c8b5 | ||
|
|
4a28f4f52b | ||
|
|
37e9c14d1e | ||
|
|
4b41b0dedb | ||
|
|
9f390a4047 | ||
|
|
fa7e50b0db | ||
|
|
92e4a99e11 | ||
|
|
c7c82ec68a | ||
|
|
639f66f08c | ||
|
|
57b6cf99d2 | ||
|
|
a9b90aab9e | ||
|
|
ed9d8d0ce2 | ||
|
|
486e2d01cf | ||
|
|
a0be9f8123 | ||
|
|
04f9cda95a | ||
|
|
594525ed10 | ||
|
|
3c8d01cca9 | ||
|
|
c4c8ef365f | ||
|
|
3911bd07f2 | ||
|
|
28a8a4e6cc | ||
|
|
5b1d7cbaf0 | ||
|
|
7b298aa6e7 | ||
|
|
7a808c37d5 | ||
|
|
8651a4020f | ||
|
|
06b4c208a6 | ||
|
|
734f9aecca | ||
|
|
a39c52cf89 | ||
|
|
4bbe29851a | ||
|
|
06d647cf72 | ||
|
|
f153ad8702 |
No files matched your search
@@ -0,0 +1,164 @@
|
||||
name: desktop-release
|
||||
|
||||
# Phase 1 M5.4 — Linux desktop packaging (jpackage app-image + deb).
|
||||
# jpackage cannot cross-compile (§7 of the phase plan), and macOS/Windows
|
||||
# GA is explicitly Phase 2 (§8) — this job therefore runs ONLY on the
|
||||
# Linux self-hosted runner; the deferred jobs at the bottom document the
|
||||
# shape the matrix takes when matching runners exist.
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
# Same retry rationale as release.yml: a tag push pins this file to the
|
||||
# tag's commit, so re-dispatching against main replays main's current
|
||||
# workflow against an already-published tag.
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Existing tag to rebuild desktop assets for, e.g. v0.4.2.0'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
desktop-linux:
|
||||
name: Build Linux desktop image (+deb when dpkg present)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
git clone https://git.trevena.info/nick/incido.git repo
|
||||
cd repo
|
||||
git fetch --depth=1 origin tag "$RELEASE_TAG" || true
|
||||
git fetch --tags origin
|
||||
git checkout "$RELEASE_TAG"
|
||||
|
||||
- name: Set up JDK 17
|
||||
run: |
|
||||
WORKDIR=/var/lib/gitea-runner/work
|
||||
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
|
||||
mkdir -p "$WORKDIR/jdk"
|
||||
tar -xzf /tmp/jdk.tar.gz -C "$WORKDIR/jdk" --strip-components=1
|
||||
rm /tmp/jdk.tar.gz
|
||||
fi
|
||||
echo "JAVA_HOME=$WORKDIR/jdk" >> $GITHUB_ENV
|
||||
echo "PATH=$WORKDIR/jdk/bin:$PATH" >> $GITHUB_ENV
|
||||
|
||||
- name: Set up Android SDK
|
||||
run: |
|
||||
# Desktop modules don't use it, but AGP evaluation of :app /
|
||||
# :composeApp needs ANDROID_HOME during the configuration
|
||||
# phase of every build in this repo. Same cache as dev.yml.
|
||||
WORKDIR=/var/lib/gitea-runner/work
|
||||
SDK=$WORKDIR/android-sdk
|
||||
if [ ! -d "$SDK/cmdline-tools/latest" ]; then
|
||||
mkdir -p "$SDK"
|
||||
wget -q 'https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip' -O /tmp/cmdline-tools.zip
|
||||
unzip -q /tmp/cmdline-tools.zip -d /tmp/cmdline-tools-extract
|
||||
mkdir -p "$SDK/cmdline-tools"
|
||||
mv /tmp/cmdline-tools-extract/cmdline-tools "$SDK/cmdline-tools/latest"
|
||||
rm -rf /tmp/cmdline-tools.zip /tmp/cmdline-tools-extract
|
||||
yes | "$SDK/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null 2>&1 || true
|
||||
"$SDK/cmdline-tools/latest/bin/sdkmanager" --install \
|
||||
"platform-tools" \
|
||||
"platforms;android-34" \
|
||||
"build-tools;34.0.0" > /dev/null 2>&1
|
||||
fi
|
||||
echo "ANDROID_HOME=$SDK" >> $GITHUB_ENV
|
||||
echo "ANDROID_SDK_ROOT=$SDK" >> $GITHUB_ENV
|
||||
|
||||
- name: Build desktop distribution
|
||||
timeout-minutes: 30
|
||||
run: |
|
||||
cd repo
|
||||
chmod +x gradlew
|
||||
./gradlew --stop 2>/dev/null || true
|
||||
# App-image first — it needs no host tooling (Phase 0 Q6).
|
||||
./gradlew :desktopApp:createDistributable :desktopApp:printPackageVersion --no-daemon
|
||||
VERSION=$(./gradlew -q :desktopApp:printPackageVersion | grep PACKAGE-VERSION | awk '{print $2}')
|
||||
echo "PKG_VERSION=$VERSION" >> $GITHUB_ENV
|
||||
IMAGE_DIR=desktopApp/build/compose/binaries/main/app/incido
|
||||
test -x "$IMAGE_DIR/bin/incido"
|
||||
# M5.3 contract: smoke the IMAGE, not just the run task (the
|
||||
# jlink runtime hides missing modules until inside the image).
|
||||
if command -v xvfb-run >/dev/null 2>&1; then
|
||||
rm -rf /tmp/ci-desktop-smoke
|
||||
xvfb-run -a "$IMAGE_DIR/bin/incido" --data-dir /tmp/ci-desktop-smoke --self-test --exit-after 6 \
|
||||
| tee /tmp/desktop-smoke.log
|
||||
grep -q 'SELFTEST wrote note' /tmp/desktop-smoke.log
|
||||
echo 'Image smoke PASS'
|
||||
else
|
||||
echo 'NO xvfb on this runner — image smoke SKIPPED (recorded, not faked).'
|
||||
fi
|
||||
# deb only when dpkg exists; rpm needs rpmbuild (absent here).
|
||||
if command -v dpkg >/dev/null 2>&1; then
|
||||
./gradlew :desktopApp:packageDeb --no-daemon || \
|
||||
echo 'deb packaging failed (recorded; app-image still shipped)'
|
||||
else
|
||||
echo 'NO dpkg on this runner — deb build skipped (recorded).'
|
||||
fi
|
||||
|
||||
- name: Stage assets
|
||||
run: |
|
||||
cd repo
|
||||
VERSION="${PKG_VERSION:-$RELEASE_TAG}"
|
||||
IMAGE_DIR=desktopApp/build/compose/binaries/main/app/incido
|
||||
# Bundle the M5.3 .desktop template + icon INSIDE the tarball.
|
||||
cp desktopApp/packaging/incido.desktop desktopApp/packaging/icon.png "$IMAGE_DIR/"
|
||||
tar -czf "Incido-${VERSION}-linux-x64.tar.gz" -C "$(dirname "$IMAGE_DIR")" incido
|
||||
ls -la Incido-*.tar.gz
|
||||
cp desktopApp/build/compose/binaries/main/deb/*.deb "Incido-${VERSION}-linux-x64.deb" 2>/dev/null \
|
||||
|| echo 'no deb produced (dpkg absent or failed) — asset list will omit it'
|
||||
|
||||
- name: Attach desktop assets to the release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.TOKEN }}
|
||||
run: |
|
||||
set -e
|
||||
cd repo
|
||||
TAG="$RELEASE_TAG"
|
||||
API="http://192.168.8.17:3000/api/v1/repos/nick/incido"
|
||||
RELEASE_ID=$(curl -s "$API/releases/tags/$TAG" \
|
||||
-H "Authorization: token $GH_TOKEN" \
|
||||
| python3 -c "import sys,json; print(json.load(sys.stdin).get('id','') or '')")
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
echo "No release for $TAG yet (APK release job may not have run) — creating it."
|
||||
RELEASE_ID=$(curl -s -X POST "$API/releases" \
|
||||
-H "Authorization: token $GH_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":\"Desktop assets for $TAG\",\"draft\":false,\"prerelease\":false}" \
|
||||
| python3 -c "import sys,json; print(json.load(sys.stdin).get('id','') or '')")
|
||||
fi
|
||||
test -n "$RELEASE_ID"
|
||||
for ASSET in Incido-*.tar.gz Incido-*.deb; do
|
||||
[ -f "$ASSET" ] || continue
|
||||
for attempt in 1 2 3 4 5; do
|
||||
echo "--- Uploading $ASSET (attempt $attempt/5) ---"
|
||||
curl -s -f -X POST "$API/releases/$RELEASE_ID/assets?name=$ASSET" \
|
||||
-H "Authorization: token $GH_TOKEN" \
|
||||
-F "attachment=@$ASSET" \
|
||||
--max-time 900 --retry 2 --retry-all-errors --retry-delay 15 >/dev/null || true
|
||||
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']=='$ASSET' for a in d['assets']) else 1)"; then
|
||||
echo "Verified: $ASSET attached."
|
||||
break
|
||||
fi
|
||||
[ "$attempt" = 5 ] && { echo "ERROR: $ASSET not attached after 5 attempts"; exit 1; }
|
||||
sleep 15
|
||||
done
|
||||
done
|
||||
|
||||
# Deferred per phase plan §8 (macOS/Windows GA = Phase 2): enable when
|
||||
# this Gitea instance has runner labels for those OSes. jpackage will
|
||||
# not cross-compile; each OS needs its own host.
|
||||
#
|
||||
# desktop-macos:
|
||||
# runs-on: macos-latest # (a self-hosted macOS runner label)
|
||||
# steps: [ ...createDistributable with Dmg; codesigning TBD... ]
|
||||
# desktop-windows:
|
||||
# runs-on: windows-latest # (a self-hosted Windows runner label)
|
||||
# steps: [ ...createDistributable with Msi/Exe... ]
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
|
||||
- name: Set up JDK 17
|
||||
run: |
|
||||
WORKDIR=/tmp/gitea-runner-work
|
||||
WORKDIR=/var/lib/gitea-runner/work
|
||||
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
|
||||
mkdir -p "$WORKDIR/jdk"
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
|
||||
- name: Set up Android SDK
|
||||
run: |
|
||||
WORKDIR=/tmp/gitea-runner-work
|
||||
WORKDIR=/var/lib/gitea-runner/work
|
||||
SDK=$WORKDIR/android-sdk
|
||||
if [ ! -d "$SDK/cmdline-tools/latest" ]; then
|
||||
mkdir -p "$SDK"
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
run: |
|
||||
cd repo
|
||||
chmod +x gradlew
|
||||
export JAVA_HOME=/tmp/gitea-runner-work/jdk
|
||||
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
|
||||
./gradlew assembleDebug --no-daemon
|
||||
@@ -4,21 +4,42 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- '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:
|
||||
build-release:
|
||||
name: Build & attach release APK
|
||||
runs-on: ubuntu-latest
|
||||
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:
|
||||
- name: Checkout
|
||||
run: |
|
||||
git clone https://git.trevena.info/nick/incido.git repo
|
||||
git clone --depth=1 https://git.trevena.info/nick/incido.git 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 checkout "$RELEASE_TAG"
|
||||
|
||||
- name: Set up JDK 17
|
||||
run: |
|
||||
WORKDIR=/tmp/gitea-runner-work
|
||||
WORKDIR=/var/lib/gitea-runner/work
|
||||
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
|
||||
mkdir -p "$WORKDIR/jdk"
|
||||
@@ -30,7 +51,7 @@ jobs:
|
||||
|
||||
- name: Set up Android SDK
|
||||
run: |
|
||||
WORKDIR=/tmp/gitea-runner-work
|
||||
WORKDIR=/var/lib/gitea-runner/work
|
||||
SDK=$WORKDIR/android-sdk
|
||||
if [ ! -d "$SDK/cmdline-tools/latest" ]; then
|
||||
mkdir -p "$SDK"
|
||||
@@ -39,6 +60,8 @@ jobs:
|
||||
mkdir -p "$SDK/cmdline-tools"
|
||||
mv /tmp/cmdline-tools-extract/cmdline-tools "$SDK/cmdline-tools/latest"
|
||||
rm -rf /tmp/cmdline-tools.zip /tmp/cmdline-tools-extract
|
||||
export JAVA_HOME=$WORKDIR/jdk
|
||||
export PATH=$JAVA_HOME/bin:$PATH
|
||||
yes | "$SDK/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null 2>&1 || true
|
||||
"$SDK/cmdline-tools/latest/bin/sdkmanager" --install \
|
||||
"platform-tools" \
|
||||
@@ -49,75 +72,170 @@ jobs:
|
||||
echo "ANDROID_SDK_ROOT=$SDK" >> $GITHUB_ENV
|
||||
echo "PATH=$SDK/cmdline-tools/latest/bin:$SDK/platform-tools:$PATH" >> $GITHUB_ENV
|
||||
|
||||
# The release signing config in app/build.gradle.kts only attaches a
|
||||
# storeFile when keystore/release.jks exists, and that .jks is
|
||||
# gitignored -- so the CI runner must mint its own. We use the exact
|
||||
# dev keystore documented in keystore/README.md (alias "incido",
|
||||
# both passwords "incido_dev_keystore"). Move to a Gitea Actions
|
||||
# secret + production keystore before publishing to Play / F-Droid.
|
||||
- name: Generate dev release keystore
|
||||
run: |
|
||||
cd repo
|
||||
mkdir -p keystore
|
||||
keytool -genkey -noprompt -v \
|
||||
-keystore keystore/release.jks \
|
||||
-keyalg RSA -keysize 2048 -validity 10000 \
|
||||
-alias incido \
|
||||
-storepass incido_dev_keystore \
|
||||
-keypass incido_dev_keystore \
|
||||
-dname "CN=Incido Dev, OU=Local, O=Incido, L=Local, ST=Local, C=NZ"
|
||||
|
||||
- name: Build debug + release APKs
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.TOKEN }}
|
||||
timeout-minutes: 25
|
||||
run: |
|
||||
set -e
|
||||
cd repo
|
||||
chmod +x gradlew
|
||||
export JAVA_HOME=/tmp/gitea-runner-work/jdk
|
||||
export ANDROID_HOME=/tmp/gitea-runner-work/android-sdk
|
||||
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
|
||||
if [ ! -f /var/lib/gitea-runner/work/release.jks ]; then
|
||||
echo "Minting new persistent CI keystore"
|
||||
keytool -genkey -noprompt -v \
|
||||
-keystore /var/lib/gitea-runner/work/release.jks \
|
||||
-keyalg RSA -keysize 2048 -validity 10000 \
|
||||
-alias incido \
|
||||
-storepass incido_dev_keystore \
|
||||
-keypass incido_dev_keystore \
|
||||
-dname "CN=Incido Dev, OU=Local, O=Incido, L=Local, ST=Local, C=NZ"
|
||||
else
|
||||
echo "Reusing persistent CI keystore from runner cache"
|
||||
fi
|
||||
cp /var/lib/gitea-runner/work/release.jks keystore/release.jks
|
||||
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
|
||||
|
||||
# Build both variants; copyReleaseApks finalizes assembleRelease and
|
||||
# drops version-stamped APKs at the repo root:
|
||||
# Incido-<version>-debug.apk
|
||||
# Incido-<version>-release.apk
|
||||
./gradlew assembleDebug assembleRelease --no-daemon
|
||||
|
||||
# Verify both files exist before proceeding
|
||||
TAG="${GITHUB_REF##*/}"
|
||||
chmod +x ./gradlew
|
||||
./gradlew --stop 2>/dev/null || true
|
||||
./gradlew assembleDebug assembleRelease --no-daemon --stacktrace 2>&1 | tee /tmp/build.log
|
||||
BUILD_STATUS=${PIPESTATUS[0]}
|
||||
echo "Gradle exit status: $BUILD_STATUS"
|
||||
if [ $BUILD_STATUS -ne 0 ]; then
|
||||
echo "Build failed"
|
||||
tail -100 /tmp/build.log
|
||||
exit 1
|
||||
fi
|
||||
ls -la app/build/outputs/apk/debug/ app/build/outputs/apk/release/
|
||||
|
||||
- name: Create release + attach both APKs
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.TOKEN }}
|
||||
GH_TOKEN: ${{ secrets.TOKEN }}
|
||||
run: |
|
||||
set -e
|
||||
cd repo
|
||||
TAG="${GITHUB_REF##*/}"
|
||||
TAG="$RELEASE_TAG"
|
||||
VERSION="${TAG#v}"
|
||||
API="http://192.168.8.17:3000/api/v1/repos/nick/incido"
|
||||
APK_DEBUG="Incido-$VERSION-debug.apk"
|
||||
APK_RELEASE="Incido-$VERSION-release.apk"
|
||||
|
||||
echo "Creating release for tag: $TAG"
|
||||
RELEASE_ID=$(curl -s -X POST "https://git.trevena.info/api/v1/repos/nick/incido/releases" \
|
||||
-H "Authorization: token $GITHUB_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"tag_name\": \"$TAG\",
|
||||
\"name\": \"$TAG\",
|
||||
\"draft\": false,
|
||||
\"prerelease\": false
|
||||
}" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id','') or '')")
|
||||
echo "Release ID: $RELEASE_ID"
|
||||
echo "Tag: $TAG Version: $VERSION"
|
||||
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
echo "ERROR: Failed to create release"
|
||||
exit 1
|
||||
# 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
|
||||
|
||||
for APK in "Incido-${VERSION}-debug.apk" "Incido-${VERSION}-release.apk"; do
|
||||
echo "Attaching $APK to release $RELEASE_ID"
|
||||
RESPONSE=$(curl -s -X POST \
|
||||
"https://git.trevena.info/api/v1/repos/nick/incido/releases/$RELEASE_ID/assets?name=$APK" \
|
||||
-H "Authorization: token $GITHUB_TOKEN" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary "@$APK")
|
||||
echo "Attach response: $RESPONSE"
|
||||
echo "--- Check for existing release ---"
|
||||
RELEASE_ID=$(curl -s "$API/releases/tags/$TAG" \
|
||||
-H "Authorization: token $GH_TOKEN" \
|
||||
| python3 -c "import sys,json; print(json.load(sys.stdin).get('id','') or '')")
|
||||
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
echo "--- Create release ---"
|
||||
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
|
||||
RELEASE_ID=$(curl -s -X POST "$API/releases" \
|
||||
-H "Authorization: token $GH_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @/tmp/release_payload.json \
|
||||
| python3 -c "import sys,json; print(json.load(sys.stdin).get('id','') or '')")
|
||||
else
|
||||
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
|
||||
|
||||
echo "Release ID: $RELEASE_ID"
|
||||
if [ -z "$RELEASE_ID" ]; then echo "ERROR: no release ID"; exit 1; fi
|
||||
|
||||
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
|
||||
if echo "$APK" | grep -q "debug"; then
|
||||
APK_PATH="app/build/outputs/apk/debug/app-debug.apk"
|
||||
else
|
||||
APK_PATH="app/build/outputs/apk/release/app-release.apk"
|
||||
fi
|
||||
if [ ! -f "$APK_PATH" ]; then
|
||||
echo "ERROR: APK not found: $APK_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "--- Deleting stale assets for $APK ---"
|
||||
python3 /tmp/delete_asset.py "$API" "$RELEASE_ID" "$APK" "$GH_TOKEN"
|
||||
|
||||
upload_asset "$APK" "$APK_PATH" || exit 1
|
||||
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 ---"
|
||||
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')"
|
||||
@@ -24,9 +24,16 @@ captures/
|
||||
# Kotlin
|
||||
.kotlin/
|
||||
|
||||
# ObjectBox generated models (kept under build, but ignore if moved out)
|
||||
**/objectbox-models/
|
||||
**/objectbox-models/default.json
|
||||
# ObjectBox generated models. The *model file itself* is the schema
|
||||
# contract — UIDs in it must stay stable across machines and across the two
|
||||
# modules that generate from the same entities (:core:data and
|
||||
# :core:data-jvm), so default.json is tracked and everything else stays out.
|
||||
**/objectbox-models/*
|
||||
!**/objectbox-models/default.json
|
||||
# ObjectBox self-extraction lands this at the process CWD (repo root for
|
||||
# gradle runs) — a build artifact, never source (the tracked copies live in
|
||||
# desktopApp/ and core/data-jvm/).
|
||||
/libobjectbox-jni-linux-x64.so
|
||||
|
||||
# VS Code
|
||||
.vscode/
|
||||
@@ -38,3 +45,4 @@ Thumbs.db
|
||||
# Built APKs at the repo root (stamped with version — see Incido
|
||||
# Development Plan §11 for the release build procedure).
|
||||
incido-*.apk
|
||||
Incido-*.apk
|
||||
@@ -63,8 +63,19 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
or your feature's manual verification steps.
|
||||
|
||||
### 5. Commit
|
||||
We use [Conventional Commits](https://www.conventionalcommits.org/) so
|
||||
the changelog can be generated automatically later:
|
||||
We use [Conventional Commits](https://www.conventionalcommits.org/).
|
||||
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 |
|
||||
|------|---------|
|
||||
@@ -142,7 +153,7 @@ under GPL-3.0 before opening the PR.
|
||||
> fails immediately — there's a validator in `app/build.gradle.kts`.
|
||||
|
||||
1. Bump `versionCode` (+1) and `versionName` in `app/build.gradle.kts`.
|
||||
2. Update the Development Plan §10 history table with the new dot-name.
|
||||
2. Update the Development Plan §10 history table with the new dot-name, and give the release its `PREVIOUS_HISTORY.md` section — opening, as every release does from v0.4.2.0 on, with the standard backup-warning callout (users must back up before installing).
|
||||
3. Tag the commit: `git tag -s vX.Y.Z.W -m "vX.Y.Z.W — short summary"`.
|
||||
4. `./gradlew assembleDebug assembleRelease` — confirm both green.
|
||||
5. Upload `app/build/outputs/apk/release/app-release.apk` to Gitea Releases.
|
||||
|
||||
@@ -135,7 +135,7 @@ incido/
|
||||
| F1 | **List of currently saved notes** | On app launch (and at all times when on the home screen), the user sees a scrollable list of all notes currently stored in the database. Each note is represented as a card showing a preview of its content and its last-updated timestamp. |
|
||||
| F2 | Create a new note | Tapping "+" opens an empty editor; saving adds the note to the list and database. |
|
||||
| F3 | Edit an existing note | Tapping a note card opens the editor pre-filled with its content; saving updates the note in place and reflects the change on the list. |
|
||||
| F4 | Delete a note | A delete action on a note card (or in the editor) removes the note from both the list and the database. |
|
||||
| F4 | Delete a note | A delete action on a note card (or in the editor) moves the note to the Trash filter. Notes in Trash are excluded from Home, Favorites, Untagged, tag, and ordinary search views; deleting a note from Trash destroys it permanently. |
|
||||
| F5 | Data persists across restarts | Notes created in one session are visible in the list after force-closing and reopening the app. |
|
||||
| F6 | Empty state | When the list is empty (no notes saved), show a friendly empty-state message instead of an empty list. |
|
||||
| F7 | List refreshes automatically | The list of saved notes updates immediately after creating, editing, or deleting a note — no manual reload required. |
|
||||
@@ -168,7 +168,7 @@ All features listed in §6.
|
||||
- Displays the note content (first ~3 lines, truncated)
|
||||
- Shows relative timestamp ("2 min ago", "Yesterday", etc.)
|
||||
- Whole card is tappable → opens editor for that note
|
||||
- Long-press or swipe reveals delete action
|
||||
- Long-press or swipe reveals move-to-Trash action; Trash cards expose Restore and permanent Delete
|
||||
|
||||
### 5.2 Screen 2 — Note Editor
|
||||
- **Top bar:** Back arrow + Save action
|
||||
@@ -176,7 +176,7 @@ All features listed in §6.
|
||||
- **Behavior:**
|
||||
- Back arrow without save = discard (no confirmation in v0.1; v0.2 should confirm if content changed)
|
||||
- Save action persists and returns to the list; the updated/created note is visible immediately on the list
|
||||
- Delete button (only when editing existing note) at bottom or in top bar overflow
|
||||
- Delete button (only when editing existing note) at bottom or in top bar overflow; it moves the note to Trash
|
||||
|
||||
### 5.3 Theming
|
||||
- **Material 3** (Material You) design system
|
||||
@@ -196,7 +196,6 @@ This list is the canonical backlog. Items can be promoted into future versions a
|
||||
- Color-coded notes and labels
|
||||
- Pinning notes to top
|
||||
- Archive (vs. delete) with archive view
|
||||
- Trash with soft-delete and recovery window
|
||||
- Full-text search across note content
|
||||
- Tag / hashtag system
|
||||
- Search by tag or content
|
||||
@@ -204,6 +203,11 @@ This list is the canonical backlog. Items can be promoted into future versions a
|
||||
- Image attachments from camera and gallery
|
||||
- Audio attachments / voice notes
|
||||
|
||||
> **Trash status:** Soft-delete, Trash filtering, Restore, and permanent
|
||||
> deletion are implemented in the current Android app. There is no
|
||||
> automatic purge window yet; a note is destroyed immediately when it is
|
||||
> permanently deleted from Trash.
|
||||
|
||||
### 6.2 On-Device Machine Learning
|
||||
- **OCR (Optical Character Recognition):**
|
||||
- Extract text from images attached to notes
|
||||
@@ -297,8 +301,9 @@ v0.1 is considered complete when **all** of the following are true:
|
||||
[ ] Tap "Test note 2" card — editor opens with existing content
|
||||
[ ] Change to "Test note 2 (edited)" — tap save
|
||||
[ ] Confirm updated text appears on the card on the list
|
||||
[ ] Long-press "Test note 3" — delete option appears
|
||||
[ ] Confirm delete — note removed from the list
|
||||
[ ] Long-press "Test note 3" — move-to-Trash option appears
|
||||
[ ] Confirm move — note disappears from the list and appears in Trash
|
||||
[ ] Restore from Trash — note returns to the list; delete permanently from Trash — note is destroyed
|
||||
[ ] Force-stop app from system settings
|
||||
[ ] Reopen app — "Test note 1" and "Test note 2 (edited)" both visible on the list
|
||||
[ ] Pass — v0.1 verified
|
||||
@@ -365,11 +370,22 @@ A short reference for AI assistants:
|
||||
|
||||
| Version | Date | Notes |
|
||||
|---------|------|-------|
|
||||
| 0.4.2.0 | 2026-09-23 | **Feature release — voice notes, with a maintenance pass folded in (Opus recording format + editor toolbar reorder).** **1. Voice notes.** New `NoteType.VOICE_NOTE` toggled by a mic button on the editor's bottom toolbar (`RECORD_AUDIO` requested on first tap into voice mode): `VoiceRecorder` (framework `MediaRecorder`) writes the take via `cacheDir/voice_rec/`; `VoiceNoteSection` pins a record/re-record card plus a `MediaPlayer`-backed player bar (play/pause, seek, elapsed/total) at the top of the body, with a Download action (MediaStore Downloads on API 29+, FileProvider share-sheet fallback on API 26–28). Takes ride the ordinary attachment pipeline (`PendingAttachment` → `NoteAttachment`) — encrypted at rest, included in backups, survive type changes; one take per note, re-recording replaces the old one. `Note.firstAudioAttachment` convenience; mic badge on cards; zero new dependencies. **2. Opus audio format (maintenance).** Takes record as Opus-in-Ogg (`.opus` — 32 kbps, single channel, 48 kHz) via `OutputFormat.OGG` + `AudioEncoder.OPUS` on API 29+ (the public-API floor for OGG output), keeping the previous AAC/MPEG-4 (`.m4a`, 96 kbps) path for API 26–28; `VoiceRecorder.recordedMimeType` propagates the actual container to the attachment mime (`audio/ogg`), display name (`Voice_*.opus`), playback cache file, MediaStore download mime and share-intent type. Opus frame size / encoder complexity are platform defaults — `MediaRecorder` exposes no knob (120 ms frames + complexity 10 would require bundled native libopus; deferred). Existing `.m4a` takes still play; no migration. **3. Editor toolbar reorder (maintenance).** Bottom action row is now Photo · Voice · Attach · Tasks · Shopping list, with the hashtag button justified flush right via a weighted `Spacer`, separated from the cluster; handlers, permission flows and tints unchanged. **4. Backup-warning convention.** From this version every release section opens with a ⚠️ back-up-before-installing callout (PREVIOUS_HISTORY.md header, §11.1, CONTRIBUTING release process, README upgrade callout). **Lockstep (§11.1).** versionCode 37→38, versionName 0.4.1.1→0.4.2.0, `SettingsViewModel.APP_VERSION` bumped, README intro + current-release line + smoke-test step, PREVIOUS_HISTORY.md section (backup callout first; feeds the release description + `Incido-0.4.2.0-changes.md` asset), `ReleaseNotes.RECENT` (v0.3.8.0 drops off the 5-entry tail). |
|
||||
| 0.4.1.1 | 2026-09-23 | **Emergency hotfix — two v0.4.1.0 editor regressions.** **1. Saved notes landed in Drafts.** `NoteEditorViewModel.save()` published the note but left `UiState.existing.isDraft = true`, so the editor's dispose-time `flushDraft()` immediately re-persisted the just-saved note as a draft — every confirmed note ended up in Drafts. The save path now adopts the published row into state (`isDraft = false`, current hashtags kept), letting `persistDraftNow()`'s already-published guard turn that flush into a no-op. **2. Enter on a shopping-list Price field wrapped the cursor to the Title.** A bare `ImeAction.Next` with no handler fell through to system focus traversal — price being the row's last field inside the LazyColumn wrapped focus all the way back to the Title; the field now passes `KeyboardActions(onNext = { onAddAfter() })`, matching Enter on the Product field (fresh row, cursor in its Product box). **Lockstep (§11.1).** versionCode 36→37, versionName "0.4.1.0"→"0.4.1.1", SettingsViewModel.APP_VERSION bumped, README current-release line + two smoke-test regression steps, PREVIOUS_HISTORY.md section (feeds the release description + `Incido-0.4.1.1-changes.md` asset), ReleaseNotes.RECENT (v0.3.8.1 drops off the 5-entry tail). |
|
||||
| 0.4.1.0 | 2026-09-23 | **Feature release — colour filters + auto-saved drafts, plus Trash & editor polish.** **1. Colour filters.** The drawer gains a horizontal five-swatch strip (Blue / Green / Amber / Red / Purple) between Favorites and Drafts — no labels, the colours are self-explanatory; selecting a swatch shows ONLY **active** notes of that colour (tagged and untagged eligible, trashed never — same rules as Favorites / Untagged), search narrows within the colour, re-tapping the selected swatch returns to Home. `NoteFilter` gains `ByColor` (+ `color:<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.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.1 | 2026-08-19 | **Emergency hotfix** — two UX bugs in the v0.3.6.0 New/Edit screen. **1. Top-bar title crowded the action buttons.** `NoteEditorScreen` used `CenterAlignedTopAppBar`, but with six actions on the right (camera, attach, tag, favourite, save, more) the visually-centred title ended up pressed against the action cluster — users read it as "the title is on the right". Fix: swap the top bar for `TopAppBar` (Material 3's left-aligned variant) so "New"/"Edit" sits flush right of the back arrow on the left and the action cluster keeps the right edge. Import swap; no behavioural change for the actions or title text. **2. Colour chooser was not equally spaced.** The picker `Row` had `padding(vertical = 4.dp)` (4dp above + 4dp below), but the `OutlinedTextField` below it has an intrinsic top inset (~16dp) inside its border, so the perceived gap from the picker to the first line of the note dwarfed the gap from the title bar's bottom to the picker's top — to the user, "the picker is jammed up against the title bar". Fix: remove the row's `vertical = 4.dp` and bracket it with two explicit `Spacer(Modifier.height(12.dp))` siblings (one before the row, one after) so the picker sits 12dp from the title bar AND 12dp from the field's top border. The asymmetric `OutlinedTextField` internal padding is now matched on both sides of the picker, giving visually equal breathing room up and down. versionCode 27→28, versionName "0.3.6.0"→"0.3.6.1", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.6.0 | 2026-08-19 | **Maintenance release** — share-into titles + encryption-key recovery. **1. Share webpages into Incido with a subject line.** `Intent.EXTRA_SUBJECT` from an inbound `ACTION_SEND` is now routed through `NoteEditorViewModel.initialSharedSubject` and prepended to the new note's content as a first line ("Page title") above the shared body/URL (already supported since v0.3.1.0). Browsers fill `EXTRA_SUBJECT` with the page title when the user shares a URL, so the resulting note reads naturally as a bookmark without ever leaving the device — fully offline, no `INTERNET` permission. **2. Export / Import encryption key.** New rows in Settings → Security expose the underlying AES-256 wrapping key as a passphrase-protected `.inckey` envelope (PBKDF2 200k iters + AES-GCM): "Export encryption key" writes the wrapped blob to a user-chosen SAF uri, "Import encryption key" reads it back, validates the passphrase, and atomically replaces the active key — with a clear warning dialog listing the consequences ("your existing encrypted notes will become unverifiable"). The 32-byte raw key never appears on screen or in logs; only the wrapped envelope crosses the SAF boundary. versionCode 26→27, versionName "0.3.5.1"→"0.3.6.0", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.5.1 | 2026-08-17 | **Emergency hotfix** — two UX bugs in v0.3.5.0. **1. "Encrypted" badge silently failed to appear on the first enable.** Audit found `EncryptionVerifier.checkNow()` early-returned with `if (_checking.value) return` whenever a verify-all was in flight. The startup pass launched from `AppContainer.init` could still be running when the user toggled Encrypt-at-rest in Settings; the post-migration re-check then silently dropped, the startup pass eventually wrote its stale (pre-encryption, empty verified-id) result back to the StateFlow, and the cards never earned the badge until the second toggle or a relaunch let a fresh check actually run. Fix: drop the `_checking` skip-guard and replace it with a `kotlinx.coroutines.sync.Mutex` that serializes checks in invocation order. Every `checkNow()` call now takes its turn and the last call's result wins, so the post-migration check always produces the fresh verified-id set; the startup pass is cheap (no encrypted rows yet → all skips) so user-triggered checks after a real migration only wait milliseconds. **2. "Encrypted" badge UX on note cards.** v0.3.5.0 rendered the indicator as a centred `Row` with a lock icon + "Encrypted" label at the card's bottom edge. Replace with a bare 14 dp `Lock` `Icon` sitting immediately to the LEFT of the timestamp inside the card's existing bottom Row — the row already uses `Alignment.CenterVertically`, so the icon is vertically centred with the date/time and lives in the same left-anchored position on every card regardless of card content (tag row, body preview, checklist summary). The icon keeps the existing `contentDescription = "Encrypted"`. versionCode 25→26, versionName "0.3.5.0"→"0.3.5.1", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.5.0 | 2026-08-17 | **Maintenance release** — real at-rest encryption, verified "Encrypted" badge, and screenshot blocking. **1. Real field-level encryption ("Encrypt in place" now works).** Audit of the v0.3.2.0 toggle found it was cosmetic: `ObjectBoxStore.init()` ignored the key (`@Suppress("UNUSED_PARAMETER")`), `AppContainer` always passed `encryptionKey = null`, and the OSS ObjectBox 4.0.3 `BoxStoreBuilder` exposes no encryption API at all (verified against the local artifact — page-level encryption is ObjectBox Sync/Pro only). Fix: application-layer field encryption. `NoteEntity` gains `cipherVersion` (0=plain, 1=AES-256-GCM) + `contentBlob`; `NoteAttachmentEntity` gains the same pair for `bytesBlob` — additive schema, auto-migrated. New `FieldCipher` abstraction in `:core:data` with `AesGcmFieldCipher` in `:composeApp` (fresh random 12-byte nonce per blob; GCM tag = integrity proof), keyed by the existing Keystore-wrapped 32-byte key from `ObjectBoxKeyProvider`. The repository consults a shared `CipherHolder` on every read/write (encrypt-on-write, decrypt-on-read, in-memory content search while encrypted); `NoteCryptoService` sweeps all rows in place with progress. Toggling encryption ON installs the cipher and encrypts every plaintext note + attachment row live (no restart); toggling OFF decrypts everything first, then removes the cipher and deletes the key; disabling Security entirely also runs the decrypt sweep so no data is orphaned. AES-256-GCM is the correct PQ-era choice for data at rest (NIST: Grover halves effective security → ~128-bit residual; no public-key crypto in this path). **2. Verified "Encrypted" badge on cards.** New `EncryptionVerifier` runs on every app open (and after each migration): full trial-decrypt of every `cipherVersion = 1` note row; the GCM auth tag passing is the proof of integrity. Only notes in the resulting verified-id set get a bottom-centre "Encrypted" label (with lock icon) on their card — never derived from the settings flag alone; rows that fail verification are reported and excluded. **3. Block screenshots toggle (default ON).** New `UserSettings.blockScreenshots` (DataStore-backed, defaults true); `MainActivity` applies/clears `FLAG_SECURE` from a startup snapshot + live settings-flow collection, blocking screenshots, screen recording, and app-switcher previews; Settings → Security gains the "Block screenshots" switch. Settings copy for encryption updated (no longer claims a restart is required). versionCode 24→25, versionName "0.3.4.0"→"0.3.5.0", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.4.0 | 2026-08-17 | **Maintenance release** — three changes. **1. Attachment indicator on note cards** — a paperclip icon (`Icons.Filled.AttachFile`) now appears on the right edge of every card whose note carries at least one attachment (any type — image, PDF, audio…). It is a non-interactive `Icon` (24 dp, `contentDescription = "Has attachments"`) aligned `Alignment.CenterEnd` with `padding(end = 16.dp)` so its glyph centre sits at 28 dp from the right edge — the same vertical column as the ⋮ overflow `IconButton` (top) and the favourite star (bottom), exactly halfway between them (both neighbours centre their 24 dp glyphs at 28 dp: 4 dp padding + 24 dp inside a 48 dp `IconButton`). Bare `Icon` rather than `IconButton` so it never intercepts the whole-card tap that opens the editor. **2. Light-theme readability over image thumbnails** — the card's 0.45-alpha black scrim always renders the background dark, but the overlay content kept the theme-driven colours, so in Light mode dark text sat on a dark photo (all but invisible). Fix: when a thumbnail is present every overlay switches to a forced light palette regardless of theme — title pure white; body preview, checklist summary, timestamp, ⋮ icon, unfilled star, paperclip and "+N" tag overflow white @ 85 %; hashtag chips white; favourited star a light amber (`#FFD54F`) so "favourited" stays distinguishable; the Card's `contentColor` is also set to white. Plain (no-thumbnail) cards are untouched and keep their existing tinted/surface colours. `HashtagRow` now takes caller-supplied `tagColor` / `overflowColor` params. **3. Auto-Lock = Immediate + file-picker hotfix** — with Auto-Lock set to "Immediately", attaching a file (paperclip → SAF picker), taking a photo (camera), opening an attachment in the system viewer, or exporting/importing a backup locked the app the moment the external activity returned: the picker backgrounds the Activity (`ON_STOP`), the return fires `ON_RESUME`, and the 0 ms timeout always re-locks. The lock gate then tore down the `NavHost` from composition, destroying the editor's `NavBackStackEntry` ViewModelStore — so the unsaved note vanished and the picker result never landed. Fix: `SecurityManager` gains an in-flight flag (`externalActivityInFlight`, `@Volatile`) set by a new `beginExternalActivity()` and consumed exactly once by `onAppForegrounded()`, which skips the re-lock check and clears `backgroundedAt` when the flag is set. Call sites: `NoteEditorScreen` (file picker launch, camera launch after permission grant, system-viewer `ACTION_VIEW` — `securityManager` threaded through `AttachmentStrip`/`AttachmentThumbnail`), `SettingsScreen` (backup export + import SAF launchers), with `IncidoApp` threading `resolvedSecurity` to both screens. Genuine background/foreground cycles still lock as configured; cold launch is unaffected (fresh process ⇒ flag always false). versionCode 23→24, versionName "0.3.3.8"→"0.3.4.0", SettingsViewModel.APP_VERSION bumped in lockstep. || 0.3.3.8 | 2026-08-17 | **Emergency hotfix** — the designed `incido.png` artwork (glass shield + fountain-pen nib) replaces the v0.1 placeholder launcher icon. The 2048×2048 source is downscaled (LANCZOS) into density-correct raster buckets: `mipmap-{mdpi…xxxhdpi}/ic_launcher.png` (48/72/96/144/192 px square) plus anti-aliased circular `ic_launcher_round.png` in the same buckets, and `drawable-{mdpi…xxxhdpi}/ic_launcher_foreground.png` (108/162/216/324/432 px) feeding the `mipmap-anydpi-v26` adaptive icons (`ic_launcher.xml` / `ic_launcher_round.xml`), whose stale `<monochrome>` placeholder reference is dropped and whose `ic_launcher_background` colour is re-tinted from `#6650A4` to the artwork's edge navy `#010435` so parallax exposure is seamless. The obsolete placeholder vector `drawable/ic_launcher_foreground.xml` is deleted; manifest `android:icon` / `android:roundIcon` references are unchanged. versionCode 22→23, versionName "0.3.3.7"→"0.3.3.8", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.4.0 | 2026-08-17 | **Maintenance release** — three changes. **1. Attachment indicator on note cards** — a paperclip icon (`Icons.Filled.AttachFile`) now appears on the right edge of every card whose note carries at least one attachment (any type — image, PDF, audio…). It is a non-interactive `Icon` (24 dp, `contentDescription = "Has attachments"`) aligned `Alignment.CenterEnd` with `padding(end = 16.dp)` so its glyph centre sits at 28 dp from the right edge — the same vertical column as the ⋮ overflow `IconButton` (top) and the favourite star (bottom), exactly halfway between them (both neighbours centre their 24 dp glyphs at 28 dp: 4 dp padding + 24 dp inside a 48 dp `IconButton`). Bare `Icon` rather than `IconButton` so it never intercepts the whole-card tap that opens the editor. **2. Light-theme readability over image thumbnails** — the card's 0.45-alpha black scrim always renders the background dark, but the overlay content kept the theme-driven colours, so in Light mode dark text sat on a dark photo (all but invisible). Fix: when a thumbnail is present every overlay switches to a forced light palette regardless of theme — title pure white; body preview, checklist summary, timestamp, ⋮ icon, unfilled star, paperclip and "+N" tag overflow white @ 85 %; hashtag chips white; favourited star a light amber (`#FFD54F`) so "favourited" stays distinguishable; the Card's `contentColor` is also set to white. Plain (no-thumbnail) cards are untouched and keep their existing tinted/surface colours. `HashtagRow` now takes caller-supplied `tagColor` / `overflowColor` params. **3. Auto-Lock = Immediate + file-picker hotfix** — with Auto-Lock set to "Immediately", attaching a file (paperclip → SAF picker), taking a photo (camera), opening an attachment in the system viewer, or exporting/importing a backup locked the app the moment the external activity returned: the picker backgrounds the Activity (`ON_STOP`), the return fires `ON_RESUME`, and the 0 ms timeout always re-locks. The lock gate then tore down the `NavHost` from composition, destroying the editor's `NavBackStackEntry` ViewModelStore — so the unsaved note vanished and the picker result never landed. Fix: `SecurityManager` gains an in-flight flag (`externalActivityInFlight`, `@Volatile`) set by a new `beginExternalActivity()` and consumed exactly once by `onAppForegrounded()`, which skips the re-lock check and clears `backgroundedAt` when the flag is set. Call sites: `NoteEditorScreen` (file picker launch, camera launch after permission grant, system-viewer `ACTION_VIEW` — `securityManager` threaded through `AttachmentStrip`/`AttachmentThumbnail`), `SettingsScreen` (backup export + import SAF launchers), with `IncidoApp` threading `resolvedSecurity` to both screens. Genuine background/foreground cycles still lock as configured; cold launch is unaffected (fresh process ⇒ flag always false). versionCode 23→24, versionName "0.3.3.8"→"0.3.4.0", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.3.8 | 2026-08-17 | **Emergency hotfix** — the designed `incido.png` artwork (glass shield + fountain-pen nib) replaces the v0.1 placeholder launcher icon. The 2048×2048 source is downscaled (LANCZOS) into density-correct raster buckets: `mipmap-{mdpi…xxxhdpi}/ic_launcher.png` (48/72/96/144/192 px square) plus anti-aliased circular `ic_launcher_round.png` in the same buckets, and `drawable-{mdpi…xxxhdpi}/ic_launcher_foreground.png` (108/162/216/324/432 px) feeding the `mipmap-anydpi-v26` adaptive icons (`ic_launcher.xml` / `ic_launcher_round.xml`), whose stale `<monochrome>` placeholder reference is dropped and whose `ic_launcher_background` colour is re-tinted from `#6650A4` to the artwork's edge navy `#010435` so parallax exposure is seamless. The obsolete placeholder vector `drawable/ic_launcher_foreground.xml` is deleted; manifest `android:icon` / `android:roundIcon` references are unchanged. versionCode 22→23, versionName "0.3.3.7"→"0.3.3.8", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.3.7 | 2026-08-17 | **Emergency hotfix** — when Biometric is the active lock method, the lock screen's "Authenticate" button required an extra tap before the fingerprint / face reader would start. Fix: `PinEntryScreen` now auto-launches the `BiometricPrompt` as soon as the lock screen composes in biometric-only mode (`settings.isBiometricLockActive`), via a one-shot `LaunchedEffect(biometricOnly)` guarded by an `autoLaunched` flag (so a cancelled prompt cannot re-trigger). Success → `onUnlocked()`; cancel/error → the lock screen stays with an error message and the "Authenticate" button remains as the manual-retry path. The failure message in biometric-only mode no longer mentions a PIN ("Authentication failed. Tap Authenticate to try again."). PIN mode is untouched — `biometricOnly` is false there, so the auto-launch effect never runs and the PIN field keeps its auto-focus. versionCode 21→22, versionName "0.3.3.6"→"0.3.3.7", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.3.6 | 2026-08-17 | **Emergency hotfix** — the fixed card height shipped in v0.3.3.5 (`168.dp`) proved too tall on real devices. Fix: `CARD_HEIGHT_DP` in `NoteListScreen.kt` reduced by ~15% to `143.dp` (~15% taller than the pre-0.3.3.5 wrap-content typical of ~124.dp). Everything else from v0.3.3.5 is unchanged — cards remain a single fixed height, the timestamp stays pinned to the card's bottom edge via the weighted spacer, the hashtag row is still hidden when empty, and the colour stripe still spans the full card height. versionCode 20→21, versionName "0.3.3.5"→"0.3.3.6", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
| 0.3.3.5 | 2026-08-17 | **Emergency hotfix** — the note cards on the main page used wrap-content height, so card heights varied depending on whether the note carried a body preview, hashtag row, or checklist summary (and untagged notes rendered visibly shorter than tagged ones). Fix: every `NoteCard` now has a fixed height of `168.dp` (~35% taller than the previous typical wrap-content height of ~124.dp for a title + 2-line body preview), applied via `Modifier.height(CARD_HEIGHT_DP)` on the Card. A `Spacer(Modifier.weight(1f))` inside the content column pins the timestamp row to the bottom of the fixed-height card so the layout stays consistent regardless of content; the hashtag row is still hidden entirely when the note has no tags. The left colour stripe now spans the full card height (`fillMaxHeight().width(14.dp)`) instead of the hardcoded `size(width = 14.dp, height = 110.dp)`. Thumbnail background + scrim, dog-ear, ⋮ overflow button, favourite-star overlay, and long-press menu are unaffected (all corner-anchored). versionCode 19→20, versionName "0.3.3.4"→"0.3.3.5", SettingsViewModel.APP_VERSION bumped in lockstep. |
|
||||
@@ -420,9 +436,27 @@ A small Gradle task called `copyReleaseApks` (registered in
|
||||
Settings displays the new version and the in-app release-notes
|
||||
dialog recognises it.
|
||||
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
|
||||
is the user-facing changelog — §10 keeps the historical release
|
||||
notes).
|
||||
line. **`PREVIOUS_HISTORY.md`** — append a new
|
||||
`## v<NEW_VERSION> — <DATE>` section at the top: friendly user-facing
|
||||
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)
|
||||
|
||||
@@ -503,6 +537,39 @@ adb install -r incido-<versionName>-debug.apk
|
||||
have to type it — `./gradlew assembleRelease` has already deposited
|
||||
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)
|
||||
|
||||
@@ -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.**
|
||||
@@ -6,16 +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
|
||||
trackers.
|
||||
|
||||
This repository contains the **v0.3.6.3** release: a single-user, offline
|
||||
note app with hashtags, favourites, full-text search, colour-coded
|
||||
notes, photo and file attachments, share-into from other apps and the
|
||||
web, at-rest AES-256-GCM encryption with screenshot blocking, PIN /
|
||||
biometric lock, encrypted backup and restore, and an exportable
|
||||
encryption key for device migrations. The architecture is multi-module
|
||||
Android today and is structured so iOS / Desktop ports can happen later
|
||||
without UI rewrites.
|
||||
This repository contains the **v0.4.2.0** release: a single-user, offline
|
||||
note app with hashtags, favourites, task lists, shopping lists with a
|
||||
running total, voice notes with an in-app media player and downloadable
|
||||
recordings, colour-coded notes with per-colour swatch filters,
|
||||
auto-saved drafts, photo and file attachments, share-into from other
|
||||
apps and the web, importing notes from third-party apps (Carnet /
|
||||
QuickNote `.zip` exports) directly on-device, Trash (soft delete with
|
||||
Restore / permanent delete / one-tap Empty Trash), at-rest
|
||||
AES-256-GCM encryption with screenshot blocking, PIN / biometric lock,
|
||||
encrypted backup and restore, and an exportable encryption key for
|
||||
device migrations. The architecture is multi-module Android today and is
|
||||
structured so iOS / Desktop ports can happen later without UI rewrites.
|
||||
|
||||
**Current release:** v0.3.6.3 (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` —
|
||||
> e.g. `0.3.0.0`. `MAJOR.MINOR.MAINTENANCE` are normal release numbers;
|
||||
@@ -26,74 +51,6 @@ without UI 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**, a divider, then a live scrollable
|
||||
list of the most-recently-used hashtags. Tap any entry to filter the
|
||||
list to just those notes.
|
||||
- **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
|
||||
|
||||
See [`Incido Development Plan.txt`](./Incido%20Development%20Plan.txt) at
|
||||
@@ -104,37 +61,13 @@ cross-platform ports, end-to-end sync, and security features.
|
||||
|
||||
## Changelog
|
||||
|
||||
| Version | Date | Highlights |
|
||||
|-----------|------------|------------|
|
||||
| 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`. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| 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 |
|
||||
Release notes now live **on the Releases page**: every Incido release entry
|
||||
ships the full changelog for exactly that version — rendered in the
|
||||
release description and attached beside the APKs as
|
||||
`Incido-<version>-changes.md` (generated from `PREVIOUS_HISTORY.md` by the
|
||||
release workflow).
|
||||
→ [Releases](https://git.trevena.info/nick/incido/releases)
|
||||
· [Previous release history (archive)](./PREVIOUS_HISTORY.md)
|
||||
|
||||
---
|
||||
|
||||
@@ -157,8 +90,10 @@ incido/
|
||||
│ └── data/ # ObjectBox-backed repository implementation
|
||||
├── gradle/ # Version catalog (libs.versions.toml) + wrapper
|
||||
├── keystore/ # Release signing (gitignored *.jks, README kept)
|
||||
├── scripts/ci/ # Release tooling (changelog extractor for the CI)
|
||||
├── .gitea/ # Gitea Actions workflow + issue/PR templates
|
||||
├── CONTRIBUTING.md
|
||||
├── PREVIOUS_HISTORY.md # Archived user-facing release history
|
||||
└── LICENSE
|
||||
```
|
||||
|
||||
@@ -253,11 +188,21 @@ After the first push:
|
||||
|
||||
```
|
||||
[ ] 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 "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 "Home" → back to all notes
|
||||
[ ] Tap "Trash" → list shows only soft-deleted notes
|
||||
[ ] 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 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
|
||||
[ ] Open a note → chip row above text field shows current tags (empty placeholder if none)
|
||||
[ ] Tap "#" icon → sheet opens, type "wo" → suggestions filter
|
||||
[ ] Add a new tag → chip appears, counter goes from N/5 to (N+1)/5
|
||||
|
||||
@@ -28,51 +28,47 @@ android {
|
||||
applicationId = "org.incido.app"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
// v0.3.6.3: Local-dev DX — make the missing-keystore failure
|
||||
// mode actionable.
|
||||
// - signingConfigs.release now throws GradleException at
|
||||
// config time when keystore/release.jks is missing, with
|
||||
// the exact keytool incantation from keystore/README.md
|
||||
// in the error message. Previously the signing config
|
||||
// silently fell through with no storeFile, and packageRelease
|
||||
// failed much later with the cryptic "SigningConfig release
|
||||
// is missing required property storeFile" — leaving devs
|
||||
// guessing at the cause.
|
||||
// - .gitea/workflows/release.yml already mints the keystore
|
||||
// on release runners (since v0.3.6.2), so CI is unaffected.
|
||||
// - No app/Compose code changes.
|
||||
// - versionCode monotonic +1 from v0.3.6.2 (29).
|
||||
versionCode = 30
|
||||
versionName = "0.3.6.3"
|
||||
// v0.4.1.1: EMERGENCY hotfix — two editor regressions shipped
|
||||
// in v0.4.1.0. (1) Saving a note landed it in Drafts: the save
|
||||
// path published the note but left UiState.existing.isDraft =
|
||||
// true, so the editor's dispose-time flushDraft() immediately
|
||||
// re-persisted it as a draft; the state now adopts the
|
||||
// published row (isDraft = false), letting persistDraftNow()'s
|
||||
// already-published guard make the flush a no-op. (2) Enter on
|
||||
// a shopping-list Price field fell through to system focus
|
||||
// traversal and wrapped the cursor back to the Title; it now
|
||||
// wires KeyboardActions(onNext = onAddAfter) like the Product
|
||||
// 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 ---
|
||||
// v0.3.6.3: Fail fast (at config time) with an actionable error
|
||||
// when keystore/release.jks is missing, rather than silently
|
||||
// letting packageRelease die later with the cryptic "SigningConfig
|
||||
// release is missing required property storeFile". CI (see
|
||||
// .gitea/workflows/release.yml) already mints the keystore before
|
||||
// assembleRelease (since v0.3.6.2), so this branch never fires on
|
||||
// a release runner — only on a fresh local clone.
|
||||
// The release signing config is declared even when the keystore is absent;
|
||||
// the existence check is deferred to assembleRelease execution time so that
|
||||
// assembleDebug (which doesn't need the keystore) runs cleanly on a fresh
|
||||
// clone. CI always mints the keystore before calling assembleRelease, so
|
||||
// this branch never fires in the normal workflow.
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
val keystoreFilePath = rootProject.file("keystore/release.jks")
|
||||
if (!keystoreFilePath.exists()) {
|
||||
throw GradleException(
|
||||
"Missing ${keystoreFilePath.absolutePath}.\n" +
|
||||
"Generate the dev keystore documented in " +
|
||||
"keystore/README.md:\n" +
|
||||
" keytool -genkey -noprompt -v \\\n" +
|
||||
" -keystore keystore/release.jks \\\n" +
|
||||
" -keyalg RSA -keysize 2048 -validity 10000 \\\n" +
|
||||
" -alias incido \\\n" +
|
||||
" -storepass incido_dev_keystore \\\n" +
|
||||
" -keypass incido_dev_keystore \\\n" +
|
||||
" -dname \"CN=Incido Dev, OU=Local, O=Incido, " +
|
||||
"L=Local, ST=Local, C=NZ\""
|
||||
)
|
||||
}
|
||||
storeFile = keystoreFilePath
|
||||
storeFile = rootProject.file("keystore/release.jks")
|
||||
storePassword = "incido_dev_keystore"
|
||||
keyAlias = "incido"
|
||||
keyPassword = "incido_dev_keystore"
|
||||
@@ -89,6 +85,29 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// Fail fast with an actionable message only when assembleRelease actually
|
||||
// runs and the keystore is missing — not during project configuration.
|
||||
tasks.register("validateReleaseKeystore") {
|
||||
group = "build"
|
||||
description = "Validates that keystore/release.jks exists before assembleRelease runs"
|
||||
doFirst {
|
||||
val f = rootProject.file("keystore/release.jks")
|
||||
if (!f.exists()) {
|
||||
throw GradleException(
|
||||
"Missing ${f.absolutePath}.\n" +
|
||||
"Generate the dev keystore documented in keystore/README.md:\n" +
|
||||
" keytool -genkey -noprompt -v \\\n" +
|
||||
" -keystore keystore/release.jks \\\n" +
|
||||
" -keyalg RSA -keysize 2048 -validity 10000 \\\n" +
|
||||
" -alias incido \\\n" +
|
||||
" -storepass incido_dev_keystore \\\n" +
|
||||
" -keypass incido_dev_keystore \\\n" +
|
||||
" -dname \"CN=Incido Dev, OU=Local, O=Incido, " +
|
||||
"L=Local, ST=Local, C=NZ\""
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
@@ -109,6 +128,13 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// Wire the keystore validator after Android has created the release task.
|
||||
// Looking the task up before configuration completes makes the build fail
|
||||
// for unrelated compile/debug tasks as well.
|
||||
afterEvaluate {
|
||||
tasks.findByName("assembleRelease")?.dependsOn("validateReleaseKeystore")
|
||||
}
|
||||
|
||||
// v0.3.6.0: ship version-stamped APKs at the repo root for every
|
||||
// release (e.g. `Incido-0.3.6.0-debug.apk`, `Incido-0.3.6.0-release.apk`).
|
||||
// See Incido Development Plan §11 for the full release build
|
||||
@@ -120,19 +146,22 @@ android {
|
||||
// with `Iterable<T>.all(predicate: (T) -> Boolean)` and the modern
|
||||
// `androidComponents.onVariants` API doesn't expose `outputFileName` as
|
||||
// a settable property on its outputs), we just register a copy task
|
||||
// that runs after both `assembleDebug` and `assembleRelease` and drops
|
||||
// the built APKs at the project root with the right names.
|
||||
// that runs after the debug and release builds and drops the built APKs
|
||||
// at the project root with the right names. The release task is attached
|
||||
// as a finalizer below, so the copy task must not depend on it directly.
|
||||
//
|
||||
// `copyReleaseApks` is registered as a `dependsOn` of `assembleRelease`
|
||||
// so `./gradlew assembleRelease` is enough to get both files at the
|
||||
// repo root in one command.
|
||||
// `copyReleaseApks` runs as a finalizer of `assembleRelease`, so
|
||||
// `./gradlew assembleRelease` is enough to get both files at the repo
|
||||
// root in one command.
|
||||
val copyReleaseApks = tasks.register("copyReleaseApks") {
|
||||
group = "build"
|
||||
description = "Copies debug + release APKs to the repo root, " +
|
||||
"stamped with the current versionName " +
|
||||
"(e.g. Incido-0.3.6.3-debug.apk, Incido-0.3.6.3-release.apk). " +
|
||||
"See Incido Development Plan §11."
|
||||
dependsOn("assembleDebug", "assembleRelease")
|
||||
// assembleRelease invokes this task as a finalizer; depending on
|
||||
// assembleRelease here would create a task graph cycle.
|
||||
dependsOn("assembleDebug")
|
||||
doLast {
|
||||
val versionName = android.defaultConfig.versionName
|
||||
val rootDir = rootProject.projectDir
|
||||
@@ -156,9 +185,8 @@ val copyReleaseApks = tasks.register("copyReleaseApks") {
|
||||
}
|
||||
|
||||
// Make `assembleRelease` finalize with `copyReleaseApks` so a single
|
||||
// `./gradlew assembleRelease` produces both root-level APKs. Using
|
||||
// `finalizedBy` (not `dependsOn`) avoids a circular dependency:
|
||||
// `copyReleaseApks` already `dependsOn` `assembleRelease`.
|
||||
// `./gradlew assembleRelease` produces both root-level APKs. The copy
|
||||
// task depends on assembleDebug, avoiding a task graph cycle.
|
||||
afterEvaluate {
|
||||
tasks.findByName("assembleRelease")?.finalizedBy(copyReleaseApks)
|
||||
}
|
||||
@@ -170,6 +198,10 @@ dependencies {
|
||||
// viewer + the list card thumbnails). It's the *interface* in
|
||||
// :core:domain, not the impl, so this stays clean of ObjectBox.
|
||||
implementation(project(":core:domain"))
|
||||
// Phase 1 (M3 task 1): same reason for SettingsRepository — MainActivity
|
||||
// reads userSettingsFlow / snapshot() and its type moved with the class
|
||||
// into the shared :core:settings module.
|
||||
implementation(project(":core:settings"))
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
// v0.3.2.0: MainActivity now extends FragmentActivity so the
|
||||
|
||||
@@ -11,6 +11,11 @@
|
||||
database and are never uploaded anywhere.
|
||||
-->
|
||||
<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
|
||||
app-lock PIN alternative. USE_BIOMETRIC is the modern
|
||||
permission; USE_FINGERPRINT is the pre-Android-10 alias and
|
||||
@@ -21,6 +26,12 @@
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera"
|
||||
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
|
||||
android:name="android.hardware.fingerprint"
|
||||
android:required="false" />
|
||||
|
||||
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 124 KiB After Width: | Height: | Size: 90 KiB |
|
Before Width: | Height: | Size: 214 KiB After Width: | Height: | Size: 139 KiB |
@@ -1,10 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
v0.3.3.8: designed icon replaces the v0.1 placeholder glyph.
|
||||
The foreground is the density-bucketed incido.png artwork
|
||||
(drawable-<density>/ic_launcher_foreground.png, sized for the
|
||||
108dp adaptive canvas); the background matches the artwork's
|
||||
edge colour so parallax exposure is seamless.
|
||||
v0.3.7.1: foreground is now the new flat icon artwork
|
||||
(incido_flat_icon.png, downscaled into drawable-<density>/
|
||||
ic_launcher_foreground.png at the 108dp adaptive canvas sizes);
|
||||
the background colour matches the artwork's fill so parallax
|
||||
exposure is seamless.
|
||||
-->
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background" />
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
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
|
||||
layers as ic_launcher.xml.
|
||||
-->
|
||||
|
||||
|
Before Width: | Height: | Size: 8.5 KiB After Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 9.2 KiB After Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 4.8 KiB After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 47 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 38 KiB |
@@ -1,7 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- v0.3.3.8: background for the adaptive launcher icon, matched to
|
||||
the edge colour of the incido.png artwork so parallax exposure
|
||||
of the background layer is seamless. -->
|
||||
<color name="ic_launcher_background">#010435</color>
|
||||
the artwork's edge colour so parallax exposure is seamless.
|
||||
v0.3.7.1: re-tinted from #010435 to the new flat icon's fill
|
||||
colour (#352999) so the foreground's squircle edges blend
|
||||
invisibly into the background layer. -->
|
||||
<color name="ic_launcher_background">#352999</color>
|
||||
</resources>
|
||||
@@ -6,6 +6,12 @@ plugins {
|
||||
alias(libs.plugins.androidLibrary) apply false
|
||||
alias(libs.plugins.kotlinAndroid) apply false
|
||||
alias(libs.plugins.kotlinJvm) apply false
|
||||
// Phase 1 (M4.1): must be registered here too — otherwise :composeApp's
|
||||
// request for the multiplatform plugin collides with the KGP classes the
|
||||
// other Kotlin plugin markers already put on the buildscript classpath
|
||||
// ("already on classpath with unknown version" — same family as the
|
||||
// kapt trap in tools/DESKTOP_PHASE_PLAN.md §2.5).
|
||||
alias(libs.plugins.kotlinMultiplatform) apply false
|
||||
alias(libs.plugins.kotlinCompose) apply false
|
||||
alias(libs.plugins.ksp) apply false
|
||||
}
|
||||
@@ -1,16 +1,139 @@
|
||||
// composeApp — Android UI module hosting all screens, ViewModels, theme,
|
||||
// navigation, and the manual DI container. Regular Android Compose (not
|
||||
// Compose Multiplatform) is used in v0.1 to keep the build simple; the
|
||||
// migration path to Multiplatform in v0.2 is a module-level refactor.
|
||||
// composeApp — Incido's UI module: all screens, ViewModels, theme,
|
||||
// navigation, and the manual DI container.
|
||||
//
|
||||
// Phase 1 (M4.1): converted in place from `kotlin("android")` to
|
||||
// `kotlin("multiplatform")` with `androidTarget()` + `jvm()`, per the
|
||||
// order of attack in tools/DESKTOP_PHASE_PLAN.md §6.1. The split is
|
||||
// deliberately conservative — the goal of THIS step is the build shape:
|
||||
//
|
||||
// * commonMain — every file that compiles for both targets today
|
||||
// (theme Color/Type, PasswordPolicy, ReleaseNotes,
|
||||
// LinkedShareComposer) plus two expect/actual seams:
|
||||
// `platformDynamicColorScheme` and `relativeTimestamp`.
|
||||
// The Android actuals keep the pre-M4 code verbatim.
|
||||
// * androidMain — everything still touching `android.*` (screens,
|
||||
// ViewModels, AppContainer, security, backup IO, …),
|
||||
// moved UNMODIFIED. Zero behaviour change; the seams
|
||||
// for these move file-by-file in M4.2/M4.3.
|
||||
// * jvmMain — the JVM actuals. Nothing else yet: :desktopApp keeps
|
||||
// its own stand-in UI until M4.5 consumes this target.
|
||||
//
|
||||
// Note: :core:domain converted to multiplatform in M4.2, so commonMain
|
||||
// sees it — NoteColors.kt moved up with that commit.
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.androidLibrary)
|
||||
alias(libs.plugins.kotlinAndroid)
|
||||
alias(libs.plugins.kotlinMultiplatform)
|
||||
// org.jetbrains.compose provides the `compose.*` dependency accessors
|
||||
// that resolve to the right artifact per target (androidx.compose.*
|
||||
// on androidTarget, *-desktop jars on jvm).
|
||||
alias(libs.plugins.compose)
|
||||
alias(libs.plugins.kotlinCompose)
|
||||
// v0.3.2.0 — Kotlin Serialization for the Backup JSON codec.
|
||||
// v0.3.2.0 — Kotlin Serialization for the Backup JSON codec (used by
|
||||
// CarnetImporter today; the plugin stays target-agnostic).
|
||||
alias(libs.plugins.kotlinSerialization)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
|
||||
androidTarget()
|
||||
jvm()
|
||||
|
||||
sourceSets {
|
||||
commonMain.dependencies {
|
||||
implementation(compose.runtime)
|
||||
implementation(compose.ui)
|
||||
implementation(compose.foundation)
|
||||
implementation(compose.material3)
|
||||
// Phase 1 (M4.4a): moved screens (IncidoDrawer, PassphraseDialog)
|
||||
// use extended icons (Drafts/LabelOff/Tag/ContentCopy/Visibility).
|
||||
// androidMain already had the same jetbrains coordinate (it
|
||||
// resolves to androidx on that target); on jvm this pulls the
|
||||
// ~100 MB material-icons-extended-desktop jar (§3 trap — a first
|
||||
// build can time out; retry, don't debug).
|
||||
implementation(libs.compose.material.icons.extended)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
// Phase 1 (M4.3b): the §6.4 artifact check resolves GREEN —
|
||||
// these org.jetbrains.androidx.lifecycle coordinates are what
|
||||
// androidMain has been resolving since M4.1 (assembleDebug
|
||||
// proves they coexist with the AndroidX BOM on the android
|
||||
// target), and the desktopApp runtime already carried the
|
||||
// matching -desktop jars. Here they enter commonMain so the
|
||||
// ViewModels move with their `androidx.lifecycle.*` imports
|
||||
// UNCHANGED (the offline set keeps the androidx FQCNs).
|
||||
implementation(libs.androidx.lifecycle.viewmodel)
|
||||
// Phase 1 (M4.4a): screens move with their construction sites
|
||||
// intact — `viewModel(factory = …)` from viewmodel-compose and
|
||||
// `collectAsStateWithLifecycle` from runtime-compose. These are
|
||||
// the SAME jetbrains coordinates androidMain already resolved
|
||||
// since M4.1 (collectAsStateWithLifecycle reached the Android
|
||||
// classpath through them), now declared in commonMain so the
|
||||
// moved screens compile for both targets (§6.4 GREEN).
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||
// Phase 1 (M4.2): :core:domain is multiplatform now (M4.2's own
|
||||
// conversion), so commonMain can see it — this is what let
|
||||
// NoteColors.kt move up. api: screens/ViewModels across all
|
||||
// targets consume Note/NoteColor/NoteRepository from it.
|
||||
api(project(":core:domain"))
|
||||
// Phase 1 (M4.3a): :core:settings converted in the same shape —
|
||||
// M4.3's AppGraph exposes SettingsRepository/UserSettings to
|
||||
// commonMain, so this has to be api too.
|
||||
api(project(":core:settings"))
|
||||
}
|
||||
|
||||
androidMain.dependencies {
|
||||
implementation(project(":core:data"))
|
||||
// Phase 1 (M2 task 1): backup codecs + bridge now live here; the
|
||||
// org.incido.compose.data.backup package name was kept, so no imports
|
||||
// changed — only this dependency line.
|
||||
implementation(project(":core:backup"))
|
||||
// Phase 1 (M3 task 1): settings repository, same treatment — package
|
||||
// kept, the Context-based construction moved to AndroidSettingsStore.kt.
|
||||
implementation(project(":core:settings"))
|
||||
|
||||
// Core / lifecycle
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime)
|
||||
implementation(libs.androidx.lifecycle.process)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
|
||||
// Compose BOM keeps all Compose artefact versions aligned.
|
||||
// (Called inline — the KMP source-set dependency handler's
|
||||
// platform() returns a raw notation, not a Dependency, so the
|
||||
// old `val composeBom = platform(…)` idiom fails here.)
|
||||
implementation(project.dependencies.platform(libs.composeBom))
|
||||
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
|
||||
// Compose (same org.jetbrains.compose artifacts as before the
|
||||
// M4.1 conversion — they resolve to the androidx variants on
|
||||
// this target; version alignment unchanged).
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
implementation(libs.compose.foundation)
|
||||
implementation(libs.compose.material3)
|
||||
implementation(libs.compose.material.icons.extended)
|
||||
|
||||
// v0.3.2.0 — Settings (DataStore Preferences), Security (Biometric),
|
||||
// and Backup (Kotlin Serialization JSON) support.
|
||||
implementation(libs.androidx.datastore.preferences)
|
||||
implementation(libs.androidx.biometric)
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
}
|
||||
|
||||
jvmMain.dependencies {
|
||||
// Nothing yet — the compose artifacts arrive via commonMain;
|
||||
// :core:data-jvm / :core:settings wiring lands with M4.3's
|
||||
// container seam when :desktopApp starts consuming this target.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "org.incido.compose"
|
||||
compileSdk = 35
|
||||
@@ -19,20 +142,15 @@ android {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
// M4.1: `buildFeatures.compose` is NOT set — the org.jetbrains.compose
|
||||
// plugin owns Compose wiring on this target (setting it here alongside
|
||||
// the KMP plugin is the classic double-wire; see §3 trap 6's sibling).
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
|
||||
packaging {
|
||||
resources {
|
||||
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
||||
@@ -40,37 +158,11 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// AGP's debug-only configurations are project-level, so the Compose
|
||||
// tooling dependency that was `debugImplementation` before the M4.1
|
||||
// conversion keeps that exact scope here (the KMP `sourceSets { … }`
|
||||
// dependency handlers only expose implementation/api/compileOnly).
|
||||
dependencies {
|
||||
implementation(project(":core:domain"))
|
||||
implementation(project(":core:data"))
|
||||
|
||||
// Core / lifecycle
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime)
|
||||
implementation(libs.androidx.lifecycle.process)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
|
||||
// Compose BOM keeps all Compose artefact versions aligned
|
||||
val composeBom = platform(libs.composeBom)
|
||||
implementation(composeBom)
|
||||
androidTestImplementation(composeBom)
|
||||
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
|
||||
// Compose
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
implementation(libs.compose.foundation)
|
||||
implementation(libs.compose.material3)
|
||||
implementation(libs.compose.material.icons.extended)
|
||||
debugImplementation(libs.compose.ui.tooling)
|
||||
|
||||
// v0.3.2.0 — Settings (DataStore Preferences), Security (Biometric),
|
||||
// and Backup (Kotlin Serialization JSON) support.
|
||||
implementation(libs.androidx.datastore.preferences)
|
||||
implementation(libs.androidx.biometric)
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
package org.incido.compose
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.DrawerValue
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ModalNavigationDrawer
|
||||
import androidx.compose.material3.rememberDrawerState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshots.SnapshotStateList
|
||||
import androidx.compose.runtime.toMutableStateList
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavType
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import androidx.navigation.navArgument
|
||||
import kotlinx.coroutines.launch
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.compose.data.settings.SettingsRepository
|
||||
import org.incido.compose.di.LocalAndroidContainer
|
||||
import org.incido.compose.di.LocalAppGraph
|
||||
import org.incido.compose.share.SharedIntentBuffer
|
||||
import org.incido.compose.ui.drawer.IncidoDrawer
|
||||
import org.incido.compose.ui.editor.NoteEditorScreen
|
||||
import org.incido.compose.ui.editor.SharedImage
|
||||
import org.incido.compose.ui.notelist.NoteListScreen
|
||||
import org.incido.compose.ui.settings.SettingsScreen
|
||||
import org.incido.compose.ui.settings.auth.PinChangeScreen
|
||||
import org.incido.compose.ui.settings.auth.PinEntryScreen
|
||||
import org.incido.compose.ui.settings.auth.PinSetupScreen
|
||||
import org.incido.compose.ui.theme.IncidoTheme
|
||||
import org.incido.domain.model.NoteColor
|
||||
import org.incido.domain.model.NoteFilter
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/** Top-level navigation destinations. */
|
||||
private object Routes {
|
||||
const val LIST = "list"
|
||||
const val EDITOR = "editor/{noteId}"
|
||||
const val SETTINGS = "settings"
|
||||
const val PIN_SETUP = "pin_setup"
|
||||
/** v0.3.3.0: three-step "Reset PIN" flow. */
|
||||
const val PIN_CHANGE = "pin_change"
|
||||
fun editor(noteId: Long?): String = "editor/${noteId ?: -1L}"
|
||||
}
|
||||
|
||||
/** Stable serialisation for [NoteFilter] so `rememberSaveable` works. */
|
||||
private fun NoteFilter.toSaveableKey(): String = key()
|
||||
|
||||
private fun String.toNoteFilter(): NoteFilter = when {
|
||||
this == "home" -> NoteFilter.Home
|
||||
this == "favorites" -> NoteFilter.Favorites
|
||||
this == "untagged" -> NoteFilter.Untagged
|
||||
this == "drafts" -> NoteFilter.Drafts
|
||||
this == "trash" -> NoteFilter.Trash
|
||||
startsWith("tag:") -> NoteFilter.ByTag(this.removePrefix("tag:"))
|
||||
startsWith("color:") -> NoteColor.values()
|
||||
.firstOrNull { it.name == this.removePrefix("color:") }
|
||||
?.let { NoteFilter.ByColor(it) }
|
||||
?: NoteFilter.Home
|
||||
else -> NoteFilter.Home
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.1.0: Holds the share-into payload (text + pre-loaded image
|
||||
* bytes) so the [NoteEditorScreen] can read it on first composition.
|
||||
* Cleared as soon as the editor is created.
|
||||
*
|
||||
* v0.3.6.0: also carries [subject] (`Intent.EXTRA_SUBJECT`) so the
|
||||
* editor can put the page title on the note's first line for URL
|
||||
* shares — still offline-only, no network fetch.
|
||||
*/
|
||||
private class ShareIntoHolder {
|
||||
var text: String? = null
|
||||
var images: List<SharedImage> = emptyList()
|
||||
var subject: String? = null
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun IncidoApp(
|
||||
repository: NoteRepository? = null,
|
||||
securityManager: SecurityManager? = null,
|
||||
settingsRepository: SettingsRepository? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val app = context.applicationContext as IncidoApplication
|
||||
// v0.3.2.0: prefer explicit params, fall back to the application
|
||||
// container. Both hosts (`MainActivity` + tests) supply them in
|
||||
// production — the fallback is just a robustness net.
|
||||
val resolvedSecurity = securityManager ?: app.container.securityManager
|
||||
val resolvedSettings = settingsRepository ?: app.container.settingsRepository
|
||||
|
||||
// v0.3.2.0: collect user settings to drive theme + the auth gate.
|
||||
val settings by resolvedSettings.userSettingsFlow.collectAsStateWithLifecycle(
|
||||
initialValue = org.incido.compose.data.settings.UserSettings(),
|
||||
)
|
||||
val lockState by resolvedSecurity.lockState.collectAsStateWithLifecycle()
|
||||
|
||||
// M4.3: the platform graph reaches the screens through the composition —
|
||||
// the same face DesktopContainer implements (commonMain di/AppGraph.kt).
|
||||
CompositionLocalProvider(
|
||||
LocalAppGraph provides app.container,
|
||||
LocalAndroidContainer provides app.container,
|
||||
) {
|
||||
IncidoTheme(
|
||||
darkTheme = settings.themeMode.resolveDark(isSystemInDarkTheme()),
|
||||
dynamicColor = settings.dynamicColor,
|
||||
) {
|
||||
// v0.3.2.0: hard lock gate. If the app is locked we render
|
||||
// the PIN entry screen in place of the regular UI.
|
||||
if (lockState is SecurityManager.LockState.Locked) {
|
||||
PinEntryScreen()
|
||||
return@IncidoTheme
|
||||
}
|
||||
|
||||
val navController = rememberNavController()
|
||||
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
|
||||
val scope = rememberCoroutineScope()
|
||||
var filterMode by rememberSaveable(
|
||||
stateSaver = androidx.compose.runtime.saveable.Saver(
|
||||
save = { it.toSaveableKey() },
|
||||
restore = { it.toNoteFilter() },
|
||||
),
|
||||
) { mutableStateOf<NoteFilter>(NoteFilter.Home) }
|
||||
|
||||
// v0.3.1.0: consume any inbound share-into payload once at
|
||||
// composition. The buffer is single-shot — first composition
|
||||
// wins. If a payload is present, we open a fresh editor with
|
||||
// the shared content pre-filled.
|
||||
val shareHolder = remember { ShareIntoHolder() }
|
||||
LaunchedEffect(Unit) {
|
||||
val payload = SharedIntentBuffer.consume()
|
||||
if (payload != null && !payload.isEmpty) {
|
||||
shareHolder.text = payload.text
|
||||
shareHolder.images = payload.images
|
||||
shareHolder.subject = payload.subject
|
||||
navController.navigate(Routes.editor(null)) {
|
||||
popUpTo(Routes.LIST)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val currentBackStack by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = currentBackStack?.destination?.route?.substringBefore("/")
|
||||
// Disable the drawer on the editor so back arrow / gesture do
|
||||
// exactly what the user expects there.
|
||||
val isListRoute = currentRoute == Routes.LIST
|
||||
|
||||
LaunchedEffect(currentRoute) {
|
||||
// If we land on the editor via deep link without a list in
|
||||
// the back stack, snap the drawer closed.
|
||||
if (!isListRoute && drawerState.isOpen) drawerState.close()
|
||||
}
|
||||
|
||||
// v0.3.2.0: forward app foreground/background transitions to
|
||||
// the SecurityManager so it can re-lock when the timeout
|
||||
// elapses. LifecycleEventObserver wires ON_RESUME / ON_STOP
|
||||
// automatically.
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
when (event) {
|
||||
Lifecycle.Event.ON_RESUME -> resolvedSecurity.onAppForegrounded()
|
||||
Lifecycle.Event.ON_STOP -> resolvedSecurity.onAppBackgrounded()
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
|
||||
ModalNavigationDrawer(
|
||||
drawerState = drawerState,
|
||||
gesturesEnabled = isListRoute,
|
||||
drawerContent = {
|
||||
IncidoDrawer(
|
||||
currentFilter = filterMode,
|
||||
onSelectFilter = { picked ->
|
||||
filterMode = picked
|
||||
scope.launch { drawerState.close() }
|
||||
},
|
||||
onOpenSettings = {
|
||||
scope.launch { drawerState.close() }
|
||||
navController.navigate(Routes.SETTINGS)
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
NavHost(navController = navController, startDestination = Routes.LIST) {
|
||||
composable(Routes.LIST) {
|
||||
NoteListScreen(
|
||||
filterMode = filterMode,
|
||||
onOpenDrawer = { scope.launch { drawerState.open() } },
|
||||
onOpenEditor = { id -> navController.navigate(Routes.editor(id)) },
|
||||
// v0.3.1.0: thread the NoteRepository through so the
|
||||
// card thumbnail composables can fetch image bytes.
|
||||
repository = repository,
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = Routes.EDITOR,
|
||||
arguments = listOf(
|
||||
navArgument("noteId") {
|
||||
type = NavType.LongType
|
||||
defaultValue = -1L
|
||||
},
|
||||
),
|
||||
) { entry ->
|
||||
val raw = entry.arguments?.getLong("noteId") ?: -1L
|
||||
val id = if (raw <= 0L) null else raw
|
||||
// Read the share payload ONCE (consume) so back-then-reopen
|
||||
// doesn't re-route us into the editor with stale data.
|
||||
val sharedText = shareHolder.text.also { shareHolder.text = null }
|
||||
val sharedImages = shareHolder.images.also { shareHolder.images = emptyList() }
|
||||
// v0.3.6.0: also drain the page-title subject from the
|
||||
// share intent so the editor can format the note
|
||||
// with title on the first line.
|
||||
val sharedSubject = shareHolder.subject.also { shareHolder.subject = null }
|
||||
NoteEditorScreen(
|
||||
noteId = id,
|
||||
onClose = { navController.popBackStack() },
|
||||
initialSharedText = sharedText,
|
||||
initialSharedImages = sharedImages,
|
||||
initialSharedSubject = sharedSubject,
|
||||
repository = repository,
|
||||
// v0.3.4.0 hotfix: suppress auto-lock around
|
||||
// the editor's picker / camera / system-viewer
|
||||
// round-trips. M4.4c: the editor lives in
|
||||
// commonMain now and cannot name the Android
|
||||
// SecurityManager — it takes this neutral
|
||||
// lambda instead.
|
||||
beginExternalActivity = resolvedSecurity
|
||||
?.let { sec -> { sec.beginExternalActivity() } },
|
||||
)
|
||||
}
|
||||
composable(Routes.SETTINGS) {
|
||||
SettingsScreen(
|
||||
onBack = { navController.popBackStack() },
|
||||
onRequestPinSetup = { navController.navigate(Routes.PIN_SETUP) },
|
||||
// v0.3.3.0: "Reset PIN" row navigates here.
|
||||
onRequestPinChange = { navController.navigate(Routes.PIN_CHANGE) },
|
||||
// v0.3.4.0 hotfix: suppress auto-lock around
|
||||
// the backup export/import SAF pickers.
|
||||
securityManager = resolvedSecurity,
|
||||
)
|
||||
}
|
||||
composable(Routes.PIN_SETUP) {
|
||||
PinSetupScreen(
|
||||
onDone = { navController.popBackStack() },
|
||||
onCancel = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(Routes.PIN_CHANGE) {
|
||||
PinChangeScreen(
|
||||
onDone = { navController.popBackStack() },
|
||||
onCancel = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Suppress unused-import lint for the snapshots helper that may be
|
||||
// re-introduced in future filter-state extensions.
|
||||
@Suppress("unused")
|
||||
private fun <T> List<T>.toSnapshotStateList(): SnapshotStateList<T> = toMutableStateList<T>()
|
||||
@@ -8,8 +8,10 @@ import org.incido.compose.di.AppContainer
|
||||
* Application class. Constructs the singleton [AppContainer] holding the
|
||||
* ObjectBox store and the note repository.
|
||||
*
|
||||
* ViewModels reach the container via `(application as IncidoApplication).container`
|
||||
* (see `NoteListViewModel.Factory` and `NoteEditorViewModel.factory`).
|
||||
* M4.3: the screens reach the container through `LocalAppGraph` (provided
|
||||
* by `IncidoApp`); the graph-based ViewModel factories (`factory(graph)`)
|
||||
* no longer touch the Application through CreationExtras. The Application
|
||||
* still owns construction order.
|
||||
*
|
||||
* v0.3.2.0 — initialises the [SecurityManager] lock state during
|
||||
* `onCreate` so the first composition of the root Compose tree
|
||||
@@ -0,0 +1,103 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* v0.3.2.0: orchestration layer for Backup / Import / Export.
|
||||
*
|
||||
* Phase 1 (M2 task 1): this class is now a **thin Storage Access
|
||||
* Framework shim**. It converts the [Uri]s that
|
||||
* `ActivityResultContracts.CreateDocument` / `OpenDocument` hand back
|
||||
* into streams and delegates everything else — format, crypto,
|
||||
* snapshotting — to [BackupManager]'s former body, now the platform-
|
||||
* neutral [BackupBridge] in `:core:backup`. The desktop app (M2 task 2)
|
||||
* calls [BackupBridge] directly with file streams.
|
||||
*
|
||||
* Public API is unchanged: [SettingsViewModel] and the backup screens
|
||||
* compile exactly as before.
|
||||
*/
|
||||
class BackupManager(
|
||||
private val context: Context,
|
||||
private val repository: NoteRepository,
|
||||
) {
|
||||
|
||||
/**
|
||||
* Snapshot every note in [repository] and stream it to [uri] as a
|
||||
* plain JSON file. Throws on I/O failure.
|
||||
*
|
||||
* Returns the number of notes exported.
|
||||
*/
|
||||
suspend fun exportPlain(
|
||||
uri: Uri,
|
||||
appVersion: String,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int = withContext(Dispatchers.IO) {
|
||||
BackupBridge.exportPlain(repository, openOutput(uri), appVersion, onProgress)
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot every note and stream it to [uri] as a passphrase-
|
||||
* encrypted envelope. [passphrase] is consumed (zeroed) inside
|
||||
* [EncryptedBackupCodec.encrypt].
|
||||
*/
|
||||
suspend fun exportEncrypted(
|
||||
uri: Uri,
|
||||
passphrase: CharArray,
|
||||
appVersion: String,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int = withContext(Dispatchers.IO) {
|
||||
BackupBridge.exportEncrypted(repository, openOutput(uri), passphrase, appVersion, onProgress)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read [uri] and import every note it contains. Auto-detects
|
||||
* plain vs encrypted via the magic header. For encrypted files,
|
||||
* [passphrase] is required (caller validates with
|
||||
* [PasswordPolicy]).
|
||||
*
|
||||
* [skipExisting] (default true) dedupes on the bridge's
|
||||
* (createdAt, updatedAt, sha256(content)) key — see
|
||||
* [BackupBridge.import]. Returns what was imported vs skipped.
|
||||
*/
|
||||
suspend fun import(
|
||||
uri: Uri,
|
||||
passphrase: CharArray? = null,
|
||||
skipExisting: Boolean = true,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): ImportSummary = withContext(Dispatchers.IO) {
|
||||
BackupBridge.import(repository, openInput(uri), passphrase, skipExisting, onProgress)
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap metadata preview — used by the "Import from file…" flow
|
||||
* to show the user how many notes / attachments they're about to
|
||||
* bring in before they commit.
|
||||
*
|
||||
* Returns `null` if the file can't be read or the passphrase is
|
||||
* wrong (so the UI can surface "wrong passphrase" cleanly).
|
||||
*/
|
||||
suspend fun preview(uri: Uri, passphrase: CharArray? = null): BackupPreview? =
|
||||
withContext(Dispatchers.IO) {
|
||||
val input: InputStream = try {
|
||||
context.contentResolver.openInputStream(uri) ?: return@withContext null
|
||||
} catch (_: IOException) {
|
||||
return@withContext null
|
||||
}
|
||||
BackupBridge.preview(input, passphrase)
|
||||
}
|
||||
|
||||
private fun openOutput(uri: Uri): OutputStream =
|
||||
context.contentResolver.openOutputStream(uri, "wt")
|
||||
?: throw IOException("Could not open output stream for $uri")
|
||||
|
||||
private fun openInput(uri: Uri): InputStream =
|
||||
context.contentResolver.openInputStream(uri)
|
||||
?: throw IOException("Could not open input stream for $uri")
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.util.zip.ZipInputStream
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import org.incido.domain.model.Hashtag
|
||||
import org.incido.domain.model.Note
|
||||
import org.incido.domain.model.NoteColor
|
||||
import org.incido.domain.model.NoteType
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* v0.3.9.0 — imports notes from a **Carnet / QuickNote** archive.
|
||||
*
|
||||
* The source is a `.zip` whose top-level entries are `*.sqd` files (plus
|
||||
* some metadata dirs we ignore). Each `.sqd` is *itself* a zip containing:
|
||||
* * `index.html` — the note body inside `<div class="edit-zone">…</div>`
|
||||
* * `metadata.json` — `creation_date`, `last_modification_date`,
|
||||
* `keywords[]`, `rating`, `color`, `urls{}`, `todolists[]`
|
||||
* * `data/<file>` — optional attachments (images etc). A companion
|
||||
* `data/preview_` thumbnail is skipped so we don't
|
||||
* import a low-res duplicate.
|
||||
*
|
||||
* Incido stores note bodies as **plain text**, so the rich-text HTML is
|
||||
* flattened to text (block tags → newlines, entities decoded, tags stripped).
|
||||
* The `.sqd` filename becomes the note's title line, which also gives
|
||||
* image-only notes (no HTML body) a readable title.
|
||||
*
|
||||
* Import is **additive** — matching the existing backup-import behaviour:
|
||||
* existing notes are preserved, every imported note gets a fresh id, and
|
||||
* attachments are stored via [NoteRepository.addAttachment] (which applies
|
||||
* EXIF normalisation + at-rest encryption transparently).
|
||||
*
|
||||
* Both archive shapes are accepted: a bundle of `*.sqd` files, or a single
|
||||
* `.sqd` file picked directly (its zip entries are the note's own
|
||||
* `index.html` / `metadata.json` / files under `data/`).
|
||||
*/
|
||||
class CarnetImporter(
|
||||
private val context: Context,
|
||||
private val repository: NoteRepository,
|
||||
) {
|
||||
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the archive at [uri] and import every Carnet note it contains.
|
||||
* Returns the number of notes imported.
|
||||
*/
|
||||
suspend fun import(
|
||||
uri: Uri,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int = withContext(Dispatchers.IO) {
|
||||
val archiveBytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw java.io.IOException("Could not open input stream for $uri")
|
||||
|
||||
val topLevel = readZip(archiveBytes)
|
||||
|
||||
// The picked file is a single archive that bundles every note as a
|
||||
// nested `.sqd` entry (each `.sqd` is itself a zip). Collect those.
|
||||
val sqdNotes = topLevel.filter { (name, _) -> name.endsWith(".sqd", ignoreCase = true) }
|
||||
.toList()
|
||||
|
||||
// Candidates as (title-file-name, raw-bytes). If no `.sqd` entries
|
||||
// were found, the picked file is treated as a single `.sqd` (its own
|
||||
// zip entries are index.html / metadata.json / data/…).
|
||||
val candidates: List<Pair<String, ByteArray>> = if (sqdNotes.isNotEmpty()) {
|
||||
sqdNotes
|
||||
} else {
|
||||
listOf((queryDisplayName(uri) ?: "Imported note.sqd") to archiveBytes)
|
||||
}
|
||||
|
||||
// Parse phase — fault-isolated so one corrupt `.sqd` can't abort the
|
||||
// rest of the archive.
|
||||
val notes = candidates.mapNotNull { (name, bytes) ->
|
||||
runCatching { parseSqd(name.substringAfterLast('/'), bytes) }.getOrNull()
|
||||
}.filter { it.hasContent() }
|
||||
|
||||
// Persist phase — also per-note, so a single bad note doesn't lose the
|
||||
// ones already written (the repository commits each note independently).
|
||||
val total = notes.size
|
||||
var imported = 0
|
||||
notes.forEach { parsed ->
|
||||
val ok = runCatching { persist(parsed) }.isSuccess
|
||||
if (ok) imported++
|
||||
onProgress(imported, total)
|
||||
}
|
||||
imported
|
||||
}
|
||||
|
||||
// --- Persistence ---------------------------------------------------------
|
||||
|
||||
private suspend fun persist(parsed: ParsedSqd) {
|
||||
val hashtags = parsed.keywords
|
||||
.flatMap { raw ->
|
||||
// Prefer the whole keyword as one tag; if it isn't a valid
|
||||
// hashtag (Incido allows only [a-z0-9._-], 1–31 chars), split
|
||||
// on whitespace/commas and keep the valid sub-tokens.
|
||||
val one = Hashtag.normalise(raw)
|
||||
if (Hashtag.parseOrNull(one) != null) {
|
||||
listOf(one)
|
||||
} else {
|
||||
raw.split(Regex("[\\s,]+"))
|
||||
.map { Hashtag.normalise(it) }
|
||||
.filter { Hashtag.parseOrNull(it) != null }
|
||||
}
|
||||
}
|
||||
.filter { it.isNotEmpty() }
|
||||
.toSet()
|
||||
|
||||
val saved = repository.saveNoteWithHashtags(
|
||||
note = Note(
|
||||
id = 0L, // force a fresh id
|
||||
content = parsed.content,
|
||||
createdAt = parsed.createdAt,
|
||||
updatedAt = parsed.updatedAt,
|
||||
isFavorite = parsed.isFavorite,
|
||||
color = parsed.color,
|
||||
isTrashed = false,
|
||||
type = parsed.type,
|
||||
),
|
||||
hashtagsToAdd = hashtags,
|
||||
hashtagsToRemove = emptySet(),
|
||||
)
|
||||
|
||||
for (att in parsed.attachments) {
|
||||
repository.addAttachment(
|
||||
noteId = saved.id,
|
||||
bytes = att.bytes,
|
||||
mimeType = sniffMimeType(att.bytes),
|
||||
displayName = att.displayName,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// --- .sqd parsing --------------------------------------------------------
|
||||
|
||||
private fun parseSqd(fileName: String, sqdBytes: ByteArray): ParsedSqd {
|
||||
val files = readZip(sqdBytes)
|
||||
val title = fileName.substringBeforeLast('.')
|
||||
.ifBlank { "Untitled" }
|
||||
|
||||
val html = files["index.html"]?.toString(Charsets.UTF_8).orEmpty()
|
||||
val meta = files["metadata.json"]
|
||||
?.let {
|
||||
runCatching {
|
||||
json.decodeFromString(CarnetMetadata.serializer(), it.toString(Charsets.UTF_8))
|
||||
}.getOrNull()
|
||||
}
|
||||
?: CarnetMetadata()
|
||||
|
||||
val body = htmlToText(html)
|
||||
|
||||
// Attachments: anything under data/ that is a real file (not a dir
|
||||
// entry) and not an auto-generated preview thumbnail.
|
||||
val attachments = files
|
||||
.filter { (name, bytes) ->
|
||||
name.startsWith("data/") &&
|
||||
!name.endsWith("/") &&
|
||||
bytes.isNotEmpty() &&
|
||||
!name.substringAfterLast('/').startsWith("preview_")
|
||||
}
|
||||
.map { (name, bytes) -> Attachment(name.substringAfterLast('/'), bytes) }
|
||||
|
||||
val type = if (meta.todolists.isNotEmpty()) NoteType.TASK_LIST else NoteType.TEXT
|
||||
|
||||
return ParsedSqd(
|
||||
content = buildContent(title, body, meta),
|
||||
createdAt = meta.creationDate.takeIf { it > 0 } ?: System.currentTimeMillis(),
|
||||
updatedAt = meta.lastModificationDate.takeIf { it > 0 } ?: System.currentTimeMillis(),
|
||||
isFavorite = meta.rating >= 5,
|
||||
color = mapColor(meta.color),
|
||||
type = type,
|
||||
keywords = meta.keywords,
|
||||
attachments = attachments,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble the final plain-text body. The filename is used as the title
|
||||
* (first non-blank line in Incido's title/body split); then the HTML
|
||||
* body; then any URLs from the metadata; then any to-do lists rendered as
|
||||
* GFM checkbox lines (`- [ ]` / `- [x]`) so [NoteType.TASK_LIST] renders.
|
||||
*/
|
||||
private fun buildContent(title: String, body: String, meta: CarnetMetadata): String {
|
||||
val blocks = mutableListOf<String>()
|
||||
blocks += title
|
||||
if (body.isNotBlank()) blocks += body
|
||||
if (meta.urls.isNotEmpty()) {
|
||||
blocks += meta.urls.keys.filter { it.isNotBlank() }
|
||||
}
|
||||
for (todo in meta.todolists) {
|
||||
val lines = buildList {
|
||||
todo.done.forEach { if (it.isNotBlank()) add("- [x] ${it.trim()}") }
|
||||
todo.todo.forEach { if (it.isNotBlank()) add("- [ ] ${it.trim()}") }
|
||||
}
|
||||
if (lines.isNotEmpty()) blocks += lines.joinToString("\n")
|
||||
}
|
||||
return blocks.filter { it.isNotBlank() }.joinToString("\n\n").trim()
|
||||
}
|
||||
|
||||
// --- Helpers -------------------------------------------------------------
|
||||
|
||||
/** Read every file entry (name → bytes) from a zip, skipping dirs. */
|
||||
private fun readZip(bytes: ByteArray): LinkedHashMap<String, ByteArray> {
|
||||
val out = LinkedHashMap<String, ByteArray>()
|
||||
ZipInputStream(ByteArrayInputStream(bytes)).use { zis ->
|
||||
while (true) {
|
||||
val entry = zis.nextEntry ?: break
|
||||
if (entry.isDirectory) { zis.closeEntry(); continue }
|
||||
val data = zis.readBytes()
|
||||
out[entry.name] = data
|
||||
zis.closeEntry()
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Query the user-visible name of a SAF [uri] (falls back to null). */
|
||||
private fun queryDisplayName(uri: Uri): String? {
|
||||
return try {
|
||||
context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||
val idx = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
|
||||
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** MIME type detected from magic bytes, falling back to a default. */
|
||||
fun sniffMimeType(bytes: ByteArray): String {
|
||||
fun b(i: Int) = if (i < bytes.size) bytes[i].toInt() and 0xFF else -1
|
||||
if (b(0) == 0xFF && b(1) == 0xD8 && b(2) == 0xFF) return "image/jpeg"
|
||||
if (b(0) == 0x89 && b(1) == 0x50 && b(2) == 0x4E && b(3) == 0x47) return "image/png"
|
||||
if (b(0) == 0x47 && b(1) == 0x49 && b(2) == 0x46 && b(3) == 0x38) return "image/gif"
|
||||
if (b(0) == 0x52 && b(1) == 0x49 && b(2) == 0x46 && b(3) == 0x46 &&
|
||||
b(8) == 0x57 && b(9) == 0x45 && b(10) == 0x42 && b(11) == 0x50
|
||||
) return "image/webp"
|
||||
if (b(0) == 0x42 && b(1) == 0x4D) return "image/bmp"
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
||||
/** Carnet color string → Incido [NoteColor]. Unknown values → NONE. */
|
||||
fun mapColor(raw: String): NoteColor = when (raw.trim().lowercase()) {
|
||||
"red" -> NoteColor.RED
|
||||
"green" -> NoteColor.GREEN
|
||||
"blue" -> NoteColor.BLUE
|
||||
"yellow", "amber" -> NoteColor.AMBER
|
||||
"purple" -> NoteColor.PURPLE
|
||||
else -> NoteColor.NONE
|
||||
}
|
||||
|
||||
/**
|
||||
* Flatten a Carnet `index.html` note body to plain text:
|
||||
* strip comments, isolate the `.edit-zone` content, turn block
|
||||
* boundaries into newlines, decode entities (incl. ` `), 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(
|
||||
" " to " ",
|
||||
"&" to "&",
|
||||
"<" to "<",
|
||||
">" to ">",
|
||||
""" to "\"",
|
||||
"'" to "'",
|
||||
"'" to "'",
|
||||
"©" to "\u00A9",
|
||||
"®" to "\u00AE",
|
||||
"™" to "\u2122",
|
||||
"…" to "\u2026",
|
||||
"—" to "\u2014",
|
||||
"–" to "\u2013",
|
||||
"’" to "\u2019",
|
||||
"‘" to "\u2018",
|
||||
"”" to "\u201D",
|
||||
"“" to "\u201C",
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
// --- Data ----------------------------------------------------------------
|
||||
|
||||
/** A parsed, ready-to-persist Carnet note. */
|
||||
data class ParsedSqd(
|
||||
val content: String,
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long,
|
||||
val isFavorite: Boolean,
|
||||
val color: NoteColor,
|
||||
val type: NoteType,
|
||||
val keywords: List<String>,
|
||||
val attachments: List<Attachment>,
|
||||
) {
|
||||
fun hasContent(): Boolean = content.isNotBlank() || attachments.isNotEmpty()
|
||||
}
|
||||
|
||||
/** A single attachment (file name + raw bytes) inside a `.sqd`'s `data/`. */
|
||||
data class Attachment(val displayName: String, val bytes: ByteArray)
|
||||
|
||||
@Serializable
|
||||
private data class CarnetMetadata(
|
||||
@SerialName("creation_date") val creationDate: Long = 0,
|
||||
@SerialName("last_modification_date") val lastModificationDate: Long = 0,
|
||||
val keywords: List<String> = emptyList(),
|
||||
val rating: Int = -1,
|
||||
val color: String = "none",
|
||||
val urls: Map<String, JsonElement> = emptyMap(),
|
||||
val todolists: List<CarnetTodo> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class CarnetTodo(
|
||||
val id: String = "",
|
||||
val todo: List<String> = emptyList(),
|
||||
val done: List<String> = emptyList(),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* M4.4a seam for [PassphraseGenerator] — identical two-liner actual on
|
||||
* both targets (both targets ARE the JVM; commonMain just cannot spell
|
||||
* `java.security`). Behaviour (CSPRNG backing, draw distribution) is
|
||||
* exactly the pre-M4 `SecureRandom()` field it replaces.
|
||||
*/
|
||||
|
||||
private val secureRandom = SecureRandom()
|
||||
|
||||
internal actual fun secureRandomInt(bound: Int): Int = secureRandom.nextInt(bound)
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.incido.compose.data.settings
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
|
||||
/**
|
||||
* Phase 1 (M3 task 1): the Android half of the settings seam.
|
||||
*
|
||||
* v0.3.2.0: Application-wide DataStore Preferences instance. Declared
|
||||
* as a Context extension property so the same backing file is shared
|
||||
* by every call site. Backed by `incido_settings.preferences_pb` in
|
||||
* the app's `noBackupFiles` directory.
|
||||
*
|
||||
* Lives on the Android side now that [SettingsRepository] is platform
|
||||
* neutral (it takes an injected DataStore); the desktop build creates the
|
||||
* same-format store from a file path instead of a Context.
|
||||
*/
|
||||
val Context.settingsDataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = "incido_settings",
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.incido.compose.di
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
|
||||
/**
|
||||
* M4.3c — Android-only bridge beside [LocalAppGraph].
|
||||
*
|
||||
* `SettingsViewModel` still needs the concrete [AppContainer] (Security
|
||||
* Manager, Keystore key provider, BackupManager, CarnetImporter — the
|
||||
* Android services M4.3 deliberately did NOT widen the graph with). The
|
||||
* screen reads this local until M4.4/4.5 ports or hides that surface;
|
||||
* `IncidoApp` provides the SAME container instance through both locals.
|
||||
*/
|
||||
val LocalAndroidContainer = compositionLocalOf<AppContainer?> { null }
|
||||
|
||||
/** Read [LocalAndroidContainer] or throw with context — call at composition. */
|
||||
@Composable
|
||||
fun requireAndroidContainer(): AppContainer = checkNotNull(LocalAndroidContainer.current) {
|
||||
"No AppContainer provided — IncidoApp provides it at the root."
|
||||
}
|
||||
@@ -5,17 +5,24 @@ import io.objectbox.BoxStore
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import org.incido.data.AndroidImageOrientationNormalizer
|
||||
import org.incido.data.ObjectBoxStore
|
||||
import org.incido.data.crypto.AesGcmFieldCipher
|
||||
import org.incido.data.crypto.CipherHolder
|
||||
import org.incido.data.crypto.EncryptionVerifier
|
||||
import org.incido.data.crypto.NoteCryptoService
|
||||
import org.incido.data.repository.NoteRepositoryImpl
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
import org.incido.compose.data.backup.BackupManager
|
||||
import org.incido.compose.data.security.AesGcmFieldCipher
|
||||
import org.incido.compose.data.security.EncryptionVerifier
|
||||
import org.incido.compose.data.backup.CarnetImporter
|
||||
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.compose.data.settings.SettingsRepository
|
||||
import org.incido.compose.data.settings.settingsDataStore
|
||||
import org.incido.compose.di.AppGraph
|
||||
import org.incido.compose.di.EncryptionBadge
|
||||
import org.incido.compose.di.LibraryVerification
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
/**
|
||||
* Hand-rolled DI container. Replaces Hilt/Dagger for v0.1 — keeps the
|
||||
@@ -38,8 +45,14 @@ import org.incido.compose.data.settings.SettingsRepository
|
||||
* After startup the [encryptionVerifier] re-checks every encrypted row
|
||||
* by trial-decrypting it; only rows that pass earn the "Encrypted"
|
||||
* badge on the note cards.
|
||||
*
|
||||
* Phase 1 (M4.3): implements [AppGraph] — the platform-neutral face the
|
||||
* commonMain ViewModels consume. Android-only services (Keystore key
|
||||
* provider, SecurityManager, BackupManager, CarnetImporter) stay on this
|
||||
* concrete class; the graph is exactly what the desktop
|
||||
* `DesktopContainer` can implement too.
|
||||
*/
|
||||
class AppContainer(context: Context) {
|
||||
class AppContainer(context: Context) : AppGraph {
|
||||
|
||||
private val appContext: Context = context.applicationContext
|
||||
|
||||
@@ -47,7 +60,11 @@ class AppContainer(context: Context) {
|
||||
* (verification sweeps, etc.). SupervisorJob isolates failures. */
|
||||
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
val settingsRepository: SettingsRepository = SettingsRepository(appContext)
|
||||
// Phase 1 (M3 task 1): the store is injected — SettingsRepository moved
|
||||
// to :core:settings so the desktop build can share it. Android supplies
|
||||
// the Context-backed `incido_settings.preferences_pb` store here.
|
||||
override val settingsRepository: SettingsRepository =
|
||||
SettingsRepository(appContext.settingsDataStore)
|
||||
|
||||
val objectBoxKeyProvider: ObjectBoxKeyProvider = ObjectBoxKeyProvider(appContext)
|
||||
|
||||
@@ -70,20 +87,44 @@ class AppContainer(context: Context) {
|
||||
init {
|
||||
val s = settingsRepository.snapshot()
|
||||
if (s.isEncryptionActive && objectBoxKeyProvider.hasKeyBlocking()) {
|
||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
|
||||
// M3 task 2 seam: the cipher only needs the key bytes; the
|
||||
// Keystore-wrapped provider is passed as a plain function.
|
||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
|
||||
}
|
||||
}
|
||||
|
||||
val noteRepository: NoteRepository = NoteRepositoryImpl(boxStore, cipherHolder)
|
||||
override val noteRepository: NoteRepository = NoteRepositoryImpl(
|
||||
boxStore,
|
||||
cipherHolder,
|
||||
// Phase 1 (M1a) platform seam: EXIF rotation needs a bitmap decoder,
|
||||
// which Android owns and the desktop build has yet to grow.
|
||||
AndroidImageOrientationNormalizer(),
|
||||
)
|
||||
|
||||
val backupManager: BackupManager = BackupManager(appContext, noteRepository)
|
||||
|
||||
/** v0.3.9.0 — Carnet / QuickNote `.sqd` archive importer. */
|
||||
val carnetImporter: CarnetImporter = CarnetImporter(appContext, noteRepository)
|
||||
|
||||
|
||||
/** Migration sweep + startup integrity checker for the note store. */
|
||||
val noteCryptoService = NoteCryptoService(boxStore, cipherHolder)
|
||||
|
||||
/** Runs on every app open — feeds the verified-encryption badge. */
|
||||
val encryptionVerifier = EncryptionVerifier(noteCryptoService, appScope)
|
||||
|
||||
/**
|
||||
* M4.3c: [AppGraph]'s shared face over the concrete verifier — the
|
||||
* 3-field copy is why `LibraryVerification` mirrors the data class
|
||||
* (see EncryptionBadge.kt: :core:data is an androidLibrary, invisible
|
||||
* to commonMain, and must stay that way per invariant §2.3).
|
||||
*/
|
||||
override val encryptionBadge: EncryptionBadge = object : EncryptionBadge {
|
||||
override val verification = encryptionVerifier.verification.map { result ->
|
||||
result?.let { LibraryVerification(it.verifiedNoteIds, it.failedNoteIds, it.checkedAt) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Kick the startup verification off immediately. */
|
||||
init {
|
||||
encryptionVerifier.checkNow()
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.incido.compose.di
|
||||
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
|
||||
internal actual val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
|
||||
@@ -0,0 +1,312 @@
|
||||
package org.incido.compose.ui.editor
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.content.FileProvider
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.domain.model.NoteAttachment
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* M4.4c Android actual — the editor's Android intake code, moved from
|
||||
* `NoteEditorScreen` essentially verbatim (camera + permission + file
|
||||
* launchers, the FileProvider/ACTION_VIEW open path from
|
||||
* `AttachmentThumbnail`, the Toasts, and the two private file helpers).
|
||||
*
|
||||
* The one spelling change: `securityManager?.beginExternalActivity()`
|
||||
* is now the injected neutral `beginExternalActivity` lambda (the
|
||||
* screen can no longer name the Android type in commonMain). Call sites
|
||||
* (camera round-trip, picker, system viewer) are unchanged.
|
||||
*/
|
||||
@Composable
|
||||
actual fun rememberEditorIntake(
|
||||
onPickedBytes: suspend (bytes: ByteArray, mimeType: String, displayName: String) -> Unit,
|
||||
onVoiceConvert: () -> Unit,
|
||||
isVoiceMode: Boolean,
|
||||
beginExternalActivity: (() -> Unit)?,
|
||||
): EditorIntake {
|
||||
val ctx = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
// v0.3.1.0: camera permission + capture. The camera launcher is
|
||||
// declared FIRST so the permission callback (below) can forward to it
|
||||
// without a Kotlin forward-reference error.
|
||||
var pendingCameraUri by remember { mutableStateOf<Uri?>(null) }
|
||||
val cameraLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.TakePicture()
|
||||
) { success ->
|
||||
val uri = pendingCameraUri
|
||||
if (success && uri != null) {
|
||||
scope.launch {
|
||||
val bytes = withContext(Dispatchers.IO) {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
}
|
||||
// Always delete the temp file — its bytes are now in the DB.
|
||||
runCatching { uri.path?.let { File(it).delete() } }
|
||||
pendingCameraUri = null
|
||||
if (bytes != null) {
|
||||
onPickedBytes(
|
||||
bytes,
|
||||
"image/jpeg",
|
||||
"IMG_${System.currentTimeMillis()}.jpg",
|
||||
)
|
||||
} else {
|
||||
Toast.makeText(ctx, "Couldn't read captured photo", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pendingCameraUri = null
|
||||
}
|
||||
}
|
||||
// Now declared AFTER cameraLauncher so it can forward to it.
|
||||
val cameraPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { granted ->
|
||||
if (granted) {
|
||||
pendingCameraUri?.let { uri ->
|
||||
// v0.3.4.0 hotfix: the camera app takes us fully out of
|
||||
// the process — with Auto-Lock = Immediate the return
|
||||
// trip used to land on the lock screen (losing the
|
||||
// unsaved note). Flag the round-trip so the re-lock is
|
||||
// suppressed.
|
||||
beginExternalActivity?.invoke()
|
||||
cameraLauncher.launch(uri)
|
||||
}
|
||||
} else {
|
||||
Toast.makeText(ctx, "Camera permission denied", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
val filePickerLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocument()
|
||||
) { uri ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
scope.launch {
|
||||
val ctxForResolver = ctx
|
||||
val (bytes, displayName, mime) = withContext(Dispatchers.IO) {
|
||||
val resolver = ctxForResolver.contentResolver
|
||||
val name = queryDisplayName(resolver, uri) ?: "Attachment_${System.currentTimeMillis()}"
|
||||
val mimeType = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val data = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
Triple(data, name, mimeType)
|
||||
}
|
||||
if (bytes != null) {
|
||||
onPickedBytes(bytes, mime, displayName)
|
||||
} else {
|
||||
Toast.makeText(ctx, "Couldn't read attachment", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
onVoiceConvert()
|
||||
} else {
|
||||
Toast.makeText(ctx, "Microphone permission denied", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
fun micPermissionGranted(): Boolean =
|
||||
ContextCompat.checkSelfPermission(
|
||||
ctx,
|
||||
Manifest.permission.RECORD_AUDIO,
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
return object : EditorIntake {
|
||||
override val supportsCamera = true
|
||||
override val supportsVoice = true
|
||||
|
||||
override fun takePhoto() {
|
||||
val (uri, _) = createTempCameraUri(ctx)
|
||||
if (uri == null) {
|
||||
Toast.makeText(ctx, "Couldn't prepare camera outbox", Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
pendingCameraUri = uri
|
||||
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
|
||||
override fun pickFiles() {
|
||||
// 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.
|
||||
beginExternalActivity?.invoke()
|
||||
filePickerLauncher.launch(arrayOf("*/*"))
|
||||
}
|
||||
|
||||
override fun toggleVoiceMode() {
|
||||
if (isVoiceMode) {
|
||||
// Toggling back needs no mic at all — the take survives as
|
||||
// an ordinary attachment.
|
||||
onVoiceConvert()
|
||||
return
|
||||
}
|
||||
if (micPermissionGranted()) {
|
||||
onVoiceConvert()
|
||||
} else {
|
||||
micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
}
|
||||
|
||||
override fun checkMicPermission(): Boolean = micPermissionGranted()
|
||||
|
||||
override fun requestMicPermission() {
|
||||
micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
|
||||
override fun notify(msg: String) {
|
||||
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
override fun openExternal(bytes: ByteArray, mimeType: String, displayName: String) {
|
||||
// v0.3.1.2 path, verbatim from AttachmentThumbnail's tap
|
||||
// handler: cache temp file → FileProvider Uri → ACTION_VIEW.
|
||||
runCatching {
|
||||
// Sanitise displayName for use as a filename —
|
||||
// strip any path separators / chars the OS
|
||||
// doesn't allow in filenames.
|
||||
val safeName = displayName.replace(Regex("[/\\\\:*?\"<>|]"), "_")
|
||||
// v0.3.1.3: write into a dedicated `open_outbox/`
|
||||
// subdir under cacheDir so it falls inside the
|
||||
// FileProvider's exposed path set (see
|
||||
// app/src/main/res/xml/file_paths.xml). Previously
|
||||
// this wrote straight to cacheDir which is NOT
|
||||
// exposed, so FileProvider.getUriForFile threw
|
||||
// IllegalArgumentException and the runCatching
|
||||
// swallowed it as the misleading "No app can
|
||||
// open …" toast.
|
||||
val outbox = File(ctx.cacheDir, "open_outbox").apply { mkdirs() }
|
||||
val tmp = File(
|
||||
outbox,
|
||||
"open_${System.currentTimeMillis()}_$safeName",
|
||||
).apply { createNewFile() }
|
||||
tmp.writeBytes(bytes)
|
||||
val uri = FileProvider.getUriForFile(
|
||||
ctx,
|
||||
"${ctx.packageName}.fileprovider",
|
||||
tmp,
|
||||
)
|
||||
val intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, mimeType)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
// v0.3.4.0 hotfix: opening an attachment in the system
|
||||
// viewer also leaves the app — suppress the auto-lock on
|
||||
// return.
|
||||
beginExternalActivity?.invoke()
|
||||
ctx.startActivity(intent)
|
||||
}.onFailure { err ->
|
||||
// v0.3.1.3: distinguish "no handler" from "couldn't
|
||||
// open". ActivityNotFoundException means the OS has no
|
||||
// app registered for this mime type (e.g. no PDF viewer
|
||||
// installed); anything else (typically
|
||||
// IllegalArgumentException from FileProvider when
|
||||
// file_paths.xml is misconfigured, or IOException from
|
||||
// the cache write) gets a generic message.
|
||||
val msg = if (err is android.content.ActivityNotFoundException) {
|
||||
"No app can open $displayName"
|
||||
} else {
|
||||
"Couldn't open $displayName"
|
||||
}
|
||||
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* M4.4c Android actual: the voice recorder card — the same
|
||||
* `VoiceNoteSection` the screen called directly, now reached through
|
||||
* the common slot. The old `securityManager` argument becomes the
|
||||
* neutral [beginExternalActivity] lambda (see VoiceNoteSection).
|
||||
*/
|
||||
@Composable
|
||||
actual fun VoiceNoteSlot(
|
||||
voicePending: PendingAttachment?,
|
||||
voicePendingBytes: ByteArray?,
|
||||
voicePersisted: NoteAttachment?,
|
||||
repository: NoteRepository?,
|
||||
hasMicPermission: () -> Boolean,
|
||||
onRequestPermission: () -> Unit,
|
||||
onTakeRecorded: (ByteArray, String) -> Unit,
|
||||
onDeleteTake: () -> Unit,
|
||||
beginExternalActivity: (() -> Unit)?,
|
||||
modifier: Modifier,
|
||||
) {
|
||||
VoiceNoteSection(
|
||||
voicePending = voicePending,
|
||||
voicePendingBytes = voicePendingBytes,
|
||||
voicePersisted = voicePersisted,
|
||||
repository = repository,
|
||||
hasMicPermission = hasMicPermission,
|
||||
onRequestPermission = onRequestPermission,
|
||||
onTakeRecorded = onTakeRecorded,
|
||||
onDeleteTake = onDeleteTake,
|
||||
beginExternalActivity = beginExternalActivity,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// helpers — moved verbatim from NoteEditorScreen.kt
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a temporary file in the app's cache and return a
|
||||
* FileProvider-scoped Uri pointing at it. The camera app writes a JPEG
|
||||
* there; we read the bytes and delete the temp file. Returns
|
||||
* `(uri, file)` so the caller can clean up if reading fails.
|
||||
*/
|
||||
private fun createTempCameraUri(ctx: Context): Pair<Uri?, File?> {
|
||||
return try {
|
||||
val outbox = File(ctx.cacheDir, "camera_outbox").apply { mkdirs() }
|
||||
val file = File(outbox, "cap_${System.currentTimeMillis()}.jpg")
|
||||
file.createNewFile()
|
||||
val authority = "${ctx.packageName}.fileprovider"
|
||||
val uri = FileProvider.getUriForFile(ctx, authority, file)
|
||||
uri to file
|
||||
} catch (e: Exception) {
|
||||
null to null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the Open Documents column DISPLAY_NAME for a content:// Uri,
|
||||
* falling back to the last path segment. Returns null if neither
|
||||
* works (which is fine — the caller uses a generated default).
|
||||
*/
|
||||
private fun queryDisplayName(resolver: android.content.ContentResolver, uri: Uri): String? {
|
||||
return try {
|
||||
resolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||
?.use { cursor ->
|
||||
if (cursor.moveToFirst()) {
|
||||
val idx = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
|
||||
if (idx >= 0) cursor.getString(idx) else null
|
||||
} else null
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
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.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). */
|
||||
beginExternalActivity: (() -> Unit)?,
|
||||
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, beginExternalActivity, 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,
|
||||
beginExternalActivity: (() -> Unit)?,
|
||||
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).
|
||||
beginExternalActivity?.invoke()
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ import kotlinx.coroutines.launch
|
||||
import org.incido.compose.data.backup.BackupPreview
|
||||
import org.incido.compose.data.backup.EncryptedBackupCodec
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.compose.di.requireAndroidContainer
|
||||
import org.incido.compose.data.settings.AutoLockTimeout
|
||||
import org.incido.compose.data.settings.ThemeMode
|
||||
|
||||
@@ -93,7 +94,7 @@ fun SettingsScreen(
|
||||
* suppression (the pre-0.3.4.0 behaviour).
|
||||
*/
|
||||
securityManager: SecurityManager? = null,
|
||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
|
||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
|
||||
) {
|
||||
val settings by viewModel.userSettings.collectAsStateWithLifecycle()
|
||||
val migrationState by viewModel.migrationState.collectAsStateWithLifecycle()
|
||||
@@ -122,6 +123,15 @@ fun SettingsScreen(
|
||||
var showRecoveryImportWarning by remember { mutableStateOf(false) }
|
||||
|
||||
// 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(
|
||||
contract = ActivityResultContracts.CreateDocument("application/json"),
|
||||
) { uri ->
|
||||
@@ -296,6 +306,12 @@ fun SettingsScreen(
|
||||
securityManager?.beginExternalActivity()
|
||||
importLauncher.launch(arrayOf("application/json", "*/*"))
|
||||
},
|
||||
onImportCarnet = {
|
||||
securityManager?.beginExternalActivity()
|
||||
carnetImportLauncher.launch(
|
||||
arrayOf("application/zip", "application/x-zip-compressed", "application/octet-stream", "*/*"),
|
||||
)
|
||||
},
|
||||
)
|
||||
AboutSection(
|
||||
version = SettingsViewModel.APP_VERSION,
|
||||
@@ -395,6 +411,13 @@ fun SettingsScreen(
|
||||
// the app.
|
||||
pendingImportPassphrase = chars.copyOf()
|
||||
if (importUri != null) {
|
||||
// v0.4.2.1 hotfix: re-arm the URI slot that
|
||||
// the shared preamble above just cleared.
|
||||
// The preview-confirm dialog's Import button
|
||||
// reads pendingImportUri; leaving it null
|
||||
// made encrypted imports a silent no-op
|
||||
// (dialog closed, nothing imported).
|
||||
pendingImportUri = importUri
|
||||
scope.launch {
|
||||
// `chars` is consumed (zeroed) by the
|
||||
// decrypt step; the retained copy survives.
|
||||
@@ -644,55 +667,6 @@ private var pendingPassphraseMode: PassphraseDialogMode = PassphraseDialogMode.E
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AppearanceSection(
|
||||
themeMode: ThemeMode,
|
||||
dynamicColor: Boolean,
|
||||
onThemeMode: (ThemeMode) -> Unit,
|
||||
onDynamicColor: (Boolean) -> Unit,
|
||||
) {
|
||||
SettingsSection(title = "Appearance") {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Text("Theme", style = MaterialTheme.typography.labelLarge)
|
||||
Spacer(Modifier.padding(top = 6.dp))
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
ThemeMode.values().forEachIndexed { index, mode ->
|
||||
SegmentedButton(
|
||||
selected = themeMode == mode,
|
||||
onClick = { onThemeMode(mode) },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = ThemeMode.values().size,
|
||||
),
|
||||
label = {
|
||||
Text(when (mode) {
|
||||
ThemeMode.SYSTEM -> "System"
|
||||
ThemeMode.LIGHT -> "Light"
|
||||
ThemeMode.DARK -> "Dark"
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.padding(top = 12.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("Dynamic color", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
"Use the system Material You palette on Android 12+.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(checked = dynamicColor, onCheckedChange = onDynamicColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.3.0: PIN and Biometric are mutually-exclusive toggles. When
|
||||
* the master security switch is off, both are greyed. When one is
|
||||
@@ -821,148 +795,6 @@ private fun SecuritySection(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BackupSection(
|
||||
onExport: () -> Unit,
|
||||
onImport: () -> Unit,
|
||||
) {
|
||||
SettingsSection(title = "Backup & Restore") {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
"Export your notes to a JSON file (with optional passphrase " +
|
||||
"encryption) or import a backup. Imports are additive — " +
|
||||
"they don't replace your existing notes.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(onClick = onExport, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Export to file…")
|
||||
}
|
||||
OutlinedButton(onClick = onImport, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Import from file…")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AboutSection(
|
||||
version: String,
|
||||
onVersionClick: () -> Unit,
|
||||
) {
|
||||
SettingsSection(title = "About") {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onVersionClick)
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("Incido", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
text = "Version $version",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = "Tap for release notes",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Building blocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun SettingsSection(title: String, content: @Composable () -> Unit) {
|
||||
Column {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(start = 4.dp, top = 8.dp, bottom = 4.dp),
|
||||
)
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** v0.3.3.0: optionally renders a disabled (greyed) switch — used for
|
||||
* the mutually-exclusive PIN / Biometric toggles. */
|
||||
@Composable
|
||||
private fun SettingsToggle(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
val color = if (enabled) {
|
||||
MaterialTheme.colorScheme.onSurface
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
val subColor = if (enabled) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium, color = color)
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = subColor,
|
||||
)
|
||||
}
|
||||
Switch(checked = checked, onCheckedChange = onCheckedChange, enabled = enabled)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SettingsRow(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TimeoutDialog(
|
||||
@@ -2,7 +2,6 @@ package org.incido.compose.ui.settings
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.initializer
|
||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||
@@ -12,13 +11,14 @@ import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import org.incido.compose.IncidoApplication
|
||||
import org.incido.compose.di.AppContainer
|
||||
import org.incido.compose.data.backup.BackupManager
|
||||
import org.incido.compose.data.security.AesGcmFieldCipher
|
||||
import org.incido.compose.data.security.EncryptionVerifier
|
||||
import org.incido.compose.data.backup.CarnetImporter
|
||||
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.data.crypto.AesGcmFieldCipher
|
||||
import org.incido.data.crypto.CipherHolder
|
||||
import org.incido.data.crypto.EncryptionVerifier
|
||||
import org.incido.data.crypto.NoteCryptoService
|
||||
import org.incido.compose.data.settings.AutoLockTimeout
|
||||
import org.incido.compose.data.settings.SettingsRepository
|
||||
@@ -46,6 +46,7 @@ class SettingsViewModel(
|
||||
private val security: SecurityManager,
|
||||
private val objectBoxKeyProvider: ObjectBoxKeyProvider,
|
||||
private val backupManager: BackupManager,
|
||||
private val carnetImporter: CarnetImporter,
|
||||
private val noteCryptoService: NoteCryptoService,
|
||||
private val cipherHolder: CipherHolder,
|
||||
private val encryptionVerifier: EncryptionVerifier,
|
||||
@@ -139,7 +140,8 @@ class SettingsViewModel(
|
||||
if (enabled) {
|
||||
// Key first (idempotent), cipher into the holder, sweep.
|
||||
objectBoxKeyProvider.getOrCreateKey()
|
||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
|
||||
cipherHolder.cipher =
|
||||
AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
|
||||
noteCryptoService.encryptAllInPlace { done, total ->
|
||||
_migrationState.value = MigrationState.Running(
|
||||
if (total == 0) 1f else done.toFloat() / total,
|
||||
@@ -241,8 +243,31 @@ class SettingsViewModel(
|
||||
backupManager.preview(uri, passphrase)
|
||||
|
||||
suspend fun import(uri: android.net.Uri, passphrase: CharArray? = null) {
|
||||
val count = backupManager.import(uri, passphrase)
|
||||
_snackbar.value = "Imported $count note(s)."
|
||||
val result = backupManager.import(uri, passphrase)
|
||||
_snackbar.value = if (result.skipped > 0) {
|
||||
"Imported ${result.imported} note(s), skipped ${result.skipped} already imported."
|
||||
} else {
|
||||
"Imported ${result.imported} note(s)."
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.9.0 — import a Carnet / QuickNote archive (`.zip` of `*.sqd`, or a
|
||||
* single `.sqd`) picked via SAF. Additive — existing notes are kept.
|
||||
* Failures are caught and surfaced via the snackbar so a bad file never
|
||||
* crashes the app.
|
||||
*/
|
||||
suspend fun importCarnet(uri: android.net.Uri) {
|
||||
try {
|
||||
val count = carnetImporter.import(uri)
|
||||
_snackbar.value = if (count > 0) {
|
||||
"Imported $count Carnet note(s)."
|
||||
} else {
|
||||
"No Carnet notes found in that file."
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_snackbar.value = "Carnet import failed: ${e.message ?: "unreadable file"}"
|
||||
}
|
||||
}
|
||||
|
||||
// --- v0.3.6.0 recovery key ---
|
||||
@@ -295,7 +320,8 @@ class SettingsViewModel(
|
||||
// Swap the live cipher to point at the freshly-installed key.
|
||||
// We build a new wrapper that re-reads the (just-persisted)
|
||||
// wrapped blob — no need to re-implement the unwrap here.
|
||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
|
||||
cipherHolder.cipher =
|
||||
AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
|
||||
encryptionVerifier.checkNow()
|
||||
_snackbar.value = if (overwroteExisting) {
|
||||
"Recovery key installed. Previously-encrypted notes will appear as unverified."
|
||||
@@ -333,17 +359,25 @@ class SettingsViewModel(
|
||||
/** The version string baked into backup payloads and shown on
|
||||
* the About card. Mirrors `app/build.gradle.kts` `versionName`
|
||||
* — if you bump one, bump both. */
|
||||
const val APP_VERSION = "0.3.6.3"
|
||||
const val APP_VERSION = "0.4.2.0"
|
||||
|
||||
val Factory: ViewModelProvider.Factory = viewModelFactory {
|
||||
/**
|
||||
* M4.3c: graph-based factory — but this ViewModel genuinely needs
|
||||
* the ANDROID services (SecurityManager, Keystore key provider,
|
||||
* BackupManager's Uri IO, CarnetImporter), so it takes the
|
||||
* concrete AppContainer, not just the AppGraph face. It stays in
|
||||
* androidMain until those services gain desktop answers (or the
|
||||
* UI hides them — plan §6.5).
|
||||
*/
|
||||
fun factory(container: AppContainer): ViewModelProvider.Factory = viewModelFactory {
|
||||
initializer {
|
||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
||||
val c = app.container
|
||||
val c = container
|
||||
SettingsViewModel(
|
||||
settings = c.settingsRepository,
|
||||
security = c.securityManager,
|
||||
objectBoxKeyProvider = c.objectBoxKeyProvider,
|
||||
backupManager = c.backupManager,
|
||||
carnetImporter = c.carnetImporter,
|
||||
noteCryptoService = c.noteCryptoService,
|
||||
cipherHolder = c.cipherHolder,
|
||||
encryptionVerifier = c.encryptionVerifier,
|
||||
@@ -40,6 +40,7 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import kotlinx.coroutines.launch
|
||||
import org.incido.compose.di.requireAndroidContainer
|
||||
import org.incido.compose.ui.settings.SettingsViewModel
|
||||
|
||||
/**
|
||||
@@ -57,7 +58,7 @@ import org.incido.compose.ui.settings.SettingsViewModel
|
||||
* stored hash + salt. The screen pops on success and surfaces a
|
||||
* "PIN updated." snackbar via the existing viewModel.snackbar flow.
|
||||
*
|
||||
* Reuses the existing [SettingsViewModel.Factory] — the new screen
|
||||
* Reuses the existing [SettingsViewModel.factory] — the new screen
|
||||
* doesn't need its own ViewModel because every operation goes through
|
||||
* the existing security manager.
|
||||
*/
|
||||
@@ -66,7 +67,7 @@ import org.incido.compose.ui.settings.SettingsViewModel
|
||||
fun PinChangeScreen(
|
||||
onDone: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
|
||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var step by remember { mutableStateOf(Step.VerifyOld) }
|
||||
@@ -36,6 +36,7 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import kotlinx.coroutines.launch
|
||||
import org.incido.compose.di.requireAndroidContainer
|
||||
import org.incido.compose.ui.settings.SettingsViewModel
|
||||
|
||||
/**
|
||||
@@ -60,7 +61,7 @@ import org.incido.compose.ui.settings.SettingsViewModel
|
||||
fun PinSetupScreen(
|
||||
onDone: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
|
||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.incido.compose.ui.theme
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.material3.ColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
/** Android actual — the verbatim pre-M4 dynamic-colour branch: a real
|
||||
* Material You scheme on API 31+ (S), null below that. */
|
||||
@Composable
|
||||
actual fun platformDynamicColorScheme(darkTheme: Boolean): ColorScheme? {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return null
|
||||
val context = LocalContext.current
|
||||
return if (darkTheme) dynamicDarkColorScheme(context)
|
||||
else dynamicLightColorScheme(context)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
|
||||
/**
|
||||
* M4.4b Android actual — the verbatim pre-M4 decode
|
||||
* (`BitmapFactory.decodeByteArray` returns null on undecodable bytes,
|
||||
* exactly the contract [decodeImageBytes] keeps).
|
||||
*/
|
||||
actual fun decodeImageBytes(bytes: ByteArray): ImageBitmap? =
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
|
||||
@@ -0,0 +1,9 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
/** M4.4c Android actual — the verbatim `activity-compose` back handler. */
|
||||
@Composable
|
||||
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
|
||||
androidx.activity.compose.BackHandler(enabled = enabled, onBack = onBack)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import android.text.format.DateUtils
|
||||
|
||||
/** Android actual — verbatim pre-M4 formatting: Android's own
|
||||
* localised relative-time helper, unchanged. */
|
||||
actual fun relativeTimestamp(epochMillis: Long, nowMillis: Long): String =
|
||||
DateUtils.getRelativeTimeSpanString(
|
||||
epochMillis,
|
||||
nowMillis,
|
||||
DateUtils.MINUTE_IN_MILLIS,
|
||||
DateUtils.FORMAT_ABBREV_RELATIVE,
|
||||
).toString()
|
||||
@@ -1,7 +1,6 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import org.incido.compose.data.settings.PasswordPolicy
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* v0.3.2.0: SecureRandom-based passphrase generator for encrypted
|
||||
@@ -15,6 +14,12 @@ import java.security.SecureRandom
|
||||
* If a freshly-generated passphrase fails validation (rare — only if
|
||||
* the random draw happens to miss both a digit and a special) we
|
||||
* regenerate, so the return type is non-nullable.
|
||||
*
|
||||
* M4.4a: `java.security.SecureRandom` is not a commonMain declaration,
|
||||
* so the draw goes through [secureRandomInt] — an internal expect/actual
|
||||
* whose actuals are the same one-liner over a shared SecureRandom on
|
||||
* both targets (same seam discipline as M4.3a's `blockingFirst`; both
|
||||
* targets ARE JVM, this is spelling, not behaviour).
|
||||
*/
|
||||
object PassphraseGenerator {
|
||||
|
||||
@@ -33,8 +38,6 @@ object PassphraseGenerator {
|
||||
PasswordPolicy.SPECIAL_CHARS
|
||||
).toCharArray()
|
||||
|
||||
private val secureRandom = SecureRandom()
|
||||
|
||||
/**
|
||||
* Generate a passphrase of [length] characters (clamped to the
|
||||
* policy's [PasswordPolicy.MIN_LENGTH] / [PasswordPolicy.MAX_LENGTH]
|
||||
@@ -50,14 +53,17 @@ object PassphraseGenerator {
|
||||
// and a special in any draw of >= 12 chars. Fall back to a
|
||||
// hand-crafted compliant value so we never throw from a UI
|
||||
// button tap.
|
||||
return "IncidoBackup!" + secureRandom.nextInt(10_000).toString().padStart(4, '0')
|
||||
return "IncidoBackup!" + secureRandomInt(10_000).toString().padStart(4, '0')
|
||||
}
|
||||
|
||||
private fun buildRandom(length: Int): String {
|
||||
val out = StringBuilder(length)
|
||||
repeat(length) { out.append(ALPHABET[secureRandom.nextInt(ALPHABET.size)]) }
|
||||
repeat(length) { out.append(ALPHABET[secureRandomInt(ALPHABET.size)]) }
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
private const val MAX_ATTEMPTS = 16
|
||||
}
|
||||
|
||||
/** CSPRNG draw in `[0, bound)` — SecureRandom on every target. */
|
||||
internal expect fun secureRandomInt(bound: Int): Int
|
||||
@@ -0,0 +1,161 @@
|
||||
package org.incido.compose.data.settings
|
||||
|
||||
/**
|
||||
* One entry in the "What's New" dialog. Surfaced from the Settings
|
||||
* screen when the user taps the version number.
|
||||
*
|
||||
* v0.3.2.0: the dialog shows the [RECENT] list (newest first) in a
|
||||
* scrollable column. Each entry has a version, a release date, and a
|
||||
* list of bullet points summarising what shipped in that release.
|
||||
*
|
||||
* Content is mirrored from `Incido Development Plan.txt` §10 so the
|
||||
* in-app dialog and the repo's history of changes stay in lockstep
|
||||
* (the plan file is the source of truth at release time).
|
||||
*/
|
||||
data class ReleaseNote(
|
||||
val version: String,
|
||||
val date: String,
|
||||
val bullets: List<String>,
|
||||
)
|
||||
|
||||
object ReleaseNotes {
|
||||
|
||||
/**
|
||||
* The 5 most recent Incido releases, ordered newest → oldest.
|
||||
* Append a new entry on top each release.
|
||||
*/
|
||||
val RECENT: List<ReleaseNote> = listOf(
|
||||
ReleaseNote(
|
||||
version = "0.4.2.0",
|
||||
date = "2026-09-23",
|
||||
bullets = listOf(
|
||||
"Before you update: please make certain you have a " +
|
||||
"current backup — Settings → Backup & Restore → " +
|
||||
"Export (plus your encryption key under Settings → " +
|
||||
"Security if encryption is on) — before installing " +
|
||||
"this version. Every future release will remind " +
|
||||
"you the same way.",
|
||||
"Voice notes: the editor's bottom toolbar gained a mic " +
|
||||
"button, right after the camera — the row is now " +
|
||||
"Photo · Voice · Attach · Tasks · Shopping list, " +
|
||||
"with the hashtag button moved to the far right. " +
|
||||
"Tap it and the note grows a recording card " +
|
||||
"at the top of its body — tap record, stop when " +
|
||||
"you're done, and your take gets a media player with " +
|
||||
"play / pause, a seek bar, and elapsed / total time.",
|
||||
"Recordings are captured as compact Opus audio " +
|
||||
"(.opus files \u2014 32 kbps, single channel): tiny " +
|
||||
"files, clear speech. Phones on Android 8.x / 9 " +
|
||||
"fall back to the old AAC format automatically.",
|
||||
"Your recording is saved with the note like any other " +
|
||||
"attachment — encrypted at rest when encryption " +
|
||||
"is on, riding along in backups — and a download " +
|
||||
"button copies it out to the system Downloads folder " +
|
||||
"when you need the file itself.",
|
||||
"Voice notes are still normal notes: title, text body, " +
|
||||
"colours, tags, favourites, drafts, and search all " +
|
||||
"work as before. Re-recording replaces the old take; " +
|
||||
"converting back to a text note keeps the recording " +
|
||||
"as an ordinary attachment.",
|
||||
"Voice note cards carry a mic badge, and the microphone " +
|
||||
"permission is only asked for on the first tap into " +
|
||||
"voice mode — recordings never leave the device.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.4.1.1",
|
||||
date = "2026-09-23",
|
||||
bullets = listOf(
|
||||
"Saved notes stay put: in v0.4.1.0 every note you " +
|
||||
"saved ended up in Drafts instead of Home \u2014 " +
|
||||
"the editor still believed it was a draft and " +
|
||||
"quietly re-saved it as one when you left the " +
|
||||
"screen. Saving now publishes properly: the note " +
|
||||
"goes to Home and leaves Drafts for good.",
|
||||
"Enter behaves in the price box: in a shopping list, " +
|
||||
"Enter in a row's Price field used to jump the " +
|
||||
"cursor back to the note title \u2014 it now works " +
|
||||
"like Enter in the product field: a fresh row " +
|
||||
"appears below, cursor ready in its Product box.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.4.1.0",
|
||||
date = "2026-09-23",
|
||||
bullets = listOf(
|
||||
"Colour filters in the drawer: a strip of five swatches " +
|
||||
"\u2014 Blue, Green, Amber, Red, Purple \u2014 sits " +
|
||||
"right under Favorites. Tap one and the list shows " +
|
||||
"ONLY notes of that colour; tap it again for Home.",
|
||||
"Colour views follow the Favorites / Untagged rules: " +
|
||||
"trashed notes never show, untagged ones do, and " +
|
||||
"search narrows within the selected colour.",
|
||||
"Auto-saved drafts: a new note saves itself while you " +
|
||||
"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(
|
||||
version = "0.4.0.0",
|
||||
date = "2026-09-18",
|
||||
bullets = listOf(
|
||||
"Import 3rd-party notes: Settings \u2192 Backup & Restore now " +
|
||||
"has an \u201cImport 3rd Party Notes\u201d button that reads a " +
|
||||
"Carnet / QuickNote .zip export (a single archive bundling " +
|
||||
"one .sqd per note) and brings every note in \u2014 directly " +
|
||||
"on-device, with no pre-conversion step.",
|
||||
"Formatting is preserved as plain text: rich-text bodies are " +
|
||||
"flattened, and note colours, keywords (imported as tags) " +
|
||||
"and links carry over. To-do lists become native " +
|
||||
"checklists you can tick off.",
|
||||
"Images come across too \u2014 photo attachments inside each " +
|
||||
"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(
|
||||
version = "0.3.8.0",
|
||||
date = "2026-09-16",
|
||||
bullets = listOf(
|
||||
"Task lists: a checklist button next to the # button in the " +
|
||||
"editor turns any note into an editable task list — add, " +
|
||||
"remove, and tick off items with real checkboxes.",
|
||||
"Shopping lists with a running total: each row gets a " +
|
||||
"quantity dropdown (1\u20139) and a supermarket-style " +
|
||||
"price field \u2014 every digit you tap on the number pad " +
|
||||
"is a cent, so entering 199 means $1.99 (the price box " +
|
||||
"shows your raw entry beside its $ sign; the running " +
|
||||
"total speaks real dollars). Tick an " +
|
||||
"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.4.2.0 push drops v0.3.7.1 off the "5 most recent" tail.
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package org.incido.compose.di
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import org.incido.compose.data.settings.SettingsRepository
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* Phase 1 (M4.3) — the platform-neutral face of the DI container.
|
||||
*
|
||||
* The seam that lets the ViewModels leave `IncidoApplication` /
|
||||
* `AndroidViewModelFactory.APPLICATION_KEY` behind: they receive an
|
||||
* [AppGraph] (via the screen's `viewModel(factory = …)` construction site)
|
||||
* instead of digging the Application out of CreationExtras. Android's
|
||||
* `AppContainer` and the desktop `DesktopContainer` implement the same
|
||||
* face — that is the M4.3 exit proof.
|
||||
*
|
||||
* Scope discipline (§9, no silently widened seams): only what BOTH
|
||||
* platforms can honestly serve lives here — the note store and the
|
||||
* settings stream. Android-only services (Keystore key provider,
|
||||
* SecurityManager lock state, BackupManager's Uri IO, CarnetImporter)
|
||||
* stay on `AppContainer`; the cipher services reach the shared ViewModels
|
||||
* through [EncryptionBadge] instead of the concrete `EncryptionVerifier`.
|
||||
* ViewModels that genuinely need the Android extras (SettingsViewModel
|
||||
* today) stay in androidMain and take the concrete `AppContainer`.
|
||||
*/
|
||||
interface AppGraph {
|
||||
val noteRepository: NoteRepository
|
||||
val settingsRepository: SettingsRepository
|
||||
/**
|
||||
* M4.3c: the encryption-badge feed (verified/unverified note ids from
|
||||
* the trial-decrypt sweep). Both platforms genuinely run
|
||||
* `EncryptionVerifier` on their own store, so this is a shared face,
|
||||
* not an Android concept — see EncryptionBadge.kt for the mapping.
|
||||
*/
|
||||
val encryptionBadge: EncryptionBadge
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the screens find the graph: provided at the root composable of
|
||||
* each platform (`IncidoApp` on Android; the desktop window in M4.5), read
|
||||
* at composition time to build ViewModel factories. Nullable so a screen
|
||||
* rendered outside a provider (preview/test) fails at the factory call
|
||||
* with a clear message instead of a CompositionLocal-absent crash.
|
||||
*/
|
||||
val LocalAppGraph = compositionLocalOf<AppGraph?> { null }
|
||||
|
||||
/** Read [LocalAppGraph] or throw with the M4.3 context — call at composition. */
|
||||
@Composable
|
||||
fun requireAppGraph(): AppGraph = checkNotNull(LocalAppGraph.current) {
|
||||
"No AppGraph provided — wrap the screen in CompositionLocalProvider(LocalAppGraph provides …)."
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.incido.compose.di
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Phase 1 (M4.3c) — the commonMain mirror of `EncryptionVerification`
|
||||
* (`org.incido.data.crypto`, :core:data shared sources).
|
||||
*
|
||||
* Why a mirror instead of the real type: :core:data is an androidLibrary —
|
||||
* its classes are invisible to a KMP commonMain, and it can never become
|
||||
* multiplatform without colliding with invariant §2.3
|
||||
* (objectbox-android and objectbox-java may never share a classpath).
|
||||
* A ViewModel only ever READS the verification result, so the graph
|
||||
* exposes this read-only view; both containers map the real class into it
|
||||
* with a 3-field copy at the seam.
|
||||
*/
|
||||
data class LibraryVerification(
|
||||
val verifiedNoteIds: Set<Long>,
|
||||
val failedNoteIds: Set<Long>,
|
||||
/** [System.currentTimeMillis] when the check ran (set by the platform). */
|
||||
val checkedAt: Long,
|
||||
) {
|
||||
val allOk: Boolean get() = failedNoteIds.isEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* The encryption-badge feed the note list binds to: `null` until the
|
||||
* first verification sweep completes; empty sets when the library is
|
||||
* unencrypted. `EncryptionVerifier`'s common face (see [LibraryVerification]
|
||||
* for why the concrete class can't cross the seam).
|
||||
*/
|
||||
interface EncryptionBadge {
|
||||
val verification: Flow<LibraryVerification?>
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.incido.compose.di
|
||||
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
|
||||
/**
|
||||
* Phase 1 (M4.3c): `Dispatchers.IO` has no commonMain declaration
|
||||
* (coroutines 1.9 keeps it JVM-only). NoteEditorViewModel swaps its four
|
||||
* `withContext(Dispatchers.IO)` sites for this seam — both actuals are
|
||||
* literally `Dispatchers.IO`, so the Android behaviour is unchanged
|
||||
* (invariant §2.1), it is merely spelled through an expect/actual.
|
||||
*/
|
||||
internal expect val ioDispatcher: CoroutineDispatcher
|
||||
@@ -2,14 +2,13 @@ package org.incido.compose.ui.drawer
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.initializer
|
||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import org.incido.compose.IncidoApplication
|
||||
import org.incido.compose.di.AppGraph
|
||||
import org.incido.domain.model.HashtagUsage
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
@@ -18,6 +17,12 @@ import org.incido.domain.repository.NoteRepository
|
||||
* tags" list. Kept separate from [NoteListViewModel] because the
|
||||
* drawer may render even before the list screen is created (and
|
||||
* vice-versa).
|
||||
*
|
||||
* Phase 1 (M4.3b): first ViewModel in commonMain — the §6.4 probe. It
|
||||
* compiles for both targets with its `androidx.lifecycle.*` imports
|
||||
* unchanged (the org.jetbrains.androidx.lifecycle offline set keeps the
|
||||
* androidx FQCNs), and takes the [AppGraph] instead of digging
|
||||
* `IncidoApplication` out of CreationExtras via APPLICATION_KEY.
|
||||
*/
|
||||
class DrawerViewModel(
|
||||
repository: NoteRepository,
|
||||
@@ -32,11 +37,8 @@ class DrawerViewModel(
|
||||
)
|
||||
|
||||
companion object {
|
||||
val Factory: ViewModelProvider.Factory = viewModelFactory {
|
||||
initializer {
|
||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
||||
DrawerViewModel(app.container.noteRepository)
|
||||
}
|
||||
fun factory(graph: AppGraph): ViewModelProvider.Factory = viewModelFactory {
|
||||
initializer { DrawerViewModel(graph.noteRepository) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,15 @@
|
||||
package org.incido.compose.ui.drawer
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
@@ -11,6 +18,9 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Home
|
||||
import androidx.compose.material.icons.filled.LabelOff
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Drafts
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Star
|
||||
import androidx.compose.material.icons.filled.Tag
|
||||
@@ -24,18 +34,25 @@ import androidx.compose.material3.NavigationDrawerItemDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import org.incido.compose.di.requireAppGraph
|
||||
import org.incido.compose.ui.theme.AllNoteColors
|
||||
import org.incido.compose.ui.theme.toComposeColor
|
||||
import org.incido.domain.model.HashtagUsage
|
||||
import org.incido.domain.model.NoteColor
|
||||
import org.incido.domain.model.NoteFilter
|
||||
|
||||
/**
|
||||
* Left-side navigation drawer. Top section has four fixed entries
|
||||
* (Home / Favorites / Untagged / Settings); a `HorizontalDivider`; then
|
||||
* Left-side navigation drawer. Top section has the fixed entries
|
||||
* (Home / Favorites / the colour-swatch strip / Drafts / Untagged /
|
||||
* Trash / Settings); a `HorizontalDivider`; then
|
||||
* a live scrollable list of the user's most-recently-used hashtags.
|
||||
*
|
||||
* Tapping a filter entry calls [onSelectFilter]; tapping Settings
|
||||
@@ -44,6 +61,16 @@ import org.incido.domain.model.NoteFilter
|
||||
*
|
||||
* v0.3.2.0 — Settings is a new entry directly underneath "Untagged"
|
||||
* with its own divider for visual separation.
|
||||
*
|
||||
* Colour filters sit between "Favorites" and "Drafts" as one
|
||||
* horizontal strip of swatches — the colours are self-explanatory, so
|
||||
* there are no labels. Selecting one shows ONLY active notes of that
|
||||
* colour — trashed notes never appear, untagged ones do (see
|
||||
* NoteFilter.ByColor); tapping the selected swatch again returns to
|
||||
* Home.
|
||||
*
|
||||
* "Drafts" lists auto-saved new notes (see Note.isDraft) — a new note
|
||||
* is persisted automatically while it is being written.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -52,7 +79,7 @@ fun IncidoDrawer(
|
||||
onSelectFilter: (NoteFilter) -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.Factory),
|
||||
viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.factory(requireAppGraph())),
|
||||
) {
|
||||
val recent by viewModel.recentHashtags.collectAsStateWithLifecycle()
|
||||
|
||||
@@ -82,12 +109,76 @@ fun IncidoDrawer(
|
||||
onClick = { onSelectFilter(NoteFilter.Favorites) },
|
||||
icon = { Icon(Icons.Filled.Star, contentDescription = null) },
|
||||
)
|
||||
// Colour filters: one horizontal strip of swatches under
|
||||
// Favorites (NONE is not offered; the colours are
|
||||
// self-explanatory, so there are no labels). Each shows
|
||||
// ONLY active notes of that colour — trashed notes never
|
||||
// appear, untagged ones do. Tapping the selected swatch
|
||||
// again returns to Home.
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(
|
||||
space = 14.dp,
|
||||
alignment = Alignment.CenterHorizontally,
|
||||
),
|
||||
) {
|
||||
AllNoteColors.filter { it != NoteColor.NONE }.forEach { color ->
|
||||
val selected = currentFilter == NoteFilter.ByColor(color)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(30.dp)
|
||||
.clip(CircleShape)
|
||||
.background(color.toComposeColor())
|
||||
.then(
|
||||
if (selected) {
|
||||
Modifier.border(
|
||||
width = 3.dp,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
shape = CircleShape,
|
||||
)
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
)
|
||||
.clickable {
|
||||
onSelectFilter(
|
||||
if (selected) NoteFilter.Home
|
||||
else NoteFilter.ByColor(color),
|
||||
)
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (selected) {
|
||||
Icon(
|
||||
Icons.Filled.Check,
|
||||
contentDescription = "${color.label} filter selected",
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = Color.White,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
NavigationDrawerItem(
|
||||
label = { Text("Drafts") },
|
||||
selected = currentFilter == NoteFilter.Drafts,
|
||||
onClick = { onSelectFilter(NoteFilter.Drafts) },
|
||||
icon = { Icon(Icons.Filled.Drafts, contentDescription = null) },
|
||||
)
|
||||
NavigationDrawerItem(
|
||||
label = { Text("Untagged") },
|
||||
selected = currentFilter == NoteFilter.Untagged,
|
||||
onClick = { onSelectFilter(NoteFilter.Untagged) },
|
||||
icon = { Icon(Icons.Filled.LabelOff, contentDescription = null) },
|
||||
)
|
||||
NavigationDrawerItem(
|
||||
label = { Text("Trash") },
|
||||
selected = currentFilter == NoteFilter.Trash,
|
||||
onClick = { onSelectFilter(NoteFilter.Trash) },
|
||||
icon = { Icon(Icons.Filled.Delete, contentDescription = null) },
|
||||
)
|
||||
|
||||
HorizontalDivider(modifier = Modifier.padding(vertical = 12.dp))
|
||||
|
||||
@@ -121,6 +212,10 @@ fun IncidoDrawer(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
// weight(1f) caps this list at the remaining
|
||||
// sheet height so long tag lists scroll inside
|
||||
// the drawer instead of overflowing the bottom.
|
||||
.weight(1f)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
@@ -158,6 +253,3 @@ private fun DrawerHashtagEntry(
|
||||
icon = { Icon(Icons.Filled.Tag, contentDescription = null) },
|
||||
)
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
private val _ignored: Color = Color.Unspecified
|
||||
@@ -0,0 +1,90 @@
|
||||
package org.incido.compose.ui.editor
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import org.incido.domain.model.NoteAttachment
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* Phase 1 (M4.4c) — the §6.3 file-intake seam for the editor.
|
||||
*
|
||||
* Everything the editor reaches outside Compose — camera capture, file
|
||||
* picker, mic-permission dance, "open this attachment in another app"
|
||||
* — lives behind this interface, provided per platform by
|
||||
* [rememberEditorIntake]. Android's actual keeps the pre-M4 code
|
||||
* (Activity result launchers, FileProvider, Toasts) verbatim; the JVM
|
||||
* actual answers with AWT dialogs (file picker = `FileDialog`, the same
|
||||
* mechanism M2's desktop Import/Export menu uses) and reports
|
||||
* `supportsCamera = supportsVoice = false` so the editor HIDES those
|
||||
* affordances rather than stubbing them (§6.5).
|
||||
*
|
||||
* `beginExternalActivity` is the neutral replacement for the editor's
|
||||
* old `SecurityManager?` parameter: Android passes
|
||||
* `{ securityManager?.beginExternalActivity() }` (auto-lock suppression
|
||||
* around every round-trip that backgrounds the app), desktop passes
|
||||
* null — there is no auto-lock on desktop (M3 decision).
|
||||
*/
|
||||
interface EditorIntake {
|
||||
/** Camera capture available (Android yes, desktop no — §6.5). */
|
||||
val supportsCamera: Boolean
|
||||
/** Voice-note recording available (Android yes, desktop no — §6.5). */
|
||||
val supportsVoice: Boolean
|
||||
|
||||
/** Permission-checked camera round-trip ending in `onPickedBytes`. */
|
||||
fun takePhoto()
|
||||
|
||||
/** File picker ending in `onPickedBytes`. */
|
||||
fun pickFiles()
|
||||
|
||||
/** Voice-mode toggle including the first-tap mic-permission ask. */
|
||||
fun toggleVoiceMode()
|
||||
|
||||
/** Live-checked (never cached) RECORD_AUDIO state. */
|
||||
fun checkMicPermission(): Boolean
|
||||
|
||||
/** Ask for RECORD_AUDIO; grants feed back into [toggleVoiceMode]. */
|
||||
fun requestMicPermission()
|
||||
|
||||
/** Hand bytes to the platform's "open with" mechanism. */
|
||||
fun openExternal(bytes: ByteArray, mimeType: String, displayName: String)
|
||||
|
||||
/**
|
||||
* One-shot user nudge (the thumbnail "Loading…" hint that used to be
|
||||
* a Toast on the tap path). Android actual = Toast (verbatim
|
||||
* behaviour); JVM actual = no-op — a desktop window has no Toast
|
||||
* surface and the hint concerns a transient lazy-load state.
|
||||
*/
|
||||
fun notify(msg: String)
|
||||
}
|
||||
|
||||
/** Construction-time provider for [EditorIntake] (launchers are composables). */
|
||||
@Composable
|
||||
expect fun rememberEditorIntake(
|
||||
onPickedBytes: suspend (bytes: ByteArray, mimeType: String, displayName: String) -> Unit,
|
||||
onVoiceConvert: () -> Unit,
|
||||
/** Whether the note is currently in voice mode — the mic toggle
|
||||
* converts BACK without a permission ask (verbatim pre-M4 rule). */
|
||||
isVoiceMode: Boolean,
|
||||
beginExternalActivity: (() -> Unit)?,
|
||||
): EditorIntake
|
||||
|
||||
/**
|
||||
* The editor's voice-recorder card. Android actual renders
|
||||
* `VoiceNoteSection` (MediaStore recorder, MediaPlayer); the JVM actual
|
||||
* renders NOTHING (§6.5 — hidden, not stubbed: voice notes imported
|
||||
* from a phone keep their audio attachment, there is just no desktop
|
||||
* recorder UI).
|
||||
*/
|
||||
@Composable
|
||||
expect fun VoiceNoteSlot(
|
||||
voicePending: PendingAttachment?,
|
||||
voicePendingBytes: ByteArray?,
|
||||
voicePersisted: NoteAttachment?,
|
||||
repository: NoteRepository?,
|
||||
hasMicPermission: () -> Boolean,
|
||||
onRequestPermission: () -> Unit,
|
||||
onTakeRecorded: (ByteArray, String) -> Unit,
|
||||
onDeleteTake: () -> Unit,
|
||||
beginExternalActivity: (() -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
)
|
||||
@@ -18,7 +18,6 @@ import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
@@ -27,19 +26,17 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import android.graphics.BitmapFactory
|
||||
import android.widget.Toast
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.compose.di.ioDispatcher
|
||||
import org.incido.compose.util.decodeImageBytes
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
@@ -91,37 +88,31 @@ fun ImageViewerScreen(
|
||||
offsetY += panChange.y
|
||||
}
|
||||
|
||||
// Decode the image (or display an error / "unsupported"
|
||||
// message for non-image attachments).
|
||||
val bitmap by produceState<android.graphics.Bitmap?>(initialValue = null, key1 = attachmentId) {
|
||||
// Decode the image (or display an error message when the
|
||||
// bytes can't be loaded / decoded).
|
||||
var loadFailed by remember { mutableStateOf(false) }
|
||||
val bitmap by produceState<ImageBitmap?>(initialValue = null, key1 = attachmentId) {
|
||||
loadFailed = false
|
||||
val bytes: ByteArray? = when (attachmentId) {
|
||||
is ViewerAttachmentId.Persisted -> withContext(Dispatchers.IO) {
|
||||
is ViewerAttachmentId.Persisted -> withContext(ioDispatcher) {
|
||||
repository.getAttachmentBytes(attachmentId.id)
|
||||
}
|
||||
is ViewerAttachmentId.Pending -> pendingBytes
|
||||
}
|
||||
if (bytes == null) {
|
||||
value = null
|
||||
loadFailed = true
|
||||
return@produceState
|
||||
}
|
||||
value = withContext(Dispatchers.IO) {
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
}
|
||||
}
|
||||
|
||||
val ctx = LocalContext.current
|
||||
LaunchedEffect(attachmentId) {
|
||||
if (attachmentId is ViewerAttachmentId.Persisted) {
|
||||
val mime = "image" // we only open the viewer for images; see editor
|
||||
if (bitmap == null) {
|
||||
Toast.makeText(ctx, "Couldn't decode $mime attachment", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
val decoded = withContext(ioDispatcher) {
|
||||
decodeImageBytes(bytes)
|
||||
}
|
||||
value = decoded
|
||||
if (decoded == null) loadFailed = true
|
||||
}
|
||||
|
||||
if (bitmap != null) {
|
||||
Image(
|
||||
bitmap = bitmap!!.asImageBitmap(),
|
||||
bitmap = bitmap!!,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier
|
||||
@@ -152,7 +143,7 @@ fun ImageViewerScreen(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
text = "Loading…",
|
||||
text = if (loadFailed) "Couldn't load image" else "Loading…",
|
||||
color = Color.White,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
@@ -2,25 +2,32 @@ package org.incido.compose.ui.editor
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.initializer
|
||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.debounce
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.compose.IncidoApplication
|
||||
import org.incido.compose.di.AppGraph
|
||||
import org.incido.compose.di.ioDispatcher
|
||||
import org.incido.compose.share.LinkedShareComposer
|
||||
import org.incido.domain.model.ChecklistItem
|
||||
import org.incido.domain.model.Hashtag
|
||||
import org.incido.domain.model.Note
|
||||
import org.incido.domain.model.NoteAttachment
|
||||
import org.incido.domain.model.NoteColor
|
||||
import org.incido.domain.model.NoteType
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
@@ -33,6 +40,16 @@ data class NoteEditorUiState(
|
||||
val color: NoteColor = NoteColor.NONE,
|
||||
/** Normalised, sorted ascending. */
|
||||
val hashtags: List<String> = emptyList(),
|
||||
|
||||
/** v0.3.8.0 — which editor surface the body uses (see [NoteType]). */
|
||||
val type: NoteType = NoteType.TEXT,
|
||||
|
||||
/** v0.3.8.0 — title / preamble kept above the rows in list modes. */
|
||||
val listHeader: String = "",
|
||||
|
||||
/** v0.3.8.0 — parsed checklist rows; always empty for [NoteType.TEXT]. */
|
||||
val items: List<ChecklistItem> = emptyList(),
|
||||
|
||||
/** True while the add-tag sheet is open. */
|
||||
val isAddingTag: Boolean = false,
|
||||
/** Latest typing in the add-tag sheet (raw, before normalisation). */
|
||||
@@ -75,12 +92,29 @@ data class NoteEditorUiState(
|
||||
*/
|
||||
val fullScreenAttachmentId: ViewerAttachmentId? = null,
|
||||
) {
|
||||
/** `true` while content is non-blank and not in the middle of saving. */
|
||||
val canSave: Boolean get() = content.isNotBlank() && !isSaving
|
||||
|
||||
/** `true` when editing an existing note (existing != null). */
|
||||
val isEditing: Boolean get() = existing != null
|
||||
|
||||
/**
|
||||
* v0.4.2.0 — `true` once a voice take exists (staged pending or
|
||||
* already persisted as an attachment).
|
||||
*/
|
||||
val hasVoiceTake: Boolean get() =
|
||||
pendingAttachments.any { it.mimeType.startsWith("audio/") } ||
|
||||
attachments.any { it.mimeType.startsWith("audio/") }
|
||||
|
||||
/**
|
||||
* `true` while content is non-blank and not in the middle of
|
||||
* saving. v0.4.2.0: a VOICE_NOTE may also save on the strength of
|
||||
* its recording alone — the take IS the note's content.
|
||||
*/
|
||||
val canSave: Boolean get() =
|
||||
(content.isNotBlank() || (type == NoteType.VOICE_NOTE && hasVoiceTake)) &&
|
||||
!isSaving
|
||||
|
||||
/** `true` while this note is an auto-saved draft (see Note.isDraft). */
|
||||
val isDraft: Boolean get() = existing?.isDraft == true
|
||||
|
||||
/** `true` when there's still room to add another tag. */
|
||||
val canAddMoreTags: Boolean get() = hashtags.size < MAX_TAGS
|
||||
|
||||
@@ -90,10 +124,12 @@ data class NoteEditorUiState(
|
||||
initialFavorite: Boolean,
|
||||
initialColor: NoteColor,
|
||||
initialTags: List<String>,
|
||||
initialType: NoteType,
|
||||
): Boolean = content != initialContent ||
|
||||
isFavorite != initialFavorite ||
|
||||
color != initialColor ||
|
||||
hashtags != initialTags
|
||||
hashtags != initialTags ||
|
||||
type != initialType
|
||||
|
||||
companion object {
|
||||
/** Hard cap on tags per note (matches Development Plan §6.1). */
|
||||
@@ -129,6 +165,7 @@ data class PendingAttachment(
|
||||
val isImage: Boolean get() = mimeType.startsWith("image/")
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
|
||||
class NoteEditorViewModel(
|
||||
private val repository: NoteRepository,
|
||||
private val noteId: Long?,
|
||||
@@ -178,6 +215,8 @@ class NoteEditorViewModel(
|
||||
private set
|
||||
var initialHashtags: List<String> = emptyList()
|
||||
private set
|
||||
var initialType: NoteType = NoteType.TEXT
|
||||
private set
|
||||
|
||||
/** Internal: re-emits suggestions whenever the tag input changes. */
|
||||
private val tagInputFlow = MutableStateFlow("")
|
||||
@@ -190,21 +229,60 @@ class NoteEditorViewModel(
|
||||
*/
|
||||
private var nextPendingTempId: Long = -System.currentTimeMillis()
|
||||
|
||||
/**
|
||||
* Draft autosave. A NEW note (or one still flagged as a draft) is
|
||||
* persisted automatically: every edit lands in the DB ~400 ms after
|
||||
* the last keystroke (coalesced so typing doesn't write per char),
|
||||
* and [flushDraft] forces an immediate write whenever the editor
|
||||
* closes or disposes. A crash can therefore only ever lose the last
|
||||
* few keystrokes — never a whole draft.
|
||||
*/
|
||||
private val draftAutosave = noteId == null || noteId == 0L
|
||||
|
||||
/** True while this session autosaves: brand-new notes and draft editing. */
|
||||
val isDraftFlow: Boolean
|
||||
get() = draftAutosave || _state.value.isDraft
|
||||
|
||||
private var draftPersistInProgress = false
|
||||
|
||||
init {
|
||||
// Signature-driven debounced autosave: whenever anything a draft
|
||||
// persists changes, write the draft row shortly after.
|
||||
viewModelScope.launch {
|
||||
_state
|
||||
.map { s ->
|
||||
listOf(s.content, s.isFavorite, s.color, s.type, s.hashtags)
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
.debounce(DRAFT_AUTOSAVE_DEBOUNCE_MS)
|
||||
.collect { persistDraftNow() }
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
// Tag autocomplete — re-query on every keystroke (debounced upstream
|
||||
// would be nice but ObjectBox is plenty fast for this size).
|
||||
// Tag autocomplete. v0.3.8.0 FIX: the previous nested
|
||||
// `tagInputFlow.collect { pool.collect { … } }` never resumed
|
||||
// past the first keystroke — observeAllHashtags()/searchHashtags()
|
||||
// are infinite callbackFlows, so the outer lambda suspended in
|
||||
// the inner collect forever and typing never re-queried (the
|
||||
// sheet only ever showed "+ Create"). flatMapLatest cancels the
|
||||
// previous subscription per keystroke, and each fresh flow
|
||||
// try-sends its snapshot immediately ⇒ live filtering.
|
||||
viewModelScope.launch {
|
||||
tagInputFlow.collect { raw ->
|
||||
val prefix = Hashtag.normalise(raw)
|
||||
val pool = if (prefix.isEmpty()) {
|
||||
repository.observeAllHashtags()
|
||||
} else {
|
||||
repository.searchHashtags(prefix)
|
||||
tagInputFlow
|
||||
.flatMapLatest { raw ->
|
||||
val prefix = Hashtag.normalise(raw)
|
||||
if (prefix.isEmpty()) {
|
||||
repository.observeAllHashtags()
|
||||
} else {
|
||||
repository.searchHashtags(prefix)
|
||||
}
|
||||
}
|
||||
pool.collect { suggestions ->
|
||||
.collect { suggestions ->
|
||||
_state.update { it.copy(tagSuggestions = suggestions) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Live attachments: pump persisted rows into state.attachments.
|
||||
@@ -258,12 +336,29 @@ class NoteEditorViewModel(
|
||||
} else {
|
||||
viewModelScope.launch {
|
||||
repository.observeById(noteId).collect { note ->
|
||||
if (note != null && _state.value.isLoading) {
|
||||
val firstLoad = _state.value.isLoading
|
||||
if (note != null && firstLoad) {
|
||||
initialContent = note.content
|
||||
initialFavorite = note.isFavorite
|
||||
initialColor = note.color
|
||||
initialHashtags = note.hashtags
|
||||
initialType = note.type
|
||||
}
|
||||
// Draft echoes: emissions caused by our own autosave
|
||||
// must not clobber in-progress edits mid-typing —
|
||||
// the local state is authoritative while drafting.
|
||||
if (note != null && note.isDraft && !firstLoad) return@collect
|
||||
// Parse list rows once on first load; later DB
|
||||
// emissions must not clobber in-progress edits.
|
||||
val listSeed: Pair<String, List<ChecklistItem>>? =
|
||||
if (note != null && firstLoad && note.type != NoteType.TEXT) {
|
||||
Note.splitListContent(
|
||||
note.content,
|
||||
interpretCosts = note.type == NoteType.SHOPPING_LIST,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
existing = note,
|
||||
@@ -271,6 +366,9 @@ class NoteEditorViewModel(
|
||||
isFavorite = note?.isFavorite ?: it.isFavorite,
|
||||
color = note?.color ?: it.color,
|
||||
hashtags = note?.hashtags ?: it.hashtags,
|
||||
type = note?.type ?: it.type,
|
||||
listHeader = listSeed?.first ?: it.listHeader,
|
||||
items = listSeed?.second ?: it.items,
|
||||
isLoading = false,
|
||||
)
|
||||
}
|
||||
@@ -292,17 +390,18 @@ class NoteEditorViewModel(
|
||||
}
|
||||
|
||||
fun openAddTagSheet() {
|
||||
_state.update {
|
||||
it.copy(
|
||||
isAddingTag = true,
|
||||
tagInput = "",
|
||||
tagSuggestions = emptyList(),
|
||||
)
|
||||
}
|
||||
// v0.3.8.0 FIX: push the empty query through the suggestion
|
||||
// pipeline FIRST so the flatMapLatest collector re-emits every
|
||||
// existing tag (most-used first) while the sheet opens — the
|
||||
// old code just cleared the list to emptyList() here and the
|
||||
// stuck collector never refilled it.
|
||||
tagInputFlow.value = ""
|
||||
_state.update { it.copy(isAddingTag = true, tagInput = "") }
|
||||
}
|
||||
|
||||
fun closeAddTagSheet() {
|
||||
_state.update { it.copy(isAddingTag = false, tagInput = "", tagSuggestions = emptyList()) }
|
||||
tagInputFlow.value = ""
|
||||
_state.update { it.copy(isAddingTag = false, tagInput = "") }
|
||||
}
|
||||
|
||||
fun onTagInputChange(raw: String) {
|
||||
@@ -330,6 +429,169 @@ class NoteEditorViewModel(
|
||||
_state.update { it.copy(hashtags = it.hashtags.filterNot { tag -> tag == normalised }) }
|
||||
}
|
||||
|
||||
// ---- v0.3.8.0 task / shopping list editing ----
|
||||
|
||||
/**
|
||||
* Keep the [NoteEditorUiState.items] / [NoteEditorUiState.listHeader]
|
||||
* rows and the derived [NoteEditorUiState.content] in step, so the
|
||||
* save path, dirty-check, search preview, and `canSave` gate all
|
||||
* keep working off the single content string.
|
||||
*/
|
||||
private fun NoteEditorUiState.withListEdits(
|
||||
header: String = this.listHeader,
|
||||
items: List<ChecklistItem>,
|
||||
): NoteEditorUiState = copy(
|
||||
listHeader = header,
|
||||
items = items,
|
||||
content = Note.serializeListContent(header, items, type),
|
||||
)
|
||||
|
||||
private fun List<ChecklistItem>.patched(
|
||||
index: Int,
|
||||
transform: (ChecklistItem) -> ChecklistItem,
|
||||
): List<ChecklistItem> = mapIndexed { i, item ->
|
||||
if (i == index) transform(item) else item
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the body to [target]; tapping the already-active mode
|
||||
* converts back to [NoteType.TEXT]. Text moves losslessly between
|
||||
* the plain editor and the checkbox serialisation — costs are only
|
||||
* stored while the note is a shopping list (converting to a task
|
||||
* list folds each cost back into the item text).
|
||||
*/
|
||||
fun convertTo(target: NoteType) {
|
||||
_state.update { s ->
|
||||
val next = if (s.type == target) NoteType.TEXT else target
|
||||
if (next == NoteType.VOICE_NOTE) {
|
||||
// v0.4.2.0 — voice mode keeps the plain text field
|
||||
// (title = first line) exactly like TEXT; a list body
|
||||
// folds back to its plain form first. The recording is
|
||||
// NOT body content — it's an ordinary audio attachment,
|
||||
// so it also survives converting back to plain text.
|
||||
val source =
|
||||
if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) s.content
|
||||
else Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
|
||||
s.copy(
|
||||
type = next,
|
||||
listHeader = "",
|
||||
items = emptyList(),
|
||||
content = source,
|
||||
)
|
||||
} else if (next == NoteType.TEXT) {
|
||||
// Content already holds the serialised `- [ ]` rows;
|
||||
// just drop out of the structured editor (the inline
|
||||
// GFM checklist rendering from v0.2.0.0 still applies).
|
||||
s.copy(type = NoteType.TEXT, listHeader = "", items = emptyList())
|
||||
} else {
|
||||
val source = if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) {
|
||||
s.content
|
||||
} else {
|
||||
// Serialise through the FOLDED legacy form (plain
|
||||
// "Milk 2 x 3.90" lines, never `{q…p…}` markers) so
|
||||
// structured values survive the trip and re-parse
|
||||
// cleanly under the target mode's rules.
|
||||
Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
|
||||
}
|
||||
val (header, parsedRaw) = Note.splitListContent(
|
||||
source,
|
||||
interpretCosts = next == NoteType.SHOPPING_LIST,
|
||||
)
|
||||
val parsed = if (parsedRaw.isEmpty()) listOf(ChecklistItem("")) else parsedRaw
|
||||
s.copy(
|
||||
type = next,
|
||||
listHeader = header,
|
||||
items = parsed,
|
||||
content = Note.serializeListContent(header, parsed, next),
|
||||
)
|
||||
}
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
snackbar = when (it.type) {
|
||||
NoteType.TASK_LIST -> "Task list mode — first line stays the title."
|
||||
NoteType.SHOPPING_LIST -> "Shopping list mode — check an item once it's in your basket."
|
||||
NoteType.VOICE_NOTE -> "Voice note mode — record with the mic card above the text."
|
||||
else -> "Back to plain text."
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onHeaderChange(value: String) {
|
||||
_state.update { it.withListEdits(header = value, items = it.items) }
|
||||
}
|
||||
|
||||
fun addListItem() {
|
||||
_state.update { s ->
|
||||
if (s.type == NoteType.TEXT) return@update s
|
||||
s.withListEdits(items = s.items + ChecklistItem(""))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a blank row right after [index] (or append it on the last
|
||||
* row). Driven by Enter/Return in the task/product field so the
|
||||
* writer flows downward into a fresh row instead of tabbing sideways.
|
||||
*/
|
||||
fun addListItemAfter(index: Int) {
|
||||
_state.update { s ->
|
||||
if (s.type == NoteType.TEXT) return@update s
|
||||
if (index !in s.items.indices) return@update s
|
||||
val updated = s.items.toMutableList().also { it.add(index + 1, ChecklistItem("")) }
|
||||
s.withListEdits(items = updated)
|
||||
}
|
||||
}
|
||||
|
||||
fun removeListItem(index: Int) {
|
||||
_state.update { s ->
|
||||
if (index !in s.items.indices) return@update s
|
||||
s.withListEdits(items = s.items.filterIndexed { i, _ -> i != index })
|
||||
}
|
||||
}
|
||||
|
||||
fun setItemChecked(index: Int, checked: Boolean) {
|
||||
_state.update { s ->
|
||||
if (index !in s.items.indices) return@update s
|
||||
s.withListEdits(items = s.items.patched(index) { it.copy(checked = checked) })
|
||||
}
|
||||
}
|
||||
|
||||
fun setItemText(index: Int, text: String) {
|
||||
_state.update { s ->
|
||||
if (index !in s.items.indices) return@update s
|
||||
s.withListEdits(items = s.items.patched(index) { it.copy(text = text) })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Price field input — POS style: everything is reduced to cents
|
||||
* digits ("199" ⇒ $1.99, separators typed or pasted are stripped).
|
||||
*/
|
||||
fun setItemCost(index: Int, rawCost: String) {
|
||||
val sanitized = Note.normalisePriceInput(rawCost)
|
||||
_state.update { s ->
|
||||
if (index !in s.items.indices) return@update s
|
||||
s.withListEdits(items = s.items.patched(index) { it.copy(cost = sanitized) })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quantity line input (free-text digits); blank means the default 1.
|
||||
*
|
||||
* v0.3.8.0: "1" now stays stored as "1" — the field is free text, so
|
||||
* the typed digit must remain visible. The serialiser already omits
|
||||
* `{q1}` and cards only show "×qty" when the quantity is > 1, so this
|
||||
* is storage-neutral. "0" / blank normalise to "" (meaning 1).
|
||||
*/
|
||||
fun setItemQuantity(index: Int, rawQty: String) {
|
||||
val stored = Note.normaliseQuantity(rawQty)
|
||||
_state.update { s ->
|
||||
if (index !in s.items.indices) return@update s
|
||||
s.withListEdits(items = s.items.patched(index) { it.copy(quantity = stored) })
|
||||
}
|
||||
}
|
||||
|
||||
fun consumeSnackbar() {
|
||||
_state.update { it.copy(snackbar = null) }
|
||||
}
|
||||
@@ -351,7 +613,7 @@ class NoteEditorViewModel(
|
||||
val existingId = _state.value.existing?.id
|
||||
if (existingId != null && existingId > 0L) {
|
||||
// Persist straight to the DB; observeAttachments will surface it.
|
||||
withContext(Dispatchers.IO) {
|
||||
withContext(ioDispatcher) {
|
||||
repository.addAttachment(
|
||||
noteId = existingId,
|
||||
bytes = bytes,
|
||||
@@ -393,7 +655,47 @@ class NoteEditorViewModel(
|
||||
/** Delete a persisted attachment by id (used by the ✕ on the thumbnail strip). */
|
||||
fun deletePersistedAttachment(id: Long) {
|
||||
viewModelScope.launch {
|
||||
withContext(Dispatchers.IO) { repository.removeAttachment(id) }
|
||||
withContext(ioDispatcher) { repository.removeAttachment(id) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.4.2.0 — stage/persist the finished take of a voice note.
|
||||
* One take per note: any previous take (pending or already
|
||||
* persisted) is discarded first. The bytes then ride the ordinary
|
||||
* attachment pipeline — staged as a [PendingAttachment] while the
|
||||
* note is unsaved, written straight to the DB afterwards — so
|
||||
* encryption, backup/restore, and the trash cascade all apply
|
||||
* without any voice-specific storage.
|
||||
*
|
||||
* [mimeType] is the container the recorder actually produced —
|
||||
* `audio/ogg` (Opus, 32 kbps mono) on API 29+, `audio/mp4` (AAC)
|
||||
* on API 26–28; the display-name extension follows suit.
|
||||
*/
|
||||
fun setVoiceRecording(bytes: ByteArray, mimeType: String = "audio/ogg") {
|
||||
if (bytes.size < 2048) {
|
||||
_state.update { it.copy(snackbar = "Recording too short \u2014 try again.") }
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
_state.value.pendingAttachments
|
||||
.filter { it.mimeType.startsWith("audio/") }
|
||||
.forEach { removePendingAttachment(it.tempId) }
|
||||
val stalePersisted = _state.value.attachments
|
||||
.filter { it.mimeType.startsWith("audio/") }
|
||||
if (stalePersisted.isNotEmpty()) {
|
||||
withContext(ioDispatcher) {
|
||||
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",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -409,22 +711,81 @@ class NoteEditorViewModel(
|
||||
|
||||
// ---- save ----
|
||||
|
||||
/**
|
||||
* Force-write the current draft state to the DB right now — used
|
||||
* when the editor closes / disposes so pending edits never sit in
|
||||
* the debounce window. No-op for non-draft sessions and blank
|
||||
* content (see [persistDraftNow]).
|
||||
*/
|
||||
fun flushDraft() {
|
||||
viewModelScope.launch { persistDraftNow() }
|
||||
}
|
||||
|
||||
/** Write the draft row if this session is in the draft lifecycle. */
|
||||
private suspend fun persistDraftNow() {
|
||||
val current = _state.value
|
||||
if (current.isLoading || current.isSaving) return
|
||||
if (draftPersistInProgress) return
|
||||
val baseNote = current.existing
|
||||
if (baseNote != null && !baseNote.isDraft) return // already published
|
||||
if (!draftAutosave && baseNote?.isDraft != true) return
|
||||
if (current.content.isBlank()) return
|
||||
draftPersistInProgress = true
|
||||
try {
|
||||
val now = System.currentTimeMillis()
|
||||
val draft = baseNote?.copy(
|
||||
content = current.content,
|
||||
isFavorite = current.isFavorite,
|
||||
color = current.color,
|
||||
type = current.type,
|
||||
isDraft = true,
|
||||
) ?: Note(
|
||||
content = current.content,
|
||||
createdAt = now,
|
||||
updatedAt = now,
|
||||
isFavorite = current.isFavorite,
|
||||
color = current.color,
|
||||
type = current.type,
|
||||
isDraft = true,
|
||||
)
|
||||
val previous = baseNote?.hashtags.orEmpty().toSet()
|
||||
val currentSet = current.hashtags.toSet()
|
||||
val saved = repository.saveNoteWithHashtags(
|
||||
note = draft,
|
||||
hashtagsToAdd = currentSet - previous,
|
||||
hashtagsToRemove = previous - currentSet,
|
||||
)
|
||||
// Adopt the persisted row so every later write updates the
|
||||
// SAME note — one draft per editing session.
|
||||
_state.update {
|
||||
it.copy(existing = saved.copy(isDraft = true, hashtags = current.hashtags))
|
||||
}
|
||||
} finally {
|
||||
draftPersistInProgress = false
|
||||
}
|
||||
}
|
||||
|
||||
fun save(onDone: () -> Unit) {
|
||||
val current = _state.value
|
||||
if (!current.canSave) return
|
||||
_state.update { it.copy(isSaving = true) }
|
||||
viewModelScope.launch {
|
||||
val baseNote = current.existing
|
||||
// An explicit Save PUBLISHES the note: a draft row loses
|
||||
// its flag here and joins the normal views for good.
|
||||
val toPersist = baseNote?.copy(
|
||||
content = current.content,
|
||||
isFavorite = current.isFavorite,
|
||||
color = current.color,
|
||||
type = current.type,
|
||||
isDraft = false,
|
||||
) ?: Note(
|
||||
content = current.content,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
isFavorite = current.isFavorite,
|
||||
color = current.color,
|
||||
type = current.type,
|
||||
)
|
||||
val previous = baseNote?.hashtags.orEmpty().toSet()
|
||||
val currentSet = current.hashtags.toSet()
|
||||
@@ -437,7 +798,7 @@ class NoteEditorViewModel(
|
||||
current.pendingAttachments.forEach { pending ->
|
||||
val bytes = current.pendingAttachmentBytes[pending.tempId]
|
||||
if (bytes != null) {
|
||||
withContext(Dispatchers.IO) {
|
||||
withContext(ioDispatcher) {
|
||||
repository.addAttachment(
|
||||
noteId = saved.id,
|
||||
bytes = bytes,
|
||||
@@ -447,7 +808,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()
|
||||
}
|
||||
}
|
||||
@@ -456,14 +835,18 @@ class NoteEditorViewModel(
|
||||
val id = _state.value.existing?.id ?: return
|
||||
_state.update { it.copy(isSaving = true) }
|
||||
viewModelScope.launch {
|
||||
repository.delete(id)
|
||||
repository.softDelete(id)
|
||||
_state.update { it.copy(isSaving = false, isDeleted = true) }
|
||||
onDone()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Typing-pause before a draft autosave fires (ms). */
|
||||
const val DRAFT_AUTOSAVE_DEBOUNCE_MS = 400L
|
||||
|
||||
fun factory(
|
||||
graph: AppGraph,
|
||||
noteId: Long?,
|
||||
initialSharedText: String? = null,
|
||||
initialSharedImages: List<SharedImage> = emptyList(),
|
||||
@@ -475,9 +858,8 @@ class NoteEditorViewModel(
|
||||
initialSharedSubject: String? = null,
|
||||
): ViewModelProvider.Factory = viewModelFactory {
|
||||
initializer {
|
||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
||||
NoteEditorViewModel(
|
||||
repository = app.container.noteRepository,
|
||||
repository = graph.noteRepository,
|
||||
noteId = noteId,
|
||||
initialSharedText = initialSharedText,
|
||||
initialSharedImages = initialSharedImages,
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.incido.compose.ui.notelist
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
@@ -27,14 +26,20 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.CheckBox
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.DeleteForever
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material.icons.filled.Menu
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.PhotoCamera
|
||||
import androidx.compose.material.icons.filled.Restore
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.ShoppingBasket
|
||||
import androidx.compose.material.icons.filled.Star
|
||||
import androidx.compose.material.icons.outlined.StarOutline
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.CenterAlignedTopAppBar
|
||||
@@ -48,6 +53,7 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -57,21 +63,27 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import org.incido.compose.di.ioDispatcher
|
||||
import org.incido.compose.di.requireAppGraph
|
||||
import org.incido.compose.ui.theme.toComposeColor
|
||||
import org.incido.compose.util.decodeImageBytes
|
||||
import org.incido.compose.util.rememberRelativeTimestamp
|
||||
import org.incido.domain.model.Note
|
||||
import org.incido.domain.model.NoteAttachment
|
||||
import org.incido.domain.model.NoteColor
|
||||
import org.incido.domain.model.NoteFilter
|
||||
import org.incido.domain.model.NoteType
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
@@ -117,13 +129,53 @@ fun NoteListScreen(
|
||||
onOpenEditor: (Long?) -> Unit,
|
||||
/** v0.3.1.0 — used to fetch image bytes for card thumbnails. */
|
||||
repository: NoteRepository? = null,
|
||||
viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.Factory),
|
||||
viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.factory(requireAppGraph())),
|
||||
) {
|
||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
var localQuery by remember { mutableStateOf("") }
|
||||
var showEmptyTrashDialog by remember { mutableStateOf(false) }
|
||||
val searchFocusRequester = remember { FocusRequester() }
|
||||
|
||||
LaunchedEffect(filterMode) { viewModel.setFilter(filterMode) }
|
||||
|
||||
// Auto-focus the search field when it opens so typing can start
|
||||
// immediately.
|
||||
LaunchedEffect(state.isSearchActive) {
|
||||
if (state.isSearchActive) {
|
||||
runCatching { searchFocusRequester.requestFocus() }
|
||||
}
|
||||
}
|
||||
|
||||
// "Empty Trash" confirmation. The whole trash goes, attachments
|
||||
// included — say so plainly before the one tap that does it.
|
||||
if (showEmptyTrashDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showEmptyTrashDialog = false },
|
||||
title = { Text("Empty Trash?") },
|
||||
text = {
|
||||
Text(
|
||||
"Every note in the Trash, including attachments, will be " +
|
||||
"permanently deleted. This cannot be undone.",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
showEmptyTrashDialog = false
|
||||
viewModel.emptyTrash()
|
||||
},
|
||||
) {
|
||||
Text("Empty Trash", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showEmptyTrashDialog = false }) {
|
||||
Text("Cancel")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
CenterAlignedTopAppBar(
|
||||
@@ -135,7 +187,7 @@ fun NoteListScreen(
|
||||
},
|
||||
actions = {
|
||||
// v0.3.1.0: search is now context-aware on Home,
|
||||
// Favorites, and Untagged. ByTag filters already
|
||||
// Favorites, Untagged, and Trash. ByTag filters already
|
||||
// narrow by a single tag so the additional text
|
||||
// query would be ambiguous.
|
||||
if (filterMode !is NoteFilter.ByTag) {
|
||||
@@ -147,6 +199,17 @@ fun NoteListScreen(
|
||||
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",
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
@@ -166,12 +229,25 @@ fun NoteListScreen(
|
||||
localQuery = it
|
||||
viewModel.onQueryChange(it)
|
||||
},
|
||||
placeholder = { Text("Search notes…") },
|
||||
placeholder = {
|
||||
Text(if (filterMode == NoteFilter.Trash) "Search trash…" else "Search notes…")
|
||||
},
|
||||
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
|
||||
trailingIcon = {
|
||||
if (localQuery.isNotEmpty()) {
|
||||
IconButton(onClick = {
|
||||
localQuery = ""
|
||||
viewModel.onQueryChange("")
|
||||
}) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Clear search")
|
||||
}
|
||||
}
|
||||
},
|
||||
singleLine = true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
.focusRequester(searchFocusRequester),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -182,7 +258,15 @@ fun NoteListScreen(
|
||||
else -> NoteList(
|
||||
notes = state.notes,
|
||||
onClick = { onOpenEditor(it.id) },
|
||||
onDelete = viewModel::delete,
|
||||
onDelete = {
|
||||
if (filterMode == NoteFilter.Trash) {
|
||||
viewModel.permanentlyDelete(it)
|
||||
} else {
|
||||
viewModel.softDelete(it)
|
||||
}
|
||||
},
|
||||
onRestore = viewModel::restore,
|
||||
isTrash = filterMode == NoteFilter.Trash,
|
||||
onToggleFavorite = viewModel::toggleFavorite,
|
||||
repository = repository,
|
||||
// v0.3.5.0: ONLY notes whose ciphertext passed the
|
||||
@@ -198,7 +282,10 @@ private fun screenTitle(filter: NoteFilter): String = when (filter) {
|
||||
NoteFilter.Home -> "Incido"
|
||||
NoteFilter.Favorites -> "Favorites"
|
||||
NoteFilter.Untagged -> "Untagged"
|
||||
NoteFilter.Drafts -> "Drafts"
|
||||
NoteFilter.Trash -> "Trash"
|
||||
is NoteFilter.ByTag -> "#${filter.hashtag}"
|
||||
is NoteFilter.ByColor -> filter.color.label
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -207,7 +294,10 @@ private fun EmptyState(filterMode: NoteFilter) {
|
||||
NoteFilter.Home -> "No notes yet. Tap + to start."
|
||||
NoteFilter.Favorites -> "No favourites yet. Tap ⭐ on a card to add one."
|
||||
NoteFilter.Untagged -> "All notes are tagged. 🎉"
|
||||
NoteFilter.Drafts -> "No drafts yet. Start typing a new note and it lands here."
|
||||
NoteFilter.Trash -> "Trash is empty."
|
||||
is NoteFilter.ByTag -> "No notes tagged #${filterMode.hashtag} yet."
|
||||
is NoteFilter.ByColor -> "No " + filterMode.color.label.lowercase() + " notes yet. Pick a colour in the editor."
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
@@ -227,6 +317,9 @@ private fun EmptyState(filterMode: NoteFilter) {
|
||||
private fun NoResultsState(filterMode: NoteFilter) {
|
||||
val message = when (filterMode) {
|
||||
NoteFilter.Home -> "No matching notes."
|
||||
NoteFilter.Drafts -> "No drafts match your search."
|
||||
NoteFilter.Trash -> "No notes in Trash match your search."
|
||||
is NoteFilter.ByColor -> "No matching notes of this colour."
|
||||
else -> "Nothing here."
|
||||
}
|
||||
Box(
|
||||
@@ -248,6 +341,8 @@ private fun NoteList(
|
||||
notes: List<Note>,
|
||||
onClick: (Note) -> Unit,
|
||||
onDelete: (Long) -> Unit,
|
||||
onRestore: (Long) -> Unit,
|
||||
isTrash: Boolean,
|
||||
onToggleFavorite: (Long, Boolean) -> Unit,
|
||||
/** v0.3.1.0 — threaded through to [NoteCard] for thumbnail loading. */
|
||||
repository: NoteRepository?,
|
||||
@@ -271,8 +366,10 @@ private fun NoteList(
|
||||
items(items = notes, key = { it.id }) { note ->
|
||||
NoteCard(
|
||||
note = note,
|
||||
onClick = { onClick(note) },
|
||||
onClick = { if (!isTrash) onClick(note) },
|
||||
onDelete = { onDelete(note.id) },
|
||||
onRestore = { onRestore(note.id) },
|
||||
isTrash = isTrash,
|
||||
onToggleFavorite = { onToggleFavorite(note.id, !note.isFavorite) },
|
||||
repository = repository,
|
||||
showEncryptionBadge = note.id in verifiedEncryptedIds,
|
||||
@@ -293,10 +390,9 @@ private fun NoteList(
|
||||
*
|
||||
* v0.3.3.0:
|
||||
* - The bottom-right delete `IconButton` is gone.
|
||||
* - A long-press anywhere on the card opens a `DropdownMenu`
|
||||
* anchored on the card itself, with a "Delete" entry as the first
|
||||
* item. The menu is designed to grow (Share, etc.) — additional
|
||||
* entries are added as `DropdownMenuItem`s.
|
||||
* - A long-press anywhere on the card opens a `DropdownMenu` anchored on
|
||||
* the card itself. Active cards offer "Delete"; Trash cards offer
|
||||
* "Restore" and permanent "Delete" without opening the editor.
|
||||
* - Card now uses `Modifier.combinedClickable` for click + long-click.
|
||||
*
|
||||
* v0.3.3.5:
|
||||
@@ -330,6 +426,8 @@ private fun NoteCard(
|
||||
note: Note,
|
||||
onClick: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onRestore: () -> Unit,
|
||||
isTrash: Boolean,
|
||||
onToggleFavorite: () -> Unit,
|
||||
/** v0.3.1.0 — used to load the first image attachment as a
|
||||
* thumbnail background. Null disables the feature (still works). */
|
||||
@@ -346,7 +444,24 @@ private fun NoteCard(
|
||||
*/
|
||||
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 checklistSummary = Note.checklistSummary(note.content)
|
||||
val noteColor = note.color
|
||||
@@ -357,13 +472,13 @@ private fun NoteCard(
|
||||
// a downsampled bitmap for the card background. The produceState
|
||||
// scopes the work to the card's lifetime, so off-screen cards
|
||||
// don't keep their bitmaps alive.
|
||||
val thumbnailBitmap by produceState<android.graphics.Bitmap?>(initialValue = null, key1 = firstImage?.id) {
|
||||
val thumbnailBitmap by produceState<ImageBitmap?>(initialValue = null, key1 = firstImage?.id) {
|
||||
if (firstImage == null || repository == null) {
|
||||
value = null
|
||||
} else {
|
||||
value = withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
value = withContext(ioDispatcher) {
|
||||
val bytes = repository.getAttachmentBytes(firstImage.id) ?: return@withContext null
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
decodeImageBytes(bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -423,7 +538,7 @@ private fun NoteCard(
|
||||
// Card's opaque containerColor was drawn on top of them).
|
||||
if (thumbnailBitmap != null) {
|
||||
Image(
|
||||
bitmap = thumbnailBitmap!!.asImageBitmap(),
|
||||
bitmap = thumbnailBitmap!!,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.matchParentSize(),
|
||||
@@ -460,7 +575,7 @@ private fun NoteCard(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
text = displayTitle,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = titleColor,
|
||||
maxLines = 1,
|
||||
@@ -482,7 +597,11 @@ private fun NoteCard(
|
||||
Spacer(modifier = Modifier.padding(top = 4.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
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,
|
||||
modifier = Modifier.size(14.dp),
|
||||
tint = secondaryColor,
|
||||
@@ -495,6 +614,27 @@ private fun NoteCard(
|
||||
)
|
||||
}
|
||||
}
|
||||
if (note.type == NoteType.VOICE_NOTE) {
|
||||
// v0.4.2.0: voice notes carry a mic badge so the
|
||||
// kind is recognisable on the card even when the
|
||||
// body is empty (the take itself is an audio
|
||||
// attachment, not visible as a thumbnail).
|
||||
Spacer(modifier = Modifier.padding(top = 4.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Default.Mic,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(14.dp),
|
||||
tint = secondaryColor,
|
||||
)
|
||||
Spacer(Modifier.size(6.dp))
|
||||
Text(
|
||||
text = note.type.displayName,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = secondaryColor,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (note.hashtags.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.padding(top = 4.dp))
|
||||
HashtagRow(
|
||||
@@ -569,8 +709,23 @@ private fun NoteCard(
|
||||
expanded = showMenu,
|
||||
onDismissRequest = { showMenu = false },
|
||||
) {
|
||||
if (isTrash) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Restore") },
|
||||
leadingIcon = {
|
||||
Icon(
|
||||
Icons.Filled.Restore,
|
||||
contentDescription = null,
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
showMenu = false
|
||||
onRestore()
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = { Text("Delete") },
|
||||
text = { Text(if (isTrash) "Delete permanently" else "Delete") },
|
||||
leadingIcon = {
|
||||
Icon(
|
||||
Icons.Filled.Delete,
|
||||
@@ -599,14 +754,16 @@ private fun NoteCard(
|
||||
// Hotfix: favorite star moved from the title row to the
|
||||
// bottom-right corner, vertically aligned with the
|
||||
// three-dot overflow button above.
|
||||
Box(modifier = Modifier.align(Alignment.BottomEnd).padding(end = 4.dp, bottom = 4.dp)) {
|
||||
IconButton(onClick = onToggleFavorite) {
|
||||
Icon(
|
||||
imageVector = if (note.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
|
||||
contentDescription = if (note.isFavorite) "Unfavorite" else "Favorite",
|
||||
tint = if (note.isFavorite) favoriteActiveColor
|
||||
else secondaryColor,
|
||||
)
|
||||
if (!isTrash) {
|
||||
Box(modifier = Modifier.align(Alignment.BottomEnd).padding(end = 4.dp, bottom = 4.dp)) {
|
||||
IconButton(onClick = onToggleFavorite) {
|
||||
Icon(
|
||||
imageVector = if (note.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
|
||||
contentDescription = if (note.isFavorite) "Unfavorite" else "Favorite",
|
||||
tint = if (note.isFavorite) favoriteActiveColor
|
||||
else secondaryColor,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package org.incido.compose.ui.notelist
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.initializer
|
||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||
@@ -16,7 +15,8 @@ import kotlinx.coroutines.flow.debounce
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import org.incido.compose.IncidoApplication
|
||||
import org.incido.compose.di.AppGraph
|
||||
import org.incido.compose.di.EncryptionBadge
|
||||
import org.incido.domain.model.HashtagUsage
|
||||
import org.incido.domain.model.Note
|
||||
import org.incido.domain.model.NoteFilter
|
||||
@@ -42,15 +42,21 @@ data class NoteListUiState(
|
||||
/** Encrypted rows that FAILED verification (corrupted / wrong key). */
|
||||
val unverifiedEncryptedNoteCount: Int = 0,
|
||||
) {
|
||||
val isEmpty: Boolean get() = !isLoading && notes.isEmpty() && !isSearchActive && filter == NoteFilter.Home
|
||||
val isEmpty: Boolean
|
||||
get() = !isLoading && notes.isEmpty() && !isSearchActive &&
|
||||
(filter == NoteFilter.Home || filter == NoteFilter.Trash ||
|
||||
filter == NoteFilter.Drafts)
|
||||
val noResults: Boolean get() = !isLoading && notes.isEmpty() && !isEmpty
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
|
||||
class NoteListViewModel(
|
||||
private val repository: NoteRepository,
|
||||
/** v0.3.5.0 — source of the verified-encryption badge set. */
|
||||
private val encryptionVerifier: org.incido.compose.data.security.EncryptionVerifier? = null,
|
||||
/** v0.3.5.0 — source of the verified-encryption badge set.
|
||||
* M4.3c: the concrete `EncryptionVerifier` (androidLibrary sources)
|
||||
* becomes the commonMain [EncryptionBadge] face — same StateFlow
|
||||
* contents, mapped 1:1 by each container. */
|
||||
private val encryptionBadge: EncryptionBadge? = null,
|
||||
) : ViewModel() {
|
||||
|
||||
private val filterMode = MutableStateFlow<NoteFilter>(NoteFilter.Home)
|
||||
@@ -60,18 +66,22 @@ class NoteListViewModel(
|
||||
/** Notes stream — switches on (filter, query) so the same ViewModel
|
||||
* instance handles Home, Favorites, Untagged, ByTag, and search.
|
||||
*
|
||||
* v0.3.1.0: search is now **context-aware** — on Favorites or
|
||||
* Untagged, the typed query is intersected with the active filter
|
||||
* (only favourites / only untagged) rather than ignored. On Home,
|
||||
* search spans everything. ByTag keeps the same behaviour (the
|
||||
* tag itself is already the filter). */
|
||||
* v0.3.1.0: search is now **context-aware** — on Favorites,
|
||||
* Untagged, and Trash, the typed query is intersected with the
|
||||
* active filter rather than ignored. On Home, search spans all
|
||||
* active notes. ByTag keeps the same behaviour (the tag itself is
|
||||
* already the filter). */
|
||||
private val notesFlow = combine(filterMode, rawQuery) { f, q -> f to q }
|
||||
.flatMapLatest { (f, q) ->
|
||||
when (f) {
|
||||
NoteFilter.Home -> if (q.isBlank()) repository.observeAll() else repository.search(q)
|
||||
NoteFilter.Favorites -> if (q.isBlank()) repository.observeFavorites() else repository.searchFavorites(q)
|
||||
NoteFilter.Untagged -> if (q.isBlank()) repository.observeUntagged() else repository.searchUntagged(q)
|
||||
NoteFilter.Drafts -> if (q.isBlank()) repository.observeDrafts() else repository.searchDrafts(q)
|
||||
NoteFilter.Trash -> if (q.isBlank()) repository.observeTrashed() else repository.searchTrashed(q)
|
||||
is NoteFilter.ByTag -> repository.observeNotesForHashtag(f.hashtag)
|
||||
is NoteFilter.ByColor ->
|
||||
if (q.isBlank()) repository.observeByColor(f.color) else repository.searchByColor(q, f.color)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +115,7 @@ class NoteListViewModel(
|
||||
*/
|
||||
val uiState: StateFlow<NoteListUiState> = combine(
|
||||
baseUiState,
|
||||
encryptionVerifier?.verification
|
||||
encryptionBadge?.verification
|
||||
?: kotlinx.coroutines.flow.flowOf(null),
|
||||
) { state, verification ->
|
||||
state.copy(
|
||||
@@ -143,21 +153,36 @@ class NoteListViewModel(
|
||||
rawQuery.value = ""
|
||||
}
|
||||
|
||||
fun delete(id: Long) {
|
||||
/** Move an active note to Trash. */
|
||||
fun softDelete(id: Long) {
|
||||
viewModelScope.launch { repository.softDelete(id) }
|
||||
}
|
||||
|
||||
/** Permanently destroy a note from the Trash view. */
|
||||
fun permanentlyDelete(id: Long) {
|
||||
viewModelScope.launch { repository.delete(id) }
|
||||
}
|
||||
|
||||
/** "Empty Trash": permanently destroy every note in the Trash. */
|
||||
fun emptyTrash() {
|
||||
viewModelScope.launch { repository.deleteAllTrashed() }
|
||||
}
|
||||
|
||||
/** Restore a note from Trash. */
|
||||
fun restore(id: Long) {
|
||||
viewModelScope.launch { repository.restore(id) }
|
||||
}
|
||||
|
||||
fun toggleFavorite(id: Long, isFavorite: Boolean) {
|
||||
viewModelScope.launch { repository.setFavorite(id, isFavorite) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
val Factory: ViewModelProvider.Factory = viewModelFactory {
|
||||
fun factory(graph: AppGraph): ViewModelProvider.Factory = viewModelFactory {
|
||||
initializer {
|
||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
||||
NoteListViewModel(
|
||||
repository = app.container.noteRepository,
|
||||
encryptionVerifier = app.container.encryptionVerifier,
|
||||
repository = graph.noteRepository,
|
||||
encryptionBadge = graph.encryptionBadge,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
package org.incido.compose.ui.settings
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
@@ -27,7 +24,9 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.ClipboardManager
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
@@ -61,13 +60,23 @@ import org.incido.compose.data.settings.PasswordPolicy
|
||||
* truth for "is this passphrase correct", surfaced as
|
||||
* "Incorrect passphrase." via snackbar on mismatch.
|
||||
*/
|
||||
@Suppress("DEPRECATION") // LocalClipboardManager: see body comment — 1.8 API swap
|
||||
@Composable
|
||||
fun PassphraseDialog(
|
||||
onConfirm: (CharArray) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
mode: PassphraseDialogMode = PassphraseDialogMode.EXPORT,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
// M4.4a clipboard migration: the §6.3 note (`LocalClipboardManager` →
|
||||
// `LocalClipboard` + `ClipEntry`) describes the Compose UI **1.8** API —
|
||||
// on this stack (1.7.3) `ClipEntry` has no public constructor and
|
||||
// `LocalClipboard` does not exist yet (paid for while compiling).
|
||||
// LocalClipboardManager is the SAME API on both targets in 1.7.x — the
|
||||
// Android side keeps its ClipboardManager write verbatim by delegation,
|
||||
// desktop goes through AWT (the spike's Q5 clipboard PASS used exactly
|
||||
// this). Re-swap to LocalClipboard + ClipEntry when the stack moves to
|
||||
// Compose 1.8 (recorded for M5+).
|
||||
val clipboard: ClipboardManager = LocalClipboardManager.current
|
||||
// v0.3.6.0: use the enum helper so RECOVERY_EXPORT shares the
|
||||
// EXPORT chrome (policy check, Generate/Copy, Confirm field).
|
||||
val isExport = mode.isExport
|
||||
@@ -178,8 +187,10 @@ fun PassphraseDialog(
|
||||
Icon(Icons.Filled.Refresh, contentDescription = "Generate")
|
||||
}
|
||||
IconButton(onClick = {
|
||||
copyToClipboard(context, passphrase)
|
||||
copied = true
|
||||
if (passphrase.isNotEmpty()) {
|
||||
clipboard.setText(AnnotatedString(passphrase))
|
||||
copied = true
|
||||
}
|
||||
}) {
|
||||
Icon(Icons.Filled.ContentCopy, contentDescription = "Copy")
|
||||
}
|
||||
@@ -269,10 +280,4 @@ enum class PassphraseDialogMode {
|
||||
* password-policy check). Import variants skip those because
|
||||
* an existing passphrase may predate the current policy. */
|
||||
val isExport: Boolean get() = this == EXPORT || this == RECOVERY_EXPORT
|
||||
}
|
||||
|
||||
private fun copyToClipboard(context: Context, value: String) {
|
||||
if (value.isEmpty()) return
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("Incido backup passphrase", value))
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package org.incido.compose.ui.settings
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.incido.compose.data.settings.ThemeMode
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M4.4d — the platform-neutral settings sections, lifted verbatim from
|
||||
// SettingsScreen.kt (which keeps the Android-only Security section, the
|
||||
// SAF wiring, and the screen chrome). The desktop settings screen (M4.5)
|
||||
// composes exactly these three.
|
||||
//
|
||||
// Two callbacks became nullable so a platform can HIDE a row it cannot
|
||||
// serve (dynamic color is Android-12 Material You; the Carnet importer is
|
||||
// Android-side) — Android passes non-null everywhere, so its rendering
|
||||
// is pixel-identical to pre-M4.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
fun AppearanceSection(
|
||||
themeMode: ThemeMode,
|
||||
dynamicColor: Boolean,
|
||||
onThemeMode: (ThemeMode) -> Unit,
|
||||
/** Null hides the Dynamic-color row (desktop has no Material You). */
|
||||
onDynamicColor: ((Boolean) -> Unit)?,
|
||||
) {
|
||||
SettingsSection(title = "Appearance") {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Text("Theme", style = MaterialTheme.typography.labelLarge)
|
||||
Spacer(Modifier.padding(top = 6.dp))
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
ThemeMode.values().forEachIndexed { index, mode ->
|
||||
SegmentedButton(
|
||||
selected = themeMode == mode,
|
||||
onClick = { onThemeMode(mode) },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = ThemeMode.values().size,
|
||||
),
|
||||
label = {
|
||||
Text(when (mode) {
|
||||
ThemeMode.SYSTEM -> "System"
|
||||
ThemeMode.LIGHT -> "Light"
|
||||
ThemeMode.DARK -> "Dark"
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (onDynamicColor != null) {
|
||||
Spacer(Modifier.padding(top = 12.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("Dynamic color", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
"Use the system Material You palette on Android 12+.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(checked = dynamicColor, onCheckedChange = onDynamicColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun BackupSection(
|
||||
onExport: () -> Unit,
|
||||
onImport: () -> Unit,
|
||||
/** Null hides the Carnet row — its importer lives in androidMain. */
|
||||
onImportCarnet: (() -> Unit)?,
|
||||
) {
|
||||
SettingsSection(title = "Backup & Restore") {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
"Export your notes to a JSON file (with optional passphrase " +
|
||||
"encryption) or import a backup. Imports are additive — " +
|
||||
"they don't replace your existing notes.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(onClick = onExport, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Export to file…")
|
||||
}
|
||||
OutlinedButton(onClick = onImport, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Import from file…")
|
||||
}
|
||||
if (onImportCarnet != null) {
|
||||
OutlinedButton(onClick = onImportCarnet, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Import 3rd Party Notes")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AboutSection(
|
||||
version: String,
|
||||
onVersionClick: () -> Unit,
|
||||
) {
|
||||
SettingsSection(title = "About") {
|
||||
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onVersionClick)
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("Incido", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
text = "Version $version",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = "Tap for release notes",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Building blocks — M4.4d: shared vocabulary for SettingsScreen
|
||||
// (androidMain) and DesktopSettingsScreen. M4.5 note: public, not
|
||||
// internal — desktopApp is a separate Gradle module.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
fun SettingsSection(title: String, content: @Composable () -> Unit) {
|
||||
Column {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(start = 4.dp, top = 8.dp, bottom = 4.dp),
|
||||
)
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** v0.3.3.0: optionally renders a disabled (greyed) switch — used for
|
||||
* the mutually-exclusive PIN / Biometric toggles. */
|
||||
@Composable
|
||||
fun SettingsToggle(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
val color = if (enabled) {
|
||||
MaterialTheme.colorScheme.onSurface
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
val subColor = if (enabled) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium, color = color)
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = subColor,
|
||||
)
|
||||
}
|
||||
Switch(checked = checked, onCheckedChange = onCheckedChange, enabled = enabled)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SettingsRow(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,23 @@
|
||||
package org.incido.compose.ui.theme
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ColorScheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
/**
|
||||
* Phase 1 (M4.1) platform seam for Material You dynamic color.
|
||||
*
|
||||
* Android returns a real scheme on API 31+ (the pre-M4 behaviour, kept
|
||||
* verbatim in `androidMain`); every other platform returns null and the
|
||||
* brand palette below applies. Desktop deliberately has no dynamic
|
||||
* colour — same decision as M3 ("desktop hides the four Android-only
|
||||
* security/appearance features").
|
||||
*/
|
||||
@Composable
|
||||
expect fun platformDynamicColorScheme(darkTheme: Boolean): ColorScheme?
|
||||
|
||||
private val DarkColorScheme = darkColorScheme(
|
||||
primary = Purple80,
|
||||
@@ -34,11 +43,8 @@ fun IncidoTheme(
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val colorScheme = when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val context = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(context)
|
||||
else dynamicLightColorScheme(context)
|
||||
}
|
||||
dynamicColor -> platformDynamicColorScheme(darkTheme)
|
||||
?: if (darkTheme) DarkColorScheme else LightColorScheme
|
||||
darkTheme -> DarkColorScheme
|
||||
else -> LightColorScheme
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
|
||||
/**
|
||||
* Phase 1 (M4.4b) — the §6.3 image-decode seam.
|
||||
*
|
||||
* The single decode call the UI layer needs (attachment thumbnails +
|
||||
* the full-screen viewer). Android actual = the verbatim
|
||||
* `BitmapFactory.decodeByteArray` (+ `asImageBitmap`); JVM actual =
|
||||
* `org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap()`
|
||||
* — both wrapped so undecodable bytes return null, which is how the
|
||||
* pre-M4 screens already treat a failed `BitmapFactory` decode.
|
||||
*/
|
||||
expect fun decodeImageBytes(bytes: ByteArray): ImageBitmap?
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
/**
|
||||
* Phase 1 (M4.4c) — platform back-press seam (was a private one-liner
|
||||
* wrapper around `activity-compose` inside the editor file).
|
||||
*
|
||||
* Android actual = `androidx.activity.compose.BackHandler`, verbatim
|
||||
* behaviour. The JVM actual (M5.1) registers into the desktop window's
|
||||
* [PlatformBackStack], which the window drains on Esc — so the editor's
|
||||
* discard-prompt chain works on both platforms through this one seam.
|
||||
*/
|
||||
@Composable
|
||||
expect fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit)
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
|
||||
/**
|
||||
* Returns a localised "X ago" style timestamp for the given epoch millis.
|
||||
*
|
||||
* Phase 1 (M4.1) platform seam: Android formats via
|
||||
* [android.text.format.DateUtils.getRelativeTimeSpanString] (verbatim
|
||||
* pre-M4 behaviour, kept in `androidMain`); the JVM target formats with
|
||||
* `java.time` (see `RelativeTime.jvm.kt`).
|
||||
*/
|
||||
@Composable
|
||||
fun rememberRelativeTimestamp(epochMillis: Long): String {
|
||||
val now = remember { System.currentTimeMillis() }
|
||||
return remember(epochMillis) { relativeTimestamp(epochMillis, now) }
|
||||
}
|
||||
|
||||
/** Formats [epochMillis] relative to [nowMillis] — "23 min. ago" /
|
||||
* "Today" / "Yesterday" / "3 days ago" / absolute date beyond that. */
|
||||
expect fun relativeTimestamp(epochMillis: Long, nowMillis: Long): String
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* M4.4a seam for [PassphraseGenerator] — identical two-liner actual on
|
||||
* both targets (both targets ARE the JVM; commonMain just cannot spell
|
||||
* `java.security`). Behaviour (CSPRNG backing, draw distribution) is
|
||||
* exactly the pre-M4 `SecureRandom()` field it replaces.
|
||||
*/
|
||||
|
||||
private val secureRandom = SecureRandom()
|
||||
|
||||
internal actual fun secureRandomInt(bound: Int): Int = secureRandom.nextInt(bound)
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.incido.compose.di
|
||||
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
|
||||
internal actual val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
|
||||
@@ -0,0 +1,126 @@
|
||||
package org.incido.compose.ui.editor
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Modifier
|
||||
import java.awt.Desktop
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.domain.model.NoteAttachment
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* M4.4c JVM actual — desktop file intake per §6.3: AWT `FileDialog`
|
||||
* (the native GTK dialog M2's Import/Export menu already proved out)
|
||||
* instead of SAF, "open with" via `java.awt.Desktop` (falling back to
|
||||
* `xdg-open`), and camera/voice HIDDEN (§6.5 — the editor asks
|
||||
* `supportsCamera`/`supportsVoice` and does not render those buttons).
|
||||
*/
|
||||
@Composable
|
||||
actual fun rememberEditorIntake(
|
||||
onPickedBytes: suspend (bytes: ByteArray, mimeType: String, displayName: String) -> Unit,
|
||||
onVoiceConvert: () -> Unit,
|
||||
isVoiceMode: Boolean,
|
||||
beginExternalActivity: (() -> Unit)?,
|
||||
): EditorIntake {
|
||||
val scope = rememberCoroutineScope()
|
||||
return remember(scope) {
|
||||
object : EditorIntake {
|
||||
override val supportsCamera = false
|
||||
override val supportsVoice = false
|
||||
|
||||
override fun takePhoto() = Unit // hidden: supportsCamera is false
|
||||
|
||||
override fun pickFiles() {
|
||||
scope.launch {
|
||||
val picked = withContext(Dispatchers.IO) {
|
||||
val dialog = java.awt.FileDialog(null as java.awt.Frame?, "Attach file").apply {
|
||||
mode = java.awt.FileDialog.LOAD
|
||||
file = null // start with no preselected name
|
||||
}
|
||||
dialog.show()
|
||||
val dir = dialog.directory ?: return@withContext null
|
||||
val name = dialog.file ?: return@withContext null
|
||||
val file = File(dir, name)
|
||||
runCatching { file.readBytes() }.getOrNull()
|
||||
?.let { it to file.name }
|
||||
}
|
||||
val (bytes, name) = picked ?: return@launch
|
||||
onPickedBytes(bytes, guessMimeType(name), name)
|
||||
}
|
||||
}
|
||||
|
||||
override fun toggleVoiceMode() = Unit // hidden: supportsVoice is false
|
||||
|
||||
override fun checkMicPermission(): Boolean = false
|
||||
|
||||
override fun requestMicPermission() = Unit
|
||||
|
||||
override fun notify(msg: String) {
|
||||
// No Toast surface on desktop; the lazy-load "Loading…"
|
||||
// nudge is a no-op (the thumbnail resolves in ms locally).
|
||||
}
|
||||
|
||||
override fun openExternal(bytes: ByteArray, mimeType: String, displayName: String) {
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val safeName = displayName.replace(Regex("[^A-Za-z0-9._-]"), "_")
|
||||
val outbox = File(System.getProperty("java.io.tmpdir"), "incido-open-outbox")
|
||||
.apply { mkdirs() }
|
||||
val tmp = File(outbox, "open_${'$'}{System.currentTimeMillis()}_$safeName")
|
||||
tmp.writeBytes(bytes)
|
||||
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
|
||||
Desktop.getDesktop().open(tmp)
|
||||
} else {
|
||||
ProcessBuilder("xdg-open", tmp.absolutePath).start()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Best-effort mime guess from the extension (the mime only labels the
|
||||
* attachment row; the desktop open path dispatches on the file). */
|
||||
private fun guessMimeType(name: String): String = when (name.substringAfterLast('.', "").lowercase()) {
|
||||
"png" -> "image/png"
|
||||
"jpg", "jpeg" -> "image/jpeg"
|
||||
"gif" -> "image/gif"
|
||||
"webp" -> "image/webp"
|
||||
"svg" -> "image/svg+xml"
|
||||
"txt", "md" -> "text/plain"
|
||||
"pdf" -> "application/pdf"
|
||||
"ogg", "oga" -> "audio/ogg"
|
||||
"opus" -> "audio/opus"
|
||||
"mp3" -> "audio/mpeg"
|
||||
"m4a" -> "audio/mp4"
|
||||
"wav" -> "audio/wav"
|
||||
"zip" -> "application/zip"
|
||||
else -> "application/octet-stream"
|
||||
}
|
||||
|
||||
/**
|
||||
* M4.4c JVM actual: the voice recorder card renders NOTHING (§6.5
|
||||
* hide-don't-stub). Audio imported from a phone survives as a plain
|
||||
* attachment row; there is simply no desktop recorder UI.
|
||||
*/
|
||||
@Composable
|
||||
actual fun VoiceNoteSlot(
|
||||
voicePending: PendingAttachment?,
|
||||
voicePendingBytes: ByteArray?,
|
||||
voicePersisted: NoteAttachment?,
|
||||
repository: NoteRepository?,
|
||||
hasMicPermission: () -> Boolean,
|
||||
onRequestPermission: () -> Unit,
|
||||
onTakeRecorded: (ByteArray, String) -> Unit,
|
||||
onDeleteTake: () -> Unit,
|
||||
beginExternalActivity: (() -> Unit)?,
|
||||
modifier: Modifier,
|
||||
) = Unit
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.incido.compose.ui.theme
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.material3.ColorScheme
|
||||
|
||||
/** JVM actual — desktop has no Material You (hidden, not faked; same
|
||||
* posture as M3's four hidden Android-only features). Always null, so
|
||||
* [IncidoTheme] falls through to the brand palette. */
|
||||
@Composable
|
||||
actual fun platformDynamicColorScheme(darkTheme: Boolean): ColorScheme? = null
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.toComposeImageBitmap
|
||||
import org.jetbrains.skia.Image
|
||||
|
||||
/**
|
||||
* M4.4b JVM actual — the §6.3 recipe:
|
||||
* `Image.makeFromEncoded(bytes).toComposeImageBitmap()`. skia THROWS on
|
||||
* undecodable bytes where BitmapFactory returns null, so the
|
||||
* runCatching keeps the seam's null-on-failure contract (empty/partial
|
||||
* attachment bytes must show the placeholder, not crash the strip).
|
||||
*/
|
||||
actual fun decodeImageBytes(bytes: ByteArray): ImageBitmap? =
|
||||
runCatching { Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.remember
|
||||
|
||||
/**
|
||||
* M5.1 — the M4.4c no-op made real: a desktop back stack.
|
||||
*
|
||||
* A desktop window has no system back gesture, so the desktop window
|
||||
* translates Esc (`Window(onPreviewKeyEvent)`) into [dispatchBack] on the
|
||||
* [PlatformBackStack] provided through [LocalPlatformBackStack]. Every live
|
||||
* `PlatformBackHandler` becomes an entry here, so the editor's existing
|
||||
* tryClose/discard-prompt chain behaves exactly like Android's BackHandler
|
||||
* stack: the topmost enabled entry wins.
|
||||
*
|
||||
* Entries keep their stack position across recompositions: the registration
|
||||
* object is remembered and its callback slot refreshed per composition.
|
||||
* Re-registering on every `onBack` lambda change would let a lower handler's
|
||||
* recomposition jump above an editor or dialog stacked on top of it.
|
||||
*/
|
||||
class PlatformBackStack {
|
||||
internal class Entry(var enabled: Boolean = false, var onBack: () -> Unit = {})
|
||||
|
||||
private val entries = ArrayDeque<Entry>()
|
||||
|
||||
internal fun push(entry: Entry) {
|
||||
entries.addLast(entry)
|
||||
}
|
||||
|
||||
internal fun remove(entry: Entry) {
|
||||
entries.remove(entry)
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the topmost enabled handler. Returns true when consumed — the
|
||||
* window uses that to decide whether Esc falls through to content.
|
||||
*/
|
||||
fun dispatchBack(): Boolean {
|
||||
val top = entries.lastOrNull { it.enabled } ?: return false
|
||||
top.onBack()
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** Provided by the desktop host window (see `:desktopApp` Main.kt, M5.1). */
|
||||
val LocalPlatformBackStack = compositionLocalOf<PlatformBackStack?> { null }
|
||||
|
||||
/**
|
||||
* M4.4c/M5.1 JVM actual — registers into [LocalPlatformBackStack]. No-op
|
||||
* when the host provides no stack (headless tests, embeds).
|
||||
*/
|
||||
@Composable
|
||||
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
|
||||
val stack = LocalPlatformBackStack.current
|
||||
val entry = remember { PlatformBackStack.Entry() }
|
||||
entry.enabled = enabled
|
||||
entry.onBack = onBack
|
||||
if (stack != null) {
|
||||
DisposableEffect(stack) {
|
||||
stack.push(entry)
|
||||
onDispose { stack.remove(entry) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
/**
|
||||
* JVM actual — a `java.time` port of the Android `DateUtils` abbreviated
|
||||
* relative format ("23 min. ago" / "Today" / "Yesterday" / "3 days
|
||||
* ago" / absolute date beyond a week).
|
||||
*
|
||||
* English-only for now (desktop has no UI locale switch yet); matching
|
||||
* Android's localisation exactly is M4 follow-up work — the Android
|
||||
* actual above remains the reference behaviour.
|
||||
*/
|
||||
actual fun relativeTimestamp(epochMillis: Long, nowMillis: Long): String {
|
||||
val zone = ZoneId.systemDefault()
|
||||
val then = Instant.ofEpochMilli(epochMillis).atZone(zone).toLocalDate()
|
||||
val now = Instant.ofEpochMilli(nowMillis).atZone(zone).toLocalDate()
|
||||
val days = ChronoUnit.DAYS.between(then, now)
|
||||
val deltaMillis = nowMillis - epochMillis
|
||||
|
||||
// Same-day (and future / sub-minute) timestamps: relative clock time.
|
||||
if (days <= 0L) {
|
||||
if (deltaMillis < 60_000L) return "Just now"
|
||||
val minutes = deltaMillis / 60_000L
|
||||
if (minutes < 60L) return "$minutes min. ago"
|
||||
val hours = minutes / 60L
|
||||
return if (hours < 24L) "$hours hr. ago" else "Today"
|
||||
}
|
||||
if (days == 1L) return "Yesterday"
|
||||
if (days < 7L) return "$days days ago"
|
||||
|
||||
// Beyond a week: absolute date, year shown only when it differs —
|
||||
// DateUtils' "Oct 5" / "Oct 5, 2025" shape.
|
||||
val pattern = if (then.year == now.year) "MMM d" else "MMM d, yyyy"
|
||||
return then.format(DateTimeFormatter.ofPattern(pattern))
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
package org.incido.compose
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.DrawerValue
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ModalNavigationDrawer
|
||||
import androidx.compose.material3.rememberDrawerState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshots.SnapshotStateList
|
||||
import androidx.compose.runtime.toMutableStateList
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavType
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import androidx.navigation.navArgument
|
||||
import kotlinx.coroutines.launch
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.compose.data.settings.SettingsRepository
|
||||
import org.incido.compose.share.SharedIntentBuffer
|
||||
import org.incido.compose.ui.drawer.IncidoDrawer
|
||||
import org.incido.compose.ui.editor.NoteEditorScreen
|
||||
import org.incido.compose.ui.editor.SharedImage
|
||||
import org.incido.compose.ui.notelist.NoteListScreen
|
||||
import org.incido.compose.ui.settings.SettingsScreen
|
||||
import org.incido.compose.ui.settings.auth.PinChangeScreen
|
||||
import org.incido.compose.ui.settings.auth.PinEntryScreen
|
||||
import org.incido.compose.ui.settings.auth.PinSetupScreen
|
||||
import org.incido.compose.ui.theme.IncidoTheme
|
||||
import org.incido.domain.model.NoteFilter
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/** Top-level navigation destinations. */
|
||||
private object Routes {
|
||||
const val LIST = "list"
|
||||
const val EDITOR = "editor/{noteId}"
|
||||
const val SETTINGS = "settings"
|
||||
const val PIN_SETUP = "pin_setup"
|
||||
/** v0.3.3.0: three-step "Reset PIN" flow. */
|
||||
const val PIN_CHANGE = "pin_change"
|
||||
fun editor(noteId: Long?): String = "editor/${noteId ?: -1L}"
|
||||
}
|
||||
|
||||
/** Stable serialisation for [NoteFilter] so `rememberSaveable` works. */
|
||||
private fun NoteFilter.toSaveableKey(): String = key()
|
||||
|
||||
private fun String.toNoteFilter(): NoteFilter = when {
|
||||
this == "home" -> NoteFilter.Home
|
||||
this == "favorites" -> NoteFilter.Favorites
|
||||
this == "untagged" -> NoteFilter.Untagged
|
||||
startsWith("tag:") -> NoteFilter.ByTag(this.removePrefix("tag:"))
|
||||
else -> NoteFilter.Home
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.1.0: Holds the share-into payload (text + pre-loaded image
|
||||
* bytes) so the [NoteEditorScreen] can read it on first composition.
|
||||
* Cleared as soon as the editor is created.
|
||||
*
|
||||
* v0.3.6.0: also carries [subject] (`Intent.EXTRA_SUBJECT`) so the
|
||||
* editor can put the page title on the note's first line for URL
|
||||
* shares — still offline-only, no network fetch.
|
||||
*/
|
||||
private class ShareIntoHolder {
|
||||
var text: String? = null
|
||||
var images: List<SharedImage> = emptyList()
|
||||
var subject: String? = null
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun IncidoApp(
|
||||
repository: NoteRepository? = null,
|
||||
securityManager: SecurityManager? = null,
|
||||
settingsRepository: SettingsRepository? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val app = context.applicationContext as IncidoApplication
|
||||
// v0.3.2.0: prefer explicit params, fall back to the application
|
||||
// container. Both hosts (`MainActivity` + tests) supply them in
|
||||
// production — the fallback is just a robustness net.
|
||||
val resolvedSecurity = securityManager ?: app.container.securityManager
|
||||
val resolvedSettings = settingsRepository ?: app.container.settingsRepository
|
||||
|
||||
// v0.3.2.0: collect user settings to drive theme + the auth gate.
|
||||
val settings by resolvedSettings.userSettingsFlow.collectAsStateWithLifecycle(
|
||||
initialValue = org.incido.compose.data.settings.UserSettings(),
|
||||
)
|
||||
val lockState by resolvedSecurity.lockState.collectAsStateWithLifecycle()
|
||||
|
||||
IncidoTheme(
|
||||
darkTheme = settings.themeMode.resolveDark(isSystemInDarkTheme()),
|
||||
dynamicColor = settings.dynamicColor,
|
||||
) {
|
||||
// v0.3.2.0: hard lock gate. If the app is locked we render
|
||||
// the PIN entry screen in place of the regular UI.
|
||||
if (lockState is SecurityManager.LockState.Locked) {
|
||||
PinEntryScreen()
|
||||
return@IncidoTheme
|
||||
}
|
||||
|
||||
val navController = rememberNavController()
|
||||
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
|
||||
val scope = rememberCoroutineScope()
|
||||
var filterMode by rememberSaveable(
|
||||
stateSaver = androidx.compose.runtime.saveable.Saver(
|
||||
save = { it.toSaveableKey() },
|
||||
restore = { it.toNoteFilter() },
|
||||
),
|
||||
) { mutableStateOf<NoteFilter>(NoteFilter.Home) }
|
||||
|
||||
// v0.3.1.0: consume any inbound share-into payload once at
|
||||
// composition. The buffer is single-shot — first composition
|
||||
// wins. If a payload is present, we open a fresh editor with
|
||||
// the shared content pre-filled.
|
||||
val shareHolder = remember { ShareIntoHolder() }
|
||||
LaunchedEffect(Unit) {
|
||||
val payload = SharedIntentBuffer.consume()
|
||||
if (payload != null && !payload.isEmpty) {
|
||||
shareHolder.text = payload.text
|
||||
shareHolder.images = payload.images
|
||||
shareHolder.subject = payload.subject
|
||||
navController.navigate(Routes.editor(null)) {
|
||||
popUpTo(Routes.LIST)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val currentBackStack by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = currentBackStack?.destination?.route?.substringBefore("/")
|
||||
// Disable the drawer on the editor so back arrow / gesture do
|
||||
// exactly what the user expects there.
|
||||
val isListRoute = currentRoute == Routes.LIST
|
||||
|
||||
LaunchedEffect(currentRoute) {
|
||||
// If we land on the editor via deep link without a list in
|
||||
// the back stack, snap the drawer closed.
|
||||
if (!isListRoute && drawerState.isOpen) drawerState.close()
|
||||
}
|
||||
|
||||
// v0.3.2.0: forward app foreground/background transitions to
|
||||
// the SecurityManager so it can re-lock when the timeout
|
||||
// elapses. LifecycleEventObserver wires ON_RESUME / ON_STOP
|
||||
// automatically.
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
when (event) {
|
||||
Lifecycle.Event.ON_RESUME -> resolvedSecurity.onAppForegrounded()
|
||||
Lifecycle.Event.ON_STOP -> resolvedSecurity.onAppBackgrounded()
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
|
||||
ModalNavigationDrawer(
|
||||
drawerState = drawerState,
|
||||
gesturesEnabled = isListRoute,
|
||||
drawerContent = {
|
||||
IncidoDrawer(
|
||||
currentFilter = filterMode,
|
||||
onSelectFilter = { picked ->
|
||||
filterMode = picked
|
||||
scope.launch { drawerState.close() }
|
||||
},
|
||||
onOpenSettings = {
|
||||
scope.launch { drawerState.close() }
|
||||
navController.navigate(Routes.SETTINGS)
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
NavHost(navController = navController, startDestination = Routes.LIST) {
|
||||
composable(Routes.LIST) {
|
||||
NoteListScreen(
|
||||
filterMode = filterMode,
|
||||
onOpenDrawer = { scope.launch { drawerState.open() } },
|
||||
onOpenEditor = { id -> navController.navigate(Routes.editor(id)) },
|
||||
// v0.3.1.0: thread the NoteRepository through so the
|
||||
// card thumbnail composables can fetch image bytes.
|
||||
repository = repository,
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = Routes.EDITOR,
|
||||
arguments = listOf(
|
||||
navArgument("noteId") {
|
||||
type = NavType.LongType
|
||||
defaultValue = -1L
|
||||
},
|
||||
),
|
||||
) { entry ->
|
||||
val raw = entry.arguments?.getLong("noteId") ?: -1L
|
||||
val id = if (raw <= 0L) null else raw
|
||||
// Read the share payload ONCE (consume) so back-then-reopen
|
||||
// doesn't re-route us into the editor with stale data.
|
||||
val sharedText = shareHolder.text.also { shareHolder.text = null }
|
||||
val sharedImages = shareHolder.images.also { shareHolder.images = emptyList() }
|
||||
// v0.3.6.0: also drain the page-title subject from the
|
||||
// share intent so the editor can format the note
|
||||
// with title on the first line.
|
||||
val sharedSubject = shareHolder.subject.also { shareHolder.subject = null }
|
||||
NoteEditorScreen(
|
||||
noteId = id,
|
||||
onClose = { navController.popBackStack() },
|
||||
initialSharedText = sharedText,
|
||||
initialSharedImages = sharedImages,
|
||||
initialSharedSubject = sharedSubject,
|
||||
repository = repository,
|
||||
// v0.3.4.0 hotfix: suppress auto-lock around
|
||||
// the editor's picker / camera / system-viewer
|
||||
// round-trips.
|
||||
securityManager = resolvedSecurity,
|
||||
)
|
||||
}
|
||||
composable(Routes.SETTINGS) {
|
||||
SettingsScreen(
|
||||
onBack = { navController.popBackStack() },
|
||||
onRequestPinSetup = { navController.navigate(Routes.PIN_SETUP) },
|
||||
// v0.3.3.0: "Reset PIN" row navigates here.
|
||||
onRequestPinChange = { navController.navigate(Routes.PIN_CHANGE) },
|
||||
// v0.3.4.0 hotfix: suppress auto-lock around
|
||||
// the backup export/import SAF pickers.
|
||||
securityManager = resolvedSecurity,
|
||||
)
|
||||
}
|
||||
composable(Routes.PIN_SETUP) {
|
||||
PinSetupScreen(
|
||||
onDone = { navController.popBackStack() },
|
||||
onCancel = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(Routes.PIN_CHANGE) {
|
||||
PinChangeScreen(
|
||||
onDone = { navController.popBackStack() },
|
||||
onCancel = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Suppress unused-import lint for the snapshots helper that may be
|
||||
// re-introduced in future filter-state extensions.
|
||||
@Suppress("unused")
|
||||
private fun <T> List<T>.toSnapshotStateList(): SnapshotStateList<T> = toMutableStateList<T>()
|
||||
@@ -1,167 +0,0 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* v0.3.2.0: orchestration layer for Backup / Import / Export.
|
||||
*
|
||||
* Reads / writes go through the Storage Access Framework — the
|
||||
* Activity hands in [Uri]s from
|
||||
* `ActivityResultContracts.CreateDocument` / `OpenDocument` and the
|
||||
* manager streams bytes in / out via ContentResolver. No fixed-path
|
||||
* writes, no extra permissions.
|
||||
*
|
||||
* Encrypt-on-export and decrypt-on-import are selected by the caller;
|
||||
* the codecs themselves ([BackupCodec], [EncryptedBackupCodec]) hold
|
||||
* the format / cipher details.
|
||||
*/
|
||||
class BackupManager(
|
||||
private val context: Context,
|
||||
private val repository: NoteRepository,
|
||||
) {
|
||||
|
||||
/**
|
||||
* Snapshot every note in [repository] and stream it to [uri] as a
|
||||
* plain JSON file. Throws on I/O failure.
|
||||
*
|
||||
* Returns the number of notes exported.
|
||||
*/
|
||||
suspend fun exportPlain(
|
||||
uri: Uri,
|
||||
appVersion: String,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int = withContext(Dispatchers.IO) {
|
||||
val file = BackupCodec.exportSnapshot(repository, appVersion)
|
||||
val json = BackupCodec.encode(file)
|
||||
context.contentResolver.openOutputStream(uri, "wt")?.use { out: OutputStream ->
|
||||
out.write(json.toByteArray(Charsets.UTF_8))
|
||||
out.flush()
|
||||
} ?: throw java.io.IOException("Could not open output stream for $uri")
|
||||
onProgress(file.notes.size, file.notes.size)
|
||||
file.notes.size
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot every note and stream it to [uri] as a passphrase-
|
||||
* encrypted envelope. [passphrase] is consumed (zeroed) inside
|
||||
* [EncryptedBackupCodec.encrypt].
|
||||
*/
|
||||
suspend fun exportEncrypted(
|
||||
uri: Uri,
|
||||
passphrase: CharArray,
|
||||
appVersion: String,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int = withContext(Dispatchers.IO) {
|
||||
val file = BackupCodec.exportSnapshot(repository, appVersion)
|
||||
val json = BackupCodec.encode(file)
|
||||
val payload = EncryptedBackupCodec.encrypt(json, passphrase)
|
||||
context.contentResolver.openOutputStream(uri, "wt")?.use { out ->
|
||||
out.write(payload)
|
||||
out.flush()
|
||||
} ?: throw java.io.IOException("Could not open output stream for $uri")
|
||||
onProgress(file.notes.size, file.notes.size)
|
||||
file.notes.size
|
||||
}
|
||||
|
||||
/**
|
||||
* Read [uri] and import every note it contains. Auto-detects
|
||||
* plain vs encrypted via the magic header. For encrypted files,
|
||||
* [passphrase] is required (caller validates with
|
||||
* [PasswordPolicy]).
|
||||
*
|
||||
* Returns the number of notes imported.
|
||||
*/
|
||||
suspend fun import(
|
||||
uri: Uri,
|
||||
passphrase: CharArray? = null,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int = withContext(Dispatchers.IO) {
|
||||
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw java.io.IOException("Could not open input stream for $uri")
|
||||
|
||||
val json: String = if (EncryptedBackupCodec.isEncrypted(bytes)) {
|
||||
val pass = passphrase
|
||||
?: throw IllegalArgumentException("Encrypted backup requires a passphrase")
|
||||
EncryptedBackupCodec.decrypt(bytes, pass)
|
||||
} else {
|
||||
String(bytes, Charsets.UTF_8)
|
||||
}
|
||||
|
||||
val file = BackupCodec.decode(json)
|
||||
BackupCodec.importSnapshot(file, repository) { cur, tot -> onProgress(cur, tot) }
|
||||
file.notes.size
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap metadata preview — used by the "Import from file…" flow
|
||||
* to show the user how many notes / attachments they're about to
|
||||
* bring in before they commit.
|
||||
*
|
||||
* Returns `null` if the file can't be read or the passphrase is
|
||||
* wrong (so the UI can surface "wrong passphrase" cleanly).
|
||||
*/
|
||||
suspend fun preview(uri: Uri, passphrase: CharArray? = null): BackupPreview? =
|
||||
withContext(Dispatchers.IO) {
|
||||
val bytes: ByteArray = try {
|
||||
context.contentResolver.openInputStream(uri)?.use(InputStream::readBytes)
|
||||
?: return@withContext null
|
||||
} catch (_: java.io.IOException) {
|
||||
return@withContext null
|
||||
}
|
||||
val json: String = if (EncryptedBackupCodec.isEncrypted(bytes)) {
|
||||
val pass = passphrase ?: return@withContext null
|
||||
try {
|
||||
EncryptedBackupCodec.decrypt(bytes, pass)
|
||||
} catch (_: javax.crypto.AEADBadTagException) {
|
||||
return@withContext null
|
||||
} catch (_: javax.crypto.BadPaddingException) {
|
||||
return@withContext null
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// v0.3.3.3 hotfix: a truncated / corrupt envelope
|
||||
// fails the require(...) size checks inside
|
||||
// decrypt() with an IllegalArgumentException.
|
||||
// Previously that escaped preview() and crashed the
|
||||
// coroutine; treat it the same as a bad passphrase.
|
||||
return@withContext null
|
||||
} catch (_: java.security.GeneralSecurityException) {
|
||||
// Catch-all for any other cipher-layer failure.
|
||||
return@withContext null
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
String(bytes, Charsets.UTF_8)
|
||||
} catch (_: java.io.IOException) {
|
||||
return@withContext null
|
||||
}
|
||||
}
|
||||
val file: BackupFile = try {
|
||||
BackupCodec.decode(json)
|
||||
} catch (_: kotlinx.serialization.SerializationException) {
|
||||
return@withContext null
|
||||
} catch (_: Exception) {
|
||||
// v0.3.3.3 hotfix: any other decode failure (e.g. the
|
||||
// payload wasn't JSON after all) must not escape.
|
||||
return@withContext null
|
||||
}
|
||||
BackupPreview(
|
||||
noteCount = file.notes.size,
|
||||
attachmentCount = file.notes.sumOf { it.attachments.size },
|
||||
appVersion = file.appVersion,
|
||||
exportedAt = file.exportedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Lightweight DTO shown in the import confirmation dialog. */
|
||||
data class BackupPreview(
|
||||
val noteCount: Int,
|
||||
val attachmentCount: Int,
|
||||
val appVersion: String,
|
||||
val exportedAt: Long,
|
||||
)
|
||||
@@ -1,106 +0,0 @@
|
||||
package org.incido.compose.data.settings
|
||||
|
||||
/**
|
||||
* One entry in the "What's New" dialog. Surfaced from the Settings
|
||||
* screen when the user taps the version number.
|
||||
*
|
||||
* v0.3.2.0: the dialog shows the [RECENT] list (newest first) in a
|
||||
* scrollable column. Each entry has a version, a release date, and a
|
||||
* list of bullet points summarising what shipped in that release.
|
||||
*
|
||||
* Content is mirrored from `Incido Development Plan.txt` §10 so the
|
||||
* in-app dialog and the repo's history of changes stay in lockstep
|
||||
* (the plan file is the source of truth at release time).
|
||||
*/
|
||||
data class ReleaseNote(
|
||||
val version: String,
|
||||
val date: String,
|
||||
val bullets: List<String>,
|
||||
)
|
||||
|
||||
object ReleaseNotes {
|
||||
|
||||
/**
|
||||
* The 5 most recent Incido releases, ordered newest → oldest.
|
||||
* Append a new entry on top each release.
|
||||
*/
|
||||
val RECENT: List<ReleaseNote> = listOf(
|
||||
ReleaseNote(
|
||||
version = "0.3.6.0",
|
||||
date = "2026-08-19",
|
||||
bullets = listOf(
|
||||
"Sharing a webpage to Incido (browser \u2192 Share \u2192 Incido) now " +
|
||||
"creates a note with the page title on the first line and " +
|
||||
"the URL below it \u2014 ready to save as-is. Fully offline: " +
|
||||
"the title comes from the browser's share data, so Incido " +
|
||||
"still never touches the network.",
|
||||
"New in Settings \u2192 Security: \"Export encryption key\" saves " +
|
||||
"the AES-256 key that protects your encrypted notes to a " +
|
||||
"passphrase-protected .inckey file \u2014 your backup for " +
|
||||
"device migrations.",
|
||||
"\"Import encryption key\" restores that key on a fresh " +
|
||||
"install, with a clear warning before the current key is " +
|
||||
"replaced.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.3.5.1",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"Cards now update their \"Encrypted\" indicator the moment " +
|
||||
"you flip the Encrypt-at-rest switch on — no need to " +
|
||||
"toggle off+on or restart the app to see the badge " +
|
||||
"appear.",
|
||||
"The \"Encrypted\" indicator on each note card is now " +
|
||||
"just a small lock icon, sitting immediately to the " +
|
||||
"left of the date/time on the bottom row (consistent " +
|
||||
"position on every card, instead of a centred \"lock + " +
|
||||
"label\" group at the bottom of the card).",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.3.5.0",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"\"Encrypt notes at rest\" now really works: your note text " +
|
||||
"and attachment files are AES-256-GCM encrypted in place " +
|
||||
"the moment you flip the switch (no restart), using the " +
|
||||
"Android Keystore key.",
|
||||
"Every time the app opens, each encrypted note is " +
|
||||
"double-checked by decrypting it — a card only earns the " +
|
||||
"\"Encrypted\" badge at the bottom of the card if that " +
|
||||
"check passes.",
|
||||
"New \"Block screenshots\" toggle (on by default): prevents " +
|
||||
"screenshots, screen recording, and app-switcher previews " +
|
||||
"while Incido is open.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.3.4.0",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"Note cards now show a paperclip icon on the right edge " +
|
||||
"whenever a note has an attachment — lined up between " +
|
||||
"the favourite star and the \u22EE menu.",
|
||||
"Cards with a dark image background are now readable in " +
|
||||
"Light theme — the title, preview text, timestamp and " +
|
||||
"icons switch to light colours over the photo.",
|
||||
"Auto-Lock set to \"Immediately\" no longer locks the app " +
|
||||
"while you're picking a file to attach (or exporting / " +
|
||||
"importing a backup), so your in-progress note and the " +
|
||||
"attachment survive the trip to the file manager.",
|
||||
),
|
||||
),
|
||||
ReleaseNote(
|
||||
version = "0.3.3.8",
|
||||
date = "2026-08-17",
|
||||
bullets = listOf(
|
||||
"The designed Incido artwork — the glass shield with the " +
|
||||
"fountain-pen nib — is now the app icon, replacing the " +
|
||||
"placeholder glyph on the home screen, in the app " +
|
||||
"drawer, and in the adaptive-icon layers.",
|
||||
),
|
||||
),
|
||||
// v0.3.6.0 push drops v0.3.3.7 off the "5 most recent" tail.
|
||||
)
|
||||
}
|
||||
@@ -1,893 +0,0 @@
|
||||
package org.incido.compose.ui.editor
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.ime
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.systemBars
|
||||
import androidx.compose.foundation.layout.union
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.CameraAlt
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Done
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Star
|
||||
import androidx.compose.material.icons.filled.Tag
|
||||
import androidx.compose.material.icons.outlined.StarOutline
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.SuggestionChip
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.painter.BitmapPainter
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.compose.ui.theme.AllNoteColors
|
||||
import org.incido.compose.ui.theme.swatchBorderColor
|
||||
import org.incido.compose.ui.theme.toComposeColor
|
||||
import org.incido.domain.model.Hashtag
|
||||
import org.incido.domain.model.NoteColor
|
||||
import java.io.File
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun NoteEditorScreen(
|
||||
noteId: Long?,
|
||||
onClose: () -> Unit,
|
||||
initialSharedText: String? = null,
|
||||
initialSharedImages: List<SharedImage> = emptyList(),
|
||||
/**
|
||||
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from a share-into. Browsers
|
||||
* fill this with the page title when the user shares a URL; the
|
||||
* view-model uses it to format the note's first line.
|
||||
*/
|
||||
initialSharedSubject: String? = null,
|
||||
repository: org.incido.domain.repository.NoteRepository? = null,
|
||||
/**
|
||||
* v0.3.4.0 hotfix: used to suppress auto-lock while the user is
|
||||
* inside an external activity we launched (file picker, camera,
|
||||
* system attachment viewer). Null disables the suppression (the
|
||||
* pre-0.3.4.0 behaviour).
|
||||
*/
|
||||
securityManager: SecurityManager? = null,
|
||||
viewModel: NoteEditorViewModel = viewModel(
|
||||
factory = NoteEditorViewModel.factory(
|
||||
noteId = noteId,
|
||||
initialSharedText = initialSharedText,
|
||||
initialSharedImages = initialSharedImages,
|
||||
initialSharedSubject = initialSharedSubject,
|
||||
),
|
||||
key = "editor-$noteId",
|
||||
),
|
||||
) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
var menuExpanded by remember { mutableStateOf(false) }
|
||||
var showDiscardDialog by rememberSaveable { mutableStateOf(false) }
|
||||
val snackbarHost = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val ctx = LocalContext.current
|
||||
|
||||
// v0.3.1.0: pick up the NoteRepository from the editor's VM (it's not
|
||||
// on the ViewModel's public surface but we can grab it for the image
|
||||
// viewer via the app container — see App.kt wiring for the actual
|
||||
// route through. Fall back to null and disable the viewer.)
|
||||
val repoForViewer = repository
|
||||
|
||||
// v0.3.1.0: camera permission + capture. The camera launcher is
|
||||
// declared FIRST so the permission callback (below) can forward to it
|
||||
// without a Kotlin forward-reference error.
|
||||
var pendingCameraUri by remember { mutableStateOf<Uri?>(null) }
|
||||
val cameraLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.TakePicture()
|
||||
) { success ->
|
||||
val uri = pendingCameraUri
|
||||
if (success && uri != null) {
|
||||
scope.launch {
|
||||
val bytes = withContext(Dispatchers.IO) {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
}
|
||||
// Always delete the temp file — its bytes are now in the DB.
|
||||
runCatching { uri.path?.let { File(it).delete() } }
|
||||
pendingCameraUri = null
|
||||
if (bytes != null) {
|
||||
viewModel.importAttachmentBytes(
|
||||
bytes = bytes,
|
||||
mimeType = "image/jpeg",
|
||||
displayName = "IMG_${System.currentTimeMillis()}.jpg",
|
||||
)
|
||||
} else {
|
||||
Toast.makeText(ctx, "Couldn't read captured photo", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pendingCameraUri = null
|
||||
}
|
||||
}
|
||||
// Now declared AFTER cameraLauncher so it can forward to it.
|
||||
val cameraPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { granted ->
|
||||
if (granted) {
|
||||
pendingCameraUri?.let { uri ->
|
||||
// v0.3.4.0 hotfix: the camera app takes us fully out of
|
||||
// the process — with Auto-Lock = Immediate the return
|
||||
// trip used to land on the lock screen (losing the
|
||||
// unsaved note). Flag the round-trip so the re-lock is
|
||||
// suppressed.
|
||||
securityManager?.beginExternalActivity()
|
||||
cameraLauncher.launch(uri)
|
||||
}
|
||||
} else {
|
||||
Toast.makeText(ctx, "Camera permission denied", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
val filePickerLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocument()
|
||||
) { uri ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
scope.launch {
|
||||
val ctxForResolver = ctx
|
||||
val (bytes, displayName, mime) = withContext(Dispatchers.IO) {
|
||||
val resolver = ctxForResolver.contentResolver
|
||||
val name = queryDisplayName(resolver, uri) ?: "Attachment_${System.currentTimeMillis()}"
|
||||
val mimeType = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val data = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
Triple(data, name, mimeType)
|
||||
}
|
||||
if (bytes != null) {
|
||||
viewModel.importAttachmentBytes(
|
||||
bytes = bytes,
|
||||
mimeType = mime,
|
||||
displayName = displayName,
|
||||
)
|
||||
} else {
|
||||
Toast.makeText(ctx, "Couldn't read attachment", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun launchCamera() {
|
||||
val (uri, _) = createTempCameraUri(ctx)
|
||||
if (uri == null) {
|
||||
Toast.makeText(ctx, "Couldn't prepare camera outbox", Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
pendingCameraUri = uri
|
||||
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
|
||||
LaunchedEffect(state.isLoading) {
|
||||
if (!state.isLoading && state.existing != null) {
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
if (noteId == null) focusRequester.requestFocus()
|
||||
}
|
||||
|
||||
LaunchedEffect(state.snackbar) {
|
||||
val msg = state.snackbar ?: return@LaunchedEffect
|
||||
scope.launch {
|
||||
snackbarHost.showSnackbar(msg)
|
||||
viewModel.consumeSnackbar()
|
||||
}
|
||||
}
|
||||
|
||||
fun isDirty(): Boolean {
|
||||
if (state.isLoading) return false
|
||||
return state.isDirty(
|
||||
initialContent = viewModel.initialContent,
|
||||
initialFavorite = viewModel.initialFavorite,
|
||||
initialColor = viewModel.initialColor,
|
||||
initialTags = viewModel.initialHashtags,
|
||||
)
|
||||
}
|
||||
|
||||
fun tryClose() {
|
||||
if (isDirty()) showDiscardDialog = true else onClose()
|
||||
}
|
||||
|
||||
BackHandler(enabled = true) { tryClose() }
|
||||
|
||||
if (showDiscardDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showDiscardDialog = false },
|
||||
title = { Text("Discard changes?") },
|
||||
text = { Text("You have unsaved edits. Leaving now will discard them.") },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showDiscardDialog = false
|
||||
onClose()
|
||||
}) {
|
||||
Text("Discard")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDiscardDialog = false }) {
|
||||
Text("Keep editing")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
contentWindowInsets = WindowInsets.systemBars.union(WindowInsets.ime),
|
||||
snackbarHost = { SnackbarHost(hostState = snackbarHost) },
|
||||
topBar = {
|
||||
// v0.3.6.1 Emergency Patch: left-anchored title sits against the back arrow
|
||||
// (CenterAlignedTopAppBar was crowded by the six right-side actions).
|
||||
TopAppBar(
|
||||
title = { Text(if (state.isEditing) "Edit" else "New") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { tryClose() }) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
// v0.3.1.0: Camera (camera icon) + Attach File (paperclip icon).
|
||||
IconButton(onClick = { launchCamera() }) {
|
||||
Icon(
|
||||
Icons.Filled.CameraAlt,
|
||||
contentDescription = "Take photo",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = {
|
||||
// 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() }) {
|
||||
Icon(
|
||||
imageVector = if (state.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
|
||||
contentDescription = if (state.isFavorite) "Unfavorite" else "Favorite",
|
||||
tint = if (state.isFavorite) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { viewModel.save(onClose) },
|
||||
enabled = state.canSave,
|
||||
) {
|
||||
Icon(Icons.Default.Done, contentDescription = "Save")
|
||||
}
|
||||
if (state.isEditing) {
|
||||
IconButton(onClick = { menuExpanded = true }) {
|
||||
Icon(Icons.Default.MoreVert, contentDescription = "More")
|
||||
}
|
||||
DropdownMenu(
|
||||
expanded = menuExpanded,
|
||||
onDismissRequest = { menuExpanded = false },
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Delete") },
|
||||
onClick = {
|
||||
menuExpanded = false
|
||||
viewModel.delete(onClose)
|
||||
},
|
||||
leadingIcon = {
|
||||
Icon(Icons.Default.Delete, contentDescription = null)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
) {
|
||||
// v0.3.0.1: colour picker centred horizontally.
|
||||
// v0.3.6.1 Emergency Patch: equal 12dp Spacers above and below so
|
||||
// the picker sits symmetrically between the title bar and the
|
||||
// top edge of the note content (previously the row's
|
||||
// `vertical = 4.dp` padding was dwarfed by the OutlinedTextField's
|
||||
// intrinsic top inset, making the lower gap appear far larger).
|
||||
androidx.compose.foundation.layout.Spacer(Modifier.height(12.dp))
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(
|
||||
space = 12.dp,
|
||||
alignment = Alignment.CenterHorizontally,
|
||||
),
|
||||
) {
|
||||
AllNoteColors.forEach { color ->
|
||||
ColorSwatch(
|
||||
color = color,
|
||||
selected = state.color == color,
|
||||
onClick = { viewModel.setColor(color) },
|
||||
)
|
||||
}
|
||||
}
|
||||
androidx.compose.foundation.layout.Spacer(Modifier.height(12.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = state.content,
|
||||
onValueChange = viewModel::onContentChange,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp)
|
||||
.focusRequester(focusRequester),
|
||||
placeholder = { Text("Write something…") },
|
||||
keyboardOptions = KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.Sentences,
|
||||
imeAction = ImeAction.Default,
|
||||
),
|
||||
)
|
||||
|
||||
// v0.3.1.0: attachment thumbnail strip. Combines persisted
|
||||
// attachments (loaded via observeAttachments in the VM) with
|
||||
// any pending attachments that haven't been saved yet. Each
|
||||
// thumbnail has a ✕ in the top-right corner; tap the
|
||||
// thumbnail to open the full-screen viewer.
|
||||
if (state.attachments.isNotEmpty() || state.pendingAttachments.isNotEmpty()) {
|
||||
AttachmentStrip(
|
||||
persisted = state.attachments,
|
||||
persistedBytes = emptyMap(), // resolved lazily in the viewer
|
||||
persistedViewerIds = state.attachments.associate { it.id to ViewerAttachmentId.Persisted(it.id) },
|
||||
persistedOpen = { id -> viewModel.openFullScreen(id) },
|
||||
persistedDelete = { id -> viewModel.deletePersistedAttachment(id) },
|
||||
pending = state.pendingAttachments,
|
||||
pendingBytes = state.pendingAttachmentBytes,
|
||||
pendingOpen = { tempId -> viewModel.openFullScreen(ViewerAttachmentId.Pending(tempId)) },
|
||||
pendingDelete = { tempId -> viewModel.removePendingAttachment(tempId) },
|
||||
// v0.3.1.1: source of bytes for persisted thumbnail lazy load
|
||||
repository = repository,
|
||||
// v0.3.4.0 hotfix: needed by the non-image tap
|
||||
// handler so the system-viewer round-trip doesn't
|
||||
// trigger an immediate re-lock.
|
||||
securityManager = securityManager,
|
||||
)
|
||||
}
|
||||
|
||||
// v0.3.0.1: hashtag chip row at the bottom of the editor.
|
||||
HashtagChipRow(
|
||||
tags = state.hashtags,
|
||||
onRemove = { viewModel.removeTag(it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (state.isAddingTag) {
|
||||
AddTagSheet(
|
||||
tagInput = state.tagInput,
|
||||
suggestions = state.tagSuggestions,
|
||||
canCreate = Hashtag.parseOrNull(state.tagInput) != null &&
|
||||
Hashtag.normalise(state.tagInput) !in state.hashtags,
|
||||
onInputChange = viewModel::onTagInputChange,
|
||||
onPickSuggestion = { picked ->
|
||||
viewModel.addTag(picked)
|
||||
viewModel.closeAddTagSheet()
|
||||
},
|
||||
onCreate = {
|
||||
if (viewModel.addTag(state.tagInput)) {
|
||||
viewModel.closeAddTagSheet()
|
||||
}
|
||||
},
|
||||
onDismiss = { viewModel.closeAddTagSheet() },
|
||||
)
|
||||
}
|
||||
|
||||
// v0.3.1.0: full-screen image viewer.
|
||||
state.fullScreenAttachmentId?.let { viewerId ->
|
||||
if (repoForViewer != null) {
|
||||
val pendingBytes: ByteArray? = when (viewerId) {
|
||||
is ViewerAttachmentId.Pending -> state.pendingAttachmentBytes[viewerId.tempId]
|
||||
is ViewerAttachmentId.Persisted -> null // viewer loads from DB
|
||||
}
|
||||
ImageViewerScreen(
|
||||
attachmentId = viewerId,
|
||||
repository = repoForViewer,
|
||||
pendingBytes = pendingBytes,
|
||||
onClose = { viewModel.closeFullScreen() },
|
||||
)
|
||||
} else {
|
||||
// No repository access — viewer unavailable. Just close.
|
||||
viewModel.closeFullScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// v0.3.1.0 / v0.3.1.1: attachment strip + thumbnail helpers. v0.3.1.1
|
||||
// fix: persisted image attachments now render a thumbnail in the
|
||||
// editor strip (previously they fell through to the file-type
|
||||
// placeholder because `bytes` was null for them). Each persisted
|
||||
// thumbnail lazy-loads its own bytes via `produceState` so we don't
|
||||
// have to keep every attachment's bytes in memory.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AttachmentStrip(
|
||||
persisted: List<org.incido.domain.model.NoteAttachment>,
|
||||
persistedBytes: Map<Long, ByteArray>,
|
||||
persistedViewerIds: Map<Long, ViewerAttachmentId>,
|
||||
persistedOpen: (ViewerAttachmentId) -> Unit,
|
||||
persistedDelete: (Long) -> Unit,
|
||||
pending: List<PendingAttachment>,
|
||||
pendingBytes: Map<Long, ByteArray>,
|
||||
pendingOpen: (Long) -> Unit,
|
||||
pendingDelete: (Long) -> Unit,
|
||||
repository: org.incido.domain.repository.NoteRepository?,
|
||||
/** v0.3.4.0 hotfix: forwarded to [AttachmentThumbnail] for the
|
||||
* system-viewer auto-lock suppression. */
|
||||
securityManager: SecurityManager?,
|
||||
) {
|
||||
LazyRow(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 0.dp),
|
||||
) {
|
||||
items(persisted, key = { it.id }) { att ->
|
||||
AttachmentThumbnail(
|
||||
displayName = att.displayName,
|
||||
mimeType = att.mimeType,
|
||||
pendingBytes = null, // not a pending attachment
|
||||
attachmentId = att.id, // v0.3.1.1: drives the lazy DB load
|
||||
repository = repository, // v0.3.1.1: source of bytes
|
||||
// v0.3.1.2: lambda fires only for image attachments —
|
||||
// non-image taps launch a system viewer internally.
|
||||
onOpenImage = { persistedOpen(persistedViewerIds[att.id] ?: ViewerAttachmentId.Persisted(att.id)) },
|
||||
onRemove = { persistedDelete(att.id) },
|
||||
securityManager = securityManager,
|
||||
)
|
||||
}
|
||||
items(pending, key = { it.tempId }) { p ->
|
||||
AttachmentThumbnail(
|
||||
displayName = p.displayName,
|
||||
mimeType = p.mimeType,
|
||||
pendingBytes = pendingBytes[p.tempId],
|
||||
attachmentId = null, // pending, no DB id to load from
|
||||
repository = repository,
|
||||
onOpenImage = { pendingOpen(p.tempId) },
|
||||
onRemove = { pendingDelete(p.tempId) },
|
||||
securityManager = securityManager,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AttachmentThumbnail(
|
||||
displayName: String,
|
||||
mimeType: String,
|
||||
/** In-memory bytes for a pending attachment (null for persisted). */
|
||||
pendingBytes: ByteArray?,
|
||||
/** DB id for a persisted attachment (null for pending). Drives the lazy DB load. */
|
||||
attachmentId: Long?,
|
||||
repository: org.incido.domain.repository.NoteRepository?,
|
||||
/** v0.3.1.2: fires only when the user taps an IMAGE thumbnail
|
||||
* (opens the in-app full-screen viewer). Non-image taps launch
|
||||
* the system viewer internally so PDFs / MP3s / etc. don't fall
|
||||
* into the bitmap decode path that would silently fail. */
|
||||
onOpenImage: () -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
/** v0.3.4.0 hotfix: suppress auto-lock around the external
|
||||
* "open in system viewer" intent. */
|
||||
securityManager: SecurityManager?,
|
||||
) {
|
||||
val isImage = mimeType.startsWith("image/")
|
||||
val ctx = LocalContext.current
|
||||
|
||||
// v0.3.1.1: lazy-load bytes from DB for persisted image attachments
|
||||
// so the editor strip shows a thumbnail even after the note is
|
||||
// reopened. Re-keys on attachmentId so navigating between notes /
|
||||
// re-rendering re-fetches rather than reusing stale bytes.
|
||||
//
|
||||
// v0.3.1.3: widened to ALL mime types — non-image persisted
|
||||
// attachments also need their bytes loaded so the "open in default
|
||||
// app" tap handler can write a temp file and launch an
|
||||
// ACTION_VIEW intent. Previously the `isImage` gate caused the
|
||||
// handler to bail with a misleading "Loading…" Toast forever.
|
||||
val lazyBytes by produceState<ByteArray?>(initialValue = null, key1 = attachmentId) {
|
||||
if (pendingBytes == null && attachmentId != null && repository != null) {
|
||||
value = withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
repository.getAttachmentBytes(attachmentId)
|
||||
}
|
||||
}
|
||||
}
|
||||
val effectiveBytes: ByteArray? = pendingBytes ?: lazyBytes
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(96.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))
|
||||
// v0.3.1.2: branch on isImage — image taps open the
|
||||
// in-app viewer; non-image taps (PDF / MP3 / video / etc.)
|
||||
// write the bytes to a cache temp file and launch the
|
||||
// system viewer via FileProvider + ACTION_VIEW. The
|
||||
// previous unconditional viewer path silently failed for
|
||||
// non-image mime types (BitmapFactory.decodeByteArray
|
||||
// returns null and the viewer just shows "Loading…").
|
||||
.clickable {
|
||||
if (isImage) {
|
||||
onOpenImage()
|
||||
} else {
|
||||
val bytes = effectiveBytes
|
||||
if (bytes == null) {
|
||||
// Lazy load still in flight for a persisted
|
||||
// attachment — nudge the user instead of
|
||||
// silently doing nothing.
|
||||
Toast.makeText(ctx, "Loading\u2026", Toast.LENGTH_SHORT).show()
|
||||
return@clickable
|
||||
}
|
||||
runCatching {
|
||||
// Sanitise displayName for use as a filename —
|
||||
// strip any path separators / chars the OS
|
||||
// doesn't allow in filenames.
|
||||
val safeName = displayName.replace(Regex("[/\\\\:*?\"<>|]"), "_")
|
||||
// v0.3.1.3: write into a dedicated `open_outbox/`
|
||||
// subdir under cacheDir so it falls inside the
|
||||
// FileProvider's exposed path set (see
|
||||
// app/src/main/res/xml/file_paths.xml). Previously
|
||||
// this wrote straight to cacheDir which is NOT
|
||||
// exposed, so FileProvider.getUriForFile threw
|
||||
// IllegalArgumentException and the runCatching
|
||||
// swallowed it as the misleading "No app can
|
||||
// open …" toast.
|
||||
val outbox = File(ctx.cacheDir, "open_outbox").apply { mkdirs() }
|
||||
val tmp = File(
|
||||
outbox,
|
||||
"open_${System.currentTimeMillis()}_$safeName",
|
||||
).apply { createNewFile() }
|
||||
tmp.writeBytes(bytes)
|
||||
val uri = FileProvider.getUriForFile(
|
||||
ctx,
|
||||
"${ctx.packageName}.fileprovider",
|
||||
tmp,
|
||||
)
|
||||
val intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, mimeType)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
// v0.3.4.0 hotfix: opening an attachment in the
|
||||
// system viewer also leaves the app — suppress
|
||||
// the auto-lock on return.
|
||||
securityManager?.beginExternalActivity()
|
||||
ctx.startActivity(intent)
|
||||
}.onFailure { err ->
|
||||
// v0.3.1.3: distinguish "no handler" from "couldn't
|
||||
// open". ActivityNotFoundException means the OS has
|
||||
// no app registered for this mime type (e.g. no
|
||||
// PDF viewer installed); anything else (typically
|
||||
// IllegalArgumentException from FileProvider when
|
||||
// file_paths.xml is misconfigured, or IOException
|
||||
// from the cache write) gets a generic message.
|
||||
val msg = if (err is android.content.ActivityNotFoundException) {
|
||||
"No app can open $displayName"
|
||||
} else {
|
||||
"Couldn't open $displayName"
|
||||
}
|
||||
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
) {
|
||||
// Image preview OR file-type fallback.
|
||||
if (isImage && effectiveBytes != null) {
|
||||
val bitmap = remember(effectiveBytes.contentHashCode()) {
|
||||
BitmapFactory.decodeByteArray(effectiveBytes, 0, effectiveBytes.size)
|
||||
}
|
||||
if (bitmap != null) {
|
||||
androidx.compose.foundation.Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = displayName,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
} else {
|
||||
// decode failed → fall back to icon
|
||||
FileTypePlaceholder(mimeType, displayName)
|
||||
}
|
||||
} else {
|
||||
// Non-image OR no bytes yet (still loading) — show placeholder.
|
||||
FileTypePlaceholder(mimeType, displayName)
|
||||
}
|
||||
// ✕ in top-right.
|
||||
IconButton(
|
||||
onClick = onRemove,
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.size(28.dp)
|
||||
.padding(2.dp)
|
||||
.background(
|
||||
color = Color.Black.copy(alpha = 0.55f),
|
||||
shape = CircleShape,
|
||||
),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
contentDescription = "Remove $displayName",
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FileTypePlaceholder(mimeType: String, displayName: String) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
modifier = Modifier.fillMaxSize().padding(6.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Description,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
androidx.compose.foundation.layout.Spacer(Modifier.size(4.dp))
|
||||
Text(
|
||||
text = displayName.take(14) + if (displayName.length > 14) "…" else "",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 2,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Existing editor UI (color swatch, hashtag chips, add-tag sheet)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun ColorSwatch(
|
||||
color: NoteColor,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val fillColor = color.toComposeColor()
|
||||
val border = if (selected) swatchBorderColor else MaterialTheme.colorScheme.outlineVariant
|
||||
val borderWidth = if (selected) 2.dp else 1.dp
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(36.dp)
|
||||
.clip(CircleShape)
|
||||
.background(fillColor)
|
||||
.border(borderWidth, border, CircleShape)
|
||||
.clickable(onClick = onClick),
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun HashtagChipRow(
|
||||
tags: List<String>,
|
||||
onRemove: (String) -> Unit,
|
||||
) {
|
||||
if (tags.isEmpty()) return
|
||||
FlowRow(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
tags.forEach { tag ->
|
||||
AssistChip(
|
||||
onClick = { onRemove(tag) },
|
||||
label = { Text("#$tag") },
|
||||
trailingIcon = {
|
||||
Icon(Icons.Filled.Close, contentDescription = "Remove $tag", modifier = Modifier.size(16.dp))
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AddTagSheet(
|
||||
tagInput: String,
|
||||
suggestions: List<String>,
|
||||
canCreate: Boolean,
|
||||
onInputChange: (String) -> Unit,
|
||||
onPickSuggestion: (String) -> Unit,
|
||||
onCreate: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = onDismiss,
|
||||
sheetState = sheetState,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Text("Add a tag", style = MaterialTheme.typography.titleMedium)
|
||||
OutlinedTextField(
|
||||
value = tagInput,
|
||||
onValueChange = onInputChange,
|
||||
placeholder = { Text("hashtag-name") },
|
||||
singleLine = true,
|
||||
leadingIcon = { Icon(Icons.Filled.Tag, contentDescription = null) },
|
||||
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (suggestions.isNotEmpty()) {
|
||||
Text(
|
||||
"Suggestions",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
suggestions.forEach { s ->
|
||||
SuggestionChip(
|
||||
onClick = { onPickSuggestion(s) },
|
||||
label = { Text("#$s") },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (canCreate) {
|
||||
TextButton(onClick = onCreate) {
|
||||
Text("+ Create \"${Hashtag.normalise(tagInput)}\"")
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Tags help you find notes later. Up to ${NoteEditorUiState.MAX_TAGS} per note.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// v0.3.1.0: helpers (camera URI + SAF display-name query)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a temporary file in the app's cache and return a
|
||||
* FileProvider-scoped Uri pointing at it. The camera app writes a JPEG
|
||||
* there; we read the bytes and delete the temp file. Returns
|
||||
* `(uri, file)` so the caller can clean up if reading fails.
|
||||
*/
|
||||
private fun createTempCameraUri(ctx: Context): Pair<Uri?, File?> {
|
||||
return try {
|
||||
val outbox = File(ctx.cacheDir, "camera_outbox").apply { mkdirs() }
|
||||
val file = File(outbox, "cap_${System.currentTimeMillis()}.jpg")
|
||||
file.createNewFile()
|
||||
val authority = "${ctx.packageName}.fileprovider"
|
||||
val uri = FileProvider.getUriForFile(ctx, authority, file)
|
||||
uri to file
|
||||
} catch (e: Exception) {
|
||||
null to null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the Open Documents column DISPLAY_NAME for a content:// Uri,
|
||||
* falling back to the last path segment. Returns null if neither
|
||||
* works (which is fine — the caller uses a generated default).
|
||||
*/
|
||||
private fun queryDisplayName(resolver: android.content.ContentResolver, uri: Uri): String? {
|
||||
return try {
|
||||
resolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||
?.use { cursor ->
|
||||
if (cursor.moveToFirst()) {
|
||||
val idx = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
|
||||
if (idx >= 0) cursor.getString(idx) else null
|
||||
} else null
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight [BackHandler] wrapper to avoid pulling activity-compose
|
||||
* into the editor file for a single symbol. The platform back press
|
||||
* closes the editor or prompts for discard confirmation.
|
||||
*/
|
||||
@Composable
|
||||
private fun BackHandler(enabled: Boolean, onBack: () -> Unit) {
|
||||
androidx.activity.compose.BackHandler(enabled = enabled, onBack = onBack)
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package org.incido.compose.util
|
||||
|
||||
import android.text.format.DateUtils
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
|
||||
/**
|
||||
* Returns a localised "X ago" style timestamp for the given epoch millis.
|
||||
* Uses Android's [DateUtils.getRelativeTimeSpanString] which handles all
|
||||
* the edge cases (Today / Yesterday / N days ago / N weeks ago / …) and
|
||||
* is automatically localised to the device language.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberRelativeTimestamp(epochMillis: Long): String {
|
||||
val now = remember { System.currentTimeMillis() }
|
||||
return DateUtils.getRelativeTimeSpanString(
|
||||
epochMillis,
|
||||
now,
|
||||
DateUtils.MINUTE_IN_MILLIS,
|
||||
DateUtils.FORMAT_ABBREV_RELATIVE,
|
||||
).toString()
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// core/backup — Phase 1 (M2 task 1): the backup bridge, extracted from
|
||||
// :composeApp so the desktop build can speak the phone's file format.
|
||||
//
|
||||
// Everything here is pure JVM/kotlinx (verified by reading the code in the
|
||||
// Phase-0 spike: zero android.* imports in the codecs). The package name
|
||||
// stays org.incido.compose.data.backup so the Android diff is file moves
|
||||
// only — no import churn in composeApp.
|
||||
//
|
||||
// Shape follows :core:domain (plain kotlin("jvm"), consumed by both the
|
||||
// Android app and the desktop app). No ObjectBox here: the codec talks to
|
||||
// the app only through the NoteRepository interface from :core:domain.
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.kotlinJvm)
|
||||
// @Serializable DTOs (BackupFile / BackupNote / BackupAttachment) live in
|
||||
// BackupCodec.kt — the plugin generates their serializers here.
|
||||
alias(libs.plugins.kotlinSerialization)
|
||||
}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// Public API speaks domain types (Note, NoteRepository) — api, not impl.
|
||||
api(project(":core:domain"))
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package org.incido.compose.data.backup
|
||||
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.security.GeneralSecurityException
|
||||
import javax.crypto.AEADBadTagException
|
||||
import javax.crypto.BadPaddingException
|
||||
import kotlinx.coroutines.flow.first
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
* Phase 1 (M2 task 1): platform-neutral orchestration for Backup /
|
||||
* Import / Export, extracted from `BackupManager` so the desktop build
|
||||
* can speak the exact same file format as the phone.
|
||||
*
|
||||
* The only difference from the old `BackupManager` internals is the I/O
|
||||
* boundary: streams in, streams out — no `Uri`, no `ContentResolver`, no
|
||||
* `Context`. Android keeps a thin `Uri → stream` shim around this object;
|
||||
* desktop will hand it `FileInputStream` / `FileOutputStream` (task 2).
|
||||
*
|
||||
* Format / cipher details stay in [BackupCodec] and
|
||||
* [EncryptedBackupCodec]; this class only sequences them. Like the codecs,
|
||||
* these functions are **not** dispatcher-wrapped — the caller decides
|
||||
* (Android's shim uses `withContext(Dispatchers.IO)`).
|
||||
*/
|
||||
object BackupBridge {
|
||||
|
||||
/**
|
||||
* Snapshot every note in [repository] and write it to [output] as
|
||||
* plain JSON. Closes [output]. Throws on I/O failure.
|
||||
*
|
||||
* Returns the number of notes exported.
|
||||
*/
|
||||
suspend fun exportPlain(
|
||||
repository: NoteRepository,
|
||||
output: OutputStream,
|
||||
appVersion: String,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int {
|
||||
val file = BackupCodec.exportSnapshot(repository, appVersion)
|
||||
val json = BackupCodec.encode(file)
|
||||
output.use { out ->
|
||||
out.write(json.toByteArray(Charsets.UTF_8))
|
||||
out.flush()
|
||||
}
|
||||
onProgress(file.notes.size, file.notes.size)
|
||||
return file.notes.size
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot every note and write it to [output] as a passphrase-
|
||||
* encrypted envelope. Closes [output]. [passphrase] is consumed
|
||||
* (zeroed) inside [EncryptedBackupCodec.encrypt].
|
||||
*
|
||||
* Returns the number of notes exported.
|
||||
*/
|
||||
suspend fun exportEncrypted(
|
||||
repository: NoteRepository,
|
||||
output: OutputStream,
|
||||
passphrase: CharArray,
|
||||
appVersion: String,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): Int {
|
||||
val file = BackupCodec.exportSnapshot(repository, appVersion)
|
||||
val json = BackupCodec.encode(file)
|
||||
val payload = EncryptedBackupCodec.encrypt(json, passphrase)
|
||||
output.use { out ->
|
||||
out.write(payload)
|
||||
out.flush()
|
||||
}
|
||||
onProgress(file.notes.size, file.notes.size)
|
||||
return file.notes.size
|
||||
}
|
||||
|
||||
/**
|
||||
* Read [input] and import every note it contains. Closes [input].
|
||||
* Auto-detects plain vs encrypted via the magic header. For
|
||||
* encrypted files, [passphrase] is required (caller validates with
|
||||
* `PasswordPolicy`).
|
||||
*
|
||||
* **Dedupe (M2 task 3):** with [skipExisting] (the default) a note is
|
||||
* skipped when the library already holds a note with the same
|
||||
* `(createdAt, updatedAt, sha256(content))` key — the triple the
|
||||
* export preserves verbatim on both platforms (sound only since the
|
||||
* M2 import-timestamp fix). The existing keys are snapshotted BEFORE
|
||||
* this call, so a file containing two genuinely identical notes still
|
||||
* imports both into a fresh library; only a *second import* of the
|
||||
* same file adds nothing. Pass `skipExisting = false` to force the
|
||||
* old additive behaviour.
|
||||
*
|
||||
* Errors surface as thrown exceptions, same as the old
|
||||
* `BackupManager.import`: missing passphrase →
|
||||
* [IllegalArgumentException]; bad passphrase / corrupt envelope →
|
||||
* `GeneralSecurityException` family.
|
||||
*/
|
||||
suspend fun import(
|
||||
repository: NoteRepository,
|
||||
input: InputStream,
|
||||
passphrase: CharArray? = null,
|
||||
skipExisting: Boolean = true,
|
||||
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): ImportSummary {
|
||||
val bytes = input.use(InputStream::readBytes)
|
||||
val json = payloadJson(bytes, passphrase)
|
||||
val file = BackupCodec.decode(json)
|
||||
|
||||
val toImport = if (!skipExisting) {
|
||||
file.notes
|
||||
} else {
|
||||
val existing = repository.observeAllIncludingTrashed().first()
|
||||
.map { keyFor(it.createdAt, it.updatedAt, it.content) }
|
||||
.toSet()
|
||||
file.notes.filterNot { keyFor(it.createdAt, it.updatedAt, it.content) in existing }
|
||||
}
|
||||
val skipped = file.notes.size - toImport.size
|
||||
BackupCodec.importSnapshot(file.copy(notes = toImport), repository) { cur, tot ->
|
||||
onProgress(cur, tot)
|
||||
}
|
||||
return ImportSummary(imported = toImport.size, skipped = skipped)
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap metadata preview — used by the "Import from file…" flow
|
||||
* to show the user how many notes / attachments they're about to
|
||||
* bring in before they commit. Closes [input].
|
||||
*
|
||||
* Returns `null` if the file can't be read or the passphrase is
|
||||
* wrong (so the UI can surface "wrong passphrase" cleanly).
|
||||
*/
|
||||
fun preview(input: InputStream, passphrase: CharArray? = null): BackupPreview? {
|
||||
val bytes: ByteArray = try {
|
||||
input.use(InputStream::readBytes)
|
||||
} catch (_: IOException) {
|
||||
return null
|
||||
}
|
||||
val json: String = try {
|
||||
payloadJson(bytes, passphrase)
|
||||
} catch (_: AEADBadTagException) {
|
||||
return null
|
||||
} catch (_: BadPaddingException) {
|
||||
return null
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// v0.3.3.3 hotfix (kept from BackupManager.preview): a
|
||||
// truncated / corrupt envelope fails the require(...) size
|
||||
// checks inside decrypt(); treat it like a bad passphrase
|
||||
// instead of letting it escape and crash the coroutine.
|
||||
return null
|
||||
} catch (_: GeneralSecurityException) {
|
||||
// Catch-all for any other cipher-layer failure.
|
||||
return null
|
||||
}
|
||||
val file: BackupFile = try {
|
||||
BackupCodec.decode(json)
|
||||
} catch (_: kotlinx.serialization.SerializationException) {
|
||||
return null
|
||||
} catch (_: Exception) {
|
||||
// v0.3.3.3 hotfix: any other decode failure (e.g. the
|
||||
// payload wasn't JSON after all) must not escape.
|
||||
return null
|
||||
}
|
||||
return BackupPreview(
|
||||
noteCount = file.notes.size,
|
||||
attachmentCount = file.notes.sumOf { it.attachments.size },
|
||||
appVersion = file.appVersion,
|
||||
exportedAt = file.exportedAt,
|
||||
)
|
||||
}
|
||||
|
||||
/** Decrypt-if-encrypted / pass-through-if-plain, shared by import + preview. */
|
||||
private fun payloadJson(bytes: ByteArray, passphrase: CharArray?): String {
|
||||
if (!EncryptedBackupCodec.isEncrypted(bytes)) return String(bytes, Charsets.UTF_8)
|
||||
val pass = passphrase
|
||||
?: throw IllegalArgumentException("Encrypted backup requires a passphrase")
|
||||
return EncryptedBackupCodec.decrypt(bytes, pass)
|
||||
}
|
||||
|
||||
/**
|
||||
* M2 task 3 dedupe key: `(createdAt, updatedAt, sha256(content))`.
|
||||
* Every component survives export/import on both platforms, and the
|
||||
* timestamps are only trustworthy for dedupe because the repository
|
||||
* now honours caller-supplied values (M2 import-timestamp fix).
|
||||
* NUL-separated so distinct field splits can never collide; the
|
||||
* content rides as a SHA-256 digest to keep the compared set cheap.
|
||||
*/
|
||||
private fun keyFor(createdAt: Long, updatedAt: Long, content: String): String {
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256")
|
||||
.digest(content.toByteArray(Charsets.UTF_8))
|
||||
val hex = digest.joinToString("") { "%02x".format(it) }
|
||||
return "$createdAt\u0000$updatedAt\u0000$hex"
|
||||
}
|
||||
}
|
||||
|
||||
/** Outcome of [BackupBridge.import] — what a duplicate-safe import did. */
|
||||
data class ImportSummary(val imported: Int, val skipped: Int)
|
||||
|
||||
/** Lightweight DTO shown in the import confirmation dialog. */
|
||||
data class BackupPreview(
|
||||
val noteCount: Int,
|
||||
val attachmentCount: Int,
|
||||
val appVersion: String,
|
||||
val exportedAt: Long,
|
||||
)
|
||||
|
||||
@@ -6,6 +6,7 @@ import kotlinx.serialization.json.Json
|
||||
import org.incido.domain.model.Note
|
||||
import org.incido.domain.model.NoteAttachment
|
||||
import org.incido.domain.model.NoteColor
|
||||
import org.incido.domain.model.NoteType
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
|
||||
/**
|
||||
@@ -37,9 +38,11 @@ object BackupCodec {
|
||||
appVersion: String,
|
||||
): BackupFile {
|
||||
// The repository exposes Flows; we materialise a one-shot
|
||||
// snapshot via `.first()`. Notes come from `observeAll`, tags
|
||||
// from `observeAllHashtags`.
|
||||
val noteList: List<Note> = repository.observeAll().first()
|
||||
// snapshot via `.first()`. Notes come from `observeAllIncludingTrashed`,
|
||||
// tags from `observeAllHashtags`.
|
||||
// Backup includes active and trashed notes so a soft-deleted note
|
||||
// can be restored after a device migration as well.
|
||||
val noteList: List<Note> = repository.observeAllIncludingTrashed().first()
|
||||
val tagList: List<String> = repository.observeAllHashtags().first()
|
||||
|
||||
// NoteAttachment.bytes is loaded on demand via
|
||||
@@ -90,6 +93,9 @@ object BackupCodec {
|
||||
bytes = decodeBase64(ba.bytesBase64),
|
||||
mimeType = ba.mimeType,
|
||||
displayName = ba.displayName,
|
||||
// Restore the phone's attachment timestamp (M2:
|
||||
// everything import claims to preserve must survive).
|
||||
createdAt = ba.createdAt,
|
||||
)
|
||||
}
|
||||
onProgress(idx + 1, total)
|
||||
@@ -121,6 +127,16 @@ data class BackupNote(
|
||||
val color: String,
|
||||
val hashtags: List<String> = emptyList(),
|
||||
val attachments: List<BackupAttachment> = emptyList(),
|
||||
/** Preserve soft-delete state; defaults to false for older backups. */
|
||||
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
|
||||
@@ -151,6 +167,9 @@ private suspend fun Note.toBackup(repository: NoteRepository): BackupNote {
|
||||
updatedAt = updatedAt,
|
||||
isFavorite = isFavorite,
|
||||
color = color.name,
|
||||
isTrashed = isTrashed,
|
||||
isDraft = isDraft,
|
||||
noteType = type.name,
|
||||
hashtags = hashtags,
|
||||
attachments = backups,
|
||||
)
|
||||
@@ -166,6 +185,9 @@ private fun Note.toBackup(): BackupNote = BackupNote(
|
||||
updatedAt = updatedAt,
|
||||
isFavorite = isFavorite,
|
||||
color = color.name,
|
||||
isTrashed = isTrashed,
|
||||
isDraft = isDraft,
|
||||
noteType = type.name,
|
||||
hashtags = hashtags,
|
||||
attachments = emptyList(),
|
||||
)
|
||||
@@ -177,6 +199,9 @@ private fun BackupNote.toDomain(): Note = Note(
|
||||
updatedAt = updatedAt,
|
||||
isFavorite = isFavorite,
|
||||
color = runCatching { NoteColor.valueOf(color) }.getOrDefault(NoteColor.NONE),
|
||||
isTrashed = isTrashed,
|
||||
isDraft = isDraft,
|
||||
type = runCatching { NoteType.valueOf(noteType) }.getOrDefault(NoteType.TEXT),
|
||||
hashtags = hashtags,
|
||||
// Attachments are inserted separately by importSnapshot so they
|
||||
// get assigned to the freshly-created note id.
|
||||
@@ -0,0 +1,143 @@
|
||||
// core/data-jvm — the DESKTOP build of the same data layer the Android app
|
||||
// compiles (Development Plan §6, Phase 1 milestone M1a).
|
||||
//
|
||||
// Shape: sibling JVM module sharing :core:data's platform-neutral sources,
|
||||
// NOT one multiplatform module. Two reasons, both proven in the Phase-0
|
||||
// spike (tools/DESKTOP_FEASIBILITY.md):
|
||||
// 1. ObjectBox's generator cannot read Kotlin common code, so entities have
|
||||
// to be compiled per-target anyway.
|
||||
// 2. objectbox-android and objectbox-java ship the same io.objectbox.*
|
||||
// classes; keeping them in separate modules is what stops a duplicate
|
||||
// classpath clash. Each module runs its own codegen and gets its own
|
||||
// MyObjectBox.
|
||||
// The shared model file is copied to objectbox-models/, and regenerating in a
|
||||
// second module reports "ID model file unchanged" — no UID churn.
|
||||
|
||||
// The ObjectBox Gradle plugin publishes no plugin marker (same reason
|
||||
// :core/data/build.gradle.kts wires it through a buildscript classpath).
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath("io.objectbox:objectbox-gradle-plugin:${libs.versions.objectbox.get()}")
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.kotlinJvm)
|
||||
}
|
||||
|
||||
// SPIKE FINDING: `alias(libs.plugins.kotlinKapt)` fails here ("plugin is
|
||||
// already on the classpath with an unknown version") because the root build
|
||||
// already loads the Kotlin Gradle Plugin, which ships kapt. Applying by id
|
||||
// reuses that copy.
|
||||
apply(plugin = "org.jetbrains.kotlin.kapt")
|
||||
apply(plugin = "io.objectbox")
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
main {
|
||||
kotlin.setSrcDirs(
|
||||
listOf(
|
||||
"build/generated/source/objectbox",
|
||||
"src/main/kotlin",
|
||||
// The platform-neutral data layer, compiled from :core:data's
|
||||
// directory. Nothing in here may import android.*.
|
||||
"../data/src/main/kotlin",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api(project(":core:domain"))
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
|
||||
// Phase 1 (M2): the backup bridge, for the backupSmoke round-trip probe.
|
||||
// No classpath risk here — :core:backup carries no ObjectBox at all.
|
||||
implementation(project(":core:backup"))
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
|
||||
// Phase 1 (M4.4e): EXIF orientation for the JVM normalizer — the
|
||||
// desktop counterpart of androidx.exifinterface that :core:data's
|
||||
// Android side uses (§6.3 EXIF row: "not cached, Maven Central
|
||||
// reachable" — pulled once here).
|
||||
implementation(libs.metadata.extractor)
|
||||
|
||||
// JVM counterparts of the objectbox-android the Android build uses.
|
||||
implementation(libs.objectbox.java)
|
||||
implementation(libs.objectbox.kotlin)
|
||||
|
||||
// Native database library for the build/host OS. Declared explicitly so a
|
||||
// packaged desktop app knows what it must bundle (objectbox-macos /
|
||||
// objectbox-windows on other platforms).
|
||||
runtimeOnly(libs.objectbox.linux)
|
||||
}
|
||||
|
||||
/**
|
||||
* `./gradlew :core:data-jvm:smoke` — boots the shared data layer against a
|
||||
* real ObjectBox store on the JVM and round-trips a note. Temporary until
|
||||
* :desktopApp provides the real entry point (Phase 1, M1b).
|
||||
*/
|
||||
tasks.register<JavaExec>("smoke") {
|
||||
group = "verification"
|
||||
description = "Opens a JVM ObjectBox store through the shared data layer."
|
||||
classpath = sourceSets["main"].runtimeClasspath
|
||||
mainClass.set("org.incido.data.jvm.StoreSmokeKt")
|
||||
val smokeDir = layout.buildDirectory.dir("data-jvm-smoke").get().asFile
|
||||
args = listOf(smokeDir.absolutePath)
|
||||
// The probe asserts exact note counts, so it needs a virgin library —
|
||||
// wipe the directory here to keep `smoke` idempotent across runs.
|
||||
doFirst { smokeDir.deleteRecursively() }
|
||||
}
|
||||
|
||||
/**
|
||||
* `./gradlew :core:data-jvm:orientationSmoke` — Phase 1 (M4.4e): feeds a
|
||||
* hand-crafted EXIF-Orientation-90 JPEG through JvmImageOrientationNormalizer
|
||||
* and checks the rotation is baked into the pixels (Android contract kept).
|
||||
*/
|
||||
tasks.register<JavaExec>("orientationSmoke") {
|
||||
group = "verification"
|
||||
description = "Proves EXIF orientation handling on the JVM."
|
||||
classpath = sourceSets["main"].runtimeClasspath
|
||||
mainClass.set("org.incido.data.jvm.OrientationSmokeKt")
|
||||
}
|
||||
|
||||
/**
|
||||
* `./gradlew :core:data-jvm:backupSmoke --args="<backup.incido.json> [libDir]"`
|
||||
* — feeds a REAL Android backup file through the :core:backup bridge on the
|
||||
* JVM: preview, import into a fresh library, re-export and compare, then the
|
||||
* encrypted-envelope path (including wrong-passphrase rejection). Runs
|
||||
* against a fresh library every time (the script deletes libDir first).
|
||||
*/
|
||||
tasks.register<JavaExec>("backupSmoke") {
|
||||
group = "verification"
|
||||
description = "Round-trips a real Android backup export through BackupBridge on the JVM."
|
||||
classpath = sourceSets["main"].runtimeClasspath
|
||||
mainClass.set("org.incido.data.jvm.BackupRoundTripKt")
|
||||
}
|
||||
|
||||
/**
|
||||
* `./gradlew :core:data-jvm:backupMemory` — synthesizes worst-case
|
||||
* libraries and samples heap peak during BackupBridge.exportPlain
|
||||
* (Phase 1, M2 task 5: measure & record, no redesign). Needs a bigger
|
||||
* heap than the other probes on purpose — the "watch tier" is ~320 MB of
|
||||
* attachments and the bridge holds the whole JSON in memory by design.
|
||||
*/
|
||||
tasks.register<JavaExec>("backupMemory") {
|
||||
group = "verification"
|
||||
description = "Measures export heap peaks on synthesized worst-case libraries (M2 t5)."
|
||||
classpath = sourceSets["main"].runtimeClasspath
|
||||
mainClass.set("org.incido.data.jvm.BackupMemoryProbeKt")
|
||||
maxHeapSize = "2g"
|
||||
}
|
||||