Repository Public License
1// ORIX Alarm2// File: App/Features/Missions/QRTagViews.swift3// Description: QR tag management: list, picker mode, registration by scanning, deletion, and a locally generated printable code.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import CoreImage9import CoreImage.CIFilterBuiltins10import SwiftUI11import UIKit1213/// Lists registered QR tags and lets the user add or remove them. `selection` (optional) picks a tag for a mission step.14/// Present it inside a `NavigationStack` (pushed, or as the root of a sheet) to get its title.15struct QRTagManagerView: View {16 @Environment(AppModel.self) private var model17 var selection: Binding<UUID?>? = nil1819 @State private var showAdd = false20 @State private var showPrint = false21 @State private var pendingDelete: QRTag?2223 var body: some View {24 ScrollView {25 VStack(spacing: 14) {26 Text(selection == nil27 ? "Place a QR code somewhere you have to walk to. A QR Escape mission ends only when that exact code is scanned."28 : "Choose the code this mission asks for. You will have to walk to it and scan it.")29 .font(.orixBody).foregroundStyle(Theme.textSecondary).frame(maxWidth: .infinity, alignment: .leading)3031 if model.qrTags.isEmpty {32 VStack(spacing: 10) {33 Image(systemName: "qrcode.viewfinder").font(.system(size: 44)).foregroundStyle(Theme.nightGradient).accessibilityHidden(true)34 Text("No QR code yet").font(.orixHeadline)35 Text("Any QR code works: a product box, a sticker, or one you print from here.")36 .font(.orixCaption).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center)37 }38 .frame(maxWidth: .infinity).glassCard(padding: 22)39 .accessibilityElement(children: .combine).accessibilityIdentifier("qrtags.empty")40 } else {41 Overline(selection == nil ? "Registered codes" : "Your codes")42 ForEach(model.qrTags) { tag in row(tag) }43 }4445 Button { showAdd = true } label: { Label("Add a place", systemImage: "plus.viewfinder") }46 .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("qrtags.add").padding(.top, 6)47 Button { showPrint = true } label: { Label("Print a code", systemImage: "printer") }48 .buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("qrtags.print")4950 Label("Only a fingerprint (SHA-256) of each code is kept on this iPhone. The content of the code and camera images are never stored.", systemImage: "lock.shield")51 .font(.orixCaption).foregroundStyle(Theme.textTertiary).frame(maxWidth: .infinity, alignment: .leading).padding(.top, 4)52 }53 .padding(20)54 }55 .navigationTitle("QR codes")56 .navigationBarTitleDisplayMode(.inline)57 .orixScreen()58 .sheet(isPresented: $showAdd) {59 QRTagAddView { tag in selection?.wrappedValue = tag.id }60 }61 .sheet(isPresented: $showPrint) { QRPrintView() }62 .confirmationDialog("Delete this QR code?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), titleVisibility: .visible, presenting: pendingDelete) { tag in63 Button("Delete \(tag.label)", role: .destructive) {64 if selection?.wrappedValue == tag.id { selection?.wrappedValue = nil }65 model.removeQRTag(tag.id); Haptics.play(.warning)66 }67 Button("Cancel", role: .cancel) {}68 } message: { _ in69 Text("Missions that ask for this code will offer an alternative mission until you choose another code.")70 }71 }7273 private func row(_ tag: QRTag) -> some View {74 let isSelected = selection?.wrappedValue == tag.id75 return HStack(spacing: 12) {76 Button {77 guard let selection else { return }78 selection.wrappedValue = tag.id; Haptics.play(.selection)79 } label: {80 HStack(spacing: 12) {81 if selection != nil {82 Image(systemName: isSelected ? "checkmark.circle.fill" : "circle").font(.title2)83 .foregroundStyle(isSelected ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.textTertiary))84 }85 Image(systemName: "qrcode").font(.title3).foregroundStyle(Theme.azure)86 .frame(width: 44, height: 44).background(Theme.azure.opacity(0.16), in: RoundedRectangle(cornerRadius: 12, style: .continuous))87 VStack(alignment: .leading, spacing: 2) {88 Text(tag.label.isEmpty ? String(localized: "QR code") : tag.label).font(.orixHeadline).foregroundStyle(Theme.textPrimary).lineLimit(2)89 Text(isSelected ? "Selected · added \(tag.createdAt.formatted(date: .abbreviated, time: .omitted))" : "Added \(tag.createdAt.formatted(date: .abbreviated, time: .omitted))")90 .font(.orixCaption).foregroundStyle(Theme.textSecondary)91 }92 Spacer(minLength: 0)93 }94 .contentShape(Rectangle())95 }96 .buttonStyle(.plain)97 .disabled(selection == nil)98 .accessibilityAddTraits(isSelected ? .isSelected : [])99 .accessibilityIdentifier("qrtags.row.\(tag.label)")100 Button { pendingDelete = tag } label: {101 Image(systemName: "trash").font(.body).foregroundStyle(Theme.danger).frame(width: 44, height: 44)102 }103 .accessibilityLabel("Delete \(tag.label)")104 .accessibilityIdentifier("qrtags.delete.\(tag.label)")105 }106 .glassCard(padding: 12, tint: isSelected ? Theme.sunrise : nil)107 }108}109110/// Registration: name the place, then scan the code that sits there.111struct QRTagAddView: View {112 @Environment(AppModel.self) private var model113 @Environment(\.dismiss) private var dismiss114 var onAdded: (QRTag) -> Void = { _ in }115116 private enum Step { case name, scan, done }117 @State private var step: Step = .name118 @State private var label = ""119 @State private var scanner = QRScanner()120 @State private var feedback: QRScanFeedback = .none121 @State private var problem: String?122 @FocusState private var nameFocused: Bool123124 private static let suggestions: [(String, String)] = [125 (String(localized: "Bathroom"), "shower.fill"), (String(localized: "Kitchen"), "fork.knife"),126 (String(localized: "Coffee machine"), "cup.and.saucer.fill"), (String(localized: "Desk"), "desktopcomputer"),127 ]128 private var trimmed: String { label.trimmingCharacters(in: .whitespacesAndNewlines) }129130 var body: some View {131 NavigationStack {132 Group {133 switch step {134 case .name: naming135 case .scan, .done: scanning136 }137 }138 .padding(20)139 .navigationTitle(step == .name ? "New place" : "Scan the code")140 .navigationBarTitleDisplayMode(.inline)141 .toolbar {142 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() }.accessibilityIdentifier("qrtags.add.cancel") }143 }144 .orixScreen()145 }146 .preferredColorScheme(.dark)147 .onDisappear { scanner.stop() }148 }149150 private var naming: some View {151 VStack(alignment: .leading, spacing: 16) {152 Text("Where is the QR code?").font(.orixTitle)153 Text("Pick a spot far enough from your bed that you have to get up.").font(.orixBody).foregroundStyle(Theme.textSecondary)154 TextField("Name of the place", text: $label)155 .font(.orixBody).textInputAutocapitalization(.sentences).submitLabel(.continue)156 .focused($nameFocused)157 .padding(.horizontal, 16).frame(minHeight: 54)158 .background(Theme.surfaceRaised, in: RoundedRectangle(cornerRadius: 16, style: .continuous))159 .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Theme.hairline))160 .onSubmit { if !trimmed.isEmpty { startScan() } }161 .onChange(of: label) { _, value in if value.count > 40 { label = String(value.prefix(40)) } }162 .accessibilityIdentifier("qrtags.add.name")163 Overline("Suggestions")164 LazyVGrid(columns: [GridItem(.adaptive(minimum: 140), spacing: 8)], alignment: .leading, spacing: 8) {165 ForEach(Self.suggestions, id: \.0) { item in166 Chip(title: item.0, symbol: item.1, isSelected: trimmed == item.0) { label = item.0; Haptics.play(.selection) }167 .frame(minHeight: 44).frame(maxWidth: .infinity, alignment: .leading)168 .accessibilityIdentifier("qrtags.add.suggestion.\(item.0)")169 }170 }171 Spacer()172 Button("Continue") { startScan() }173 .buttonStyle(PrimaryButtonStyle()).disabled(trimmed.isEmpty).accessibilityIdentifier("qrtags.add.continue")174 }175 }176177 private var scanning: some View {178 VStack(spacing: 14) {179 Text(step == .done ? "\(trimmed) is registered." : "Point the camera at the QR code placed at: \(trimmed).")180 .font(.orixBody).foregroundStyle(step == .done ? Theme.success : Theme.textSecondary)181 .frame(maxWidth: .infinity, alignment: .leading)182 if step == .done {183 VStack(spacing: 14) {184 Image(systemName: "checkmark.seal.fill").font(.system(size: 64)).foregroundStyle(Theme.success).accessibilityHidden(true)185 Text("Code registered").font(.orixTitle)186 Text("Only its fingerprint is kept on this iPhone.").font(.orixCaption).foregroundStyle(Theme.textSecondary)187 }188 .frame(maxWidth: .infinity, maxHeight: .infinity).glassCard(padding: 22)189 .accessibilityElement(children: .combine).accessibilityIdentifier("qrtags.add.done")190 } else {191 QRScannerPanel(scanner: scanner, feedback: feedback)192 }193 if let problem {194 Label(problem, systemImage: "exclamationmark.triangle.fill").font(.orixCaption).foregroundStyle(Theme.gold)195 .frame(maxWidth: .infinity, alignment: .leading).accessibilityIdentifier("qrtags.add.problem")196 }197 if scanner.state.isUnavailable, step == .scan {198 Text("You can register a code later from a device with a working camera.").font(.orixCaption).foregroundStyle(Theme.textTertiary)199 }200 #if DEBUG201 if let payload = QRDebug.fakePayload, step == .scan {202 Label("Debug build only", systemImage: "ladybug.fill").font(.orixOverline).foregroundStyle(Theme.gold)203 Button("Simulate scan") { register(payload) }.buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("qrtags.add.debugScan")204 }205 #endif206 Button("Change the name") { scanner.stop(); feedback = .none; problem = nil; step = .name }207 .font(.orixCaption).foregroundStyle(Theme.textSecondary).frame(minHeight: 44)208 .opacity(step == .scan ? 1 : 0).disabled(step != .scan)209 }210 }211212 private func startScan() {213 guard !trimmed.isEmpty else { return }214 nameFocused = false215 problem = nil; feedback = .none216 step = .scan217 scanner.onCode = { register($0) }218 scanner.prepare()219 }220221 /// Single registration path for the camera and for the debug hook.222 private func register(_ payload: String) {223 guard step == .scan else { return }224 if let existing = model.qrTags.first(where: { model.qrPayloadMatches(payload, tagID: $0.id) }) {225 problem = String(localized: "This code is already registered as “\(existing.label)”. Scan a different code.")226 withAnimation(.snappy) { feedback = .wrong }227 Haptics.play(.failure)228 Task {229 try? await Task.sleep(for: .seconds(2.5))230 if step == .scan { withAnimation(.smooth) { feedback = .none } }231 }232 return233 }234 let tag = model.addQRTag(label: trimmed, payload: payload)235 scanner.stop()236 problem = nil237 withAnimation(.snappy) { feedback = .accepted; step = .done }238 Haptics.play(.success)239 onAdded(tag)240 Task {241 try? await Task.sleep(for: .milliseconds(900))242 dismiss()243 }244 }245}246247/// Generates a QR code on the device from a random token so that it can be printed or shown on another screen, then scanned to register it.248struct QRPrintView: View {249 @Environment(\.dismiss) private var dismiss250 @State private var code: QRCodeImage?251252 var body: some View {253 NavigationStack {254 ScrollView {255 VStack(spacing: 18) {256 Text("No spare QR code at home? Print this one, or keep it on another screen, and put it where you want to walk to.")257 .font(.orixBody).foregroundStyle(Theme.textSecondary).frame(maxWidth: .infinity, alignment: .leading)258 if let code {259 Image(uiImage: code.image).interpolation(.none).resizable().scaledToFit()260 .frame(maxWidth: 260)261 .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))262 .shadow(color: Theme.violet.opacity(0.5), radius: 24)263 .accessibilityLabel("Generated QR code")264 .accessibilityIdentifier("qrprint.image")265 ShareLink(item: code.fileURL, preview: SharePreview("ORIX Alarm QR code", image: Image(uiImage: code.image))) {266 Label("Print or share", systemImage: "square.and.arrow.up")267 }268 .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("qrprint.share")269 } else {270 Label("The code could not be generated on this device.", systemImage: "exclamationmark.triangle.fill")271 .font(.orixCaption).foregroundStyle(Theme.gold)272 }273 Button { regenerate(); Haptics.play(.selection) } label: { Label("Generate another code", systemImage: "arrow.triangle.2.circlepath") }274 .buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("qrprint.regenerate")275 VStack(alignment: .leading, spacing: 8) {276 Overline("Then")277 Label("Stick the printed code in place.", systemImage: "1.circle.fill")278 Label("Come back here and choose Add a place.", systemImage: "2.circle.fill")279 Label("Scan the code to register it.", systemImage: "3.circle.fill")280 }281 .font(.orixCaption).foregroundStyle(Theme.textSecondary).frame(maxWidth: .infinity, alignment: .leading).glassCard(padding: 16)282 Text("The code holds a random token created on this iPhone. It is not registered until you scan it.")283 .font(.orixCaption).foregroundStyle(Theme.textTertiary).frame(maxWidth: .infinity, alignment: .leading)284 }285 .padding(20)286 }287 .navigationTitle("Print a code")288 .navigationBarTitleDisplayMode(.inline)289 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() }.accessibilityIdentifier("qrprint.done") } }290 .orixScreen()291 }292 .preferredColorScheme(.dark)293 .onAppear { if code == nil { regenerate() } }294 }295296 private func regenerate() { code = QRCodeImage.make(payload: "ORIX-ALARM-" + UUID().uuidString) }297}298299/// A QR code rendered with Core Image, with a white quiet zone, plus a PNG copy in the temporary folder for the share sheet.300struct QRCodeImage {301 let image: UIImage302 let fileURL: URL303304 static func make(payload: String, side: CGFloat = 1024) -> QRCodeImage? {305 let filter = CIFilter.qrCodeGenerator()306 filter.message = Data(payload.utf8)307 filter.correctionLevel = "M"308 guard let output = filter.outputImage, output.extent.width > 0,309 let modules = CIContext().createCGImage(output, from: output.extent) else { return nil }310 let format = UIGraphicsImageRendererFormat()311 format.scale = 1; format.opaque = true312 let image = UIGraphicsImageRenderer(size: CGSize(width: side, height: side), format: format).image { context in313 UIColor.white.setFill()314 context.fill(CGRect(x: 0, y: 0, width: side, height: side))315 context.cgContext.interpolationQuality = .none316 let margin = side * 0.09317 UIImage(cgImage: modules).draw(in: CGRect(x: margin, y: margin, width: side - 2 * margin, height: side - 2 * margin))318 }319 guard let data = image.pngData() else { return nil }320 let url = FileManager.default.temporaryDirectory.appendingPathComponent("ORIX-Alarm-QR-code.png")321 do { try data.write(to: url, options: .atomic) } catch { return nil }322 return QRCodeImage(image: image, fileURL: url)323 }324}325