| 1 | import Foundation |
| 2 | import Combine |
| 3 | import Dispatch |
| 4 | import Darwin |
| 5 | |
| 6 | public enum PetSource: String, CaseIterable, Identifiable { |
| 7 | case wild, demo, live, file |
| 8 | public var id: String { rawValue } |
| 9 | public var label: String { switch self { case .wild: return "Wild"; case .demo: return "Event demo"; case .live: return "Shared"; case .file: return "File study" } } |
| 10 | } |
| 11 | |
| 12 | public func petArchiveLabel(_ name: String) -> String { |
| 13 | let tick = Double(name.split(separator: "-").dropLast().last ?? "") ?? 0 |
| 14 | let seconds = Int(tick / 30) |
| 15 | return String(format: "Through %d:%02d:%02d", seconds / 3600, seconds / 60 % 60, seconds % 60) |
| 16 | } |
| 17 | |
| 18 | /// Thin host: settings, fixed-rate ticks, lifecycle and file delivery. The shared |
| 19 | /// world owns behaviour, accepted telemetry, interactions and score scheduling. |
| 20 | @MainActor public final class PetHost: ObservableObject { |
| 21 | @Published public private(set) var core: PetNativeCore? |
| 22 | @Published public private(set) var message = "" |
| 23 | @Published public private(set) var persistenceMessage = "" |
| 24 | @Published public private(set) var source: PetSource = .wild |
| 25 | @Published public private(set) var archives: [String] = [] |
| 26 | @Published public var still = false { didSet { defaults.set(still, forKey: "pet.still") } } |
| 27 | @Published public var sound = false { didSet { defaults.set(sound, forKey: "pet.sound"); configureSound() } } |
| 28 | public var systemReducedMotion = false |
| 29 | public let shared = PetSharedHost() |
| 30 | private let points: [(Double, Double)] |
| 31 | private let bundle: Bundle |
| 32 | private let defaults: UserDefaults |
| 33 | private let storageDirectory: URL |
| 34 | private var store: PetHabitatStore? |
| 35 | private var archiveStore: PetHabitatStore? |
| 36 | private var migratingLegacy = false |
| 37 | private let audio = PetAudioOutput() |
| 38 | private var timer: Timer? |
| 39 | private var monitor: DispatchSourceFileSystemObject? |
| 40 | private var fileMonitor: DispatchSourceFileSystemObject? |
| 41 | private var count = 0 |
| 42 | private var stateURL: URL? |
| 43 | private var paused = false |
| 44 | private var failed = false |
| 45 | private var restoring = false |
| 46 | |
| 47 | public init(points: [(Double, Double)], bundle: Bundle = .main, defaults: UserDefaults = .standard, storageDirectory: URL? = nil) { |
| 48 | self.points = points; self.bundle = bundle; self.defaults = defaults |
| 49 | self.storageDirectory = storageDirectory ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("CodewhalePet", isDirectory: true) |
| 50 | source = PetSource(rawValue: defaults.string(forKey: "pet.source") ?? "live") ?? .live |
| 51 | still = defaults.bool(forKey: "pet.still"); sound = defaults.bool(forKey: "pet.sound") |
| 52 | restart() |
| 53 | timer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30, repeats: true) { [weak self] _ in |
| 54 | Task { @MainActor in self?.tick() } |
| 55 | } |
| 56 | } |
| 57 | public func suspend(_ value: Bool) { |
| 58 | let wasPaused = paused; paused = value |
| 59 | if source == .live { if value { shared.stop() } else { shared.start() }; return } |
| 60 | if value { |
| 61 | save(); audio.stop(); monitor?.cancel(); fileMonitor?.cancel(); monitor = nil; fileMonitor = nil |
| 62 | } else { |
| 63 | if wasPaused && source == .file { |
| 64 | do { try core?.resumeLiveInput(); if let stateURL { watch(stateURL) }; objectWillChange.send() } |
| 65 | catch { message = error.localizedDescription } |
| 66 | } |
| 67 | configureSound() |
| 68 | } |
| 69 | } |
| 70 | @discardableResult public func selectSource(_ next: PetSource, discardingUnsaved: Bool = false) -> Bool { |
| 71 | guard next != source else { return true } |
| 72 | guard discardingUnsaved || save() else { return false } |
| 73 | source = next; defaults.set(next.rawValue, forKey: "pet.source"); restart() |
| 74 | return true |
| 75 | } |
| 76 | private func restart() { |
| 77 | shared.stop(); core = nil |
| 78 | if source == .live { store = nil; archiveStore = nil; archives = []; return } |
| 79 | audio.stop(); restoring = false; failed = false; monitor?.cancel(); fileMonitor?.cancel(); monitor = nil; fileMonitor = nil |
| 80 | store = nil; archiveStore = nil; archives = []; persistenceMessage = ""; migratingLegacy = false; count = 0 |
| 81 | do { |
| 82 | guard let script = bundle.url(forResource: "pet-native", withExtension: "js") else { throw PetCoreError.invalid("The shared pet core is missing from this app.") } |
| 83 | var tape = "" |
| 84 | if source == .demo { |
| 85 | guard let demo = bundle.url(forResource: "demo", withExtension: "jsonl") else { throw PetCoreError.invalid("The event demo is missing from this app.") } |
| 86 | tape = try String(contentsOf: demo, encoding: .utf8) |
| 87 | } |
| 88 | var saved: Data? |
| 89 | do { |
| 90 | let files = try PetHabitatStore(directory: storageDirectory, source: source == .file ? "live" : source.rawValue) |
| 91 | archiveStore = files; archives = (try? files.archives()) ?? [] |
| 92 | saved = try files.load(); store = files |
| 93 | } catch { persistenceMessage = "Habitat storage is unavailable. Existing files were kept. This visit stays in memory." } |
| 94 | let legacy = source == .wild && saved == nil && store != nil |
| 95 | let hasLegacy = legacy && (defaults.object(forKey: "pet.elapsed") != nil || defaults.object(forKey: "pet.interactions") != nil) |
| 96 | let interactions = legacy ? defaults.string(forKey: "pet.interactions") ?? "[]" : "[]" |
| 97 | let restoredCore: PetNativeCore |
| 98 | if let saved { |
| 99 | do { restoredCore = try PetNativeCore(points: points, bundle: script, live: source == .file, saved: saved) } |
| 100 | catch { |
| 101 | store = nil; persistenceMessage = "The habitat could not be restored. Its saved file was kept. This visit stays in memory." |
| 102 | restoredCore = try PetNativeCore(points: points, bundle: script, tape: tape, live: source == .file) |
| 103 | } |
| 104 | } else { restoredCore = try PetNativeCore(points: points, bundle: script, tape: tape, interactions: interactions, live: source == .file, expressionVersion: hasLegacy ? 1 : 2) } |
| 105 | core = restoredCore |
| 106 | message = source == .wild ? "Simulated creature" : source == .demo ? "Synthetic telemetry" : "Waiting for local telemetry" |
| 107 | if source == .file, let stateURL { watch(stateURL) } |
| 108 | if legacy { |
| 109 | // Only pre-checkpoint preferences need historical simulation. |
| 110 | // The first successful atomic save retires both legacy keys. |
| 111 | migratingLegacy = hasLegacy |
| 112 | let elapsed = defaults.double(forKey: "pet.elapsed") |
| 113 | if elapsed.isFinite && elapsed > 0 && elapsed <= 86_400 { |
| 114 | restoring = true |
| 115 | Task { @MainActor [weak self, weak core] in |
| 116 | guard let self, let core else { return } |
| 117 | do { |
| 118 | for i in 0..<Int(elapsed * 30) { |
| 119 | guard self.core === core else { return } |
| 120 | try core.tick(motion: !(self.still || self.systemReducedMotion)) |
| 121 | if i % 120 == 0 { self.message = "Restoring the habitat…"; self.objectWillChange.send(); await Task.yield() } |
| 122 | } |
| 123 | self.message = "Simulated creature"; self.restoring = false; self.save(); self.configureSound() |
| 124 | } catch { self.restoring = false; self.store = nil; self.message = error.localizedDescription } |
| 125 | } |
| 126 | } else if !elapsed.isFinite || elapsed < 0 || elapsed > 86_400 { |
| 127 | store = nil; persistenceMessage = "The older habitat could not be restored. Its saved preferences were kept. This visit stays in memory." |
| 128 | } |
| 129 | } |
| 130 | if !restoring { configureSound() } |
| 131 | } catch { core = nil; message = error.localizedDescription } |
| 132 | } |
| 133 | public func setLiveFile(_ url: URL) { |
| 134 | let changed = stateURL != url; stateURL = url |
| 135 | if source == .file && !paused { |
| 136 | monitor?.cancel(); fileMonitor?.cancel() |
| 137 | do { if changed { try core?.resumeLiveInput() }; watch(url) } |
| 138 | catch { message = error.localizedDescription } |
| 139 | } |
| 140 | } |
| 141 | public func interact(food: Bool) { |
| 142 | if source == .live { shared.interact(food: food); return } |
| 143 | do { try core?.interact(food: food); save() } catch { message = error.localizedDescription } |
| 144 | } |
| 145 | public func exportRecording(to url: URL) throws { |
| 146 | try recordingForExport().write(to: url, options: .atomic) |
| 147 | } |
| 148 | public func recordingForExport() throws -> Data { |
| 149 | guard !restoring, let core else { throw PetCoreError.invalid("Wait for the habitat to finish opening before exporting.") } |
| 150 | return try core.exportRecording() |
| 151 | } |
| 152 | public func archivedRecording(_ name: String) throws -> Data { |
| 153 | guard let archiveStore else { throw PetCoreError.invalid("Habitat storage is unavailable.") } |
| 154 | return try archiveStore.archivedRecording(name) |
| 155 | } |
| 156 | private func configureSound() { |
| 157 | if source == .live { Task { await shared.setSound(sound) }; return } |
| 158 | do { try audio.setEnabled(sound && !paused && !failed && !restoring, simulationTime: (core?.frame.timeMs ?? 0) / 1000) } |
| 159 | catch { sound = false; message = "Sound unavailable: \(error.localizedDescription)" } |
| 160 | } |
| 161 | private func tick() { |
| 162 | guard !paused, !failed, !restoring, let core else { return } |
| 163 | do { |
| 164 | let f = try core.tick(motion: !(still || systemReducedMotion)) |
| 165 | do { try audio.present(f.voices, core: core) } |
| 166 | catch { sound = false; message = "Sound unavailable: \(error.localizedDescription)" } |
| 167 | count += 1; if count % 150 == 0 { save() } |
| 168 | objectWillChange.send() |
| 169 | } catch { audio.stop(); failed = true; message = error.localizedDescription } |
| 170 | } |
| 171 | @discardableResult public func save() -> Bool { |
| 172 | if source == .live { return true } |
| 173 | guard let core else { return true } |
| 174 | guard let store, !restoring, !failed else { return false } |
| 175 | do { |
| 176 | if let next = try core.prepareSegment() { |
| 177 | let archive = try core.exportRecording(completed: true) |
| 178 | try store.save(next, archive: archive, tick: Int((core.frame.timeMs * 30 / 1000).rounded())) |
| 179 | try core.commitSegment(); archives = (try? store.archives()) ?? archives |
| 180 | } else { try store.save(core.recording(checkpoint: true)) } |
| 181 | if migratingLegacy { |
| 182 | defaults.removeObject(forKey: "pet.interactions"); defaults.removeObject(forKey: "pet.elapsed"); migratingLegacy = false |
| 183 | } |
| 184 | persistenceMessage = "" |
| 185 | return true |
| 186 | } catch { |
| 187 | persistenceMessage = "The habitat could not be saved. Its previous file was kept. This visit stays in memory." |
| 188 | return false |
| 189 | } |
| 190 | } |
| 191 | private func watch(_ url: URL) { |
| 192 | guard source == .file, stateURL == url, !paused else { return } |
| 193 | // Watch the directory so atomic file replacement and initial creation work. |
| 194 | let descriptor = open(url.deletingLastPathComponent().path, O_EVTONLY) |
| 195 | guard descriptor >= 0 else { message = "Create the telemetry directory, then select Live again."; return } |
| 196 | let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: descriptor, eventMask: [.write, .rename, .delete], queue: .main) |
| 197 | source.setEventHandler { [weak self] in Task { @MainActor in self?.watchContents(url) } } |
| 198 | source.setCancelHandler { close(descriptor) }; monitor = source; source.resume(); watchContents(url) |
| 199 | } |
| 200 | private func watchContents(_ url: URL) { |
| 201 | guard source == .file, stateURL == url, !paused else { return } |
| 202 | fileMonitor?.cancel(); fileMonitor = nil |
| 203 | let descriptor = open(url.path, O_EVTONLY) |
| 204 | guard descriptor >= 0 else { _ = try? core?.acceptLiveTail(""); message = "Telemetry unavailable · unobserved"; return } |
| 205 | let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: descriptor, eventMask: [.write, .rename, .delete], queue: .main) |
| 206 | source.setEventHandler { [weak self] in Task { @MainActor in self?.readPacket(url) } } |
| 207 | source.setCancelHandler { close(descriptor) }; fileMonitor = source; source.resume(); readPacket(url) |
| 208 | } |
| 209 | private func readPacket(_ url: URL) { |
| 210 | guard source == .file, stateURL == url, !paused else { return } |
| 211 | do { |
| 212 | let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } |
| 213 | let size = try handle.seekToEnd(); try handle.seek(toOffset: size > 262_144 ? size - 262_144 : 0) |
| 214 | let data = try handle.read(upToCount: 262_144) ?? Data() |
| 215 | try core?.acceptLiveTail(String(decoding: data, as: UTF8.self)) |
| 216 | message = "Following local telemetry" |
| 217 | } catch { _ = try? core?.acceptLiveTail(""); message = "Telemetry unavailable · unobserved" } |
| 218 | // Missing/unchanged input never falls back to a demo. The recorded 400ms |
| 219 | // packet expires in the core and subsequent ticks are visibly unobserved. |
| 220 | } |
| 221 | } |
| 222 |