Branchwell

PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / ProjectMPresets.swift

Raw 23.8 KB on 15681b389943bdb82ce0ee35ea3df6538f046361
1import Foundation
2import Combine
3
4struct ProjectMError: LocalizedError {
5 let message: String
6 init(_ message: String) {self.message = message}
7 var errorDescription: String? {message}
8}
9
10struct ProjectMPreset: Codable, Identifiable {
11 let id: String
12 let path: String
13 let title: String
14 let category: String
15 var originalTitle: String? = nil
16 var icon: String? = nil
17}
18
19/// The shared group scopes browsing and fresh visualizer assignments.
20enum VisualizerRandomizerGroup: Hashable, Codable {
21 case all
22 case favorites
23 case category(String)
24 case custom
25
26 var title: String {
27 switch self {
28 case .all: return String(localized: "Randomize all")
29 case .favorites: return String(localized: "Randomize favorites")
30 case .category(let name):
31 let title = Bundle.main.localizedString(forKey: name, value: name, table: nil)
32 return String(localized: "Randomize \(title)")
33 case .custom: return String(localized: "Randomize pool")
34 }
35 }
36}
37
38struct VisualizerPool: Codable, Equatable, Sendable {
39 var enabled = false
40 var collection = ""
41 var category = ""
42 var favoritesOnly = false
43}
44
45@MainActor
46final class ProjectMPresets: ObservableObject {
47 static let shared: ProjectMPresets = {
48 #if DEBUG && os(iOS)
49 if ProcessInfo.processInfo.arguments.contains("-PCMobileQA") {
50 let suite = "PulseCanvas.MobileVisualizers.QA"
51 let defaults = UserDefaults(suiteName: suite)!
52 defaults.removePersistentDomain(forName: suite)
53 return ProjectMPresets(defaults: defaults)
54 }
55 #endif
56 return ProjectMPresets()
57 }()
58 @Published private(set) var pool = VisualizerPool()
59 @Published private(set) var poolRevision = 0
60 @Published private(set) var entries: [ProjectMPreset] = []
61 private(set) var sceneNames: [String] = []
62 @Published private(set) var favoriteIDs: Set<String> = []
63 private var favoriteAppearances: [String: VisualPreset] = [:]
64 @Published private(set) var favoritesBackupError: String?
65 let favoritesBackupDirectory: URL?
66 #if os(visionOS)
67 private let backupEdition = "Vision-Pro"
68 #elseif os(iOS)
69 private let backupEdition = "iPhone-iPad"
70 #elseif STORE_BUILD
71 private let backupEdition = "Mac-App-Store"
72 #elseif LOCAL_BUILD
73 private let backupEdition = "Creators-Local"
74 #else
75 private let backupEdition = "Creators"
76 #endif
77 #if STORE_BUILD
78 private let poolKey = "PulseCanvas.metalVisualizerPool.v1"
79 #else
80 private let poolKey = "PulseCanvas.visualizerPool.v1"
81 #endif
82 private let defaults: UserDefaults
83 #if STORE_BUILD
84 private let favoritesKey = "PulseCanvas.metalEffectFavorites.v1"
85 #else
86 private let favoritesKey = "PulseCanvas.effectFavorites.v1"
87 #endif
88 let bundledRoot: URL
89 let importedRoot: URL
90 private var imported: [ProjectMPreset] = []
91 private var importedIDs = Set<String>()
92 private var nativeCount: Int { RenderState.nativeSceneNames.count }
93 // Projects without stable identities predate expansion of the native catalog.
94 // Their external preset indices always start at 31, regardless of today's count.
95 private let legacyNativeCount = NativeEffects.legacyCount
96 private var scenesByID: [String: Int] = [:]
97 private var legacyIDs: [String] = []
98 private(set) var retiredIDs: Set<String> = []
99 let iconNames: [String]
100 private static let nativeIcons = NativeEffects.all.map(\.icon)
101
102 init(importedRoot: URL? = nil, defaults: UserDefaults = .standard, favoritesBackupDirectory: URL? = nil) {
103 self.defaults = defaults
104 if let data = defaults.data(forKey: poolKey), data.count < 4096,
105 let saved = try? JSONDecoder().decode(VisualizerPool.self, from: data),
106 saved.collection.count < 100, saved.category.count < 200 { pool = saved }
107 let isolatedQA = Bundle.main.object(forInfoDictionaryKey: "PulseCanvasIsolatedTesting") as? Bool == true
108 self.favoritesBackupDirectory = favoritesBackupDirectory ?? (defaults === UserDefaults.standard && !isolatedQA
109 ? UserDataStorage.support.appendingPathComponent("Favorites Backups", isDirectory: true) : nil)
110 #if STORE_BUILD
111 bundledRoot = Bundle.module.resourceURL ?? URL(fileURLWithPath: "/missing-resources")
112 self.importedRoot = importedRoot ?? bundledRoot
113 iconNames = Self.nativeIcons
114 #else
115 bundledRoot = [Bundle.module.resourceURL?.appendingPathComponent("Resources/ProjectM"), Bundle.module.resourceURL?.appendingPathComponent("ProjectM"), URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("Sources/PulseCanvas/Resources/ProjectM")].compactMap({$0}).first(where: {FileManager.default.fileExists(atPath: $0.appendingPathComponent("catalog.json").path)}) ?? URL(fileURLWithPath: "/missing-projectm")
116 iconNames = (try? PresetNaming(root: bundledRoot).icons).flatMap { $0.isEmpty ? nil : $0 } ?? ["sparkles"]
117 self.importedRoot = importedRoot ?? UserDataStorage.support.appendingPathComponent("ProjectM", isDirectory: true)
118 entries = (try? JSONDecoder().decode([ProjectMPreset].self, from: Data(contentsOf: bundledRoot.appendingPathComponent("catalog.json")))) ?? []
119 imported = (try? JSONDecoder().decode([ProjectMPreset].self, from: Data(contentsOf: self.importedRoot.appendingPathComponent("imports.json")))) ?? []
120 importedIDs = Set(imported.map(\.id))
121 legacyIDs = (try? JSONDecoder().decode([String].self, from: Data(contentsOf: bundledRoot.appendingPathComponent("legacy-identities.json")))) ?? entries.map(\.id)
122 let retired = (try? JSONDecoder().decode([RetiredPreset].self, from: Data(contentsOf: bundledRoot.appendingPathComponent("retired-presets.json")))) ?? []
123 retiredIDs = Set(retired.map(\.id))
124 entries += imported
125 #endif
126 var savedFavorites = defaults.stringArray(forKey: favoritesKey)
127 #if STORE_BUILD
128 savedFavorites = savedFavorites ?? defaults.stringArray(forKey: "PulseCanvas.effectFavorites.v1")
129 #endif
130 #if LOCAL_BUILD
131 // Seed a fresh isolated test build once, without altering the installed app.
132 if savedFavorites == nil, defaults === UserDefaults.standard, !isolatedQA {
133 savedFavorites = ["com.protomota.pulsecanvas", "com.protomota.pulsecanvas.direct"].flatMap {
134 UserDefaults.standard.persistentDomain(forName: $0)?["PulseCanvas.effectFavorites.v1"] as? [String] ?? []
135 }
136 defaults.set(savedFavorites, forKey: favoritesKey)
137 }
138 #endif
139 if let data = defaults.data(forKey: favoritesKey + ".appearances"),
140 let saved = try? JSONDecoder().decode([String: VisualPreset].self, from: data) {
141 favoriteAppearances = saved.filter { $0.value.isValid }
142 }
143 // An explicitly empty list stays empty; a missing preference can recover
144 // from this edition's last successful automatic backup.
145 if savedFavorites == nil, let directory = self.favoritesBackupDirectory,
146 let data = try? Data(contentsOf: directory.appendingPathComponent("Favorites-\(backupEdition).json")),
147 let backup = try? FavoritesBackup.read(data) {
148 savedFavorites = backup.favorites.map(\.id)
149 for favorite in backup.favorites { if let look = favorite.appearance { favoriteAppearances[favorite.id] = look } }
150 defaults.set(savedFavorites, forKey: favoritesKey)
151 }
152 let savedIDs = Set(savedFavorites ?? [])
153 rebuildNames()
154 favoriteIDs = savedIDs.intersection(availableFavoriteIDs)
155 favoriteAppearances = favoriteAppearances.filter { favoriteIDs.contains($0.key) }
156 if favoriteIDs != savedIDs { persistFavorites() }
157 else if !favoriteIDs.isEmpty { backUpFavorites() }
158 }
159 private func rebuildNames() {
160 sceneNames = RenderState.nativeSceneNames + entries.map(\.title)
161 scenesByID = Dictionary(uniqueKeysWithValues: entries.enumerated().map { ($0.element.id, $0.offset + nativeCount) })
162 availableScenes = NativeEffects.libraryOrder + Array(nativeCount..<sceneNames.count)
163 categories = categories(in: "")
164 }
165 private var availableFavoriteIDs: Set<String> { Set(availableScenes.map { identity(for: $0) }) }
166 func identity(for scene: Int) -> String {preset(for: scene)?.id ?? "native:\(scene)"}
167 func isFavorite(_ scene: Int) -> Bool {favoriteIDs.contains(identity(for: scene))}
168 /// Every scene offered in the library, timeline and random choices. Retired native
169 /// designs keep their IDs for migration but are never offered.
170 private(set) var availableScenes: [Int] = []
171 func icon(for scene: Int) -> String {
172 if Self.nativeIcons.indices.contains(scene) { return Self.nativeIcons[scene] }
173 return preset(for:scene)?.icon ?? iconNames[max(0,scene) % iconNames.count]
174 }
175 func toggleFavorite(_ scene: Int, appearance: VisualPreset? = nil) {
176 guard availableScenes.contains(scene) else { return }
177 let id = identity(for: scene)
178 if favoriteIDs.contains(id) {
179 favoriteIDs.remove(id); favoriteAppearances.removeValue(forKey: id)
180 } else {
181 favoriteIDs.insert(id)
182 favoriteAppearances[id] = appearance.flatMap { $0.isValid ? $0 : nil } ?? VisualPreset.defaults(for: scene)
183 }
184 persistFavorites()
185 }
186
187 /// Gestures only add favorites. Repeating one preserves the originally saved look.
188 @discardableResult
189 func favorite(_ scene: Int, appearance: VisualPreset? = nil) -> Bool {
190 guard availableScenes.contains(scene) else { return false }
191 if !isFavorite(scene) { toggleFavorite(scene, appearance: appearance) }
192 return true
193 }
194
195 /// Upgrade ID-only favorites once from the editor's existing saved looks.
196 /// Subsequent slider edits never rewrite an already saved favorite.
197 func migrateFavoriteAppearances(_ appearance: (Int) -> VisualPreset) {
198 var changed = false
199 for scene in availableScenes where isFavorite(scene) && favoriteAppearances[identity(for: scene)] == nil {
200 let value = appearance(scene)
201 if value.isValid { favoriteAppearances[identity(for: scene)] = value; changed = true }
202 }
203 if changed { persistFavorites() }
204 }
205
206 func favoriteAppearance(for scene: Int) -> VisualPreset? {
207 guard isFavorite(scene) else { return nil }
208 if let saved = favoriteAppearances[identity(for: scene)] { return saved }
209 // Legacy favorites without a saved look migrate once, never on each selection.
210 let saved = VisualPreset.defaults(for: scene)
211 favoriteAppearances[identity(for: scene)] = saved
212 persistFavorites()
213 return saved
214 }
215
216 func appearanceForSelection(_ scene: Int) -> VisualPreset {
217 favoriteAppearance(for: scene) ?? .randomized()
218 }
219
220 func exportFavorites() throws -> Data {
221 try FavoritesBackup(ids: favoriteIDs, appearances: favoriteAppearances) { id in
222 if id.hasPrefix("native:"), let scene = Int(id.dropFirst(7)), sceneNames.indices.contains(scene) { return sceneNames[scene] }
223 return scenesByID[id].map { sceneNames[$0] }
224 }.encoded()
225 }
226
227 /// Merge installed favorites. Removed designs must not reappear from a backup
228 /// or silently favorite a replacement the listener never selected.
229 @discardableResult
230 func importFavorites(_ data: Data) throws -> (added: Int, unavailable: Int) {
231 let backup = try FavoritesBackup.read(data)
232 let restored = Set(backup.favorites.map(\.id))
233 let available = availableFavoriteIDs
234 let installed = restored.intersection(available)
235 let added = installed.subtracting(favoriteIDs).count
236 for favorite in backup.favorites where installed.contains(favorite.id) {
237 if let look = favorite.appearance { favoriteAppearances[favorite.id] = look }
238 }
239 favoriteIDs.formUnion(installed)
240 persistFavorites()
241 return (added, restored.subtracting(available).count)
242 }
243
244 private func persistFavorites() {
245 if pool.enabled && pool.favoritesOnly { poolRevision &+= 1 }
246 favoriteAppearances = favoriteAppearances.filter { favoriteIDs.contains($0.key) }
247 defaults.set(favoriteIDs.sorted(), forKey: favoritesKey)
248 if let data = try? JSONEncoder().encode(favoriteAppearances) { defaults.set(data, forKey: favoritesKey + ".appearances") }
249 backUpFavorites()
250 NotificationCenter.default.post(name: .pulseCanvasUserDataChanged, object: nil)
251 }
252
253 func applyCloudFavorites(_ favorites: [FavoritesBackup.Favorite], removed: Set<String>) {
254 let available = availableFavoriteIDs
255 favoriteIDs.subtract(removed.intersection(available))
256 for favorite in favorites where available.contains(favorite.id) {
257 favoriteIDs.insert(favorite.id)
258 if let look = favorite.appearance, look.isValid { favoriteAppearances[favorite.id] = look }
259 }
260 persistFavorites()
261 }
262
263 private func backUpFavorites() {
264 guard let directory = favoritesBackupDirectory else { return }
265 do {
266 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
267 let data = try exportFavorites()
268 let day = String(ISO8601DateFormatter().string(from: Date()).prefix(10))
269 try data.write(to: directory.appendingPathComponent("Favorites-\(backupEdition)-\(day).json"), options: .atomic)
270 try data.write(to: directory.appendingPathComponent("Favorites-\(backupEdition).json"), options: .atomic)
271 favoritesBackupError = nil
272 } catch { favoritesBackupError = "Automatic favorites backup failed: \(error.localizedDescription)" }
273 }
274 func category(for scene: Int) -> String {
275 guard let preset = preset(for: scene) else {return NativeEffects.category(for: scene)}
276 return preset.category.hasPrefix("Imported") ? "Imported" : String(preset.category.split(separator: "/").first ?? "ProjectM")
277 }
278 func collection(for scene: Int) -> String {
279 guard let preset = preset(for: scene) else { return "Native Metal" }
280 return importedIDs.contains(preset.id) ? "Imported" : "Cream of the Crop"
281 }
282 var collections: [String] {
283 ["Native Metal", "Cream of the Crop", "Imported"].filter { collection in
284 availableScenes.contains { self.collection(for: $0) == collection }
285 }
286 }
287 private(set) var categories: [String] = []
288 func categories(in collection: String) -> [String] {
289 Set(availableScenes.filter { collection.isEmpty || self.collection(for: $0) == collection }
290 .map { category(for: $0) }).sorted()
291 }
292 func folders(in category: String, collection: String = "") -> [String] {
293 guard !category.isEmpty else { return [] }
294 return Set(availableScenes.filter {
295 self.category(for: $0) == category && (collection.isEmpty || self.collection(for: $0) == collection)
296 }.compactMap { preset(for: $0)?.category }.filter { $0.contains("/") }).sorted()
297 }
298 /// The installed catalog remains intact for identities, migration and favorite backups.
299 /// This separate pool limits only discovery and new assignments.
300 var eligibleScenes: [Int] { scenes(in: pool) }
301 var favoritesFallbackMessage: String? {
302 guard pool.enabled, pool.favoritesOnly else { return nil }
303 let choices = scenes(in: pool)
304 guard !choices.isEmpty, !choices.contains(where: { isFavorite($0) }) else { return nil }
305 return pool.collection.isEmpty && pool.category.isEmpty
306 ? "No saved favorite visualizers yet. Playing random visualizers from the full library."
307 : String(localized: "No favorite visualizers in this group. Playing random visualizers from the group.")
308 }
309 func scenes(in pool: VisualizerPool) -> [Int] {
310 guard pool.enabled else { return availableScenes }
311 let group = availableScenes.filter {
312 (pool.collection.isEmpty || collection(for: $0) == pool.collection)
313 && (pool.category.isEmpty || category(for: $0) == pool.category)
314 }
315 guard pool.favoritesOnly else { return group }
316 let favorites = group.filter { isFavorite($0) }
317 // A discovery preference must not disable playback or Studio when no
318 // favorites exist. Keep category/collection limits and the saved choice.
319 return favorites.isEmpty ? group : favorites
320 }
321 var randomizerGroup: VisualizerRandomizerGroup {
322 guard pool.enabled else { return .all }
323 if pool.collection.isEmpty {
324 if pool.category.isEmpty { return pool.favoritesOnly ? .favorites : .all }
325 if !pool.favoritesOnly { return .category(pool.category) }
326 }
327 return .custom
328 }
329 func setRandomizerGroup(_ group: VisualizerRandomizerGroup) {
330 switch group {
331 case .all: setPool(VisualizerPool())
332 case .favorites: setPool(VisualizerPool(enabled: true, favoritesOnly: true))
333 case .category(let name): setPool(VisualizerPool(enabled: true, category: name))
334 case .custom: break
335 }
336 }
337 func setPool(_ value: VisualizerPool) {
338 guard value != pool, value.collection.count < 100, value.category.count < 200 else { return }
339 pool = value
340 poolRevision &+= 1
341 if let data = try? JSONEncoder().encode(value) { defaults.set(data, forKey: poolKey) }
342 }
343 var poolSummary: String {
344 guard pool.enabled else { return String(localized: "All visualizers") }
345 let labels = [pool.collection, pool.category, pool.favoritesOnly ? String(localized: "Favorites") : ""].filter { !$0.isEmpty }
346 return labels.isEmpty ? String(localized: "All visualizers") : labels.map { Bundle.main.localizedString(forKey: $0, value: $0, table: nil) }.joined(separator: " · ")
347 }
348 func filteredScenes(query: String = "", collection: String = "", category: String = "",
349 folder: String = "", favoritesOnly: Bool = false) -> [Int] {
350 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
351 return eligibleScenes.filter { scene in
352 (!favoritesOnly || isFavorite(scene))
353 && (collection.isEmpty || self.collection(for: scene) == collection)
354 && (category.isEmpty || self.category(for: scene) == category)
355 && (folder.isEmpty || preset(for: scene)?.category == folder)
356 && (text.isEmpty || sceneNames[scene].localizedCaseInsensitiveContains(text)
357 || (preset(for: scene)?.originalTitle?.localizedCaseInsensitiveContains(text) ?? false)
358 || (preset(for: scene)?.category.localizedCaseInsensitiveContains(text) ?? false)
359 || self.category(for: scene).localizedCaseInsensitiveContains(text))
360 }
361 }
362 func preset(for scene: Int) -> ProjectMPreset? {
363 let index = scene - nativeCount
364 return entries.indices.contains(index) ? entries[index] : nil
365 }
366 func url(for preset: ProjectMPreset) -> URL {
367 (importedIDs.contains(preset.id) ? importedRoot : bundledRoot.appendingPathComponent("Presets")).appendingPathComponent(preset.path)
368 }
369 func texturePaths(for preset: ProjectMPreset) -> [URL] {
370 [url(for: preset).deletingLastPathComponent(), importedRoot, bundledRoot.appendingPathComponent("Textures")]
371 }
372 func scene(for id: String) -> Int? { scenesByID[id] }
373 /// Resolve old numeric scenes by their stable identities before applying settings.
374 /// Retired effects and retired native designs open a replacement design; unavailable
375 /// user imports still report an error.
376 func migratedScene(_ scene: Int, identities: [Int: String]?) throws -> Int {
377 guard scene >= 0 else { throw ProjectMError("Invalid visualizer index: \(scene).") }
378 if let id = identities?[scene], id.hasPrefix("native:") {
379 guard let index = Int(id.dropFirst(7)), RenderState.nativeSceneNames.indices.contains(index) else {
380 throw ProjectMError("This project requires a native visualizer unavailable in this version: \(id).")
381 }
382 return NativeEffects.resolved(index)
383 }
384 if identities?[scene] == nil && scene < legacyNativeCount { return NativeEffects.resolved(scene) }
385 #if STORE_BUILD
386 throw ProjectMError("This project uses effects available only in the direct-download edition. Open it there to preserve its visualizers.")
387 #else
388 let index = scene - legacyNativeCount
389 let legacy = legacyIDs.indices.contains(index) ? legacyIDs[index] : imported.indices.contains(index - legacyIDs.count) ? imported[index - legacyIDs.count].id : nil
390 guard let id = identities == nil ? legacy : identities?[scene] else { throw ProjectMError("Missing identity for preset \(scene)") }
391 if let current = scenesByID[id] { return current }
392 if retiredIDs.contains(id) { return 22 }
393 throw ProjectMError("This project requires a custom visualizer that is not installed: \(id).")
394 #endif
395 }
396 func isRetiredScene(_ scene: Int, identities: [Int: String]?) -> Bool {
397 if let id = identities?[scene], id.hasPrefix("native:") { return Int(id.dropFirst(7)).map(NativeEffects.isRetired) ?? false }
398 if identities?[scene] == nil && scene < legacyNativeCount { return NativeEffects.isRetired(scene) }
399 let index = scene - legacyNativeCount
400 let id = identities == nil && legacyIDs.indices.contains(index) ? legacyIDs[index] : identities?[scene]
401 return id.map { retiredIDs.contains($0) } ?? false
402 }
403 func identities(for scenes: Set<Int>) -> [Int: String] {
404 Dictionary(uniqueKeysWithValues: scenes.filter { sceneNames.indices.contains($0) }.map { ($0, identity(for: $0)) })
405 }
406}
407
408private struct RetiredPreset: Decodable { let id: String }
409
410private struct PresetNaming: Decodable {
411 let icons: [String]
412 init(root: URL) throws {self = try JSONDecoder().decode(Self.self,from:Data(contentsOf:root.appendingPathComponent("naming.json")))}
413}
414
415
416/// Portable stable identities survive renamed effects and catalog reordering.
417struct FavoritesBackup: Codable {
418 struct Favorite: Codable {
419 let id: String
420 let name: String?
421 var appearance: VisualPreset? = nil
422 }
423 let format: String
424 let version: Int
425 let savedAt: Date
426 let favorites: [Favorite]
427
428 init(ids: Set<String>, appearances: [String: VisualPreset] = [:], name: (String) -> String?) {
429 format = "PulseCanvas Favorites"
430 version = 2
431 savedAt = Date()
432 favorites = ids.sorted().map { Favorite(id: $0, name: name($0), appearance: appearances[$0]) }
433 }
434
435 func encoded() throws -> Data {
436 let encoder = JSONEncoder()
437 encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
438 encoder.dateEncodingStrategy = .iso8601
439 return try encoder.encode(self)
440 }
441
442 static func read(_ data: Data) throws -> Self {
443 guard data.count <= 10_000_000 else { throw invalid(String(localized: "The favorites backup is too large.")) }
444 let decoder = JSONDecoder()
445 decoder.dateDecodingStrategy = .iso8601
446 let backup = try decoder.decode(Self.self, from: data)
447 guard backup.format == "PulseCanvas Favorites", (1...2).contains(backup.version) else {
448 throw invalid(String(localized: "Choose a supported PulseCanvas favorites backup."))
449 }
450 guard backup.favorites.count <= 100_000, backup.favorites.allSatisfy({
451 ($0.appearance?.isValid ?? true) && !$0.id.isEmpty && $0.id.utf8.count <= 4096 && !$0.id.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) })
452 }) else { throw invalid(String(localized: "The backup contains invalid favorite identities.")) }
453 return backup
454 }
455
456 private static func invalid(_ message: String) -> NSError {
457 NSError(domain: "PulseCanvas.FavoritesBackup", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
458 }
459}