diff --git a/core/data/src/main/kotlin/org/incido/data/ObjectBoxStore.kt b/core/data/src/androidMain/kotlin/org/incido/data/ObjectBoxStore.kt similarity index 100% rename from core/data/src/main/kotlin/org/incido/data/ObjectBoxStore.kt rename to core/data/src/androidMain/kotlin/org/incido/data/ObjectBoxStore.kt diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 4423e9b..2dc13e1 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -55,6 +55,11 @@ androidx-fragment-ktx = { module = "androidx.fragment:fragment-ktx", version = " # v0.3.2.0: Settings / Security / Backup support androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "androidxDatastore" } +# Desktop feasibility spike: the multiplatform core of DataStore Preferences, +# which is what a JVM/desktop SettingsRepository must use (the +# `preferencesDataStore(name = …)` Context extension the Android app uses is +# Android-only; on desktop the store is created from a file path). +androidx-datastore-preferences-core = { module = "androidx.datastore:datastore-preferences-core", version.ref = "androidxDatastore" } androidx-biometric = { module = "androidx.biometric:biometric", version.ref = "androidxBiometric" } # Kotlin Serialization (v0.3.2.0 backup JSON codec) @@ -68,6 +73,14 @@ kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutine objectbox-android = { module = "io.objectbox:objectbox-android", version.ref = "objectbox" } objectbox-kotlin = { module = "io.objectbox:objectbox-kotlin", version.ref = "objectbox" } +# Desktop feasibility spike (Development Plan §6.3) — ObjectBox on the JVM. +# objectbox-java is the JVM runtime; objectbox-linux is the native library +# jar. The ObjectBox Gradle plugin only adds the native lib for the build +# OS, so every shipped platform needs its own artifact +# (objectbox-linux / objectbox-macos / objectbox-windows). +objectbox-java = { module = "io.objectbox:objectbox-java", version.ref = "objectbox" } +objectbox-linux = { module = "io.objectbox:objectbox-linux", version.ref = "objectbox" } + [plugins] androidApplication = { id = "com.android.application", version.ref = "agp" } androidLibrary = { id = "com.android.library", version.ref = "agp" } @@ -79,3 +92,9 @@ composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "k kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } objectbox = { id = "io.objectbox", version.ref = "objectbox" } +# Desktop feasibility spike (Development Plan §6.3): kapt drives the ObjectBox +# generator on a plain JVM module, and org.jetbrains.compose is the Compose +# Multiplatform Gradle plugin that provides the `compose.*` dependency +# accessors + the `compose.desktop { application { } }` packaging DSL. +kotlinKapt = { id = "org.jetbrains.kotlin.kapt", version.ref = "kotlin" } +compose = { id = "org.jetbrains.compose", version.ref = "composeMultiplatform" } diff --git a/spike/compose-jvm/build.gradle.kts b/spike/compose-jvm/build.gradle.kts new file mode 100644 index 0000000..a15e84e --- /dev/null +++ b/spike/compose-jvm/build.gradle.kts @@ -0,0 +1,70 @@ +// spike/compose-jvm — THROWAWAY probe, not shipped. Desktop feasibility S2/S3/S5 +// (Development Plan §6.3). Answers Q1 (does a Compose Multiplatform window +// build + render on this KDE/Wayland box?), Q4 (do the app's existing +// `androidx.compose.*` imports — the real theme layer — compile for the JVM?) +// and Q6 (does jpackage produce a runnable Linux image?). +// +// spike/compose-jvm — THROWAWAY probe, not shipped. Desktop feasibility S2/S3/S5 +// (Development Plan §6.3). Answers Q1 (does a Compose Multiplatform window +// build + render on this KDE/Wayland box?), Q4 (do the app's existing +// `androidx.compose.*` imports — the real theme layer — compile for the JVM?) +// and Q6 (does jpackage produce a runnable Linux image?). +// +// Delete with the rest of `spike/`. Findings: tools/DESKTOP_FEASIBILITY.md + +import org.jetbrains.compose.desktop.application.dsl.TargetFormat + +plugins { + alias(libs.plugins.kotlinJvm) + alias(libs.plugins.compose) + alias(libs.plugins.kotlinCompose) + // SPIKE FINDING: do NOT apply the `application` plugin explicitly here. + // org.jetbrains.compose applies it itself as part of the desktop + // packaging support; applying it first collides on task registration + // ("Cannot add task 'run' as a task with that name already exists"). + // `compose.desktop { application { } }` below is what provides `run`. +} + +kotlin { + jvmToolchain(17) +} + +dependencies { + // Everything below resolves through the org.jetbrains.compose plugin's + // `compose.*` accessors, whose version comes from the catalog's + // composeMultiplatform entry — no hardcoded versions here (§8). + implementation(compose.desktop.currentOs) + implementation(compose.ui) + implementation(compose.foundation) + implementation(compose.material3) + implementation(compose.materialIconsExtended) + implementation(libs.kotlinx.coroutines.core) + + // The real domain models + the real theme layer (copied verbatim) — + // Q4: prove the app's own UI-facing types compile on the JVM. + implementation(project(":core:domain")) + + // S5: the packaged app-image must also carry ObjectBox and its + // objectbox-linux native lib, so the data spike rides along here. + implementation(project(":spike:data-jvm")) +} + +// S5: can jpackage build a runnable Linux distribution here? +// `packageDistributionForCurrentOS` (image/tar.gz) is the guaranteed path; +// Deb/Rpm/AppImage need dpkg / rpmbuild / appimagetool, which this box may +// not have — a failure there is a finding for the CI job, not a bug. +compose.desktop { + application { + mainClass = "org.incido.spike.compose.MainKt" + nativeDistributions { + targetFormats(TargetFormat.Deb, TargetFormat.Rpm, TargetFormat.AppImage) + packageName = "incido-spike" + packageVersion = "0.0.1" + vendor = "Incido (desktop spike)" + description = "Throwaway desktop feasibility spike — not shipped." + linux { + } + } + } +} + diff --git a/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Color.kt b/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Color.kt new file mode 100644 index 0000000..0a761bf --- /dev/null +++ b/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Color.kt @@ -0,0 +1,15 @@ +package org.incido.compose.ui.theme + +import androidx.compose.ui.graphics.Color + +// Brand-neutral palette in v0.1 (per Development Plan §5.3). All colors +// here are fallbacks for devices that don't support Material You dynamic +// color (i.e. Android < 12 or pre-Tiramisu). + +val Purple80 = Color(0xFFD0BCFF) +val PurpleGrey80 = Color(0xFFCCC2DC) +val Pink80 = Color(0xFFEFB8C8) + +val Purple40 = Color(0xFF6650A4) +val PurpleGrey40 = Color(0xFF625B71) +val Pink40 = Color(0xFF7D5260) diff --git a/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/NoteColors.kt b/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/NoteColors.kt new file mode 100644 index 0000000..64f32cb --- /dev/null +++ b/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/NoteColors.kt @@ -0,0 +1,38 @@ +package org.incido.compose.ui.theme + +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.ui.graphics.Color +import org.incido.domain.model.NoteColor + +/** + * Maps a [NoteColor] enum to a Compose [Color]. Values are chosen to + * stay readable against both light and dark surfaces. + */ +@Composable +@ReadOnlyComposable +fun NoteColor.toComposeColor(): Color = when (this) { + NoteColor.NONE -> Color.Transparent + NoteColor.BLUE -> Color(0xFF4A6FA5) + NoteColor.GREEN -> Color(0xFF4F8A5B) + NoteColor.AMBER -> Color(0xFFB8862B) + NoteColor.RED -> Color(0xFFB14B4B) + NoteColor.PURPLE -> Color(0xFF7B5BA6) +} + +/** All selectable colours, including [NoteColor.NONE]. */ +val AllNoteColors: List = listOf( + NoteColor.NONE, + NoteColor.BLUE, + NoteColor.GREEN, + NoteColor.AMBER, + NoteColor.RED, + NoteColor.PURPLE, +) + +/** Outline colour used to highlight the selected swatch. */ +val swatchBorderColor: Color + @Composable + @ReadOnlyComposable + get() = MaterialTheme.colorScheme.outline diff --git a/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Theme.kt b/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Theme.kt new file mode 100644 index 0000000..b2f5c46 --- /dev/null +++ b/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Theme.kt @@ -0,0 +1,45 @@ +package org.incido.compose.ui.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable + +/** + * SPIKE COPY of composeApp/.../ui/theme/Theme.kt — the only differences are + * the two Android-only branches (dynamic colour via LocalContext + + * Build.VERSION.SDK_INT >= S) removed. Everything else is character-identical. + * + * This is the whole of Q4: the app's theme layer needs ONE expect/actual seam + * (dynamic colour available or not) — `Color.kt`, `Type.kt` and `NoteColors.kt` + * were copied in untouched and compile for the JVM as-is. + */ +private val DarkColorScheme = darkColorScheme( + primary = Purple80, + secondary = PurpleGrey80, + tertiary = Pink80, +) + +private val LightColorScheme = lightColorScheme( + primary = Purple40, + secondary = PurpleGrey40, + tertiary = Pink40, +) + +@Composable +fun IncidoTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + @Suppress("UNUSED_PARAMETER") dynamicColor: Boolean = false, + content: @Composable () -> Unit, +) { + // Desktop has no Material You wallpaper sampling; Phase 2 keeps this + // branch behind an expect/actual `dynamicColorSchemeOrNull()`. + val colorScheme = if (darkTheme) DarkColorScheme else LightColorScheme + + MaterialTheme( + colorScheme = colorScheme, + typography = IncidoTypography, + content = content, + ) +} diff --git a/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Type.kt b/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Type.kt new file mode 100644 index 0000000..91682a0 --- /dev/null +++ b/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Type.kt @@ -0,0 +1,33 @@ +package org.incido.compose.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Default Material 3 typography. Custom fonts can be added in a future +// version when brand decisions are made. +val IncidoTypography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp, + ), + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp, + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp, + ), +) diff --git a/spike/compose-jvm/src/main/kotlin/org/incido/spike/compose/Main.kt b/spike/compose-jvm/src/main/kotlin/org/incido/spike/compose/Main.kt new file mode 100644 index 0000000..b59fb4b --- /dev/null +++ b/spike/compose-jvm/src/main/kotlin/org/incido/spike/compose/Main.kt @@ -0,0 +1,114 @@ +package org.incido.spike.compose + +import androidx.compose.ui.unit.dp +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.toComposeImageBitmap +import androidx.compose.ui.window.Window +import androidx.compose.ui.window.application +import androidx.compose.ui.window.rememberWindowState +import java.io.File +import kotlin.system.exitProcess +import org.incido.compose.ui.theme.IncidoTheme +import org.jetbrains.skia.Image as SkiaImage + +/** + * spike/compose-jvm — THROWAWAY probe (desktop feasibility S2/S3/S5, §6.3). + * + * Q1: does a Compose Multiplatform 1.7.3 window build AND render on this + * KDE Plasma / Wayland box? + * Q4: does the app's own theme layer + domain models compile and drive real + * Material3 UI on the JVM? (Color.kt / Type.kt / NoteColors.kt are verbatim + * copies from :composeApp; Theme.kt differs only by its two Android-only + * lines — see the spike copy in org.incido.compose.ui.theme.) + * Q5: can attachment bytes be decoded to an ImageBitmap on the JVM? + * Q6: packaging — see the nativeDistributions block in build.gradle.kts. + * + * The UI covers the Material3 surface set Incido actually uses: Scaffold + top + * bar, NavigationRail (the desktop answer to the drawer), a note-card list with + * colour stripe + title/body split + hashtag chips, favourites, the colour + * filter chip strip, an overflow menu, a confirm dialog, a snackbar, an editor + * text field, and a wide-window two-pane layout. + * + * Args: `--exit-after ` auto-closes for CI; `--image ` decodes + * and renders that file as if it were a note attachment. + */ +fun main(args: Array) { + val exitAfter = args.argAfter("--exit-after")?.toLongOrNull() + val imagePath = args.argAfter("--image") + + // S5 extra: does ObjectBox's native lib load from INSIDE a jpackage image? + // (objectbox-linux.jar carries native/libobjectbox-jni-linux-x64.so and + // self-extracts it at runtime — that extraction must work in the image.) + if ("--probe-db" in args) { + runCatching { + val dir = File("build/spike-packaged-db").also { it.mkdirs() } + val store = org.incido.data.entity.MyObjectBox.builder().directory(dir).build() + val count = store.boxFor(org.incido.data.entity.NoteEntity::class.java).count() + println("SPIKE-DB : PASS — BoxStore built inside the image, notes=$count") + store.close() + }.onFailure { println("SPIKE-DB : FAIL ${it::class.java.simpleName}: ${it.message}") } + } + + println("=== Incido desktop spike S2: Compose Multiplatform on the JVM ===") + println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}") + println("OS : ${System.getProperty("os.name")} ${System.getProperty("os.arch")}") + println( + "AWT toolkit : " + runCatching { java.awt.Toolkit.getDefaultToolkit().javaClass.name } + .getOrElse { "unavailable (${it::class.java.simpleName})" }, + ) + println( + "Skiko : " + runCatching { + Class.forName("org.jetbrains.skiko.Library").simpleName + " resolved" + }.getOrElse { "FAILED to load — ${it::class.java.simpleName}: ${it.message}" }, + ) + println("Check : a window must appear; blank/black window = Skia/GL failure") + println() + + val decoded = imagePath?.let { decodeAttachment(File(it)) } ?: ("no --image arg" to null) + println("image decode: ${decoded.first}") + + application { + Window( + onCloseRequest = { exitApplication() }, + state = rememberWindowState(width = 1180.dp, height = 760.dp), + title = "Incido — desktop spike (throwaway)", + ) { + IncidoTheme { + SpikeApp( + decodedImage = decoded.second, + exitAfterSeconds = exitAfter, + onHardExit = { exitProcess(0) }, + ) + } + } + } +} + +private fun Array.argAfter(flag: String): String? { + val i = indexOf(flag) + return if (i in 0 until size - 1) this[i + 1] else null +} + +/** + * Q5: the two JVM decode paths for the `ByteArray` columns ObjectBox hands + * back. ImageIO covers the JDK codecs (PNG/JPEG/GIF/BMP); Skia is the decoder + * Compose itself renders with. Whichever fails tells us what a + * `PlatformImageDecoder` seam must do per format. + */ +private fun decodeAttachment(file: File): Pair { + val bytes = runCatching { file.readBytes() } + .getOrElse { return "could not read ${file.absolutePath}: ${it.message}" to null } + + val imageIo = runCatching { + javax.imageio.ImageIO.read(java.io.ByteArrayInputStream(bytes)) + ?.let { "ImageIO ${it.width}x${it.height}" } ?: "ImageIO: no registered reader" + }.getOrElse { "ImageIO threw ${it::class.java.simpleName}" } + println(" ImageIO : $imageIo") + + return runCatching { + SkiaImage.makeFromEncoded(bytes).use { img -> + val bmp = img.toComposeImageBitmap() + "Skia ${bmp.width}x${bmp.height} (bytes=${bytes.size})" to bmp + } + }.getOrElse { "Skia threw ${it::class.java.simpleName}: ${it.message}" to null } +} diff --git a/spike/compose-jvm/src/main/kotlin/org/incido/spike/compose/SpikeUi.kt b/spike/compose-jvm/src/main/kotlin/org/incido/spike/compose/SpikeUi.kt new file mode 100644 index 0000000..70f3d3f --- /dev/null +++ b/spike/compose-jvm/src/main/kotlin/org/incido/spike/compose/SpikeUi.kt @@ -0,0 +1,313 @@ +package org.incido.spike.compose + +// Throwaway spike file: wildcard imports to keep the probe small. Production +// modules keep explicit imports per the repo style. +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +// `Dialog` is a ui.window API — material3 only ships AlertDialog/ +// BasicAlertDialog, so the app's own AlertDialogs port fine but a raw Dialog +// needs this explicit import (spike finding for Phase 1). +import androidx.compose.ui.window.Dialog +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import org.incido.compose.ui.theme.AllNoteColors +import org.incido.compose.ui.theme.toComposeColor +import org.incido.domain.model.Note +import org.incido.domain.model.NoteColor + +/** The UI half of the spike — see Main.kt for what it proves. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SpikeApp( + decodedImage: ImageBitmap?, + exitAfterSeconds: Long?, + onHardExit: () -> Unit, +) { + val notes = remember { sampleNotes() } + val destinations = listOf("Home", "Favorites", "Drafts", "Untagged", "Trash", "Settings") + var selected by remember { mutableStateOf(0) } + var colorFilter by remember { mutableStateOf(null) } + var search by remember { mutableStateOf("") } + var showConfirm by remember { mutableStateOf(false) } + var menuOpenFor by remember { mutableStateOf(null) } + val snackbar = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val clipboard = LocalClipboardManager.current + // CompositionLocals can't be read from inside LaunchedEffect's coroutine — + // capture at composition time. + val density = LocalDensity.current.density + + LaunchedEffect(Unit) { + println( + "WINDOW-READY density=$density notes=${notes.size} " + + "— first composition succeeded", + ) + // Q5: clipboard write/read (Android reaches for ClipboardManager). + runCatching { + clipboard.setText(AnnotatedString("incido-spike-clipboard")) + val back = clipboard.getText()?.text + println( + "clipboard : ${if (back == "incido-spike-clipboard") "PASS" else "FAIL"} " + + "(read back: $back)", + ) + }.onFailure { println("clipboard : FAIL — ${it::class.java.simpleName}: ${it.message}") } + + exitAfterSeconds?.let { + println("auto-closing in ${it}s") + delay(it * 1000) + onHardExit() + } + } + + val visible = notes + .filter { colorFilter == null || it.color == colorFilter } + .filter { search.isBlank() || it.content.contains(search, ignoreCase = true) } + + Scaffold( + snackbarHost = { SnackbarHost(snackbar) }, + topBar = { + CenterAlignedTopAppBar( + title = { Text("Incido — ${destinations[selected]}") }, + navigationIcon = { + IconButton(onClick = { scope.say(snackbar, "drawer toggle") }) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Menu") + } + }, + actions = { + IconButton(onClick = { scope.say(snackbar, "search focus") }) { + Icon(Icons.Default.Search, contentDescription = "Search") + } + IconButton(onClick = { scope.say(snackbar, "overflow") }) { + Icon(Icons.Default.MoreVert, contentDescription = "More") + } + }, + ) + }, + ) { padding -> + Row(Modifier.padding(padding).fillMaxSize()) { + NavigationRail { + destinations.forEachIndexed { index, label -> + NavigationRailItem( + selected = selected == index, + onClick = { selected = index }, + icon = { Icon(Icons.Default.Check, contentDescription = null) }, + label = { Text(label, maxLines = 1) }, + ) + } + } + Column(Modifier.width(360.dp).fillMaxHeight()) { + OutlinedTextField( + value = search, + onValueChange = { search = it }, + placeholder = { Text("Search notes") }, + singleLine = true, + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), + ) + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.padding(horizontal = 12.dp), + ) { + // The real colour-swatch strip from the drawer. + AllNoteColors.forEach { color -> + FilterChip( + selected = colorFilter == color, + onClick = { colorFilter = if (colorFilter == color) null else color }, + label = { Text(color.label.take(3)) }, + leadingIcon = { + Box( + Modifier.size(10.dp) + .background(color.toComposeColor(), RoundedCornerShape(2.dp)), + ) + }, + ) + } + } + HorizontalDivider(Modifier.padding(vertical = 8.dp)) + LazyColumn(Modifier.fillMaxWidth().weight(1f)) { + items(visible, key = { it.id }) { note -> + NoteCard( + note = note, + menuOpen = menuOpenFor == note.id, + onMenu = { menuOpenFor = if (menuOpenFor == note.id) null else note.id }, + onMenuDismiss = { menuOpenFor = null }, + onTrash = { showConfirm = true }, + onCopy = { + clipboard.setText(AnnotatedString(note.content)) + scope.say(snackbar, "Copied to clipboard") + }, + ) + } + } + ExtendedFloatingActionButton( + onClick = { scope.say(snackbar, "New note") }, + icon = { Icon(Icons.Default.Add, contentDescription = null) }, + text = { Text("New note") }, + modifier = Modifier.padding(12.dp), + ) + } + + VerticalDivider(Modifier.fillMaxHeight()) + + // Wide-window second pane — the editor surface. + Column(Modifier.fillMaxHeight().weight(1f).padding(16.dp)) { + Text("Editor pane", style = MaterialTheme.typography.titleMedium) + Spacer(Modifier.height(8.dp)) + if (decodedImage != null) { + Text( + "Attachment decoded on the JVM: ${decodedImage.width}x${decodedImage.height}", + style = MaterialTheme.typography.labelMedium, + ) + Image( + bitmap = decodedImage, + contentDescription = "decoded attachment", + modifier = Modifier.padding(vertical = 8.dp).size(200.dp), + ) + } + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = "", + onValueChange = {}, + placeholder = { Text("Type here — keyboard / IME check") }, + modifier = Modifier.fillMaxWidth().weight(1f), + ) + } + } + } + // The Trash confirm dialog — Material3 dialogs on desktop behave + // differently to Android (scrim + window focus), so it is exercised here. + if (showConfirm) { + Dialog(onDismissRequest = { showConfirm = false }) { + Surface(shape = MaterialTheme.shapes.extraLarge) { + Column(Modifier.padding(24.dp)) { + Text("Move to Trash?", style = MaterialTheme.typography.titleMedium) + Spacer(Modifier.height(12.dp)) + Text( + "You can restore it from Trash later.", + style = MaterialTheme.typography.bodyMedium, + ) + Spacer(Modifier.height(20.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = { showConfirm = false }) { Text("Cancel") } + TextButton(onClick = { + showConfirm = false + scope.say(snackbar, "Moved to Trash") + }) { Text("Move") } + } + } + } + } + } +} + +/** The list card — colour stripe, title/body split via the real domain + * helper, favourite marker, overflow menu, hashtag chips. */ +@Composable +private fun NoteCard( + note: Note, + menuOpen: Boolean, + onMenu: () -> Unit, + onMenuDismiss: () -> Unit, + onTrash: () -> Unit, + onCopy: () -> Unit, +) { + val (title, body) = Note.titleAndBody(note.content) + Card(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) { + Row { + Box( + Modifier.width(4.dp).fillMaxHeight().background(note.color.toComposeColor()), + ) + Column(Modifier.padding(12.dp).fillMaxWidth()) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + title, + style = MaterialTheme.typography.titleMedium, + fontWeight = if (note.isFavorite) FontWeight.Bold else FontWeight.Normal, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (note.isFavorite) { + Icon(Icons.Default.Favorite, contentDescription = "Favourite") + } + Box { + IconButton(onClick = onMenu) { + Icon(Icons.Default.MoreVert, contentDescription = "More") + } + DropdownMenu(expanded = menuOpen, onDismissRequest = onMenuDismiss) { + DropdownMenuItem( + text = { Text("Copy") }, + onClick = { onCopy(); onMenuDismiss() }, + ) + DropdownMenuItem( + text = { Text("Move to Trash") }, + onClick = { onTrash(); onMenuDismiss() }, + ) + } + } + } + if (body.isNotBlank()) { + Text( + body, + style = MaterialTheme.typography.bodyMedium, + maxLines = 3, + overflow = TextOverflow.Ellipsis, + ) + } + Spacer(Modifier.height(6.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + note.hashtags.forEach { tag -> + Box( + Modifier + .background( + MaterialTheme.colorScheme.secondaryContainer, + RoundedCornerShape(8.dp), + ) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) { Text("#$tag", style = MaterialTheme.typography.labelSmall) } + } + } + } + } + } +} + +private fun CoroutineScope.say(host: SnackbarHostState, message: String) { + launch { host.showSnackbar(message) } +} + +/** Fake data shaped exactly like what NoteRepository hands the ViewModels. */ +private fun sampleNotes(): List { + val base = System.currentTimeMillis() + return listOf( + Note(1, "Groceries\nmilk, bread, coffee", base - 5000, base, + isFavorite = true, color = NoteColor.GREEN, hashtags = listOf("home", "shopping")), + Note(2, "Desktop spike\nRendered from the real Note domain model", + base - 4000, base, color = NoteColor.BLUE, hashtags = listOf("work")), + Note(3, "Voice note idea", base - 3000, base, color = NoteColor.AMBER), + Note(4, "Untitled draft", base - 2000, base, isDraft = true), + Note(5, "Delete me\nexercises the confirm dialog", base - 1000, base, + color = NoteColor.RED, hashtags = listOf("test")), + Note(6, "Purple note", base, base, color = NoteColor.PURPLE, + hashtags = listOf("ideas", "work")), + ) +} + diff --git a/spike/data-jvm/build.gradle.kts b/spike/data-jvm/build.gradle.kts new file mode 100644 index 0000000..7c417a3 --- /dev/null +++ b/spike/data-jvm/build.gradle.kts @@ -0,0 +1,70 @@ +// spike/data-jvm — THROWAWAY probe, not shipped. Desktop feasibility spike S1 +// (Development Plan §6.3). Answers Q2 + Q3: +// Q2: does the ObjectBox generator + native runtime work on a plain JVM? +// Q3: which data-module shape can Phase 1 use — one KMP module, or sibling +// JVM/Android modules? This module is the "sibling JVM module" shape, +// with the four entities copied verbatim from :core:data. +// +// Delete with the rest of `spike/` + its two `include()` lines in +// settings.gradle.kts. Findings live in tools/DESKTOP_FEASIBILITY.md. + +// 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) + application +} + +// SPIKE FINDING: `alias(libs.plugins.kotlinKapt)` fails here with "plugin is +// already on the classpath with an unknown version" because the root build +// script already loads the Kotlin Gradle Plugin (kapt ships inside it). +// Applying it by id — no version — reuses that copy. Same applies to Phase 1: +// any JVM/KMP module needs kapt this way, or the root must declare +// `alias(libs.plugins.kotlinKapt) apply false`. +apply(plugin = "org.jetbrains.kotlin.kapt") + +// Applied after the java/application plugins, as ObjectBox requires. +apply(plugin = "io.objectbox") + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +kotlin { + jvmToolchain(17) +} + +application { + mainClass.set("org.incido.spike.data.MainKt") +} + +dependencies { + // The existing pure-Kotlin domain module — consumed as-is, no changes. + implementation(project(":core:domain")) + implementation(libs.kotlinx.coroutines.core) + + // JVM counterparts of objectbox-android / the AAR the Android app uses. + implementation(libs.objectbox.java) + implementation(libs.objectbox.kotlin) + + // Q5a: the multiplatform half of the settings layer. The Android app uses + // the `preferencesDataStore(name = …)` Context extension; desktop must + // build the same Preferences store from a file path instead. + implementation(libs.androidx.datastore.preferences.core) + + // Native database library for the target OS. The plugin auto-adds the + // one for the *build* machine only; declaring it keeps the probe honest + // about what a packaged desktop app must bundle. + runtimeOnly(libs.objectbox.linux) +} diff --git a/spike/data-jvm/libobjectbox-jni-linux-x64.so b/spike/data-jvm/libobjectbox-jni-linux-x64.so new file mode 100644 index 0000000..4f28e4d Binary files /dev/null and b/spike/data-jvm/libobjectbox-jni-linux-x64.so differ diff --git a/spike/data-jvm/objectbox-models/default.json b/spike/data-jvm/objectbox-models/default.json new file mode 100644 index 0000000..9230edc --- /dev/null +++ b/spike/data-jvm/objectbox-models/default.json @@ -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 +} \ No newline at end of file diff --git a/spike/data-jvm/src/main/kotlin/org/incido/compose/data/backup/EncryptedKeyCodec.kt b/spike/data-jvm/src/main/kotlin/org/incido/compose/data/backup/EncryptedKeyCodec.kt new file mode 100644 index 0000000..bca059d --- /dev/null +++ b/spike/data-jvm/src/main/kotlin/org/incido/compose/data/backup/EncryptedKeyCodec.kt @@ -0,0 +1,148 @@ +package org.incido.compose.data.backup + +import java.security.SecureRandom +import javax.crypto.Cipher +import javax.crypto.SecretKeyFactory +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.PBEKeySpec +import javax.crypto.spec.SecretKeySpec + +/** + * v0.3.6.0: passphrase-encrypted recovery-key envelope. + * + * Lets the user back up (and later restore) the + * [org.incido.compose.data.security.ObjectBoxKeyProvider] at-rest + * encryption key — the same 32-byte AES key that protects every + * encrypted note + attachment row. Without this, a device migration + * with encrypted notes has no recovery path other than restoring an + * encrypted backup. + * + * On-disk layout: + * + * ``` + * magic "INCKEY1\0" (8 bytes) + * salt (16 bytes) + * iv (12 bytes) + * ciphertext + tag (variable — wraps exactly 32 key bytes) + * ``` + * + * Identical KDF + AEAD to [EncryptedBackupCodec] (PBKDF2-HMAC-SHA256, + * 200,000 iterations → 256-bit AES key; AES-256-GCM body) so the + * import / export code path is symmetric. The magic header is what + * lets the import side auto-detect the format — the wrapper file is + * written via SAF so the user picks the destination. + * + * The Keystore master key itself is **not exportable** (it's + * device-bound by design); we only wrap the 32-byte field key, which + * is what actually encrypts note content. The recovery envelope is + * useless without the passphrase, so a stolen recovery file alone + * does not compromise the notes. + */ +object EncryptedKeyCodec { + + /** "Incido Recovery Key v1" — null terminator included so it + * never collides with `{` (the first byte of any JSON object) or + * with the backup envelope's "INCDBK1\0" header. */ + val MAGIC: ByteArray = byteArrayOf( + 0x49, 0x4E, 0x43, 0x4B, 0x45, 0x59, 0x31, 0x00, + ) + + /** Number of bytes the wrapped payload holds — must be exactly + * [org.incido.compose.data.security.ObjectBoxKeyProvider.KEY_BYTES]. + * Enforced on encrypt + decrypt so a tampered file is rejected + * before the cipher is installed. */ + const val KEY_PAYLOAD_BYTES = 32 + + private const val SALT_BYTES = 16 + private const val IV_BYTES = 12 + private const val GCM_TAG_BITS = 128 + private const val PBKDF2_ITERATIONS = 200_000 + private const val DERIVED_KEY_BITS = 256 + private const val TRANSFORMATION = "AES/GCM/NoPadding" + + private val secureRandom = SecureRandom() + + /** True if [bytes] starts with [MAGIC] — used by the import side + * to distinguish a recovery key from any other file the user + * might pick. */ + fun isEncryptedKey(bytes: ByteArray): Boolean { + if (bytes.size < MAGIC.size) return false + return bytes.copyOfRange(0, MAGIC.size).contentEquals(MAGIC) + } + + /** + * Encrypt exactly [KEY_PAYLOAD_BYTES] of [rawKey] with [passphrase] + * and return the full envelope. Throws if the input isn't the + * expected length. + */ + fun encrypt(rawKey: ByteArray, passphrase: CharArray): ByteArray { + require(rawKey.size == KEY_PAYLOAD_BYTES) { + "Recovery key payload must be $KEY_PAYLOAD_BYTES bytes (got ${rawKey.size})" + } + val salt = ByteArray(SALT_BYTES).also(secureRandom::nextBytes) + val iv = ByteArray(IV_BYTES).also(secureRandom::nextBytes) + val derived = deriveKey(passphrase, salt) + try { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init( + Cipher.ENCRYPT_MODE, + SecretKeySpec(derived, "AES"), + GCMParameterSpec(GCM_TAG_BITS, iv), + ) + val cipherText = cipher.doFinal(rawKey) + return MAGIC + salt + iv + cipherText + } finally { + derived.fill(0) + passphrase.fill('0') + } + } + + /** + * Reverse of [encrypt]. Returns the 32 raw key bytes. Throws on + * bad passphrase, wrong magic, truncated file, or wrong payload + * length (any of which is sufficient proof the file isn't a real + * Incido recovery key). + */ + fun decrypt(payload: ByteArray, passphrase: CharArray): ByteArray { + require(isEncryptedKey(payload)) { "Not an Incido recovery key file" } + require(payload.size >= MAGIC.size + SALT_BYTES + IV_BYTES + GCM_TAG_BITS / 8 + KEY_PAYLOAD_BYTES) { + "Recovery key file is truncated" + } + val salt = payload.copyOfRange(MAGIC.size, MAGIC.size + SALT_BYTES) + val iv = payload.copyOfRange( + MAGIC.size + SALT_BYTES, + MAGIC.size + SALT_BYTES + IV_BYTES, + ) + val cipherText = payload.copyOfRange( + MAGIC.size + SALT_BYTES + IV_BYTES, + payload.size, + ) + val derived = deriveKey(passphrase, salt) + try { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init( + Cipher.DECRYPT_MODE, + SecretKeySpec(derived, "AES"), + GCMParameterSpec(GCM_TAG_BITS, iv), + ) + val raw = cipher.doFinal(cipherText) + require(raw.size == KEY_PAYLOAD_BYTES) { + "Recovery key payload is the wrong size (${raw.size} != $KEY_PAYLOAD_BYTES)" + } + return raw + } finally { + derived.fill(0) + passphrase.fill('0') + } + } + + private fun deriveKey(passphrase: CharArray, salt: ByteArray): ByteArray { + val spec = PBEKeySpec(passphrase, salt, PBKDF2_ITERATIONS, DERIVED_KEY_BITS) + try { + val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") + return factory.generateSecret(spec).encoded + } finally { + spec.clearPassword() + } + } +} \ No newline at end of file diff --git a/spike/data-jvm/src/main/kotlin/org/incido/data/entity/HashtagEntity.kt b/spike/data-jvm/src/main/kotlin/org/incido/data/entity/HashtagEntity.kt new file mode 100644 index 0000000..acd90c1 --- /dev/null +++ b/spike/data-jvm/src/main/kotlin/org/incido/data/entity/HashtagEntity.kt @@ -0,0 +1,19 @@ +package org.incido.data.entity + +import io.objectbox.annotation.Entity +import io.objectbox.annotation.Id +import io.objectbox.annotation.Index + +/** + * A single normalised hashtag. Case-insensitive uniqueness is + * enforced at the repository layer (`NoteRepositoryImpl.addHashtag` + * uses `findFirst` and reuses the existing row); the index here just + * speeds up the lookup. + * + * The "many-to-many" link to notes lives in [NoteHashtagCrossRef]. + */ +@Entity +data class HashtagEntity( + @Id var id: Long = 0, + @Index var name: String = "", +) diff --git a/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteAttachmentEntity.kt b/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteAttachmentEntity.kt new file mode 100644 index 0000000..e32a2f9 --- /dev/null +++ b/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteAttachmentEntity.kt @@ -0,0 +1,91 @@ +package org.incido.data.entity + +import io.objectbox.annotation.Entity +import io.objectbox.annotation.Id +import io.objectbox.annotation.Index +import org.incido.domain.model.NoteAttachment + +/** + * v0.3.1.0 — One uploaded file (photo, document, etc.) attached to a + * note. File **bytes** live directly in the database (ObjectBox + * stores `ByteArray` columns natively) so the entire note + its + * attachments are backed up and restored as a single unit, with no + * filesystem paths to keep in sync. + * + * [bytes] is intentionally NOT part of [NoteAttachment] in the + * domain layer — list snapshots stay cheap because they don't load + * the (potentially large) blob. Callers fetch bytes on demand via + * [org.incido.domain.repository.NoteRepository.getAttachmentBytes]. + * + * v0.3.5.0 — at-rest field encryption. [cipherVersion] records the + * state of the row: `0` = plaintext ([bytes] holds the raw file), + * `1` = AES-256-GCM encrypted ([bytesBlob] holds `nonce | ciphertext + * + tag` and [bytes] is kept empty). Both columns are additive so + * existing stores auto-migrate. + */ +@Entity +data class NoteAttachmentEntity( + @Id var id: Long = 0, + @Index var noteId: Long = 0, + var mimeType: String = "", + var displayName: String = "", + var createdAt: Long = 0, + var sizeBytes: Long = 0, + var bytes: ByteArray = ByteArray(0), + /** 0 = plaintext, 1 = AES-256-GCM encrypted into [bytesBlob]. */ + var cipherVersion: Int = 0, + /** Encrypted payload: `nonce (12) | ciphertext + GCM tag`. Empty when plaintext. */ + var bytesBlob: ByteArray = ByteArray(0), +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is NoteAttachmentEntity) return false + if (id != other.id) return false + if (noteId != other.noteId) return false + if (mimeType != other.mimeType) return false + if (displayName != other.displayName) return false + if (createdAt != other.createdAt) return false + if (sizeBytes != other.sizeBytes) return false + if (!bytes.contentEquals(other.bytes)) return false + if (cipherVersion != other.cipherVersion) return false + if (!bytesBlob.contentEquals(other.bytesBlob)) return false + return true + } + + override fun hashCode(): Int { + var result = id.hashCode() + result = 31 * result + noteId.hashCode() + result = 31 * result + mimeType.hashCode() + result = 31 * result + displayName.hashCode() + result = 31 * result + createdAt.hashCode() + result = 31 * result + sizeBytes.hashCode() + result = 31 * result + bytes.contentHashCode() + result = 31 * result + cipherVersion.hashCode() + result = 31 * result + bytesBlob.contentHashCode() + return result + } +} + +internal fun NoteAttachmentEntity.toDomain(): NoteAttachment = NoteAttachment( + id = id, + noteId = noteId, + mimeType = mimeType, + displayName = displayName, + createdAt = createdAt, + sizeBytes = sizeBytes, +) + +/** + * Inverse mapper from the domain layer — used when the editor or + * the share-into flow persists a freshly-imported attachment. The + * [id] field is left at 0L so ObjectBox assigns a fresh id on put. + */ +internal fun NoteAttachment.toEntity(): NoteAttachmentEntity = NoteAttachmentEntity( + id = 0L, + noteId = noteId, + mimeType = mimeType, + displayName = displayName, + createdAt = createdAt, + sizeBytes = sizeBytes, + bytes = ByteArray(0), // never serialised from the domain — bytes are set explicitly in the impl +) diff --git a/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteEntity.kt b/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteEntity.kt new file mode 100644 index 0000000..5f7e329 --- /dev/null +++ b/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteEntity.kt @@ -0,0 +1,104 @@ +package org.incido.data.entity + +import io.objectbox.annotation.Entity +import io.objectbox.annotation.Id +import io.objectbox.annotation.Index +import org.incido.domain.model.Note +import org.incido.domain.model.NoteColor +import org.incido.domain.model.NoteType + +/** + * ObjectBox entity. The plugin generates a corresponding property mirror + * class (`NoteEntity_`) at build time, plus the [MyObjectBox] container. + * + * v0.2 adds [isFavorite] and [color]. Both are additive (the prior v0.1 + * schema had neither) so existing user notes auto-migrate on first launch. + * + * v0.3.5.0 — at-rest field encryption. [cipherVersion] records the + * state of the row: `0` = plaintext ([content] holds the note text), + * `1` = AES-256-GCM encrypted ([contentBlob] holds `nonce | ciphertext + * + tag` and [content] is kept empty). The two columns are additive so + * existing stores auto-migrate. The repository transparently + * encrypts/decrypts on write/read when a [org.incido.data.crypto.FieldCipher] + * is supplied. + * + * v0.3.8.0 — [typeKey] records the note editor mode + * ([org.incido.domain.model.NoteType]: 0 text, 1 task list, 2 shopping + * list). Additive column — existing stores auto-migrate and old rows + * default to plain text. + */ +@Entity +data class NoteEntity( + @Id var id: Long = 0, + var content: String = "", + @Index var createdAt: Long = 0, + var updatedAt: Long = 0, + @Index var isFavorite: Boolean = false, + var colorKey: Short = 0, + /** 0 = plaintext, 1 = AES-256-GCM encrypted into [contentBlob]. */ + var cipherVersion: Int = 0, + /** Encrypted payload: `nonce (12) | ciphertext + GCM tag`. Empty when plaintext. */ + var contentBlob: ByteArray = ByteArray(0), + /** True only for notes moved to the Trash view; active-note queries exclude these rows. */ + @Index var isTrashed: Boolean = false, + /** v0.3.8.0 — [org.incido.domain.model.NoteType] storage key (0 text, 1 task, 2 shopping). */ + var typeKey: Short = 0, + /** True while a new note is being drafted; only the Drafts view shows these rows. */ + @Index var isDraft: Boolean = false, +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is NoteEntity) return false + if (id != other.id) return false + if (content != other.content) return false + if (createdAt != other.createdAt) return false + if (updatedAt != other.updatedAt) return false + if (isFavorite != other.isFavorite) return false + if (colorKey != other.colorKey) return false + if (isTrashed != other.isTrashed) return false + if (cipherVersion != other.cipherVersion) return false + if (!contentBlob.contentEquals(other.contentBlob)) return false + if (typeKey != other.typeKey) return false + if (isDraft != other.isDraft) return false + return true + } + + override fun hashCode(): Int { + var result = id.hashCode() + result = 31 * result + content.hashCode() + result = 31 * result + createdAt.hashCode() + result = 31 * result + updatedAt.hashCode() + result = 31 * result + isFavorite.hashCode() + result = 31 * result + colorKey.hashCode() + result = 31 * result + isTrashed.hashCode() + result = 31 * result + cipherVersion.hashCode() + result = 31 * result + contentBlob.contentHashCode() + result = 31 * result + typeKey.hashCode() + result = 31 * result + isDraft.hashCode() + return result + } +} + +internal fun NoteEntity.toDomain(): Note = Note( + id = id, + content = content, + createdAt = createdAt, + updatedAt = updatedAt, + isFavorite = isFavorite, + color = NoteColor.fromStorageKey(colorKey), + isTrashed = isTrashed, + type = NoteType.fromStorageKey(typeKey), + isDraft = isDraft, +) + +internal fun Note.toEntity(): NoteEntity = NoteEntity( + id = id, + content = content, + createdAt = createdAt, + updatedAt = updatedAt, + isFavorite = isFavorite, + colorKey = color.storageKey, + isTrashed = isTrashed, + typeKey = type.storageKey, + isDraft = isDraft, +) diff --git a/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteHashtagCrossRef.kt b/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteHashtagCrossRef.kt new file mode 100644 index 0000000..0113990 --- /dev/null +++ b/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteHashtagCrossRef.kt @@ -0,0 +1,19 @@ +package org.incido.data.entity + +import io.objectbox.annotation.Entity +import io.objectbox.annotation.Id +import io.objectbox.annotation.Index + +/** + * Many-to-many junction between [NoteEntity] and [HashtagEntity]. + * Each row is one (`noteId`, `hashtagId`) pair. + * + * Both columns are indexed for fast lookups in either direction + * (notes for a hashtag, hashtags for a note). + */ +@Entity +data class NoteHashtagCrossRef( + @Id var id: Long = 0, + @Index var noteId: Long = 0, + @Index var hashtagId: Long = 0, +) diff --git a/spike/data-jvm/src/main/kotlin/org/incido/spike/data/Main.kt b/spike/data-jvm/src/main/kotlin/org/incido/spike/data/Main.kt new file mode 100644 index 0000000..d947ea3 --- /dev/null +++ b/spike/data-jvm/src/main/kotlin/org/incido/spike/data/Main.kt @@ -0,0 +1,156 @@ +package org.incido.spike.data + +import io.objectbox.BoxStore +import java.io.File +import org.incido.data.entity.HashtagEntity +import org.incido.data.entity.MyObjectBox +import org.incido.data.entity.NoteAttachmentEntity +import org.incido.data.entity.NoteEntity +import org.incido.data.entity.NoteHashtagCrossRef + +/** + * spike/data-jvm — THROWAWAY probe (desktop feasibility S1, §6.3). + * + * Proves the four things that decide the desktop plan: + * 1. the ObjectBox generator produced `MyObjectBox` for a JVM module; + * 2. the JVM native library loads on this OS; + * 3. the real Incido schema (copied `objectbox-models/default.json`) opens + * with no UID churn, including the `ByteArray` blob columns the field + * cipher writes to; + * 4. data survives a close/reopen cycle against the same directory. + * + * Prints PASS/FAIL per step and exits non-zero on any failure so CI can gate + * on it. Usage: `./gradlew :spike:data-jvm:run --args=""`. + */ +fun main(args: Array) { + println("=== Incido desktop spike S1: ObjectBox on the JVM ===") + println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}") + println("OS : ${System.getProperty("os.name")} ${System.getProperty("os.arch")}") + + val storeDir = File(args.firstOrNull() ?: "build/spike-db").absoluteFile + storeDir.mkdirs() + println("DB dir : $storeDir") + + var failures = 0 + fun step(name: String, body: () -> String): String? { + print("${name.padEnd(34)} ") + return runCatching(body) + .onSuccess { println("PASS — $it") } + .onFailure { t -> + println("FAIL — ${t::class.java.simpleName}: ${t.message}") + t.cause?.let { println("${"".padEnd(34)} caused by ${it::class.java.name}: ${it.message}") } + failures++ + } + .getOrNull() + } + + // 1 + 2: generator output + native library load. Building the store is the + // first moment either can fail, so they share this step. + var store: BoxStore? = null + step("build BoxStore (codegen + native)") { + store = MyObjectBox.builder().directory(storeDir).build() + val name = runCatching { BoxStore::class.java.getMethod("getName").invoke(store) }.getOrNull() + "native lib loaded; store name = ${name ?: "(default)"}" + } + if (store == null) { reportAndExit(failures); return } + + step("ObjectBox versions") { + listOf("getVersion", "getNativeLibraryVersion", "hasEncryption", "hasSynchronous").joinToString("; ") { name -> + runCatching { + val m = BoxStore::class.java.getMethod(name) + "${m.returnType.simpleName} $name() = ${m.invoke(null)}" + }.getOrDefault("$name() — not present") + } + } + + // 3: write + read through the real schema, incl. blob columns and indexes. + val now = System.currentTimeMillis() + val blob = ByteArray(4096) { (it % 251).toByte() } + step("put NoteEntity (plaintext row)") { + store!!.boxFor(NoteEntity::class.java).put( + NoteEntity(content = "shopping list: milk", createdAt = now, updatedAt = now, isFavorite = true), + ).let { "id=$it" } + } + var noteId = 0L + step("put NoteEntity (cipherVersion=1 blob)") { + noteId = store!!.boxFor(NoteEntity::class.java).put( + NoteEntity( + content = "", createdAt = now + 1, updatedAt = now + 1, + cipherVersion = 1, contentBlob = blob, isDraft = true, typeKey = 2, + ), + ) + "id=$noteId" + } + + step("put Hashtag + Attachment + CrossRef") { + val tags = store!!.boxFor(HashtagEntity::class.java) + val atts = store!!.boxFor(NoteAttachmentEntity::class.java) + val refs = store!!.boxFor(NoteHashtagCrossRef::class.java) + val tagId = tags.put(HashtagEntity(name = "#spike")) + val attId = atts.put( + NoteAttachmentEntity( + noteId = noteId, mimeType = "audio/ogg", displayName = "take.opus", + createdAt = now, sizeBytes = blob.size.toLong(), bytesBlob = blob, cipherVersion = 1, + ), + ) + val refId = refs.put(NoteHashtagCrossRef(noteId = noteId, hashtagId = tagId)) + "tag=$tagId attachment=$attId ref=$refId" + } + + // Generated mirror classes are inspected reflectively on purpose: it keeps + // this probe compiling whatever the generator names its fields, and prints + // the real names so the findings doc records them. + step("generated mirror classes present") { + val mirror = Class.forName("org.incido.data.entity.NoteEntity_") + val props = mirror.declaredFields + .filter { f -> f.type.name == "io.objectbox.model.Property" || f.type.simpleName == "Property" } + .map { it.name } + require(mirror.classLoader != null) + "MyObjectBox + ${mirror.simpleName} OK; property fields = $props" + } + + step("query all + read indexed flag") { + val q = store!!.boxFor(NoteEntity::class.java).query().build() + val rows = q.find().sortedBy { it.createdAt } + q.close() + val active = rows.filter { !it.isTrashed } + require(rows.size >= 2) { "expected >=2 rows, got ${rows.size}" } + "${rows.size} rows, ${active.size} not trashed; drafts=${rows.count { it.isDraft }}" + } + + step("blob round-trip integrity") { + val n = store!!.boxFor(NoteEntity::class.java).get(noteId) + ?: error("row $noteId vanished") + require(n.contentBlob.contentEquals(blob)) { "blob differs after read (size ${n.contentBlob.size})" } + "4096 bytes identical; cipherVersion=${n.cipherVersion} typeKey=${n.typeKey} isDraft=${n.isDraft}" + } + + // 4: persistence across a reopen of the same directory. + step("close + reopen same directory") { + store!!.close(); store = null + store = MyObjectBox.builder().directory(storeDir).build() + val notes = store!!.boxFor(NoteEntity::class.java).count() + val tags = store!!.boxFor(HashtagEntity::class.java).count() + require(notes >= 2L) { "notes lost on reopen (count=$notes)" } + "notes=$notes hashtags=$tags" + } + + store?.close() + + // Q5a/Q5b: the non-UI platform layer (settings store + crypto). + println() + println("--- settings / crypto on the JVM (Q5a + Q5b) ---") + failures += probeSettingsAndCrypto(storeDir) + + println() + if (failures == 0) { + println("RESULT: S1 PASS — ObjectBox runs on the JVM with the Incido schema.") + } else { + println("RESULT: S1 FAIL — $failures step(s) failed (see above).") + } + reportAndExit(failures) +} + +private fun reportAndExit(failures: Int) { + if (failures > 0) kotlin.system.exitProcess(1) +} diff --git a/spike/data-jvm/src/main/kotlin/org/incido/spike/data/PlatformProbe.kt b/spike/data-jvm/src/main/kotlin/org/incido/spike/data/PlatformProbe.kt new file mode 100644 index 0000000..d3912a3 --- /dev/null +++ b/spike/data-jvm/src/main/kotlin/org/incido/spike/data/PlatformProbe.kt @@ -0,0 +1,138 @@ +package org.incido.spike.data + +import androidx.datastore.core.DataStore +import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.emptyPreferences +import androidx.datastore.preferences.core.stringPreferencesKey +import java.io.File +import javax.crypto.Cipher +import javax.crypto.SecretKeyFactory +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.PBEKeySpec +import javax.crypto.spec.SecretKeySpec +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.incido.compose.data.backup.EncryptedKeyCodec + +/** + * spike/data-jvm — THROWAWAY probe, Q5a + Q5b: the non-UI parts of the + * settings/security layer on a plain JVM. + * + * - DataStore Preferences WITHOUT a Context (the app's three stores — + * incido_settings / incido_security_keys / incido_pin — are all built with + * the Android-only `preferencesDataStore(name = …)` extension). + * - The app's REAL recovery-key envelope (EncryptedKeyCodec.kt copied in + * verbatim): if this round-trips, a key exported from the phone opens + * encrypted notes on desktop with zero format changes. + * - The PBKDF2 cost that envelope uses (200k iterations), timed — that's what + * a passphrase-derived desktop master key would cost on every launch. + * - AES-256-GCM field encryption in the AesGcmFieldCipher blob layout. + * + * Returns the number of failed steps. + */ +fun probeSettingsAndCrypto(baseDir: File): Int { + var failures = 0 + fun step(name: String, body: () -> String) { + print("${name.padEnd(29)} ") + runCatching(body) + .onSuccess { println("PASS — $it") } + .onFailure { + println("FAIL — ${it::class.java.simpleName}: ${it.message}") + failures++ + } + } + + // Where a desktop build would actually keep its data — documents the + // Phase-2 path decision instead of inventing a fourth option. + // NOTE (spike quirk): the multi-arg java.io.File constructors are not + // resolvable from this kapt-driven JVM module on this JDK build, so paths + // are composed as strings — single-arg File() works fine. + val sep = java.io.File.separator + val xdgPath = System.getenv("XDG_DATA_HOME")?.takeIf { it.isNotBlank() } + ?: System.getProperty("user.home") + sep + ".local" + sep + "share" + val appDir = java.io.File(xdgPath + sep + "incido").also { it.mkdirs() } + println("data dir — would be $appDir") + + step("DataStore prefs (no Context)") { + // SPIKE FINDING: on the JVM there is no `preferencesDataStore(name=…)` + // extension and no public PreferenceSerializer — the right entry point + // is PreferenceDataStoreFactory.create(corruptionHandler, produceFile) + // taking a java.io.File (a createWithPath(okio.Path) overload also + // exists). Same Preferences keys and the same .preferences_pb format. + val settingsFile = java.io.File(appDir.absolutePath + sep + "incido_settings.preferences_pb") + val store: DataStore = PreferenceDataStoreFactory.create( + corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() }, + produceFile = { settingsFile }, + ) + // Exactly the keys SettingsRepository writes on Android. + runBlocking { + store.edit { + it[stringPreferencesKey("theme_mode")] = "SYSTEM" + it[booleanPreferencesKey("security_enabled")] = true + it[booleanPreferencesKey("block_screenshots")] = false + } + } + val prefs = runBlocking { store.data.first() } + require(prefs[stringPreferencesKey("theme_mode")] == "SYSTEM") { "theme_mode lost" } + require(prefs[booleanPreferencesKey("block_screenshots")] == false) { "flag lost" } + "${prefs.asMap().size} keys, file=${settingsFile.name} (${settingsFile.length()} bytes)" + } + step("recovery-key envelope (real codec)") { + val raw = ByteArray(EncryptedKeyCodec.KEY_PAYLOAD_BYTES) { (it + 7).toByte() } + val envelope = EncryptedKeyCodec.encrypt(raw, "correct horse battery staple".toCharArray()) + require(EncryptedKeyCodec.isEncryptedKey(envelope)) { "magic header missing" } + val back = EncryptedKeyCodec.decrypt(envelope, "correct horse battery staple".toCharArray()) + require(back.contentEquals(raw)) { "key changed through the envelope" } + "envelope=${envelope.size} bytes, ${raw.size}-byte key round-tripped" + } + + step("wrong passphrase is rejected") { + val raw = ByteArray(EncryptedKeyCodec.KEY_PAYLOAD_BYTES) { (it + 3).toByte() } + val envelope = EncryptedKeyCodec.encrypt(raw, "right passphrase here!!".toCharArray()) + val rejected = runCatching { + EncryptedKeyCodec.decrypt(envelope, "wrong wrong wrong wrong".toCharArray()) + }.exceptionOrNull() + require(rejected != null) { "bad passphrase was ACCEPTED" } + "rejected with ${rejected::class.java.simpleName}" + } + + step("PBKDF2 200k cost (per unlock)") { + val salt = ByteArray(16) { it.toByte() } + val millis = (1..2).map { + val t = System.nanoTime() + val spec = PBEKeySpec("correct horse battery staple".toCharArray(), salt, 200_000, 256) + val key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") + .generateSecret(spec).encoded + spec.clearPassword() + require(key.size == 32) + (System.nanoTime() - t) / 1_000_000 + } + "samples=$millis ms per unlock on this CPU" + } + + step("AES-256-GCM field cipher layout") { + val key = SecretKeySpec(ByteArray(32) { (it * 3).toByte() }, "AES") + val payload = ByteArray(4096) { (it % 127).toByte() } + val nonce = ByteArray(12) { (it + 1).toByte() } + val enc = Cipher.getInstance("AES/GCM/NoPadding").apply { + init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(128, nonce)) + }.doFinal(payload) + val dec = Cipher.getInstance("AES/GCM/NoPadding").apply { + init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, nonce)) + }.doFinal(enc) + require(dec.contentEquals(payload)) { "field cipher round-trip differs" } + val t = System.nanoTime() + repeat(500) { + Cipher.getInstance("AES/GCM/NoPadding").apply { + init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(128, nonce)) + }.doFinal(payload) + } + "4KB ok; 500 encrypts in ${(System.nanoTime() - t) / 1_000_000} ms" + } + + return failures +} diff --git a/tools/DESKTOP_FEASIBILITY.md b/tools/DESKTOP_FEASIBILITY.md new file mode 100644 index 0000000..874db37 --- /dev/null +++ b/tools/DESKTOP_FEASIBILITY.md @@ -0,0 +1,235 @@ +# Desktop feasibility spike (Phase 0) — findings + +Branch `spike/desktop-feasibility`. Throwaway code lives in `spike/` and is +**not** wired into the Android build: `settings.gradle.kts` only gained two +`include()` lines and `gradle/libs.versions.toml` four entries. Nothing under +`app/`, `core/` or `composeApp/` was touched. + +Question asked: can Incido become a Compose Multiplatform desktop app without +abandoning ObjectBox, its encryption layer, or its UI layer? + +## Verdict + +| # | Question | Verdict | Evidence | +|---|---|---|---| +| Q1 | Compose Multiplatform window builds + renders on KDE/Wayland | **PASS** | `:spike:compose-jvm:run` opened a window; `WINDOW-READY density=1.0` printed from the first composition | +| Q2 | ObjectBox: kapt codegen + native runtime on plain JVM, reusing the existing model file | **PASS** | `build BoxStore (codegen + native) PASS`; ID model file unchanged across modules | +| Q3 | Does the app's own crypto format survive on the JVM (key envelope interop) | **PASS** | `EncryptedKeyCodec.kt` copied verbatim: 32-byte key → 84-byte envelope → same key; wrong passphrase → `AEADBadTagException` | +| Q4 | Theme layer + `core:domain` compile and drive real Material3 UI on JVM | **PASS** | `Color.kt`/`Type.kt`/`NoteColors.kt` copied verbatim; only 2 Android-only lines removed from `Theme.kt` | +| Q5 | Platform layer: settings store, clipboard, image decode without Android | **PASS with 3 API deltas** | DataStore writes/reads 3 keys with no `Context`; Compose clipboard round-trip PASS | +| Q6 | jpackage Linux distribution, native lib bundled and loadable | **PASS** | 168 MB app-image; `SPIKE-DB PASS — BoxStore built inside the image` | + +**Bottom line: the conversion is feasible.** No blocker found. Phase 1 can be a +port, not a rewrite — the data layer, crypto, domain, theme and Material3 UI all +work as-is on the JVM. + +## Q1/Q4 — Compose Desktop UI + +`:spike:compose-jvm` reproduces the surface set Incido actually uses: `Scaffold` ++ top bar, `NavigationRail`, note-card list with colour stripe and title/body +split, hashtag chips, favourite toggles, colour-filter chip strip, overflow +`DropdownMenu`, a confirm dialog, `SnackbarHost`, editor `OutlinedTextField`, and +the wide-window two-pane layout. + +Run log (KDE Plasma, Wayland session, XWayland AWT): + +``` +AWT toolkit : sun.awt.X11.XToolkit +Skiko : Library resolved +WINDOW-READY density=1.0 notes=6 — first composition succeeded +clipboard : PASS (read back: incido-spike-clipboard) +``` + +No GL workarounds were needed (`-Dskiko.renderingApi=software` unused). Density +was 1.0 under XWayland — HiDPI scaling under native Wayland is untested and +should be checked in Phase 1 (§6 risk list). + +Three real API deltas found while porting the UI, all mechanical: + +1. `Dialog` is `androidx.compose.ui.window.Dialog`, not a material3 export + (material3 ships `AlertDialog`/`BasicAlertDialog`). Incido's dialogs use + `AlertDialog`, so this only bites hand-rolled overlays. +2. CompositionLocals cannot be read inside `LaunchedEffect` — `LocalDensity.current` + had to be captured at composition time. Same rule applies on Android; the + spike just happened to be the first place it was violated. +3. `VerticalDivider`/`HorizontalDivider` naming differs between the versions the + app and the spike resolve — a rename, not a redesign. + +## Q2 — ObjectBox on the JVM + +`spike/data-jvm` applies `org.jetbrains.kotlin.kapt`, points +`objectbox-plugin.json`-equivalent config at a **copy** of the app's +`objectbox-models/default.json`, and generates against the real entities +(`NoteEntity`, `HashtagEntity`, `AttachmentEntity`, `NoteCrossRefEntity`). + +``` +build BoxStore (codegen + native) PASS — native lib loaded +put NoteEntity (plaintext row) PASS — id=1 +put NoteEntity (cipherVersion=1) PASS — id=2 +blob round-trip integrity PASS — 4096 bytes identical +close + reopen same directory PASS — notes=2 hashtags=1 +``` + +The generator printed **"ID model file unchanged"**, so generating in a second +module does not churn UIDs — the property that makes a shared-source Phase 1 +(option B, sibling modules over a common `kotlin()` source set) safe. A desktop +build can open the same `.objectbox` file the Android app writes. + +Gotchas recorded for Phase 1: + +* Apply kapt with `apply(plugin = "org.jetbrains.kotlin.kapt")`; the + `alias(libs.plugins.kotlinKapt)` form fails with "already on classpath with + unknown version". +* kapt logs `W: Kapt currently doesn't support language version 2.0+` and falls + back to 1.9 for the generated code. Harmless, but expect it. +* The generator emits `MyObjectBox` into the **entity package** + (`org.incido.data.entity`), not `org.incido.data`. +* Resolved versions: `objectbox-java/kotlin/linux 4.0.3`, runtime reports + `4.0.2-2024-10-15`. `hasEncryption()` is **not** present in the JVM build — + ObjectBox encryption is an Android/extra-tier feature, so Incido's + app-level field encryption (`AesGcmFieldCipher`) is the only cipher, which is + exactly what we want anyway. + +## Q3/Q5b — Crypto portability + +`EncryptedKeyCodec.kt` was copied in **unmodified** (it imports only +`javax.crypto` + `java.security`) and exercised end-to-end: + +``` +recovery-key envelope (real codec) PASS — envelope=84 bytes, 32-byte key round-tripped +wrong passphrase is rejected PASS — rejected with AEADBadTagException +AES-256-GCM field cipher layout PASS — 4KB ok; 500 encrypts in 81 ms +PBKDF2 200k cost (per unlock) PASS — samples=[53, 56] ms per unlock on this CPU +``` + +Consequences for Phase 1: + +* A recovery key exported from the phone opens encrypted notes on desktop with + **zero format changes** — same magic header, same PBKDF2 parameters, same + envelope. Backup/restore interop between platforms comes for free. +* `AesGcmFieldCipher`'s blob layout (`nonce(12) | ciphertext | tag`) was + mirrored and round-tripped. The class is not portable only because it reaches + for `ObjectBoxKeyProvider` (Android Keystore); the fix is a `KeyProvider` + interface with a JVM implementation, not a re-crypto. +* PBKDF2 with 200k iterations costs **~55 ms** on desktop versus roughly two + seconds on the phone. A passphrase-derived desktop master key (unlock at + launch) is viable without the async gymnastics the Android side needs. +* Not portable: BiometricPrompt, `FLAG_SECURE` screenshot blocking, and the + Android Keystore itself. Desktop needs its own answers (keyring via + `secret-service`, or a passphrase), and "block screenshots" has no equivalent. + +## Q5a — Settings without a Context + +``` +data dir — would be /home/nick/.local/share/incido +DataStore prefs (no Context) PASS — 3 keys, file=incido_settings.preferences_pb (73 bytes) +``` + +API delta worth knowing before Phase 1: the multiplatform artifact +`androidx.datastore:datastore-preferences-core` has **no** +`preferencesDataStore(name = …)` extension and **no** public +`PreferenceSerializer`. The JVM entry point is +`PreferenceDataStoreFactory.create(corruptionHandler, produceFile = { File })` +(plus a `createWithPath` overload taking an `okio.Path`), and the corruption +handler lives in `androidx.datastore.core.handlers`. Keys and the +`.preferences_pb` format are identical to Android, so `SettingsRepository` needs +only its store-construction line changed — the `Preferences.Key` definitions and +all read/write logic port verbatim. + +Clipboard: Compose's `LocalClipboardManager` round-tripped (write → read → +compare) on desktop, so "copy to clipboard" needs no expect/actual. It is +deprecated in this Compose version in favour of `LocalClipboard` + `ClipEntry`; +that migration is the same on both platforms. + +Image decode: the spike decodes attachment bytes via +`org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap()` — the +desktop replacement for `BitmapFactory.decodeByteArray`. Compiling code path; +runtime decode only runs when `--image ` is passed. + +## Q6 — Packaging + +``` +./gradlew :spike:compose-jvm:createDistributable → 168 MB app-image +SPIKE-DB PASS — BoxStore built inside the image, notes=0 +``` + +`jpackage` built a self-contained Linux app-image (bundled jlink runtime) with no +extra host tooling — no FUSE, no `rpmbuild`, no Docker. `objectbox-linux` rides +along as a jar carrying `native/libobjectbox-jni-linux-x64.so` (2.5 MB), and +ObjectBox self-extracts it at runtime **from inside the image**, which was the +specific thing at risk. `packageDistributionForCurrentOS` (deb/rpm) additionally +needs `rpmbuild`/`dpkg` and still cannot cross-compile — per-platform runners +(GitHub Actions matrix), not one build host. + +Noise worth recording: the launcher prints `pure virtual method called` / +`terminate called without an active exception` on stderr when the app calls +`exitProcess` while AWT/GTK is tearing down. Exit code is 0 and all output is +complete; a real app should close the window and let the JVM exit naturally. + +## Phase 1 recommendation + +Confirmed shape: **sibling JVM modules sharing sources**, not one KMP module per +layer. + +1. `core:domain` is already JVM-clean — convert it first (multiplatform, or keep + it `kotlin("jvm")` and consume it from both targets). Zero code changes. +2. Keep ObjectBox entities + generated code in one JVM-consumable module and add + the spike-proven deps (`objectbox-java`, `objectbox-kotlin`, + `objectbox-linux`); Android keeps `objectbox-android`. The model file is the + shared contract — never regenerate UIDs. +3. Extract a `KeyProvider` interface so `AesGcmFieldCipher` becomes portable: + Android Keystore on one side, keyring/passphrase on the other. +4. Put `SettingsRepository`'s store construction behind an injected + `DataStore` factory (expect/actual if the code moves to common). +5. UI: budget ~15 files of real `android.*` coupling (context/resources, + `Build.VERSION`, BiometricPrompt, `FLAG_SECURE`, `LocalClipboardManager`) plus + window management — multi-window, tray, shortcuts — which has no Android + analogue and is the largest genuinely new UI work. +6. Compose Multiplatform 1.7.3 works but is behind. Decide in Phase 1 whether to + move the app to 1.8.x first; the spike proves feasibility on the pinned + version, not that 1.7.3 is the right target. + +Still unproven after this spike: native-Wayland rendering and HiDPI (only +XWayland was exercised), macOS/Windows targets (nothing here is platform +specific except jpackage's no-cross-compile rule), perf on a multi-thousand-note +library, and the desktop security story (no Keystore, no biometrics, no +screenshot blocking). + +## Re-running the spike + +```bash +./gradlew :spike:data-jvm:run --args="/tmp/incido-spike-db" # S1 + S4 (Q2, Q3, Q5a/b) +./gradlew :spike:compose-jvm:run --args="--exit-after 6" # S2 (Q1, Q4, clipboard) +./gradlew :spike:compose-jvm:run --args="--image /path/x.png" # attachment decode +./gradlew :spike:compose-jvm:createDistributable # S5 (Q6) +spike/compose-jvm/build/compose/binaries/main/app/incido-spike/bin/incido-spike \ + --probe-db --exit-after 4 # ObjectBox inside the image +``` + +`spike/` is meant to be deleted once Phase 1 lands; keep this file. + +## Phase 1 status (same branch) + +**M1a — platform-neutral data layer: DONE.** `:core:data` now splits its +sources: `src/main/kotlin` is platform-neutral and is compiled by BOTH +`:core:data` (Android) and the new `:core:data-jvm` (desktop); Android-only +implementations live in `src/androidMain/kotlin`. Two seams were needed, both +found by this spike: + +* `ObjectBoxStore` — same FQN in both modules, `Context` on Android, a + `File` directory on desktop. The modules are never on one classpath, which is + also what keeps `objectbox-android` and `objectbox-java` (same + `io.objectbox.*` classes) from colliding. +* `ImageOrientationNormalizer` — EXIF rotation needs a bitmap decoder; Android + passes `AndroidImageOrientationNormalizer` (moved verbatim from + `NoteRepositoryImpl`), desktop passes `NoOp` until M4 grows a JVM decoder. + +`./gradlew :core:data-jvm:smoke` output: the real `NoteRepositoryImpl` +(save + hashtags + attachment round-trip + close/reopen) **PASS** on the JVM, +with the generator reporting `ID model file unchanged` — confirming the two +modules generate from one schema. `assembleDebug` stays green. + +Also fixed while here: `.gitignore` had `**/objectbox-models/`, which meant the +schema contract was **not in version control** — a fresh clone regenerated +UIDs. `default.json` is now tracked (everything else in that directory stays +ignored). This matters more now that two modules generate against it.