Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/Kit/Stores/ThemeStore.swift8// Module : GlassStudio9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import Observation43import SPGlassKit4445/// The custom themes saved by the Studio, as one versioned document.46struct ThemeLibraryDocument: Codable, Sendable, Equatable {47 var schemaVersion = 148 var themes: [GlassTheme] = []49}5051/// Built-in, example and custom themes, with local persistence.52///53/// Built-in themes are read-only: editing one starts from a duplicate. Custom themes are stored on the54/// device only; nothing is sent anywhere.55@MainActor56@Observable57public final class ThemeStore {58 public private(set) var customThemes: [GlassTheme] = []59 /// Set when the stored library had to be recovered, so the interface can say so once.60 public private(set) var recoveryNotice: String?61 public private(set) var lastError: String?6263 private let store: AtomicFileStore<ThemeLibraryDocument>64 public static let maximumCustomThemes = 2006566 public init(directory: URL? = nil) {67 store = AtomicFileStore(url: StudioPaths.dataDirectory(override: directory).appendingPathComponent("themes.json"))68 let loaded = store.load(default: ThemeLibraryDocument(), migrate: Self.migrate)69 customThemes = loaded.document.themes70 switch loaded.outcome {71 case .recoveredFromBackup(let name): recoveryNotice = "recovered:\(name)"72 case .resetToDefault(let name): recoveryNotice = "reset:\(name)"73 case .loaded, .missing: break74 }75 }7677 /// Reads a library document of any known version. Themes that fail validation are skipped, not fatal.78 static func migrate(_ data: Data) throws -> ThemeLibraryDocument {79 guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {80 throw GlassThemeError.notAnObject81 }82 let version = object["schemaVersion"] as? Int ?? 083 guard version <= 1 else { throw GlassThemeError.unsupportedSchema(version) }84 // Version 0 stored a bare array under "items".85 let raw = (object["themes"] ?? object["items"]) as? [Any] ?? []86 var themes: [GlassTheme] = []87 for entry in raw.prefix(maximumCustomThemes) {88 guard let dictionary = entry as? [String: Any], JSONSerialization.isValidJSONObject(dictionary),89 let entryData = try? JSONSerialization.data(withJSONObject: dictionary), let theme = try? GlassThemeCodec.decode(entryData) else { continue }90 if !themes.contains(where: { $0.id == theme.id }) { themes.append(theme) }91 }92 return ThemeLibraryDocument(themes: themes)93 }9495 public var allThemes: [GlassTheme] { GlassTheme.builtIn + customThemes + GlassTheme.examples }9697 public func theme(_ id: GlassThemeID) -> GlassTheme? {98 customThemes.first { $0.id == id } ?? GlassTheme.named(id)99 }100101 public func isCustom(_ id: GlassThemeID) -> Bool {102 customThemes.contains { $0.id == id }103 }104105 /// Saves a custom theme (new or existing). Built-in identifiers cannot be overwritten.106 @discardableResult107 public func save(_ theme: GlassTheme) -> Bool {108 guard GlassTheme.named(theme.id) == nil else { lastError = "builtin"; return false }109 guard GlassThemeValidator.isUsable(theme) else { lastError = "invalid"; return false }110 if let index = customThemes.firstIndex(where: { $0.id == theme.id }) {111 customThemes[index] = theme112 } else {113 guard customThemes.count < Self.maximumCustomThemes else { lastError = "full"; return false }114 customThemes.append(theme)115 }116 return persist()117 }118119 /// Creates an editable copy of any theme with a unique identifier.120 public func duplicate(_ theme: GlassTheme, name: String? = nil) -> GlassTheme? {121 let base = theme.id.rawValue.hasPrefix("custom-") ? theme.id.rawValue : "custom-\(theme.id.rawValue)"122 let copy = theme.duplicated(id: uniqueID(base: base), name: name ?? "\(theme.name) Copy")123 return save(copy) ? copy : nil124 }125126 public func delete(_ id: GlassThemeID) {127 customThemes.removeAll { $0.id == id }128 persist()129 }130131 /// Imports a theme file. An identifier that is already used gets a new one, so nothing is replaced.132 public func importTheme(from data: Data) throws(GlassThemeError) -> GlassTheme {133 var theme = try GlassThemeCodec.decode(data)134 if self.theme(theme.id) != nil {135 theme.id = uniqueID(base: theme.id.rawValue.hasPrefix("custom-") ? theme.id.rawValue : "custom-\(theme.id.rawValue)")136 }137 guard save(theme) else { throw .invalid(["The theme could not be saved."]) }138 return theme139 }140141 public func uniqueID(base: String) -> GlassThemeID {142 let trimmed = GlassThemeID(String(base.prefix(56))).isValid ? String(base.prefix(56)) : "custom-theme"143 var candidate = GlassThemeID(trimmed)144 var counter = 2145 while theme(candidate) != nil {146 candidate = GlassThemeID("\(trimmed)-\(counter)")147 counter += 1148 }149 return candidate150 }151152 public func acknowledgeRecovery() { recoveryNotice = nil }153154 @discardableResult155 private func persist() -> Bool {156 do {157 try store.save(ThemeLibraryDocument(themes: customThemes))158 lastError = nil159 return true160 } catch {161 lastError = "write"162 return false163 }164 }165}166167/// Undo and redo for the theme editor, bounded in depth.168public struct ThemeEditHistory: Equatable, Sendable {169 public private(set) var current: GlassTheme170 private var undoStack: [GlassTheme] = []171 private var redoStack: [GlassTheme] = []172 public let original: GlassTheme173 public static let limit = 100174175 public init(_ theme: GlassTheme) {176 current = theme177 original = theme178 }179180 public var canUndo: Bool { !undoStack.isEmpty }181 public var canRedo: Bool { !redoStack.isEmpty }182 public var isModified: Bool { current != original }183184 /// Records a change. An edit that changes nothing is ignored.185 public mutating func apply(_ change: (inout GlassTheme) -> Void) {186 var next = current187 change(&next)188 guard next != current else { return }189 undoStack.append(current)190 if undoStack.count > Self.limit { undoStack.removeFirst() }191 redoStack.removeAll()192 current = next193 }194195 public mutating func undo() {196 guard let previous = undoStack.popLast() else { return }197 redoStack.append(current)198 current = previous199 }200201 public mutating func redo() {202 guard let next = redoStack.popLast() else { return }203 undoStack.append(current)204 current = next205 }206207 /// Goes back to the theme as it was when editing started. The reset itself can be undone.208 public mutating func reset() {209 let original = original210 apply { $0 = original }211 }212}213