diff --git a/settings.gradle.kts b/settings.gradle.kts index e6aff7f..a0a138d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -49,10 +49,8 @@ include(":core:backup") // both producing the same `.preferences_pb` format, same keys. include(":core:settings") -// --- Desktop feasibility spike (Development Plan §6.3, throwaway) --- -// Throwaway probes that answer "can the existing stack run on the JVM" -// before any of Phases 1-6 are committed to. They are additive: no module -// above is touched, and nothing outside `spike/` depends on them. -// See tools/DESKTOP_FEASIBILITY.md for the findings + how to delete these. -include(":spike:data-jvm") -include(":spike:compose-jvm") +// --- (Phase 1, M4.5) The Phase-0 spike modules :spike:data-jvm and +// :spike:compose-jvm are GONE (§6.6): everything they proved now lives in +// :core:data-jvm, :composeApp (jvm target) and :desktopApp, and the real +// screens have been hosted since M4.5b — the spike's reason to exist +// expired. Its findings live on in tools/DESKTOP_FEASIBILITY.md. diff --git a/spike/compose-jvm/build.gradle.kts b/spike/compose-jvm/build.gradle.kts deleted file mode 100644 index a15e84e..0000000 --- a/spike/compose-jvm/build.gradle.kts +++ /dev/null @@ -1,70 +0,0 @@ -// 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 deleted file mode 100644 index 0a761bf..0000000 --- a/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Color.kt +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 64f32cb..0000000 --- a/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/NoteColors.kt +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index b2f5c46..0000000 --- a/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Theme.kt +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index 91682a0..0000000 --- a/spike/compose-jvm/src/main/kotlin/org/incido/compose/ui/theme/Type.kt +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index b59fb4b..0000000 --- a/spike/compose-jvm/src/main/kotlin/org/incido/spike/compose/Main.kt +++ /dev/null @@ -1,114 +0,0 @@ -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 deleted file mode 100644 index 70f3d3f..0000000 --- a/spike/compose-jvm/src/main/kotlin/org/incido/spike/compose/SpikeUi.kt +++ /dev/null @@ -1,313 +0,0 @@ -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 deleted file mode 100644 index 7c417a3..0000000 --- a/spike/data-jvm/build.gradle.kts +++ /dev/null @@ -1,70 +0,0 @@ -// 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 deleted file mode 100644 index 4f28e4d..0000000 Binary files a/spike/data-jvm/libobjectbox-jni-linux-x64.so and /dev/null differ diff --git a/spike/data-jvm/objectbox-models/default.json b/spike/data-jvm/objectbox-models/default.json deleted file mode 100644 index 9230edc..0000000 --- a/spike/data-jvm/objectbox-models/default.json +++ /dev/null @@ -1,195 +0,0 @@ -{ - "_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 deleted file mode 100644 index bca059d..0000000 --- a/spike/data-jvm/src/main/kotlin/org/incido/compose/data/backup/EncryptedKeyCodec.kt +++ /dev/null @@ -1,148 +0,0 @@ -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 deleted file mode 100644 index acd90c1..0000000 --- a/spike/data-jvm/src/main/kotlin/org/incido/data/entity/HashtagEntity.kt +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index e32a2f9..0000000 --- a/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteAttachmentEntity.kt +++ /dev/null @@ -1,91 +0,0 @@ -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 deleted file mode 100644 index 5f7e329..0000000 --- a/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteEntity.kt +++ /dev/null @@ -1,104 +0,0 @@ -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 deleted file mode 100644 index 0113990..0000000 --- a/spike/data-jvm/src/main/kotlin/org/incido/data/entity/NoteHashtagCrossRef.kt +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index d947ea3..0000000 --- a/spike/data-jvm/src/main/kotlin/org/incido/spike/data/Main.kt +++ /dev/null @@ -1,156 +0,0 @@ -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 deleted file mode 100644 index d3912a3..0000000 --- a/spike/data-jvm/src/main/kotlin/org/incido/spike/data/PlatformProbe.kt +++ /dev/null @@ -1,138 +0,0 @@ -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 index dbaf96c..5f2eda7 100644 --- a/tools/DESKTOP_FEASIBILITY.md +++ b/tools/DESKTOP_FEASIBILITY.md @@ -730,6 +730,78 @@ each screen moves once its own android.* seam is solved. M4.5 then hosts the real screens in `:desktopApp` (replacing Main.kt's stand-in) and deletes `spike/` (§6.6). +**M4.4 — the screens: DONE.** Each screen moved once its own seam was +solved; every seam landed as expect/actual with the Android code kept +verbatim in `androidMain` (the §6.3 discipline, one seam per commit): + +- **M4.4a** — first screens (list + drawer) to commonMain. +- **M4.4b** — `ImageDecode.kt` (`decodeImageBytes`: skia + `Image.makeFromEncoded` on both targets — the BitmapFactory replacement); + `ImageViewerScreen` + card thumbnails moved. `ioDispatcher` seam. +- **M4.4c** — `NoteEditorScreen` (the big one) to commonMain behind the + **EditorIntake** seam (`rememberEditorIntake`): the Android actual is + the verbatim launcher code (camera + permission chain, SAF picker, + RECORD_AUDIO dance, FileProvider/ACTION_VIEW open, Toasts); the JVM + actual answers with AWT FileDialog + `Desktop.open` and reports + `supportsCamera/supportsVoice = false`, so the editor HIDES those + buttons (§6.5 — hidden, not stubbed). `VoiceNoteSlot` (Android renders + the untouched recorder; JVM renders nothing). `PlatformBackHandler` + (activity-compose on Android; no-op on desktop — Esc routing is M5). + The editor's `securityManager` param became a neutral + `beginExternalActivity: (() -> Unit)?`. +- **M4.4d** — the platform-neutral settings sections (Appearance / + Backup / About + `SettingsSection/Toggle/Row`) to commonMain. Design + call recorded: full commonization of the 1026-LOC SettingsScreen buys + nothing — SecuritySection is BiometricPrompt + PIN state machines; + each platform keeps its plumbing, both share the UI vocabulary. Two + callbacks went nullable to HIDE platform-incapable rows (dynamic color, + Carnet importer). Made PUBLIC in M4.5a (desktopApp is a separate module). +- **M4.4e** — the §6.3 EXIF row's "verify a JVM decoder exists" gate: + metadata-extractor 2.19.0 (first Maven Central pull of the phase) + + `JvmImageOrientationNormalizer` (BufferedImage rotate, ImageIO JPEG + @0.92) — same store-time bake contract as Android. `:core:data-jvm:orientationSmoke` + hand-splices an APP1 Orientation=6 JPEG and asserts pixels rotate + (4x2→2x4), passthroughs hold, output is flag-free. `RESULT: M4.4e PASS`. + +**M4.5 — real screens hosted; spike deleted: DONE.** + +- **M4.5a** — `DesktopSettingsScreen` composes the M4.4d sections + + desktop Encryption rows. The M2/M3 flows were SPLIT, not copied: + `BackupFlows`/`SecurityKeyFlows`/`toggleDesktopEncryption` own pick + + bridge + dialogs; the settings buttons drive the exact M2-proved code. + `--settings-smoke` composes it headlessly. +- **M4.5b** — `DesktopShell`: **the app's own NoteListScreen, + IncidoDrawer and NoteEditorScreen run on the desktop** over + `LocalAppGraph provides DesktopContainer`, themed by the shared + `IncidoTheme`. App.kt's NavHost reduces to three pieces of state. The + `--editor-smoke` leg closed the last M4 unknown: JetBrains lifecycle's + fallback ViewModelStoreOwner means `viewModel(factory=…)` just works + on the JVM. The M1b stand-in UI and the M2/M3 menu skins are deleted. +- **§6.6** — `spike/data-jvm` + `spike/compose-jvm` removed from the + build (their findings all have permanent homes now). + +Harness note for the smoke legs: the FIRST `:desktopApp:run` after a code +change sometimes rides out the `timeout` because the same invocation +rebuilds the jar first; warm re-runs auto-exit 0. Not a teardown wedge — +the app prints its legs and exits in ~20 s. + +``` +M4.4/M4.5 suite (per commit; final run this entry): + ./gradlew assembleDebug :desktopApp:build BUILD SUCCESSFUL + :composeApp:compileKotlinJvm + compileDebugKotlinAndroid SUCCESSFUL + :desktopApp:run … --self-test SELFTEST id=1 → RENDER, exit 0 + :desktopApp:run … --settings-smoke SETTINGS shown, exit 0 + :desktopApp:run … --editor-smoke EDITOR shown, exit 0 + :core:data-jvm:smoke RESULT: M1a PASS + :core:data-jvm:orientationSmoke RESULT: M4.4e PASS (5/5) + objectbox-models clean +``` + +**Next up: M5** — desktop polish: Esc/back routing through +`PlatformBackHandler` (editor discard prompt), keyboard shortcuts, +window/menu integration, packaging (`createDistributable` re-verify + +the M4.3d artifact notes), and the §9 perf pass on the real screens. +