Files
ShoeGaze/Sources/LyrebirdShoeGaze/Presets/BoardVersionStore.swift
T
2026-06-21 12:25:18 -07:00

289 lines
12 KiB
Swift

// BoardVersionStore.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Observation
/// In-memory list of `BoardVersion` snapshots with optional disk persistence.
///
/// `BoardVersionStore` is `@Observable` so SwiftUI views automatically update when the
/// `versions` list changes. All mutations run on the main actor.
///
/// ## Typical usage
///
/// ```swift
/// let store = BoardVersionStore()
/// store.capture(myBoard, name: "Lead Crunch") // add a version
/// try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory())
///
/// // Restore on next launch:
/// let freshStore = BoardVersionStore()
/// try freshStore.loadAllFromDisk(in: BoardVersionStore.defaultDirectory())
/// if let v = freshStore.versions.first {
/// try shoeGaze.rebuildBoard(myBoard, from: v.state)
/// }
/// ```
///
/// ## Disk format
///
/// Each `BoardVersion` is written as a separate pretty-printed JSON file named
/// `<sanitized-name>-<id>.json` inside the chosen directory. File names are
/// sanitised by replacing `/`, `\`, `:`, NUL, leading `.`, and whitespace with
/// underscores; the sanitised prefix is capped at 200 UTF-8 bytes; all-whitespace
/// or all-separator names fall back to `"unnamed"`. `Date` values are encoded as
/// seconds since the Unix epoch (`TimeInterval`) for lossless round-trip equality.
@MainActor
@Observable
public final class BoardVersionStore {
// MARK: - State
/// All in-memory `BoardVersion` entries, sorted by `savedAt` after any disk load.
public private(set) var versions: [BoardVersion] = []
// MARK: - Init
/// Creates an empty store. Call `loadAllFromDisk(in:)` to populate from disk.
public init() {}
// MARK: - Capture
/// Captures the current state of `board` and appends a new `BoardVersion` to `versions`.
///
/// - Parameters:
/// - board: The `PedalBoard` to snapshot.
/// - name: Human-readable label for this version (e.g. `"Lead Crunch"`).
public func capture(
_ board: PedalBoard,
name: String
) {
let version: BoardVersion = BoardVersion(
id: UUID(),
name: name,
savedAt: Date(),
state: board.captureState()
)
versions.append(version)
}
// MARK: - Remove
/// Removes a version from the in-memory list. Matching is by `id`.
///
/// This is **memory-only**. Any JSON file previously written by `writeToDisk(_:in:)` is
/// not touched; call `deleteFromDisk(_:in:)` first if you also need to remove the file
/// so that the deletion survives `loadAllFromDisk`.
///
/// - Parameter version: The `BoardVersion` to remove.
public func remove(_ version: BoardVersion) {
versions.removeAll { $0.id == version.id }
}
// MARK: - Disk delete
/// Deletes the JSON file for `version` from `directory`.
///
/// The filename is derived using the same `<sanitized-name>-<id>.json` scheme as
/// `writeToDisk(_:in:)`. No-op if the file does not exist. Use this alongside
/// `remove(_:)` to make a deletion persist across `loadAllFromDisk`.
///
/// - Parameters:
/// - version: The `BoardVersion` whose file should be removed.
/// - directory: The directory that was passed to `writeToDisk(_:in:)`.
/// - Throws: `FileManager` errors other than "file not found".
public func deleteFromDisk(
_ version: BoardVersion,
in directory: URL
) throws {
let sanitized: String = sanitizeFilename(version.name)
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
let fileURL: URL = directory.appendingPathComponent(filename)
do {
try FileManager.default.removeItem(at: fileURL)
} catch let error as NSError
where error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError {
// File does not exist — treat as a no-op.
}
}
// MARK: - Disk write
/// Writes a single `BoardVersion` to `directory` as pretty-printed JSON.
///
/// The filename is `<sanitized-name>-<id>.json`. The sanitised name replaces `/`,
/// `:`, newlines, and other whitespace with underscores so the filename is safe on
/// HFS+ and APFS. The directory is created if it does not already exist.
///
/// - Parameters:
/// - version: The `BoardVersion` to write.
/// - directory: Destination directory URL. Created recursively if absent.
/// - Throws:
/// - `FileManager` errors if directory creation fails.
/// - `JSONEncoder` errors on encode failure.
/// - `Data.write(to:options:)` errors on write failure.
public func writeToDisk(
_ version: BoardVersion,
in directory: URL
) throws {
try FileManager.default.createDirectory(
at: directory,
withIntermediateDirectories: true,
attributes: nil
)
let sanitized: String = sanitizeFilename(version.name)
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
let fileURL: URL = directory.appendingPathComponent(filename)
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .secondsSince1970
let data: Data = try encoder.encode(version)
try data.write(to: fileURL, options: .atomic)
}
/// Writes every in-memory `BoardVersion` to `directory`.
///
/// Each version is written as a separate file (see `writeToDisk(_:in:)`).
/// The directory is created if it does not already exist. A failure on one file
/// propagates immediately and stops the remaining writes.
///
/// - Parameter directory: Destination directory URL. Created recursively if absent.
/// - Throws: The first error encountered during write.
public func writeAllToDisk(in directory: URL) throws {
for version: BoardVersion in versions {
try writeToDisk(version, in: directory)
}
}
// MARK: - Disk load
/// Loads all `*.json` files in `directory` as `BoardVersion` entries, replacing the
/// current in-memory `versions` list.
///
/// Files that cannot be **read** (e.g. permission errors) and files that cannot be
/// **decoded** (corrupt or unrecognised JSON) are both silently skipped — a single
/// bad file does not prevent the rest from loading. After loading, the list is sorted
/// ascending by `savedAt`.
///
/// - Parameter directory: The directory to scan. If the directory does not exist or
/// is empty, `versions` is set to `[]` without throwing.
/// - Throws: `FileManager` errors for directory enumeration failures (not for
/// individual file read/decode failures — those are silently skipped).
public func loadAllFromDisk(in directory: URL) throws {
var loaded: [BoardVersion] = []
// Early exit if the directory doesn't exist yet.
var isDirectory: ObjCBool = false
guard FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory),
isDirectory.boolValue else {
versions = []
return
}
let contents: [URL] = try FileManager.default.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles
)
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
for fileURL: URL in contents {
guard fileURL.pathExtension == "json" else { continue }
guard let data: Data = try? Data(contentsOf: fileURL) else { continue }
guard let version: BoardVersion = try? decoder.decode(BoardVersion.self, from: data) else {
continue
}
loaded.append(version)
}
loaded.sort { $0.savedAt < $1.savedAt }
versions = loaded
}
// MARK: - Default directory
/// Returns the recommended directory for storing board version files.
///
/// Resolves to `<Application Support>/LyrebirdShoeGaze/ShoeGazeVersions/` for the
/// current user. Falls back to a `ShoeGazeVersions/` subdirectory inside the
/// system temporary directory if Application Support is unavailable.
///
/// The directory is **not** created by this method — call `writeToDisk(_:in:)` or
/// `writeAllToDisk(in:)` (which create the directory automatically) before writing.
///
/// - Returns: A `URL` for the ShoeGaze versions directory.
public static func defaultDirectory() -> URL {
let appSupportDir: URL? = try? FileManager.default.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false
)
let base: URL = appSupportDir ?? FileManager.default.temporaryDirectory
return base
.appendingPathComponent("LyrebirdShoeGaze", isDirectory: true)
.appendingPathComponent("ShoeGazeVersions", isDirectory: true)
}
// MARK: - Private helpers
/// Maximum UTF-8 byte length for the sanitised name prefix before the `-<uuid>.json`
/// suffix is appended, so the full filename stays well under the 255-byte component limit.
private let maxNameLength: Int = 200
/// Sanitises a string so it is safe as a file-system component on HFS+ and APFS.
///
/// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace characters with underscores.
/// - Replaces a leading `.` (which would produce hidden-file or `.`/`..` names) with an
/// underscore.
/// - Trims leading and trailing underscores that resulted from whitespace or separator
/// substitution (cosmetic only — the result is always safe even before trimming).
/// - Caps the UTF-8 byte length of the result at `maxNameLength` so the full filename
/// (`<name>-<uuid>.json`, 54 extra bytes) cannot exceed the 255-byte component limit.
/// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely
/// to separator characters after substitution.
private func sanitizeFilename(_ name: String) -> String {
let replacementCharacter: Character = "_"
let forbiddenCharacters: Set<Character> = ["/", "\\", ":", "\0"]
var sanitized: String = name.map { character -> Character in
if character.isWhitespace || forbiddenCharacters.contains(character) {
return replacementCharacter
}
return character
}.reduce(into: "") { $0.append($1) }
// Replace a leading dot so the filename is never `.`, `..`, or a hidden file.
if sanitized.first == "." {
sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_")
}
// Trim whitespace-replacement underscores at both ends (cosmetic).
sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
// Treat all-empty or all-separator results as unnamed.
guard !sanitized.isEmpty else { return "unnamed" }
// Cap to maxNameLength UTF-8 bytes so the full filename stays within 255 bytes.
if sanitized.utf8.count > maxNameLength {
var truncated: String = ""
var byteCount: Int = 0
for scalar: Unicode.Scalar in sanitized.unicodeScalars {
let encodedLength: Int = UTF8.width(scalar)
guard byteCount + encodedLength <= maxNameLength else { break }
truncated.unicodeScalars.append(scalar)
byteCount += encodedLength
}
sanitized = truncated
}
return sanitized.isEmpty ? "unnamed" : sanitized
}
}