Repository Public License
1// ORIX Alarm2// File: App/Features/Missions/QRScanner.swift3// Description: On-device QR scanning shared by the QR mission and tag registration: capture session, permission states, live preview panel and debug scan hook.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AVFoundation8import SwiftUI9import UIKit1011/// Owns the capture session. Everything runs on a private serial queue, never on the main thread.12/// The session has a metadata output only: no frame is recorded, stored or sent anywhere.13nonisolated final class QRCaptureCore: NSObject, AVCaptureMetadataOutputObjectsDelegate, @unchecked Sendable {14 let session = AVCaptureSession()15 private let queue = DispatchQueue(label: "ai.spboucher.orix.alarm.qr-capture")16 // Queue-confined state.17 private var configured = false18 private var device: AVCaptureDevice?19 private var handler: (@Sendable (String) -> Void)?2021 static var hasCamera: Bool { AVCaptureDevice.default(for: .video) != nil }2223 func start(onCode: @escaping @Sendable (String) -> Void, completion: @escaping @Sendable (_ running: Bool, _ hasTorch: Bool) -> Void) {24 queue.async { [self] in25 handler = onCode26 if !configured {27 guard let camera = AVCaptureDevice.default(for: .video), let input = try? AVCaptureDeviceInput(device: camera) else { completion(false, false); return }28 session.beginConfiguration()29 let output = AVCaptureMetadataOutput()30 guard session.canAddInput(input), session.canAddOutput(output) else { session.commitConfiguration(); completion(false, false); return }31 session.addInput(input)32 session.addOutput(output)33 guard output.availableMetadataObjectTypes.contains(.qr) else {34 session.removeInput(input); session.removeOutput(output); session.commitConfiguration(); completion(false, false); return35 }36 output.metadataObjectTypes = [.qr]37 output.setMetadataObjectsDelegate(self, queue: queue)38 session.commitConfiguration()39 device = camera40 configured = true41 }42 if !session.isRunning { session.startRunning() }43 completion(session.isRunning, device?.hasTorch ?? false)44 }45 }4647 func stop() {48 queue.async { [self] in49 handler = nil50 applyTorch(false)51 if session.isRunning { session.stopRunning() }52 }53 }5455 func setTorch(_ on: Bool, completion: @escaping @Sendable (Bool) -> Void) {56 queue.async { [self] in completion(applyTorch(on)) }57 }5859 /// Returns the resulting torch state.60 @discardableResult61 private func applyTorch(_ on: Bool) -> Bool {62 guard let device, device.hasTorch, device.isTorchAvailable || !on else { return false }63 guard (try? device.lockForConfiguration()) != nil else { return device.torchMode == .on }64 device.torchMode = on ? .on : .off65 device.unlockForConfiguration()66 return on67 }6869 func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {70 for object in metadataObjects {71 if let code = object as? AVMetadataMachineReadableCodeObject, code.type == .qr, let payload = code.stringValue, !payload.isEmpty {72 handler?(payload)73 return74 }75 }76 }77}7879/// Main-actor face of the scanner: permission and availability state, torch, and debounced scan results.80@Observable81final class QRScanner {82 enum State: Equatable {83 case idle, needsPermission, denied, restricted, noCamera, starting, running, failed84 /// The camera cannot be used at all here: the caller should offer another way.85 var isUnavailable: Bool { self == .denied || self == .restricted || self == .noCamera || self == .failed }86 }8788 private(set) var state: State = .idle89 private(set) var hasTorch = false90 private(set) var torchOn = false91 /// Called on the main actor for each scan. The same code held in view is reported at most every two seconds.92 @ObservationIgnored var onCode: ((String) -> Void)?93 @ObservationIgnored let core = QRCaptureCore()94 @ObservationIgnored private var lastPayload: String?95 @ObservationIgnored private var lastTime = Date.distantPast9697 /// Checks the hardware and the permission; starts the camera when it is already allowed.98 func prepare() {99 guard QRCaptureCore.hasCamera else { state = .noCamera; return }100 switch AVCaptureDevice.authorizationStatus(for: .video) {101 case .authorized: start()102 case .notDetermined: state = .needsPermission103 case .denied: state = .denied104 case .restricted: state = .restricted105 @unknown default: state = .failed106 }107 }108109 func requestAccess() async {110 if await AVCaptureDevice.requestAccess(for: .video) { start() } else { state = .denied }111 }112113 func start() {114 guard state != .starting, state != .running else { return }115 state = .starting116 core.start(onCode: { [weak self] payload in117 Task { @MainActor in self?.receive(payload) }118 }, completion: { [weak self] running, torch in119 Task { @MainActor in120 guard let self, self.state == .starting else { return }121 self.hasTorch = torch122 self.state = running ? .running : .failed123 }124 })125 }126127 func stop() {128 core.stop()129 torchOn = false130 if state == .running || state == .starting { state = .idle }131 }132133 func toggleTorch() {134 let wanted = !torchOn135 core.setTorch(wanted) { [weak self] result in136 Task { @MainActor in self?.torchOn = result }137 }138 }139140 private func receive(_ payload: String) {141 guard state == .running else { return }142 let now = Date()143 if payload == lastPayload, now.timeIntervalSince(lastTime) < 2 { return }144 lastPayload = payload; lastTime = now145 onCode?(payload)146 }147}148149/// Launch-argument hooks used by UI tests and the simulator (which has no camera). Inactive in release builds.150enum QRDebug {151 /// `-ORIXFakeQR <payload>`152 static var fakePayload: String? {153 #if DEBUG154 let value = UserDefaults.standard.string(forKey: "ORIXFakeQR")155 return value?.isEmpty == false ? value : nil156 #else157 return nil158 #endif159 }160}161162/// Result of the last scan, drawn on the reticle with a symbol and a colour.163enum QRScanFeedback: Equatable { case none, wrong, accepted }164165struct QRCameraPreview: UIViewRepresentable {166 let session: AVCaptureSession167168 final class PreviewView: UIView {169 override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }170 }171172 func makeUIView(context: Context) -> PreviewView {173 let view = PreviewView()174 view.backgroundColor = .black175 if let layer = view.layer as? AVCaptureVideoPreviewLayer {176 layer.session = session177 layer.videoGravity = .resizeAspectFill178 }179 return view180 }181182 func updateUIView(_ uiView: PreviewView, context: Context) {}183}184185/// Four corner brackets framing the area to aim at.186nonisolated struct QRReticleShape: Shape {187 var corner: CGFloat = 26188 var arm: CGFloat = 34189 func path(in rect: CGRect) -> Path {190 var p = Path()191 let r = rect192 func bracket(_ origin: CGPoint, _ sx: CGFloat, _ sy: CGFloat) {193 p.move(to: CGPoint(x: origin.x, y: origin.y + sy * arm))194 p.addLine(to: CGPoint(x: origin.x, y: origin.y + sy * corner))195 p.addQuadCurve(to: CGPoint(x: origin.x + sx * corner, y: origin.y), control: origin)196 p.addLine(to: CGPoint(x: origin.x + sx * arm, y: origin.y))197 }198 bracket(CGPoint(x: r.minX, y: r.minY), 1, 1)199 bracket(CGPoint(x: r.maxX, y: r.minY), -1, 1)200 bracket(CGPoint(x: r.minX, y: r.maxY), 1, -1)201 bracket(CGPoint(x: r.maxX, y: r.maxY), -1, -1)202 return p203 }204}205206/// Live preview with reticle and torch when the camera runs; otherwise an explanation of what is needed.207struct QRScannerPanel: View {208 let scanner: QRScanner209 var feedback: QRScanFeedback = .none210 @Environment(\.accessibilityReduceMotion) private var reduceMotion211 @Environment(\.openURL) private var openURL212213 var body: some View {214 Group {215 switch scanner.state {216 case .running, .starting, .idle: camera217 case .needsPermission:218 notice(symbol: "camera.fill", tint: Theme.azure, title: "Camera access",219 text: "ORIX Alarm uses the camera only to recognise your QR code. Images are analysed on this iPhone; nothing is saved or sent.") {220 Button("Allow camera") { Task { await scanner.requestAccess() } }221 .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("qr.allowCamera")222 }223 case .denied:224 notice(symbol: "camera.badge.ellipsis", tint: Theme.gold, title: "Camera access is off",225 text: "To scan a QR code, open Settings, choose ORIX Alarm and turn on Camera.") {226 Button("Open Settings") {227 if let url = URL(string: UIApplication.openSettingsURLString) { openURL(url) }228 }229 .buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("qr.openSettings")230 }231 case .restricted:232 notice(symbol: "lock.fill", tint: Theme.gold, title: "Camera access is restricted",233 text: "The camera is blocked on this iPhone by Screen Time or a device profile, so a QR code cannot be scanned.") { EmptyView() }234 case .noCamera:235 notice(symbol: "video.slash.fill", tint: Theme.gold, title: "No camera available",236 text: "This device has no camera that ORIX Alarm can use, so a QR code cannot be scanned here.") { EmptyView() }237 case .failed:238 notice(symbol: "exclamationmark.triangle.fill", tint: Theme.gold, title: "The camera could not start",239 text: "Another app may be using it. You can try again.") {240 Button("Try again") { scanner.prepare() }.buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("qr.retry")241 }242 }243 }244 .frame(maxWidth: .infinity, maxHeight: .infinity)245 }246247 private var reticleColor: Color {248 switch feedback { case .none: .white; case .wrong: Theme.danger; case .accepted: Theme.success }249 }250251 private var camera: some View {252 ZStack {253 QRCameraPreview(session: scanner.core.session)254 if scanner.state != .running {255 ProgressView().controlSize(.large).tint(.white)256 }257 GeometryReader { geo in258 let side = min(geo.size.width, geo.size.height) * 0.68259 ZStack {260 QRReticleShape()261 .stroke(reticleColor, style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))262 .shadow(color: reticleColor.opacity(0.7), radius: 8)263 if feedback == .none, scanner.state == .running, !reduceMotion {264 TimelineView(.animation) { context in265 let phase = context.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 2.4) / 2.4266 let y = (phase < 0.5 ? phase * 2 : (1 - phase) * 2) * (side - 36) + 18267 Capsule().fill(LinearGradient(colors: [.clear, Theme.gold, .clear], startPoint: .leading, endPoint: .trailing))268 .frame(width: side - 36, height: 3).position(x: side / 2, y: y)269 }270 }271 if feedback != .none {272 Image(systemName: feedback == .accepted ? "checkmark.circle.fill" : "xmark.circle.fill")273 .font(.system(size: 64)).foregroundStyle(reticleColor)274 .background(Circle().fill(.black.opacity(0.5)).padding(4))275 .transition(.scale.combined(with: .opacity))276 }277 }278 .frame(width: side, height: side)279 .position(x: geo.size.width / 2, y: geo.size.height / 2)280 }281 .accessibilityHidden(true)282 if scanner.hasTorch, scanner.state == .running {283 Button { scanner.toggleTorch(); Haptics.play(.selection) } label: {284 Image(systemName: scanner.torchOn ? "flashlight.on.fill" : "flashlight.off.fill")285 .font(.title2).foregroundStyle(scanner.torchOn ? Theme.midnight : .white)286 .frame(width: 56, height: 56)287 .background(scanner.torchOn ? AnyShapeStyle(Theme.gold) : AnyShapeStyle(.black.opacity(0.55)), in: Circle())288 .overlay(Circle().strokeBorder(.white.opacity(0.3)))289 }290 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing).padding(14)291 .accessibilityLabel("Flashlight").accessibilityValue(scanner.torchOn ? "On" : "Off")292 .accessibilityIdentifier("qr.torch")293 }294 }295 .clipShape(RoundedRectangle(cornerRadius: Theme.cornerRadius, style: .continuous))296 .overlay(RoundedRectangle(cornerRadius: Theme.cornerRadius, style: .continuous).strokeBorder(Theme.hairline))297 .accessibilityElement(children: .contain)298 .accessibilityLabel("Camera preview. Point it at the QR code.")299 }300301 private func notice<Actions: View>(symbol: String, tint: Color, title: LocalizedStringKey, text: LocalizedStringKey, @ViewBuilder actions: () -> Actions) -> some View {302 VStack(spacing: 14) {303 Image(systemName: symbol).font(.system(size: 44)).foregroundStyle(tint).accessibilityHidden(true)304 Text(title).font(.orixTitle).multilineTextAlignment(.center)305 Text(text).font(.orixBody).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)306 actions()307 }308 .frame(maxWidth: .infinity)309 .glassCard(padding: 22)310 .accessibilityElement(children: .contain)311 .accessibilityIdentifier("qr.notice")312 }313}314