Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Identity9// File : sdk/swift/Sources/MacLustrIdentityUI/DocumentCaptureView.swift10// Module : MacLustrIdentityUI11// Repository : https://git.spboucher.ai/maclustr-identity12// Project Website : https://identity.spboucher.ai13// Created : 2026-12-0114// Last Modified : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// Document capture: live guidance, automatic or manual shutter, review, upload. Images stay in memory.89import SwiftUI90import UniformTypeIdentifiers91import MacLustrIdentityCore9293/// Analyses video frames on the camera queue and reports a guidance hint.94final class DocumentFrameAnalyzer: @unchecked Sendable {95 private var guide = DocumentGuide()96 private var lastAnalysis: TimeInterval = 097 private var lastHint: DocumentHint?98 private let enabled = Locked(true)99 /// Called on the main queue when the hint changes.100 var onHint: (@Sendable (DocumentHint) -> Void)?101 /// About eight analyses per second are enough for guidance.102 private let minInterval: TimeInterval = 0.12103104 func setEnabled(_ on: Bool) { enabled.set(on) }105106 /// Called on the camera frame queue.107 func process(_ buffer: CVPixelBuffer, time: TimeInterval) {108 guard enabled.get() else { guide.reset(); lastHint = nil; return }109 guard time - lastAnalysis >= minInterval, let quality = ImageUtilities.lumaQuality(of: buffer) else { return }110 lastAnalysis = time111 let hint = guide.update(.init(corners: VisionAnalysis.documentCorners(in: buffer), quality: quality, time: time))112 guard hint != lastHint else { return }113 lastHint = hint114 let callback = onHint115 DispatchQueue.main.async { callback?(hint) }116 }117}118119@MainActor120final class DocumentCaptureModel: ObservableObject {121 enum Stage {122 case live123 case review(image: CGImage, jpeg: Data, textWarning: Bool, lowResolution: Bool)124 case uploading(image: CGImage)125 }126127 @Published var stage: Stage = .live128 @Published var hint: DocumentHint = .searching129 @Published var issues: [String] = []130 @Published var captureFailed = false131 @Published var isCapturing = false132133 let camera = CameraController(purpose: .document)134 private let analyzer = DocumentFrameAnalyzer()135 var automaticCapture = true136 var textQualityCheck = true137138 init() {139 analyzer.onHint = { [weak self] hint in140 Task { @MainActor in self?.received(hint) }141 }142 let analyzer = self.analyzer143 camera.onFrame.set { buffer, time in analyzer.process(buffer, time: time) }144 }145146 var isLive: Bool { if case .live = stage { return true } else { return false } }147148 func resume() {149 guard isLive else { return }150 analyzer.setEnabled(true)151 camera.start()152 }153154 func pause() {155 analyzer.setEnabled(false)156 camera.stop()157 hint = .searching158 }159160 private func received(_ new: DocumentHint) {161 guard isLive else { return }162 hint = new163 if new == .ready, automaticCapture { Task { await capture() } }164 }165166 /// Takes the photo (shutter or automatic capture) and shows it for review.167 func capture() async {168 guard isLive, !isCapturing else { return }169 isCapturing = true170 captureFailed = false171 defer { isCapturing = false }172 do {173 let raw = try await camera.captureStill()174 await present(raw)175 } catch {176 captureFailed = true177 }178 }179180 /// Uses an image file instead of the camera (devices without a camera).181 func importFile(_ url: URL) async {182 let scoped = url.startAccessingSecurityScopedResource()183 defer { if scoped { url.stopAccessingSecurityScopedResource() } }184 guard let raw = try? Data(contentsOf: url, options: [.uncached]) else { captureFailed = true; return }185 await present(raw)186 }187188 private func present(_ raw: Data) async {189 let check = textQualityCheck190 let prepared = await Task.detached(priority: .userInitiated) { () -> (CGImage, Data, Bool)? in191 guard let n = ImageUtilities.normalizedJPEG(from: raw) else { return nil }192 let warn = check && VisionAnalysis.readableCharacterCount(in: n.image) < 12193 return (n.image, n.jpeg, warn)194 }.value195 guard let (image, jpeg, warn) = prepared else { captureFailed = true; return }196 analyzer.setEnabled(false)197 camera.stop()198 issues = []199 stage = .review(image: image, jpeg: jpeg, textWarning: warn, lowResolution: ImageUtilities.isLowResolutionDocument(width: image.width, height: image.height))200 }201202 func retake() {203 stage = .live204 hint = .searching205 resume()206 }207208 func upload(side: DocumentSide, with flow: VerificationFlowModel) async {209 guard case .review(let image, let jpeg, _, let low) = stage else { return }210 stage = .uploading(image: image)211 switch await flow.uploadDocument(side: side, image: jpeg) {212 case .accepted:213 break // the flow moves to the next step and this screen goes away214 case .rejected(let codes):215 issues = codes216 retake()217 case .failed:218 // The same in-memory image stays on screen: "Use this photo" sends it again, nothing has to be recaptured.219 stage = .review(image: image, jpeg: jpeg, textWarning: false, lowResolution: low)220 }221 }222}223224struct DocumentCaptureView: View {225 @ObservedObject var flow: VerificationFlowModel226 let side: DocumentSide227 let configuration: IdentityConfiguration228229 @StateObject private var capture = DocumentCaptureModel()230 @Environment(\.identityLanguage) private var lang231 @Environment(\.scenePhase) private var scenePhase232 @State private var showImporter = false233234 var body: some View {235 CameraGate(purpose: .document) {236 content(hasCamera: true)237 .onAppear { capture.resume() }238 .onDisappear { capture.pause() }239 .onChange(of: scenePhase) { phase in240 if phase == .active { capture.resume() } else { capture.pause() }241 }242 } unavailable: {243 content(hasCamera: false)244 }245 .onAppear {246 capture.automaticCapture = configuration.automaticDocumentCapture247 capture.textQualityCheck = configuration.documentTextQualityCheck248 }249 .fileImporter(isPresented: $showImporter, allowedContentTypes: [.jpeg, .png, .heic, .webP, .image]) { result in250 if case .success(let url) = result { Task { await capture.importFile(url) } }251 }252 }253254 @ViewBuilder255 private func content(hasCamera: Bool) -> some View {256 switch capture.stage {257 case .live:258 live(hasCamera: hasCamera)259 case .review(let image, _, let warning, let low):260 review(image: image, warning: warning, lowResolution: low, uploading: false)261 case .uploading(let image):262 review(image: image, warning: false, lowResolution: false, uploading: true)263 }264 }265266 private func header() -> some View {267 VStack(alignment: .leading, spacing: 6) {268 Text((side == .front ? IdentityString.docFrontTitle : .docBackTitle).text(lang))269 .font(.title2.bold())270 .accessibilityAddTraits(.isHeader)271 Text((side == .front ? IdentityString.docFrontHint : .docBackHint).text(lang))272 .foregroundStyle(.secondary)273 .fixedSize(horizontal: false, vertical: true)274 }275 }276277 private func live(hasCamera: Bool) -> some View {278 StepLayout {279 header()280 if flow.retryRequested, side == .front {281 NoticeView(kind: .info, text: IdentityString.docRetryNotice.text(lang) + " " + IdentityString.docAttemptsLeft.text(lang, flow.state?.attemptsLeft ?? 0))282 // The reasons come from the service, in both languages, and are shown as provided.283 ForEach(flow.lastIssue.filter { !$0.message[lang].isEmpty }, id: \.code) { issue in284 NoticeView(text: issue.message[lang])285 }286 }287 ForEach(capture.issues, id: \.self) { code in288 NoticeView(text: IdentityString.forDocumentIssue(code).text(lang))289 }290 if capture.captureFailed { NoticeView(text: IdentityString.issueGeneric.text(lang)) }291 if let error = flow.lastError { NoticeView(text: IdentityString.forError(error).text(lang)) }292 if hasCamera {293 ZStack {294 CameraPreview(controller: capture.camera)295 DocumentFrameOverlay(active: capture.hint == .ready || capture.hint == .holdSteady)296 if capture.camera.status == .interrupted || capture.camera.status == .failed {297 Color.black.opacity(0.6)298 Text(IdentityString.cameraInterrupted.text(lang)).foregroundStyle(.white).padding()299 }300 }301 .aspectRatio(4.0 / 3.0, contentMode: .fit)302 .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))303 .accessibilityElement()304 .accessibilityLabel(IdentityString.a11yCameraPreview.text(lang))305 .accessibilityValue(capture.hint.string.text(lang))306 Text(capture.hint.string.text(lang))307 .font(.headline)308 .frame(maxWidth: .infinity, alignment: .center)309 .multilineTextAlignment(.center)310 .accessibilityHidden(true)311 } else {312 NoticeView(kind: .info, text: IdentityString.cameraUnavailable.text(lang))313 }314 } actions: {315 if hasCamera {316 Button(IdentityString.docShutter.text(lang)) { Task { await capture.capture() } }317 .buttonStyle(PrimaryButtonStyle())318 .disabled(capture.isCapturing || capture.camera.status != .running)319 }320 #if os(macOS)321 let offerFile = true322 #else323 let offerFile = !hasCamera324 #endif325 if offerFile {326 Button(IdentityString.docChooseFile.text(lang)) { showImporter = true }327 .buttonStyle(hasCamera ? AnyButtonStyle(SecondaryButtonStyle()) : AnyButtonStyle(PrimaryButtonStyle()))328 }329 if side == .back {330 Button(IdentityString.docNoBack.text(lang)) { Task { await flow.skipDocumentBack() } }331 .buttonStyle(SecondaryButtonStyle())332 .disabled(flow.isBusy)333 }334 if flow.canChangeMethod {335 Button(IdentityString.changeMethod.text(lang)) { flow.changeMethod() }336 .buttonStyle(SecondaryButtonStyle())337 .accessibilityIdentifier("mlid.changeMethod")338 }339 }340 .onChange(of: capture.hint) { hint in341 Accessibility.announce(hint.string.text(lang), minimumGap: hint == .ready ? 0 : 1.5)342 }343 }344345 private func review(image: CGImage, warning: Bool, lowResolution: Bool, uploading: Bool) -> some View {346 StepLayout {347 Text(IdentityString.docReviewTitle.text(lang)).font(.title2.bold()).accessibilityAddTraits(.isHeader)348 Image(decorative: image, scale: 1)349 .resizable()350 .scaledToFit()351 .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))352 .frame(maxWidth: .infinity)353 .privacySensitive()354 .accessibilityHidden(true)355 if lowResolution { NoticeView(text: IdentityString.docLowResolution.text(lang)) }356 if warning { NoticeView(text: IdentityString.docTextHardToRead.text(lang)) }357 if let error = flow.lastError, !uploading { NoticeView(text: IdentityString.forError(error).text(lang)) }358 if uploading {359 HStack(spacing: 10) {360 ProgressView()361 Text(IdentityString.docUploading.text(lang))362 }363 .frame(maxWidth: .infinity)364 .accessibilityElement(children: .combine)365 }366 } actions: {367 Button(IdentityString.docUse.text(lang)) { Task { await capture.upload(side: side, with: flow) } }368 .buttonStyle(PrimaryButtonStyle())369 .disabled(uploading)370 Button(IdentityString.docRetake.text(lang)) { capture.retake() }371 .buttonStyle(SecondaryButtonStyle())372 .disabled(uploading)373 }374 }375}376377/// Type-erased button style, to pick a style at run time.378struct AnyButtonStyle: ButtonStyle {379 private let make: (Configuration) -> AnyView380 init<S: ButtonStyle>(_ style: S) { make = { AnyView(style.makeBody(configuration: $0)) } }381 func makeBody(configuration: Configuration) -> some View { make(configuration) }382}383384/// Framing guide: a card-shaped outline that takes the accent colour when the document is well placed.385struct DocumentFrameOverlay: View {386 var active: Bool387388 var body: some View {389 GeometryReader { geo in390 let width = geo.size.width * 0.86391 let height = min(width / 1.5, geo.size.height * 0.86)392 RoundedRectangle(cornerRadius: 14, style: .continuous)393 .strokeBorder(active ? Color.accentColor : Color.white.opacity(0.9), lineWidth: active ? 4 : 2)394 .frame(width: height * 1.5, height: height)395 .position(x: geo.size.width / 2, y: geo.size.height / 2)396 }397 .allowsHitTesting(false)398 .accessibilityHidden(true)399 }400}401