feat(phase-1/m1b): :desktopApp — desktop shell over the real repository

Phase 1 milestone M1b: a Compose Multiplatform window driven by the same
NoteRepositoryImpl the Android app uses, over its own ObjectBox library.

  DesktopContainer  mirrors AppContainer's construction order (store,
                    CipherHolder, repository). Owns its library at
                    $XDG_DATA_HOME/incido — a separate library per machine,
                    since ObjectBox is single-writer; the backup file (M2)
                    is the only bridge to the phone. --data-dir opens
                    another library, e.g. one pulled off a phone.
  Main.kt           two panes, save-as-you-type with a 400ms debounce,
                    favourite toggle. Material 3 defaults on purpose: the
                    app's theme and screens arrive with the M4 composeApp
                    conversion, which deletes this stand-in.

Verified headlessly (--self-test drives the same repository calls the "+"
button and the star make, --exit-after auto-closes), against a library
previously written by :core:data-jvm:smoke — i.e. a different module's
generated MyObjectBox, same schema:

  RENDER notes=0 selected=null    first frame (collectAsState initial value)
  RENDER notes=1 selected=1       ObjectBox flow delivered
  SELFTEST wrote note id=2        write path through the UI's own calls
  RENDER notes=2 selected=2       and it came back through the flow
  reopen -> RENDER notes=2        persisted

Gotcha recorded in the findings doc: the first composition always sees the
empty initial value of collectAsState, so anything asserting on note counts
must watch the flow rather than the first frame.

Still synthetic: theme + screens. Not wired yet: settings, encryption (M3),
backup bridge (M2), packaging (M5). assembleDebug verified green.
This commit is contained in:
Incido Developer committed 2026-10-05 18:28:24 +13:00
1 parent 9fe4763aa7
commit 5f45b0921b
7 files changed
+442

No files matched your search

