Cotton code
89 lines · 3.9 KB · SwiftRaw
import Foundationimport UniformTypeIdentifiers#if os(iOS)import UIKit#elseif os(macOS)import AppKit#endif/// A file an act's pick asks for (`step.file`, SUBTITLE FILE in assets/design/cinemas/CONTRACT.md): the platform's/// picker for the extensions the core accepts, the file copied to a folder of the app's own under its **own name**/// (the core reads a subtitle's language from it), and that copy removed once the commit has answered. What else is/// picked is never filtered here: the core refuses it in its own words.@MainActorenum PickedFile {    /// The folder each picked copy stands in: `<caches>/picked/<uuid>/<name>`.    static var root: URL {        FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appending(path: "picked", directoryHint: .isDirectory)    }    /// The types the picker offers for the core's extensions. `srt` and `vtt` have no system type on every iOS, so    /// any extension without one falls back to plain text and any data.    static func types(_ accept: [String]) -> [UTType] {        let known = accept.compactMap { UTType(filenameExtension: $0) }.filter { !$0.isDynamic }        return known.count == accept.count && !known.isEmpty ? known : known + [.plainText, .data]    }    /// The person's file, copied under its own name; nil when they cancelled.    static func choose(_ accept: [String]) async throws -> URL? {        guard let picked = try await present(types(accept)) else { return nil }        return try copy(picked)    }    /// `picked` copied to `<caches>/picked/<uuid>/<its own name>`.    static func copy(_ picked: URL) throws -> URL {        let scoped = picked.startAccessingSecurityScopedResource()        defer { if scoped { picked.stopAccessingSecurityScopedResource() } }        let folder = root.appending(path: UUID().uuidString, directoryHint: .isDirectory)        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)        let copy = folder.appending(path: picked.lastPathComponent, directoryHint: .notDirectory)        try FileManager.default.copyItem(at: picked, to: copy)        return copy    }    /// The copy and its folder, gone once the commit has answered (the core keeps its own).    static func remove(_ copy: URL) {        try? FileManager.default.removeItem(at: copy.deletingLastPathComponent())    }    private static func present(_ types: [UTType]) async throws -> URL? {        #if os(iOS)        guard let top = SystemShareSheet.topViewController() else {            throw ActionRefused(ShellLines.line("documents", "picker.the_file_picker_could"))        }        let delegate = PickedFileDelegate()        let picker = UIDocumentPickerViewController(forOpeningContentTypes: types, asCopy: true)        picker.allowsMultipleSelection = false        picker.delegate = delegate        let url = await withCheckedContinuation { continuation in            delegate.continuation = continuation            top.present(picker, animated: true)        }        withExtendedLifetime(delegate) {}        return url        #elseif os(macOS)        let panel = NSOpenPanel()        panel.allowedContentTypes = types        panel.allowsMultipleSelection = false        panel.canChooseDirectories = false        return await panel.begin() == .OK ? panel.url : nil        #else        throw ActionRefused(ShellLines.line("documents", "picker.this_device_cannot_open"))        #endif    }}#if os(iOS)@MainActorprivate final class PickedFileDelegate: NSObject, UIDocumentPickerDelegate {    var continuation: CheckedContinuation<URL?, Never>?    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {        continuation?.resume(returning: urls.first)        continuation = nil    }    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {        continuation?.resume(returning: nil)        continuation = nil    }}#endif