feat(phase-1/m1a): platform-neutral data layer + :core:data-jvm

Phase 1 milestone M1a (Development Plan §6, desktop track): make the whole
data layer usable from a non-Android build, without touching what the
Android app compiles.

:core:data splits its sources:
  src/main/kotlin      platform-neutral — entities, repository, field
                       crypto, NoteCryptoService. Compiled by BOTH
                       :core:data and :core:data-jvm. Must not import
                       android.*
  src/androidMain/kotlin  Android-only seam implementations.

Two seams were required, both identified by the Phase-0 spike:
  ObjectBoxStore          Context on Android, a directory on desktop. Same
                          FQN in sibling modules that are never on one
                          classpath — which is also what keeps
                          objectbox-android and objectbox-java (they ship
                          the same io.objectbox.* classes) apart.
  ImageOrientationNormalizer  EXIF rotation needs a bitmap decoder; the
                          implementation moved verbatim out of
                          NoteRepositoryImpl, which is now platform-free.
                          The parameter is required, not defaulted, so a
                          platform that forgets it fails the build.

New :core:data-jvm compiles those shared sources against objectbox-java /
objectbox-linux with its own codegen. `:core:data-jvm:smoke` runs the real
NoteRepositoryImpl (save + hashtags + attachment round-trip + close/reopen)
on the JVM: PASS, with the generator reporting "ID model file unchanged" —
one schema, two generated runtimes.

Also: .gitignore excluded **/objectbox-models/, so the schema contract was
never committed and a fresh clone regenerated UIDs. default.json is now
tracked; the rest of that directory stays ignored. This matters more now
that two modules generate from it.

Verified: :core:data-jvm:smoke PASS, assembleDebug green.
This commit is contained in:
Incido Developer committed 2026-10-05 18:20:59 +13:00
1 parent 8b66e82acb
commit 9fe4763aa7
13 files changed
+753 -44

No files matched your search

+6 -3
View File
@@ -24,9 +24,12 @@ 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
# VS Code # VS Code
.vscode/ .vscode/
@@ -5,6 +5,7 @@ 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.CipherHolder import org.incido.data.crypto.CipherHolder
import org.incido.data.crypto.NoteCryptoService import org.incido.data.crypto.NoteCryptoService
@@ -75,7 +76,13 @@ class AppContainer(context: Context) {
} }
} }
val noteRepository: NoteRepository = NoteRepositoryImpl(boxStore, cipherHolder) 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)
+87
View File
@@ -0,0 +1,87 @@
// 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)
// 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")
args = listOf(layout.buildDirectory.dir("data-jvm-smoke").get().asFile.absolutePath)
}
Binary file not shown.
+195
View File
@@ -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,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)
}
+13 -3
View File
@@ -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",
)
} }
} }
} }
+195
View File
@@ -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
}
}
@@ -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
}
}
}
@@ -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
@@ -255,7 +257,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
} }
@@ -425,37 +427,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)
+13
View File
@@ -26,3 +26,16 @@ include(":app")
include(":composeApp") include(":composeApp")
include(":core:domain") include(":core:domain")
include(":core:data") include(":core:data")
// Phase 1 (M1a): the desktop build of the same data layer. It compiles
// :core:data's platform-neutral sources against the JVM ObjectBox runtime —
// see core/data-jvm/build.gradle.kts for why this is a sibling module and not
// a multiplatform one.
include(":core:data-jvm")
// --- Desktop feasibility spike (Development Plan §6.3, throwaway) ---
// Throwaway probes that answer "can the existing stack run on the JVM"
// before any of Phases 1-6 are committed to. They are additive: no module
// above is touched, and nothing outside `spike/` depends on them.
// See tools/DESKTOP_FEASIBILITY.md for the findings + how to delete these.
include(":spike:data-jvm")
include(":spike:compose-jvm")