Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraUI/QRCode.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 SwiftUI42import CoreImage43import CoreImage.CIFilterBuiltins4445/// Square matrix of QR modules (true = dark), without quiet zone.46public struct QRCodeMatrix: Sendable, Equatable {47 public enum ErrorCorrection: String, Sendable { case low = "L", medium = "M", quartile = "Q", high = "H" }4849 public let size: Int50 public let modules: [Bool]5152 public subscript(row: Int, column: Int) -> Bool { modules[row * size + column] }5354 /// Encodes `payload` with the system generator (Core Image). Returns nil when the payload does not fit in55 /// a QR code (about 2.9 kB at the lowest correction level) or is empty.56 public init?(payload: Data, correction: ErrorCorrection = .medium) {57 guard !payload.isEmpty else { return nil }58 let filter = CIFilter.qrCodeGenerator()59 filter.message = payload60 filter.correctionLevel = correction.rawValue61 guard let image = filter.outputImage else { return nil }62 let extent = image.extent.integral63 let width = Int(extent.width), height = Int(extent.height)64 guard width > 0, height > 0, width == height else { return nil }65 var pixels = [UInt8](repeating: 255, count: width * height)66 let drawn: Bool = pixels.withUnsafeMutableBytes { buffer in67 guard let context = CGContext(data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width,68 space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue),69 let cg = Self.context.createCGImage(image, from: extent) else { return false }70 context.interpolationQuality = .none71 context.draw(cg, in: CGRect(x: 0, y: 0, width: width, height: height))72 return true73 }74 guard drawn else { return nil }75 // Trim the generator's own margin so that the view controls the quiet zone.76 var minRow = height, maxRow = -1, minColumn = width, maxColumn = -177 for row in 0..<height {78 for column in 0..<width where pixels[row * width + column] < 128 {79 minRow = min(minRow, row)80 maxRow = max(maxRow, row)81 minColumn = min(minColumn, column)82 maxColumn = max(maxColumn, column)83 }84 }85 guard maxRow >= minRow, maxRow - minRow == maxColumn - minColumn else { return nil }86 let side = maxRow - minRow + 187 var modules = [Bool]()88 modules.reserveCapacity(side * side)89 for row in minRow...maxRow {90 for column in minColumn...maxColumn { modules.append(pixels[row * width + column] < 128) }91 }92 self.size = side93 self.modules = modules94 }9596 public init?(payload: String, correction: ErrorCorrection = .medium) {97 self.init(payload: Data(payload.utf8), correction: correction)98 }99100 private static let context = CIContext(options: [.useSoftwareRenderer: true])101}102103/// A QR code drawn module by module (always sharp), dark on white with a four-module quiet zone in both104/// appearances: scanners need that contrast, so the code does not follow the dark theme.105public struct QRCodeView: View {106 let matrix: QRCodeMatrix?107 let label: String108109 /// - Parameter label: what the code contains, for VoiceOver ("Receiving address", "Signed transaction"…).110 public init(payload: String, correction: QRCodeMatrix.ErrorCorrection = .medium, label: String = "QR code") {111 self.matrix = QRCodeMatrix(payload: payload, correction: correction)112 self.label = label113 }114115 public init(payload: Data, correction: QRCodeMatrix.ErrorCorrection = .medium, label: String = "QR code") {116 self.matrix = QRCodeMatrix(payload: payload, correction: correction)117 self.label = label118 }119120 public init(matrix: QRCodeMatrix?, label: String = "QR code") {121 self.matrix = matrix122 self.label = label123 }124125 public var body: some View {126 Group {127 if let matrix {128 Canvas(opaque: true, rendersAsynchronously: false) { context, size in129 context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(.white))130 let quiet = 4131 let total = matrix.size + quiet * 2132 // whole pixels per module keep every edge on the pixel grid133 let scale = context.environment.displayScale134 let side = min(size.width, size.height)135 let module = max(1 / scale, floor(side * scale / CGFloat(total)) / scale)136 let origin = CGPoint(x: (size.width - module * CGFloat(matrix.size)) / 2, y: (size.height - module * CGFloat(matrix.size)) / 2)137 var path = Path()138 for row in 0..<matrix.size {139 var column = 0140 while column < matrix.size {141 guard matrix[row, column] else { column += 1; continue }142 var run = 1143 while column + run < matrix.size, matrix[row, column + run] { run += 1 }144 path.addRect(CGRect(x: origin.x + CGFloat(column) * module, y: origin.y + CGFloat(row) * module,145 width: CGFloat(run) * module, height: module))146 column += run147 }148 }149 context.fill(path, with: .color(.black))150 }151 .accessibilityLabel(label)152 .accessibilityAddTraits(.isImage)153 } else {154 ZStack {155 Color.white156 VStack(spacing: 6) {157 Image(systemName: "qrcode").font(.title).foregroundStyle(.gray)158 Text("This content does not fit in a QR code").font(.caption).foregroundStyle(.black)159 .multilineTextAlignment(.center)160 }161 .padding()162 }163 .accessibilityElement(children: .combine)164 }165 }166 .aspectRatio(1, contentMode: .fit)167 .clipShape(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))168 .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))169 }170}171172/// A sequence of QR frames shown in a loop for payloads that do not fit in one code. The frame counter is173/// written under the code and the loop can be paused and stepped by hand.174public struct AnimatedQRCodeView: View {175 let frames: [String]176 let interval: TimeInterval177 let label: String178 @State private var matrices: [QRCodeMatrix?] = []179 @State private var index = 0180 @State private var paused = false181182 /// - Parameter interval: seconds per frame (clamped to at least 0.1 s).183 public init(frames: [String], interval: TimeInterval = 0.25, label: String = "Animated QR code") {184 self.frames = frames185 self.interval = max(0.1, interval)186 self.label = label187 }188189 var current: QRCodeMatrix? { index < matrices.count ? matrices[index] : nil }190191 public var body: some View {192 VStack(spacing: 12) {193 if frames.isEmpty {194 QRCodeView(matrix: nil, label: label)195 } else {196 QRCodeView(matrix: current ?? QRCodeMatrix(payload: frames[min(index, frames.count - 1)]),197 label: "\(label), frame \(index + 1) of \(frames.count)")198 }199 if frames.count > 1 {200 Text("Frame \(index + 1) of \(frames.count)")201 .font(QFont.caption.monospacedDigit())202 .foregroundStyle(QColor.textSecondary)203 .accessibilityHidden(true)204 HStack(spacing: 4) {205 stepButton("chevron.left", label: "Previous frame") { step(-1) }206 .disabled(!paused).opacity(paused ? 1 : 0.35)207 Spacer(minLength: 4)208 stepButton(paused ? "play.fill" : "pause.fill", label: paused ? "Resume" : "Pause") { paused.toggle() }209 Spacer(minLength: 4)210 stepButton("chevron.right", label: "Next frame") { step(1) }211 .disabled(!paused).opacity(paused ? 1 : 0.35)212 }213 }214 }215 .task(id: frames) {216 index = 0217 matrices = frames.map { QRCodeMatrix(payload: $0) }218 }219 .task(id: TickKey(paused: paused, count: frames.count, interval: interval)) {220 guard !paused, frames.count > 1 else { return }221 while !Task.isCancelled {222 try? await Task.sleep(for: .seconds(interval))223 if Task.isCancelled { break }224 step(1)225 }226 }227 }228229 struct TickKey: Equatable {230 let paused: Bool231 let count: Int232 let interval: TimeInterval233 }234235 func step(_ delta: Int) {236 guard !frames.isEmpty else { return }237 index = (index + delta + frames.count) % frames.count238 }239240 func stepButton(_ systemImage: String, label: String, action: @escaping () -> Void) -> some View {241 Button(action: action) {242 Image(systemName: systemImage)243 .font(.body.weight(.semibold))244 .foregroundStyle(QColor.textPrimary)245 .frame(minWidth: 44, minHeight: 44)246 .contentShape(Rectangle())247 }248 .buttonStyle(.plain)249 .accessibilityLabel(label)250 }251}252253#if DEBUG254#Preview("QR codes") {255 ScrollView {256 VStack(spacing: 24) {257 QRCodeView(payload: "preview payload", label: "Preview code").frame(maxWidth: 240)258 AnimatedQRCodeView(frames: (1...5).map { "preview frame \($0) of 5" }).frame(maxWidth: 240)259 }260 .padding()261 }262 .qScreen()263}264#endif265