SPB Git

Repository Public License

CameraScreen.swift 25.5 KB 462 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : App/Sources/Features/Camera/CameraScreen.swift10// Description      : The camera screen: viewfinder with overlays, top bar,11//                    parameter strip, dial, mode selector and shutter row.12//                    Portrait stacks the controls under the picture; a wide13//                    window (iPad landscape) moves them to a side column.14// Module           : Features15// Repository       : https://git.spboucher.ai/orix-camera16// Project Website  : https://www.orixlab.dev17// Created          : 2026-11-2118// Last Modified    : 2026-11-2119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : Proprietary, all rights reserved (see license file)85// License File     : LICENSE86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import ORIXDesign94import ORIXImaging95import SwiftUI9697struct CameraScreen: View {98    @Bindable var model: CameraModel99    let openLibrary: () -> Void100    let openSettings: () -> Void101102    @State private var showFormat = false103    @State private var showTools = false104    @State private var pinchStart: Double?105    @State private var flashOpacity = 0.0106    @Environment(\.accessibilityReduceMotion) private var reduceMotion107108    var body: some View {109        GeometryReader { proxy in110            let wide = proxy.size.width > proxy.size.height * 1.15111            ZStack {112                Instrument.body.ignoresSafeArea()113                if wide {114                    HStack(spacing: 0) {115                        monitorArea116                        VStack(spacing: 0) { topBar; Spacer(minLength: 0); deck }117                            .frame(width: min(400, proxy.size.width * 0.36))118                            .background(Instrument.body)119                    }120                } else {121                    VStack(spacing: 0) { topBar; monitorArea; deck }122                }123                phaseOverlay124            }125        }126        .background { keyboardShortcuts }127        .preferredColorScheme(.dark)128        .statusBarHidden()129        .persistentSystemOverlays(.hidden)130        .sheet(isPresented: $showFormat) { FormatSheet(model: model) }131        .sheet(isPresented: $showTools) { ToolsSheet(model: model) }132        .onChange(of: model.shutterFlash) {133            guard !reduceMotion else { return }134            flashOpacity = 0.85135            withAnimation(.easeOut(duration: 0.22)) { flashOpacity = 0 }136        }137    }138139    // MARK: Keyboard (iPad with a hardware keyboard)140141    /// Space or Return: shutter. 1–5: modes. ⌘L: library. ⌘,: settings. ⌘T: tools.142    private var keyboardShortcuts: some View {143        Group {144            Button("Shutter") { model.shutter() }.keyboardShortcut(.space, modifiers: [])145            Button("Shutter") { model.shutter() }.keyboardShortcut(.return, modifiers: [])146            ForEach(Array(CameraMode.allCases.enumerated()), id: \.offset) { index, mode in147                Button { model.setMode(mode) } label: { Text(mode.title) }148                    .keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: [])149            }150            Button("Library") { if !model.isRecording && !model.isBusy { openLibrary() } }.keyboardShortcut("l", modifiers: .command)151            Button("Settings") { if !model.isRecording { openSettings() } }.keyboardShortcut(",", modifiers: .command)152            Button("Tools") { showTools = true }.keyboardShortcut("t", modifiers: .command)153        }154        .opacity(0)155        .frame(width: 0, height: 0)156        .accessibilityHidden(true)157    }158159    // MARK: Top bar160161    private var formatTitle: String {162        if model.mode == .video {163            let option = VideoFormatOption(width: model.settings.videoWidth, height: model.settings.videoHeight, frameRate: model.settings.videoFrameRate)164            return "\(option.resolutionLabel) · \(Int(option.frameRate)) · \(model.settings.videoCodec.title)"165        }166        if model.mode == .auto { return "HEIC" }167        if model.mode == .creative { return String(localized: model.settings.creativeTool.title) }168        return model.settings.photoFormat.title169    }170171    private var storageText: String {172        if model.mode == .video { return ExposureMath.durationLabel(model.remainingRecordingTime) }173        return Measurement(value: Double(model.freeBytes), unit: UnitInformationStorage.bytes).converted(to: .gigabytes).value.formatted(.number.precision(.fractionLength(0))) + " GB"174    }175176    private var topBar: some View {177        HStack(spacing: 8) {178            if model.capabilities?.hasFlash == true, model.mode != .video, model.mode != .creative {179                InstrumentIconButton(symbol: model.settings.flash == .off ? "bolt.slash.fill" : (model.settings.flash == .auto ? "bolt.badge.automatic.fill" : "bolt.fill"),180                                     isActive: model.settings.flash != .off, label: "Flash") {181                    let all = FlashSetting.allCases182                    model.settings.flash = all[(all.firstIndex(of: model.settings.flash)! + 1) % all.count]; model.haptic()183                }184            }185            if model.capabilities?.hasTorch == true, model.mode == .video {186                InstrumentIconButton(symbol: model.live.torchOn ? "flashlight.on.fill" : "flashlight.off.fill", isActive: model.live.torchOn, label: "Torch") { model.toggleTorch() }187            }188            if model.mode == .auto || model.mode == .photo {189                InstrumentIconButton(symbol: "timer", isActive: model.settings.timerSeconds > 0, label: "Self-timer") {190                    model.settings.timerSeconds = model.settings.timerSeconds == 0 ? 3 : (model.settings.timerSeconds == 3 ? 10 : 0); model.haptic()191                }192                .overlay(alignment: .bottomTrailing) {193                    if model.settings.timerSeconds > 0 { Text("\(model.settings.timerSeconds)").font(.system(size: 9, weight: .heavy, design: .rounded)).foregroundStyle(Instrument.manual).offset(x: -4, y: -4) }194                }195                .accessibilityValue(model.settings.timerSeconds == 0 ? Text("Off") : Text("\(model.settings.timerSeconds) seconds"))196                .accessibilityIdentifier("timer")197            }198            Spacer(minLength: 4)199            Button { showFormat = true } label: {200                VStack(spacing: 1) {201                    Text(formatTitle).font(Instrument.readout(.caption)).foregroundStyle(model.mode != .auto && model.settings.photoFormat.isRAW && model.mode != .video ? Instrument.manual : Instrument.text)202                    Text(storageText).font(.system(size: 10, weight: .medium, design: .rounded).monospacedDigit()).foregroundStyle(Instrument.textFaint)203                }204                .padding(.horizontal, 12).frame(minHeight: 40)205                .background(Instrument.panel.opacity(0.72), in: Capsule())206                .frame(minHeight: 44)207            }208            .buttonStyle(.plain)209            .disabled(model.isRecording || model.isBusy || model.mode == .auto || model.mode == .creative)210            .accessibilityIdentifier("formatButton")211            .accessibilityLabel(Text("Capture format"))212            .accessibilityValue(Text("\(formatTitle), \(storageText) \(model.mode == .video ? String(localized: "of recording left") : String(localized: "free"))"))213            Spacer(minLength: 4)214            InstrumentIconButton(symbol: "slider.horizontal.3", label: "Tools") { showTools = true }.accessibilityIdentifier("toolsButton")215            InstrumentIconButton(symbol: "gearshape.fill", label: "Settings") { openSettings() }216                .disabled(model.isRecording).accessibilityIdentifier("settingsButton")217        }218        .padding(.horizontal, 12)219        .frame(height: 52)220    }221222    // MARK: Monitor223224    private var monitorArea: some View {225        GeometryReader { proxy in226            let rect = MonitorRenderer.imageRect(imageSize: model.displayedFrameSize, in: proxy.size, fill: false)227            ZStack(alignment: .topLeading) {228                MonitorView(model: model)229                // Everything below is laid out on the picture rectangle, so guides line up with pixels.230                ZStack {231                    if model.settings.grid != .none { GridOverlayView(grid: model.settings.grid) }232                    if model.settings.aspect != .native, model.mode != .video { AspectMaskView(guide: model.settings.aspect) }233                    if model.mode == .video, model.settings.aspect != .native { AspectMaskView(guide: model.settings.aspect) }234                    if model.settings.safeFraming { SafeFramingView() }235                    Color.clear.contentShape(Rectangle())236                        .onTapGesture(coordinateSpace: .local) { location in237                            model.tap(at: CGPoint(x: location.x / max(rect.width, 1), y: location.y / max(rect.height, 1)))238                        }239                        .gesture(MagnifyGesture()240                            .onChanged { value in241                                if pinchStart == nil { pinchStart = model.zoom }242                                model.setZoom((pinchStart ?? 1) * value.magnification)243                            }244                            .onEnded { _ in pinchStart = nil })245                        .accessibilityElement()246                        .accessibilityIdentifier("viewfinder")247                        .accessibilityLabel(Text("Viewfinder"))248                        .accessibilityHint(Text("Double tap to focus and expose at the centre"))249                        .accessibilityAction { model.tap(at: CGPoint(x: 0.5, y: 0.5)) }250                    if let point = model.focusReticle {251                        FocusReticle(adjusting: model.live.isAdjustingFocus)252                            .position(x: point.x * rect.width, y: point.y * rect.height)253                            .id(model.focusReticleID)254                    }255                    if model.settings.showLevel, let level = model.level { LevelView(reading: level) }256                    monitorCorners257                    if let countdown = model.countdown {258                        Text("\(countdown)").font(.system(size: 120, weight: .bold, design: .rounded)).foregroundStyle(.white).shadow(radius: 12)259                            .contentTransition(.numericText()).accessibilityLabel(Text("\(countdown) seconds"))260                    }261                    if let message = model.processingMessage {262                        HStack(spacing: 10) { ProgressView().tint(.white); Text(message).font(.callout.weight(.semibold)).foregroundStyle(.white) }263                            .padding(.horizontal, 18).padding(.vertical, 12).background(.black.opacity(0.7), in: Capsule())264                            .accessibilityIdentifier("processing")265                    }266                    Color.black.opacity(flashOpacity).allowsHitTesting(false)267                }268                .frame(width: rect.width, height: rect.height)269                .clipped()270                .offset(x: rect.minX, y: rect.minY)271            }272        }273    }274275    private var monitorCorners: some View {276        VStack(spacing: 0) {277            HStack(alignment: .top, spacing: 8) {278                if model.settings.showHistogram {279                    HistogramView(curves: model.histogramCurves, style: model.settings.histogramStyle, highlightClipping: model.snapshot.histogram.highlightClipping,280                                  shadowClipping: model.snapshot.histogram.shadowClipping, expanded: model.settings.histogramExpanded || model.mode == .analysis)281                        .onTapGesture { model.settings.histogramStyle = model.settings.histogramStyle == .luma ? .rgb : .luma; model.haptic() }282                        .onLongPressGesture { withAnimation(.snappy) { model.settings.histogramExpanded.toggle() } }283                        .accessibilityAction { model.settings.histogramStyle = model.settings.histogramStyle == .luma ? .rgb : .luma }284                }285                Spacer(minLength: 0)286                VStack(alignment: .trailing, spacing: 6) {287                    if model.isRecording {288                        MonitorBadge(text: (model.recordingKind == .timeLapse ? String(localized: "LAPSE ") : "REC ") + ExposureMath.timecode(model.recordingDuration), symbol: "circle.fill", color: Instrument.record)289                            .accessibilityIdentifier("recBadge")290                        if model.recordingDropped > 0 { MonitorBadge(text: String(localized: "\(model.recordingDropped) dropped"), symbol: "exclamationmark.triangle.fill", color: Instrument.warn) }291                    }292                    if model.accumulating {293                        MonitorBadge(text: String(localized: "\(model.accumulationFrames) frames"), symbol: "square.stack.3d.up.fill", color: Instrument.manual)294                            .accessibilityIdentifier("accumulationBadge")295                    }296                    if let remaining = model.intervalRemaining { MonitorBadge(text: String(localized: "\(remaining) left"), symbol: "timer", color: Instrument.manual) }297                    if model.burstCount > 0 { MonitorBadge(text: "\(model.burstCount)", symbol: "square.stack.fill", color: Instrument.manual) }298                    if model.pressure != .nominal {299                        MonitorBadge(text: String(localized: "HEAT \(model.pressure.rawValue.uppercased())"), symbol: "thermometer.high", color: model.pressure == .fair ? Instrument.warn : Instrument.record)300                    }301                    if model.live.stabilizationActive { MonitorBadge(text: String(localized: "STAB"), symbol: "hand.raised.fill") }302                    if model.isSynthetic {303                        // The full wording when it fits on one line, a short form beside a large histogram.304                        ViewThatFits(in: .horizontal) {305                            MonitorBadge(text: String(localized: "SIMULATOR · TEST SCENE"), color: Instrument.accent).fixedSize()306                            MonitorBadge(text: String(localized: "SIM"), color: Instrument.accent).fixedSize()307                        }308                        .accessibilityElement(children: .combine)309                        .accessibilityIdentifier("syntheticBadge")310                    }311                    if model.mode != .auto, model.mode != .video, model.settings.captureLookID != nil || (model.mode == .video && model.settings.monitorLookID != nil) {312                        MonitorBadge(text: String(localized: "LOOK"), symbol: "camera.filters")313                    }314                }315            }316            Spacer(minLength: 0)317            VStack(alignment: .leading, spacing: 6) {318                if model.mode == .auto { HintChips(hints: model.hints) }319                HStack(spacing: 6) {320                    if model.mode == .video, model.settings.recordAudio { AudioMeter(levels: model.audio) }321                    if model.mode != .auto, model.settings.zebra.highlightsEnabled {322                        MonitorBadge(text: "Z \(Int(model.settings.zebra.highlightThreshold)) % · " + model.snapshot.zebraHighlights.formatted(.percent.precision(.fractionLength(1))), symbol: "line.diagonal")323                            .accessibilityIdentifier("zebraBadge")324                    }325                }326            }327            .frame(maxWidth: .infinity, alignment: .leading)328            if model.backLenses.count > 1 {329                LensSelector(lenses: model.backLenses, selectedID: model.capabilities?.lens.id) { model.selectLens($0) }330                    .disabled(model.isRecording || model.isBusy).padding(.top, 6)331            }332        }333        .padding(10)334        .overlay(alignment: .top) {335            if let toast = model.toast {336                Text(toast.text)337                    .font(.footnote.weight(.semibold)).foregroundStyle(.white).multilineTextAlignment(.center)338                    .padding(.horizontal, 14).padding(.vertical, 9)339                    .background((toast.style == .failure ? Instrument.record : (toast.style == .warning ? Color(hex: 0x8A5A00) : Color.black)).opacity(0.86), in: RoundedRectangle(cornerRadius: 14, style: .continuous))340                    .padding(.top, 70).padding(.horizontal, 24)341                    .transition(.move(edge: .top).combined(with: .opacity))342                    .accessibilityIdentifier("toast")343                    .accessibilityAddTraits(.isStaticText)344            }345        }346        .animation(.snappy(duration: 0.25), value: model.toast)347    }348349    // MARK: Bottom deck350351    private var shutterLook: ShutterButton.Look {352        if model.isRecording { return .videoRecording }353        if model.accumulating || model.intervalRemaining != nil || model.countdown != nil { return .stop }354        if model.processingMessage != nil { return .busy }355        if model.mode == .video || (model.mode == .creative && model.settings.creativeTool == .timeLapse) { return .videoIdle }356        return .photo357    }358359    private var deck: some View {360        VStack(spacing: 6) {361            if model.mode == .analysis { AnalysisPanel(model: model) }362            if let dial = model.activeDial, model.mode != .auto { DialPanel(model: model, dial: dial) }363            if model.mode == .creative { CreativeDeck(model: model) }364            if model.mode == .auto {365                // Auto keeps one control: exposure compensation.366                HStack(spacing: 10) {367                    Image(systemName: "plusminus.circle").foregroundStyle(Instrument.textDim).accessibilityHidden(true)368                    Slider(value: Binding(get: { model.bias }, set: { model.setBias($0) }), in: -2...2, step: 1.0 / 3)369                        .tint(Instrument.manual).accessibilityIdentifier("autoBias").accessibilityLabel(Text("Exposure compensation"))370                    Text(String(format: "%+.1f", model.bias)).font(Instrument.readout()).foregroundStyle(abs(model.bias) > 0.01 ? Instrument.manual : Instrument.textDim).frame(width: 40)371                }372                .padding(.horizontal, 20)373            } else {374                ParameterStrip(model: model)375            }376            ModeSelector(selected: model.mode, enabled: !model.isRecording && !model.isBusy) { model.setMode($0) }377            HStack {378                Button(action: openLibrary) {379                    ZStack {380                        RoundedRectangle(cornerRadius: 10, style: .continuous).fill(Instrument.panelRaised)381                        if let image = model.lastThumbnail {382                            Image(uiImage: image).resizable().scaledToFill()383                        } else {384                            Image(systemName: "photo.on.rectangle").foregroundStyle(Instrument.textDim)385                        }386                    }387                    .frame(width: 52, height: 52)388                    .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))389                    .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(.white.opacity(0.35), lineWidth: 1))390                }391                .buttonStyle(.plain)392                .disabled(model.isRecording || model.isBusy)393                .accessibilityIdentifier("libraryButton")394                .accessibilityLabel(Text("Library"))395                .accessibilityValue(Text("\(model.libraryCount) items"))396                Spacer()397                ShutterButton(look: shutterLook,398                              progress: model.accumulating && model.accumulationTarget > 0 ? Double(model.accumulationFrames) / Double(model.accumulationTarget) : nil,399                              action: { model.shutter() },400                              onHoldStart: model.mode == .photo || model.mode == .auto ? { model.startBurst() } : nil,401                              onHoldEnd: { model.endBurst() })402                Spacer()403                InstrumentIconButton(symbol: "arrow.triangle.2.circlepath.camera.fill", label: "Switch between front and back camera") { model.flipCamera() }404                    .frame(width: 52, height: 52)405                    .disabled(model.isRecording || model.isBusy)406                    .accessibilityIdentifier("flipButton")407            }408            .padding(.horizontal, 28)409            .padding(.bottom, 10)410        }411        .padding(.top, 6)412        .animation(.snappy(duration: 0.22), value: model.activeDial)413        .animation(.snappy(duration: 0.22), value: model.mode)414    }415416    // MARK: Session states417418    @ViewBuilder private var phaseOverlay: some View {419        switch model.phase {420        case .denied:421            StateCard(symbol: "camera.fill", title: "Camera access is off",422                      message: "ORIX Camera cannot show or capture anything without the camera. Turn it on in Settings. Your library stays available.",423                      primary: ("Open Settings", { if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } }),424                      secondary: ("Open library", openLibrary))425                .accessibilityIdentifier("deniedCard")426        case .failed(let message):427            StateCard(symbol: "exclamationmark.triangle.fill", title: "The camera could not start", message: LocalizedStringKey(message),428                      primary: ("Try again", { Task { await model.reconfigure() } }), secondary: ("Open library", openLibrary))429        case .interrupted(let reason):430            StateCard(symbol: "pause.circle.fill", title: "Camera paused", message: LocalizedStringKey(reason), primary: nil, secondary: nil)431        case .needsPermission, .starting, .idle:432            ProgressView().tint(.white).accessibilityLabel(Text("Starting the camera"))433        case .running:434            EmptyView()435        }436    }437}438439struct StateCard: View {440    let symbol: String441    let title: LocalizedStringKey442    let message: LocalizedStringKey443    let primary: (LocalizedStringKey, () -> Void)?444    let secondary: (LocalizedStringKey, () -> Void)?445446    var body: some View {447        VStack(spacing: 14) {448            Image(systemName: symbol).font(.system(size: 34, weight: .semibold)).foregroundStyle(Instrument.accent)449            Text(title).font(.title3.weight(.bold)).foregroundStyle(Instrument.text).multilineTextAlignment(.center)450            Text(message).font(.callout).foregroundStyle(Instrument.textDim).multilineTextAlignment(.center)451            if let primary { Button(primary.0, action: primary.1).buttonStyle(.orixPrimary) }452            if let secondary { Button(secondary.0, action: secondary.1).buttonStyle(.orixSecondary) }453        }454        .padding(24)455        .frame(maxWidth: 380)456        .background(Instrument.panel, in: RoundedRectangle(cornerRadius: 24, style: .continuous))457        .overlay(RoundedRectangle(cornerRadius: 24, style: .continuous).strokeBorder(Instrument.hairline))458        .padding(24)459        .environment(\.orixAccent, .camera)460    }461}462
Files main
Menu

Theme