Files
Incido/desktopApp/src/main/kotlin/org/incido/desktop/BackupActions.kt
T
Incido Developer d264238640 feat(phase-1/m4.5a): desktop settings screen on the shared sections
DesktopSettingsScreen composes the M4.4d common sections (Appearance
/ Backup / About + building blocks) plus desktop-only Encryption rows.
Android-incapable surfaces are hidden per 6.5: dynamic-color row
(onDynamicColor null), Carnet importer (onImportCarnet null),
SecuritySection entirely (no BiometricPrompt/FLAG_SECURE on the JVM).

Flow dedupe so settings drives the EXACT M2/M3 behaviour, not a copy:
- BackupActions split: BackupFlows/rememberBackupFlows owns the pick+
  bridge + dialog machinery; the menu is now a thin skin (launchImport/
  launchExportPlain/launchExportEncrypted + Dialogs()).
- SecurityActions split: SecurityKeyFlows owns the recovery-key export/
  import dialogs (hasKey gate, overwrite warning, import leg);
  toggleDesktopEncryption() keeps the enable/disable ordering.
- M4.4d sections became PUBLIC (desktopApp is a separate module).

Main.kt: gear button routes list-window <-> settings in-place (no nav
stack yet — desktop nav polish is M5). New scripted leg
--settings-smoke renders the screen headlessly before auto-exit.

Verified: assembleDebug :desktopApp:build SUCCESSFUL + :desktopApp:
run --self-test --settings-smoke (SELFTEST id=1, RENDER notes=1
selected=1, SETTINGS shown, ST_EXIT=0) + :core:data-jvm:smoke
(M1a PASS); models clean.
2026-10-06 19:27:02 +13:00

369 lines
15 KiB
Kotlin

