1
+ package com.mohamedrejeb.calf.picker.platform.awt
2
+
3
+ import com.mohamedrejeb.calf.io.KmpFile
4
+ import kotlinx.coroutines.suspendCancellableCoroutine
5
+ import java.awt.Dialog
6
+ import java.awt.FileDialog
7
+ import java.awt.Frame
8
+ import java.awt.Window
9
+ import java.io.File
10
+ import kotlin.coroutines.resume
11
+
12
+ internal object AwtFileSaver {
13
+ suspend fun saveFile (
14
+ bytes : ByteArray? ,
15
+ baseName : String ,
16
+ extension : String ,
17
+ initialDirectory : String? ,
18
+ parentWindow : Window ? ,
19
+ ): KmpFile ? = suspendCancellableCoroutine { continuation ->
20
+ fun handleResult (value : Boolean , files : Array <File >? ) {
21
+ if (value) {
22
+ val file = files?.firstOrNull()?.let { file ->
23
+ // Write bytes to file, or create a new file
24
+ bytes?.let { file.writeBytes(bytes) } ? : file.createNewFile()
25
+ KmpFile (file)
26
+ }
27
+ continuation.resume(file)
28
+ }
29
+ }
30
+
31
+ // Handle parentWindow: Dialog, Frame, or null
32
+ val dialog = when (parentWindow) {
33
+ is Dialog -> object : FileDialog (parentWindow, " Save dialog" , SAVE ) {
34
+ override fun setVisible (value : Boolean ) {
35
+ super .setVisible(value)
36
+ handleResult(value, files)
37
+ }
38
+ }
39
+
40
+ else -> object : FileDialog (parentWindow as ? Frame , " Save dialog" , SAVE ) {
41
+ override fun setVisible (value : Boolean ) {
42
+ super .setVisible(value)
43
+ handleResult(value, files)
44
+ }
45
+ }
46
+ }
47
+
48
+ // Set initial directory
49
+ dialog.directory = initialDirectory
50
+
51
+ // Set file name
52
+ dialog.file = " $baseName .$extension "
53
+
54
+ // Show the dialog
55
+ dialog.isVisible = true
56
+
57
+ // Dispose the dialog when the continuation is cancelled
58
+ continuation.invokeOnCancellation { dialog.dispose() }
59
+ }
60
+ }
0 commit comments