@@ -0,0 +1,51 @@
package org.incido.desktop
import java.io.File
import org.incido.data.ImageOrientationNormalizer
import org.incido.data.ObjectBoxStore
import org.incido.data.crypto.CipherHolder
import org.incido.data.repository.NoteRepositoryImpl
import org.incido.domain.repository.NoteRepository
/**
* Hand-rolled DI container for the desktop build — the JVM counterpart of
* the Android app's `AppContainer` (Development Plan §6, Phase 1, M1b).
*
* Deliberately mirrors Android's construction order: open the store, then
* build the repository over a shared [CipherHolder] so installing or removing
* at-rest encryption later is a one-line change here instead of a rebuild of
* the graph.
*
* Two Android behaviours are intentionally absent, both planned work:
* - at-rest encryption (milestone M3 — needs a JVM KeyProvider; the
* recovery-key envelope is already proven portable), and
* - EXIF rotation (milestone M4 — needs a JVM image decoder, so inbound
* images are stored exactly as received for now).
*/
class DesktopContainer(dataDir: File) {
val cipherHolder = CipherHolder()
val boxStore = ObjectBoxStore.init(dataDir)
val repository: NoteRepository = NoteRepositoryImpl(
boxStore = boxStore,
cipherHolder = cipherHolder,
orientationNormalizer = ImageOrientationNormalizer.NoOp,
)
fun shutdown() = ObjectBoxStore.reset()
}
/**
* Where the desktop library lives: `$XDG_DATA_HOME/incido`, falling back to
* `~/.local/share/incido` (Development Plan §6 — a *separate* library per
* machine; the backup file is the bridge to the phone, never the DB itself,
* because ObjectBox is single-writer).
*/
fun defaultDataDir(): File {
val sep = File.separator
val base = System.getenv("XDG_DATA_HOME")?.takeIf { it.isNotBlank() }
?: System.getProperty("user.home") + sep + ".local" + sep + "share"
return File(base + sep + "incido").also { it.mkdirs() }
}
@@ -0,0 +1,302 @@
package org.incido.desktop
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.outlined.StarBorder
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import java.io.File
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.incido.domain.model.Note
import org.incido.domain.repository.NoteRepository
/**
* Incido desktop, Phase 1 milestone M1b.
*
* The window is intentionally plain: Material 3 defaults, two panes, no
* filters yet. The point of M1b is that the *real* repository drives a real
* desktop UI; the app's own theme and screens arrive with the M4 `composeApp`
* conversion, at which point this file shrinks to just the window.
*
* What is already real: notes are read through `observeAll()` and written
* through `saveNoteWithHashtags`, so they land in the same ObjectBox schema
* the Android app writes — in its own library per machine (see
* [DesktopContainer]), bridged to the phone only by the backup file.
*
* Args: `--data-dir <path>` opens another library (e.g. a database pulled off
* a phone, to prove schema compatibility); `--exit-after <seconds>` auto-closes
* for scripted smoke runs.
*/
fun main(args: Array<String>) {
val dataDir = args.argAfter("--data-dir")
?.let { File(it).also { dir -> dir.mkdirs() } }
?: defaultDataDir()
val exitAfterSeconds = args.argAfter("--exit-after")?.toLongOrNull()
// Headless end-to-end check: write a note from inside the composition and
// watch it come back through observeAll(). Used by the M1b smoke run.
val selfTest = "--self-test" in args
println("=== Incido (desktop) — Phase 1 M1b ===")
println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}")
println("library : $dataDir")
val app = DesktopContainer(dataDir)
application {
Window(
onCloseRequest = ::exitApplication,
state = rememberWindowState(width = 1100.dp, height = 760.dp),
title = "Incido",
) {
NotesWindow(
repository = app.repository,
exitAfterSeconds = exitAfterSeconds,
selfTest = selfTest,
onExit = ::exitApplication,
)
}
}
// application{} returns once every window is closed.
app.shutdown()
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun NotesWindow(
repository: NoteRepository,
exitAfterSeconds: Long?,
selfTest: Boolean,
onExit: () -> Unit,
) {
val notes by remember(repository) { repository.observeAll() }
.collectAsState(initial = emptyList())
var selectedId by remember { mutableStateOf<Long?>(null) }
val scope = rememberCoroutineScope()
// Keep a valid selection as the library changes.
val selected = notes.firstOrNull { it.id == selectedId } ?: notes.firstOrNull()
MaterialTheme {
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text("Incido") },
actions = {
IconButton(
onClick = {
scope.launch {
val now = System.currentTimeMillis()
val saved = repository.saveNoteWithHashtags(
note = Note(
id = 0L,
content = "",
createdAt = now,
updatedAt = now,
),
hashtagsToAdd = emptySet(),
hashtagsToRemove = emptySet(),
)
selectedId = saved.id
}
},
) { Icon(Icons.Filled.Add, contentDescription = "New note") }
},
)
},
) { padding ->
Row(Modifier.fillMaxSize().padding(padding)) {
Surface(
modifier = Modifier.width(340.dp).fillMaxHeight(),
tonalElevation = 2.dp,
) {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(notes, key = { it.id }) { note ->
NoteRow(
note = note,
selected = note.id == selected?.id,
onClick = { selectedId = note.id },
onToggleFavorite = {
scope.launch {
repository.setFavorite(note.id, !note.isFavorite)
}
},
)
HorizontalDivider()
}
if (notes.isEmpty()) {
item {
Text(
"No notes yet — press + to write one.",
modifier = Modifier.padding(24.dp),
style = MaterialTheme.typography.bodyMedium,
)
}
}
}
}
Editor(repository = repository, note = selected)
}
}
}
LaunchedEffect(notes.size) {
// Logged on every change: proves the ObjectBox subscription actually
// delivers to the composition (the first frame is always the empty
// initial value of collectAsState).
println("RENDER notes=${notes.size} selected=${selected?.id}")
}
if (selfTest) {
LaunchedEffect(Unit) {
// Exactly the calls the "+" button and the star make, driven
// headlessly so the write path is verified without a mouse.
delay(1200)
val now = System.currentTimeMillis()
val saved = repository.saveNoteWithHashtags(
note = Note(
id = 0L,
content = "Written by the desktop app\nself-test line",
createdAt = now,
updatedAt = now,
),
hashtagsToAdd = emptySet(),
hashtagsToRemove = emptySet(),
)
repository.setFavorite(saved.id, true)
println("SELFTEST wrote note id=${saved.id}")
}
}
if (exitAfterSeconds != null) {
LaunchedEffect(Unit) {
delay(exitAfterSeconds * 1000)
onExit()
}
}
}
@Composable
private fun NoteRow(
note: Note,
selected: Boolean,
onClick: () -> Unit,
onToggleFavorite: () -> Unit,
) {
val (title, body) = Note.titleAndBody(note.content)
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(
title,
style = MaterialTheme.typography.titleSmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = if (selected) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurface
},
)
if (body.isNotBlank()) {
Text(
body,
style = MaterialTheme.typography.bodySmall,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
IconButton(onClick = onToggleFavorite) {
if (note.isFavorite) {
Icon(Icons.Filled.Star, contentDescription = "Unfavourite")
} else {
Icon(Icons.Outlined.StarBorder, contentDescription = "Favourite")
}
}
}
}
/** Debounced write-through editor — the same "save as you type" feel as Android. */
@Composable
private fun Editor(repository: NoteRepository, note: Note?) {
if (note == null) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text("Nothing to show yet", color = MaterialTheme.colorScheme.outline)
}
return
}
var text by remember(note.id) { mutableStateOf(note.content) }
val scope = rememberCoroutineScope()
// The saved note flows back through observeAll(); once the snapshot
// matches what is on screen there is nothing to write.
LaunchedEffect(text, note.content, note.id) {
if (text == note.content) return@LaunchedEffect
delay(400)
scope.launch {
repository.saveNoteWithHashtags(
note = note.copy(content = text),
hashtagsToAdd = emptySet(),
hashtagsToRemove = emptySet(),
)
}
}
Column(
modifier = Modifier.fillMaxSize().padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text("Editing #${note.id}", style = MaterialTheme.typography.labelMedium)
OutlinedTextField(
value = text,
onValueChange = { text = it },
modifier = Modifier.fillMaxSize(),
placeholder = { Text("Write something…") },
)
}
}
private fun Array<String>.argAfter(flag: String): String? {
val index = indexOf(flag)
return takeIf { index >= 0 && index + 1 < size }?.get(index + 1)
}