Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Features/Scanner/CaptureStepView.swift8// Module : SPVault9// Repository : https://git.spboucher.ai/sp-id-card-vault10// Project Website : Not specified11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import AVFoundation42import Observation43import SwiftUI4445/// Capture of one side of a card. On a device this is the live camera; in the46/// iOS Simulator (no camera) it is a stand-in that photographs fictitious demo47/// cards, so the rest of the pipeline runs unchanged.48struct CaptureStepView: View {49 var side: CardSide50 var kind: CardKind51 var step: ScanStepIndicator.Step52 var steps: [ScanStepIndicator.Step] = ScanStepIndicator.Step.allCases53 /// Shows "No back" (only meaningful for the back).54 var allowsSkip = false55 var onCapture: (CapturedStill) -> Void56 var onSkip: () -> Void = {}57 var onClose: () -> Void5859 var body: some View {60 #if targetEnvironment(simulator)61 SimulatedCaptureView(side: side, kind: kind, step: step, steps: steps, allowsSkip: allowsSkip,62 onCapture: onCapture, onSkip: onSkip, onClose: onClose)63 #else64 LiveCaptureView(side: side, kind: kind, step: step, steps: steps, allowsSkip: allowsSkip,65 onCapture: onCapture, onSkip: onSkip, onClose: onClose)66 #endif67 }68}6970/// Title block under the top bar.71struct CaptureTitle: View {72 var side: CardSide73 var kind: CardKind7475 var body: some View {76 VStack(spacing: 4) {77 Text(side == .front ? "Front of the card" : "Back of the card").font(.spTitle).foregroundStyle(.white)78 Text(kind.title).spEyebrow(.white.opacity(0.65))79 }80 .shadow(color: .black.opacity(0.5), radius: 8)81 .accessibilityElement(children: .combine)82 .accessibilityAddTraits(.isHeader)83 }84}8586/// "No back" capsule.87struct SkipBackButton: View {88 var action: () -> Void8990 var body: some View {91 Button(action: action) {92 Text("No back").font(.system(size: 14, weight: .semibold)).foregroundStyle(.white)93 .padding(.horizontal, SP.Space.m).frame(minHeight: 44)94 .contentShape(Capsule())95 }96 .buttonStyle(.plain)97 .spGlass()98 .accessibilityHint("This card has nothing to keep on its back")99 .accessibilityIdentifier("scanner.noBack")100 }101}102103// MARK: - Live camera104105@MainActor106@Observable107final class LiveCaptureModel {108 enum Access { case unknown, granted, denied, unavailable }109110 private(set) var access: Access = .unknown111 private(set) var analysis: LiveAnalysis?112 private(set) var issues: [QualityIssue] = [.noCard]113 private(set) var readiness = 0.0114 private(set) var isCapturing = false115 private(set) var captureFailed = false116 var torchOn = false { didSet { camera.setTorch(torchOn) } }117 var autoCapture = true118119 @ObservationIgnored let camera = CameraController()120 @ObservationIgnored private var tracker = StabilityTracker(tolerance: 0.014, requiredFrames: 6)121 @ObservationIgnored var onCapture: ((CapturedStill) -> Void)?122123 var hasTorch: Bool { camera.hasTorch }124 var isReady: Bool { issues.isEmpty }125126 var hint: String {127 if captureFailed { return "Capture failed — try again" }128 if isCapturing { return "Capturing…" }129 return issues.first?.hint ?? (autoCapture ? "Hold steady — capturing" : "Ready")130 }131132 func begin() async {133 switch AVCaptureDevice.authorizationStatus(for: .video) {134 case .authorized: access = .granted135 case .notDetermined: access = await AVCaptureDevice.requestAccess(for: .video) ? .granted : .denied136 default: access = .denied137 }138 guard access == .granted else { return }139 camera.setAnalysisHandler { [weak self] analysis in self?.handle(analysis) }140 camera.setPaused(false)141 camera.start { [weak self] ready in142 if !ready { self?.access = .unavailable }143 }144 }145146 func end() {147 camera.setAnalysisHandler(nil)148 if torchOn { camera.setTorch(false) }149 camera.stop()150 }151152 private func handle(_ analysis: LiveAnalysis) {153 guard !isCapturing else { return }154 self.analysis = analysis155 let stable = tracker.feed(analysis.quad)156 var issues = analysis.report.issues157 if analysis.quad != nil, !stable { issues.append(.unstable) }158 self.issues = issues159 readiness = analysis.report.isAcceptable ? min(1, Double(tracker.steadyFrames) / Double(tracker.requiredFrames)) : 0160 if autoCapture, issues.isEmpty { shoot() }161 }162163 func shoot() {164 guard !isCapturing, access == .granted else { return }165 isCapturing = true166 captureFailed = false167 camera.setPaused(true)168 camera.capturePhoto { [weak self] result in169 guard let self else { return }170 switch result {171 case .success(let still):172 Haptics.shared.play(.capture)173 self.onCapture?(still)174 case .failure:175 Haptics.shared.play(.warning)176 self.captureFailed = true177 self.camera.setPaused(false)178 }179 self.isCapturing = false180 self.tracker.reset()181 self.readiness = 0182 }183 }184}185186struct LiveCaptureView: View {187 var side: CardSide188 var kind: CardKind189 var step: ScanStepIndicator.Step190 var steps: [ScanStepIndicator.Step]191 var allowsSkip: Bool192 var onCapture: (CapturedStill) -> Void193 var onSkip: () -> Void194 var onClose: () -> Void195196 @State private var model = LiveCaptureModel()197 @State private var showsDocumentCamera = false198199 var body: some View {200 ZStack {201 Color.black.ignoresSafeArea()202 switch model.access {203 case .granted: viewfinder204 case .unknown: ProgressView().tint(.white)205 case .denied:206 CameraAccessView(title: "Camera access is off",207 message: "SP Vault needs the camera to photograph your cards. Photos are encrypted on this iPhone and never leave it.",208 showsSettings: true, allowsSkip: allowsSkip, onSkip: onSkip, onClose: onClose)209 case .unavailable:210 CameraAccessView(title: "Camera unavailable",211 message: "The camera could not be started. Close other apps that use the camera and try again.",212 showsSettings: false, allowsSkip: allowsSkip, onSkip: onSkip, onClose: onClose)213 }214 }215 .preferredColorScheme(.dark)216 .statusBarHidden()217 .task {218 model.onCapture = onCapture219 await model.begin()220 }221 .onDisappear { model.end() }222 .fullScreenCover(isPresented: $showsDocumentCamera) {223 DocumentCameraView(onScan: { still in224 showsDocumentCamera = false225 Haptics.shared.play(.capture)226 onCapture(still)227 }, onCancel: { showsDocumentCamera = false })228 .ignoresSafeArea()229 }230 }231232 private var viewfinder: some View {233 GeometryReader { proxy in234 let size = proxy.size235 let frameSize = model.analysis?.frameSize ?? CGSize(width: 3, height: 4)236 let videoRect = ScanGeometry.rect(for: frameSize, in: size, fill: true)237 let guide = CardQuad.centred(aspect: kind.defaultFormat.aspectRatio, imageSize: size, widthFraction: 0.86)238 let corners = model.analysis?.quad.map { ScanGeometry.points(of: $0, in: videoRect) }239 ?? ScanGeometry.points(of: guide, in: CGRect(origin: .zero, size: size))240 ZStack {241 CameraPreview(session: model.camera.session) { point in model.camera.focus(at: point) }242 ViewfinderFrame(corners: corners, isLocked: model.analysis?.quad != nil, isReady: model.isReady)243 }244 .frame(width: size.width, height: size.height)245 }246 .ignoresSafeArea()247 .overlay(alignment: .top) {248 VStack(spacing: SP.Space.l) {249 ScannerTopBar(step: step, steps: steps, onClose: onClose) {250 if model.hasTorch {251 GlassIconButton(symbol: model.torchOn ? "bolt.fill" : "bolt.slash.fill", label: model.torchOn ? "Turn light off" : "Turn light on") {252 model.torchOn.toggle()253 }254 }255 }256 CaptureTitle(side: side, kind: kind)257 }258 }259 .overlay(alignment: .bottom) {260 VStack(spacing: SP.Space.l) {261 ScanHintLine(text: model.hint, tone: model.isReady ? .accent : .warning)262 HStack(alignment: .center) {263 Group {264 if DocumentCameraView.isSupported {265 GlassIconButton(symbol: "doc.viewfinder", label: "Document mode", size: 50) { showsDocumentCamera = true }266 .accessibilityIdentifier("scanner.documentMode")267 }268 }269 .frame(maxWidth: .infinity, alignment: .leading)270 ShutterButton(readiness: model.readiness, isBusy: model.isCapturing) { model.shoot() }271 Group {272 if allowsSkip { SkipBackButton(action: onSkip) } else { autoToggle }273 }274 .frame(maxWidth: .infinity, alignment: .trailing)275 }276 if allowsSkip { autoToggle }277 }278 .padding(.horizontal, SP.Space.xl)279 .padding(.bottom, SP.Space.l)280 }281 }282283 private var autoToggle: some View {284 Button { model.autoCapture.toggle() } label: {285 HStack(spacing: 6) {286 Image(systemName: model.autoCapture ? "a.circle.fill" : "a.circle")287 Text(model.autoCapture ? "Auto" : "Manual")288 }289 .font(.system(size: 14, weight: .semibold))290 .foregroundStyle(model.autoCapture ? SP.Palette.electric : .white)291 .padding(.horizontal, SP.Space.s).frame(minHeight: 44)292 .contentShape(Capsule())293 }294 .buttonStyle(.plain)295 .spGlass()296 .accessibilityLabel("Automatic capture")297 .accessibilityValue(model.autoCapture ? "On" : "Off")298 .accessibilityIdentifier("scanner.autoCapture")299 }300}301302/// Designed state for a refused or unavailable camera.303struct CameraAccessView: View {304 var title: String305 var message: String306 var showsSettings: Bool307 var allowsSkip: Bool308 var onSkip: () -> Void309 var onClose: () -> Void310311 @Environment(\.openURL) private var openURL312313 var body: some View {314 ZStack {315 VaultBackground()316 VStack(spacing: SP.Space.xl) {317 Spacer()318 IconBadge(symbol: "camera.fill", tint: SP.Palette.titanium, size: 72)319 VStack(spacing: SP.Space.s) {320 Text(title).font(.spTitle).foregroundStyle(SP.Palette.textPrimary).multilineTextAlignment(.center)321 Text(message).font(.spCallout).foregroundStyle(SP.Palette.textSecondary).multilineTextAlignment(.center)322 .fixedSize(horizontal: false, vertical: true)323 }324 if showsSettings {325 VStack(alignment: .leading, spacing: SP.Space.s) {326 Label("Open Settings", systemImage: "1.circle.fill")327 Label("Turn on Camera for SP Vault", systemImage: "2.circle.fill")328 Label("Come back and scan", systemImage: "3.circle.fill")329 }330 .font(.spCallout).foregroundStyle(SP.Palette.textSecondary)331 .frame(maxWidth: .infinity, alignment: .leading)332 .spPanel()333 }334 Spacer()335 VStack(spacing: SP.Space.s) {336 if showsSettings {337 Button("Open Settings") {338 if let url = URL(string: UIApplication.openSettingsURLString) { openURL(url) }339 }340 .buttonStyle(.spPrimary)341 .accessibilityIdentifier("scanner.openSettings")342 }343 if allowsSkip { Button("Continue without the back", action: onSkip).buttonStyle(.spSecondary) }344 Button("Cancel", action: onClose).buttonStyle(.spQuiet)345 }346 }347 .padding(SP.Space.xl)348 }349 }350}351352// MARK: - Simulator stand-in353354#if targetEnvironment(simulator)355/// Simulator only. Lets the owner of the build pick one of the fictitious demo356/// cards; the shutter "photographs" it with `SimulatedCamera` (tilted, on a357/// table) and the real pipeline takes over.358struct SimulatedCaptureView: View {359 var side: CardSide360 var kind: CardKind361 var step: ScanStepIndicator.Step362 var steps: [ScanStepIndicator.Step]363 var allowsSkip: Bool364 var onCapture: (CapturedStill) -> Void365 var onSkip: () -> Void366 var onClose: () -> Void367368 @State private var demos: [DemoCardFactory.Demo] = []369 @State private var selection = 0370 @State private var preview: SimulatedCamera.Shot?371 @State private var isCapturing = false372373 private func artwork(_ demo: DemoCardFactory.Demo) -> CGImage {374 side == .back ? (demo.back ?? demo.front) : demo.front375 }376377 var body: some View {378 ZStack {379 Color.black.ignoresSafeArea()380 GeometryReader { proxy in381 let size = proxy.size382 if let preview {383 let imageSize = CGSize(width: preview.image.width, height: preview.image.height)384 let rect = ScanGeometry.rect(for: imageSize, in: size, fill: true)385 ZStack {386 Image(decorative: preview.image, scale: 1).resizable().aspectRatio(contentMode: .fill)387 .frame(width: size.width, height: size.height).clipped()388 ViewfinderFrame(corners: ScanGeometry.points(of: preview.quad, in: rect), isLocked: true, isReady: true)389 }390 } else {391 ProgressView().tint(.white).frame(width: size.width, height: size.height)392 }393 }394 .ignoresSafeArea()395 }396 .overlay(alignment: .top) {397 VStack(spacing: SP.Space.l) {398 ScannerTopBar(step: step, steps: steps, onClose: onClose) { EmptyView() }399 CaptureTitle(side: side, kind: kind)400 }401 }402 .overlay(alignment: .bottom) {403 VStack(spacing: SP.Space.m) {404 ScanHintLine(text: "Simulator — fictitious demo cards", tone: .accent, symbol: "testtube.2")405 ScrollView(.horizontal, showsIndicators: false) {406 HStack(spacing: SP.Space.s) {407 ForEach(demos.indices, id: \.self) { index in408 Button { select(index) } label: {409 Image(decorative: artwork(demos[index]), scale: 1).resizable().aspectRatio(contentMode: .fit)410 .frame(height: 46)411 .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))412 .overlay(RoundedRectangle(cornerRadius: 5, style: .continuous)413 .strokeBorder(index == selection ? SP.Palette.electric : .white.opacity(0.25), lineWidth: index == selection ? 2 : 0.75))414 }415 .buttonStyle(.plain)416 .accessibilityLabel(demos[index].card.name)417 .accessibilityIdentifier("scanner.demo.\(index)")418 }419 }420 .padding(.horizontal, SP.Space.xl)421 }422 HStack(alignment: .center) {423 Color.clear.frame(maxWidth: .infinity, maxHeight: 1)424 ShutterButton(readiness: preview == nil ? 0 : 1, isBusy: isCapturing || preview == nil) { capture() }425 Group { if allowsSkip { SkipBackButton(action: onSkip) } }426 .frame(maxWidth: .infinity, alignment: .trailing)427 }428 .padding(.horizontal, SP.Space.xl)429 }430 .padding(.bottom, SP.Space.l)431 }432 .preferredColorScheme(.dark)433 .statusBarHidden()434 .task {435 let all = DemoCardFactory.all()436 demos = all437 select(all.firstIndex { $0.card.kind == kind } ?? all.firstIndex { $0.card.kind.categoryID == kind.categoryID } ?? 0)438 }439 }440441 private func select(_ index: Int) {442 guard demos.indices.contains(index) else { return }443 selection = index444 let art = CapturedStill(image: artwork(demos[index]))445 Task {446 // A lighter canvas, shaped like the screen, is enough for the viewfinder.447 let shot = await Task.detached(priority: .userInitiated) {448 SimulatedCamera.photograph(art.image, fill: 0.84, canvas: CGSize(width: 1170, height: 2532))449 }.value450 if selection == index { preview = shot }451 }452 }453454 private func capture() {455 guard demos.indices.contains(selection), !isCapturing else { return }456 isCapturing = true457 let art = CapturedStill(image: artwork(demos[selection]))458 Task {459 let shot = await Task.detached(priority: .userInitiated) { SimulatedCamera.photograph(art.image) }.value460 Haptics.shared.play(.capture)461 isCapturing = false462 onCapture(CapturedStill(image: shot.image))463 }464 }465}466#endif467