package org.incido.desktop
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
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.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import java.awt.FileDialog
import java.awt.Frame
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.FilenameFilter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.data.backup.BackupBridge
import org.incido.compose.data.backup.BackupPreview
import org.incido.compose.data.backup.EncryptedBackupCodec
import org.incido.domain.repository.NoteRepository
/** Exported as the payload's appVersion — mirrors the Android BuildConfig. */
const val DESKTOP_APP_VERSION = "0.4.2.0"
/**
* Phase 1 (M2 task 2): the desktop backup menu + dialogs.
*
* The phone's only bridge to this library is the backup file (ObjectBox is
* single-writer), so this is the app's most product-important desktop UI.
* Every flow here ends in the SAME [BackupBridge] calls Android's
* BackupManager makes — the file format is shared by construction, not by
* reimplementation.
*
* File picking uses java.awt.FileDialog (the same AWT path the spike proved
* under KDE/Wayland-XWayland): a blocking native GTK dialog, driven off the
* IO dispatcher so the composition never freezes. The passphrase and
* confirm dialogs are plain Material3 AlertDialogs — Android's
* PassphraseDialog.kt is deliberately NOT ported (M4 will move the real
* one into common code).
*/
/**
* M4.5: the import/export machinery, extracted from the menu so the real
* settings screen (BackupSection buttons) drives the EXACT flows M2 proved —
* same pickFile, same BackupBridge calls, same passphrase/confirm dialogs.
* BackupActions is now just the menu skin over it; the state + dialogs
* belong to whoever remembers the flows (one host at a time renders them).
*/
class BackupFlows internal constructor(
val launchImport: () -> Unit,
val launchExportPlain: () -> Unit,
val launchExportEncrypted: () -> Unit,
val Dialogs: @Composable () -> Unit,
)
@Composable
fun rememberBackupFlows(
repository: NoteRepository,
snackbar: SnackbarHostState,
): BackupFlows {
val scope = rememberCoroutineScope()
var importStage by remember { mutableStateOf<ImportStage?>(null) }
var exportStage by remember { mutableStateOf<ExportStage?>(null) }
// M2 task 3: dedupe is ON by default; the confirm dialog exposes it.
var skipDuplicates by remember { mutableStateOf(true) }
fun say(message: String) { scope.launch { snackbar.showSnackbar(message) } }
return remember(repository) {
BackupFlows(
launchImport = {
scope.launch {
val file = pickFile(load = true, title = "Import backup") ?: return@launch
startImport(file, ::say) { stage -> importStage = stage }
}
},
launchExportPlain = {
scope.launch {
val file = pickFile(load = false, title = "Export backup", suggested = suggestedExportName()) ?: return@launch
runCatching {
withContext(Dispatchers.IO) {
BackupBridge.exportPlain(repository, FileOutputStream(file), DESKTOP_APP_VERSION)
}
}.onSuccess { say("Exported $it notes to ${file.name}") }
.onFailure { say("Export failed: ${it.message}") }
}
},
launchExportEncrypted = {
exportStage = ExportStage.AwaitingPassphrase
},
Dialogs = {
// ---- import dialogs (verbatim M2 behaviour) --------------
when (val stage = importStage) {
is ImportStage.NeedPassphrase -> PassphraseDialog(
blurb = "This backup is encrypted (INCDBK1). Enter its passphrase to preview it.",
onDismiss = { importStage = null },
onConfirm = { pass ->
scope.launch {
val preview = withContext(Dispatchers.IO) {
runCatching {
BackupBridge.preview(FileInputStream(stage.file), pass.toCharArray())
}.getOrNull()
}
if (preview == null) {
say("Wrong passphrase") // dialog stays open for a retry
} else {
importStage = ImportStage.Confirm(stage.file, preview, pass)
}
}
},
)
is ImportStage.Confirm -> ConfirmImportDialog(
preview = stage.preview,
skipExisting = skipDuplicates,
onSkipChange = { skipDuplicates = it },
onDismiss = { importStage = null },
onConfirm = {
importStage = null
scope.launch {
runCatching {
withContext(Dispatchers.IO) {
BackupBridge.import(
repository,
FileInputStream(stage.file),
stage.passphrase?.toCharArray(),
skipExisting = skipDuplicates,
)
}
}.onSuccess {
say(
"Imported ${it.imported} notes" +
if (it.skipped > 0) " · skipped ${it.skipped} already imported" else "",
)
}
.onFailure { say("Import failed: ${it.message}") }
}
},
)
null -> Unit
}
// ---- export dialogs (verbatim M2 behaviour) --------------
when (exportStage) {
ExportStage.AwaitingPassphrase -> PassphraseDialog(
blurb = "Choose the passphrase for the encrypted backup (same INCDBK1 envelope as the phone).",
onDismiss = { exportStage = null },
onConfirm = { pass ->
exportStage = null
scope.launch {
val file = pickFile(load = false, title = "Export backup", suggested = suggestedExportName()) ?: return@launch
runCatching {
withContext(Dispatchers.IO) {
BackupBridge.exportEncrypted(
repository,
FileOutputStream(file),
pass.toCharArray(),
DESKTOP_APP_VERSION,
)
}
}.onSuccess { say("Exported $it encrypted notes to ${file.name}") }
.onFailure { say("Export failed: ${it.message}") }
}
},
)
null -> Unit
}
},
)
}
}
@Composable
fun BackupActions(
repository: NoteRepository,
snackbar: SnackbarHostState,
modifier: Modifier = Modifier,
) {
val flows = rememberBackupFlows(repository, snackbar)
var menuOpen by remember { mutableStateOf(false) }
IconButton(onClick = { menuOpen = true }, modifier = modifier) {
Icon(Icons.Default.MoreVert, contentDescription = "Backup menu")
}
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
DropdownMenuItem(
text = { Text("Import from file…") },
onClick = {
menuOpen = false
flows.launchImport()
},
)
DropdownMenuItem(
text = { Text("Export (plain)") },
onClick = {
menuOpen = false
flows.launchExportPlain()
},
)
DropdownMenuItem(
text = { Text("Export (encrypted)…") },
onClick = {
menuOpen = false
flows.launchExportEncrypted()
},
)
}
flows.Dialogs()
}
/** Where the import flow stands (the file is already chosen). */
private sealed interface ImportStage {
/** Preview without a passphrase failed → either encrypted or corrupt. */
data class NeedPassphrase(val file: File) : ImportStage
/** Metadata read OK — show counts, then import (passphrase for encrypted). */
data class Confirm(val file: File, val preview: BackupPreview, val passphrase: String?) : ImportStage
}
private sealed interface ExportStage {
data object AwaitingPassphrase : ExportStage
}
/**
* Pick a file and work out the first import stage, mirroring the phone's
* settings screen: plain JSON → straight to Confirm; magic header → ask
* for the passphrase; neither → report, don't dialog.
*/
private suspend fun startImport(
file: File,
say: (String) -> Unit,
setStage: (ImportStage?) -> Unit,
) {
val outcome: Pair<String?, ImportStage?> = withContext(Dispatchers.IO) {
val bytes = runCatching { file.readBytes() }.getOrNull()
if (bytes == null) {
"Could not read ${file.name}" to null
} else {
val preview = BackupBridge.preview(FileInputStream(file), null)
when {
preview != null -> null to ImportStage.Confirm(file, preview, null)
EncryptedBackupCodec.isEncrypted(bytes) -> null to ImportStage.NeedPassphrase(file)
else -> "Not an Incido backup file." to null
}
}
}
outcome.first?.let { say(it) }
outcome.second?.let(setStage)
}
@Composable
private fun ConfirmImportDialog(
preview: BackupPreview,
skipExisting: Boolean,
onSkipChange: (Boolean) -> Unit,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
val exported = java.text.DateFormat.getDateTimeInstance().format(java.util.Date(preview.exportedAt))
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Import backup?") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("${preview.noteCount} notes · ${preview.attachmentCount} attachments")
Text(
"Exported by Incido ${preview.appVersion} on $exported",
style = MaterialTheme.typography.bodySmall,
)
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(checked = skipExisting, onCheckedChange = onSkipChange)
Text(
"Skip notes that are already here",
style = MaterialTheme.typography.bodyMedium,
)
}
}
},
confirmButton = { TextButton(onClick = onConfirm) { Text("Import") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@Composable
internal fun PassphraseDialog(
blurb: String,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
) {
var value by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Passphrase") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(blurb, style = MaterialTheme.typography.bodyMedium)
OutlinedTextField(
value = value,
onValueChange = { value = it },
label = { Text("Passphrase") },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
)
}
},
confirmButton = {
TextButton(onClick = { if (value.isNotBlank()) onConfirm(value) }) { Text("Unlock") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** "incido-backup-YYYY-MM-DD.incido.json" — the phone's naming convention. */
private fun suggestedExportName(): String =
"incido-backup-${java.text.SimpleDateFormat("yyyy-MM-dd").format(java.util.Date())}.incido.json"
/**
* Blocking AWT/GTK file picker. Safe off the EDT (AWT marshals internally);
* callers run it on the IO dispatcher so the composition stays responsive.
*
* M3: shared with SecurityActions (recovery-key import/export) — the
* dialog title and the accepted extensions are now the caller's choice;
* the backup callers keep their previous behaviour exactly.
*/
internal suspend fun pickFile(
load: Boolean,
title: String,
suggested: String? = null,
extensions: List<String> = listOf("json", "incido", "incido.enc"),
): File? =
withContext(Dispatchers.IO) {
val dialog = FileDialog(
Frame.getFrames().firstOrNull(),
title,
if (load) FileDialog.LOAD else FileDialog.SAVE,
).apply {
directory = System.getProperty("user.home") + File.separator
suggested?.let { file = it }
filenameFilter = FilenameFilter { dir, name ->
dir.isDirectory || extensions.any { name.endsWith(".$it") }
}
isVisible = true
}
dialog.file?.let { File(dialog.directory, it) }
}