AppModel.swift (19201B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 // Ties the housing to the camera: the buttons that the vacuum sequence leaves free 3 // drive shooting, the menu and screen sleep. 4 import Network 5 import Observation 6 import RemoraDeco 7 import SwiftUI 8 import UIKit 9 10 @MainActor 11 @Observable 12 final class AppModel { 13 let housing = HousingClient() 14 /// The optional dive computer, and the basic dive information shown even when it is off. 15 let dive: DiveSession 16 @ObservationIgnored let engine = CameraEngine() 17 /// Leak alarm and dive computer sounds: heard even with the ring/silent switch on silent. 18 @ObservationIgnored let alerts = AlertPlayer() 19 private(set) var camera = CameraState() 20 private(set) var settings = CameraSettings.load() 21 private(set) var menu = CameraMenu() 22 private(set) var sleeping = false 23 /// Transient message (errors, calibration); goes away by itself. 24 private(set) var toast: String? 25 /// Incremented at each shot: the screen blinks like a shutter. 26 private(set) var shutterFlash = 0 27 @ObservationIgnored private var toastTask: Task<Void, Never>? 28 /// Information panel opened from the menu; any button closes it. 29 private(set) var showingInfo = false 30 /// Previews of the shots of the session (the originals go to Photos right away). 31 private(set) var roll: [URL] = [] 32 /// Gallery opened by the left button. 33 struct Gallery: Equatable { var index: Int } 34 private(set) var gallery: Gallery? 35 private(set) var galleryImage: UIImage? 36 @ObservationIgnored private var galleryTask: Task<Void, Never>? 37 @ObservationIgnored private var exporting = false 38 /// A shot arrived during a transfer: start another one when it ends. 39 @ObservationIgnored private var exportAgain = false 40 /// Leak alarm: the sound stops at the first button press, the red screen stays. 41 private(set) var alarmSilenced = false 42 /// The iPhone has network access (airplane mode is recommended before closing the housing). 43 private(set) var online = false 44 private(set) var freeBytes: Int64? 45 private(set) var hot = false 46 /// Depth (m) and dive start: experimental, until 1625 has been validated in the water. 47 var depth: Double? { dive.depth } 48 var diveStart: Date? { dive.diveStart } 49 /// Full-screen dive computer page (long press up, or Menu → Dive computer). 50 private(set) var showingComputer = false 51 /// Dive alarm: the sound stops at the first button press, the red flash stays. 52 private(set) var diveAlarmSilenced = false 53 @ObservationIgnored private let pathMonitor = NWPathMonitor() 54 @ObservationIgnored private var ticks = 0 55 /// iPhone battery, in % (nil when unknown). 56 private(set) var phoneBattery: Int? 57 @ObservationIgnored private var lastActivity = Date() 58 @ObservationIgnored private var awakeBrightness: CGFloat = 0.5 59 @ObservationIgnored private var sleepTask: Task<Void, Never>? 60 61 init(dive: DiveSession = DiveSession()) { 62 self.dive = dive 63 } 64 65 func start() { 66 UIDevice.current.isBatteryMonitoringEnabled = true 67 UIApplication.shared.isIdleTimerDisabled = true // the screen never locks by itself 68 applyOrientation() 69 DevLog.shared.set(enabled: settings.developer) 70 engine.onState = { [weak self] state in 71 guard let self else { return } 72 if state.messageCount != camera.messageCount, let message = state.message { 73 DevLog.shared.event(String(localized: "camera: \(message)")) 74 show(message) 75 } 76 if state.shots != camera.shots { 77 DevLog.shared.event(String(localized: "shot written to disk")) 78 exportRoll() 79 } 80 if state.zoomIndex != camera.zoomIndex, state.capabilities.zoomLabels.indices.contains(state.zoomIndex) { 81 DevLog.shared.event(String(localized: "lens \(state.capabilities.zoomLabels[state.zoomIndex])")) 82 } 83 if (state.recordingSince == nil) != (camera.recordingSince == nil) { 84 DevLog.shared.event(state.recordingSince == nil ? String(localized: "video: stop") : String(localized: "video: start")) 85 } 86 if let calibration = state.calibration, calibration != camera.calibration { 87 settings.colorMode = .calibrated 88 settings.calibration = calibration 89 settings.save() 90 DevLog.shared.event(String(localized: "calibration \(calibration.label)")) 91 } 92 if state.gainsSaturated != camera.gainsSaturated { 93 let grayWorld = state.grayWorld?.label ?? "?", ceiling = state.maxGain.map { String(format: "%.2f", $0) } ?? "?" 94 DevLog.shared.event((state.gainsSaturated ? String(localized: "colors: red at maximum") : String(localized: "colors: within limits")) 95 + " " + String(localized: "gray world \(grayWorld) ceiling \(ceiling)")) 96 } 97 camera = state 98 } 99 alerts.prepare() // the audio session is set before the camera starts 100 Roll.clearPreviews() // the gallery only shows the current session 101 engine.start(settings) 102 exportRoll() // shots left on disk after a crash 103 housing.cameraButton = { [weak self] event in self?.button(event) } 104 housing.anyButton = { [weak self] in 105 self?.alarmSilenced = true 106 self?.diveAlarmSilenced = true 107 } 108 housing.externalPressure = { [weak self] pa, time in 109 guard let self else { return } 110 dive.pressure(pa: pa, time: time, simulated: housing.simulated) 111 } 112 housing.linkLost = { [weak self] in self?.dive.linkLost() } 113 housing.sessionStarted = { [weak self] in 114 self?.dive.reset() 115 self?.showingComputer = false 116 } 117 dive.onCue = { [weak self] cue in self?.diveCue(cue) } 118 dive.onDiveEnded = { [weak self] saved, simulation in 119 guard let self else { return } 120 if simulation { 121 show(String(localized: "Simulated dive over: nothing is saved")) 122 } else if let saved { 123 DevLog.shared.event(String(localized: "dive no. \(String(saved.number)) saved")) 124 show(String(localized: "Dive no. \(String(saved.number)) saved")) 125 } 126 } 127 pathMonitor.pathUpdateHandler = { path in 128 let online = path.status == .satisfied 129 Task { @MainActor [weak self] in self?.online = online } 130 } 131 pathMonitor.start(queue: .global(qos: .utility)) 132 applyBrightness() 133 // Launched with "-simulation": simulated housing from the start (screenshots, demos). 134 if ProcessInfo.processInfo.arguments.contains("-simulation") { housing.startSimulation() } 135 launchArgumentsForScreenshots() 136 // "-demoMenu": opens the settings on their last row (screenshots). 137 if ProcessInfo.processInfo.arguments.contains("-demoMenu") { 138 housing.bypassVacuum() 139 menu.open() 140 for press in [HousingButton.down, .down, .down, .right, .up] { _ = menu.handle(press, settings: &settings, caps: camera.capabilities) } 141 } 142 sleepTask = Task { [weak self] in 143 while !Task.isCancelled { 144 try? await Task.sleep(for: .seconds(1)) 145 self?.everySecond() 146 } 147 } 148 } 149 150 /// Screenshots of the dive computer: "-simulateDive reef|deep|shallow" plays a dive on the simulated 151 /// housing ("-diveSkip <seconds>" jumps into it), "-testAlarm" forces the alarm, "-computerPage" opens 152 /// the full-screen page, "-demoLogbook" shows a past dive on the home screen. ("-diveComputer YES" and 153 /// "-acceptTerms" turn the computer on for the launch.) 154 private func launchArgumentsForScreenshots() { 155 let arguments = ProcessInfo.processInfo.arguments 156 if arguments.contains("-demoLogbook") { dive.store.seedDemo() } 157 if arguments.contains("-testAlarm") { dive.monitor.forcedAlarm = true } 158 if let name = UserDefaults.standard.string(forKey: "simulateDive") { 159 housing.startSimulation() 160 let profile: DemoProfile = name == "deep" ? .deep : name == "shallow" ? .shallow : .reef 161 startSimulatedDive(profile, skip: UserDefaults.standard.double(forKey: "diveSkip")) 162 } 163 if arguments.contains("-computerPage") { showingComputer = true } 164 // "-demoVacuum": simulated housing brought back to the first card of the vacuum sequence. 165 if arguments.contains("-demoVacuum") { 166 housing.startSimulation() 167 housing.simulatedPress(.right, long: true) 168 } 169 } 170 171 /// Simulated housing: plays `profile` on its pressure sensor (a minute at the surface ends the dive). 172 func startSimulatedDive(_ profile: DemoProfile = .reef, skip: Double = 0) { 173 housing.startSimulatedDive(depths: profile.depths + Array(repeating: 0, count: 75), skip: skip) 174 } 175 176 /// Feedback asked by the dive logic. Haptics are useless in a housing: sounds, and the screen wakes up. 177 /// Which sound is decided by `AlertPolicy` (the leak alarm keeps priority: no dive sound over it). 178 private func diveCue(_ cue: DiveCue) { 179 if cue != .diveSaved { 180 if sleeping { wake() } 181 lastActivity = Date() 182 } 183 if let sound = AlertPolicy.sound(for: cue, leaking: isLeaking, alarmSilenced: diveAlarmSilenced) { 184 alerts.play(sound) 185 } 186 } 187 188 /// Minutes of video that the free space allows, at the chosen quality (approximate HEVC bitrates). 189 var videoMinutesLeft: Int? { 190 guard let freeBytes else { return nil } 191 let q = settings.videoQuality 192 let perMinute: Double = switch (q.height, q.fps) { 193 case (2160, 120): 800e6 194 case (2160, 60): 400e6 195 case (2160, _): 170e6 196 case (1080, 60): 90e6 197 case (1080, _): 60e6 198 default: 40e6 199 } 200 return Int(Double(max(0, freeBytes - 1_000_000_000)) / perMinute) // 1 GB kept in reserve 201 } 202 203 private var isLeaking: Bool { 204 if case .failed(.leak) = housing.vacuum.step { return true } 205 return false 206 } 207 208 private func applyBrightness() { 209 if settings.brightness > 0, !sleeping { UIScreen.main.brightness = CGFloat(settings.brightness) / 100 } 210 } 211 212 private func everySecond() { 213 ticks += 1 214 // Leak alarm: screen at full brightness, sound repeated until the first button press. 215 if isLeaking { 216 if sleeping { wake() } 217 UIScreen.main.brightness = 1 218 if let sound = AlertPolicy.leakSound(leaking: true, silenced: alarmSilenced) { alerts.play(sound) } 219 } else { 220 alarmSilenced = false 221 } 222 if !dive.monitor.isAlarming { diveAlarmSilenced = false } 223 // The log is always on during a sealed dive, even outside development mode. 224 let sealed: Bool = switch housing.vacuum.step { 225 case .testing, .sealed, .failed: true 226 default: false 227 } 228 DevLog.shared.set(enabled: settings.developer || sealed) 229 230 if ticks % 10 == 1 { 231 let home = URL(fileURLWithPath: NSHomeDirectory()) 232 freeBytes = (try? home.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]))?.volumeAvailableCapacityForImportantUsage 233 } 234 // Heat: warn, and lighten the video before iOS shuts the camera down. 235 let thermal = ProcessInfo.processInfo.thermalState 236 let nowHot = thermal == .serious || thermal == .critical 237 if nowHot != hot { 238 hot = nowHot 239 DevLog.shared.event(String(localized: "iPhone thermal state \(String(thermal.rawValue))")) 240 if nowHot { show(String(localized: "iPhone is hot")) } 241 } 242 let light = VideoQuality(height: 1080, fps: 30) 243 if nowHot, camera.recordingSince == nil, settings.mode == .video, 244 settings.videoQuality.height * settings.videoQuality.fps > light.height * light.fps, 245 camera.capabilities.qualities.contains(light) { 246 settings.videoQuality = light 247 settings.save() 248 engine.apply(settings) 249 show(String(localized: "iPhone is hot: video reduced to \(light.label)")) 250 } 251 // The depth is followed sample by sample in `DiveSession` (see `housing.externalPressure`). 252 if ticks % 10 == 2 { dive.store.refreshOutbox() } 253 checkSleep() 254 } 255 256 private func checkSleep() { 257 258 let level = UIDevice.current.batteryLevel 259 let percent: Int? = level < 0 ? nil : Int((level * 100).rounded()) 260 if percent != phoneBattery { phoneBattery = percent } 261 262 guard !sleeping, settings.sleepAfter > 0, camera.recordingSince == nil, housing.vacuum.cameraHasButtons, 263 !(dive.isComputing && dive.monitor.isAlarming), 264 Date().timeIntervalSince(lastActivity) > Double(settings.sleepAfter) else { return } 265 sleep() 266 } 267 268 private func sleep() { 269 awakeBrightness = UIScreen.main.brightness 270 UIScreen.main.brightness = 0 271 sleeping = true 272 } 273 274 private func show(_ message: String) { 275 toast = message 276 toastTask?.cancel() 277 toastTask = Task { [weak self] in 278 try? await Task.sleep(for: .seconds(3)) 279 if !Task.isCancelled { self?.toast = nil } 280 } 281 } 282 283 func wake() { 284 lastActivity = Date() 285 guard sleeping else { return } 286 UIScreen.main.brightness = awakeBrightness 287 sleeping = false 288 applyBrightness() 289 } 290 291 func button(_ event: ButtonEvent) { 292 if sleeping { wake(); return } // the first press only wakes the screen 293 lastActivity = Date() 294 if showingInfo { showingInfo = false; return } 295 if gallery != nil { galleryButton(event); return } 296 if showingComputer { 297 // Computer page: left or a long press up closes it; the shutter still shoots; nothing else. 298 if (event.button == .left && !event.isLong) || (event.button == .up && event.isLong) { 299 showingComputer = false 300 return 301 } 302 guard event.button == .shutter else { return } 303 } 304 if menu.isOpen { 305 guard !event.isLong else { return } 306 let before = settings 307 switch menu.handle(event.button, settings: &settings, caps: camera.capabilities) { 308 case .setMode(let mode): 309 settings.mode = mode 310 case .sleepNow: sleep() 311 case .showInfo: showingInfo = true 312 case .showComputer: showingComputer = true 313 case .none, .close, .changed: break 314 } 315 if settings != before { 316 if settings.orientation != before.orientation { applyOrientation() } 317 if settings.brightness != before.brightness { applyBrightness() } 318 DevLog.shared.set(enabled: settings.developer) 319 DevLog.shared.event(String(localized: "settings: \(String(describing: settings))")) 320 settings.save() 321 engine.apply(settings) 322 } 323 return 324 } 325 if event.isLong { 326 // Long press down: calibrate the colors on what the camera is aimed at. 327 if event.button == .down { engine.calibrate() } 328 // Long press on the shutter: lock or release focus and exposure. 329 if event.button == .shutter { engine.toggleFocusLock() } 330 // Long press up: the dive computer page. 331 if event.button == .up { showingComputer = true } 332 return 333 } 334 switch event.button { 335 case .shutter: 336 if settings.mode == .photo { 337 DevLog.shared.event(String(localized: "photo requested")) 338 shutterFlash += 1 339 } 340 let comment = dive.shotComment(housingTemperature: housing.readings.temperatureC) 341 settings.mode == .photo ? engine.capturePhoto(comment: comment) : engine.toggleRecording(comment: comment) 342 case .up: engine.cycleLens(1) 343 case .down: engine.cycleLens(-1) 344 case .right: if camera.recordingSince == nil { menu.open() } 345 case .left: openGallery() 346 } 347 } 348 349 // MARK: Gallery (up, down: browse · left: close) 350 351 private func openGallery() { 352 roll = Roll.previews() 353 guard !roll.isEmpty else { show(String(localized: "No shots yet")); return } 354 gallery = Gallery(index: roll.count - 1) 355 loadGalleryImage() 356 } 357 358 private func loadGalleryImage() { 359 guard let gallery, roll.indices.contains(gallery.index) else { galleryImage = nil; return } 360 galleryImage = UIImage(contentsOfFile: roll[gallery.index].path) 361 } 362 363 private func galleryButton(_ event: ButtonEvent) { 364 guard var state = gallery, !event.isLong else { return } 365 switch event.button { 366 case .up: state.index = max(0, state.index - 1) 367 case .down: state.index = min(roll.count - 1, state.index + 1) 368 case .left, .shutter, .right: gallery = nil; galleryImage = nil; return 369 } 370 gallery = state 371 loadGalleryImage() 372 } 373 374 /// Immediate transfer to Photos of everything on disk (the preview is made first). 375 func exportRoll() { 376 guard !exporting else { exportAgain = true; return } 377 let pending = Roll.items() 378 guard !pending.isEmpty else { return } 379 exporting = true 380 Task { [weak self] in 381 for item in pending { await Roll.makePreview(item) } 382 guard let self else { return } 383 roll = Roll.previews() 384 Roll.export { moved, problem in 385 Task { @MainActor in 386 self.exporting = false 387 DevLog.shared.event(String(localized: "Photos: \(String(moved)) shot(s) saved") + (problem.map { ", \($0)" } ?? "")) 388 if let problem { self.show(String(localized: "Photos: \(problem)")) } 389 if self.exportAgain { self.exportAgain = false; self.exportRoll() } 390 } 391 } 392 } 393 } 394 395 private func applyOrientation() { 396 let mask: UIInterfaceOrientationMask = switch settings.orientation { 397 case .landscape: .landscapeRight 398 case .landscapeFlipped: .landscapeLeft 399 case .portrait: .portrait 400 } 401 AppDelegate.orientations = mask 402 for case let scene as UIWindowScene in UIApplication.shared.connectedScenes { 403 scene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) 404 scene.keyWindow?.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations() 405 } 406 } 407 408 func background() { 409 engine.stopForBackground() 410 if sleeping { wake() } 411 } 412 } 413 414 final class AppDelegate: NSObject, UIApplicationDelegate { 415 @MainActor static var orientations: UIInterfaceOrientationMask = .landscapeRight 416 417 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { 418 Self.orientations 419 } 420 }