package org.incido.desktop import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme 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.Settings 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.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider 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.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.type 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 androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import java.io.File import java.io.ByteArrayInputStream import java.io.FileOutputStream import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.incido.compose.data.backup.BackupBridge import org.incido.compose.ui.theme.IncidoTheme import org.incido.compose.util.LocalPlatformBackStack import org.incido.compose.util.PlatformBackStack import org.incido.compose.data.backup.EncryptedBackupCodec import org.incido.compose.data.backup.EncryptedKeyCodec import org.incido.data.crypto.AesGcmFieldCipher 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 ` opens another library (e.g. a database pulled off * a phone, to prove schema compatibility); `--exit-after ` auto-closes * for scripted smoke runs; `--backup-import ` / `--backup-export ` * drive the Import/Export menu's exact bridge calls headlessly; * `--backup-export-enc ` + `--backup-passphrase ` add the * encrypted-envelope legs (M2 task 4). */ fun main(args: Array) { 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 // M2 scripted backup round-trip: drive the same BackupBridge calls the // Import/Export menu makes, without clicking through native dialogs. val backupImport = args.argAfter("--backup-import") val backupExport = args.argAfter("--backup-export") // M2 task 4: encrypted-envelope legs (the RequirePassphrase dialog's calls). val backupExportEnc = args.argAfter("--backup-export-enc") val backupPassphrase = args.argAfter("--backup-passphrase") // M3 task 4: scripted at-rest encryption legs — leg A enables + proves, // leg B (a SEPARATE process) proves the relaunch auto-install + sweep. // M4.5: scripted settings leg — opens the real settings screen mid-run // so the shared sections (M4.4d) render on the JVM before auto-exit. val settingsSmoke = "--settings-smoke" in args val editorSmoke = "--editor-smoke" in args // M5.1 scripted leg: drives the exact Esc dispatch path the window's // onPreviewKeyEvent uses (backStack.dispatchBack) against the real // editor and settings registrations. val keysSmoke = "--keys-smoke" in args val cryptoSelfTest = "--crypto-self-test" in args val cryptoReopen = "--crypto-reopen" in args val cryptoPassphrase = args.argAfter("--crypto-passphrase") ?: "selftest-passphrase" // Recovery-envelope file legs: --key-export writes the INCKEY1 envelope // the phone's Settings screen writes; --key-import reads one (e.g. a // REAL phone export) with the passphrase and installs the key — the // scripted version of the SecurityActions import menu. val keyExport = args.argAfter("--key-export") val keyImport = args.argAfter("--key-import") println("=== Incido (desktop) — Phase 1 M1b ===") println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}") println("library : $dataDir") val app = DesktopContainer(dataDir) // M5.1: the desktop back stack. PlatformBackHandler (composeApp jvm // actual) registers into it; Esc below drains it, topmost enabled // entry first — the editor's discard-prompt chain included, since its // BackHandler(enabled=true){tryClose()} rides the same seam. val backStack = PlatformBackStack() // M3: window geometry is desktop-only state, kept in its OWN store file // (incido_window.preferences_pb) — settings stay the phone-shared schema. // Position is deliberately NOT stored: KWin owns placement on this stack. val windowStore = preferencesStore(dataDir, "incido_window") val windowPrefs = runBlocking { windowStore.data.first() } val savedWidth = windowPrefs[intPreferencesKey("window_width")] ?.coerceIn(640, 8_000) ?: 1100 val savedHeight = windowPrefs[intPreferencesKey("window_height")] ?.coerceIn(480, 8_000) ?: 760 application { val windowState = rememberWindowState( width = savedWidth.dp, height = savedHeight.dp, ) Window( onCloseRequest = ::exitApplication, state = windowState, title = "Incido", // M5.1: Esc = system back. Consumed only when a handler is // live; otherwise it falls through so popups keep their own // Esc handling. This is the exact dispatcher --keys-smoke // drives headlessly via backStack.dispatchBack(). onPreviewKeyEvent = { event -> if (event.type == KeyEventType.KeyDown && event.key == Key.Escape) { val consumed = backStack.dispatchBack() println("KEYS esc(captured) consumed=$consumed") consumed } else { false } }, ) { CompositionLocalProvider(LocalPlatformBackStack provides backStack) { NotesWindow( app = app, repository = app.noteRepository, windowStore = windowStore, windowState = windowState, exitAfterSeconds = exitAfterSeconds, selfTest = selfTest, settingsSmoke = settingsSmoke, editorSmoke = editorSmoke, keysSmoke = keysSmoke, backupImport = backupImport, backupExport = backupExport, backupExportEnc = backupExportEnc, backupPassphrase = backupPassphrase, cryptoSelfTest = cryptoSelfTest, cryptoReopen = cryptoReopen, cryptoPassphrase = cryptoPassphrase, keyExport = keyExport, keyImport = keyImport, onExit = ::exitApplication, ) } } } // application{} returns once every window is closed. app.shutdown() } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun NotesWindow( app: DesktopContainer, repository: NoteRepository, windowStore: androidx.datastore.core.DataStore, windowState: androidx.compose.ui.window.WindowState, exitAfterSeconds: Long?, selfTest: Boolean, settingsSmoke: Boolean, editorSmoke: Boolean, keysSmoke: Boolean, backupImport: String?, backupExport: String?, backupExportEnc: String?, backupPassphrase: String?, cryptoSelfTest: Boolean, cryptoReopen: Boolean, cryptoPassphrase: String, keyExport: String?, keyImport: String?, onExit: () -> Unit, ) { val notes by remember(repository) { repository.observeAll() } .collectAsState(initial = emptyList()) // M4.5: the real settings screen replaces the M1b placeholder list. var showSettings by remember { mutableStateOf(false) } // M3: theme_mode is a real shared setting here — resolveDark picks the // scheme. M4.5b: the app's OWN IncidoTheme wraps the shell — the // shared screens get the exact color scheme + typography the phone // renders (platformDynamicColorScheme returns null on the JVM, so // dynamic color degrades to the static palettes, §6.5-honest). val userSettings by app.settingsRepository.userSettingsFlow .collectAsState(initial = org.incido.compose.data.settings.UserSettings()) val darkTheme = userSettings.themeMode.resolveDark(isSystemInDarkTheme()) IncidoTheme(darkTheme = darkTheme, dynamicColor = false) { // M4.5b: the shell hosts the REAL screens — NoteListScreen, // IncidoDrawer, NoteEditorScreen and the M4.5a settings — over // the AppGraph DesktopContainer already implements (M4.3 proof). DesktopShell( app = app, showSettings = showSettings, onShowSettings = { showSettings = it }, editorSmoke = editorSmoke, keysSmoke = keysSmoke, ) } 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}") } 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 (settingsSmoke) { LaunchedEffect(Unit) { delay(1500) // Compose the real screen (crash = failure); it stays up as the // window's content until --exit-after closes the app. showSettings = true println("SETTINGS shown (shared Appearance/Backup/About + desktop rows)") } } if (backupImport != null || backupExportEnc != null) { LaunchedEffect(Unit) { delay(800) // mirror the self-test pacing; wait past first frame // The codec zeroes the CharArray it consumes (encrypt AND // decrypt both call passphrase.fill), so every call needs a // FRESH array — exactly what the dialogs do by re-deriving // stage.passphrase?.toCharArray() per call. fun newPw(): CharArray? = backupPassphrase?.toCharArray() if (backupImport != null) { val file = File(backupImport) val bytes = file.readBytes() val encrypted = EncryptedBackupCodec.isEncrypted(bytes) // preview() takes the passphrase exactly like the // RequirePassphrase dialog does, and returns null when the // passphrase is wrong — the dialog's own reject gate. val preview = BackupBridge.preview(ByteArrayInputStream(bytes), newPw()) println( "BACKUP preview notes=${preview?.noteCount} " + "attachments=${preview?.attachmentCount} app=${preview?.appVersion} " + "encrypted=$encrypted", ) if (preview != null) { val first = BackupBridge.import(repository, ByteArrayInputStream(bytes), newPw()) println( "BACKUP imported=${first.imported} skipped=${first.skipped} " + "(same calls as the Import… menu)", ) if (encrypted && backupPassphrase != null) { val wrong = BackupBridge.preview( ByteArrayInputStream(bytes), "definitely-the-wrong-pass".toCharArray(), ) println("BACKUP wrong-pw preview=${if (wrong == null) "null (rejected)" else "LEAKED"}") } // M2 task 3: importing the same file again must add nothing — // the dedupe path the confirm dialog's checkbox controls. val again = BackupBridge.import(repository, ByteArrayInputStream(bytes), newPw()) println("BACKUP reimport imported=${again.imported} skipped=${again.skipped} (dedupe ON)") } } if (backupExport != null) { val out = File(backupExport) val exported = BackupBridge.exportPlain(repository, FileOutputStream(out), DESKTOP_APP_VERSION) println("BACKUP exported=$exported notes to $out") } if (backupExportEnc != null) { val pass = newPw() ?: error("--backup-export-enc needs --backup-passphrase") val out = File(backupExportEnc) val n = BackupBridge.exportEncrypted(repository, FileOutputStream(out), pass, DESKTOP_APP_VERSION) val magicOk = out.inputStream().use { ins -> ins.readNBytes(EncryptedBackupCodec.MAGIC.size).contentEquals(EncryptedBackupCodec.MAGIC) } println( "BACKUP exported-enc=$n notes to $out " + "(magic=${if (magicOk) "ICDBKP1 ok" else "BAD"})", ) } } } // M3: debounced window-size persistence — desktop-only state in its own // store file (incido_window.preferences_pb). Position is not saved; the // window manager owns placement here (KDE), only geometry is ours. LaunchedEffect(windowState.size) { val width = windowState.size.width.value.toInt() val height = windowState.size.height.value.toInt() delay(750) windowStore.edit { prefs -> prefs[intPreferencesKey("window_width")] = width prefs[intPreferencesKey("window_height")] = height } } if (keyExport != null || keyImport != null) { LaunchedEffect(Unit) { delay(800) withContext(Dispatchers.IO) { if (keyExport != null) { // Same codec call the SecurityActions export menu makes — // the exact envelope the phone's ObjectBoxKeyProvider writes. val out = File(keyExport) out.writeBytes(app.keyProvider.exportRecoveryKey(cryptoPassphrase.toCharArray())) val magic = out.readBytes() .copyOf(EncryptedKeyCodec.MAGIC.size) .contentEquals(EncryptedKeyCodec.MAGIC) println( "KEYENV exported=${out.length()}B to $out " + "(magic=${if (magic) "INCKEY1 ok" else "BAD"})", ) } if (keyImport != null) { val bytes = File(keyImport).readBytes() val rejectedWrongPw = runCatching { app.keyProvider.importRecoveryKey(bytes, "wrong-pass".toCharArray()) }.isFailure val result = runCatching { app.keyProvider.importRecoveryKey(bytes, cryptoPassphrase.toCharArray()) if (app.settingsRepository.snapshot().isEncryptionActive) { app.cipherHolder.cipher = AesGcmFieldCipher(app.keyProvider) } app.noteCryptoService.verifyAll() } result.fold( onSuccess = { v -> println( "KEYENV import ok wrong-pw=" + (if (rejectedWrongPw) "rejected" else "LEAKED!") + " verify verified=${v.verifiedNoteIds.size} failed=${v.failedNoteIds.size}", ) }, onFailure = { println("KEYENV import FAILED: ${it.javaClass.simpleName}: ${it.message}") }, ) } } } } if (cryptoSelfTest || cryptoReopen) { LaunchedEffect(Unit) { delay(800) // past the first frame; assertions ride the flows, not frame one val ok = if (cryptoSelfTest) { runCryptoSelfTest(app, cryptoPassphrase) } else { runCryptoReopenCheck(app) } println( "CRYPTO ${if (cryptoSelfTest) "leg-A" else "leg-B"} " + if (ok) "ALL-OK" else "PROBLEMS (see FAIL lines above)", ) } } if (exitAfterSeconds != null) { LaunchedEffect(Unit) { delay(exitAfterSeconds * 1000) onExit() } } } private fun Array.argAfter(flag: String): String? { val index = indexOf(flag) return takeIf { index >= 0 && index + 1 < size }?.get(index + 1) }