@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.services.files import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import platform.darwin.NSObject import platform.Foundation.NSURL import platform.UIKit.UIApplication import platform.UIKit.UIDocumentPickerDelegateProtocol import platform.UIKit.UIDocumentPickerMode import platform.UIKit.UIDocumentPickerViewController import platform.UIKit.UIViewController import platform.UIKit.UISceneActivationStateForegroundActive import platform.UIKit.UIWindow import platform.UIKit.UIWindowScene actual suspend fun pickFolder(initial: String?): String? = documentPickerLock.withLock { val presenter = topViewController() ?: return@withLock null val pending = CompletableDeferred() val delegate = IosDocumentPickerDelegate(pending, emptySet(), persistReadAccess = true) val picker = UIDocumentPickerViewController( documentTypes = listOf("public.folder"), inMode = UIDocumentPickerMode.UIDocumentPickerModeOpen, ) activeDocumentPickerDelegate = delegate picker.delegate = delegate picker.allowsMultipleSelection = false presenter.presentViewController(picker, animated = true, completion = null) try { pending.await() } finally { if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null } } actual suspend fun pickFile(extensions: List, initial: String?): String? = documentPickerLock.withLock { val presenter = topViewController() ?: return@withLock null val pending = CompletableDeferred() val allowedExtensions = extensions.map(String::lowercase).toSet() val delegate = IosDocumentPickerDelegate(pending, allowedExtensions) val picker = UIDocumentPickerViewController( documentTypes = documentTypesFor(allowedExtensions), inMode = UIDocumentPickerMode.UIDocumentPickerModeImport, ) activeDocumentPickerDelegate = delegate picker.delegate = delegate picker.allowsMultipleSelection = false presenter.presentViewController(picker, animated = true, completion = null) try { pending.await() } finally { if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null } } /** Reads the selected original through a scoped URL instead of first duplicating it into Inbox. */ internal suspend fun pickScopedMediaFile(): String? = documentPickerLock.withLock { val presenter = topViewController() ?: return@withLock null val pending = CompletableDeferred() val extensions = readableLocalFileExtensions val delegate = IosDocumentPickerDelegate(pending, extensions, persistReadAccess = true) val picker = UIDocumentPickerViewController( documentTypes = documentTypesFor(extensions), inMode = UIDocumentPickerMode.UIDocumentPickerModeOpen, ) activeDocumentPickerDelegate = delegate picker.delegate = delegate picker.allowsMultipleSelection = false presenter.presentViewController(picker, animated = true, completion = null) try { pending.await() } finally { if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null } } actual suspend fun exportFile( bytes: ByteArray, suggestedName: String, mimeType: String, initial: String?, ): String? = runCatching { val files = createPlatformLocalFileService() val path = "${files.backupRoot.trimEnd('/')}/$suggestedName" files.writeBytes(path, bytes) path }.getOrNull() private val documentPickerLock = Mutex() private var activeDocumentPickerDelegate: IosDocumentPickerDelegate? = null private class IosDocumentPickerDelegate( private val pending: CompletableDeferred, private val allowedExtensions: Set, private val persistReadAccess: Boolean = false, ) : NSObject(), UIDocumentPickerDelegateProtocol { override fun documentPicker( controller: UIDocumentPickerViewController, didPickDocumentsAtURLs: List<*>, ) { val url = didPickDocumentsAtURLs.firstOrNull() as? NSURL val path = if (persistReadAccess) { url?.let { selected -> runCatching { IosSecurityScopedBookmarks.persist(selected) }.getOrNull() } } else { url?.path } val accepted = path?.takeIf { selected -> allowedExtensions.isEmpty() || selected.substringAfterLast('.', "").lowercase() in allowedExtensions } pending.complete(accepted) controller.dismissViewControllerAnimated(true, completion = null) } override fun documentPickerWasCancelled(controller: UIDocumentPickerViewController) { pending.complete(null) controller.dismissViewControllerAnimated(true, completion = null) } } private val wellKnownUtis = mapOf( "jar" to "com.sun.java-archive", "json" to "public.json", "epub" to "org.idpf.epub-container", "zip" to "public.zip-archive", "cbz" to "public.zip-archive", ) /** * Union of UTIs for every requested extension — a first-match-wins mapping * made e.g. `.backup` unselectable whenever `json` was also in the list. * Unknown extensions get a dynamic UTI (`dyn.*`) so the picker still filters * by extension; only if that fails do we fall back to `public.data`. */ internal fun documentTypesFor(extensions: Set): List { if (extensions.isEmpty()) return listOf("public.data") val types = mutableListOf() var unknown = false extensions.forEach { ext -> val uti = wellKnownUtis[ext] ?: platform.UniformTypeIdentifiers.UTType.typeWithFilenameExtension(ext)?.identifier if (uti != null) types += uti else unknown = true } if (unknown || types.isEmpty()) types += "public.data" return types.distinct() } private fun topViewController(): UIViewController? { val activeWindows = UIApplication.sharedApplication.connectedScenes .filterIsInstance() .filter { scene -> scene.activationState == UISceneActivationStateForegroundActive } .flatMap { scene -> scene.windows } .filterIsInstance() val window = activeWindows.firstOrNull { candidate -> candidate.isKeyWindow() } ?: activeWindows.firstOrNull() ?: return null var current = window.rootViewController while (current?.presentedViewController != null) current = current.presentedViewController return current }