Zum Inhalt

apple/PhysarumApp/Sources/Model/PresetDocument.swift

#if !os(tvOS)
import SwiftUI
import UniformTypeIdentifiers
import PhysarumEngine

/// Read+write FileDocument for a single preset as `.json` — unlike the export-only
/// `ExportedCapture`, this round-trips so the same `.fileExporter`/`.fileImporter`
/// machinery can both write a preset to disk and decode one back.
struct PresetDocument: FileDocument {
    static var readableContentTypes: [UTType] { [.json] }

    var preset: Preset

    init(preset: Preset) { self.preset = preset }

    init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents else {
            throw CocoaError(.fileReadCorruptFile)
        }
        preset = try JSONDecoder().decode(Preset.self, from: data)
    }

    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        FileWrapper(regularFileWithContents: try JSONEncoder().encode(preset))
    }
}

/// Read+write FileDocument for a single `AudioConfig` as `.json` — the audio-preset
/// parallel of `PresetDocument`, reusing the same `.fileExporter`/`.fileImporter`
/// machinery to round-trip a saved audio config to/from disk.
struct AudioConfigDocument: FileDocument {
    static var readableContentTypes: [UTType] { [.json] }

    var config: AudioConfig

    init(config: AudioConfig) { self.config = config }

    init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents else {
            throw CocoaError(.fileReadCorruptFile)
        }
        config = try JSONDecoder().decode(AudioConfig.self, from: data)
    }

    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        FileWrapper(regularFileWithContents: try JSONEncoder().encode(config))
    }
}
#endif