diff --git a/Demo/ShoeGazeBuilder/Info.plist b/Demo/ShoeGazeBuilder/Info.plist index 531f82f..7966158 100644 --- a/Demo/ShoeGazeBuilder/Info.plist +++ b/Demo/ShoeGazeBuilder/Info.plist @@ -40,5 +40,44 @@ Any + CFBundleDocumentTypes + + + CFBundleTypeName + ShoeGaze Document + CFBundleTypeRole + Editor + LSHandlerRank + Owner + LSItemContentTypes + + net.realizedsound.shoegaze + + + + UTExportedTypeDeclarations + + + UTTypeIdentifier + net.realizedsound.shoegaze + UTTypeDescription + ShoeGaze Document + UTTypeConformsTo + + public.json + + UTTypeTagSpecification + + public.filename-extension + + shoegaze + + public.mime-type + + application/json + + + + diff --git a/Demo/ShoeGazeBuilderiOS/Info.plist b/Demo/ShoeGazeBuilderiOS/Info.plist index 8e812d6..3aff9b1 100644 --- a/Demo/ShoeGazeBuilderiOS/Info.plist +++ b/Demo/ShoeGazeBuilderiOS/Info.plist @@ -53,5 +53,44 @@ Any + CFBundleDocumentTypes + + + CFBundleTypeName + ShoeGaze Document + CFBundleTypeRole + Editor + LSHandlerRank + Owner + LSItemContentTypes + + net.realizedsound.shoegaze + + + + UTExportedTypeDeclarations + + + UTTypeIdentifier + net.realizedsound.shoegaze + UTTypeDescription + ShoeGaze Document + UTTypeConformsTo + + public.json + + UTTypeTagSpecification + + public.filename-extension + + shoegaze + + public.mime-type + + application/json + + + + diff --git a/Demo/ShoeGazeDemo/Info.plist b/Demo/ShoeGazeDemo/Info.plist index d23e0ba..61361cd 100644 --- a/Demo/ShoeGazeDemo/Info.plist +++ b/Demo/ShoeGazeDemo/Info.plist @@ -28,5 +28,44 @@ ShoeGazeDemo can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode. NSPrincipalClass NSApplication + CFBundleDocumentTypes + + + CFBundleTypeName + ShoeGaze Document + CFBundleTypeRole + Editor + LSHandlerRank + Owner + LSItemContentTypes + + net.realizedsound.shoegaze + + + + UTExportedTypeDeclarations + + + UTTypeIdentifier + net.realizedsound.shoegaze + UTTypeDescription + ShoeGaze Document + UTTypeConformsTo + + public.json + + UTTypeTagSpecification + + public.filename-extension + + shoegaze + + public.mime-type + + application/json + + + + diff --git a/Demo/ShoeGazeiOSDemo/Info.plist b/Demo/ShoeGazeiOSDemo/Info.plist index 6723281..e73fcd5 100644 --- a/Demo/ShoeGazeiOSDemo/Info.plist +++ b/Demo/ShoeGazeiOSDemo/Info.plist @@ -41,5 +41,44 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + CFBundleDocumentTypes + + + CFBundleTypeName + ShoeGaze Document + CFBundleTypeRole + Editor + LSHandlerRank + Owner + LSItemContentTypes + + net.realizedsound.shoegaze + + + + UTExportedTypeDeclarations + + + UTTypeIdentifier + net.realizedsound.shoegaze + UTTypeDescription + ShoeGaze Document + UTTypeConformsTo + + public.json + + UTTypeTagSpecification + + public.filename-extension + + shoegaze + + public.mime-type + + application/json + + + + diff --git a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift index 3a7b1a9..8e2268a 100644 --- a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift +++ b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift @@ -278,22 +278,39 @@ public final class RigLibraryStore { // MARK: - Archive import / export - /// Encodes the entire library as a single ``RigArchive`` JSON document for export. + /// Encodes the entire library as a single ``RigArchive`` JSON document. /// - /// - Returns: Pretty-printed archive bytes suitable for a `fileExporter` / `NSSavePanel`. + /// Retained for callers and tests that want the bare archive bytes. The user-facing + /// export/share path uses ``exportDocumentData()``, which wraps the same rigs in a + /// ``ShoeGazeDocument`` envelope (the `.shoegaze` file type). + /// + /// - Returns: Pretty-printed archive bytes. /// - Throws: `JSONEncoder` errors. public func exportArchiveData() throws -> Data { let archive: RigArchive = RigArchive(rigs: entries) return try RigLibraryStore.makeEncoder().encode(archive) } + /// Encodes the entire library as a ``ShoeGazeDocument`` for export to a `.shoegaze` file. + /// + /// This is the format written by the library's **Export** action and shared via the system + /// share sheet. ``importArchive(from:)`` reads it back, and also still accepts the bare + /// ``RigArchive`` and legacy single-rig shapes. + /// + /// - Returns: Pretty-printed `.shoegaze` document bytes. + /// - Throws: `JSONEncoder` errors. + public func exportDocumentData() throws -> Data { + try ShoeGazeDocument(rigs: entries).data() + } + /// Imports rigs from archive `data`, saving each into the library, and returns how many were /// added. /// - /// Accepts either a ``RigArchive`` (the multi-rig export format) or a legacy single-rig file - /// (a bare ``ShoeGazeState``), which is imported as one entry named `legacyRigName`. Imported - /// entries whose `id` already exists in the library are given a fresh `id` so an import never - /// silently overwrites an existing rig. + /// Accepts a ``ShoeGazeDocument`` (the `.shoegaze` file type), a bare ``RigArchive`` (the prior + /// multi-rig export), or a legacy single-rig file (a bare ``ShoeGazeState``), which is imported + /// as one entry named `legacyRigName`. A document carrying a board rather than rigs contributes + /// no entries. Imported entries whose `id` already exists in the library are given a fresh `id` + /// so an import never silently overwrites an existing rig. /// /// - Parameters: /// - data: Archive or legacy-rig JSON bytes. @@ -512,19 +529,15 @@ public final class RigLibraryStore { return decoder } - /// Decodes import bytes as a ``RigArchive`` first, falling back to a legacy single-rig - /// ``ShoeGazeState``. + /// Decodes import bytes into rig entries, accepting the `.shoegaze` ``ShoeGazeDocument`` + /// envelope plus the bare ``RigArchive`` and legacy ``ShoeGazeState`` shapes (see + /// ``ShoeGazeDocument/decoded(from:legacyRigName:)``). A board-carrying document yields no rigs. private func decodeImportable( _ data: Data, legacyRigName: String ) throws -> [RigEntry] { - let decoder: JSONDecoder = RigLibraryStore.makeDecoder() - if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) { - return archive.rigs - } - // A legacy single-rig file is a bare ShoeGazeState (no `rigs` array). Decode and wrap. - let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data) - return [RigEntry(name: legacyRigName, state: state)] + let document: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data, legacyRigName: legacyRigName) + return document.rigEntries ?? [] } // MARK: - In-memory helpers diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeDocument.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeDocument.swift new file mode 100644 index 0000000..b0f6d5d --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeDocument.swift @@ -0,0 +1,201 @@ +// ShoeGazeDocument.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Format version written into every `.shoegaze` document. +/// +/// Increment when the `ShoeGazeDocument` envelope schema changes in a way that requires +/// migration on load. The payload types (``RigArchive`` / ``BoardVersion``) carry their own +/// independent version fields. +public let shoeGazeDocumentFormatVersion: Int = 1 + +/// The portable `.shoegaze` document — the single file type ShoeGaze writes when a user shares +/// or exports their work, and reads when opening a shared file. +/// +/// A document is a small versioned envelope around one of two payloads: +/// +/// - ``Payload/rigs(_:)`` — one or more rigs, carried as a ``RigArchive`` (a single shared rig is +/// a one-rig archive; the whole-library export is a many-rig archive). +/// - ``Payload/board(_:)`` — a single named board snapshot (``BoardVersion``). +/// +/// Files are written pretty-printed with sorted keys and `secondsSince1970` dates, so they stay +/// hand-readable and round-trip losslessly. +/// +/// ## Backward compatibility +/// +/// ``decoded(from:)`` accepts three on-disk shapes so older files keep opening: +/// 1. A `ShoeGazeDocument` envelope (the current format). +/// 2. A bare ``RigArchive`` (the previous multi-rig export). +/// 3. A bare ``ShoeGazeState`` (the original single-rig save). +/// +/// Shapes 2 and 3 are normalised into a ``Payload/rigs(_:)`` document on load. +public struct ShoeGazeDocument: Codable, Equatable { + + /// The two things a `.shoegaze` file can carry. + public enum Payload: Equatable { + + /// One or more rigs, as a portable archive. + case rigs(RigArchive) + + /// A single named board snapshot. + case board(BoardVersion) + } + + /// Filename extension and the basis for the document's UTType (`net.realizedsound.shoegaze`). + public static let fileExtension: String = "shoegaze" + + /// Document envelope version. Written as `shoeGazeDocumentFormatVersion` at save time. + public let version: Int + + /// What this document carries. + public let payload: Payload + + /// Creates a document with an explicit payload. + /// + /// - Parameters: + /// - version: Envelope version. Defaults to `shoeGazeDocumentFormatVersion`. + /// - payload: The rigs or board this document carries. + public init( + version: Int = shoeGazeDocumentFormatVersion, + payload: Payload + ) { + self.version = version + self.payload = payload + } + + // MARK: - Convenience constructors + + /// Creates a single-rig document by wrapping one ``RigEntry`` in a one-rig ``RigArchive``. + /// + /// - Parameter entry: The rig to share. + public init(rig entry: RigEntry) { + self.init(payload: .rigs(RigArchive(rigs: [entry]))) + } + + /// Creates a multi-rig document from a list of entries. + /// + /// - Parameter entries: The rigs to bundle, in listing order. + public init(rigs entries: [RigEntry]) { + self.init(payload: .rigs(RigArchive(rigs: entries))) + } + + /// Creates a single-board document. + /// + /// - Parameter version: The board snapshot to share. + public init(board version: BoardVersion) { + self.init(payload: .board(version)) + } + + // MARK: - Payload accessors + + /// The rigs this document carries, or `nil` when it carries a board. + public var rigEntries: [RigEntry]? { + if case .rigs(let archive) = payload { return archive.rigs } + return nil + } + + /// The board this document carries, or `nil` when it carries rigs. + public var boardVersion: BoardVersion? { + if case .board(let version) = payload { return version } + return nil + } + + // MARK: - Encoding + + /// Encodes this document to pretty-printed, hand-editable `.shoegaze` JSON. + /// + /// - Returns: The encoded document bytes. + /// - Throws: Any error from `JSONEncoder`. + public func data() throws -> Data { + try ShoeGazeDocument.makeEncoder().encode(self) + } + + /// Decodes a `.shoegaze` document, tolerating the two legacy on-disk shapes. + /// + /// Tries the `ShoeGazeDocument` envelope first, then a bare ``RigArchive``, then a bare + /// ``ShoeGazeState`` — normalising the latter two into a rigs document. A bare state with no + /// name becomes a one-rig archive named `legacyRigName`. + /// + /// - Parameters: + /// - data: The document bytes. + /// - legacyRigName: Name applied when normalising a bare ``ShoeGazeState``. Defaults to + /// `"Imported Rig"`. + /// - Returns: A normalised document. + /// - Throws: `JSONDecoder` errors when `data` matches none of the three shapes. + public static func decoded( + from data: Data, + legacyRigName: String = "Imported Rig" + ) throws -> ShoeGazeDocument { + let decoder: JSONDecoder = makeDecoder() + if let document: ShoeGazeDocument = try? decoder.decode(ShoeGazeDocument.self, from: data) { + return document + } + if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) { + return ShoeGazeDocument(payload: .rigs(archive)) + } + // Original single-rig save: a bare ShoeGazeState. Let a genuine decode failure surface here. + let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data) + return ShoeGazeDocument(rig: RigEntry(name: legacyRigName, state: state)) + } + + /// A JSON encoder configured for human-readable, round-trip-stable document files. + static func makeEncoder() -> JSONEncoder { + let encoder: JSONEncoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + encoder.dateEncodingStrategy = .secondsSince1970 + return encoder + } + + /// A JSON decoder matching ``makeEncoder()``. + static func makeDecoder() -> JSONDecoder { + let decoder: JSONDecoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + return decoder + } + + // MARK: - Codable + + /// Discriminator written into the JSON so a payload reads back unambiguously. + private enum Kind: String, Codable { + case rigs + case board + } + + private enum CodingKeys: String, CodingKey { + case version + case kind + case rigs + case board + } + + /// Encodes the envelope with an explicit `kind` discriminator and the matching payload key. + public func encode(to encoder: any Encoder) throws { + var container: KeyedEncodingContainer = encoder.container(keyedBy: CodingKeys.self) + try container.encode(version, forKey: .version) + switch payload { + case .rigs(let archive): + try container.encode(Kind.rigs, forKey: .kind) + try container.encode(archive, forKey: .rigs) + case .board(let boardVersion): + try container.encode(Kind.board, forKey: .kind) + try container.encode(boardVersion, forKey: .board) + } + } + + /// Decodes the envelope, reading the payload named by the `kind` discriminator. + public init(from decoder: any Decoder) throws { + let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) + self.version = try container.decode(Int.self, forKey: .version) + let kind: Kind = try container.decode(Kind.self, forKey: .kind) + switch kind { + case .rigs: + self.payload = .rigs(try container.decode(RigArchive.self, forKey: .rigs)) + case .board: + self.payload = .board(try container.decode(BoardVersion.self, forKey: .board)) + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/BoardEditorView.swift b/Sources/LyrebirdShoeGazeUI/BoardEditorView.swift index 660dbf0..e688d9f 100644 --- a/Sources/LyrebirdShoeGazeUI/BoardEditorView.swift +++ b/Sources/LyrebirdShoeGazeUI/BoardEditorView.swift @@ -218,6 +218,16 @@ public struct BoardEditorView: View { Button("Load") { loadVersion(version) } + // Encoding a fully-concrete BoardVersion to JSON does not fail in practice; on the + // unreachable failure path the Share item is simply omitted. + if let shareItem: BoardShareItem = try? BoardShareItem(board: version) { + ShareLink( + item: shareItem, + preview: SharePreview(version.name) + ) { + Label("Share…", systemImage: "square.and.arrow.up") + } + } Button("Delete", role: .destructive) { versionStore.remove(version) try? versionStore.deleteFromDisk(version, in: BoardVersionStore.defaultDirectory()) diff --git a/Sources/LyrebirdShoeGazeUI/BoardShareItem.swift b/Sources/LyrebirdShoeGazeUI/BoardShareItem.swift new file mode 100644 index 0000000..abdcc6d --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/BoardShareItem.swift @@ -0,0 +1,42 @@ +// BoardShareItem.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import CoreTransferable +import UniformTypeIdentifiers +import LyrebirdShoeGaze + +/// A `Transferable` wrapper that lets a `ShareLink` send a single board as a `.shoegaze` document. +/// +/// Mirrors ``RigShareItem`` for a board snapshot: it holds the already-encoded document bytes and +/// the system serialises them to a temporary `.shoegaze` file for AirDrop, Mail, Messages, +/// and Files. +struct BoardShareItem: Transferable, Sendable { + + /// Filesystem-safe base name for the shared file (no extension). + let filenameBase: String + + /// Encoded `.shoegaze` document bytes. + let data: Data + + /// Encodes `version` as a single-board `.shoegaze` document. + /// + /// - Parameter version: The board snapshot to share. + /// - Throws: Any `JSONEncoder` error from ``ShoeGazeDocument/data()``. + init(board version: BoardVersion) throws { + self.filenameBase = shareFilenameBase(version.name) + self.data = try ShoeGazeDocument(board: version).data() + } + + static var transferRepresentation: some TransferRepresentation { + DataRepresentation(exportedContentType: .shoeGaze) { item in + item.data + } + .suggestedFileName { item in + "\(item.filenameBase).\(ShoeGazeDocument.fileExtension)" + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift b/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift index 2f65de8..6e1a8fe 100644 --- a/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift +++ b/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift @@ -7,15 +7,18 @@ import SwiftUI import UniformTypeIdentifiers -/// A minimal JSON `FileDocument` wrapping a ShoeGaze rig's encoded bytes. +/// A minimal `FileDocument` wrapping a ShoeGaze document's encoded bytes. /// -/// Used by ``ShoeGazeBuilderView``'s iOS `.fileExporter` to write the result of -/// `ShoeGaze.rigData()` to a user-chosen location. macOS uses an `NSSavePanel` directly and does -/// not need this type. +/// Used by ``ShoeGazeBuilderView``'s `.fileExporter` to write the result of +/// `RigLibraryStore.exportDocumentData()` (a `.shoegaze` ``ShoeGazeDocument``) to a user-chosen +/// location. struct RigFileDocument: FileDocument { - /// The rig presets are plain JSON. - static var readableContentTypes: [UTType] { [.json] } + /// Writes the `.shoegaze` document type. + static var writableContentTypes: [UTType] { [.shoeGaze] } + + /// Reads `.shoegaze` documents and the legacy plain-JSON exports. + static var readableContentTypes: [UTType] { [.shoeGaze, .json] } /// Encoded rig JSON. let data: Data diff --git a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift index 1485f68..cbce5e0 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift @@ -132,6 +132,16 @@ struct RigLibrarySidebarView: View { .contextMenu { Button("Rename…") { onRename(entry) } Button("Duplicate…") { onDuplicate(entry) } + // Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the + // unreachable failure path the Share item is simply omitted. + if let shareItem: RigShareItem = try? RigShareItem(rig: entry) { + ShareLink( + item: shareItem, + preview: SharePreview(entry.name) + ) { + Label("Share…", systemImage: "square.and.arrow.up") + } + } Divider() Button("Delete", role: .destructive) { onDelete(entry) } } diff --git a/Sources/LyrebirdShoeGazeUI/RigShareItem.swift b/Sources/LyrebirdShoeGazeUI/RigShareItem.swift new file mode 100644 index 0000000..4563361 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/RigShareItem.swift @@ -0,0 +1,56 @@ +// RigShareItem.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import CoreTransferable +import UniformTypeIdentifiers +import LyrebirdShoeGaze + +/// A `Transferable` wrapper that lets a `ShareLink` send a single rig as a `.shoegaze` document. +/// +/// Holds the already-encoded document bytes (a value type, so the wrapper is `Sendable` as +/// `Transferable` requires). The encode happens when the share menu is built for the focused row — +/// cheap, one rig — via the throwing ``init(rig:)``. The system serialises the bytes to a temporary +/// file named `.shoegaze` for AirDrop, Mail, Messages, and Files. +struct RigShareItem: Transferable, Sendable { + + /// Filesystem-safe base name for the shared file (no extension). + let filenameBase: String + + /// Encoded `.shoegaze` document bytes. + let data: Data + + /// Encodes `entry` as a single-rig `.shoegaze` document. + /// + /// - Parameter entry: The library entry to share. + /// - Throws: Any `JSONEncoder` error from ``ShoeGazeDocument/data()``. + init(rig entry: RigEntry) throws { + self.filenameBase = shareFilenameBase(entry.name) + self.data = try ShoeGazeDocument(rig: entry).data() + } + + static var transferRepresentation: some TransferRepresentation { + DataRepresentation(exportedContentType: .shoeGaze) { item in + item.data + } + .suggestedFileName { item in + "\(item.filenameBase).\(ShoeGazeDocument.fileExtension)" + } + } +} + +/// Reduces a user-supplied name to a filesystem-safe base for a shared file, mirroring the preset +/// stores' sanitisation at the UI boundary (the core sanitiser is module-internal to +/// `LyrebirdShoeGaze`). Path separators and whitespace become underscores; an empty result falls +/// back to a generic name. Shared by ``RigShareItem`` and ``BoardShareItem``. +func shareFilenameBase(_ name: String) -> String { + let forbidden: Set = ["/", "\\", ":", "\0"] + let mapped: String = String(name.map { character -> Character in + (character.isWhitespace || forbidden.contains(character)) ? "_" : character + }) + let trimmed: String = mapped.trimmingCharacters(in: CharacterSet(charactersIn: "_")) + return trimmed.isEmpty ? "ShoeGaze" : trimmed +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index ed543b6..c8f7f56 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -360,27 +360,28 @@ public struct ShoeGazeBuilderView: View { } } - /// Hosts the archive-export (`.json`) exporter on its own node. Writes the whole library as one - /// ``RigArchive`` file for backup or transfer. + /// Hosts the library-export (`.shoegaze`) exporter on its own node. Writes the whole library as + /// one ``ShoeGazeDocument`` file for backup or transfer. private var rigExportAnchor: some View { Color.clear .fileExporter( isPresented: $showExporter, document: exportDocument, - contentType: .json, + contentType: .shoeGaze, defaultFilename: ShoeGazeBuilderView.defaultArchiveFileName ) { result in if case .failure(let error) = result { - print("[ShoeGazeBuilderView] archive export failed: \(error)") + print("[ShoeGazeBuilderView] library export failed: \(error)") } } } - /// Hosts the archive-import (`.json`) importer on its own node (cross-platform). Accepts a - /// ``RigArchive`` or a legacy single-rig file; imported rigs are added to the library. + /// Hosts the library-import (`.shoegaze`) importer on its own node (cross-platform). Accepts a + /// ``ShoeGazeDocument`` or a legacy archive / single-rig file; imported rigs are added to the + /// library. private var rigImportAnchor: some View { Color.clear - .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in + .fileImporter(isPresented: $showImporter, allowedContentTypes: [.shoeGaze, .json]) { result in handleArchiveImport(result) } } @@ -917,13 +918,13 @@ public struct ShoeGazeBuilderView: View { } } - /// Captures the current session into the whole-library archive exporter. + /// Captures the whole library into the `.shoegaze` document exporter. private func exportArchiveAction() { do { - exportDocument = RigFileDocument(data: try library.exportArchiveData()) + exportDocument = RigFileDocument(data: try library.exportDocumentData()) showExporter = true } catch { - print("[ShoeGazeBuilderView] exportArchiveData failed: \(error)") + print("[ShoeGazeBuilderView] exportDocumentData failed: \(error)") } } diff --git a/Sources/LyrebirdShoeGazeUI/UTType+ShoeGaze.swift b/Sources/LyrebirdShoeGazeUI/UTType+ShoeGaze.swift new file mode 100644 index 0000000..47ed251 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/UTType+ShoeGaze.swift @@ -0,0 +1,20 @@ +// UTType+ShoeGaze.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import UniformTypeIdentifiers + +public extension UTType { + + /// The `.shoegaze` document type — a versioned JSON envelope carrying a shared rig or board. + /// + /// Identifier `net.realizedsound.shoegaze`, conforming to `public.json` so the file stays + /// text-readable and is recognised by tools that understand JSON. The hosting app must also + /// declare this type in its `Info.plist` (`UTExportedTypeDeclarations` + `CFBundleDocumentTypes`) + /// for the system to associate the `.shoegaze` extension with the app and offer it in Share / + /// Open dialogs; this property mirrors that declaration so SwiftUI `fileExporter` / `fileImporter` + /// and `ShareLink` can reference it in code. + static let shoeGaze: UTType = UTType(exportedAs: "net.realizedsound.shoegaze", conformingTo: .json) +} diff --git a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift index 3980316..6c4bc5e 100644 --- a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift +++ b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift @@ -149,8 +149,9 @@ struct RigLibraryStoreTests { try store.save(entry) // An archive carrying the SAME id must not overwrite the existing rig on import. + // Encode with the on-disk strategy (.secondsSince1970) so dates survive the import decoder. let archive: RigArchive = RigArchive(rigs: [entry]) - let data: Data = try JSONEncoder().encode(archive) + let data: Data = try ShoeGazeDocument.makeEncoder().encode(archive) let added: Int = try store.importArchive(from: data) #expect(added == 1) #expect(store.entries.count == 2, "colliding id should be imported as a new entry") @@ -163,10 +164,42 @@ struct RigLibraryStoreTests { // A legacy file is a bare ShoeGazeState (no `rigs` array). let legacyState: ShoeGazeState = ShoeGazeState(boards: [BoardState(label: "Legacy", segments: [])]) - let data: Data = try JSONEncoder().encode(legacyState) + let data: Data = try ShoeGazeDocument.makeEncoder().encode(legacyState) let added: Int = try store.importArchive(from: data, legacyRigName: "Recovered") #expect(added == 1) #expect(store.entries.first?.name == "Recovered") store.flushPendingWrites() } + + @Test func exportDocumentThenImportRoundTrips() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + try store.save(makeEntry("One")) + try store.save(makeEntry("Two")) + // The user-facing export is a `.shoegaze` ShoeGazeDocument envelope. + let documentData: Data = try store.exportDocumentData() + #expect(try ShoeGazeDocument.decoded(from: documentData).rigEntries?.count == 2) + + let (other, otherDir): (RigLibraryStore, URL) = await makeStore() + defer { try? FileManager.default.removeItem(at: otherDir) } + let added: Int = try other.importArchive(from: documentData) + #expect(added == 2) + #expect(other.entries.map(\.name) == ["One", "Two"]) + store.flushPendingWrites() + other.flushPendingWrites() + } + + @Test func importBoardDocumentAddsNoRigs() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + // A board-carrying `.shoegaze` document is valid but contributes no library rigs. + let boardDocument: ShoeGazeDocument = + ShoeGazeDocument(board: BoardVersion(name: "Lead", state: BoardState(label: "Lead", segments: []))) + let added: Int = try store.importArchive(from: try boardDocument.data()) + #expect(added == 0) + #expect(store.entries.isEmpty) + store.flushPendingWrites() + } } diff --git a/Tests/LyrebirdShoeGazeTests/ShoeGazeDocumentTests.swift b/Tests/LyrebirdShoeGazeTests/ShoeGazeDocumentTests.swift new file mode 100644 index 0000000..c4eed10 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ShoeGazeDocumentTests.swift @@ -0,0 +1,111 @@ +// ShoeGazeDocumentTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable import LyrebirdShoeGaze + +@Suite("ShoeGazeDocument — share/export envelope") +struct ShoeGazeDocumentTests { + + /// A minimal two-board rig state for snapshotting without an engine. + private func makeState(lead: String = "Lead") -> ShoeGazeState { + let board: BoardState = BoardState(label: lead, segments: []) + let other: BoardState = BoardState(label: "Clean", segments: []) + return ShoeGazeState(boards: [board, other]) + } + + private func makeEntry(name: String = "Ambient Wash") -> RigEntry { + RigEntry(name: name, state: makeState()) + } + + private func makeBoardVersion(name: String = "Lead Crunch") -> BoardVersion { + BoardVersion(name: name, state: BoardState(label: "Lead", segments: [])) + } + + // MARK: - Round trips + + @Test func singleRigRoundTripIsLossless() throws { + let entry: RigEntry = makeEntry() + let document: ShoeGazeDocument = ShoeGazeDocument(rig: entry) + + let data: Data = try document.data() + let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data) + + #expect(decoded == document) + #expect(decoded.rigEntries == [entry]) + #expect(decoded.boardVersion == nil) + #expect(decoded.version == shoeGazeDocumentFormatVersion) + } + + @Test func multiRigRoundTripIsLossless() throws { + let entries: [RigEntry] = [makeEntry(name: "A"), makeEntry(name: "B")] + let document: ShoeGazeDocument = ShoeGazeDocument(rigs: entries) + + let data: Data = try document.data() + let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data) + + #expect(decoded == document) + #expect(decoded.rigEntries == entries) + } + + @Test func boardRoundTripIsLossless() throws { + let boardVersion: BoardVersion = makeBoardVersion() + let document: ShoeGazeDocument = ShoeGazeDocument(board: boardVersion) + + let data: Data = try document.data() + let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data) + + #expect(decoded == document) + #expect(decoded.boardVersion == boardVersion) + #expect(decoded.rigEntries == nil) + } + + // MARK: - Backward compatibility + + @Test func decodesLegacyRigArchive() throws { + let entries: [RigEntry] = [makeEntry(name: "Old A"), makeEntry(name: "Old B")] + let archive: RigArchive = RigArchive(rigs: entries) + + let encoder: JSONEncoder = ShoeGazeDocument.makeEncoder() + let data: Data = try encoder.encode(archive) + + let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data) + #expect(decoded.rigEntries == entries) + } + + @Test func decodesLegacyBareState() throws { + let state: ShoeGazeState = makeState() + + let encoder: JSONEncoder = ShoeGazeDocument.makeEncoder() + let data: Data = try encoder.encode(state) + + let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data, legacyRigName: "Recovered") + #expect(decoded.rigEntries?.count == 1) + #expect(decoded.rigEntries?.first?.name == "Recovered") + #expect(decoded.rigEntries?.first?.state == state) + } + + @Test func rejectsGarbage() { + let data: Data = Data("not a shoegaze document".utf8) + #expect(throws: (any Error).self) { + _ = try ShoeGazeDocument.decoded(from: data) + } + } + + // MARK: - On-disk shape + + @Test func envelopeCarriesKindDiscriminator() throws { + let rigData: Data = try ShoeGazeDocument(rig: makeEntry()).data() + let boardData: Data = try ShoeGazeDocument(board: makeBoardVersion()).data() + + let rigJSON: String = String(decoding: rigData, as: UTF8.self) + let boardJSON: String = String(decoding: boardData, as: UTF8.self) + + #expect(rigJSON.contains("\"kind\" : \"rigs\"")) + #expect(boardJSON.contains("\"kind\" : \"board\"")) + } +} diff --git a/docs/plans/1.3-rig-sharing.md b/docs/plans/1.3-rig-sharing.md new file mode 100644 index 0000000..98c5335 --- /dev/null +++ b/docs/plans/1.3-rig-sharing.md @@ -0,0 +1,48 @@ +# 1.3 — Rig sharing & the `.shoegaze` document type + +Goal: a single registered file type for sharing rigs and boards, migrate export/import onto it, and +add an OS share sheet to the rig library and board-version menu. Local only — no backend, no accounts. + +## File type + +- **Extension:** `.shoegaze`. **UTType:** `net.realizedsound.shoegaze`, conforms to `public.json` + (stays text-readable). `UTType.shoeGaze` lives in `LyrebirdShoeGazeUI`. +- Declared by all four demo apps and both CLI scaffolder templates + (`CFBundleDocumentTypes` Editor/Owner + `UTExportedTypeDeclarations`) so the system associates the + type with the app for Open and Share. + +## Document model — `LyrebirdShoeGaze` + +`ShoeGazeDocument` — versioned envelope (`shoeGazeDocumentFormatVersion = 1`) around one payload: + +- `.rigs(RigArchive)` — one or many rigs (a single shared rig is a one-rig archive). +- `.board(BoardVersion)` — a single board snapshot. + +`data()` encodes pretty-printed JSON (`secondsSince1970` dates). `decoded(from:legacyRigName:)` is +tolerant: tries the envelope, then a bare `RigArchive`, then a bare `ShoeGazeState` (normalised to a +one-rig document). On-disk JSON carries an explicit `kind` discriminator. + +## Migration + +- `RigLibraryStore.exportDocumentData()` writes the library as a `.shoegaze` document; the prior + `exportArchiveData()` (bare `RigArchive`) is retained for callers/tests. +- `importArchive(from:)` now decodes via `ShoeGazeDocument.decoded` — accepts `.shoegaze`, bare + archive, and legacy single-rig files. A board document contributes no rigs. +- `RigFileDocument` writes `.shoeGaze`, reads `[.shoeGaze, .json]`. The Builder's `fileExporter` + uses `.shoeGaze`; the `fileImporter` accepts `[.shoeGaze, .json]`. +- **Internal** per-rig library files and board-version files stay plain `.json` (app-private; no + churn). `.shoegaze` is the share/export surface only. + +## Share UI — `LyrebirdShoeGazeUI` + +- `RigShareItem` / `BoardShareItem` — `Transferable` wrappers holding pre-encoded `.shoegaze` bytes + (value-type payload keeps them `Sendable`). Suggested filename `.shoegaze`. +- Rig library sidebar: `Share…` per rig (context menu). Board editor Versions menu: `Share…` per + version. Both via SwiftUI `ShareLink` → AirDrop / Mail / Messages / Files. + +## Tests + +- `ShoeGazeDocumentTests` — rig/board round-trip, legacy archive + bare-state decode, garbage + rejection, `kind` discriminator on disk. +- `RigLibraryStoreTests` — `.shoegaze` export→import round-trip; board document imports zero rigs. +- Lyrebird `ProjectScaffolderTests` — generated macOS/iOS `Info.plist` registers the document type.