Cotton code
133 lines · 5.5 KB · SwiftRaw
import CottonKitimport CottonValuesimport Foundationimport UniformTypeIdentifiers#if os(macOS)import AppKit#elseif os(iOS)import UIKit#endif/// A native file chooser's captured continuation, never a method dispatcher.public struct RecordFilePick: Decodable, Hashable, Sendable {    public let accept: [String]    struct Continuation: Decodable, Hashable, Sendable {        let method: String        let arguments: [String: RecordValue]    }    let then: Continuation    enum CodingKeys: String, CodingKey { case accept, then }    public init(from decoder: Decoder) throws {        let fields = try decoder.container(keyedBy: CodingKeys.self)        accept = try fields.decode([String].self, forKey: .accept)        then = try fields.decode(Continuation.self, forKey: .then)        guard !accept.isEmpty, accept.allSatisfy({ !$0.isEmpty && UTType($0) != nil }),              then.method == "records.create",              case .text(let table)? = then.arguments["table"], !table.isEmpty,              case .text(let database)? = then.arguments["database"], !database.isEmpty,              case .object(let data)? = then.arguments["data"],              data["file"] == .text("$path"), data["name"] == .text("$name") else {            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Invalid captured file continuation"))        }    }    var table: String { then.arguments["table"]?.text ?? "" }    func arguments(file: URL) -> [String: RecordValue] {        func bind(_ value: RecordValue) -> RecordValue {            switch value {            case .text("$path"): return .text(file.path(percentEncoded: false))            case .text("$name"): return .text(file.lastPathComponent)            case .list(let values): return .list(values.map(bind))            case .object(let values): return .object(values.mapValues(bind))            default: return value            }        }        // Scope is the original command's literal, never a selected file value.        var arguments = then.arguments.mapValues(bind)        arguments["database"] = then.arguments["database"]        return arguments    }}protocol RecordFileCommands: Sendable {    func continueFilePick(_ pick: RecordFilePick, file: URL) async throws -> ChangeRecord}@MainActorenum RecordFileEffects {    static func perform(_ pick: RecordFilePick, records: (any Records)?) async throws -> ChangeRecord? {        guard let records = records as? any RecordFileCommands else {            throw ActionRefused(ShellLines.line("documents", "picker.this_build_cannot_import"))        }        return try await perform(pick, choose: choose, access: access) { url in            try await records.continueFilePick(pick, file: url)        }    }    static func perform(_ pick: RecordFilePick,                        choose: ([String]) async throws -> URL?,                        access: (URL) throws -> (() -> Void),                        run: (URL) async throws -> ChangeRecord) async throws -> ChangeRecord? {        guard let url = try await choose(pick.accept) else { return nil }        guard url.isFileURL else { throw ActionRefused(ShellLines.line("documents", "picker.the_selection_is_not")) }        let release = try access(url)        defer { release() }        return try await run(url)    }    private static func access(_ url: URL) throws -> (() -> Void) {        let scoped = url.startAccessingSecurityScopedResource()        do {            guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else {                throw ActionRefused(ShellLines.line("documents", "picker.choose_a_file"))            }        } catch {            if scoped { url.stopAccessingSecurityScopedResource() }            throw error        }        return { if scoped { url.stopAccessingSecurityScopedResource() } }    }    private static func choose(_ accept: [String]) async throws -> URL? {        let types = accept.compactMap(UTType.init)        #if os(macOS)        let panel = NSOpenPanel()        panel.allowedContentTypes = types        panel.allowsMultipleSelection = false        panel.canChooseDirectories = false        return await panel.begin() == .OK ? panel.url : nil        #elseif os(iOS)        guard let top = SystemShareSheet.topViewController() else {            throw ActionRefused(ShellLines.line("documents", "picker.the_file_picker_could"))        }        let delegate = RecordFilePickerDelegate()        let picker = UIDocumentPickerViewController(forOpeningContentTypes: types, asCopy: false)        picker.allowsMultipleSelection = false        picker.delegate = delegate        let url = await withCheckedContinuation { continuation in            delegate.continuation = continuation            top.present(picker, animated: true)        }        withExtendedLifetime(delegate) {}        return url        #else        throw ActionRefused(ShellLines.line("documents", "picker.this_device_cannot_open"))        #endif    }}#if os(iOS)@MainActorprivate final class RecordFilePickerDelegate: 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