SPB Git

Repository Public

WorkspacePanels.swift 19.7 KB 345 lines swift

1// SP Lecture Studio2// File: Apps/LectureStudio/Shared/Workspace/WorkspacePanels.swift3// Description: Workspace panels: Mac tool palette, camera preview overlay, the preflight test, and the automatic pause / stop policy editor.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import AVFoundation9import LectureCore10import LectureCapture11import LectureRender12import LectureStorage1314#if os(macOS)15struct MacToolPalette: View {16    let session: ProjectSession17    @State private var showStyle = false18    private let primary: [ToolKind] = [.pen, .marker, .eraser, .laser, .pan]19    private let shapes: [ToolKind] = [.line, .arrow, .rectangle, .ellipse]2021    var body: some View {22        HStack(spacing: 4) {23            ForEach(primary) { kind in toolButton(kind) }24            Menu {25                ForEach(shapes) { kind in Button { session.tool.kind = kind } label: { Label(kind.title, systemImage: kind.symbol) } }26                Button { session.tool.kind = .pencil } label: { Label(ToolKind.pencil.title, systemImage: ToolKind.pencil.symbol) }27            } label: { Image(systemName: shapes.contains(session.tool.kind) || session.tool.kind == .pencil ? session.tool.kind.symbol : "square.on.circle") }28            .menuStyle(.borderlessButton).fixedSize().help("Formes").accessibilityLabel("Formes")29            Divider().frame(height: 22)30            Button { showStyle.toggle() } label: {31                HStack(spacing: 6) {32                    Circle().fill(Color(session.tool.color)).frame(width: 18, height: 18).overlay(Circle().strokeBorder(Color.primary.opacity(0.3)))33                    Capsule().fill(Color.primary).frame(width: 18, height: CGFloat(2 + session.tool.thickness * 2))34                }.frame(height: 32).padding(.horizontal, 6)35            }36            .buttonStyle(.plain).help("Couleur et épaisseur").accessibilityLabel("Couleur et épaisseur")37            .popover(isPresented: $showStyle, arrowEdge: .top) { stylePopover }38        }39    }4041    private func toolButton(_ kind: ToolKind) -> some View {42        Button { session.tool.kind = kind; if kind != .laser { session.hidePointer() } } label: { Image(systemName: kind.symbol) }43            .buttonStyle(IconButtonStyle(active: session.tool.kind == kind))44            .help(kind.title).accessibilityLabel(kind.title).accessibilityAddTraits(session.tool.kind == kind ? .isSelected : [])45            .accessibilityIdentifier("tool.\(kind.rawValue)")46    }4748    private var stylePopover: some View {49        VStack(alignment: .leading, spacing: 12) {50            SectionTitle("Couleur")51            HStack(spacing: 8) {52                ForEach(RGBAColor.palette, id: \.hex) { c in53                    Button { session.tool.color = c } label: {54                        Circle().fill(Color(c)).frame(width: 26, height: 26)55                            .overlay(Circle().strokeBorder(session.tool.color == c ? DS.accent : Color.primary.opacity(0.25), lineWidth: session.tool.color == c ? 3 : 1))56                    }.buttonStyle(.plain).accessibilityLabel(Text(verbatim: c.hex))57                }58            }59            SectionTitle("Épaisseur")60            HStack(spacing: 10) {61                ForEach(0..<5, id: \.self) { i in62                    Button { session.tool.thickness = i } label: {63                        Circle().fill(Color.primary).frame(width: CGFloat(5 + i * 4), height: CGFloat(5 + i * 4)).frame(width: 30, height: 30)64                            .background(session.tool.thickness == i ? DS.accent.opacity(0.25) : .clear, in: RoundedRectangle(cornerRadius: 6))65                    }.buttonStyle(.plain).accessibilityLabel("Épaisseur \(i + 1)")66                }67            }68        }69        .padding(14)70    }71}72#endif7374// MARK: Camera overlay7576struct CameraOverlay: View {77    let session: ProjectSession78    let settings: AppSettings79    var body: some View {80        GeometryReader { geo in81            let placement = settings.stored.cameraPlacement82            let w = min(geo.size.width * CGFloat(placement.size) * 1.2, 260), h = w * 9 / 1683            CameraPreview(session: session.camera.session)84                .frame(width: w, height: h)85                .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))86                .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(.white.opacity(0.8), lineWidth: 1.5))87                .shadow(radius: 6)88                .padding(10)89                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: alignment(placement.corner))90                .contextMenu {91                    ForEach(CameraCorner.allCases, id: \.self) { c in92                        Button { settings.stored.cameraPlacement.corner = c } label: { Text(Self.name(c)) }93                    }94                }95                .allowsHitTesting(true)96                .accessibilityLabel("Aperçu de la caméra")97        }98        .allowsHitTesting(false)99    }100    private func alignment(_ c: CameraCorner) -> Alignment {101        switch c { case .topLeft: .topLeading; case .topRight: .topTrailing; case .bottomLeft: .bottomLeading; case .bottomRight: .bottomTrailing }102    }103    static func name(_ c: CameraCorner) -> LocalizedStringKey {104        switch c { case .topLeft: "En haut à gauche"; case .topRight: "En haut à droite"; case .bottomLeft: "En bas à gauche"; case .bottomRight: "En bas à droite" }105    }106}107108#if os(macOS)109struct CameraPreview: NSViewRepresentable {110    let session: AVCaptureSession111    func makeNSView(context: Context) -> NSView {112        let v = NSView(); v.wantsLayer = true113        let layer = AVCaptureVideoPreviewLayer(session: session); layer.videoGravity = .resizeAspectFill114        v.layer = layer115        return v116    }117    func updateNSView(_ nsView: NSView, context: Context) {}118}119#else120struct CameraPreview: UIViewRepresentable {121    let session: AVCaptureSession122    final class PreviewView: UIView {123        override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }124        var preview: AVCaptureVideoPreviewLayer { layer as! AVCaptureVideoPreviewLayer }125    }126    func makeUIView(context: Context) -> PreviewView { let v = PreviewView(); v.preview.session = session; v.preview.videoGravity = .resizeAspectFill; return v }127    func updateUIView(_ uiView: PreviewView, context: Context) {}128}129#endif130131// MARK: Preflight132133struct PreflightSheet: View {134    let session: ProjectSession135    let settings: AppSettings136    @Environment(\.dismiss) private var dismiss137    @State private var items: [PreflightItem] = []138    @State private var running = false139    @State private var progress = 0.0140    @State private var level = -120.0141    @State private var peak: Float = 0142    @State private var sampler: LevelSampler?143    @State private var task: Task<Void, Never>?144    @State private var inputs: [AudioInputDevice] = []145    static let testSeconds = 30.0146147    var body: some View {148        NavigationStack {149            Form {150                Section {151                    Picker("Microphone", selection: Binding(get: { settings.stored.microphoneID ?? "" }, set: { settings.stored.microphoneID = $0.isEmpty ? nil : $0 })) {152                        Text("Par défaut du système").tag("")153                        ForEach(inputs) { d in Text(verbatim: d.name).tag(d.id) }154                    }155                    Stepper(value: Binding(get: { settings.stored.plannedMinutes }, set: { settings.stored.plannedMinutes = $0 }), in: 10...240, step: 10) {156                        Text("Durée prévue : \(Int(settings.stored.plannedMinutes)) min")157                    }158                } header: { Text("Séance") }159160                Section {161                    if running {162                        VStack(alignment: .leading, spacing: 8) {163                            Text("Parlez normalement, comme pendant le cours…").font(.subheadline)164                            LevelMeter(levelDB: level, peak: peak)165                            ProgressView(value: progress)166                            Button("Terminer le test maintenant") { finish() }167                        }168                    } else {169                        Button { start() } label: { Label(items.isEmpty ? "Lancer le test (30 s)" : "Refaire le test", systemImage: "play.circle.fill") }170                            .accessibilityIdentifier("preflight.start")171                    }172                } header: { Text("Test") } footer: { Text("Le test écoute le microphone pendant 30 secondes au plus. Rien n'est enregistré ni conservé.") }173174                if !items.isEmpty {175                    Section {176                        ForEach(items) { item in177                            HStack(alignment: .top, spacing: 10) {178                                Image(systemName: item.status == .ok ? "checkmark.circle.fill" : item.status == .warning ? "exclamationmark.triangle.fill" : "xmark.octagon.fill")179                                    .foregroundStyle(item.status == .ok ? DS.ok : item.status == .warning ? DS.paused : DS.recording)180                                VStack(alignment: .leading, spacing: 2) {181                                    Text(Self.title(item.kind)).font(.subheadline.weight(.semibold))182                                    Text(verbatim: Self.message(item)).font(.caption).foregroundStyle(.secondary)183                                }184                            }185                            .accessibilityElement(children: .combine)186                        }187                    } header: { Text("Résultat") }188                }189            }190            .formStyle(.grouped)191            .navigationTitle("Test avant la séance").inlineTitle()192            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Terminé") { cancel(); dismiss() } } }193            .onAppear { inputs = MicrophoneSource.availableInputs() }194            .onDisappear { cancel() }195        }196        #if os(macOS)197        .frame(minWidth: 500, minHeight: 520)198        #endif199    }200201    private func start() {202        items = []; progress = 0; running = true203        task = Task {204            let mic = await CapturePermissions.request(.audio)205            var s: LevelSampler?206            if mic == .granted {207                let sampler = LevelSampler(deviceID: settings.stored.microphoneID)208                sampler.onLevel = { db, pk in level = db; peak = max(peak * 0.9, pk) }209                if (try? sampler.start()) != nil { s = sampler; self.sampler = sampler }210                let begun = Date()211                while !Task.isCancelled, running, Date().timeIntervalSince(begun) < Self.testSeconds {212                    progress = Date().timeIntervalSince(begun) / Self.testSeconds213                    try? await Task.sleep(nanoseconds: 100_000_000)214                }215            }216            if Task.isCancelled { _ = s?.stop(); return }217            evaluate(mic: mic, sampler: s)218        }219    }220221    private func finish() { running = false }222    private func cancel() { task?.cancel(); _ = sampler?.stop(); sampler = nil; running = false }223224    private func evaluate(mic: CapturePermission, sampler s: LevelSampler?) {225        let measured = s?.stop() ?? (levels: [], peak: 0)226        self.sampler = nil; running = false227        let opt = settings.stored.export228        let m = PreflightMeasurement(microphone: mic, camera: CapturePermissions.status(.video), cameraWanted: session.cameraOn, levels: measured.levels, peak: measured.peak,229                                     freeBytes: ProjectPackage.freeDiskSpace(at: session.package.url), plannedMinutes: settings.stored.plannedMinutes,230                                     batteryPercent: SystemStatus.batteryPercent(), charging: SystemStatus.isCharging(), thermal: ProcessInfo.processInfo.thermalState,231                                     settings: (opt.preset.size.0, opt.preset.size.1, opt.codec == .hevc, VideoExporter.isAvailable(.hevc)))232        items = Preflight.evaluate(m)233    }234235    static func title(_ kind: PreflightItemKind) -> LocalizedStringKey {236        switch kind {237        case .microphone: "Microphone"; case .camera: "Caméra"; case .inputLevel: "Niveau d'entrée"; case .storage: "Stockage"238        case .battery: "Batterie"; case .thermal: "Température"; case .output: "Sortie vidéo"239        }240    }241242    static func message(_ i: PreflightItem) -> String {243        let v = i.values244        switch i.code {245        case "mic.granted": return String(localized: "Accès autorisé.")246        case "mic.undetermined": return String(localized: "L'autorisation sera demandée au premier enregistrement.")247        case "mic.denied": return String(localized: "Accès refusé. Autorisez le microphone dans les réglages du système, ou enregistrez sans le son.")248        case "camera.granted": return String(localized: "Accès autorisé.")249        case "camera.undetermined": return String(localized: "L'autorisation sera demandée à l'activation de la caméra.")250        case "camera.denied": return String(localized: "Accès refusé. La séance peut se faire sans caméra.")251        case "level.nosignal": return String(localized: "Aucun signal reçu du microphone.")252        case "level.silent": return String(localized: "Le microphone ne capte presque rien (\(Int(v[0])) dB). Vérifiez l'entrée choisie.")253        case "level.clipping": return String(localized: "Le signal sature. Éloignez-vous du microphone ou baissez le gain d'entrée.")254        case "level.low": return String(localized: "Niveau faible (\(Int(v[0])) dB). Rapprochez-vous du microphone.")255        case "level.noisy": return String(localized: "Bruit de fond élevé : voix à \(Int(v[0])) dB, fond à \(Int(v[1])) dB.")256        case "level.good": return String(localized: "Bon niveau : voix à \(Int(v[0])) dB, fond à \(Int(v[1])) dB.")257        case "storage.insufficient": return String(localized: "Espace insuffisant : environ \(Int(v[0])) min possibles pour \(Int(v[1])) min prévues.")258        case "storage.tight": return String(localized: "Espace juste : environ \(Int(v[0])) min possibles. Gardez de la place pour l'exportation.")259        case "storage.good": return String(localized: "Espace suffisant (plus de \(Int(min(v[0], 9999))) min d'enregistrement).")260        case "battery.charging": return String(localized: "Appareil branché (\(Int(v[0])) %).")261        case "battery.low": return String(localized: "Batterie à \(Int(v[0])) %. Branchez l'appareil avant de commencer.")262        case "battery.medium": return String(localized: "Batterie à \(Int(v[0])) %. Branchez l'appareil pour une longue séance.")263        case "battery.good": return String(localized: "Batterie à \(Int(v[0])) %.")264        case "thermal.good": return String(localized: "Température normale.")265        case "thermal.serious": return String(localized: "L'appareil est chaud. Fermez les autres apps.")266        case "thermal.critical": return String(localized: "L'appareil est trop chaud. Laissez-le refroidir avant d'enregistrer.")267        case "output.hevc.unavailable": return String(localized: "HEVC n'est pas disponible sur cet appareil ; l'exportation utilisera H.264.")268        case "output.good": return String(localized: "Exportation prévue en \(Int(v[0])) × \(Int(v[1])).")269        default: return i.code270        }271    }272}273274// MARK: Automatic pause and stop275276struct PolicySheet: View {277    let settings: AppSettings278    var session: ProjectSession?279    @Environment(\.dismiss) private var dismiss280281    private func bind<T>(_ kp: WritableKeyPath<AutoPausePolicy, T>) -> Binding<T> {282        Binding(get: { settings.stored.policy[keyPath: kp] }, set: { settings.stored.policy[keyPath: kp] = $0 })283    }284285    var body: some View {286        NavigationStack {287            Form {288                Section {289                    Toggle("Proposer une pause après un silence", isOn: bind(\.silenceEnabled)).accessibilityIdentifier("policy.silence")290                    if settings.stored.policy.silenceEnabled { secondsStepper("Silence de", bind(\.silenceSeconds), 10...600, 5) }291                } footer: { Text("Une simple suggestion s'affiche. L'enregistrement continue tant que vous ne choisissez pas la pause.") }292293                Section {294                    Toggle("Détecter l'inactivité", isOn: bind(\.inactivityEnabled))295                    if settings.stored.policy.inactivityEnabled { secondsStepper("Sans voix ni interaction pendant", bind(\.inactivitySeconds), 60...1800, 30) }296                    Toggle("Durée maximale", isOn: bind(\.maxDurationEnabled))297                    if settings.stored.policy.maxDurationEnabled {298                        Stepper(value: Binding(get: { settings.stored.policy.maxDurationSeconds / 60 }, set: { settings.stored.policy.maxDurationSeconds = $0 * 60 }), in: 5...480, step: 5) {299                            Text("Maximum : \(Int(settings.stored.policy.maxDurationSeconds / 60)) min")300                        }301                    }302                    Toggle("Heure de fin", isOn: bind(\.endTimeEnabled))303                    if settings.stored.policy.endTimeEnabled {304                        DatePicker("Fin à", selection: Binding(get: { settings.stored.policy.endTime ?? Date().addingTimeInterval(5400) }, set: { settings.stored.policy.endTime = $0 }), displayedComponents: [.date, .hourAndMinute])305                    }306                } header: { Text("Avec avertissement") } footer: { Text("Un compte à rebours s'affiche avant toute action. Vous pouvez toujours continuer d'enregistrer.") }307308                Section {309                    secondsStepper("Compte à rebours", bind(\.countdownSeconds), 5...120, 5)310                    Picker("À la fin du compte à rebours", selection: bind(\.stopWhenCountdownEnds)) {311                        Text("Mettre en pause").tag(false)312                        Text("Arrêter et sauvegarder").tag(true)313                    }314                } footer: { Text("Dans tous les cas, ce qui a été enregistré est conservé. Chaque décision automatique est consignée dans le journal du projet.") }315316                Section {317                    Toggle("Commande vocale « reprise »", isOn: bind(\.retakePhraseEnabled))318                    if settings.stored.policy.retakePhraseEnabled { TextField("Mot ou phrase", text: bind(\.retakePhrase)) }319                    Toggle("Phrase de fin de séance", isOn: bind(\.endPhraseEnabled))320                    if settings.stored.policy.endPhraseEnabled { TextField("Phrase", text: bind(\.endPhrase)) }321                } header: { Text("Commandes vocales locales") } footer: {322                    Text("Reconnaissance sur l'appareil seulement, si le modèle de la langue choisie est installé. Sinon ces options restent sans effet. Jamais vérifié sur un vrai cours : à essayer avant de s'y fier.")323                }324325                Section {326                    Stepper(value: bind(\.voiceThresholdDB), in: -65 ... -25, step: 1) { Text("Seuil de voix : \(Int(settings.stored.policy.voiceThresholdDB)) dB") }327                    Stepper(value: bind(\.preRollSeconds), in: 0...1.5, step: 0.1) { Text("Tampon avant la reprise : \(String(format: "%.1f", settings.stored.policy.preRollSeconds)) s") }328                } header: { Text("Réglages fins") } footer: { Text("Le tampon conserve l'instant précédant la reprise pour ne pas couper la première syllabe.") }329            }330            .formStyle(.grouped)331            .navigationTitle("Pause et arrêt automatiques").inlineTitle()332            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Terminé") { dismiss() } } }333        }334        #if os(macOS)335        .frame(minWidth: 520, minHeight: 620)336        #endif337    }338339    private func secondsStepper(_ label: LocalizedStringKey, _ value: Binding<Double>, _ range: ClosedRange<Double>, _ step: Double) -> some View {340        Stepper(value: value, in: range, step: step) {341            HStack { Text(label); Spacer(); Text(verbatim: value.wrappedValue >= 120 ? "\(Int(value.wrappedValue / 60)) min \(Int(value.wrappedValue) % 60 == 0 ? "" : "\(Int(value.wrappedValue) % 60) s")" : "\(Int(value.wrappedValue)) s").foregroundStyle(.secondary) }342        }343    }344}345
Files main
Menu

Theme