import SwiftUI struct ContentView: View { @StateObject private var cam = Camera() @AppStorage("griglia") private var griglia = false @AppStorage("classifiche") private var classifiche = true @AppStorage("zone") private var zone = true @AppStorage("nomiVale") private var nomiVale = "" @AppStorage("nomiPaolo") private var nomiPaolo = "" /// "classifica" (le due top 5) o "vs" (Paolo vs Vale: tre fasce, Vale in alto, scatola al centro, Paolo in basso) @AppStorage("formato") private var formato = "classifica" /// chi sta registrando nel formato vs: decide in quale fascia cade l'inquadratura @AppStorage("chi") private var chi = "paolo" @State private var focusPoint: CGPoint? @State private var focusLocked = false @State private var showExposure = false @State private var hideWork: DispatchWorkItem? @State private var pinchStart: CGFloat = 1 @State private var editingNames = false @State private var showSettings = false private let topH: CGFloat = 44 private let bottomH: CGFloat = 104 var body: some View { GeometryReader { geo in let W = geo.size.width let availH = geo.size.height - topH - bottomH let fw = min(W, availH * 9 / 16) let s = fw / ReelCanvas.w VStack(spacing: 0) { topBar.frame(height: topH) Spacer(minLength: 0) frame(fw: fw, s: s) Spacer(minLength: 0) bottomBar.frame(height: bottomH) } .frame(width: W, height: geo.size.height) .background(Color.black) .overlay(alignment: .top) { toast } } .background(Color.black.ignoresSafeArea()) .statusBarHidden() .persistentSystemOverlays(.hidden) .onAppear { cam.start() } .sheet(isPresented: $editingNames) { NomiSheet(vale: $nomiVale, paolo: $nomiPaolo) } .sheet(isPresented: $showSettings) { ImpostazioniSheet(cam: cam) } } // MARK: riquadro del reel private func frame(fw: CGFloat, s: CGFloat) -> some View { let fh = ReelCanvas.h * s let vs = formato == "vs" let fascia = Fasce.fascia(chi) // nel formato vs si vede solo la striscia centrale dell'inquadratura, messa nella sua fascia: il file resta // il 9:16 intero e al montaggio se ne prende la stessa striscia let shift = vs ? fascia.minY * s : 0 let ph = vs ? Fasce.h * s : fh return ZStack(alignment: .topLeading) { // sfondo del vs (la fascia dell'altro) sotto l'anteprima if vs { VsSfondo(s: s, chi: chi) } // Una sola anteprima, sempre la stessa vista: cambiando formato o persona cambiano solo misura e posizione. // Prima nel vs se ne creava un'altra, e agganciare un preview layer nuovo alla sessione bloccava la // fotocamera per un attimo (Paolo, 24/11: "l'app sembra bloccarsi"). // Nel vs è alta quanto la fascia: con l'aspect fill mostra la striscia centrale del 9:16 e non esce dalla // fascia (prima sbordava sopra le barre e si prendeva i tocchi). ZStack { preview if griglia { GridLines() } } .frame(width: fw, height: ph) .clipped() .offset(y: shift) if vs { VsSopra(s: s) } if zone { SafeZones(s: s) } if classifiche && !vs { Classifiche(s: s, nomiVale: split(nomiVale), nomiPaolo: split(nomiPaolo)) } if let fp = focusPoint { FocusSquare(locked: focusLocked).position(x: fp.x, y: fp.y + shift).allowsHitTesting(false) } if showExposure { ExposureSlider(value: cam.exposureBias) { v in cam.setBias(v); scheduleHide() } .frame(width: 44, height: fh * 0.4) .position(x: fw - 70 * s - 22, y: fh * 0.5) } // nella striscia di sinistra, che a tutto schermo si taglia: il livello del microfono MicMeter(level: cam.audioLevel, peak: cam.audioPeak) .frame(width: 10, height: 700 * s) .position(x: 28 * s, y: 960 * s) // in alto, nella zona dell'intestazione: tempo, lente, blocco AE/AF VStack(spacing: 4) { if cam.recording { HStack(spacing: 6) { Circle().fill(.red).frame(width: 9, height: 9) Text(Camera.mmss(cam.elapsed)).monospacedDigit() } .font(.system(size: 15, weight: .semibold)) .padding(.horizontal, 10).padding(.vertical, 4) .background(Color.red.opacity(0.35), in: Capsule()) } HStack(spacing: 5) { Text(cam.lensName) Text("·") Image(systemName: "mic.fill").font(.system(size: 9)) Text(cam.micName).lineLimit(1) } .font(.system(size: 11)) .foregroundStyle(.white.opacity(0.75)) .padding(.horizontal, 8).padding(.vertical, 3) .background(Color.black.opacity(0.35), in: Capsule()) if cam.wbLocked { Text("BIANCO BLOCCATO") .font(.system(size: 11, weight: .semibold)) .padding(.horizontal, 7).padding(.vertical, 3) .background(Color.white, in: RoundedRectangle(cornerRadius: 4)) .foregroundStyle(.black) } if cam.aeafLocked { Text("BLOCCO AE/AF") .font(.system(size: 11, weight: .semibold)) .padding(.horizontal, 7).padding(.vertical, 3) .background(amber, in: RoundedRectangle(cornerRadius: 4)) .foregroundStyle(.black) } } .frame(width: fw) .padding(.top, 14 * s + 4) .allowsHitTesting(false) // in basso, nella zona del nome: lo zoom zoomBar .frame(width: fw) .position(x: fw / 2, y: 1828 * s) } .frame(width: fw, height: fh) .clipped() .overlay(Rectangle().stroke(cam.recording ? Color.red : Color.white.opacity(0.18), lineWidth: cam.recording ? 2 : 1)) } private var preview: some View { CameraPreview(camera: cam, onTap: { p, dp in tapFocus(p, dp, lock: false) }, onLongPress: { p, dp in tapFocus(p, dp, lock: true) }, onPinch: { scale, st in if st == .began { pinchStart = cam.currentDisplayZoom } cam.setZoom(pinchStart * scale) }) } // MARK: barre private var topBar: some View { HStack(spacing: 16) { if cam.torchAvailable { Button { cam.toggleTorch() } label: { Image(systemName: cam.torchOn ? "flashlight.on.fill" : "flashlight.off.fill") .foregroundStyle(cam.torchOn ? amber : .white) } } Button { griglia.toggle() } label: { Image(systemName: "grid").foregroundStyle(griglia ? amber : .white) } if formato == "vs" { HStack(spacing: 0) { ForEach(["paolo", "vale"], id: \.self) { k in Button { chi = k } label: { Text(k == "paolo" ? "P" : "V") .font(.system(size: 13, weight: .bold)) .frame(width: 26, height: 26) .background(chi == k ? amber : Color.clear) .foregroundStyle(chi == k ? Color.black : Color.white) } } } .clipShape(RoundedRectangle(cornerRadius: 6)) .overlay(RoundedRectangle(cornerRadius: 6).stroke(amber.opacity(0.8))) .fixedSize() .disabled(cam.recording) } else { Button { classifiche.toggle() } label: { Image(systemName: "list.number").foregroundStyle(classifiche ? amber : .white) } } Button { zone.toggle() } label: { Image(systemName: "rectangle.dashed").foregroundStyle(zone ? amber : .white) } Spacer() Button { cam.refreshInputs(); showSettings = true } label: { Image(systemName: "gearshape").foregroundStyle(.white) } .disabled(cam.recording) if cam.aeafLocked || focusPoint != nil { Button { cam.resetFocus(); focusPoint = nil; showExposure = false } label: { Image(systemName: "scope").foregroundStyle(.white) } } Button { formato = formato == "vs" ? "classifica" : "vs"; focusPoint = nil } label: { Text(formato == "vs" ? "VS" : "TOP 5") .font(.system(size: 13, weight: .semibold)) .lineLimit(1) .fixedSize() .padding(.horizontal, 9).padding(.vertical, 5) .background(amber, in: RoundedRectangle(cornerRadius: 6)) .foregroundStyle(.black) } .disabled(cam.recording) Button { cam.setUse4K(!cam.use4K) } label: { Text(cam.use4K ? "4K" : "HD") .font(.system(size: 13, weight: .semibold)) .lineLimit(1) .fixedSize() .frame(minWidth: 26) .padding(.horizontal, 9).padding(.vertical, 5) .overlay(RoundedRectangle(cornerRadius: 6).stroke(cam.use4K ? amber : .white.opacity(0.6))) .foregroundStyle(cam.use4K ? amber : .white) } .disabled(cam.recording) } .font(.system(size: 20)) .padding(.horizontal, 20) } private var zoomBar: some View { HStack(spacing: 10) { ForEach(cam.presets, id: \.self) { p in let active = isActive(p) Button { cam.setZoom(p) } label: { Text(active ? label(cam.displayZoom) : label(p, short: true)) .font(.system(size: active ? 13 : 11, weight: .bold)) .foregroundStyle(active ? amber : .white) .frame(width: active ? 40 : 32, height: active ? 40 : 32) .background(Circle().fill(Color.black.opacity(0.45))) } } } .animation(.easeOut(duration: 0.15), value: cam.displayZoom) } private var bottomBar: some View { HStack { Button { if let u = URL(string: "photos-redirect://") { UIApplication.shared.open(u) } } label: { Group { if let t = cam.lastThumb { Image(uiImage: t).resizable().scaledToFill() } else { Color.white.opacity(0.1) } } .frame(width: 40, height: 64) .clipShape(RoundedRectangle(cornerRadius: 7)) .overlay(RoundedRectangle(cornerRadius: 7).stroke(.white.opacity(0.4))) .overlay { if cam.saving { ProgressView() } } } .frame(width: 70, alignment: .leading) Spacer() Button { cam.toggleRecord() } label: { ZStack { Circle().stroke(.white, lineWidth: 4).frame(width: 76, height: 76) RoundedRectangle(cornerRadius: cam.recording ? 7 : 31) .fill(Color.red) .frame(width: cam.recording ? 30 : 62, height: cam.recording ? 30 : 62) .animation(.easeInOut(duration: 0.2), value: cam.recording) } } .disabled(cam.saving) Spacer() VStack(spacing: 10) { Button { cam.flip() } label: { Image(systemName: "arrow.triangle.2.circlepath.camera") .font(.system(size: 22)) .foregroundStyle(cam.recording ? .gray : .white) } .disabled(cam.recording) if formato != "vs" { Button { editingNames = true } label: { Text("TITOLI") .font(.system(size: 10, weight: .bold)) .foregroundStyle(.white.opacity(0.8)) } } } .frame(width: 70, alignment: .trailing) } .padding(.horizontal, 26) } @ViewBuilder private var toast: some View { if let m = cam.message { Text(m) .font(.system(size: 14, weight: .semibold)) .padding(.horizontal, 14).padding(.vertical, 8) .background(.ultraThinMaterial, in: Capsule()) .padding(.top, 60) .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) { cam.message = nil } } } if !cam.authorized { Text("Consenti l'accesso alla fotocamera in Impostazioni › Reel") .font(.system(size: 15)) .multilineTextAlignment(.center) .padding() .padding(.top, 200) } } // MARK: azioni private func split(_ s: String) -> [String] { s.components(separatedBy: "\n") } private func tapFocus(_ p: CGPoint, _ dp: CGPoint, lock: Bool) { focusPoint = p focusLocked = lock showExposure = true cam.focus(at: dp, lock: lock) if lock { UIImpactFeedbackGenerator(style: .medium).impactOccurred() } scheduleHide() } private func scheduleHide() { hideWork?.cancel() let w = DispatchWorkItem { withAnimation { showExposure = false } if !cam.aeafLocked { focusPoint = nil } } hideWork = w DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: w) } private func isActive(_ p: CGFloat) -> Bool { let z = cam.displayZoom + 0.001 let lower = cam.presets.filter { $0 <= z }.max() ?? cam.presets.first! return lower == p } private func label(_ z: CGFloat, short: Bool = false) -> String { if z < 1 { return short ? ".5" : String(format: "%.1f×", z).replacingOccurrences(of: "0.", with: ".") } if abs(z - z.rounded()) < 0.05 { return "\(Int(z.rounded()))" + (short ? "" : "×") } return String(format: "%.1f×", z) } } /// I dieci titoli, solo per vedere l'ingombro vero delle righe in anteprima (nel video non finiscono). struct NomiSheet: View { @Binding var vale: String @Binding var paolo: String @Environment(\.dismiss) private var dismiss @State private var v: [String] = Array(repeating: "", count: 5) @State private var p: [String] = Array(repeating: "", count: 5) var body: some View { NavigationStack { Form { Section("Top 5 di Vale") { ForEach(0..<5, id: \.self) { i in TextField("Gioco \(i + 1)", text: $v[i]) } } Section("Top 5 di Paolo") { ForEach(0..<5, id: \.self) { i in TextField("Gioco \(i + 1)", text: $p[i]) } } Section { Button("Svuota", role: .destructive) { v = Array(repeating: "", count: 5); p = v } } footer: { Text("Solo per l'anteprima: nel video registrato le classifiche non ci sono, si aggiungono al montaggio.") } } .navigationTitle("Titoli") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Fatto") { vale = v.joined(separator: "\n") paolo = p.joined(separator: "\n") dismiss() } } } .onAppear { let a = vale.components(separatedBy: "\n"), b = paolo.components(separatedBy: "\n") for i in 0..<5 { v[i] = i < a.count ? a[i] : "" p[i] = i < b.count ? b[i] : "" } } } } } /// Impostazioni: da quale microfono registrare. Paolo e Vale hanno un microfono Bluetooth a testa (24/11). struct ImpostazioniSheet: View { @ObservedObject var cam: Camera @Environment(\.dismiss) private var dismiss var body: some View { NavigationStack { Form { Section { riga(uid: "", nome: "Automatico", sotto: "sceglie iOS (di solito l'ultimo collegato)", icona: "wand.and.stars") ForEach(cam.inputs) { i in riga(uid: i.id, nome: i.name, sotto: i.kind, icona: i.icon) } if !cam.micUID.isEmpty && !cam.inputs.contains(where: { $0.id == cam.micUID }) { Label("Il microfono scelto ora non è collegato: si registra con \(cam.micName)", systemImage: "exclamationmark.triangle") .font(.footnote) .foregroundStyle(.orange) } } header: { Text("Microfono") } footer: { Text("In uso adesso: \(cam.micName). Il microfono Bluetooth va acceso e collegato all'iPhone prima: compare qui da solo. La scelta resta salvata e torna appena il microfono si ricollega. Col Bluetooth l'app chiede la qualità piena; se il microfono non la regge, iOS lo usa in qualità telefonica. Se ha un ricevitore USB-C, collegato all'iPhone registra sempre al meglio.") } Section("Livello") { MicMeterOrizzontale(level: cam.audioLevel, peak: cam.audioPeak) .frame(height: 10) } Section { Toggle("Blocca il bianco durante la registrazione", isOn: $cam.lockWBWhileRecording) } header: { Text("Video") } footer: { Text("Come nella Fotocamera dell'iPhone: quando parte la registrazione il bilanciamento del bianco resta quello del momento fino alla fine. Inquadra un foglio bianco, avvia, poi togli il foglio.") } } .navigationTitle("Impostazioni") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Fatto") { dismiss() } } } } } private func riga(uid: String, nome: String, sotto: String, icona: String) -> some View { Button { cam.chooseMic(uid) } label: { HStack { Image(systemName: icona).frame(width: 28) VStack(alignment: .leading, spacing: 2) { Text(nome).foregroundStyle(.primary) Text(sotto).font(.caption).foregroundStyle(.secondary) } Spacer() if cam.micUID == uid { Image(systemName: "checkmark").foregroundStyle(amber) } } } } } struct MicMeterOrizzontale: View { var level: Float var peak: Float var body: some View { GeometryReader { g in let w = g.size.width ZStack(alignment: .leading) { Capsule().fill(Color.white.opacity(0.12)) Capsule() .fill(LinearGradient(stops: [ .init(color: .green, location: 0), .init(color: .green, location: 0.78), .init(color: .yellow, location: 0.86), .init(color: .red, location: 0.97), ], startPoint: .leading, endPoint: .trailing)) .mask(alignment: .leading) { Rectangle().frame(width: max(0, CGFloat((level + 60) / 60)) * w) } Rectangle().fill(.white).frame(width: 2).offset(x: max(0, CGFloat((peak + 60) / 60)) * w - 1) } } } }