SPB Git

Repository Public

QRScanner.swift 15.7 KB 395 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/QRScanner.swift8// Module           : Qyvora UI9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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 SwiftUI4243/// Progress of a multi-frame scan, returned by the caller's reducer after each new frame.44public struct QRScanProgress: Sendable, Equatable {45    /// Frames (or fragments) accepted so far.46    public var collected: Int47    /// Frames needed, when the sequence announces it.48    public var total: Int?49    /// True when the payload is complete: the scanner stops.50    public var isComplete: Bool51    /// Optional message for a frame that does not belong to the sequence.52    public var note: String?5354    public init(collected: Int, total: Int? = nil, isComplete: Bool = false, note: String? = nil) {55        self.collected = collected56        self.total = total57        self.isComplete = isComplete58        self.note = note59    }6061    /// 0…1 when the total is known.62    public var fraction: Double? {63        guard let total, total > 0 else { return nil }64        return min(1, Double(collected) / Double(total))65    }66}6768/// Decides what the scanner does with consecutive readings (pure, testable).69struct QRScanGate {70    private(set) var last: String?71    private(set) var seen: Set<String> = []7273    /// Single mode: only the first reading passes. Sequence mode: each distinct frame passes once.74    mutating func accept(_ value: String, sequence: Bool) -> Bool {75        guard !value.isEmpty else { return false }76        if sequence {77            return seen.insert(value).inserted78        }79        guard last == nil else { return false }80        last = value81        return true82    }8384    mutating func reset() {85        last = nil86        seen = []87    }88}8990#if os(iOS)91@preconcurrency import AVFoundation92import UIKit9394/// Camera QR scanner with permission handling, a torch toggle and a paste path.95///96/// Single code: `QRScannerView(onScan:)` delivers the first code read, then pauses.97/// Multi-frame sequence: `QRScannerView(collect:onComplete:)` passes every distinct frame to the reducer,98/// shows the progress it returns, and calls `onComplete` when the reducer reports completion.99/// Pasted text goes through the same path as a scanned code.100public struct QRScannerView: View {101    enum Access: Equatable { case unknown, authorized, denied, restricted, noCamera }102103    let prompt: String104    let allowsPaste: Bool105    let onScan: ((String) -> Void)?106    let collect: ((String) -> QRScanProgress)?107    let onComplete: (() -> Void)?108109    @State private var access: Access = .unknown110    @State private var camera = QRCamera()111    @State private var gate = QRScanGate()112    @State private var torch = false113    @State private var progress: QRScanProgress?114    @State private var accepted = 0115    @State private var finished = false116    @Environment(\.openURL) private var openURL117    @Environment(\.scenePhase) private var scenePhase118119    public init(prompt: String = "Point the camera at a QR code", allowsPaste: Bool = true, onScan: @escaping (String) -> Void) {120        self.prompt = prompt121        self.allowsPaste = allowsPaste122        self.onScan = onScan123        self.collect = nil124        self.onComplete = nil125    }126127    public init(prompt: String = "Keep the animated code in the frame", allowsPaste: Bool = true,128                collect: @escaping (String) -> QRScanProgress, onComplete: @escaping () -> Void) {129        self.prompt = prompt130        self.allowsPaste = allowsPaste131        self.onScan = nil132        self.collect = collect133        self.onComplete = onComplete134    }135136    public var body: some View {137        VStack(spacing: 16) {138            viewport139            footer140        }141        .task { await prepare() }142        .onDisappear { camera.stop() }143        .onChange(of: scenePhase) { _, phase in144            guard access == .authorized, !finished else { return }145            if phase == .active { camera.start() } else { camera.stop(); torch = false }146        }147        .sensoryFeedback(.success, trigger: accepted)148    }149150    @ViewBuilder var viewport: some View {151        ZStack {152            RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous).fill(Color.black)153            switch access {154            case .unknown:155                ProgressView().tint(.white)156            case .authorized:157                QRCameraPreview(session: camera.session)158                    .clipShape(RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous))159                    .accessibilityLabel("Camera viewfinder")160                ViewfinderCorners()161                    .stroke(Color.white, style: StrokeStyle(lineWidth: 3, lineCap: .round, lineJoin: .round))162                    .padding(36)163                    .accessibilityHidden(true)164                if camera.hasTorch {165                    Button {166                        torch.toggle()167                        camera.setTorch(torch)168                    } label: {169                        Image(systemName: torch ? "flashlight.on.fill" : "flashlight.off.fill")170                            .font(.title3)171                            .foregroundStyle(.white)172                            .frame(width: 48, height: 48)173                            .background(.ultraThinMaterial, in: Circle())174                    }175                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)176                    .padding(14)177                    .accessibilityLabel("Torch")178                    .accessibilityValue(torch ? "On" : "Off")179                }180            case .denied:181                notice(systemImage: "video.slash", title: "Camera access is off",182                       message: "QYVORA uses the camera only to read QR codes. Allow it in Settings, or paste the content instead.",183                       actionTitle: "Open Settings") {184                    if let url = URL(string: UIApplication.openSettingsURLString) { openURL(url) }185                }186            case .restricted:187                notice(systemImage: "video.slash", title: "Camera restricted",188                       message: "This device does not allow camera access for this app. Paste the content instead.", actionTitle: nil) {}189            case .noCamera:190                notice(systemImage: "camera.metering.unknown", title: "No camera available",191                       message: "This device has no usable camera. Paste the content instead.", actionTitle: nil) {}192            }193        }194        .aspectRatio(1, contentMode: .fit)195        .overlay(RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))196    }197198    func notice(systemImage: String, title: String, message: String, actionTitle: String?, action: @escaping () -> Void) -> some View {199        VStack(spacing: 10) {200            Image(systemName: systemImage).font(.largeTitle.weight(.light)).foregroundStyle(.white.opacity(0.7)).accessibilityHidden(true)201            Text(title).font(QFont.headline).foregroundStyle(.white)202            Text(message).font(QFont.callout).foregroundStyle(.white.opacity(0.75)).multilineTextAlignment(.center)203                .fixedSize(horizontal: false, vertical: true)204            if let actionTitle {205                Button(actionTitle, action: action)206                    .font(.callout.weight(.semibold))207                    .foregroundStyle(.white)208                    .padding(.horizontal, 16)209                    .frame(minHeight: 44)210                    .overlay(Capsule().strokeBorder(.white.opacity(0.5), lineWidth: 1))211                    .padding(.top, 4)212            }213        }214        .padding(20)215    }216217    @ViewBuilder var footer: some View {218        VStack(spacing: 12) {219            if let progress {220                VStack(spacing: 6) {221                    if let fraction = progress.fraction {222                        ProgressView(value: fraction).tint(QColor.violet)223                    } else {224                        ProgressView().controlSize(.small)225                    }226                    Text(progressText(progress))227                        .font(QFont.callout.monospacedDigit())228                        .foregroundStyle(QColor.textPrimary)229                        .contentTransition(.numericText())230                    if let note = progress.note {231                        Text(note).font(QFont.caption).foregroundStyle(QColor.warning)232                    }233                }234                .accessibilityElement(children: .combine)235            } else if access == .authorized {236                Text(prompt).font(QFont.callout).foregroundStyle(QColor.textSecondary).multilineTextAlignment(.center)237            }238            if allowsPaste {239                HStack(spacing: 10) {240                    Text("Or paste instead").font(QFont.callout).foregroundStyle(QColor.textSecondary)241                    PasteButton(payloadType: String.self) { strings in242                        guard let text = strings.first?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else { return }243                        Task { @MainActor in handle(text) }244                    }245                    .buttonBorderShape(.capsule)246                    .tint(QColor.violet)247                }248            }249        }250    }251252    func progressText(_ p: QRScanProgress) -> String {253        if p.isComplete { return "Complete" }254        if let total = p.total { return "\(p.collected) of \(total) frames" }255        return "\(p.collected) frames read"256    }257258    func prepare() async {259        guard AVCaptureDevice.default(for: .video) != nil else {260            access = .noCamera261            return262        }263        switch AVCaptureDevice.authorizationStatus(for: .video) {264        case .authorized: access = .authorized265        case .notDetermined: access = await AVCaptureDevice.requestAccess(for: .video) ? .authorized : .denied266        case .denied: access = .denied267        case .restricted: access = .restricted268        @unknown default: access = .denied269        }270        guard access == .authorized else { return }271        camera.onCode = { value in handle(value) }272        camera.start()273    }274275    func handle(_ value: String) {276        guard !finished, gate.accept(value, sequence: collect != nil) else { return }277        accepted += 1278        if let collect {279            let p = collect(value)280            withAnimation(.snappy(duration: 0.2)) { progress = p }281            if p.isComplete {282                finished = true283                camera.stop()284                onComplete?()285            }286        } else {287            finished = true288            camera.stop()289            onScan?(value)290        }291    }292}293294/// Capture session wrapper. Configuration and start/stop run on a private queue; codes are delivered on the main actor.295final class QRCamera: NSObject, AVCaptureMetadataOutputObjectsDelegate, @unchecked Sendable {296    let session = AVCaptureSession()297    private let queue = DispatchQueue(label: "ai.spboucher.qyvora.qr-camera")298    private var configured = false299    private var device: AVCaptureDevice?300    @MainActor var onCode: ((String) -> Void)?301302    var hasTorch: Bool { AVCaptureDevice.default(for: .video)?.hasTorch ?? false }303304    func start() {305        queue.async { [self] in306            if !configured {307                configured = true308                session.beginConfiguration()309                if let camera = AVCaptureDevice.default(for: .video), let input = try? AVCaptureDeviceInput(device: camera),310                   session.canAddInput(input) {311                    session.addInput(input)312                    device = camera313                }314                let output = AVCaptureMetadataOutput()315                if session.canAddOutput(output) {316                    session.addOutput(output)317                    output.setMetadataObjectsDelegate(self, queue: .main)318                    if output.availableMetadataObjectTypes.contains(.qr) { output.metadataObjectTypes = [.qr] }319                }320                session.commitConfiguration()321            }322            if !session.isRunning { session.startRunning() }323        }324    }325326    func stop() {327        queue.async { [self] in328            if let device, device.hasTorch, device.torchMode != .off, (try? device.lockForConfiguration()) != nil {329                device.torchMode = .off330                device.unlockForConfiguration()331            }332            if session.isRunning { session.stopRunning() }333        }334    }335336    func setTorch(_ on: Bool) {337        queue.async { [self] in338            guard let device, device.hasTorch, (try? device.lockForConfiguration()) != nil else { return }339            device.torchMode = on ? .on : .off340            device.unlockForConfiguration()341        }342    }343344    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {345        let values = metadataObjects.compactMap { ($0 as? AVMetadataMachineReadableCodeObject)?.stringValue }346        guard !values.isEmpty else { return }347        // The delegate queue is the main queue (set in `start`).348        MainActor.assumeIsolated {349            for value in values { onCode?(value) }350        }351    }352}353354struct QRCameraPreview: UIViewRepresentable {355    let session: AVCaptureSession356357    final class PreviewView: UIView {358        override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }359        var previewLayer: AVCaptureVideoPreviewLayer? { layer as? AVCaptureVideoPreviewLayer }360    }361362    func makeUIView(context: Context) -> PreviewView {363        let view = PreviewView()364        view.backgroundColor = .black365        view.previewLayer?.session = session366        view.previewLayer?.videoGravity = .resizeAspectFill367        return view368    }369370    func updateUIView(_ uiView: PreviewView, context: Context) {}371}372373struct ViewfinderCorners: Shape {374    func path(in rect: CGRect) -> Path {375        let arm = min(rect.width, rect.height) * 0.14376        var p = Path()377        for (corner, dx, dy) in [(CGPoint(x: rect.minX, y: rect.minY), 1.0, 1.0), (CGPoint(x: rect.maxX, y: rect.minY), -1.0, 1.0),378                                 (CGPoint(x: rect.maxX, y: rect.maxY), -1.0, -1.0), (CGPoint(x: rect.minX, y: rect.maxY), 1.0, -1.0)] {379            p.move(to: CGPoint(x: corner.x + arm * dx, y: corner.y))380            p.addLine(to: corner)381            p.addLine(to: CGPoint(x: corner.x, y: corner.y + arm * dy))382        }383        return p384    }385}386387#if DEBUG388#Preview("QR scanner") {389    QRScannerView { _ in }390        .padding()391        .qScreen()392}393#endif394#endif395
Files main
Menu

Theme