Repository Public License
1// ORIX Alarm2// File: App/Features/Missions/QRMissionView.swift3// Description: QR Escape mission: walk to the registered QR code and scan it; handles camera permission, missing hardware and missing tags.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct QRMissionView: View {11 @Environment(AppModel.self) private var model12 let mission: ResolvedMission13 let onFinish: (MissionOutcome) -> Void1415 @State private var scanner = QRScanner()16 @State private var feedback: QRScanFeedback = .none17 @State private var wrongScans = 018 @State private var started = Date()19 @State private var finished = false20 /// DEBUG only: tag registered from `-ORIXFakeQR` when the previewed step has none.21 @State private var debugTagID: UUID?22 @State private var showDebugManager = false2324 private var tagID: UUID? { mission.step.qrTagID ?? debugTagID }25 private var tag: QRTag? { model.qrTag(tagID) }2627 var body: some View {28 MissionScaffold(instruction: tag == nil ? String(localized: "This mission needs a registered QR code.") : String(localized: "Get up, walk to your QR code and scan it.")) {29 if let tag { scanning(tag) } else { missingTag }30 }31 .onAppear(perform: begin)32 .onDisappear { scanner.stop() }33 #if DEBUG34 .sheet(isPresented: $showDebugManager) {35 NavigationStack { QRTagManagerView(selection: $debugTagID) }.preferredColorScheme(.dark)36 }37 #endif38 }3940 private func begin() {41 started = Date()42 #if DEBUG43 if mission.step.qrTagID == nil, let payload = QRDebug.fakePayload {44 debugTagID = model.qrTags.first { model.qrPayloadMatches(payload, tagID: $0.id) }?.id ?? model.addQRTag(label: "Test tag", payload: payload).id45 }46 showDebugManager = UserDefaults.standard.bool(forKey: "ORIXQRManager")47 #endif48 guard tag != nil else { return }49 scanner.onCode = { handle($0) }50 scanner.prepare()51 }5253 // MARK: Scanning5455 private func scanning(_ tag: QRTag) -> some View {56 VStack(spacing: 14) {57 HStack(spacing: 14) {58 Image(systemName: "qrcode").font(.title2).foregroundStyle(Theme.midnight)59 .frame(width: 48, height: 48).background(Theme.sunriseGradient, in: RoundedRectangle(cornerRadius: 14, style: .continuous))60 .accessibilityHidden(true)61 VStack(alignment: .leading, spacing: 2) {62 Text("Code to scan").font(.orixOverline).kerning(1.2).foregroundStyle(Theme.textTertiary)63 Text(tag.label.isEmpty ? String(localized: "Your QR code") : tag.label).font(.orixTitle).lineLimit(2).minimumScaleFactor(0.7)64 }65 Spacer(minLength: 0)66 }67 .frame(maxWidth: .infinity, alignment: .leading)68 .glassCard(padding: 14)69 .accessibilityElement(children: .combine)70 .accessibilityIdentifier("qr.expectedTag")7172 QRScannerPanel(scanner: scanner, feedback: feedback)7374 statusLine7576 if scanner.state.isUnavailable {77 Button("Use an alternative mission") { finish(.unavailable) }78 .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("qr.useAlternative")79 }80 #if DEBUG81 if let payload = QRDebug.fakePayload {82 VStack(spacing: 6) {83 Label("Debug build only", systemImage: "ladybug.fill").font(.orixOverline).foregroundStyle(Theme.gold)84 HStack(spacing: 10) {85 Button("Simulate scan") { handle(payload) }.accessibilityIdentifier("qr.debugScan")86 Button("Wrong code") { handle(payload + "-wrong") }.accessibilityIdentifier("qr.debugWrongScan")87 }88 .buttonStyle(SecondaryButtonStyle())89 }90 }91 #endif92 }93 }9495 @ViewBuilder private var statusLine: some View {96 switch feedback {97 case .accepted:98 Label("Code recognised", systemImage: "checkmark.circle.fill").font(.orixHeadline).foregroundStyle(Theme.success)99 .accessibilityIdentifier("qr.accepted")100 case .wrong:101 Label("That is a different QR code. Find the one you registered.", systemImage: "xmark.octagon.fill")102 .font(.orixCaption).foregroundStyle(Theme.danger).multilineTextAlignment(.leading)103 .accessibilityIdentifier("qr.wrong")104 case .none:105 if scanner.state == .running || scanner.state == .starting {106 Text("Hold the code inside the frame. Nothing is recorded: the image is read on this iPhone and discarded.")107 .font(.orixCaption).foregroundStyle(Theme.textTertiary).multilineTextAlignment(.center)108 }109 }110 }111112 private var missingTag: some View {113 VStack(spacing: 16) {114 Spacer()115 VStack(spacing: 14) {116 Image(systemName: "qrcode").font(.system(size: 44)).foregroundStyle(Theme.gold)117 .overlay(alignment: .bottomTrailing) { Image(systemName: "questionmark.circle.fill").font(.title3).foregroundStyle(Theme.gold, Theme.midnight).offset(x: 10, y: 8) }118 .accessibilityHidden(true)119 Text("No QR code to scan").font(.orixTitle)120 Text("The QR code chosen for this mission is not registered any more, so it cannot be checked. Choose a code again when you edit the alarm.")121 .font(.orixBody).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)122 }123 .frame(maxWidth: .infinity).glassCard(padding: 22)124 .accessibilityElement(children: .combine).accessibilityIdentifier("qr.missingTag")125 Spacer()126 Button("Use an alternative mission") { finish(.unavailable) }127 .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("qr.useAlternative")128 }129 }130131 // MARK: Validation132133 /// Single validation path for the camera and for the debug hook.134 private func handle(_ payload: String) {135 guard !finished, feedback != .accepted else { return }136 if model.qrPayloadMatches(payload, tagID: tagID) {137 withAnimation(.snappy) { feedback = .accepted }138 Haptics.play(.success); SoundFX.play(.correct)139 scanner.stop()140 Task {141 try? await Task.sleep(for: .milliseconds(800))142 finish(.completed)143 }144 } else {145 wrongScans += 1146 withAnimation(.snappy) { feedback = .wrong }147 Haptics.play(.failure); SoundFX.play(.wrong)148 let count = wrongScans149 Task {150 try? await Task.sleep(for: .seconds(2.5))151 if count == wrongScans, feedback == .wrong { withAnimation(.smooth) { feedback = .none } }152 }153 }154 }155156 private func finish(_ result: MissionOutcome.Result) {157 guard !finished else { return }158 finished = true159 scanner.stop()160 onFinish(MissionOutcome(result: result, mistakes: wrongScans, duration: Date().timeIntervalSince(started), rounds: result == .completed ? 1 : 0))161 }162}163