package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.services.scheduling.DesktopSession import javax.swing.JFileChooser import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.swing.Swing import kotlinx.coroutines.withContext // Swing components must be created and shown on the EDT; the modal dialog keeps pumping events. actual suspend fun pickFolder(initial: String?): String? = withContext(Dispatchers.Swing) { runCatching { val chooser = JFileChooser().apply { fileSelectionMode = JFileChooser.DIRECTORIES_ONLY isMultiSelectionEnabled = false initial?.takeIf { it.isNotBlank() }?.let { path -> currentDirectory = java.io.File(path.removePrefix("file://")) } } val result = chooser.showOpenDialog(DesktopSession.frame) if (result == JFileChooser.APPROVE_OPTION) chooser.selectedFile.absolutePath else null }.getOrNull() } actual suspend fun pickFile(extensions: List, initial: String?): String? = withContext(Dispatchers.Swing) { runCatching { val chooser = JFileChooser().apply { fileSelectionMode = JFileChooser.FILES_ONLY isMultiSelectionEnabled = false initial?.takeIf { it.isNotBlank() }?.let { path -> currentDirectory = java.io.File(path.removePrefix("file://")) } if (extensions.isNotEmpty()) { fileFilter = object : javax.swing.filechooser.FileFilter() { override fun accept(file: java.io.File): Boolean = file.isDirectory || extensions.any { ext -> file.name.endsWith(".$ext", ignoreCase = true) } override fun getDescription(): String = extensions.joinToString(", ") { "*.$it" } } } } val result = chooser.showOpenDialog(DesktopSession.frame) if (result == JFileChooser.APPROVE_OPTION) chooser.selectedFile.absolutePath else null }.getOrNull() } actual suspend fun exportFile( bytes: ByteArray, suggestedName: String, mimeType: String, initial: String?, ): String? { val target = withContext(Dispatchers.Swing) { runCatching { val chooser = JFileChooser().apply { fileSelectionMode = JFileChooser.FILES_ONLY isMultiSelectionEnabled = false dialogTitle = "Export backup" val initialDirectory = initial ?.takeIf { it.isNotBlank() } ?.let { java.io.File(it.removePrefix("file://")) } ?.takeIf { it.isDirectory } if (initialDirectory != null) currentDirectory = initialDirectory selectedFile = java.io.File(initialDirectory ?: currentDirectory, suggestedName) } if (chooser.showSaveDialog(DesktopSession.frame) == JFileChooser.APPROVE_OPTION) chooser.selectedFile else null }.getOrNull() } ?: return null // Keep the (possibly large) backup write off the EDT. return withContext(Dispatchers.IO) { runCatching { target.parentFile?.mkdirs() target.writeBytes(bytes) target.absolutePath }.getOrNull() } }