@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.services.files import kotlinx.cinterop.BooleanVarOf import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.alloc import kotlinx.cinterop.ObjCObjectVar import kotlinx.cinterop.memScoped import kotlinx.cinterop.ptr import kotlinx.cinterop.value import platform.Foundation.NSData import platform.Foundation.NSURL import platform.Foundation.NSURLBookmarkCreationMinimalBookmark import platform.Foundation.NSURLBookmarkResolutionWithoutImplicitStartAccessing import platform.Foundation.NSFileCoordinator import platform.Foundation.NSFileCoordinatorReadingWithoutChanges import platform.Foundation.NSError import platform.Foundation.NSUserDefaults import eu.friedcutlet.yokan.services.blockingDispatcher import kotlin.coroutines.ContinuationInterceptor import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext /** * Keeps security-scoped bookmark data outside the common settings model. The * configured path remains the opaque path returned by the picker; this class * resolves it only at the point where a filesystem operation is performed. */ @OptIn(ExperimentalForeignApi::class) internal object IosSecurityScopedBookmarks { private const val rootsKey = "eu.friedcutlet.yokan.securityScopedBookmarkRoots" private const val bookmarkKeyPrefix = "eu.friedcutlet.yokan.securityScopedBookmark." private val defaults: NSUserDefaults get() = NSUserDefaults.standardUserDefaults fun persist(url: NSURL): String? { val path = url.path?.takeIf(String::isNotBlank) ?: return null val started = url.startAccessingSecurityScopedResource() return try { val bookmark = url.bookmarkDataWithOptions( options = NSURLBookmarkCreationMinimalBookmark, includingResourceValuesForKeys = null, relativeToURL = null, error = null, ) ?: return null defaults.setObject(bookmark, forKey = bookmarkKey(path)) val roots = storedRoots() if (path !in roots) defaults.setObject(roots + path, forKey = rootsKey) path } finally { if (started) url.stopAccessingSecurityScopedResource() } } /** * Resolves the bookmark for [path], refreshes stale data, and holds the * security scope for exactly the duration of [block]. A path without a * bookmark is treated as an app-local path and is used directly. */ fun withAccess(path: String, block: (String) -> T): T? { val logicalPath = if (path.startsWith("file:")) { NSURL.URLWithString(path)?.path ?: return null } else path val root = matchingRoot(logicalPath) if (root == null) return runCatching { block(logicalPath) }.getOrNull() val bookmark = defaults.objectForKey(bookmarkKey(root)) as? NSData ?: return null return memScoped { val stale = alloc>() val resolved = NSURL.URLByResolvingBookmarkData( bookmarkData = bookmark, options = NSURLBookmarkResolutionWithoutImplicitStartAccessing, relativeToURL = null, bookmarkDataIsStale = stale.ptr, error = null, ) ?: return@memScoped null val physicalRoot = resolved.path?.takeIf(String::isNotBlank) ?: return@memScoped null val started = resolved.startAccessingSecurityScopedResource() try { if (stale.value) refresh(root, resolved) val relative = logicalPath.removePrefix(root).trimStart('/') if (relative.split('/').any { it == ".." }) return@memScoped null val physicalPath = if (relative.isEmpty()) physicalRoot else "$physicalRoot/$relative" runCatching { block(physicalPath) }.getOrNull() } finally { if (started) resolved.stopAccessingSecurityScopedResource() } } } /** Holds a balanced security scope across suspended, bounded file reads. Errors propagate. */ suspend fun withAccessAsync(path: String, block: suspend (String) -> T): T { val logicalPath = if (path.startsWith("file:")) { requireNotNull(NSURL.URLWithString(path)?.path) } else path val root = matchingRoot(logicalPath) ?: return block(logicalPath) val bookmark = defaults.objectForKey(bookmarkKey(root)) as? NSData ?: error("Folder permission is unavailable") var staleBookmark = false val resolved = memScoped { val stale = alloc>() val url = NSURL.URLByResolvingBookmarkData(bookmark, NSURLBookmarkResolutionWithoutImplicitStartAccessing, null, stale.ptr, null) ?: error("Folder permission could not be resolved") staleBookmark = stale.value url } val physicalRoot = requireNotNull(resolved.path) val started = resolved.startAccessingSecurityScopedResource() try { if (staleBookmark) refresh(root, resolved) val relative = logicalPath.removePrefix(root).trimStart('/') require(relative.split('/').none { it == ".." }) return block(if (relative.isEmpty()) physicalRoot else "$physicalRoot/$relative") } finally { if (started) resolved.stopAccessingSecurityScopedResource() } } /** Keeps provider materialization and all reads inside its synchronous coordination accessor. */ @OptIn(kotlinx.cinterop.BetaInteropApi::class) suspend fun withCoordinatedRead(path: String, block: suspend (String) -> T): T = withContext(blockingDispatcher) { withAccessAsync(path) { physical -> coroutineScope { val coordinator = NSFileCoordinator(filePresenter = null) suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { coordinator.cancel() } launch(blockingDispatcher) { val outcome = runCatching { val readerContext = currentCoroutineContext().minusKey(ContinuationInterceptor) memScoped { val failure = alloc>() failure.value = null var result: Result? = null coordinator.coordinateReadingItemAtURL( NSURL.fileURLWithPath(physical), options = NSFileCoordinatorReadingWithoutChanges, error = failure.ptr, ) { coordinated -> // This bridge stays on the background thread and inherits cancellation. // The native destination writer is synchronous; no UI thread is blocked. result = runCatching { runBlocking(readerContext) { block(requireNotNull(requireNotNull(coordinated).path)) } } } val completed = result ?: error(failure.value?.localizedDescription ?: "Document provider could not open the file") completed.getOrThrow() } } if (continuation.isActive) continuation.resumeWith(outcome) } } } } } private fun refresh(root: String, url: NSURL) { runCatching { url.bookmarkDataWithOptions( options = NSURLBookmarkCreationMinimalBookmark, includingResourceValuesForKeys = null, relativeToURL = null, error = null, )?.let { defaults.setObject(it, forKey = bookmarkKey(root)) } } } private fun matchingRoot(path: String): String? = storedRoots() .filter { root -> val normalizedRoot = root.trimEnd('/').ifEmpty { "/" } path == normalizedRoot || (normalizedRoot == "/" && path.startsWith('/')) || path.startsWith("$normalizedRoot/") } .maxByOrNull(String::length) private fun storedRoots(): List = defaults.arrayForKey(rootsKey)?.filterIsInstance().orEmpty() private fun bookmarkKey(root: String): String = bookmarkKeyPrefix + root }