CameraScreen.swift (23730B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import AVFoundation 3 import RemoraDeco 4 import RemoraUI 5 import SwiftUI 6 7 struct PreviewView: UIViewRepresentable { 8 let layer: AVCaptureVideoPreviewLayer 9 10 final class Host: UIView { 11 var preview: AVCaptureVideoPreviewLayer? 12 override func layoutSubviews() { 13 super.layoutSubviews() 14 preview?.frame = bounds 15 } 16 } 17 18 func makeUIView(context: Context) -> Host { 19 let view = Host() 20 view.backgroundColor = .black 21 view.preview = layer 22 view.layer.addSublayer(layer) 23 return view 24 } 25 26 func updateUIView(_ view: Host, context: Context) {} 27 } 28 29 /// Stand-in for the camera preview ("-previewPattern"): the simulator has no camera, and screenshots must 30 /// show what is opaque. Deliberately garish. 31 struct PreviewPattern: View { 32 var body: some View { 33 Canvas { context, size in 34 let step = 40.0 35 var x = -size.height 36 var i = 0 37 while x < size.width { 38 var stripe = Path() 39 stripe.move(to: CGPoint(x: x, y: size.height)) 40 stripe.addLine(to: CGPoint(x: x + size.height, y: 0)) 41 stripe.addLine(to: CGPoint(x: x + size.height + step, y: 0)) 42 stripe.addLine(to: CGPoint(x: x + step, y: size.height)) 43 stripe.closeSubpath() 44 context.fill(stripe, with: .color(i % 2 == 0 ? Color(red: 1, green: 0, blue: 0.8) : Color(red: 0.2, green: 1, blue: 0))) 45 x += step 46 i += 1 47 } 48 } 49 } 50 } 51 52 /// Main screen: the image full screen, the information around it, and on top the vacuum 53 /// sequence as long as it keeps the buttons. 54 struct CameraScreen: View { 55 let model: AppModel 56 @Environment(\.scenePhase) private var scenePhase 57 @State private var showDiagnostics = false 58 @State private var flashing = false 59 60 private var housing: HousingClient { model.housing } 61 62 var body: some View { 63 ZStack { 64 Color.black.ignoresSafeArea() 65 if CommandLine.arguments.contains("-previewPattern") { 66 PreviewPattern().ignoresSafeArea() 67 } else { 68 PreviewView(layer: model.engine.previewLayer).ignoresSafeArea() 69 } 70 71 // Shutter blink: the image goes dark for an instant at each photo. 72 Color.black.ignoresSafeArea().opacity(flashing ? 1 : 0).allowsHitTesting(false) 73 74 // Before and after the camera (home, vacuum sequence, opening), the preview is of no use: those 75 // screens are on plain black, like the dive computer page. During the leak test the camera is 76 // usable, and visible. 77 if !cameraInUse { Color.black.ignoresSafeArea() } 78 79 // Dive computer alarm: the whole screen flashes red, under the read-outs. 80 if diveAlarm { AlarmFlash().allowsHitTesting(false) } 81 if showingComputer { ComputerPage(model: model) } 82 83 VStack { 84 // The home screen has the whole screen; the bottom bar only describes the camera. 85 if !isHome { topBar } 86 if model.dive.isComputing, !showingComputer { DiveBand(model: model) } 87 if model.settings.developer { devOverlay } 88 Spacer() 89 if let message = model.toast, !model.menu.isOpen { 90 Text(message).font(.footnote).padding(8).background(.black.opacity(0.5), in: Capsule()) 91 } 92 if cameraInUse { bottomBar } 93 } 94 .padding() 95 96 Group { 97 if !model.camera.authorized { 98 card { Text("Allow camera access in Settings → Open Mérou.") } 99 } else if isHome { 100 HomeScreen(model: model) { showDiagnostics = true } 101 .overlay(alignment: .bottom) { 102 if let message = model.toast { 103 Text(message).font(.footnote).padding(8).background(.gray.opacity(0.4), in: Capsule()).padding(.bottom, 6) 104 } 105 } 106 } else if !housing.vacuum.cameraHasButtons { 107 card { 108 VacuumView(vacuum: housing.vacuum) 109 Text(housing.status.label).font(.footnote).foregroundStyle(.secondary) 110 } 111 } else if let gallery = model.gallery { 112 GalleryView(model: model, gallery: gallery) 113 } else if model.showingInfo { 114 InfoPanel(model: model) 115 } else if model.menu.isOpen { 116 MenuView(model: model) 117 } 118 } 119 // In simulation, the panels move to the left to keep the simulated buttons visible. 120 .frame(maxWidth: .infinity, alignment: housing.simulated ? .leading : .center) 121 .padding(.leading, housing.simulated ? 40 : 0) 122 123 if housing.vacuum.linkLost { 124 VStack { 125 Label("Housing disconnected: seal not monitored, buttons inactive. Reconnecting…", systemImage: "antenna.radiowaves.left.and.right.slash") 126 .font(.subheadline.weight(.semibold)).foregroundStyle(.black) 127 .padding(10).background(.orange, in: RoundedRectangle(cornerRadius: 12)) 128 Spacer() 129 } 130 .padding(.top, 50) 131 } 132 133 if diveAlarm, !showingComputer { DiveAlarmLabel(monitor: model.dive.monitor) } 134 135 // The leak alarm keeps priority over everything else. 136 if case .failed(.leak(let rise)) = housing.vacuum.step { 137 LeakAlarm(risePa: rise) 138 } 139 140 if housing.simulated { SimulatedButtons(housing: housing) { model.startSimulatedDive() } } 141 142 if model.sleeping { 143 Color.black.ignoresSafeArea().onTapGesture { model.wake() } 144 } 145 } 146 .foregroundStyle(.white) 147 .preferredColorScheme(.dark) 148 .statusBarHidden() 149 .persistentSystemOverlays(.hidden) 150 .onChange(of: model.shutterFlash) { 151 flashing = true 152 withAnimation(.easeOut(duration: 0.25).delay(0.08)) { flashing = false } 153 } 154 .sheet(isPresented: $showDiagnostics) { HousingView(housing: housing) } 155 .onChange(of: scenePhase) { _, phase in 156 if phase != .active { 157 model.background() 158 if housing.pumpRequested { housing.stopPump(reason: String(localized: "app in the background")) } 159 } 160 } 161 } 162 163 /// The buttons go to the camera (leak test, sealed dive, simulation): the preview is what matters. 164 private var cameraInUse: Bool { model.camera.authorized && housing.vacuum.cameraHasButtons } 165 /// Home screen: no housing sequence started yet (a simulated housing goes straight to the camera). 166 private var isHome: Bool { model.camera.authorized && housing.vacuum.step == .prepare && !housing.simulated } 167 168 /// The dive computer is following a dive and raises an alarm (violation, depth unknown). 169 private var diveAlarm: Bool { model.dive.isComputing && model.dive.monitor.isAlarming } 170 /// The computer page is a camera-mode page: never over the vacuum sequence. 171 private var showingComputer: Bool { model.showingComputer && housing.vacuum.cameraHasButtons } 172 173 private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View { 174 VStack(alignment: .leading, spacing: 8) { content() } 175 .padding(20) 176 .frame(maxWidth: 460) 177 .background(.black.opacity(0.75), in: RoundedRectangle(cornerRadius: 20)) 178 .padding() 179 } 180 181 private var topBar: some View { 182 HStack(spacing: 12) { 183 sealChip 184 if let p = housing.readings.internalPressurePa { Text(String(format: "%.0f hPa", p / 100)) } 185 if let t = housing.readings.temperatureC { Text(String(format: "%.0f °C", t)) } 186 if let b = housing.readings.batteryPercent { Text("Housing \(b) %").foregroundStyle(b <= 20 ? .orange : .white) } 187 if let b = model.phoneBattery { Text("iPhone \(b) %").foregroundStyle(b <= 20 ? .orange : .white) } 188 if model.hot { Label("HOT", systemImage: "thermometer.high").foregroundStyle(.orange) } 189 // Basic dive information (the band of the dive computer replaces it when it is on). 190 if !model.dive.isComputing, let depth = model.depth, depth > 0.3 { 191 Text(String(format: "≈ %.1f m", depth)) 192 if let start = model.diveStart { Text(start, style: .timer) } 193 } 194 Spacer() 195 if let since = model.camera.recordingSince { 196 HStack(spacing: 6) { 197 Circle().fill(.red).frame(width: 12, height: 12) 198 Text(since, style: .timer) 199 } 200 .font(.headline) 201 } 202 Button { showDiagnostics = true } label: { Image(systemName: "info.circle") } 203 } 204 .font(.subheadline.weight(.semibold)) 205 .monospacedDigit() 206 .shadow(radius: 3) 207 } 208 209 /// Development mode: raw values, for in-water trials. 210 private var devOverlay: some View { 211 let r = housing.readings, v = housing.vacuum 212 let rise: Double? = switch v.step { 213 case .testing(let b), .sealed(let b): v.correctedRise(since: b) 214 default: nil 215 } 216 func n(_ value: Double?, _ format: String) -> String { value.map { String(format: format, $0) } ?? "—" } 217 let pump = r.pumpState.map { "\($0)" } ?? "—", alarm = r.alarmRaw.map { String(format: "%02X", $0) } ?? "—" 218 let battery = r.batteryPercent.map(String.init) ?? "—" 219 let step = String(String(describing: v.step).prefix { $0 != "(" }) 220 let thermal = String(ProcessInfo.processInfo.thermalState.rawValue) 221 let lines = [ 222 String(localized: "P int \(n(r.internalPressurePa, "%.0f")) Pa rise \(n(rise, "%+.0f")) Pa"), 223 "P ext? \(n(r.externalPressurePa, "%.0f")) Pa T \(n(r.temperatureC, "%.2f")) °C", 224 String(localized: "pump \(pump) 1628 \(alarm) batt \(battery) %"), 225 String(localized: "step \(step) iPhone thermal \(thermal)"), 226 String(localized: "colors \(model.camera.gains?.label ?? "iPhone")") + (model.camera.gainsSaturated ? " MAX" : ""), 227 String(localized: "gray world \(model.camera.grayWorld?.label ?? "—") ceiling ×\(n(model.camera.maxGain, "%.2f"))"), 228 String(localized: "log \(DevLog.shared.url?.lastPathComponent ?? "—")"), 229 ] 230 return HStack { 231 VStack(alignment: .leading, spacing: 2) { 232 ForEach(lines, id: \.self) { Text($0) } 233 } 234 .font(.system(size: 11, design: .monospaced)) 235 .padding(6) 236 .background(.black.opacity(0.55), in: RoundedRectangle(cornerRadius: 8)) 237 Spacer() 238 } 239 } 240 241 private var sealChip: some View { 242 let (text, color): (String, Color) = switch housing.vacuum.step { 243 case .sealed: (String(localized: "Sealed"), .green) 244 case .testing: (String(localized: "Testing"), .orange) 245 case .bypassed: (housing.simulated ? String(localized: "Simulation") : String(localized: "Dry"), .yellow) 246 case .failed: (String(localized: "Alert"), .red) 247 default: (String(localized: "Not checked"), .gray) 248 } 249 return HStack(spacing: 6) { 250 Text(text) 251 if case .testing = housing.vacuum.step { 252 TimelineView(.periodic(from: .now, by: 1)) { context in 253 let left = Int((housing.vacuum.testRemaining(now: context.date) ?? 0).rounded(.up)) 254 Text(String(format: "%d:%02d", left / 60, left % 60)) 255 } 256 } 257 } 258 .padding(.horizontal, 10).padding(.vertical, 4) 259 .background(color.opacity(0.85), in: Capsule()) 260 .foregroundStyle(.black) 261 } 262 263 private var bottomBar: some View { 264 HStack { 265 Text(model.settings.mode == .photo ? String(localized: "PHOTO") : String(localized: "VIDEO")) 266 if model.settings.mode == .video { Text(model.settings.videoQuality.label) } 267 if model.settings.mode == .photo, model.settings.photoFormat == .rawHeif { Text("RAW") } 268 switch model.settings.colorMode { 269 case .system: EmptyView() 270 case .underwater: Label("AUTO", systemImage: "drop.fill") 271 case .calibrated: Label("CAL.", systemImage: "drop.fill") 272 } 273 if model.camera.focusLocked { Label("AE/AF", systemImage: "lock.fill").foregroundStyle(.yellow) } 274 if model.camera.gainsSaturated { Label("RED MAX", systemImage: "exclamationmark.triangle.fill").foregroundStyle(.orange) } 275 if model.settings.exposureBias != 0 { Text(String(format: "%+.1f EV", model.settings.exposureBias)) } 276 Label("\(model.roll.count)", systemImage: "photo.on.rectangle") 277 .contentTransition(.numericText()) 278 .animation(.default, value: model.roll.count) 279 Spacer() 280 let labels = model.camera.capabilities.zoomLabels 281 ForEach(labels.indices, id: \.self) { i in 282 Text(labels[i]) 283 .padding(.horizontal, 8).padding(.vertical, 4) 284 .background(i == model.camera.zoomIndex ? Color.yellow : .black.opacity(0.4), in: Capsule()) 285 .foregroundStyle(i == model.camera.zoomIndex ? .black : .white) 286 } 287 } 288 .font(.subheadline.weight(.semibold)) 289 .shadow(radius: 3) 290 } 291 } 292 293 struct MenuView: View { 294 let model: AppModel 295 296 var body: some View { 297 let (title, rows, selected) = content 298 // In landscape the screen is short: show a window of rows that follows the selection. 299 let visible = 5 300 let first = max(0, min(selected - visible / 2, rows.count - visible)) 301 let shown = Array(rows.indices).filter { $0 >= first && $0 < first + visible } 302 VStack(alignment: .leading, spacing: 2) { 303 HStack { 304 Text(title).font(.headline) 305 Spacer() 306 Text("\(selected + 1)/\(rows.count)").font(.caption).foregroundStyle(.secondary) 307 } 308 .padding(.bottom, 4) 309 if first > 0 { Image(systemName: "chevron.compact.up").frame(maxWidth: .infinity).foregroundStyle(.secondary) } 310 ForEach(shown, id: \.self) { i in 311 HStack { 312 Text(rows[i].0) 313 Spacer() 314 if let value = rows[i].1 { Text(value).foregroundStyle(i == selected ? .black : .secondary) } 315 } 316 .padding(.horizontal, 12).padding(.vertical, 6) 317 .background(i == selected ? Color.yellow : .clear, in: RoundedRectangle(cornerRadius: 10)) 318 .foregroundStyle(i == selected ? .black : .white) 319 } 320 if first + visible < rows.count { Image(systemName: "chevron.compact.down").frame(maxWidth: .infinity).foregroundStyle(.secondary) } 321 Text("Up, down: choose · right: confirm · left: back") 322 .font(.caption2).foregroundStyle(.secondary).padding(.top, 4) 323 } 324 .padding(.horizontal, 16).padding(.vertical, 12) 325 .frame(maxWidth: 420) 326 .background(.black.opacity(0.8), in: RoundedRectangle(cornerRadius: 20)) 327 .padding(8) 328 } 329 330 private var content: (String, [(String, String?)], Int) { 331 let settings = model.settings, caps = model.camera.capabilities 332 switch model.menu.level { 333 case nil: 334 return ("Menu", [], 0) 335 case .root(let i): 336 return ("Menu", CameraMenu.RootItem.allCases.map { item in 337 let mark: String? = switch item { 338 case .photo: settings.mode == .photo ? "●" : nil 339 case .video: settings.mode == .video ? "●" : nil 340 case .brightness: settings.current(.brightness).label 341 default: nil 342 } 343 return (item.title, mark) 344 }, i) 345 case .settings(let i): 346 return (CameraMenu.RootItem.settings.title, CameraSetting.listed.map { ($0.title, settings.current($0).label) }, i) 347 case .options(let setting, let i): 348 let current = settings.current(setting) 349 return (setting.title, settings.options(for: setting, caps).map { ($0.label, $0 == current ? "●" : nil) }, i) 350 } 351 } 352 } 353 354 /// Buttons of the simulated housing: same layout as the real one (cross at the back, shutter on top). 355 struct SimulatedButtons: View { 356 let housing: HousingClient 357 /// Plays a dive on the simulated pressure sensor. 358 let startDive: () -> Void 359 360 var body: some View { 361 VStack { 362 Spacer() 363 HStack(alignment: .bottom) { 364 Spacer() 365 VStack(spacing: 6) { 366 key("camera.fill", .shutter) 367 key("chevron.up", .up) 368 HStack(spacing: 6) { 369 key("chevron.left", .left) 370 key("chevron.down", .down) 371 key("chevron.right", .right) 372 } 373 Text("Simulation · long press available").font(.caption2) 374 HStack(spacing: 6) { 375 if !housing.simulatedDiveRunning { 376 Button("Simulate a dive", action: startDive) 377 .font(.caption).padding(6).background(.black.opacity(0.6), in: Capsule()) 378 } 379 Button("Leave the simulation") { housing.stopSimulation() } 380 .font(.caption).padding(6).background(.black.opacity(0.6), in: Capsule()) 381 } 382 } 383 } 384 } 385 .padding(.horizontal).padding(.bottom, 44) 386 } 387 388 private func key(_ symbol: String, _ button: HousingButton) -> some View { 389 Image(systemName: symbol) 390 .font(.title3.weight(.bold)) 391 .frame(width: 52, height: 44) 392 .background(.black.opacity(0.6), in: RoundedRectangle(cornerRadius: 10)) 393 .overlay(RoundedRectangle(cornerRadius: 10).stroke(.white.opacity(0.6))) 394 .onTapGesture { housing.simulatedPress(button) } 395 .onLongPressGesture(minimumDuration: 1) { housing.simulatedPress(button, long: true) } 396 .accessibilityLabel(button.label) 397 } 398 } 399 400 /// Housing information, opened from the menu (the ⓘ button cannot be reached underwater). 401 struct InfoPanel: View { 402 let model: AppModel 403 404 private var rows: [(String, String)] { 405 let housing = model.housing, r = housing.readings 406 func n(_ value: Double?, _ format: String) -> String { value.map { String(format: format, $0) } ?? "—" } 407 let housingBattery = r.batteryPercent.map { "\($0) %" } ?? "—", phoneBattery = model.phoneBattery.map { "\($0) %" } ?? "—" 408 let videoLeft = model.videoMinutesLeft.map { String(localized: "≈ \(String($0)) min of video left") } ?? "—" 409 return [ 410 (String(localized: "Housing"), housing.status.label), 411 (String(localized: "Internal pressure"), n(r.internalPressurePa.map { $0 / 100 }, "%.1f hPa")), 412 (String(localized: "External pressure (assumed)"), n(r.externalPressurePa.map { $0 / 100 }, "%.1f hPa")), 413 (String(localized: "Internal temperature"), n(r.temperatureC, "%.1f °C")), 414 (String(localized: "Batteries"), String(localized: "housing \(housingBattery) · iPhone \(phoneBattery)")), 415 (CameraSetting.color.title, model.camera.gains?.label ?? "iPhone"), 416 (String(localized: "Shots"), String(localized: "\(String(model.roll.count)) this session · \(videoLeft)")), 417 (DeviceInfoField.firmware.label, housing.deviceInfo[.firmware] ?? "—"), 418 ] + computerRows 419 } 420 421 /// The settings of the dive computer, read-only: underwater they can only be displayed. 422 private var computerRows: [(String, String)] { 423 let title = CameraMenu.RootItem.computer.title 424 guard model.dive.isActive else { return [(title, String(localized: "Disabled"))] } 425 let s = model.dive.store.settings 426 return [ 427 (title, "\(s.gas.description) · \(SettingsText.conservatism(s)) · \(s.water.label)"), 428 (String(localized: "NDL alarm · maximum ppO2"), "\(SettingsText.ndlAlarm(s.ndlAlarmMinutes)) · \(SettingsText.ppO2(s.ppO2Max))"), 429 ] 430 } 431 432 var body: some View { 433 let housing = model.housing 434 VStack(alignment: .leading, spacing: 3) { 435 Text("Information").font(.headline).padding(.bottom, 2) 436 ForEach(rows, id: \.0) { row in 437 HStack { Text(row.0).foregroundStyle(.secondary); Spacer(); Text(row.1).monospacedDigit() } 438 } 439 ForEach(housing.log.prefix(3)) { line in 440 Text(line.text).font(.caption2).foregroundStyle(.secondary).lineLimit(1) 441 } 442 Text("Any button: close").font(.caption2).foregroundStyle(.secondary).padding(.top, 2) 443 } 444 .font(.footnote) 445 .padding(.horizontal, 16).padding(.vertical, 12) 446 .frame(maxWidth: 480) 447 .background(.black.opacity(0.8), in: RoundedRectangle(cornerRadius: 20)) 448 .padding(8) 449 } 450 } 451 452 /// Gallery of the session, driven by the housing buttons (the originals are already in Photos). 453 struct GalleryView: View { 454 let model: AppModel 455 let gallery: AppModel.Gallery 456 457 var body: some View { 458 let isVideo = model.roll.indices.contains(gallery.index) && model.roll[gallery.index].lastPathComponent.contains("-video") 459 ZStack { 460 Color.black.ignoresSafeArea() 461 if let image = model.galleryImage { 462 Image(uiImage: image).resizable().scaledToFit().ignoresSafeArea() 463 } 464 VStack { 465 HStack { 466 Text("\(gallery.index + 1) / \(model.roll.count)").monospacedDigit() 467 if isVideo { Label("VIDEO", systemImage: "video.fill") } 468 Spacer() 469 } 470 .font(.subheadline.weight(.semibold)).shadow(radius: 3) 471 Spacer() 472 Text("Up, down: browse · left: close") 473 .font(.caption).padding(8).background(.black.opacity(0.5), in: Capsule()) 474 } 475 .padding() 476 } 477 } 478 } 479 480 /// Leak alarm: full screen, blinking, impossible to miss. 481 struct LeakAlarm: View { 482 let risePa: Double 483 484 var body: some View { 485 TimelineView(.periodic(from: .now, by: 0.5)) { context in 486 let on = Int(context.date.timeIntervalSinceReferenceDate * 2) % 2 == 0 487 ZStack { 488 (on ? Color.red : Color.black).opacity(0.9).ignoresSafeArea() 489 VStack(spacing: 10) { 490 Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 60)) 491 Text("LEAK").font(.system(size: 64, weight: .black)) 492 Text("Surface and take the housing out of the water").font(.title2.bold()) 493 Text("Internal pressure rose by \(String(format: "%.0f", risePa)) Pa").font(.subheadline) 494 Text("Right button: resume monitoring · long press right: open the housing").font(.footnote) 495 } 496 .foregroundStyle(.white) 497 .multilineTextAlignment(.center) 498 .padding() 499 } 500 } 501 } 502 }