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

+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 {
getByName("main") {
// ObjectBox generates a MyObjectBox class at build time; expose
// the generated sources directory.
kotlin.srcDirs("build/generated/source/objectbox")
// NOTE: srcDirs() *replaces* the set, so every directory this
// module compiles has to be listed here.
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
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import androidx.exifinterface.media.ExifInterface
import io.objectbox.BoxStore
import io.objectbox.kotlin.boxFor
import io.objectbox.query.QueryBuilder
import io.objectbox.reactive.DataSubscription
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.concurrent.Callable
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
@@ -17,6 +11,7 @@ import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.Dispatchers
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_PLAIN
import org.incido.data.crypto.CipherHolder
@@ -64,6 +59,13 @@ import org.incido.domain.repository.NoteRepository
class NoteRepositoryImpl(
private val boxStore: BoxStore,
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 {
private val fieldCipher get() = cipherHolder.cipher
@@ -255,7 +257,7 @@ class NoteRepositoryImpl(
// (editor thumbnail, card thumbnail, full-screen viewer) sees
// the photo the right way up. Non-images pass through unchanged.
val storedBytes: ByteArray = if (mimeType.startsWith("image/")) {
withContext(Dispatchers.IO) { normalizeImageOrientation(bytes) }
withContext(Dispatchers.IO) { orientationNormalizer.normalize(bytes) }
} else {
bytes
}
@@ -425,37 +427,10 @@ class NoteRepositoryImpl(
}
/**
* v0.3.1.2 — rotate [bytes] to match the EXIF Orientation tag, then
* re-encode as JPEG so the stored bytes have no orientation flag
* (downstream renderers — editor thumbnail, card thumbnail, viewer
* — 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.
* v0.3.1.2 EXIF rotation now lives behind [ImageOrientationNormalizer]
* (Phase 1, M1a) — see `AndroidImageOrientationNormalizer` in
* `core/data/src/androidMain`.
*/
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) {
attachmentBox.remove(id)