Pickers.desktop.kt
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.desktop.kt
1package eu.friedcutlet.yokan.services.files23import eu.friedcutlet.yokan.services.scheduling.DesktopSession4import javax.swing.JFileChooser5import kotlinx.coroutines.Dispatchers6import kotlinx.coroutines.swing.Swing7import kotlinx.coroutines.withContext89// Swing components must be created and shown on the EDT; the modal dialog keeps pumping events.10actual suspend fun pickFolder(initial: String?): String? = withContext(Dispatchers.Swing) {11 runCatching {12 val chooser = JFileChooser().apply {13 fileSelectionMode = JFileChooser.DIRECTORIES_ONLY14 isMultiSelectionEnabled = false15 initial?.takeIf { it.isNotBlank() }?.let { path ->16 currentDirectory = java.io.File(path.removePrefix("file://"))17 }18 }19 val result = chooser.showOpenDialog(DesktopSession.frame)20 if (result == JFileChooser.APPROVE_OPTION) chooser.selectedFile.absolutePath else null21 }.getOrNull()22}2324actual suspend fun pickFile(extensions: List<String>, initial: String?): String? = withContext(Dispatchers.Swing) {25 runCatching {26 val chooser = JFileChooser().apply {27 fileSelectionMode = JFileChooser.FILES_ONLY28 isMultiSelectionEnabled = false29 initial?.takeIf { it.isNotBlank() }?.let { path ->30 currentDirectory = java.io.File(path.removePrefix("file://"))31 }32 if (extensions.isNotEmpty()) {33 fileFilter = object : javax.swing.filechooser.FileFilter() {34 override fun accept(file: java.io.File): Boolean =35 file.isDirectory || extensions.any { ext -> file.name.endsWith(".$ext", ignoreCase = true) }36 override fun getDescription(): String = extensions.joinToString(", ") { "*.$it" }37 }38 }39 }40 val result = chooser.showOpenDialog(DesktopSession.frame)41 if (result == JFileChooser.APPROVE_OPTION) chooser.selectedFile.absolutePath else null42 }.getOrNull()43}4445actual suspend fun exportFile(46 bytes: ByteArray,47 suggestedName: String,48 mimeType: String,49 initial: String?,50): String? {51 val target = withContext(Dispatchers.Swing) {52 runCatching {53 val chooser = JFileChooser().apply {54 fileSelectionMode = JFileChooser.FILES_ONLY55 isMultiSelectionEnabled = false56 dialogTitle = "Export backup"57 val initialDirectory = initial58 ?.takeIf { it.isNotBlank() }59 ?.let { java.io.File(it.removePrefix("file://")) }60 ?.takeIf { it.isDirectory }61 if (initialDirectory != null) currentDirectory = initialDirectory62 selectedFile = java.io.File(initialDirectory ?: currentDirectory, suggestedName)63 }64 if (chooser.showSaveDialog(DesktopSession.frame) == JFileChooser.APPROVE_OPTION) chooser.selectedFile else null65 }.getOrNull()66 } ?: return null67 // Keep the (possibly large) backup write off the EDT.68 return withContext(Dispatchers.IO) {69 runCatching {70 target.parentFile?.mkdirs()71 target.writeBytes(bytes)72 target.absolutePath73 }.getOrNull()74 }75}76