Compare commits
39
Commits
f87ca17ded
...
7e0b4b0380
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e0b4b0380 | ||
|
|
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 |
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... ]
|
||||||
+10
-3
@@ -24,9 +24,16 @@ captures/
|
|||||||
# Kotlin
|
# Kotlin
|
||||||
.kotlin/
|
.kotlin/
|
||||||
|
|
||||||
# ObjectBox generated models (kept under build, but ignore if moved out)
|
# ObjectBox generated models. The *model file itself* is the schema
|
||||||
**/objectbox-models/
|
# contract — UIDs in it must stay stable across machines and across the two
|
||||||
**/objectbox-models/default.json
|
# 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
|
# VS Code
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
@@ -198,6 +198,10 @@ dependencies {
|
|||||||
// viewer + the list card thumbnails). It's the *interface* in
|
// viewer + the list card thumbnails). It's the *interface* in
|
||||||
// :core:domain, not the impl, so this stays clean of ObjectBox.
|
// :core:domain, not the impl, so this stays clean of ObjectBox.
|
||||||
implementation(project(":core:domain"))
|
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.androidx.core.ktx)
|
||||||
implementation(libs.kotlinx.coroutines.android)
|
implementation(libs.kotlinx.coroutines.android)
|
||||||
// v0.3.2.0: MainActivity now extends FragmentActivity so the
|
// v0.3.2.0: MainActivity now extends FragmentActivity so the
|
||||||
|
|||||||
@@ -6,6 +6,12 @@ plugins {
|
|||||||
alias(libs.plugins.androidLibrary) apply false
|
alias(libs.plugins.androidLibrary) apply false
|
||||||
alias(libs.plugins.kotlinAndroid) apply false
|
alias(libs.plugins.kotlinAndroid) apply false
|
||||||
alias(libs.plugins.kotlinJvm) 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.kotlinCompose) apply false
|
||||||
alias(libs.plugins.ksp) apply false
|
alias(libs.plugins.ksp) apply false
|
||||||
}
|
}
|
||||||
+137
-45
@@ -1,16 +1,139 @@
|
|||||||
// composeApp — Android UI module hosting all screens, ViewModels, theme,
|
// composeApp — Incido's UI module: all screens, ViewModels, theme,
|
||||||
// navigation, and the manual DI container. Regular Android Compose (not
|
// navigation, and the manual DI container.
|
||||||
// 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.
|
// 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 {
|
plugins {
|
||||||
alias(libs.plugins.androidLibrary)
|
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)
|
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)
|
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 {
|
android {
|
||||||
namespace = "org.incido.compose"
|
namespace = "org.incido.compose"
|
||||||
compileSdk = 35
|
compileSdk = 35
|
||||||
@@ -19,20 +142,15 @@ android {
|
|||||||
minSdk = 26
|
minSdk = 26
|
||||||
}
|
}
|
||||||
|
|
||||||
buildFeatures {
|
// M4.1: `buildFeatures.compose` is NOT set — the org.jetbrains.compose
|
||||||
compose = true
|
// plugin owns Compose wiring on this target (setting it here alongside
|
||||||
buildConfig = true
|
// the KMP plugin is the classic double-wire; see §3 trap 6's sibling).
|
||||||
}
|
|
||||||
|
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility = JavaVersion.VERSION_17
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
targetCompatibility = JavaVersion.VERSION_17
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
}
|
}
|
||||||
|
|
||||||
kotlin {
|
|
||||||
jvmToolchain(17)
|
|
||||||
}
|
|
||||||
|
|
||||||
packaging {
|
packaging {
|
||||||
resources {
|
resources {
|
||||||
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
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 {
|
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)
|
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
File renamed without changes.
@@ -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>()
|
||||||
+4
-2
@@ -8,8 +8,10 @@ import org.incido.compose.di.AppContainer
|
|||||||
* Application class. Constructs the singleton [AppContainer] holding the
|
* Application class. Constructs the singleton [AppContainer] holding the
|
||||||
* ObjectBox store and the note repository.
|
* ObjectBox store and the note repository.
|
||||||
*
|
*
|
||||||
* ViewModels reach the container via `(application as IncidoApplication).container`
|
* M4.3: the screens reach the container through `LocalAppGraph` (provided
|
||||||
* (see `NoteListViewModel.Factory` and `NoteEditorViewModel.factory`).
|
* 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
|
* v0.3.2.0 — initialises the [SecurityManager] lock state during
|
||||||
* `onCreate` so the first composition of the root Compose tree
|
* `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")
|
||||||
|
}
|
||||||
File renamed without changes.
+14
@@ -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)
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+22
@@ -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."
|
||||||
|
}
|
||||||
+42
-6
@@ -5,18 +5,24 @@ import io.objectbox.BoxStore
|
|||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import org.incido.data.AndroidImageOrientationNormalizer
|
||||||
import org.incido.data.ObjectBoxStore
|
import org.incido.data.ObjectBoxStore
|
||||||
|
import org.incido.data.crypto.AesGcmFieldCipher
|
||||||
import org.incido.data.crypto.CipherHolder
|
import org.incido.data.crypto.CipherHolder
|
||||||
|
import org.incido.data.crypto.EncryptionVerifier
|
||||||
import org.incido.data.crypto.NoteCryptoService
|
import org.incido.data.crypto.NoteCryptoService
|
||||||
import org.incido.data.repository.NoteRepositoryImpl
|
import org.incido.data.repository.NoteRepositoryImpl
|
||||||
import org.incido.domain.repository.NoteRepository
|
import org.incido.domain.repository.NoteRepository
|
||||||
import org.incido.compose.data.backup.BackupManager
|
import org.incido.compose.data.backup.BackupManager
|
||||||
import org.incido.compose.data.backup.CarnetImporter
|
import org.incido.compose.data.backup.CarnetImporter
|
||||||
import org.incido.compose.data.security.AesGcmFieldCipher
|
|
||||||
import org.incido.compose.data.security.EncryptionVerifier
|
|
||||||
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
||||||
import org.incido.compose.data.security.SecurityManager
|
import org.incido.compose.data.security.SecurityManager
|
||||||
import org.incido.compose.data.settings.SettingsRepository
|
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
|
* Hand-rolled DI container. Replaces Hilt/Dagger for v0.1 — keeps the
|
||||||
@@ -39,8 +45,14 @@ import org.incido.compose.data.settings.SettingsRepository
|
|||||||
* After startup the [encryptionVerifier] re-checks every encrypted row
|
* After startup the [encryptionVerifier] re-checks every encrypted row
|
||||||
* by trial-decrypting it; only rows that pass earn the "Encrypted"
|
* by trial-decrypting it; only rows that pass earn the "Encrypted"
|
||||||
* badge on the note cards.
|
* 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
|
private val appContext: Context = context.applicationContext
|
||||||
|
|
||||||
@@ -48,7 +60,11 @@ class AppContainer(context: Context) {
|
|||||||
* (verification sweeps, etc.). SupervisorJob isolates failures. */
|
* (verification sweeps, etc.). SupervisorJob isolates failures. */
|
||||||
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
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)
|
val objectBoxKeyProvider: ObjectBoxKeyProvider = ObjectBoxKeyProvider(appContext)
|
||||||
|
|
||||||
@@ -71,11 +87,19 @@ class AppContainer(context: Context) {
|
|||||||
init {
|
init {
|
||||||
val s = settingsRepository.snapshot()
|
val s = settingsRepository.snapshot()
|
||||||
if (s.isEncryptionActive && objectBoxKeyProvider.hasKeyBlocking()) {
|
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)
|
val backupManager: BackupManager = BackupManager(appContext, noteRepository)
|
||||||
|
|
||||||
@@ -89,6 +113,18 @@ class AppContainer(context: Context) {
|
|||||||
/** Runs on every app open — feeds the verified-encryption badge. */
|
/** Runs on every app open — feeds the verified-encryption badge. */
|
||||||
val encryptionVerifier = EncryptionVerifier(noteCryptoService, appScope)
|
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. */
|
/** Kick the startup verification off immediately. */
|
||||||
init {
|
init {
|
||||||
encryptionVerifier.checkNow()
|
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
|
||||||
File renamed without changes.
+312
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-5
@@ -56,7 +56,6 @@ import androidx.core.content.FileProvider
|
|||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import org.incido.compose.data.security.SecurityManager
|
|
||||||
import org.incido.domain.model.NoteAttachment
|
import org.incido.domain.model.NoteAttachment
|
||||||
import org.incido.domain.repository.NoteRepository
|
import org.incido.domain.repository.NoteRepository
|
||||||
import java.io.File
|
import java.io.File
|
||||||
@@ -102,7 +101,7 @@ fun VoiceNoteSection(
|
|||||||
/** Remove the current take (pending or persisted). */
|
/** Remove the current take (pending or persisted). */
|
||||||
onDeleteTake: () -> Unit,
|
onDeleteTake: () -> Unit,
|
||||||
/** Suppress auto-lock around the download share-sheet round-trip (API < 29). */
|
/** Suppress auto-lock around the download share-sheet round-trip (API < 29). */
|
||||||
securityManager: SecurityManager?,
|
beginExternalActivity: (() -> Unit)?,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
val ctx = LocalContext.current
|
val ctx = LocalContext.current
|
||||||
@@ -244,7 +243,7 @@ fun VoiceNoteSection(
|
|||||||
sourceKey = takeKey,
|
sourceKey = takeKey,
|
||||||
takeName = takeName,
|
takeName = takeName,
|
||||||
onDelete = onDeleteTake,
|
onDelete = onDeleteTake,
|
||||||
onDownload = { saveVoiceTakeToDevice(ctx, securityManager, takeName, takeMime, takeBytes) },
|
onDownload = { saveVoiceTakeToDevice(ctx, beginExternalActivity, takeName, takeMime, takeBytes) },
|
||||||
onRecordAgain = { startRecording() },
|
onRecordAgain = { startRecording() },
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -465,7 +464,7 @@ private fun VoicePlayerBar(
|
|||||||
*/
|
*/
|
||||||
private fun saveVoiceTakeToDevice(
|
private fun saveVoiceTakeToDevice(
|
||||||
ctx: Context,
|
ctx: Context,
|
||||||
securityManager: SecurityManager?,
|
beginExternalActivity: (() -> Unit)?,
|
||||||
displayName: String,
|
displayName: String,
|
||||||
mimeType: String,
|
mimeType: String,
|
||||||
bytes: ByteArray,
|
bytes: ByteArray,
|
||||||
@@ -513,7 +512,7 @@ private fun saveVoiceTakeToDevice(
|
|||||||
}
|
}
|
||||||
// Auto-Lock = Immediate must not fire while the chooser is up
|
// Auto-Lock = Immediate must not fire while the chooser is up
|
||||||
// (same v0.3.4.0 hotfix as the attachment viewer).
|
// (same v0.3.4.0 hotfix as the attachment viewer).
|
||||||
securityManager?.beginExternalActivity()
|
beginExternalActivity?.invoke()
|
||||||
ctx.startActivity(Intent.createChooser(send, "Save recording"))
|
ctx.startActivity(Intent.createChooser(send, "Save recording"))
|
||||||
}.onFailure {
|
}.onFailure {
|
||||||
Toast.makeText(ctx, "Couldn't save recording", Toast.LENGTH_SHORT).show()
|
Toast.makeText(ctx, "Couldn't save recording", Toast.LENGTH_SHORT).show()
|
||||||
File renamed without changes.
+9
-196
@@ -52,6 +52,7 @@ import kotlinx.coroutines.launch
|
|||||||
import org.incido.compose.data.backup.BackupPreview
|
import org.incido.compose.data.backup.BackupPreview
|
||||||
import org.incido.compose.data.backup.EncryptedBackupCodec
|
import org.incido.compose.data.backup.EncryptedBackupCodec
|
||||||
import org.incido.compose.data.security.SecurityManager
|
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.AutoLockTimeout
|
||||||
import org.incido.compose.data.settings.ThemeMode
|
import org.incido.compose.data.settings.ThemeMode
|
||||||
|
|
||||||
@@ -93,7 +94,7 @@ fun SettingsScreen(
|
|||||||
* suppression (the pre-0.3.4.0 behaviour).
|
* suppression (the pre-0.3.4.0 behaviour).
|
||||||
*/
|
*/
|
||||||
securityManager: SecurityManager? = null,
|
securityManager: SecurityManager? = null,
|
||||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
|
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
|
||||||
) {
|
) {
|
||||||
val settings by viewModel.userSettings.collectAsStateWithLifecycle()
|
val settings by viewModel.userSettings.collectAsStateWithLifecycle()
|
||||||
val migrationState by viewModel.migrationState.collectAsStateWithLifecycle()
|
val migrationState by viewModel.migrationState.collectAsStateWithLifecycle()
|
||||||
@@ -410,6 +411,13 @@ fun SettingsScreen(
|
|||||||
// the app.
|
// the app.
|
||||||
pendingImportPassphrase = chars.copyOf()
|
pendingImportPassphrase = chars.copyOf()
|
||||||
if (importUri != null) {
|
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 {
|
scope.launch {
|
||||||
// `chars` is consumed (zeroed) by the
|
// `chars` is consumed (zeroed) by the
|
||||||
// decrypt step; the retained copy survives.
|
// decrypt step; the retained copy survives.
|
||||||
@@ -659,55 +667,6 @@ private var pendingPassphraseMode: PassphraseDialogMode = PassphraseDialogMode.E
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@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
|
* v0.3.3.0: PIN and Biometric are mutually-exclusive toggles. When
|
||||||
* the master security switch is off, both are greyed. When one is
|
* the master security switch is off, both are greyed. When one is
|
||||||
@@ -836,152 +795,6 @@ private fun SecuritySection(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun BackupSection(
|
|
||||||
onExport: () -> Unit,
|
|
||||||
onImport: () -> Unit,
|
|
||||||
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…")
|
|
||||||
}
|
|
||||||
OutlinedButton(onClick = onImportCarnet, modifier = Modifier.fillMaxWidth()) {
|
|
||||||
Text("Import 3rd Party Notes")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@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
|
@Composable
|
||||||
private fun TimeoutDialog(
|
private fun TimeoutDialog(
|
||||||
+23
-11
@@ -2,7 +2,6 @@ package org.incido.compose.ui.settings
|
|||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.ViewModelProvider
|
import androidx.lifecycle.ViewModelProvider
|
||||||
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
|
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import androidx.lifecycle.viewmodel.initializer
|
import androidx.lifecycle.viewmodel.initializer
|
||||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||||
@@ -12,14 +11,14 @@ import kotlinx.coroutines.flow.StateFlow
|
|||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
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.backup.BackupManager
|
||||||
import org.incido.compose.data.backup.CarnetImporter
|
import org.incido.compose.data.backup.CarnetImporter
|
||||||
import org.incido.compose.data.security.AesGcmFieldCipher
|
|
||||||
import org.incido.compose.data.security.EncryptionVerifier
|
|
||||||
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
||||||
import org.incido.compose.data.security.SecurityManager
|
import org.incido.compose.data.security.SecurityManager
|
||||||
|
import org.incido.data.crypto.AesGcmFieldCipher
|
||||||
import org.incido.data.crypto.CipherHolder
|
import org.incido.data.crypto.CipherHolder
|
||||||
|
import org.incido.data.crypto.EncryptionVerifier
|
||||||
import org.incido.data.crypto.NoteCryptoService
|
import org.incido.data.crypto.NoteCryptoService
|
||||||
import org.incido.compose.data.settings.AutoLockTimeout
|
import org.incido.compose.data.settings.AutoLockTimeout
|
||||||
import org.incido.compose.data.settings.SettingsRepository
|
import org.incido.compose.data.settings.SettingsRepository
|
||||||
@@ -141,7 +140,8 @@ class SettingsViewModel(
|
|||||||
if (enabled) {
|
if (enabled) {
|
||||||
// Key first (idempotent), cipher into the holder, sweep.
|
// Key first (idempotent), cipher into the holder, sweep.
|
||||||
objectBoxKeyProvider.getOrCreateKey()
|
objectBoxKeyProvider.getOrCreateKey()
|
||||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
|
cipherHolder.cipher =
|
||||||
|
AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
|
||||||
noteCryptoService.encryptAllInPlace { done, total ->
|
noteCryptoService.encryptAllInPlace { done, total ->
|
||||||
_migrationState.value = MigrationState.Running(
|
_migrationState.value = MigrationState.Running(
|
||||||
if (total == 0) 1f else done.toFloat() / total,
|
if (total == 0) 1f else done.toFloat() / total,
|
||||||
@@ -243,8 +243,12 @@ class SettingsViewModel(
|
|||||||
backupManager.preview(uri, passphrase)
|
backupManager.preview(uri, passphrase)
|
||||||
|
|
||||||
suspend fun import(uri: android.net.Uri, passphrase: CharArray? = null) {
|
suspend fun import(uri: android.net.Uri, passphrase: CharArray? = null) {
|
||||||
val count = backupManager.import(uri, passphrase)
|
val result = backupManager.import(uri, passphrase)
|
||||||
_snackbar.value = "Imported $count note(s)."
|
_snackbar.value = if (result.skipped > 0) {
|
||||||
|
"Imported ${result.imported} note(s), skipped ${result.skipped} already imported."
|
||||||
|
} else {
|
||||||
|
"Imported ${result.imported} note(s)."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -316,7 +320,8 @@ class SettingsViewModel(
|
|||||||
// Swap the live cipher to point at the freshly-installed key.
|
// Swap the live cipher to point at the freshly-installed key.
|
||||||
// We build a new wrapper that re-reads the (just-persisted)
|
// We build a new wrapper that re-reads the (just-persisted)
|
||||||
// wrapped blob — no need to re-implement the unwrap here.
|
// wrapped blob — no need to re-implement the unwrap here.
|
||||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
|
cipherHolder.cipher =
|
||||||
|
AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
|
||||||
encryptionVerifier.checkNow()
|
encryptionVerifier.checkNow()
|
||||||
_snackbar.value = if (overwroteExisting) {
|
_snackbar.value = if (overwroteExisting) {
|
||||||
"Recovery key installed. Previously-encrypted notes will appear as unverified."
|
"Recovery key installed. Previously-encrypted notes will appear as unverified."
|
||||||
@@ -356,10 +361,17 @@ class SettingsViewModel(
|
|||||||
* — if you bump one, bump both. */
|
* — if you bump one, bump both. */
|
||||||
const val APP_VERSION = "0.4.2.0"
|
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 {
|
initializer {
|
||||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
val c = container
|
||||||
val c = app.container
|
|
||||||
SettingsViewModel(
|
SettingsViewModel(
|
||||||
settings = c.settingsRepository,
|
settings = c.settingsRepository,
|
||||||
security = c.securityManager,
|
security = c.securityManager,
|
||||||
+3
-2
@@ -40,6 +40,7 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import org.incido.compose.di.requireAndroidContainer
|
||||||
import org.incido.compose.ui.settings.SettingsViewModel
|
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
|
* stored hash + salt. The screen pops on success and surfaces a
|
||||||
* "PIN updated." snackbar via the existing viewModel.snackbar flow.
|
* "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
|
* doesn't need its own ViewModel because every operation goes through
|
||||||
* the existing security manager.
|
* the existing security manager.
|
||||||
*/
|
*/
|
||||||
@@ -66,7 +67,7 @@ import org.incido.compose.ui.settings.SettingsViewModel
|
|||||||
fun PinChangeScreen(
|
fun PinChangeScreen(
|
||||||
onDone: () -> Unit,
|
onDone: () -> Unit,
|
||||||
onCancel: () -> Unit,
|
onCancel: () -> Unit,
|
||||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
|
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
|
||||||
) {
|
) {
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
var step by remember { mutableStateOf(Step.VerifyOld) }
|
var step by remember { mutableStateOf(Step.VerifyOld) }
|
||||||
File renamed without changes.
+2
-1
@@ -36,6 +36,7 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import org.incido.compose.di.requireAndroidContainer
|
||||||
import org.incido.compose.ui.settings.SettingsViewModel
|
import org.incido.compose.ui.settings.SettingsViewModel
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,7 +61,7 @@ import org.incido.compose.ui.settings.SettingsViewModel
|
|||||||
fun PinSetupScreen(
|
fun PinSetupScreen(
|
||||||
onDone: () -> Unit,
|
onDone: () -> Unit,
|
||||||
onCancel: () -> Unit,
|
onCancel: () -> Unit,
|
||||||
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
|
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
|
||||||
) {
|
) {
|
||||||
val scope = rememberCoroutineScope()
|
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()
|
||||||
+11
-5
@@ -1,7 +1,6 @@
|
|||||||
package org.incido.compose.data.backup
|
package org.incido.compose.data.backup
|
||||||
|
|
||||||
import org.incido.compose.data.settings.PasswordPolicy
|
import org.incido.compose.data.settings.PasswordPolicy
|
||||||
import java.security.SecureRandom
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* v0.3.2.0: SecureRandom-based passphrase generator for encrypted
|
* 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
|
* If a freshly-generated passphrase fails validation (rare — only if
|
||||||
* the random draw happens to miss both a digit and a special) we
|
* the random draw happens to miss both a digit and a special) we
|
||||||
* regenerate, so the return type is non-nullable.
|
* 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 {
|
object PassphraseGenerator {
|
||||||
|
|
||||||
@@ -33,8 +38,6 @@ object PassphraseGenerator {
|
|||||||
PasswordPolicy.SPECIAL_CHARS
|
PasswordPolicy.SPECIAL_CHARS
|
||||||
).toCharArray()
|
).toCharArray()
|
||||||
|
|
||||||
private val secureRandom = SecureRandom()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate a passphrase of [length] characters (clamped to the
|
* Generate a passphrase of [length] characters (clamped to the
|
||||||
* policy's [PasswordPolicy.MIN_LENGTH] / [PasswordPolicy.MAX_LENGTH]
|
* 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
|
// and a special in any draw of >= 12 chars. Fall back to a
|
||||||
// hand-crafted compliant value so we never throw from a UI
|
// hand-crafted compliant value so we never throw from a UI
|
||||||
// button tap.
|
// 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 {
|
private fun buildRandom(length: Int): String {
|
||||||
val out = StringBuilder(length)
|
val out = StringBuilder(length)
|
||||||
repeat(length) { out.append(ALPHABET[secureRandom.nextInt(ALPHABET.size)]) }
|
repeat(length) { out.append(ALPHABET[secureRandomInt(ALPHABET.size)]) }
|
||||||
return out.toString()
|
return out.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val MAX_ATTEMPTS = 16
|
private const val MAX_ATTEMPTS = 16
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** CSPRNG draw in `[0, bound)` — SecureRandom on every target. */
|
||||||
|
internal expect fun secureRandomInt(bound: Int): Int
|
||||||
File renamed without changes.
File renamed without changes.
@@ -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
|
||||||
File renamed without changes.
+9
-7
@@ -2,14 +2,13 @@ package org.incido.compose.ui.drawer
|
|||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.ViewModelProvider
|
import androidx.lifecycle.ViewModelProvider
|
||||||
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
|
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import androidx.lifecycle.viewmodel.initializer
|
import androidx.lifecycle.viewmodel.initializer
|
||||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.stateIn
|
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.model.HashtagUsage
|
||||||
import org.incido.domain.repository.NoteRepository
|
import org.incido.domain.repository.NoteRepository
|
||||||
|
|
||||||
@@ -18,6 +17,12 @@ import org.incido.domain.repository.NoteRepository
|
|||||||
* tags" list. Kept separate from [NoteListViewModel] because the
|
* tags" list. Kept separate from [NoteListViewModel] because the
|
||||||
* drawer may render even before the list screen is created (and
|
* drawer may render even before the list screen is created (and
|
||||||
* vice-versa).
|
* 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(
|
class DrawerViewModel(
|
||||||
repository: NoteRepository,
|
repository: NoteRepository,
|
||||||
@@ -32,11 +37,8 @@ class DrawerViewModel(
|
|||||||
)
|
)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val Factory: ViewModelProvider.Factory = viewModelFactory {
|
fun factory(graph: AppGraph): ViewModelProvider.Factory = viewModelFactory {
|
||||||
initializer {
|
initializer { DrawerViewModel(graph.noteRepository) }
|
||||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
|
||||||
DrawerViewModel(app.container.noteRepository)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-1
@@ -42,6 +42,7 @@ import androidx.compose.ui.text.font.FontWeight
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import org.incido.compose.di.requireAppGraph
|
||||||
import org.incido.compose.ui.theme.AllNoteColors
|
import org.incido.compose.ui.theme.AllNoteColors
|
||||||
import org.incido.compose.ui.theme.toComposeColor
|
import org.incido.compose.ui.theme.toComposeColor
|
||||||
import org.incido.domain.model.HashtagUsage
|
import org.incido.domain.model.HashtagUsage
|
||||||
@@ -78,7 +79,7 @@ fun IncidoDrawer(
|
|||||||
onSelectFilter: (NoteFilter) -> Unit,
|
onSelectFilter: (NoteFilter) -> Unit,
|
||||||
onOpenSettings: () -> Unit,
|
onOpenSettings: () -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.Factory),
|
viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.factory(requireAppGraph())),
|
||||||
) {
|
) {
|
||||||
val recent by viewModel.recentHashtags.collectAsStateWithLifecycle()
|
val recent by viewModel.recentHashtags.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
@@ -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,
|
||||||
|
)
|
||||||
+8
-8
@@ -26,7 +26,7 @@ import androidx.compose.runtime.setValue
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
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.graphics.graphicsLayer
|
||||||
import androidx.compose.ui.input.pointer.pointerInput
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
import androidx.compose.ui.layout.ContentScale
|
import androidx.compose.ui.layout.ContentScale
|
||||||
@@ -34,9 +34,9 @@ import androidx.compose.ui.text.font.FontWeight
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.window.Dialog
|
import androidx.compose.ui.window.Dialog
|
||||||
import androidx.compose.ui.window.DialogProperties
|
import androidx.compose.ui.window.DialogProperties
|
||||||
import android.graphics.BitmapFactory
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import org.incido.compose.di.ioDispatcher
|
||||||
|
import org.incido.compose.util.decodeImageBytes
|
||||||
import org.incido.domain.repository.NoteRepository
|
import org.incido.domain.repository.NoteRepository
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -91,10 +91,10 @@ fun ImageViewerScreen(
|
|||||||
// Decode the image (or display an error message when the
|
// Decode the image (or display an error message when the
|
||||||
// bytes can't be loaded / decoded).
|
// bytes can't be loaded / decoded).
|
||||||
var loadFailed by remember { mutableStateOf(false) }
|
var loadFailed by remember { mutableStateOf(false) }
|
||||||
val bitmap by produceState<android.graphics.Bitmap?>(initialValue = null, key1 = attachmentId) {
|
val bitmap by produceState<ImageBitmap?>(initialValue = null, key1 = attachmentId) {
|
||||||
loadFailed = false
|
loadFailed = false
|
||||||
val bytes: ByteArray? = when (attachmentId) {
|
val bytes: ByteArray? = when (attachmentId) {
|
||||||
is ViewerAttachmentId.Persisted -> withContext(Dispatchers.IO) {
|
is ViewerAttachmentId.Persisted -> withContext(ioDispatcher) {
|
||||||
repository.getAttachmentBytes(attachmentId.id)
|
repository.getAttachmentBytes(attachmentId.id)
|
||||||
}
|
}
|
||||||
is ViewerAttachmentId.Pending -> pendingBytes
|
is ViewerAttachmentId.Pending -> pendingBytes
|
||||||
@@ -103,8 +103,8 @@ fun ImageViewerScreen(
|
|||||||
loadFailed = true
|
loadFailed = true
|
||||||
return@produceState
|
return@produceState
|
||||||
}
|
}
|
||||||
val decoded = withContext(Dispatchers.IO) {
|
val decoded = withContext(ioDispatcher) {
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
decodeImageBytes(bytes)
|
||||||
}
|
}
|
||||||
value = decoded
|
value = decoded
|
||||||
if (decoded == null) loadFailed = true
|
if (decoded == null) loadFailed = true
|
||||||
@@ -112,7 +112,7 @@ fun ImageViewerScreen(
|
|||||||
|
|
||||||
if (bitmap != null) {
|
if (bitmap != null) {
|
||||||
Image(
|
Image(
|
||||||
bitmap = bitmap!!.asImageBitmap(),
|
bitmap = bitmap!!,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
contentScale = ContentScale.Fit,
|
contentScale = ContentScale.Fit,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
+76
-269
@@ -1,14 +1,5 @@
|
|||||||
package org.incido.compose.ui.editor
|
package org.incido.compose.ui.editor
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.graphics.BitmapFactory
|
|
||||||
import android.net.Uri
|
|
||||||
import android.widget.Toast
|
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
@@ -98,10 +89,8 @@ import androidx.compose.ui.geometry.Offset
|
|||||||
import androidx.compose.ui.geometry.Size
|
import androidx.compose.ui.geometry.Size
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.SolidColor
|
import androidx.compose.ui.graphics.SolidColor
|
||||||
import androidx.compose.ui.graphics.asImageBitmap
|
|
||||||
import androidx.compose.ui.graphics.painter.BitmapPainter
|
import androidx.compose.ui.graphics.painter.BitmapPainter
|
||||||
import androidx.compose.ui.layout.ContentScale
|
import androidx.compose.ui.layout.ContentScale
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
@@ -109,14 +98,14 @@ import androidx.compose.ui.text.style.TextOverflow
|
|||||||
import androidx.compose.ui.text.TextStyle
|
import androidx.compose.ui.text.TextStyle
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import androidx.core.content.FileProvider
|
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import org.incido.compose.data.security.SecurityManager
|
import org.incido.compose.di.ioDispatcher
|
||||||
|
import org.incido.compose.di.requireAppGraph
|
||||||
|
import org.incido.compose.util.PlatformBackHandler
|
||||||
|
import org.incido.compose.util.decodeImageBytes
|
||||||
import org.incido.compose.ui.theme.AllNoteColors
|
import org.incido.compose.ui.theme.AllNoteColors
|
||||||
import org.incido.compose.ui.theme.swatchBorderColor
|
import org.incido.compose.ui.theme.swatchBorderColor
|
||||||
import org.incido.compose.ui.theme.toComposeColor
|
import org.incido.compose.ui.theme.toComposeColor
|
||||||
@@ -125,7 +114,6 @@ import org.incido.domain.model.Hashtag
|
|||||||
import org.incido.domain.model.Note
|
import org.incido.domain.model.Note
|
||||||
import org.incido.domain.model.NoteColor
|
import org.incido.domain.model.NoteColor
|
||||||
import org.incido.domain.model.NoteType
|
import org.incido.domain.model.NoteType
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -146,10 +134,16 @@ fun NoteEditorScreen(
|
|||||||
* inside an external activity we launched (file picker, camera,
|
* inside an external activity we launched (file picker, camera,
|
||||||
* system attachment viewer). Null disables the suppression (the
|
* system attachment viewer). Null disables the suppression (the
|
||||||
* pre-0.3.4.0 behaviour).
|
* pre-0.3.4.0 behaviour).
|
||||||
|
*
|
||||||
|
* M4.4c: was `securityManager: SecurityManager?` — the Android type
|
||||||
|
* cannot be named in commonMain and the editor only ever used
|
||||||
|
* beginExternalActivity(), so the parameter became this neutral
|
||||||
|
* lambda; App.kt passes `{ securityManager?.beginExternalActivity() }`.
|
||||||
*/
|
*/
|
||||||
securityManager: SecurityManager? = null,
|
beginExternalActivity: (() -> Unit)? = null,
|
||||||
viewModel: NoteEditorViewModel = viewModel(
|
viewModel: NoteEditorViewModel = viewModel(
|
||||||
factory = NoteEditorViewModel.factory(
|
factory = NoteEditorViewModel.factory(
|
||||||
|
graph = requireAppGraph(),
|
||||||
noteId = noteId,
|
noteId = noteId,
|
||||||
initialSharedText = initialSharedText,
|
initialSharedText = initialSharedText,
|
||||||
initialSharedImages = initialSharedImages,
|
initialSharedImages = initialSharedImages,
|
||||||
@@ -164,123 +158,19 @@ fun NoteEditorScreen(
|
|||||||
var showDiscardDialog by rememberSaveable { mutableStateOf(false) }
|
var showDiscardDialog by rememberSaveable { mutableStateOf(false) }
|
||||||
val snackbarHost = remember { SnackbarHostState() }
|
val snackbarHost = remember { SnackbarHostState() }
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val ctx = LocalContext.current
|
// M4.4c: camera capture, file picking, the mic-permission dance and
|
||||||
|
// open-this-attachment-elsewhere now live behind the intake seam —
|
||||||
// v0.3.1.0: camera permission + capture. The camera launcher is
|
// the Android actual is the verbatim launcher code that used to sit
|
||||||
// declared FIRST so the permission callback (below) can forward to it
|
// here, the JVM actual answers with AWT dialogs and hides
|
||||||
// without a Kotlin forward-reference error.
|
// camera/voice (S6.5). See EditorIntake.kt.
|
||||||
var pendingCameraUri by remember { mutableStateOf<Uri?>(null) }
|
val intake = rememberEditorIntake(
|
||||||
val cameraLauncher = rememberLauncherForActivityResult(
|
onPickedBytes = { bytes, mimeType, displayName ->
|
||||||
ActivityResultContracts.TakePicture()
|
viewModel.importAttachmentBytes(bytes, mimeType, displayName)
|
||||||
) { success ->
|
},
|
||||||
val uri = pendingCameraUri
|
onVoiceConvert = { viewModel.convertTo(NoteType.VOICE_NOTE) },
|
||||||
if (success && uri != null) {
|
isVoiceMode = state.type == NoteType.VOICE_NOTE,
|
||||||
scope.launch {
|
beginExternalActivity = beginExternalActivity,
|
||||||
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()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// v0.4.2.0 — voice notes. RECORD_AUDIO is requested the first time
|
|
||||||
// the user toggles the mic mode; on grant the note converts. The
|
|
||||||
// grant state is checked LIVE on every tap (a revoke from Settings
|
|
||||||
// mid-session must not slip through a cached flag).
|
|
||||||
val micPermissionLauncher = rememberLauncherForActivityResult(
|
|
||||||
ActivityResultContracts.RequestPermission()
|
|
||||||
) { granted ->
|
|
||||||
if (granted) {
|
|
||||||
viewModel.convertTo(NoteType.VOICE_NOTE)
|
|
||||||
} else {
|
|
||||||
Toast.makeText(ctx, "Microphone permission denied", Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fun micPermissionGranted(): Boolean =
|
|
||||||
ContextCompat.checkSelfPermission(
|
|
||||||
ctx,
|
|
||||||
Manifest.permission.RECORD_AUDIO,
|
|
||||||
) == PackageManager.PERMISSION_GRANTED
|
|
||||||
|
|
||||||
fun toggleVoiceMode() {
|
|
||||||
if (state.type == NoteType.VOICE_NOTE) {
|
|
||||||
// Toggling back needs no mic at all — the take survives as
|
|
||||||
// an ordinary attachment.
|
|
||||||
viewModel.convertTo(NoteType.VOICE_NOTE)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (micPermissionGranted()) {
|
|
||||||
viewModel.convertTo(NoteType.VOICE_NOTE)
|
|
||||||
} else {
|
|
||||||
micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun launchCamera() {
|
|
||||||
val (uri, _) = createTempCameraUri(ctx)
|
|
||||||
if (uri == null) {
|
|
||||||
Toast.makeText(ctx, "Couldn't prepare camera outbox", Toast.LENGTH_SHORT).show()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
pendingCameraUri = uri
|
|
||||||
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
|
|
||||||
}
|
|
||||||
|
|
||||||
LaunchedEffect(state.isLoading) {
|
LaunchedEffect(state.isLoading) {
|
||||||
if (!state.isLoading && state.existing != null) {
|
if (!state.isLoading && state.existing != null) {
|
||||||
@@ -458,23 +348,21 @@ fun NoteEditorScreen(
|
|||||||
val voicePending = state.pendingAttachments
|
val voicePending = state.pendingAttachments
|
||||||
.lastOrNull { it.mimeType.startsWith("audio/") }
|
.lastOrNull { it.mimeType.startsWith("audio/") }
|
||||||
val voicePersisted = state.attachments.lastOrNull { it.isAudio }
|
val voicePersisted = state.attachments.lastOrNull { it.isAudio }
|
||||||
VoiceNoteSection(
|
VoiceNoteSlot(
|
||||||
voicePending = voicePending,
|
voicePending = voicePending,
|
||||||
voicePendingBytes = voicePending?.let {
|
voicePendingBytes = voicePending?.let {
|
||||||
state.pendingAttachmentBytes[it.tempId]
|
state.pendingAttachmentBytes[it.tempId]
|
||||||
},
|
},
|
||||||
voicePersisted = voicePersisted,
|
voicePersisted = voicePersisted,
|
||||||
repository = repository,
|
repository = repository,
|
||||||
hasMicPermission = { micPermissionGranted() },
|
hasMicPermission = { intake.checkMicPermission() },
|
||||||
onRequestPermission = {
|
onRequestPermission = { intake.requestMicPermission() },
|
||||||
micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
|
|
||||||
},
|
|
||||||
onTakeRecorded = viewModel::setVoiceRecording,
|
onTakeRecorded = viewModel::setVoiceRecording,
|
||||||
onDeleteTake = {
|
onDeleteTake = {
|
||||||
voicePending?.let { viewModel.removePendingAttachment(it.tempId) }
|
voicePending?.let { viewModel.removePendingAttachment(it.tempId) }
|
||||||
?: voicePersisted?.let { viewModel.deletePersistedAttachment(it.id) }
|
?: voicePersisted?.let { viewModel.deletePersistedAttachment(it.id) }
|
||||||
},
|
},
|
||||||
securityManager = securityManager,
|
beginExternalActivity = beginExternalActivity,
|
||||||
modifier = Modifier.padding(horizontal = 16.dp),
|
modifier = Modifier.padding(horizontal = 16.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -538,7 +426,7 @@ fun NoteEditorScreen(
|
|||||||
// v0.3.4.0 hotfix: needed by the non-image tap
|
// v0.3.4.0 hotfix: needed by the non-image tap
|
||||||
// handler so the system-viewer round-trip doesn't
|
// handler so the system-viewer round-trip doesn't
|
||||||
// trigger an immediate re-lock.
|
// trigger an immediate re-lock.
|
||||||
securityManager = securityManager,
|
intake = intake,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -562,31 +450,36 @@ fun NoteEditorScreen(
|
|||||||
.padding(horizontal = 8.dp, vertical = 4.dp),
|
.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
IconButton(onClick = { launchCamera() }) {
|
// M4.4c §6.5: camera + voice affordances are HIDDEN where
|
||||||
Icon(
|
// the platform has no capture stack (desktop), not stubbed.
|
||||||
Icons.Filled.CameraAlt,
|
if (intake.supportsCamera) {
|
||||||
contentDescription = "Take photo",
|
IconButton(onClick = { intake.takePhoto() }) {
|
||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
Icon(
|
||||||
)
|
Icons.Filled.CameraAlt,
|
||||||
|
contentDescription = "Take photo",
|
||||||
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// v0.4.2.0 — voice-note toggle, first after Photo:
|
// v0.4.2.0 — voice-note toggle, first after Photo:
|
||||||
// converts the note to / from voice mode (mic permission
|
// converts the note to / from voice mode (mic permission
|
||||||
// is requested on the first tap into the mode).
|
// is requested on the first tap into the mode).
|
||||||
IconButton(onClick = { toggleVoiceMode() }) {
|
if (intake.supportsVoice) {
|
||||||
Icon(
|
IconButton(onClick = { intake.toggleVoiceMode() }) {
|
||||||
Icons.Filled.Mic,
|
Icon(
|
||||||
contentDescription = "Voice note",
|
Icons.Filled.Mic,
|
||||||
tint = if (state.type == NoteType.VOICE_NOTE)
|
contentDescription = "Voice note",
|
||||||
MaterialTheme.colorScheme.primary
|
tint = if (state.type == NoteType.VOICE_NOTE)
|
||||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
MaterialTheme.colorScheme.primary
|
||||||
)
|
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
IconButton(onClick = {
|
IconButton(onClick = {
|
||||||
// v0.3.4.0 hotfix: the SAF picker backgrounds
|
// v0.3.4.0 hotfix kept: the picker round-trip's
|
||||||
// the app; with Auto-Lock = Immediate the return
|
// auto-lock suppression now happens inside
|
||||||
// used to lock the app and wipe the unsaved note.
|
// intake.pickFiles() (Android actual).
|
||||||
securityManager?.beginExternalActivity()
|
intake.pickFiles()
|
||||||
filePickerLauncher.launch(arrayOf("*/*"))
|
|
||||||
}) {
|
}) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Filled.AttachFile,
|
Icons.Filled.AttachFile,
|
||||||
@@ -698,9 +591,9 @@ private fun AttachmentStrip(
|
|||||||
pendingOpen: (Long) -> Unit,
|
pendingOpen: (Long) -> Unit,
|
||||||
pendingDelete: (Long) -> Unit,
|
pendingDelete: (Long) -> Unit,
|
||||||
repository: org.incido.domain.repository.NoteRepository?,
|
repository: org.incido.domain.repository.NoteRepository?,
|
||||||
/** v0.3.4.0 hotfix: forwarded to [AttachmentThumbnail] for the
|
/** M4.4c: forwarded to [AttachmentThumbnail] — replaces the old
|
||||||
* system-viewer auto-lock suppression. */
|
* SecurityManager parameter (open-external + auto-lock suppression). */
|
||||||
securityManager: SecurityManager?,
|
intake: EditorIntake,
|
||||||
) {
|
) {
|
||||||
LazyRow(
|
LazyRow(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -719,7 +612,7 @@ private fun AttachmentStrip(
|
|||||||
// non-image taps launch a system viewer internally.
|
// non-image taps launch a system viewer internally.
|
||||||
onOpenImage = { persistedOpen(persistedViewerIds[att.id] ?: ViewerAttachmentId.Persisted(att.id)) },
|
onOpenImage = { persistedOpen(persistedViewerIds[att.id] ?: ViewerAttachmentId.Persisted(att.id)) },
|
||||||
onRemove = { persistedDelete(att.id) },
|
onRemove = { persistedDelete(att.id) },
|
||||||
securityManager = securityManager,
|
intake = intake,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
items(pending, key = { it.tempId }) { p ->
|
items(pending, key = { it.tempId }) { p ->
|
||||||
@@ -731,7 +624,7 @@ private fun AttachmentStrip(
|
|||||||
repository = repository,
|
repository = repository,
|
||||||
onOpenImage = { pendingOpen(p.tempId) },
|
onOpenImage = { pendingOpen(p.tempId) },
|
||||||
onRemove = { pendingDelete(p.tempId) },
|
onRemove = { pendingDelete(p.tempId) },
|
||||||
securityManager = securityManager,
|
intake = intake,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -753,12 +646,11 @@ private fun AttachmentThumbnail(
|
|||||||
* into the bitmap decode path that would silently fail. */
|
* into the bitmap decode path that would silently fail. */
|
||||||
onOpenImage: () -> Unit,
|
onOpenImage: () -> Unit,
|
||||||
onRemove: () -> Unit,
|
onRemove: () -> Unit,
|
||||||
/** v0.3.4.0 hotfix: suppress auto-lock around the external
|
/** M4.4c: platform intake — replaces the old SecurityManager
|
||||||
* "open in system viewer" intent. */
|
* parameter (open-external + auto-lock suppression + nudges). */
|
||||||
securityManager: SecurityManager?,
|
intake: EditorIntake,
|
||||||
) {
|
) {
|
||||||
val isImage = mimeType.startsWith("image/")
|
val isImage = mimeType.startsWith("image/")
|
||||||
val ctx = LocalContext.current
|
|
||||||
|
|
||||||
// v0.3.1.1: lazy-load bytes from DB for persisted image attachments
|
// 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
|
// so the editor strip shows a thumbnail even after the note is
|
||||||
@@ -772,7 +664,7 @@ private fun AttachmentThumbnail(
|
|||||||
// handler to bail with a misleading "Loading…" Toast forever.
|
// handler to bail with a misleading "Loading…" Toast forever.
|
||||||
val lazyBytes by produceState<ByteArray?>(initialValue = null, key1 = attachmentId) {
|
val lazyBytes by produceState<ByteArray?>(initialValue = null, key1 = attachmentId) {
|
||||||
if (pendingBytes == null && attachmentId != null && repository != null) {
|
if (pendingBytes == null && attachmentId != null && repository != null) {
|
||||||
value = withContext(Dispatchers.IO) {
|
value = withContext(ioDispatcher) {
|
||||||
repository.getAttachmentBytes(attachmentId)
|
repository.getAttachmentBytes(attachmentId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -786,11 +678,11 @@ private fun AttachmentThumbnail(
|
|||||||
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))
|
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))
|
||||||
// v0.3.1.2: branch on isImage — image taps open the
|
// v0.3.1.2: branch on isImage — image taps open the
|
||||||
// in-app viewer; non-image taps (PDF / MP3 / video / etc.)
|
// in-app viewer; non-image taps (PDF / MP3 / video / etc.)
|
||||||
// write the bytes to a cache temp file and launch the
|
// hand the bytes to the platform's open-with mechanism
|
||||||
// system viewer via FileProvider + ACTION_VIEW. The
|
// (M4.4c: EditorIntake.openExternal — FileProvider +
|
||||||
|
// ACTION_VIEW on Android, Desktop.open on JVM). The
|
||||||
// previous unconditional viewer path silently failed for
|
// previous unconditional viewer path silently failed for
|
||||||
// non-image mime types (BitmapFactory.decodeByteArray
|
// non-image mime types.
|
||||||
// returns null and the viewer just shows "Loading…").
|
|
||||||
.clickable {
|
.clickable {
|
||||||
if (isImage) {
|
if (isImage) {
|
||||||
onOpenImage()
|
onOpenImage()
|
||||||
@@ -800,57 +692,9 @@ private fun AttachmentThumbnail(
|
|||||||
// Lazy load still in flight for a persisted
|
// Lazy load still in flight for a persisted
|
||||||
// attachment — nudge the user instead of
|
// attachment — nudge the user instead of
|
||||||
// silently doing nothing.
|
// silently doing nothing.
|
||||||
Toast.makeText(ctx, "Loading\u2026", Toast.LENGTH_SHORT).show()
|
intake.notify("Loading…")
|
||||||
return@clickable
|
} else {
|
||||||
}
|
intake.openExternal(bytes, mimeType, displayName)
|
||||||
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()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -859,11 +703,11 @@ private fun AttachmentThumbnail(
|
|||||||
// Image preview OR file-type fallback.
|
// Image preview OR file-type fallback.
|
||||||
if (isImage && effectiveBytes != null) {
|
if (isImage && effectiveBytes != null) {
|
||||||
val bitmap = remember(effectiveBytes.contentHashCode()) {
|
val bitmap = remember(effectiveBytes.contentHashCode()) {
|
||||||
BitmapFactory.decodeByteArray(effectiveBytes, 0, effectiveBytes.size)
|
decodeImageBytes(effectiveBytes)
|
||||||
}
|
}
|
||||||
if (bitmap != null) {
|
if (bitmap != null) {
|
||||||
Image(
|
Image(
|
||||||
bitmap = bitmap.asImageBitmap(),
|
bitmap = bitmap!!,
|
||||||
contentDescription = displayName,
|
contentDescription = displayName,
|
||||||
contentScale = ContentScale.Crop,
|
contentScale = ContentScale.Crop,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
@@ -1438,49 +1282,12 @@ private fun EditorLineField(
|
|||||||
// ---------------------------------------------------------------------
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a temporary file in the app's cache and return a
|
* Lightweight [BackHandler] wrapper — M4.4c: delegates to the
|
||||||
* FileProvider-scoped Uri pointing at it. The camera app writes a JPEG
|
* [PlatformBackHandler] seam (activity-compose on Android, no-op on
|
||||||
* there; we read the bytes and delete the temp file. Returns
|
* desktop). The platform back press closes the editor or prompts for
|
||||||
* `(uri, file)` so the caller can clean up if reading fails.
|
* discard confirmation.
|
||||||
*/
|
|
||||||
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
|
@Composable
|
||||||
private fun BackHandler(enabled: Boolean, onBack: () -> Unit) {
|
private fun BackHandler(enabled: Boolean, onBack: () -> Unit) {
|
||||||
androidx.activity.compose.BackHandler(enabled = enabled, onBack = onBack)
|
PlatformBackHandler(enabled = enabled, onBack = onBack)
|
||||||
}
|
}
|
||||||
+8
-9
@@ -2,11 +2,9 @@ package org.incido.compose.ui.editor
|
|||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.ViewModelProvider
|
import androidx.lifecycle.ViewModelProvider
|
||||||
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
|
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import androidx.lifecycle.viewmodel.initializer
|
import androidx.lifecycle.viewmodel.initializer
|
||||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
import kotlinx.coroutines.FlowPreview
|
import kotlinx.coroutines.FlowPreview
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -21,7 +19,8 @@ import kotlinx.coroutines.flow.stateIn
|
|||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import org.incido.compose.IncidoApplication
|
import org.incido.compose.di.AppGraph
|
||||||
|
import org.incido.compose.di.ioDispatcher
|
||||||
import org.incido.compose.share.LinkedShareComposer
|
import org.incido.compose.share.LinkedShareComposer
|
||||||
import org.incido.domain.model.ChecklistItem
|
import org.incido.domain.model.ChecklistItem
|
||||||
import org.incido.domain.model.Hashtag
|
import org.incido.domain.model.Hashtag
|
||||||
@@ -614,7 +613,7 @@ class NoteEditorViewModel(
|
|||||||
val existingId = _state.value.existing?.id
|
val existingId = _state.value.existing?.id
|
||||||
if (existingId != null && existingId > 0L) {
|
if (existingId != null && existingId > 0L) {
|
||||||
// Persist straight to the DB; observeAttachments will surface it.
|
// Persist straight to the DB; observeAttachments will surface it.
|
||||||
withContext(Dispatchers.IO) {
|
withContext(ioDispatcher) {
|
||||||
repository.addAttachment(
|
repository.addAttachment(
|
||||||
noteId = existingId,
|
noteId = existingId,
|
||||||
bytes = bytes,
|
bytes = bytes,
|
||||||
@@ -656,7 +655,7 @@ class NoteEditorViewModel(
|
|||||||
/** Delete a persisted attachment by id (used by the ✕ on the thumbnail strip). */
|
/** Delete a persisted attachment by id (used by the ✕ on the thumbnail strip). */
|
||||||
fun deletePersistedAttachment(id: Long) {
|
fun deletePersistedAttachment(id: Long) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
withContext(Dispatchers.IO) { repository.removeAttachment(id) }
|
withContext(ioDispatcher) { repository.removeAttachment(id) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -685,7 +684,7 @@ class NoteEditorViewModel(
|
|||||||
val stalePersisted = _state.value.attachments
|
val stalePersisted = _state.value.attachments
|
||||||
.filter { it.mimeType.startsWith("audio/") }
|
.filter { it.mimeType.startsWith("audio/") }
|
||||||
if (stalePersisted.isNotEmpty()) {
|
if (stalePersisted.isNotEmpty()) {
|
||||||
withContext(Dispatchers.IO) {
|
withContext(ioDispatcher) {
|
||||||
stalePersisted.forEach { repository.removeAttachment(it.id) }
|
stalePersisted.forEach { repository.removeAttachment(it.id) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -799,7 +798,7 @@ class NoteEditorViewModel(
|
|||||||
current.pendingAttachments.forEach { pending ->
|
current.pendingAttachments.forEach { pending ->
|
||||||
val bytes = current.pendingAttachmentBytes[pending.tempId]
|
val bytes = current.pendingAttachmentBytes[pending.tempId]
|
||||||
if (bytes != null) {
|
if (bytes != null) {
|
||||||
withContext(Dispatchers.IO) {
|
withContext(ioDispatcher) {
|
||||||
repository.addAttachment(
|
repository.addAttachment(
|
||||||
noteId = saved.id,
|
noteId = saved.id,
|
||||||
bytes = bytes,
|
bytes = bytes,
|
||||||
@@ -847,6 +846,7 @@ class NoteEditorViewModel(
|
|||||||
const val DRAFT_AUTOSAVE_DEBOUNCE_MS = 400L
|
const val DRAFT_AUTOSAVE_DEBOUNCE_MS = 400L
|
||||||
|
|
||||||
fun factory(
|
fun factory(
|
||||||
|
graph: AppGraph,
|
||||||
noteId: Long?,
|
noteId: Long?,
|
||||||
initialSharedText: String? = null,
|
initialSharedText: String? = null,
|
||||||
initialSharedImages: List<SharedImage> = emptyList(),
|
initialSharedImages: List<SharedImage> = emptyList(),
|
||||||
@@ -858,9 +858,8 @@ class NoteEditorViewModel(
|
|||||||
initialSharedSubject: String? = null,
|
initialSharedSubject: String? = null,
|
||||||
): ViewModelProvider.Factory = viewModelFactory {
|
): ViewModelProvider.Factory = viewModelFactory {
|
||||||
initializer {
|
initializer {
|
||||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
|
||||||
NoteEditorViewModel(
|
NoteEditorViewModel(
|
||||||
repository = app.container.noteRepository,
|
repository = graph.noteRepository,
|
||||||
noteId = noteId,
|
noteId = noteId,
|
||||||
initialSharedText = initialSharedText,
|
initialSharedText = initialSharedText,
|
||||||
initialSharedImages = initialSharedImages,
|
initialSharedImages = initialSharedImages,
|
||||||
+9
-7
@@ -1,6 +1,5 @@
|
|||||||
package org.incido.compose.ui.notelist
|
package org.incido.compose.ui.notelist
|
||||||
|
|
||||||
import android.graphics.BitmapFactory
|
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.combinedClickable
|
import androidx.compose.foundation.combinedClickable
|
||||||
@@ -68,14 +67,17 @@ import androidx.compose.ui.focus.FocusRequester
|
|||||||
import androidx.compose.ui.focus.focusRequester
|
import androidx.compose.ui.focus.focusRequester
|
||||||
import androidx.compose.ui.graphics.Brush
|
import androidx.compose.ui.graphics.Brush
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.asImageBitmap
|
import androidx.compose.ui.graphics.ImageBitmap
|
||||||
import androidx.compose.ui.graphics.lerp
|
import androidx.compose.ui.graphics.lerp
|
||||||
import androidx.compose.ui.layout.ContentScale
|
import androidx.compose.ui.layout.ContentScale
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import org.incido.compose.di.ioDispatcher
|
||||||
|
import org.incido.compose.di.requireAppGraph
|
||||||
import org.incido.compose.ui.theme.toComposeColor
|
import org.incido.compose.ui.theme.toComposeColor
|
||||||
|
import org.incido.compose.util.decodeImageBytes
|
||||||
import org.incido.compose.util.rememberRelativeTimestamp
|
import org.incido.compose.util.rememberRelativeTimestamp
|
||||||
import org.incido.domain.model.Note
|
import org.incido.domain.model.Note
|
||||||
import org.incido.domain.model.NoteAttachment
|
import org.incido.domain.model.NoteAttachment
|
||||||
@@ -127,7 +129,7 @@ fun NoteListScreen(
|
|||||||
onOpenEditor: (Long?) -> Unit,
|
onOpenEditor: (Long?) -> Unit,
|
||||||
/** v0.3.1.0 — used to fetch image bytes for card thumbnails. */
|
/** v0.3.1.0 — used to fetch image bytes for card thumbnails. */
|
||||||
repository: NoteRepository? = null,
|
repository: NoteRepository? = null,
|
||||||
viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.Factory),
|
viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.factory(requireAppGraph())),
|
||||||
) {
|
) {
|
||||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
var localQuery by remember { mutableStateOf("") }
|
var localQuery by remember { mutableStateOf("") }
|
||||||
@@ -470,13 +472,13 @@ private fun NoteCard(
|
|||||||
// a downsampled bitmap for the card background. The produceState
|
// a downsampled bitmap for the card background. The produceState
|
||||||
// scopes the work to the card's lifetime, so off-screen cards
|
// scopes the work to the card's lifetime, so off-screen cards
|
||||||
// don't keep their bitmaps alive.
|
// 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) {
|
if (firstImage == null || repository == null) {
|
||||||
value = null
|
value = null
|
||||||
} else {
|
} else {
|
||||||
value = withContext(kotlinx.coroutines.Dispatchers.IO) {
|
value = withContext(ioDispatcher) {
|
||||||
val bytes = repository.getAttachmentBytes(firstImage.id) ?: return@withContext null
|
val bytes = repository.getAttachmentBytes(firstImage.id) ?: return@withContext null
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
decodeImageBytes(bytes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -536,7 +538,7 @@ private fun NoteCard(
|
|||||||
// Card's opaque containerColor was drawn on top of them).
|
// Card's opaque containerColor was drawn on top of them).
|
||||||
if (thumbnailBitmap != null) {
|
if (thumbnailBitmap != null) {
|
||||||
Image(
|
Image(
|
||||||
bitmap = thumbnailBitmap!!.asImageBitmap(),
|
bitmap = thumbnailBitmap!!,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
contentScale = ContentScale.Crop,
|
contentScale = ContentScale.Crop,
|
||||||
modifier = Modifier.matchParentSize(),
|
modifier = Modifier.matchParentSize(),
|
||||||
+11
-9
@@ -2,7 +2,6 @@ package org.incido.compose.ui.notelist
|
|||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.ViewModelProvider
|
import androidx.lifecycle.ViewModelProvider
|
||||||
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
|
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import androidx.lifecycle.viewmodel.initializer
|
import androidx.lifecycle.viewmodel.initializer
|
||||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||||
@@ -16,7 +15,8 @@ import kotlinx.coroutines.flow.debounce
|
|||||||
import kotlinx.coroutines.flow.flatMapLatest
|
import kotlinx.coroutines.flow.flatMapLatest
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
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.HashtagUsage
|
||||||
import org.incido.domain.model.Note
|
import org.incido.domain.model.Note
|
||||||
import org.incido.domain.model.NoteFilter
|
import org.incido.domain.model.NoteFilter
|
||||||
@@ -52,8 +52,11 @@ data class NoteListUiState(
|
|||||||
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
|
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
|
||||||
class NoteListViewModel(
|
class NoteListViewModel(
|
||||||
private val repository: NoteRepository,
|
private val repository: NoteRepository,
|
||||||
/** v0.3.5.0 — source of the verified-encryption badge set. */
|
/** v0.3.5.0 — source of the verified-encryption badge set.
|
||||||
private val encryptionVerifier: org.incido.compose.data.security.EncryptionVerifier? = null,
|
* 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() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val filterMode = MutableStateFlow<NoteFilter>(NoteFilter.Home)
|
private val filterMode = MutableStateFlow<NoteFilter>(NoteFilter.Home)
|
||||||
@@ -112,7 +115,7 @@ class NoteListViewModel(
|
|||||||
*/
|
*/
|
||||||
val uiState: StateFlow<NoteListUiState> = combine(
|
val uiState: StateFlow<NoteListUiState> = combine(
|
||||||
baseUiState,
|
baseUiState,
|
||||||
encryptionVerifier?.verification
|
encryptionBadge?.verification
|
||||||
?: kotlinx.coroutines.flow.flowOf(null),
|
?: kotlinx.coroutines.flow.flowOf(null),
|
||||||
) { state, verification ->
|
) { state, verification ->
|
||||||
state.copy(
|
state.copy(
|
||||||
@@ -175,12 +178,11 @@ class NoteListViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val Factory: ViewModelProvider.Factory = viewModelFactory {
|
fun factory(graph: AppGraph): ViewModelProvider.Factory = viewModelFactory {
|
||||||
initializer {
|
initializer {
|
||||||
val app = this[APPLICATION_KEY] as IncidoApplication
|
|
||||||
NoteListViewModel(
|
NoteListViewModel(
|
||||||
repository = app.container.noteRepository,
|
repository = graph.noteRepository,
|
||||||
encryptionVerifier = app.container.encryptionVerifier,
|
encryptionBadge = graph.encryptionBadge,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+18
-13
@@ -1,8 +1,5 @@
|
|||||||
package org.incido.compose.ui.settings
|
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.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
@@ -27,7 +24,9 @@ import androidx.compose.runtime.mutableStateOf
|
|||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Modifier
|
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.KeyboardType
|
||||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
import androidx.compose.ui.text.input.VisualTransformation
|
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
|
* truth for "is this passphrase correct", surfaced as
|
||||||
* "Incorrect passphrase." via snackbar on mismatch.
|
* "Incorrect passphrase." via snackbar on mismatch.
|
||||||
*/
|
*/
|
||||||
|
@Suppress("DEPRECATION") // LocalClipboardManager: see body comment — 1.8 API swap
|
||||||
@Composable
|
@Composable
|
||||||
fun PassphraseDialog(
|
fun PassphraseDialog(
|
||||||
onConfirm: (CharArray) -> Unit,
|
onConfirm: (CharArray) -> Unit,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
mode: PassphraseDialogMode = PassphraseDialogMode.EXPORT,
|
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
|
// v0.3.6.0: use the enum helper so RECOVERY_EXPORT shares the
|
||||||
// EXPORT chrome (policy check, Generate/Copy, Confirm field).
|
// EXPORT chrome (policy check, Generate/Copy, Confirm field).
|
||||||
val isExport = mode.isExport
|
val isExport = mode.isExport
|
||||||
@@ -178,8 +187,10 @@ fun PassphraseDialog(
|
|||||||
Icon(Icons.Filled.Refresh, contentDescription = "Generate")
|
Icon(Icons.Filled.Refresh, contentDescription = "Generate")
|
||||||
}
|
}
|
||||||
IconButton(onClick = {
|
IconButton(onClick = {
|
||||||
copyToClipboard(context, passphrase)
|
if (passphrase.isNotEmpty()) {
|
||||||
copied = true
|
clipboard.setText(AnnotatedString(passphrase))
|
||||||
|
copied = true
|
||||||
|
}
|
||||||
}) {
|
}) {
|
||||||
Icon(Icons.Filled.ContentCopy, contentDescription = "Copy")
|
Icon(Icons.Filled.ContentCopy, contentDescription = "Copy")
|
||||||
}
|
}
|
||||||
@@ -270,9 +281,3 @@ enum class PassphraseDialogMode {
|
|||||||
* an existing passphrase may predate the current policy. */
|
* an existing passphrase may predate the current policy. */
|
||||||
val isExport: Boolean get() = this == EXPORT || this == RECOVERY_EXPORT
|
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))
|
|
||||||
}
|
|
||||||
File renamed without changes.
@@ -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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
File renamed without changes.
+15
-9
@@ -1,14 +1,23 @@
|
|||||||
package org.incido.compose.ui.theme
|
package org.incido.compose.ui.theme
|
||||||
|
|
||||||
import android.os.Build
|
|
||||||
import androidx.compose.foundation.isSystemInDarkTheme
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.ColorScheme
|
||||||
import androidx.compose.material3.darkColorScheme
|
import androidx.compose.material3.darkColorScheme
|
||||||
import androidx.compose.material3.dynamicDarkColorScheme
|
|
||||||
import androidx.compose.material3.dynamicLightColorScheme
|
|
||||||
import androidx.compose.material3.lightColorScheme
|
import androidx.compose.material3.lightColorScheme
|
||||||
import androidx.compose.runtime.Composable
|
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(
|
private val DarkColorScheme = darkColorScheme(
|
||||||
primary = Purple80,
|
primary = Purple80,
|
||||||
@@ -34,11 +43,8 @@ fun IncidoTheme(
|
|||||||
content: @Composable () -> Unit,
|
content: @Composable () -> Unit,
|
||||||
) {
|
) {
|
||||||
val colorScheme = when {
|
val colorScheme = when {
|
||||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
dynamicColor -> platformDynamicColorScheme(darkTheme)
|
||||||
val context = LocalContext.current
|
?: if (darkTheme) DarkColorScheme else LightColorScheme
|
||||||
if (darkTheme) dynamicDarkColorScheme(context)
|
|
||||||
else dynamicLightColorScheme(context)
|
|
||||||
}
|
|
||||||
darkTheme -> DarkColorScheme
|
darkTheme -> DarkColorScheme
|
||||||
else -> LightColorScheme
|
else -> LightColorScheme
|
||||||
}
|
}
|
||||||
File renamed without changes.
@@ -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,269 +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.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()
|
|
||||||
|
|
||||||
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,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,
|
||||||
|
)
|
||||||
|
|
||||||
+3
@@ -93,6 +93,9 @@ object BackupCodec {
|
|||||||
bytes = decodeBase64(ba.bytesBase64),
|
bytes = decodeBase64(ba.bytesBase64),
|
||||||
mimeType = ba.mimeType,
|
mimeType = ba.mimeType,
|
||||||
displayName = ba.displayName,
|
displayName = ba.displayName,
|
||||||
|
// Restore the phone's attachment timestamp (M2:
|
||||||
|
// everything import claims to preserve must survive).
|
||||||
|
createdAt = ba.createdAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
onProgress(idx + 1, total)
|
onProgress(idx + 1, total)
|
||||||
File renamed without changes.
File renamed without changes.
@@ -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"
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -0,0 +1,195 @@
|
|||||||
|
{
|
||||||
|
"_note1": "KEEP THIS FILE! Check it into a version control system (VCS) like git.",
|
||||||
|
"_note2": "ObjectBox manages crucial IDs for your object model. See docs for details.",
|
||||||
|
"_note3": "If you have VCS merge conflicts, you must resolve them according to ObjectBox docs.",
|
||||||
|
"entities": [
|
||||||
|
{
|
||||||
|
"id": "1:2086366869756073512",
|
||||||
|
"lastPropertyId": "11:3900643584337280163",
|
||||||
|
"name": "NoteEntity",
|
||||||
|
"properties": [
|
||||||
|
{
|
||||||
|
"id": "1:504738300062779212",
|
||||||
|
"name": "id",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:934725261850395537",
|
||||||
|
"name": "content",
|
||||||
|
"type": 9
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3:7787800412489145126",
|
||||||
|
"name": "createdAt",
|
||||||
|
"indexId": "1:2377104061956606005",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "4:7214601561419742071",
|
||||||
|
"name": "updatedAt",
|
||||||
|
"type": 6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "5:8997711518431222149",
|
||||||
|
"name": "isFavorite",
|
||||||
|
"indexId": "2:2889322420050596277",
|
||||||
|
"type": 1,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "6:2157877161769308588",
|
||||||
|
"name": "colorKey",
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "7:9124062984393699059",
|
||||||
|
"name": "cipherVersion",
|
||||||
|
"type": 5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "8:505259681403080579",
|
||||||
|
"name": "contentBlob",
|
||||||
|
"type": 23
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "9:2838488564098834737",
|
||||||
|
"name": "isTrashed",
|
||||||
|
"indexId": "7:9172152715891628247",
|
||||||
|
"type": 1,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "10:5547426387212371555",
|
||||||
|
"name": "typeKey",
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "11:3900643584337280163",
|
||||||
|
"name": "isDraft",
|
||||||
|
"indexId": "8:9185376899648223266",
|
||||||
|
"type": 1,
|
||||||
|
"flags": 8
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relations": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:2528940840759116824",
|
||||||
|
"lastPropertyId": "2:6290673541624313354",
|
||||||
|
"name": "HashtagEntity",
|
||||||
|
"properties": [
|
||||||
|
{
|
||||||
|
"id": "1:6991393863924167484",
|
||||||
|
"name": "id",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:6290673541624313354",
|
||||||
|
"name": "name",
|
||||||
|
"indexId": "3:8935974229325273672",
|
||||||
|
"type": 9,
|
||||||
|
"flags": 2048
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relations": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3:1814708994588042328",
|
||||||
|
"lastPropertyId": "3:4619895459374594011",
|
||||||
|
"name": "NoteHashtagCrossRef",
|
||||||
|
"properties": [
|
||||||
|
{
|
||||||
|
"id": "1:8394679598512920368",
|
||||||
|
"name": "id",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:7132785913803437080",
|
||||||
|
"name": "noteId",
|
||||||
|
"indexId": "4:4609493987894622099",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3:4619895459374594011",
|
||||||
|
"name": "hashtagId",
|
||||||
|
"indexId": "5:4178528765644585892",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 8
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relations": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "4:715630424595534313",
|
||||||
|
"lastPropertyId": "9:5604884960166980615",
|
||||||
|
"name": "NoteAttachmentEntity",
|
||||||
|
"properties": [
|
||||||
|
{
|
||||||
|
"id": "1:8895066388904375968",
|
||||||
|
"name": "id",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:5099883303141941942",
|
||||||
|
"name": "noteId",
|
||||||
|
"indexId": "6:644263235201197567",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3:5923891227223085632",
|
||||||
|
"name": "mimeType",
|
||||||
|
"type": 9
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "4:5969004045087908818",
|
||||||
|
"name": "displayName",
|
||||||
|
"type": 9
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "5:1484939891319950467",
|
||||||
|
"name": "createdAt",
|
||||||
|
"type": 6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "6:4541111239334797694",
|
||||||
|
"name": "sizeBytes",
|
||||||
|
"type": 6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "7:5483350198068298485",
|
||||||
|
"name": "bytes",
|
||||||
|
"type": 23
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "8:6354828434115894982",
|
||||||
|
"name": "cipherVersion",
|
||||||
|
"type": 5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "9:5604884960166980615",
|
||||||
|
"name": "bytesBlob",
|
||||||
|
"type": 23
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relations": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"lastEntityId": "4:715630424595534313",
|
||||||
|
"lastIndexId": "8:9185376899648223266",
|
||||||
|
"lastRelationId": "0:0",
|
||||||
|
"lastSequenceId": "0:0",
|
||||||
|
"modelVersion": 5,
|
||||||
|
"modelVersionParserMinimum": 5,
|
||||||
|
"retiredEntityUids": [],
|
||||||
|
"retiredIndexUids": [],
|
||||||
|
"retiredPropertyUids": [],
|
||||||
|
"retiredRelationUids": [],
|
||||||
|
"version": 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package org.incido.data
|
||||||
|
|
||||||
|
import io.objectbox.BoxStore
|
||||||
|
import java.io.File
|
||||||
|
import org.incido.data.entity.MyObjectBox
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Desktop (JVM) counterpart of `:core:data`'s Android `ObjectBoxStore`.
|
||||||
|
*
|
||||||
|
* Deliberately the same fully-qualified name as the Android object: the two
|
||||||
|
* live in sibling modules that are never on one classpath, so shared code
|
||||||
|
* (repositories, services) refers to `org.incido.data.ObjectBoxStore` and each
|
||||||
|
* platform links its own implementation. The only real difference is how the
|
||||||
|
* store is located — Android hands ObjectBox a `Context`, desktop passes an
|
||||||
|
* explicit directory (XDG data dir in the desktop app).
|
||||||
|
*
|
||||||
|
* Encryption story is unchanged from Android: OSS ObjectBox 4.0.3 exposes no
|
||||||
|
* page-level encryption, so at-rest protection is the field cipher in
|
||||||
|
* `NoteRepositoryImpl` / `NoteCryptoService`; [encryptionKey] stays a no-op
|
||||||
|
* parameter for source compatibility.
|
||||||
|
*/
|
||||||
|
object ObjectBoxStore {
|
||||||
|
@Volatile
|
||||||
|
private var instance: BoxStore? = null
|
||||||
|
|
||||||
|
/** Open (or create) the library in [directory]. Idempotent. */
|
||||||
|
@Suppress("UNUSED_PARAMETER")
|
||||||
|
fun init(directory: File, encryptionKey: ByteArray? = null): BoxStore =
|
||||||
|
instance ?: synchronized(this) {
|
||||||
|
instance ?: MyObjectBox.builder()
|
||||||
|
.directory(directory)
|
||||||
|
.build()
|
||||||
|
.also { instance = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Close + drop the singleton (used by tests and store re-opens). */
|
||||||
|
fun reset() {
|
||||||
|
synchronized(this) {
|
||||||
|
instance?.close()
|
||||||
|
instance = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun get(): BoxStore =
|
||||||
|
instance ?: error("ObjectBoxStore not initialised — call init(directory) first")
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package org.incido.data.jvm
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import kotlin.random.Random
|
||||||
|
import kotlin.system.measureTimeMillis
|
||||||
|
import java.lang.management.ManagementFactory
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.incido.compose.data.backup.BackupBridge
|
||||||
|
import org.incido.data.ImageOrientationNormalizer
|
||||||
|
import org.incido.data.ObjectBoxStore
|
||||||
|
import org.incido.data.crypto.CipherHolder
|
||||||
|
import org.incido.data.repository.NoteRepositoryImpl
|
||||||
|
import org.incido.domain.model.Note
|
||||||
|
import org.incido.domain.repository.NoteRepository
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase 1 (M2 task 5): MEASURE the export path's memory on synthesized
|
||||||
|
* worst-case libraries — do not redesign it. The plan's gate: ~10–20
|
||||||
|
* notes with attachments must be trivial, 200+ with large attachments is
|
||||||
|
* "watch", and only a >250 MB peak forces the streaming-redesign
|
||||||
|
* discussion (which would be a formatVersion=2 change, Phase 2).
|
||||||
|
*
|
||||||
|
* The probe drives `BackupBridge.exportPlain` — the exact code the phone
|
||||||
|
* runs inside its `Uri → stream` shim — against three fresh ObjectBox
|
||||||
|
* libraries, sampling heap-used at 1 ms while the export runs.
|
||||||
|
*
|
||||||
|
* Run with `./gradlew :core:data-jvm:backupMemory` (2 GB ceiling set in
|
||||||
|
* the task; a tier that outruns it is itself the finding).
|
||||||
|
*/
|
||||||
|
private const val MB = 1024 * 1024
|
||||||
|
|
||||||
|
private class Tier(
|
||||||
|
val label: String,
|
||||||
|
val dirName: String,
|
||||||
|
val notes: Int,
|
||||||
|
/** One attachment each on the first N notes; 0 = no attachments. */
|
||||||
|
val attachmentsTotal: Int,
|
||||||
|
val attachmentMb: Int,
|
||||||
|
) {
|
||||||
|
val payloadMb: Long get() = notes * 1300L / MB + attachmentsTotal * attachmentMb.toLong()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 1 ms heap sampler; peak is the highest heap-used seen while running. */
|
||||||
|
private class HeapSampler : Runnable {
|
||||||
|
@Volatile var stop = false
|
||||||
|
@Volatile var peak = 0L
|
||||||
|
private val bean = ManagementFactory.getMemoryMXBean()
|
||||||
|
override fun run() {
|
||||||
|
while (!stop) {
|
||||||
|
val used = bean.heapMemoryUsage.used
|
||||||
|
if (used > peak) peak = used
|
||||||
|
try {
|
||||||
|
Thread.sleep(1)
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun main() = runBlocking {
|
||||||
|
println("=== Incido Phase 1 M2 task 5: backup export memory (measure, don't redesign) ===")
|
||||||
|
println("heap ceiling : ${Runtime.getRuntime().maxMemory() / MB} MB (-Xmx of the backupMemory task)")
|
||||||
|
|
||||||
|
val libRoot = File("build/backup-memory").apply { deleteRecursively(); mkdirs() }
|
||||||
|
val tiers = listOf(
|
||||||
|
// Cheapest first so a failure in a later tier can't eat the findings.
|
||||||
|
Tier("phone-at-gate (20 notes, 3 att x 8 MB)", "t1-gate", 20, 3, 8),
|
||||||
|
Tier("many notes (2000 notes, no att)", "t2-count", 2000, 0, 0),
|
||||||
|
Tier("phone-heavy (100 notes, 10 att x 8 MB)", "t3-heavy", 100, 10, 8),
|
||||||
|
Tier("watch tier (200 notes, 40 att x 8 MB)", "t4-watch", 200, 40, 8),
|
||||||
|
)
|
||||||
|
|
||||||
|
for (tier in tiers) {
|
||||||
|
val dir = File(libRoot, tier.dirName).apply { mkdirs() }
|
||||||
|
val out = File(libRoot, "${tier.dirName}.out.json")
|
||||||
|
runCatching {
|
||||||
|
ObjectBoxStore.reset()
|
||||||
|
ObjectBoxStore.init(dir)
|
||||||
|
val repo: NoteRepository =
|
||||||
|
NoteRepositoryImpl(ObjectBoxStore.get(), CipherHolder(), ImageOrientationNormalizer.NoOp)
|
||||||
|
|
||||||
|
// Synthesize: fixed seed for repeatability; ~1.3 KB text per note.
|
||||||
|
val rnd = Random(42)
|
||||||
|
val ids = ArrayList<Long>(tier.notes)
|
||||||
|
repeat(tier.notes) { i ->
|
||||||
|
val content = (1..24).joinToString("\n") { "Note $i line $it — synthesized filler for the memory probe." }
|
||||||
|
val now = 1_700_000_000_000L + i * 1000L
|
||||||
|
val saved = repo.saveNoteWithHashtags(
|
||||||
|
note = Note(id = 0L, content = content, createdAt = now, updatedAt = now),
|
||||||
|
hashtagsToAdd = emptySet(),
|
||||||
|
hashtagsToRemove = emptySet(),
|
||||||
|
)
|
||||||
|
ids += saved.id
|
||||||
|
}
|
||||||
|
if (tier.attachmentMb > 0) {
|
||||||
|
val blob = ByteArray(tier.attachmentMb * MB)
|
||||||
|
repeat(tier.attachmentsTotal) { j ->
|
||||||
|
rnd.nextBytes(blob)
|
||||||
|
repo.addAttachment(
|
||||||
|
noteId = ids[j % ids.size],
|
||||||
|
bytes = blob,
|
||||||
|
mimeType = "image/jpeg",
|
||||||
|
displayName = "att-$j.jpg",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.gc()
|
||||||
|
Thread.sleep(100)
|
||||||
|
val baseline = ManagementFactory.getMemoryMXBean().heapMemoryUsage.used
|
||||||
|
val sampler = HeapSampler()
|
||||||
|
val samplerThread = Thread(sampler).apply { isDaemon = true; start() }
|
||||||
|
val ms = measureTimeMillis {
|
||||||
|
BackupBridge.exportPlain(repo, FileOutputStream(out), "m2-memory-probe")
|
||||||
|
}
|
||||||
|
sampler.stop = true
|
||||||
|
samplerThread.join()
|
||||||
|
println(
|
||||||
|
"%s | data≈%d MB → export %d ms | heap peak %d MB (+%d MB alloc pressure) | file %d MB"
|
||||||
|
.format(
|
||||||
|
tier.label, tier.payloadMb, ms,
|
||||||
|
sampler.peak / MB, (sampler.peak - baseline) / MB, out.length() / MB,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}.onFailure {
|
||||||
|
println(
|
||||||
|
"%s | data≈%d MB → FAILED: %s: %s"
|
||||||
|
.format(tier.label, tier.payloadMb, it::class.java.simpleName, it.message),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
out.delete()
|
||||||
|
ObjectBoxStore.reset()
|
||||||
|
dir.deleteRecursively()
|
||||||
|
}
|
||||||
|
|
||||||
|
val hwm = runCatching {
|
||||||
|
File("/proc/self/status").readLines().first { it.startsWith("VmHWM:") }
|
||||||
|
.filter(Char::isDigit).toLong() / 1024
|
||||||
|
}.getOrNull()
|
||||||
|
println("process peak RSS (VmHWM, incl. ObjectBox native): ${hwm ?: -1} MB")
|
||||||
|
println("verdict reference: plan gate = >250 MB forces streaming-redesign talk (formatVersion 2, Phase 2)")
|
||||||
|
println("=== backupMemory done ===")
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
package org.incido.data.jvm
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileInputStream
|
||||||
|
import java.util.Base64
|
||||||
|
import kotlin.system.exitProcess
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.incido.compose.data.backup.BackupBridge
|
||||||
|
import org.incido.compose.data.backup.BackupCodec
|
||||||
|
import org.incido.compose.data.backup.BackupFile
|
||||||
|
import org.incido.compose.data.backup.BackupNote
|
||||||
|
import org.incido.compose.data.backup.EncryptedBackupCodec
|
||||||
|
import org.incido.data.ImageOrientationNormalizer
|
||||||
|
import org.incido.data.ObjectBoxStore
|
||||||
|
import org.incido.data.crypto.CipherHolder
|
||||||
|
import org.incido.data.repository.NoteRepositoryImpl
|
||||||
|
import org.incido.domain.repository.NoteRepository
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase 1 (M2) round-trip probe: runs a **real** `.incido.json` export
|
||||||
|
* produced by the Android app through the extracted `:core:backup`
|
||||||
|
* bridge on a plain JVM — import into a live ObjectBox library, re-export,
|
||||||
|
* and compare note-for-note (incl. attachment bytes), plus the encrypted
|
||||||
|
* envelope path with a wrong-passphrase rejection.
|
||||||
|
*
|
||||||
|
* Unlike `smoke`, this script deletes [libDir] up front — it always runs
|
||||||
|
* against a fresh library.
|
||||||
|
*
|
||||||
|
* Run with
|
||||||
|
* `./gradlew :core:data-jvm:backupSmoke --args="<backup.incido.json> [libDir]"`.
|
||||||
|
*/
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
val src = File(args.getOrNull(0) ?: error("usage: backupSmoke <backup.incido.json> [libDir]"))
|
||||||
|
require(src.isFile) { "backup file not found: $src" }
|
||||||
|
val libDir = File(args.getOrNull(1) ?: "build/backup-roundtrip").also {
|
||||||
|
it.deleteRecursively()
|
||||||
|
it.mkdirs()
|
||||||
|
}
|
||||||
|
println("=== Incido Phase 1 M2: backup bridge on the JVM (real Android export) ===")
|
||||||
|
println("source file : $src (${src.length()} bytes)")
|
||||||
|
|
||||||
|
val original = BackupCodec.decode(src.readText())
|
||||||
|
val origAttachments = original.notes.sumOf { it.attachments.size }
|
||||||
|
println(
|
||||||
|
"source : notes=${original.notes.size} attachments=$origAttachments " +
|
||||||
|
"orphanTags=${original.orphanedHashtags.size} app=${original.appVersion}",
|
||||||
|
)
|
||||||
|
|
||||||
|
var failures = 0
|
||||||
|
fun step(name: String, body: () -> String) {
|
||||||
|
print("${name.padEnd(32)} ")
|
||||||
|
runCatching(body)
|
||||||
|
.onSuccess { println("PASS — $it") }
|
||||||
|
.onFailure {
|
||||||
|
println("FAIL — ${it::class.java.simpleName}: ${it.message}")
|
||||||
|
failures++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Fresh CharArray per use — the codecs zero the passphrase they consume.
|
||||||
|
fun pw(): CharArray = "RoundTrip passphrase #2026!".toCharArray()
|
||||||
|
fun repo(): NoteRepository =
|
||||||
|
NoteRepositoryImpl(ObjectBoxStore.get(), CipherHolder(), ImageOrientationNormalizer.NoOp)
|
||||||
|
|
||||||
|
step("preview (plain, no passphrase)") {
|
||||||
|
val p = BackupBridge.preview(FileInputStream(src)) ?: error("preview returned null")
|
||||||
|
require(p.noteCount == original.notes.size) { "noteCount=${p.noteCount}" }
|
||||||
|
require(p.attachmentCount == origAttachments) { "attachmentCount=${p.attachmentCount}" }
|
||||||
|
require(p.appVersion == original.appVersion) { "appVersion=${p.appVersion}" }
|
||||||
|
"notes=${p.noteCount} attachments=${p.attachmentCount} app=${p.appVersion}"
|
||||||
|
}
|
||||||
|
|
||||||
|
step("import into fresh JVM library") {
|
||||||
|
ObjectBoxStore.init(libDir)
|
||||||
|
val n = runBlocking { BackupBridge.import(repo(), FileInputStream(src)).imported }
|
||||||
|
require(n == original.notes.size) { "imported $n, expected ${original.notes.size}" }
|
||||||
|
val inStore = runBlocking { repo().observeAllIncludingTrashed().first().size }
|
||||||
|
require(inStore == original.notes.size) { "store holds $inStore" }
|
||||||
|
"imported $n notes, all readable back through the flow"
|
||||||
|
}
|
||||||
|
|
||||||
|
step("re-export plain == original") {
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
runBlocking { BackupBridge.exportPlain(repo(), out, "m2-roundtrip") }
|
||||||
|
val round = BackupCodec.decode(out.toString(Charsets.UTF_8))
|
||||||
|
val lostOrphans = original.orphanedHashtags.toSet() - round.orphanedHashtags.toSet()
|
||||||
|
compareNotes(original, round) +
|
||||||
|
" (orphan tags: ${round.orphanedHashtags.size}/${original.orphanedHashtags.size} recreated — " +
|
||||||
|
"importSnapshot has never restored orphans, pre-existing)" +
|
||||||
|
(if (lostOrphans.isEmpty()) "" else " [-$lostOrphans]")
|
||||||
|
}
|
||||||
|
|
||||||
|
var envelope = ByteArray(0)
|
||||||
|
step("encrypted export + wrong-pw reject") {
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
runBlocking { BackupBridge.exportEncrypted(repo(), out, pw(), "m2-roundtrip") }
|
||||||
|
envelope = out.toByteArray()
|
||||||
|
require(EncryptedBackupCodec.isEncrypted(envelope)) { "no INCDBK1 magic" }
|
||||||
|
val wrong = BackupBridge.preview(
|
||||||
|
ByteArrayInputStream(envelope),
|
||||||
|
"wrong wrong wrong #2026!".toCharArray(),
|
||||||
|
)
|
||||||
|
require(wrong == null) { "wrong passphrase was accepted!" }
|
||||||
|
"envelope=${envelope.size}B (json=${original.notes.size} notes), wrong passphrase → null"
|
||||||
|
}
|
||||||
|
|
||||||
|
step("import encrypted into 2nd library") {
|
||||||
|
ObjectBoxStore.reset()
|
||||||
|
val dir2 = File(libDir.absolutePath + "-enc").also { it.deleteRecursively(); it.mkdirs() }
|
||||||
|
ObjectBoxStore.init(dir2)
|
||||||
|
val n = runBlocking { BackupBridge.import(repo(), ByteArrayInputStream(envelope), pw()).imported }
|
||||||
|
require(n == original.notes.size) { "imported $n, expected ${original.notes.size}" }
|
||||||
|
val withAtt = runBlocking { repo().observeAllIncludingTrashed().first() }
|
||||||
|
.first { it.attachments.isNotEmpty() }
|
||||||
|
val bytes = runBlocking { repo().getAttachmentBytes(withAtt.attachments.single().id) }
|
||||||
|
?: error("attachment missing after encrypted import")
|
||||||
|
val expected = Base64.getDecoder()
|
||||||
|
.decode(original.notes.first { it.attachments.isNotEmpty() }.attachments.first().bytesBase64)
|
||||||
|
require(bytes.contentEquals(expected)) { "attachment bytes differ (${bytes.size} vs ${expected.size})" }
|
||||||
|
"imported $n notes; attachment ${bytes.size}B byte-identical to the phone's"
|
||||||
|
}
|
||||||
|
step("dedupe: re-import same file") {
|
||||||
|
ObjectBoxStore.reset()
|
||||||
|
val dir3 = File(libDir.absolutePath + "-dedupe").also { it.deleteRecursively(); it.mkdirs() }
|
||||||
|
ObjectBoxStore.init(dir3)
|
||||||
|
val first = runBlocking { BackupBridge.import(repo(), FileInputStream(src)) }
|
||||||
|
require(first.imported == original.notes.size && first.skipped == 0) { "first=$first" }
|
||||||
|
val again = runBlocking { BackupBridge.import(repo(), FileInputStream(src)) }
|
||||||
|
require(again.imported == 0 && again.skipped == original.notes.size) { "again=$again" }
|
||||||
|
// The override must still behave like the old additive import.
|
||||||
|
val forced = runBlocking { BackupBridge.import(repo(), FileInputStream(src), skipExisting = false) }
|
||||||
|
require(forced.imported == original.notes.size) { "forced=$forced" }
|
||||||
|
val count = runBlocking { repo().observeAllIncludingTrashed().first().size }
|
||||||
|
require(count == original.notes.size * 2) { "store holds $count after forced re-import" }
|
||||||
|
"re-import skipped=${again.skipped}; override added ${forced.imported} (store=$count)"
|
||||||
|
}
|
||||||
|
step("close libraries") {
|
||||||
|
ObjectBoxStore.reset()
|
||||||
|
"clean"
|
||||||
|
}
|
||||||
|
|
||||||
|
println()
|
||||||
|
println(
|
||||||
|
if (failures == 0) "RESULT: M2 round-trip PASS — a real Android export survives the desktop bridge."
|
||||||
|
else "RESULT: M2 round-trip FAIL — $failures step(s) failed.",
|
||||||
|
)
|
||||||
|
if (failures != 0) exitProcess(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Field-by-field comparison of two snapshots. Import forces fresh ids, so
|
||||||
|
* rows are paired positionally after sorting by the only stable keys every
|
||||||
|
* platform preserves: (createdAt, content). Attachments are paired the same
|
||||||
|
* way within each note and compared including their Base64 payload.
|
||||||
|
*/
|
||||||
|
private fun compareNotes(original: BackupFile, round: BackupFile): String {
|
||||||
|
require(round.notes.size == original.notes.size) {
|
||||||
|
"note count drifted: ${round.notes.size} != ${original.notes.size}"
|
||||||
|
}
|
||||||
|
fun List<BackupNote>.keyed() = sortedWith(
|
||||||
|
compareBy({ it.createdAt }, { it.content }),
|
||||||
|
)
|
||||||
|
val a = original.notes.keyed()
|
||||||
|
val b = round.notes.keyed()
|
||||||
|
a.forEachIndexed { i, want ->
|
||||||
|
val got = b[i]
|
||||||
|
val at = "note[$i] createdAt=${want.createdAt}"
|
||||||
|
if (got.content != want.content) {
|
||||||
|
val w = want.content
|
||||||
|
val g = got.content
|
||||||
|
val firstDiff = (0 until minOf(w.length, g.length)).firstOrNull { w[it] != g[it] }
|
||||||
|
error(
|
||||||
|
"$at: content differs at char $firstDiff " +
|
||||||
|
"(len ${w.length} vs ${g.length}) " +
|
||||||
|
"want=<${w.substring(maxOf(0, (firstDiff ?: 0) - 20), minOf(w.length, (firstDiff ?: 0) + 30)).replace("\n", "\\n")}> " +
|
||||||
|
"got=<${g.substring(maxOf(0, (firstDiff ?: 0) - 20), minOf(g.length, (firstDiff ?: 0) + 30)).replace("\n", "\\n")}>",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
require(got.updatedAt == want.updatedAt) { "$at: updatedAt differs" }
|
||||||
|
require(got.isFavorite == want.isFavorite) { "$at: isFavorite differs" }
|
||||||
|
require(got.color == want.color) { "$at: color ${got.color} != ${want.color}" }
|
||||||
|
require(got.noteType == want.noteType) { "$at: noteType ${got.noteType} != ${want.noteType}" }
|
||||||
|
require(got.isTrashed == want.isTrashed) { "$at: isTrashed differs" }
|
||||||
|
require(got.isDraft == want.isDraft) { "$at: isDraft differs" }
|
||||||
|
require(got.hashtags.sorted() == want.hashtags.sorted()) {
|
||||||
|
"$at: hashtags ${got.hashtags.sorted()} != ${want.hashtags.sorted()}"
|
||||||
|
}
|
||||||
|
require(got.attachments.size == want.attachments.size) { "$at: attachment count differs" }
|
||||||
|
val sortKey = compareBy<org.incido.compose.data.backup.BackupAttachment>(
|
||||||
|
{ it.createdAt },
|
||||||
|
{ it.displayName },
|
||||||
|
)
|
||||||
|
val wa = want.attachments.sortedWith(sortKey)
|
||||||
|
val ga = got.attachments.sortedWith(sortKey)
|
||||||
|
wa.forEachIndexed { j, waJ ->
|
||||||
|
val gaJ = ga[j]
|
||||||
|
require(gaJ.mimeType == waJ.mimeType) { "$at.att[$j]: mimeType differs" }
|
||||||
|
require(gaJ.displayName == waJ.displayName) { "$at.att[$j]: displayName differs" }
|
||||||
|
require(gaJ.sizeBytes == waJ.sizeBytes) { "$at.att[$j]: sizeBytes differs" }
|
||||||
|
require(gaJ.createdAt == waJ.createdAt) { "$at.att[$j]: createdAt differs" }
|
||||||
|
require(gaJ.bytesBase64 == waJ.bytesBase64) { "$at.att[$j]: BYTES DIFFER" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val attTotal = a.sumOf { it.attachments.size }
|
||||||
|
return "all ${a.size} notes + $attTotal attachments identical (content/times/fav/color/type/trash/draft/tags/bytes)"
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package org.incido.data.jvm
|
||||||
|
|
||||||
|
import com.drew.imaging.ImageMetadataReader
|
||||||
|
import com.drew.metadata.exif.ExifIFD0Directory
|
||||||
|
import java.awt.geom.AffineTransform
|
||||||
|
import java.awt.image.BufferedImage
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import javax.imageio.IIOImage
|
||||||
|
import javax.imageio.ImageIO
|
||||||
|
import javax.imageio.ImageWriteParam
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
import kotlin.math.sin
|
||||||
|
import org.incido.data.ImageOrientationNormalizer
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase 1 (M4.4e) — JVM [ImageOrientationNormalizer], replacing the
|
||||||
|
* NoOp placeholder the §6.3 EXIF row deferred ("metadata-extractor not
|
||||||
|
* cached, Maven Central reachable — feasible in JVM impl").
|
||||||
|
*
|
||||||
|
* Same contract as `AndroidImageOrientationNormalizer`: read the EXIF
|
||||||
|
* Orientation tag, bake 90/180/270 rotations into the pixels, re-encode
|
||||||
|
* JPEG @ 0.92 so the stored bytes carry no orientation flag; return the
|
||||||
|
* input UNCHANGED when orientation is normal/absent, the image can't be
|
||||||
|
* decoded, or anything else goes wrong.
|
||||||
|
*
|
||||||
|
* Tooling differs, contract doesn't:
|
||||||
|
* - tag read: com.drewnoakes:metadata-extractor (the Central-side
|
||||||
|
* peer of androidx.exifinterface),
|
||||||
|
* - rotate: BufferedImage + AffineTransform (no android.graphics),
|
||||||
|
* - encode: ImageIO JPEG writer at explicit 0.92 quality (Android
|
||||||
|
* uses Bitmap.compress(JPEG, 92)).
|
||||||
|
*
|
||||||
|
* Like the Android side, only the rotate-90/180/270 orientations do
|
||||||
|
* work; the mirror orientations (2–5, 7) fall through unchanged there
|
||||||
|
* too, so behaviour matches tag-for-tag.
|
||||||
|
*/
|
||||||
|
class JvmImageOrientationNormalizer : ImageOrientationNormalizer {
|
||||||
|
|
||||||
|
override fun normalize(bytes: ByteArray): ByteArray = runCatching {
|
||||||
|
val metadata = ImageMetadataReader.readMetadata(ByteArrayInputStream(bytes))
|
||||||
|
val ifd0 = metadata.getFirstDirectoryOfType(ExifIFD0Directory::class.java)
|
||||||
|
?: return@runCatching bytes
|
||||||
|
if (ifd0.hasErrors()) return@runCatching bytes
|
||||||
|
val angle = when (ifd0.getInteger(ExifIFD0Directory.TAG_ORIENTATION)) {
|
||||||
|
6 -> 90
|
||||||
|
3 -> 180
|
||||||
|
8 -> 270
|
||||||
|
else -> return@runCatching bytes // normal, absent, or a mirror tag
|
||||||
|
}
|
||||||
|
val img = ImageIO.read(ByteArrayInputStream(bytes)) ?: return@runCatching bytes
|
||||||
|
val rotated = rotate(img, angle)
|
||||||
|
encodeJpeg(rotated)
|
||||||
|
}.getOrDefault(bytes)
|
||||||
|
|
||||||
|
private fun rotate(img: BufferedImage, degrees: Int): BufferedImage {
|
||||||
|
val radians = Math.toRadians(degrees.toDouble())
|
||||||
|
val sin = abs(sin(radians))
|
||||||
|
val cos = abs(kotlin.math.cos(radians))
|
||||||
|
val w = img.width
|
||||||
|
val h = img.height
|
||||||
|
val out = BufferedImage(
|
||||||
|
(sin * h + cos * w).roundToInt(),
|
||||||
|
(cos * h + sin * w).roundToInt(),
|
||||||
|
BufferedImage.TYPE_INT_RGB,
|
||||||
|
)
|
||||||
|
val g = out.createGraphics()
|
||||||
|
val tx = AffineTransform()
|
||||||
|
tx.translate(out.width / 2.0, out.height / 2.0)
|
||||||
|
tx.rotate(radians)
|
||||||
|
tx.translate(-w / 2.0, -h / 2.0)
|
||||||
|
g.drawImage(img, tx, null)
|
||||||
|
g.dispose()
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun encodeJpeg(img: BufferedImage): ByteArray {
|
||||||
|
val writer = ImageIO.getImageWritersByFormatName("jpeg").next()
|
||||||
|
try {
|
||||||
|
val params = (writer.defaultWriteParam as ImageWriteParam).apply {
|
||||||
|
setCompressionMode(ImageWriteParam.MODE_EXPLICIT)
|
||||||
|
compressionQuality = 0.92f // matches the Android side's compress(JPEG, 92)
|
||||||
|
}
|
||||||
|
val bos = ByteArrayOutputStream()
|
||||||
|
ImageIO.createImageOutputStream(bos).use { out ->
|
||||||
|
writer.output = out
|
||||||
|
writer.write(null, IIOImage(img, null, null), params)
|
||||||
|
}
|
||||||
|
return bos.toByteArray()
|
||||||
|
} finally {
|
||||||
|
writer.dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package org.incido.data.jvm
|
||||||
|
|
||||||
|
import java.awt.image.BufferedImage
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import javax.imageio.ImageIO
|
||||||
|
import org.incido.data.ImageOrientationNormalizer
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase 1 (M4.4e) — `./gradlew :core:data-jvm:orientationSmoke`.
|
||||||
|
*
|
||||||
|
* Proves [JvmImageOrientationNormalizer] end-to-end without needing a
|
||||||
|
* phone: hand-builds a JPEG whose EXIF Orientation tag says
|
||||||
|
* "rotate 90", feeds it through the same [ImageOrientationNormalizer]
|
||||||
|
* seam `NoteRepositoryImpl` stores images through, and checks the
|
||||||
|
* rotation was baked into the pixels (dimensions swapped) while a
|
||||||
|
* no-EXIF / garbage input comes back byte-identical — the exact
|
||||||
|
* contract the Android normalizer established.
|
||||||
|
*/
|
||||||
|
fun main() {
|
||||||
|
val normalizer = JvmImageOrientationNormalizer()
|
||||||
|
var failures = 0
|
||||||
|
fun check(name: String, ok: Boolean) {
|
||||||
|
println("EXIF ${if (ok) "PASS" else "FAIL"} $name")
|
||||||
|
if (!ok) failures++
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4x2 base JPEG (deliberately non-square so a 90° rotation swaps
|
||||||
|
// the dimensions in an observable way).
|
||||||
|
val base = jpegOf(BufferedImage(4, 2, BufferedImage.TYPE_INT_RGB))
|
||||||
|
check("no-EXIF input returned unchanged", normalizer.normalize(base).contentEquals(base))
|
||||||
|
|
||||||
|
val tagged = injectExifOrientation90(base)
|
||||||
|
val normalized = normalizer.normalize(tagged)
|
||||||
|
check("EXIF-90 input was rewritten", !normalized.contentEquals(tagged))
|
||||||
|
|
||||||
|
val decoded = ImageIO.read(ByteArrayInputStream(normalized))
|
||||||
|
check(
|
||||||
|
"rotation baked into pixels (4x2 -> 2x4)",
|
||||||
|
decoded != null && decoded.width == 2 && decoded.height == 4,
|
||||||
|
)
|
||||||
|
// The stored bytes carry no orientation flag — a second pass must
|
||||||
|
// be a no-op (this is WHY the app bakes the rotation at store time).
|
||||||
|
check("normalized output is stable (no orientation flag left)", normalizer.normalize(normalized).contentEquals(normalized))
|
||||||
|
|
||||||
|
check("garbage input returned unchanged", normalizer.normalize(byteArrayOf(1, 2, 3)).contentEquals(byteArrayOf(1, 2, 3)))
|
||||||
|
|
||||||
|
if (failures == 0) {
|
||||||
|
println("RESULT: M4.4e PASS — EXIF orientation is honoured on the JVM (Android contract kept).")
|
||||||
|
} else {
|
||||||
|
println("RESULT: M4.4e FAIL — $failures check(s) failed.")
|
||||||
|
kotlin.system.exitProcess(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun jpegOf(img: BufferedImage): ByteArray {
|
||||||
|
val bos = ByteArrayOutputStream()
|
||||||
|
ImageIO.write(img, "jpeg", bos)
|
||||||
|
return bos.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splice a minimal APP1/EXIF segment (big-endian TIFF, one IFD0 entry:
|
||||||
|
* 0x0112 Orientation = 6 → "rotate 90 CW") in right after the JPEG SOI
|
||||||
|
* marker. metadata-extractor is read-only, so the probe writes its own.
|
||||||
|
*/
|
||||||
|
private fun injectExifOrientation90(jpeg: ByteArray): ByteArray {
|
||||||
|
require(jpeg[0] == 0xFF.toByte() && jpeg[1] == 0xD8.toByte()) { "not a JPEG" }
|
||||||
|
val tiff = byteArrayOf(
|
||||||
|
'M'.code.toByte(), 'M'.code.toByte(), // big-endian
|
||||||
|
0x00, 0x2A, // TIFF magic
|
||||||
|
0x00, 0x00, 0x00, 0x08, // IFD0 at offset 8
|
||||||
|
0x00, 0x01, // one entry
|
||||||
|
0x01, 0x12, // tag: Orientation
|
||||||
|
0x00, 0x03, // type: SHORT
|
||||||
|
0x00, 0x00, 0x00, 0x01, // count: 1
|
||||||
|
0x00, 0x06, 0x00, 0x00, // value: 6 (rotate 90 CW)
|
||||||
|
0x00, 0x00, 0x00, 0x00, // no next IFD
|
||||||
|
)
|
||||||
|
val payload = "Exif".toByteArray(Charsets.US_ASCII) + byteArrayOf(0, 0) + tiff
|
||||||
|
val segmentLen = payload.size + 2
|
||||||
|
val segment = byteArrayOf(
|
||||||
|
0xFF.toByte(), 0xE1.toByte(),
|
||||||
|
(segmentLen ushr 8).toByte(), (segmentLen and 0xFF).toByte(),
|
||||||
|
) + payload
|
||||||
|
return jpeg.copyOfRange(0, 2) + segment + jpeg.copyOfRange(2, jpeg.size)
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package org.incido.data.jvm
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
import kotlin.system.exitProcess
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.incido.data.ImageOrientationNormalizer
|
||||||
|
import org.incido.data.ObjectBoxStore
|
||||||
|
import org.incido.data.crypto.CipherHolder
|
||||||
|
import org.incido.data.repository.NoteRepositoryImpl
|
||||||
|
import org.incido.domain.model.Note
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase 1 (M1a) smoke test: proves the platform-neutral data layer —
|
||||||
|
* `NoteRepositoryImpl`, the entity/codegen layer, and the repository's
|
||||||
|
* hashtag/attachment logic — runs unchanged on a plain JVM.
|
||||||
|
*
|
||||||
|
* Temporary scaffolding: replaced by the real `:desktopApp` entry point in
|
||||||
|
* M1b. Run with `./gradlew :core:data-jvm:smoke`.
|
||||||
|
*/
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
val dir = File(args.firstOrNull() ?: "build/data-jvm-smoke").also { it.mkdirs() }
|
||||||
|
println("=== Incido Phase 1 M1a: shared data layer on the JVM ===")
|
||||||
|
println("library dir : $dir")
|
||||||
|
|
||||||
|
var failures = 0
|
||||||
|
fun step(name: String, body: () -> String) {
|
||||||
|
print("${name.padEnd(30)} ")
|
||||||
|
runCatching(body)
|
||||||
|
.onSuccess { println("PASS — $it") }
|
||||||
|
.onFailure {
|
||||||
|
println("FAIL — ${it::class.java.simpleName}: ${it.message}")
|
||||||
|
failures++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val holder = CipherHolder()
|
||||||
|
step("open store (shared codegen)") {
|
||||||
|
// BoxStore.getName()/getStoreDirectory() exist only in the Android
|
||||||
|
// runtime; the JVM build just reports the directory it was given.
|
||||||
|
val store = ObjectBoxStore.init(dir)
|
||||||
|
"BoxStore built; ${store.javaClass.simpleName}"
|
||||||
|
}
|
||||||
|
val repo = NoteRepositoryImpl(ObjectBoxStore.get(), holder, ImageOrientationNormalizer.NoOp)
|
||||||
|
|
||||||
|
step("save note + hashtag") {
|
||||||
|
runBlocking {
|
||||||
|
repo.saveNoteWithHashtags(
|
||||||
|
note = Note(
|
||||||
|
id = 0L,
|
||||||
|
content = "M1a smoke note\nsecond line",
|
||||||
|
createdAt = System.currentTimeMillis(),
|
||||||
|
updatedAt = System.currentTimeMillis(),
|
||||||
|
isFavorite = true,
|
||||||
|
),
|
||||||
|
hashtagsToAdd = setOf("m1a"),
|
||||||
|
hashtagsToRemove = emptySet(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
"saved"
|
||||||
|
}
|
||||||
|
|
||||||
|
step("read back through observeAll") {
|
||||||
|
val notes = runBlocking { repo.observeAll().first() }
|
||||||
|
require(notes.size == 1) { "expected 1 note, got ${notes.size}" }
|
||||||
|
val n = notes.single()
|
||||||
|
require(n.isFavorite) { "favourite flag lost" }
|
||||||
|
require(n.hashtags.contains("m1a")) { "hashtag lost: ${n.hashtags}" }
|
||||||
|
"1 note, tags=${n.hashtags}, favorite=${n.isFavorite}"
|
||||||
|
}
|
||||||
|
|
||||||
|
step("attachment round-trip") {
|
||||||
|
val noteId = runBlocking { repo.observeAll().first().single().id }
|
||||||
|
val payload = ByteArray(2048) { (it % 97).toByte() }
|
||||||
|
val id = runBlocking {
|
||||||
|
repo.addAttachment(noteId, payload, "image/png", "shot.png")
|
||||||
|
}
|
||||||
|
val back = runBlocking { repo.getAttachmentBytes(id) }
|
||||||
|
?: error("attachment not readable")
|
||||||
|
require(back.contentEquals(payload)) { "attachment bytes differ (${back.size})" }
|
||||||
|
"id=$id, ${back.size} bytes identical"
|
||||||
|
}
|
||||||
|
|
||||||
|
step("close + reopen persists") {
|
||||||
|
ObjectBoxStore.reset()
|
||||||
|
val again = ObjectBoxStore.init(dir)
|
||||||
|
val count = runBlocking {
|
||||||
|
NoteRepositoryImpl(again, holder, ImageOrientationNormalizer.NoOp)
|
||||||
|
.observeAll().first().size
|
||||||
|
}
|
||||||
|
require(count == 1) { "expected 1 note after reopen, got $count" }
|
||||||
|
"note survived close/reopen"
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjectBoxStore.reset()
|
||||||
|
println()
|
||||||
|
println(
|
||||||
|
if (failures == 0) "RESULT: M1a PASS — the shared data layer runs on the JVM."
|
||||||
|
else "RESULT: M1a FAIL — $failures step(s) failed.",
|
||||||
|
)
|
||||||
|
if (failures != 0) exitProcess(1)
|
||||||
|
}
|
||||||
@@ -41,9 +41,19 @@ android {
|
|||||||
|
|
||||||
sourceSets {
|
sourceSets {
|
||||||
getByName("main") {
|
getByName("main") {
|
||||||
// ObjectBox generates a MyObjectBox class at build time; expose
|
// NOTE: srcDirs() *replaces* the set, so every directory this
|
||||||
// the generated sources directory.
|
// module compiles has to be listed here.
|
||||||
kotlin.srcDirs("build/generated/source/objectbox")
|
kotlin.srcDirs(
|
||||||
|
// ObjectBox generates a MyObjectBox class at build time.
|
||||||
|
"build/generated/source/objectbox",
|
||||||
|
// Phase 1 (M1a): the platform-neutral data layer. The SAME
|
||||||
|
// directory is compiled by :core:data-jvm for the desktop
|
||||||
|
// build — it must contain no android.* imports.
|
||||||
|
"src/main/kotlin",
|
||||||
|
// Android-only implementations of the platform seams
|
||||||
|
// (Context-based store bootstrap, EXIF rotation).
|
||||||
|
"src/androidMain/kotlin",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
{
|
||||||
|
"_note1": "KEEP THIS FILE! Check it into a version control system (VCS) like git.",
|
||||||
|
"_note2": "ObjectBox manages crucial IDs for your object model. See docs for details.",
|
||||||
|
"_note3": "If you have VCS merge conflicts, you must resolve them according to ObjectBox docs.",
|
||||||
|
"entities": [
|
||||||
|
{
|
||||||
|
"id": "1:2086366869756073512",
|
||||||
|
"lastPropertyId": "11:3900643584337280163",
|
||||||
|
"name": "NoteEntity",
|
||||||
|
"properties": [
|
||||||
|
{
|
||||||
|
"id": "1:504738300062779212",
|
||||||
|
"name": "id",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:934725261850395537",
|
||||||
|
"name": "content",
|
||||||
|
"type": 9
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3:7787800412489145126",
|
||||||
|
"name": "createdAt",
|
||||||
|
"indexId": "1:2377104061956606005",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "4:7214601561419742071",
|
||||||
|
"name": "updatedAt",
|
||||||
|
"type": 6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "5:8997711518431222149",
|
||||||
|
"name": "isFavorite",
|
||||||
|
"indexId": "2:2889322420050596277",
|
||||||
|
"type": 1,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "6:2157877161769308588",
|
||||||
|
"name": "colorKey",
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "7:9124062984393699059",
|
||||||
|
"name": "cipherVersion",
|
||||||
|
"type": 5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "8:505259681403080579",
|
||||||
|
"name": "contentBlob",
|
||||||
|
"type": 23
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "9:2838488564098834737",
|
||||||
|
"name": "isTrashed",
|
||||||
|
"indexId": "7:9172152715891628247",
|
||||||
|
"type": 1,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "10:5547426387212371555",
|
||||||
|
"name": "typeKey",
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "11:3900643584337280163",
|
||||||
|
"name": "isDraft",
|
||||||
|
"indexId": "8:9185376899648223266",
|
||||||
|
"type": 1,
|
||||||
|
"flags": 8
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relations": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:2528940840759116824",
|
||||||
|
"lastPropertyId": "2:6290673541624313354",
|
||||||
|
"name": "HashtagEntity",
|
||||||
|
"properties": [
|
||||||
|
{
|
||||||
|
"id": "1:6991393863924167484",
|
||||||
|
"name": "id",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:6290673541624313354",
|
||||||
|
"name": "name",
|
||||||
|
"indexId": "3:8935974229325273672",
|
||||||
|
"type": 9,
|
||||||
|
"flags": 2048
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relations": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3:1814708994588042328",
|
||||||
|
"lastPropertyId": "3:4619895459374594011",
|
||||||
|
"name": "NoteHashtagCrossRef",
|
||||||
|
"properties": [
|
||||||
|
{
|
||||||
|
"id": "1:8394679598512920368",
|
||||||
|
"name": "id",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:7132785913803437080",
|
||||||
|
"name": "noteId",
|
||||||
|
"indexId": "4:4609493987894622099",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3:4619895459374594011",
|
||||||
|
"name": "hashtagId",
|
||||||
|
"indexId": "5:4178528765644585892",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 8
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relations": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "4:715630424595534313",
|
||||||
|
"lastPropertyId": "9:5604884960166980615",
|
||||||
|
"name": "NoteAttachmentEntity",
|
||||||
|
"properties": [
|
||||||
|
{
|
||||||
|
"id": "1:8895066388904375968",
|
||||||
|
"name": "id",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2:5099883303141941942",
|
||||||
|
"name": "noteId",
|
||||||
|
"indexId": "6:644263235201197567",
|
||||||
|
"type": 6,
|
||||||
|
"flags": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3:5923891227223085632",
|
||||||
|
"name": "mimeType",
|
||||||
|
"type": 9
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "4:5969004045087908818",
|
||||||
|
"name": "displayName",
|
||||||
|
"type": 9
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "5:1484939891319950467",
|
||||||
|
"name": "createdAt",
|
||||||
|
"type": 6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "6:4541111239334797694",
|
||||||
|
"name": "sizeBytes",
|
||||||
|
"type": 6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "7:5483350198068298485",
|
||||||
|
"name": "bytes",
|
||||||
|
"type": 23
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "8:6354828434115894982",
|
||||||
|
"name": "cipherVersion",
|
||||||
|
"type": 5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "9:5604884960166980615",
|
||||||
|
"name": "bytesBlob",
|
||||||
|
"type": 23
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relations": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"lastEntityId": "4:715630424595534313",
|
||||||
|
"lastIndexId": "8:9185376899648223266",
|
||||||
|
"lastRelationId": "0:0",
|
||||||
|
"lastSequenceId": "0:0",
|
||||||
|
"modelVersion": 5,
|
||||||
|
"modelVersionParserMinimum": 5,
|
||||||
|
"retiredEntityUids": [],
|
||||||
|
"retiredIndexUids": [],
|
||||||
|
"retiredPropertyUids": [],
|
||||||
|
"retiredRelationUids": [],
|
||||||
|
"version": 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package org.incido.data
|
||||||
|
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.Matrix
|
||||||
|
import androidx.exifinterface.media.ExifInterface
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Android [ImageOrientationNormalizer].
|
||||||
|
*
|
||||||
|
* v0.3.1.2 — rotate [bytes] to match the EXIF Orientation tag, then
|
||||||
|
* re-encode as JPEG so the stored bytes carry no orientation flag
|
||||||
|
* (downstream renderers — editor thumbnail, card thumbnail, viewer —
|
||||||
|
* all decode raw pixels without honouring EXIF, so the rotation is
|
||||||
|
* baked into the bitmap at storage time). Returns the input unchanged
|
||||||
|
* when the orientation is normal, the bitmap can't be decoded, or the
|
||||||
|
* rotation fails for any reason.
|
||||||
|
*
|
||||||
|
* Behaviour is byte-for-byte the code that lived in
|
||||||
|
* `NoteRepositoryImpl.normalizeImageOrientation` before the Phase-1 M1a
|
||||||
|
* platform split; only the enclosing type changed.
|
||||||
|
*/
|
||||||
|
class AndroidImageOrientationNormalizer : ImageOrientationNormalizer {
|
||||||
|
|
||||||
|
override fun normalize(bytes: ByteArray): ByteArray {
|
||||||
|
val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return bytes
|
||||||
|
val angle = ExifInterface(ByteArrayInputStream(bytes))
|
||||||
|
.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
|
||||||
|
.let {
|
||||||
|
when (it) {
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_90 -> 90f
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_180 -> 180f
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_270 -> 270f
|
||||||
|
else -> 0f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (angle == 0f) return bytes
|
||||||
|
val matrix = Matrix().apply { postRotate(angle) }
|
||||||
|
val rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, matrix, true)
|
||||||
|
bmp.recycle()
|
||||||
|
val out = ByteArrayOutputStream().use { baos ->
|
||||||
|
rotated.compress(Bitmap.CompressFormat.JPEG, 92, baos)
|
||||||
|
rotated.recycle()
|
||||||
|
baos.toByteArray()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
@@ -0,0 +1,26 @@
|
|||||||
|
package org.incido.data
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase 1 (M1a) platform seam for image normalisation.
|
||||||
|
*
|
||||||
|
* The Android app rotates inbound JPEGs against their EXIF Orientation tag
|
||||||
|
* at storage time, because every render path (card thumbnail, editor
|
||||||
|
* thumbnail, full-screen viewer) decodes raw pixels without honouring EXIF.
|
||||||
|
* That behaviour is Android-specific (`Bitmap` + `androidx.exifinterface`),
|
||||||
|
* so it is injected here and the repository stays platform-neutral.
|
||||||
|
*
|
||||||
|
* Android passes `AndroidImageOrientationNormalizer` (`:core:data`).
|
||||||
|
* Desktop currently passes [NoOp]; a JVM implementation (EXIF parse +
|
||||||
|
* re-encode) is milestone M4 — see tools/DESKTOP_FEASIBILITY.md.
|
||||||
|
*/
|
||||||
|
interface ImageOrientationNormalizer {
|
||||||
|
/** Return the bytes that should be stored for this image. */
|
||||||
|
fun normalize(bytes: ByteArray): ByteArray
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** Stores inbound images exactly as received. */
|
||||||
|
val NoOp: ImageOrientationNormalizer = object : ImageOrientationNormalizer {
|
||||||
|
override fun normalize(bytes: ByteArray): ByteArray = bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-5
@@ -1,14 +1,13 @@
|
|||||||
package org.incido.compose.data.security
|
package org.incido.data.crypto
|
||||||
|
|
||||||
import java.security.SecureRandom
|
import java.security.SecureRandom
|
||||||
import javax.crypto.Cipher
|
import javax.crypto.Cipher
|
||||||
import javax.crypto.spec.GCMParameterSpec
|
import javax.crypto.spec.GCMParameterSpec
|
||||||
import javax.crypto.spec.SecretKeySpec
|
import javax.crypto.spec.SecretKeySpec
|
||||||
import org.incido.data.crypto.FieldCipher
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* v0.3.5.0: AES-256-GCM implementation of [FieldCipher] backed by the
|
* v0.3.5.0: AES-256-GCM implementation of [FieldCipher] backed by the
|
||||||
* Keystore-wrapped 32-byte key owned by [ObjectBoxKeyProvider].
|
* 32-byte key served by a [FieldKeyProvider].
|
||||||
*
|
*
|
||||||
* This is what actually makes "Encrypt in place" work: note content
|
* This is what actually makes "Encrypt in place" work: note content
|
||||||
* and attachment blobs are stored as
|
* and attachment blobs are stored as
|
||||||
@@ -23,9 +22,14 @@ import org.incido.data.crypto.FieldCipher
|
|||||||
* primitives (public-key exchange / signatures) are not used here.
|
* primitives (public-key exchange / signatures) are not used here.
|
||||||
*
|
*
|
||||||
* The key bytes are cached for the process lifetime (they already live
|
* The key bytes are cached for the process lifetime (they already live
|
||||||
* in memory whenever [ObjectBoxKeyProvider] unwraps them at startup).
|
* in memory whenever the provider serves them at startup — Keystore
|
||||||
|
* unwrap on Android, key-file read on desktop).
|
||||||
|
*
|
||||||
|
* Phase 1 (M3 task 2): moved from :composeApp into the shared data layer
|
||||||
|
* behind the [FieldKeyProvider] seam — the class itself never touched
|
||||||
|
* Android APIs, only the key source did. Compiled for BOTH platforms.
|
||||||
*/
|
*/
|
||||||
class AesGcmFieldCipher(keyProvider: ObjectBoxKeyProvider) : FieldCipher {
|
class AesGcmFieldCipher(keyProvider: FieldKeyProvider) : FieldCipher {
|
||||||
|
|
||||||
private val keyBytes: ByteArray = keyProvider.getOrCreateKey()
|
private val keyBytes: ByteArray = keyProvider.getOrCreateKey()
|
||||||
private val secretKey = SecretKeySpec(keyBytes, "AES")
|
private val secretKey = SecretKeySpec(keyBytes, "AES")
|
||||||
+1
-3
@@ -1,4 +1,4 @@
|
|||||||
package org.incido.compose.data.security
|
package org.incido.data.crypto
|
||||||
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
@@ -8,8 +8,6 @@ import kotlinx.coroutines.flow.asStateFlow
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import org.incido.data.crypto.EncryptionVerification
|
|
||||||
import org.incido.data.crypto.NoteCryptoService
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* v0.3.5.0: runs the note-encryption integrity check and exposes the
|
* v0.3.5.0: runs the note-encryption integrity check and exposes the
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package org.incido.data.crypto
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase 1 (M3 task 2): the platform seam the field cipher is built on.
|
||||||
|
*
|
||||||
|
* [AesGcmFieldCipher] only ever needs "the 32-byte field key, get it or
|
||||||
|
* make one" — everything else about where the key lives is platform
|
||||||
|
* territory:
|
||||||
|
*
|
||||||
|
* - Android: `ObjectBoxKeyProvider` (Keystore-wrapped key persisted in
|
||||||
|
* DataStore) is passed as `objectBoxKeyProvider::getOrCreateKey`.
|
||||||
|
* - Desktop: a JVM key provider (M3 task 3) reads/generates a `0600`
|
||||||
|
* key file, or installs the key imported through an
|
||||||
|
* [org.incido.compose.data.backup.EncryptedKeyCodec] recovery
|
||||||
|
* envelope.
|
||||||
|
*
|
||||||
|
* Declared `fun interface` so both platforms can pass a plain function
|
||||||
|
* reference / lambda instead of a class.
|
||||||
|
*/
|
||||||
|
fun interface FieldKeyProvider {
|
||||||
|
/** Return the 32-byte field key, creating and persisting one if none
|
||||||
|
* exists yet. Idempotent; blocking by design (startup call site). */
|
||||||
|
fun getOrCreateKey(): ByteArray
|
||||||
|
}
|
||||||
@@ -1,15 +1,9 @@
|
|||||||
package org.incido.data.repository
|
package org.incido.data.repository
|
||||||
|
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.graphics.BitmapFactory
|
|
||||||
import android.graphics.Matrix
|
|
||||||
import androidx.exifinterface.media.ExifInterface
|
|
||||||
import io.objectbox.BoxStore
|
import io.objectbox.BoxStore
|
||||||
import io.objectbox.kotlin.boxFor
|
import io.objectbox.kotlin.boxFor
|
||||||
import io.objectbox.query.QueryBuilder
|
import io.objectbox.query.QueryBuilder
|
||||||
import io.objectbox.reactive.DataSubscription
|
import io.objectbox.reactive.DataSubscription
|
||||||
import java.io.ByteArrayInputStream
|
|
||||||
import java.io.ByteArrayOutputStream
|
|
||||||
import java.util.concurrent.Callable
|
import java.util.concurrent.Callable
|
||||||
import kotlinx.coroutines.channels.awaitClose
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -17,6 +11,7 @@ import kotlinx.coroutines.flow.callbackFlow
|
|||||||
import kotlinx.coroutines.flow.flowOn
|
import kotlinx.coroutines.flow.flowOn
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import org.incido.data.ImageOrientationNormalizer
|
||||||
import org.incido.data.crypto.CIPHER_VERSION_AES_GCM
|
import org.incido.data.crypto.CIPHER_VERSION_AES_GCM
|
||||||
import org.incido.data.crypto.CIPHER_VERSION_PLAIN
|
import org.incido.data.crypto.CIPHER_VERSION_PLAIN
|
||||||
import org.incido.data.crypto.CipherHolder
|
import org.incido.data.crypto.CipherHolder
|
||||||
@@ -64,6 +59,13 @@ import org.incido.domain.repository.NoteRepository
|
|||||||
class NoteRepositoryImpl(
|
class NoteRepositoryImpl(
|
||||||
private val boxStore: BoxStore,
|
private val boxStore: BoxStore,
|
||||||
private val cipherHolder: CipherHolder = CipherHolder(),
|
private val cipherHolder: CipherHolder = CipherHolder(),
|
||||||
|
/**
|
||||||
|
* Phase 1 (M1a): EXIF rotation is applied by the platform that owns an
|
||||||
|
* image decoder, so the repository itself compiles for Android *and* the
|
||||||
|
* desktop JVM build. Required (no default) on purpose — a missing
|
||||||
|
* implementation must fail the build, not silently store rotated JPEGs.
|
||||||
|
*/
|
||||||
|
private val orientationNormalizer: ImageOrientationNormalizer,
|
||||||
) : NoteRepository {
|
) : NoteRepository {
|
||||||
|
|
||||||
private val fieldCipher get() = cipherHolder.cipher
|
private val fieldCipher get() = cipherHolder.cipher
|
||||||
@@ -248,6 +250,7 @@ class NoteRepositoryImpl(
|
|||||||
bytes: ByteArray,
|
bytes: ByteArray,
|
||||||
mimeType: String,
|
mimeType: String,
|
||||||
displayName: String,
|
displayName: String,
|
||||||
|
createdAt: Long,
|
||||||
): Long {
|
): Long {
|
||||||
// v0.3.1.2 — honour the EXIF Orientation tag on inbound images
|
// v0.3.1.2 — honour the EXIF Orientation tag on inbound images
|
||||||
// (camera intent usually writes landscape pixels + an EXIF
|
// (camera intent usually writes landscape pixels + an EXIF
|
||||||
@@ -255,7 +258,7 @@ class NoteRepositoryImpl(
|
|||||||
// (editor thumbnail, card thumbnail, full-screen viewer) sees
|
// (editor thumbnail, card thumbnail, full-screen viewer) sees
|
||||||
// the photo the right way up. Non-images pass through unchanged.
|
// the photo the right way up. Non-images pass through unchanged.
|
||||||
val storedBytes: ByteArray = if (mimeType.startsWith("image/")) {
|
val storedBytes: ByteArray = if (mimeType.startsWith("image/")) {
|
||||||
withContext(Dispatchers.IO) { normalizeImageOrientation(bytes) }
|
withContext(Dispatchers.IO) { orientationNormalizer.normalize(bytes) }
|
||||||
} else {
|
} else {
|
||||||
bytes
|
bytes
|
||||||
}
|
}
|
||||||
@@ -263,7 +266,9 @@ class NoteRepositoryImpl(
|
|||||||
noteId = noteId,
|
noteId = noteId,
|
||||||
mimeType = mimeType,
|
mimeType = mimeType,
|
||||||
displayName = displayName,
|
displayName = displayName,
|
||||||
createdAt = System.currentTimeMillis(),
|
// IMPORT FIX (Phase 1, M2): backup import supplies the phone's
|
||||||
|
// original timestamp; 0 keeps the old "now" behaviour.
|
||||||
|
createdAt = createdAt.takeIf { it != 0L } ?: System.currentTimeMillis(),
|
||||||
sizeBytes = storedBytes.size.toLong(),
|
sizeBytes = storedBytes.size.toLong(),
|
||||||
bytes = storedBytes,
|
bytes = storedBytes,
|
||||||
)
|
)
|
||||||
@@ -425,37 +430,10 @@ class NoteRepositoryImpl(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* v0.3.1.2 — rotate [bytes] to match the EXIF Orientation tag, then
|
* v0.3.1.2 EXIF rotation now lives behind [ImageOrientationNormalizer]
|
||||||
* re-encode as JPEG so the stored bytes have no orientation flag
|
* (Phase 1, M1a) — see `AndroidImageOrientationNormalizer` in
|
||||||
* (downstream renderers — editor thumbnail, card thumbnail, viewer
|
* `core/data/src/androidMain`.
|
||||||
* — all decode raw pixels without honouring EXIF, so we bake the
|
|
||||||
* rotation into the bitmap at storage time). Returns the input
|
|
||||||
* unchanged when the orientation is normal, the bitmap can't be
|
|
||||||
* decoded, or the rotation fails for any reason.
|
|
||||||
*/
|
*/
|
||||||
private fun normalizeImageOrientation(bytes: ByteArray): ByteArray {
|
|
||||||
val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return bytes
|
|
||||||
val angle = ExifInterface(ByteArrayInputStream(bytes))
|
|
||||||
.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
|
|
||||||
.let {
|
|
||||||
when (it) {
|
|
||||||
ExifInterface.ORIENTATION_ROTATE_90 -> 90f
|
|
||||||
ExifInterface.ORIENTATION_ROTATE_180 -> 180f
|
|
||||||
ExifInterface.ORIENTATION_ROTATE_270 -> 270f
|
|
||||||
else -> 0f
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (angle == 0f) return bytes
|
|
||||||
val matrix = Matrix().apply { postRotate(angle) }
|
|
||||||
val rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, matrix, true)
|
|
||||||
bmp.recycle()
|
|
||||||
val out = ByteArrayOutputStream().use { baos ->
|
|
||||||
rotated.compress(Bitmap.CompressFormat.JPEG, 92, baos)
|
|
||||||
rotated.recycle()
|
|
||||||
baos.toByteArray()
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun removeAttachment(id: Long) {
|
override suspend fun removeAttachment(id: Long) {
|
||||||
attachmentBox.remove(id)
|
attachmentBox.remove(id)
|
||||||
@@ -468,7 +446,15 @@ class NoteRepositoryImpl(
|
|||||||
override suspend fun upsert(note: Note): Note {
|
override suspend fun upsert(note: Note): Note {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
val toPersist = if (note.id == 0L) {
|
val toPersist = if (note.id == 0L) {
|
||||||
note.copy(createdAt = now, updatedAt = now).toEntity()
|
// IMPORT FIX (Phase 1, M2): a caller that supplies a real
|
||||||
|
// createdAt/updatedAt (backup import must — they are the dedupe
|
||||||
|
// key and the user's own history) is honoured; 0 still means
|
||||||
|
// "now". The Android editor already stamps both fields itself,
|
||||||
|
// so this only changes the import path.
|
||||||
|
note.copy(
|
||||||
|
createdAt = note.createdAt.takeIf { it != 0L } ?: now,
|
||||||
|
updatedAt = note.updatedAt.takeIf { it != 0L } ?: now,
|
||||||
|
).toEntity()
|
||||||
} else {
|
} else {
|
||||||
note.copy(updatedAt = now).toEntity()
|
note.copy(updatedAt = now).toEntity()
|
||||||
}
|
}
|
||||||
@@ -571,7 +557,12 @@ class NoteRepositoryImpl(
|
|||||||
): Note {
|
): Note {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
val toPersist = if (note.id == 0L) {
|
val toPersist = if (note.id == 0L) {
|
||||||
note.copy(createdAt = now, updatedAt = now).toEntity()
|
// IMPORT FIX (Phase 1, M2): honour caller-supplied timestamps
|
||||||
|
// (backup import) — see the matching change in upsert().
|
||||||
|
note.copy(
|
||||||
|
createdAt = note.createdAt.takeIf { it != 0L } ?: now,
|
||||||
|
updatedAt = note.updatedAt.takeIf { it != 0L } ?: now,
|
||||||
|
).toEntity()
|
||||||
} else {
|
} else {
|
||||||
note.copy(updatedAt = now).toEntity()
|
note.copy(updatedAt = now).toEntity()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,45 @@
|
|||||||
// core/domain — pure-Kotlin domain module (no Android dependencies).
|
// core/domain — pure-Kotlin domain module (no Android dependencies).
|
||||||
// Contains business types and repository interfaces only.
|
// Contains business types and repository interfaces only.
|
||||||
// Implementation lives in :core:data.
|
// Implementation lives in :core:data.
|
||||||
|
//
|
||||||
|
// Phase 1 (M4.2): converted kotlin("jvm") → kotlin("multiplatform") with
|
||||||
|
// androidTarget() + jvm(), per the Phase-0 recommendation ("core:domain is
|
||||||
|
// already JVM-clean — convert it first. Zero code changes"). This is what
|
||||||
|
// lets a KMP module's commonMain (composeApp) depend on it — plain
|
||||||
|
// kotlin("jvm") modules are invisible to commonMain. Existing plain-JVM
|
||||||
|
// (:core:data-jvm, :desktopApp) and AGP (:core:data, :app, :composeApp)
|
||||||
|
// consumers keep working through the variant metadata — zero import
|
||||||
|
// changes anywhere.
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.kotlinJvm)
|
alias(libs.plugins.androidLibrary)
|
||||||
}
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
|
|
||||||
java {
|
|
||||||
sourceCompatibility = JavaVersion.VERSION_17
|
|
||||||
targetCompatibility = JavaVersion.VERSION_17
|
|
||||||
}
|
}
|
||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
jvmToolchain(17)
|
jvmToolchain(17)
|
||||||
|
|
||||||
|
androidTarget()
|
||||||
|
jvm()
|
||||||
|
|
||||||
|
sourceSets {
|
||||||
|
commonMain.dependencies {
|
||||||
|
// Flow/StateFlow appear in the public repository interfaces.
|
||||||
|
api(libs.kotlinx.coroutines.core)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
android {
|
||||||
implementation(libs.kotlinx.coroutines.core)
|
namespace = "org.incido.domain"
|
||||||
|
compileSdk = 35
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = 26
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+5
@@ -197,12 +197,17 @@ interface NoteRepository {
|
|||||||
* verbatim in the database (ObjectBox `ByteArray` column). The
|
* verbatim in the database (ObjectBox `ByteArray` column). The
|
||||||
* generated id is returned so the caller can reference the row
|
* generated id is returned so the caller can reference the row
|
||||||
* (e.g. for display or removal).
|
* (e.g. for display or removal).
|
||||||
|
*
|
||||||
|
* [createdAt] lets backup import restore the original timestamp;
|
||||||
|
* `0` (the default) means "now", so every existing caller is
|
||||||
|
* unchanged.
|
||||||
*/
|
*/
|
||||||
suspend fun addAttachment(
|
suspend fun addAttachment(
|
||||||
noteId: Long,
|
noteId: Long,
|
||||||
bytes: ByteArray,
|
bytes: ByteArray,
|
||||||
mimeType: String,
|
mimeType: String,
|
||||||
displayName: String,
|
displayName: String,
|
||||||
|
createdAt: Long = 0L,
|
||||||
): Long
|
): Long
|
||||||
|
|
||||||
/** Delete an attachment by id. Idempotent. */
|
/** Delete an attachment by id. Idempotent. */
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
// core/settings — Phase 1 (M3 task 1): user settings, extracted from
|
||||||
|
// :composeApp so the desktop build reads and writes the SAME preferences
|
||||||
|
// file format the phone uses (`.preferences_pb`, identical keys).
|
||||||
|
//
|
||||||
|
// Phase 1 (M4.3a): converted kotlin("jvm") → kotlin("multiplatform") with
|
||||||
|
// androidTarget() + jvm(), the exact M4.2 (:core:domain) playbook. This is
|
||||||
|
// what makes SettingsRepository/UserSettings visible to a KMP commonMain —
|
||||||
|
// the gate M4.3's AppGraph needs (plain kotlin("jvm") modules are invisible
|
||||||
|
// to commonMain). Sources moved UNMODIFIED into commonMain except one two-
|
||||||
|
// line seam: runBlocking has no commonMain declaration, so snapshot() goes
|
||||||
|
// through expect/actual `blockingFirst` (both actuals identical — both our
|
||||||
|
// targets are JVM). Consumers unchanged by design: :desktopApp (plain jvm)
|
||||||
|
// and :composeApp (AGP + KMP) resolve through variant metadata.
|
||||||
|
//
|
||||||
|
// The one M3 API shape stands: SettingsRepository takes an injected
|
||||||
|
// DataStore<Preferences> instead of a Context — Android supplies the
|
||||||
|
// `preferencesDataStore(name = …)` Context-extension store, desktop builds
|
||||||
|
// one with PreferenceDataStoreFactory.create(produceFile = …) (the spike
|
||||||
|
// finding: the multiplatform core artifact has no Context extension).
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.androidLibrary)
|
||||||
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
jvmToolchain(17)
|
||||||
|
|
||||||
|
androidTarget()
|
||||||
|
jvm()
|
||||||
|
|
||||||
|
sourceSets {
|
||||||
|
commonMain.dependencies {
|
||||||
|
// Public API (constructor + flow types) exposes DataStore<Preferences> —
|
||||||
|
// api, not impl. On the Android classpath this resolves to the same
|
||||||
|
// android variant :composeApp's datastore-preferences already pulls, so
|
||||||
|
// there is no duplicate-class situation. The 1.1.1 artifact is itself
|
||||||
|
// multiplatform (its jvm variant is what the plain-JVM desktop build
|
||||||
|
// has been resolving all along).
|
||||||
|
api(libs.androidx.datastore.preferences.core)
|
||||||
|
implementation(libs.kotlinx.coroutines.core)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "org.incido.compose.data.settings"
|
||||||
|
compileSdk = 35
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = 26
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user