Pickers.ios.kt
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.ios.kt
1@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)23package eu.friedcutlet.yokan.services.files45import kotlinx.coroutines.CompletableDeferred6import kotlinx.coroutines.sync.Mutex7import kotlinx.coroutines.sync.withLock8import platform.darwin.NSObject9import platform.Foundation.NSURL10import platform.UIKit.UIApplication11import platform.UIKit.UIDocumentPickerDelegateProtocol12import platform.UIKit.UIDocumentPickerMode13import platform.UIKit.UIDocumentPickerViewController14import platform.UIKit.UIViewController15import platform.UIKit.UISceneActivationStateForegroundActive16import platform.UIKit.UIWindow17import platform.UIKit.UIWindowScene1819actual suspend fun pickFolder(initial: String?): String? =20 documentPickerLock.withLock {21 val presenter = topViewController() ?: return@withLock null22 val pending = CompletableDeferred<String?>()23 val delegate = IosDocumentPickerDelegate(pending, emptySet(), persistReadAccess = true)24 val picker = UIDocumentPickerViewController(25 documentTypes = listOf("public.folder"),26 inMode = UIDocumentPickerMode.UIDocumentPickerModeOpen,27 )28 activeDocumentPickerDelegate = delegate29 picker.delegate = delegate30 picker.allowsMultipleSelection = false31 presenter.presentViewController(picker, animated = true, completion = null)32 try {33 pending.await()34 } finally {35 if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null36 }37 }3839actual suspend fun pickFile(extensions: List<String>, initial: String?): String? =40 documentPickerLock.withLock {41 val presenter = topViewController() ?: return@withLock null42 val pending = CompletableDeferred<String?>()43 val allowedExtensions = extensions.map(String::lowercase).toSet()44 val delegate = IosDocumentPickerDelegate(pending, allowedExtensions)45 val picker = UIDocumentPickerViewController(46 documentTypes = documentTypesFor(allowedExtensions),47 inMode = UIDocumentPickerMode.UIDocumentPickerModeImport,48 )49 activeDocumentPickerDelegate = delegate50 picker.delegate = delegate51 picker.allowsMultipleSelection = false52 presenter.presentViewController(picker, animated = true, completion = null)53 try {54 pending.await()55 } finally {56 if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null57 }58 }5960/** Reads the selected original through a scoped URL instead of first duplicating it into Inbox. */61internal suspend fun pickScopedMediaFile(): String? = documentPickerLock.withLock {62 val presenter = topViewController() ?: return@withLock null63 val pending = CompletableDeferred<String?>()64 val extensions = readableLocalFileExtensions65 val delegate = IosDocumentPickerDelegate(pending, extensions, persistReadAccess = true)66 val picker = UIDocumentPickerViewController(67 documentTypes = documentTypesFor(extensions),68 inMode = UIDocumentPickerMode.UIDocumentPickerModeOpen,69 )70 activeDocumentPickerDelegate = delegate71 picker.delegate = delegate72 picker.allowsMultipleSelection = false73 presenter.presentViewController(picker, animated = true, completion = null)74 try { pending.await() }75 finally { if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null }76}7778actual suspend fun exportFile(79 bytes: ByteArray,80 suggestedName: String,81 mimeType: String,82 initial: String?,83): String? = runCatching {84 val files = createPlatformLocalFileService()85 val path = "${files.backupRoot.trimEnd('/')}/$suggestedName"86 files.writeBytes(path, bytes)87 path88}.getOrNull()8990private val documentPickerLock = Mutex()9192private var activeDocumentPickerDelegate: IosDocumentPickerDelegate? = null9394private class IosDocumentPickerDelegate(95 private val pending: CompletableDeferred<String?>,96 private val allowedExtensions: Set<String>,97 private val persistReadAccess: Boolean = false,98) : NSObject(), UIDocumentPickerDelegateProtocol {99 override fun documentPicker(100 controller: UIDocumentPickerViewController,101 didPickDocumentsAtURLs: List<*>,102 ) {103 val url = didPickDocumentsAtURLs.firstOrNull() as? NSURL104 val path = if (persistReadAccess) {105 url?.let { selected -> runCatching { IosSecurityScopedBookmarks.persist(selected) }.getOrNull() }106 } else {107 url?.path108 }109 val accepted = path?.takeIf { selected ->110 allowedExtensions.isEmpty() || selected.substringAfterLast('.', "").lowercase() in allowedExtensions111 }112 pending.complete(accepted)113 controller.dismissViewControllerAnimated(true, completion = null)114 }115116 override fun documentPickerWasCancelled(controller: UIDocumentPickerViewController) {117 pending.complete(null)118 controller.dismissViewControllerAnimated(true, completion = null)119 }120}121122private val wellKnownUtis = mapOf(123 "jar" to "com.sun.java-archive",124 "json" to "public.json",125 "epub" to "org.idpf.epub-container",126 "zip" to "public.zip-archive",127 "cbz" to "public.zip-archive",128)129130/**131 * Union of UTIs for every requested extension — a first-match-wins mapping132 * made e.g. `.backup` unselectable whenever `json` was also in the list.133 * Unknown extensions get a dynamic UTI (`dyn.*`) so the picker still filters134 * by extension; only if that fails do we fall back to `public.data`.135 */136internal fun documentTypesFor(extensions: Set<String>): List<String> {137 if (extensions.isEmpty()) return listOf("public.data")138 val types = mutableListOf<String>()139 var unknown = false140 extensions.forEach { ext ->141 val uti = wellKnownUtis[ext]142 ?: platform.UniformTypeIdentifiers.UTType.typeWithFilenameExtension(ext)?.identifier143 if (uti != null) types += uti else unknown = true144 }145 if (unknown || types.isEmpty()) types += "public.data"146 return types.distinct()147}148149private fun topViewController(): UIViewController? {150 val activeWindows = UIApplication.sharedApplication.connectedScenes151 .filterIsInstance<UIWindowScene>()152 .filter { scene -> scene.activationState == UISceneActivationStateForegroundActive }153 .flatMap { scene -> scene.windows }154 .filterIsInstance<UIWindow>()155 val window = activeWindows.firstOrNull { candidate -> candidate.isKeyWindow() }156 ?: activeWindows.firstOrNull()157 ?: return null158 var current = window.rootViewController159 while (current?.presentedViewController != null) current = current.presentedViewController160 return current161}162