SPB Git

Repository Public

EditorView.swift 23.3 KB 372 lines swift

1// SP Lecture Studio2// File: Apps/LectureStudio/Shared/Editor/EditorView.swift3// Description: Editing studio: export-accurate preview, transport, timeline tools, and the cuts / audio / chapters / transcript / ink panels.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import LectureCore9import LectureTranscription1011struct EditorView: View {12    let session: ProjectSession13    let settings: AppSettings14    var chrome: ProjectChrome?15    @Environment(\.horizontalSizeClass) private var hSize16    @Environment(\.verticalSizeClass) private var vSize17    @State private var model: EditorModel?18    @State private var panel: EditorPanel = .cuts19    @State private var showPanelSheet = false20    @State private var confirmRevert = false2122    private var compact: Bool { hSize == .compact || vSize == .compact }2324    var body: some View {25        Group {26            if let model {27                if session.manifest.hasRecording { content(model) } else { empty }28            } else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }29        }30        .task(id: session.manifest.duration) {31            model?.teardown()32            model = EditorModel(session: session, settings: settings)33        }34        .onDisappear { model?.teardown() }35    }3637    private var empty: some View {38        VStack(spacing: 10) {39            Image(systemName: "waveform.slash").font(.system(size: 40)).foregroundStyle(.tertiary)40            Text("Rien à monter pour l'instant").font(.title3.weight(.semibold))41            Text("Enregistrez d'abord la séance dans l'onglet « Présenter ».").foregroundStyle(.secondary)42        }.frame(maxWidth: .infinity, maxHeight: .infinity)43    }4445    @ViewBuilder private func content(_ m: EditorModel) -> some View {46        VStack(spacing: 0) {47            if compact {48                preview(m).frame(maxHeight: .infinity)49            } else {50                HStack(spacing: 0) {51                    preview(m).frame(maxWidth: .infinity, maxHeight: .infinity)52                    Divider()53                    panels(m).frame(width: 330)54                }55            }56            Divider()57            transport(m)58            Divider()59            TimelineView(model: m, compact: compact)60            Divider()61            tools(m)62        }63        .sheet(isPresented: $showPanelSheet) {64            NavigationStack {65                panels(m).navigationTitle("Montage").inlineTitle().toolbar { ToolbarItem(placement: .confirmationAction) { Button("Terminé") { showPanelSheet = false } } }66            }67            .presentationDetents([.medium, .large])68        }69        .confirmationDialog("Revenir à l'enregistrement d'origine ?", isPresented: $confirmRevert, titleVisibility: .visible) {70            Button("Retirer toutes les modifications") { m.revertToOriginal() }71            Button("Annuler", role: .cancel) {}72        } message: { Text("Toutes les coupes et tous les réglages sont retirés. Vous pourrez annuler cette action ; les enregistrements ne sont jamais modifiés.") }73    }7475    private func preview(_ m: EditorModel) -> some View {76        ZStack {77            DS.stage78            if let img = m.previewImage { Image(cg: img).resizable().aspectRatio(contentMode: .fit).accessibilityLabel("Aperçu de la vidéo à \(MediaTime.clock(m.playhead))") }79        }80        .overlay(alignment: .bottomLeading) {81            if !m.map.isKept(m.playhead) && m.playhead < m.duration {82                PillLabel(text: "Passage coupé", color: DS.recording, systemImage: "scissors").padding(8)83            }84        }85        .accessibilityIdentifier("editor.preview")86    }8788    private func transport(_ m: EditorModel) -> some View {89        HStack(spacing: compact ? 4 : 8) {90            if let chrome { ChromeCluster(chrome: chrome, busy: false) }91            Button { m.jump(forward: false) } label: { Image(systemName: "backward.end.fill") }.buttonStyle(IconButtonStyle()).accessibilityLabel("Repère précédent")92            Button { m.togglePlay() } label: { Image(systemName: m.isPlaying ? "pause.fill" : "play.fill") }93                .buttonStyle(IconButtonStyle(active: m.isPlaying)).keyboardShortcut(.space, modifiers: []).accessibilityLabel(m.isPlaying ? "Pause" : "Lecture")94                .accessibilityIdentifier("editor.play")95            Button { m.jump(forward: true) } label: { Image(systemName: "forward.end.fill") }.buttonStyle(IconButtonStyle()).accessibilityLabel("Repère suivant")96            VStack(alignment: .leading, spacing: 0) {97                Text(verbatim: "\(MediaTime.clock(m.map.toOutput(m.playhead), tenths: true)) / \(MediaTime.clock(m.outputDuration))").font(.system(.callout, design: .monospaced).weight(.semibold))98                    .lineLimit(1).minimumScaleFactor(0.7)99                    .accessibilityIdentifier("editor.clock")100                if !m.map.isIdentity { Text("Original : \(MediaTime.clock(m.duration)) · \(m.edits.cuts.count) coupe(s)").font(.caption2).foregroundStyle(.secondary) }101            }102            Spacer(minLength: 0)103            if let p = m.envelopeProgress { ProgressView(value: p).frame(width: 60) }104            Button { m.pixelsPerSecond = max(0.3, m.pixelsPerSecond / 1.6) } label: { Image(systemName: "minus.magnifyingglass") }.buttonStyle(IconButtonStyle()).accessibilityLabel("Dézoomer la ligne de temps")105            Button { m.pixelsPerSecond = min(240, m.pixelsPerSecond * 1.6) } label: { Image(systemName: "plus.magnifyingglass") }.buttonStyle(IconButtonStyle()).accessibilityLabel("Zoomer la ligne de temps")106            if compact {107                Button { showPanelSheet = true } label: { Image(systemName: "slider.horizontal.3") }.buttonStyle(IconButtonStyle(active: true)).accessibilityLabel("Panneaux de montage")108                    .accessibilityIdentifier("editor.panels")109            }110        }111        .padding(.horizontal, 8).frame(height: 48).background(.bar)112    }113114    private func tools(_ m: EditorModel) -> some View {115        ScrollView(.horizontal, showsIndicators: false) {116            HStack(spacing: 6) {117                Button { m.undo() } label: { Image(systemName: "arrow.uturn.backward") }.buttonStyle(IconButtonStyle()).disabled(!m.canUndo)118                    .keyboardShortcut("z", modifiers: [.command]).help("Annuler (⌘Z)").accessibilityLabel("Annuler la modification").accessibilityIdentifier("editor.undo")119                Button { m.redo() } label: { Image(systemName: "arrow.uturn.forward") }.buttonStyle(IconButtonStyle()).disabled(!m.canRedo)120                    .keyboardShortcut("z", modifiers: [.command, .shift]).help("Rétablir (⇧⌘Z)").accessibilityLabel("Rétablir la modification")121                Divider().frame(height: 22)122                toolButton("Début", "arrow.right.to.line", id: "editor.in") { m.markIn() }.keyboardShortcut("i", modifiers: [])123                toolButton("Fin", "arrow.left.to.line", id: "editor.out") { m.markOut() }.keyboardShortcut("o", modifiers: [])124                toolButton("Couper", "scissors", id: "editor.cut") { m.cutSelection() }.disabled(m.selection?.isEmpty ?? true).keyboardShortcut(.delete, modifiers: [])125                toolButton("Muet", "speaker.slash", id: "editor.mute") { m.muteSelection() }.disabled(m.selection?.isEmpty ?? true)126                Divider().frame(height: 22)127                toolButton("Scinder", "square.split.2x1", id: "editor.split") { m.splitAtPlayhead() }.keyboardShortcut("b", modifiers: [.command])128                toolButton("Supprimer le plan", "delete.left", id: "editor.ripple") { m.deleteClipAtPlayhead() }129                toolButton("Rogner le début", "arrow.left.to.line.compact", id: "editor.trimStart") { m.trimStartHere() }130                toolButton("Rogner la fin", "arrow.right.to.line.compact", id: "editor.trimEnd") { m.trimEndHere() }131                Divider().frame(height: 22)132                toolButton("Original", "clock.arrow.circlepath", id: "editor.revert") { confirmRevert = true }.disabled(m.edits == EditDecisionList())133            }134            .padding(.horizontal, 8)135        }136        .frame(height: 48).background(.bar)137    }138139    private func toolButton(_ title: LocalizedStringKey, _ symbol: String, id: String, action: @escaping () -> Void) -> some View {140        Button(action: action) {141            if compact { Image(systemName: symbol) } else { Label(title, systemImage: symbol).labelStyle(.titleAndIcon).font(.callout).padding(.horizontal, 8) }142        }143        .buttonStyle(IconButtonStyle()).help(title).accessibilityLabel(title).accessibilityIdentifier(id)144    }145146    private func panels(_ m: EditorModel) -> some View {147        VStack(spacing: 0) {148            Picker("Panneau", selection: $panel) { ForEach(EditorPanel.allCases) { p in Image(systemName: p.symbol).accessibilityLabel(p.title).tag(p) } }149                .pickerStyle(.segmented).labelsHidden().padding(8)150            Divider()151            ScrollView {152                VStack(alignment: .leading, spacing: 12) {153                    switch panel {154                    case .cuts: CutsPanel(model: m)155                    case .audio: AudioPanel(model: m)156                    case .chapters: ChaptersPanel(model: m)157                    case .transcript: TranscriptPanel(model: m, settings: settings)158                    case .ink: InkPanel(model: m)159                    }160                }161                .padding(12).frame(maxWidth: .infinity, alignment: .leading)162            }163        }164        .background(DS.panel)165    }166}167168// MARK: Panels169170struct CutsPanel: View {171    let model: EditorModel172    var body: some View {173        SectionTitle("Suggestions (jamais appliquées sans accord)")174        HStack {175            Button { model.detectSilences() } label: { Label("Longs silences", systemImage: "waveform.badge.minus") }.accessibilityIdentifier("cuts.detect")176            Button { model.suggestRetakes() } label: { Label("Reprises", systemImage: "arrow.counterclockwise") }177        }.buttonStyle(.bordered)178        if let msg = model.statusMessage { Text(verbatim: msg).font(.caption).foregroundStyle(.secondary) }179        if !model.edits.suggestions.isEmpty {180            Button("Approuver celles à 80 % et plus") { model.approveAll(minConfidence: 0.8) }.font(.caption)181            ForEach(model.edits.suggestions) { s in CutRow(model: model, cut: s, suggestion: true) }182        }183        SectionTitle("Coupes appliquées").padding(.top, 6)184        if model.edits.cuts.isEmpty { Text("Aucune coupe. Sélectionnez un passage sur la ligne de temps puis « Couper ».").font(.caption).foregroundStyle(.secondary) }185        ForEach(model.edits.cuts.sorted { $0.range.start < $1.range.start }) { c in CutRow(model: model, cut: c, suggestion: false) }186    }187}188189struct CutRow: View {190    let model: EditorModel191    let cut: Cut192    var suggestion: Bool193    var body: some View {194        Card {195            VStack(alignment: .leading, spacing: 6) {196                HStack(spacing: 6) {197                    Image(systemName: icon).foregroundStyle(suggestion ? DS.paused : DS.recording)198                    Button { model.selectedCut = cut.id; model.seek(to: cut.range.start) } label: {199                        Text(verbatim: "\(MediaTime.clock(cut.range.start, tenths: true)) → \(MediaTime.clock(cut.range.end, tenths: true))").font(.system(.caption, design: .monospaced).weight(.semibold))200                    }.buttonStyle(.plain)201                    Spacer()202                    Text(verbatim: String(format: "%.1f s", cut.range.duration.seconds)).font(.caption).foregroundStyle(.secondary)203                    if let c = cut.confidence { Text(verbatim: "\(Int(c * 100)) %").font(.caption2.weight(.bold)).padding(.horizontal, 5).padding(.vertical, 1).background(Color.primary.opacity(0.1), in: Capsule()).help("Confiance de la détection") }204                }205                HStack(spacing: 6) {206                    Button { model.audition(cut, applied: false) } label: { Label("Avant", systemImage: "play") }.help("Écouter le passage sans la coupe")207                    Button { model.audition(cut, applied: true) } label: { Label("Après", systemImage: "play.fill") }.help("Écouter le raccord avec la coupe")208                    Spacer()209                    if suggestion {210                        Button { model.reject(cut) } label: { Image(systemName: "xmark") }.accessibilityLabel("Rejeter la suggestion")211                        Button { model.approve(cut) } label: { Image(systemName: "checkmark") }.buttonStyle(.borderedProminent).accessibilityLabel("Approuver la coupe")212                            .accessibilityIdentifier("cuts.approve")213                    } else {214                        Button { model.restore(cut) } label: { Label("Rétablir", systemImage: "arrow.uturn.backward") }.accessibilityIdentifier("cuts.restore")215                    }216                }217                .buttonStyle(.bordered).controlSize(.small).font(.caption)218            }219        }220    }221    private var icon: String {222        switch cut.origin { case .silence: "waveform.badge.minus"; case .retake: "arrow.counterclockwise"; case .trim: "arrow.left.and.right"; case .transcript: "text.badge.minus"; case .manual: "scissors" }223    }224}225226struct AudioPanel: View {227    let model: EditorModel228    private func bind<T>(_ kp: WritableKeyPath<EditDecisionList, T>) -> Binding<T> {229        Binding(get: { model.edits[keyPath: kp] }, set: { v in model.apply { $0[keyPath: kp] = v } })230    }231    private func seconds(_ kp: WritableKeyPath<EditDecisionList, MediaTime>) -> Binding<Double> {232        Binding(get: { model.edits[keyPath: kp].seconds }, set: { v in model.apply { $0[keyPath: kp] = MediaTime(seconds: v) } })233    }234    var body: some View {235        SectionTitle("Niveau")236        Toggle("Normaliser le volume (−16 LUFS)", isOn: bind(\.normalizeLoudness))237        Text("Mesure le volume moyen du montage et applique un gain unique, sans jamais dépasser −1 dB en crête.").font(.caption).foregroundStyle(.secondary)238        LabeledContent("Gain manuel") { Text(verbatim: String(format: "%+.0f dB", model.edits.gainDB)) }239        Slider(value: bind(\.gainDB), in: -12...12, step: 1).accessibilityLabel("Gain manuel")240        SectionTitle("Nettoyage").padding(.top, 6)241        Toggle("Atténuer le bruit de fond", isOn: bind(\.noiseReduction))242        Text("Filtre passe-haut à 80 Hz et atténuation douce (12 dB au plus) des passages sans voix. Réglage prudent : la voix n'est pas modifiée.").font(.caption).foregroundStyle(.secondary)243        SectionTitle("Fondus").padding(.top, 6)244        LabeledContent("Fondu d'ouverture") { Text(verbatim: String(format: "%.1f s", model.edits.fadeIn.seconds)) }245        Slider(value: seconds(\.fadeIn), in: 0...5, step: 0.5).accessibilityLabel("Fondu d'ouverture")246        LabeledContent("Fondu de fermeture") { Text(verbatim: String(format: "%.1f s", model.edits.fadeOut.seconds)) }247        Slider(value: seconds(\.fadeOut), in: 0...5, step: 0.5).accessibilityLabel("Fondu de fermeture")248        LabeledContent("Fondu enchaîné aux coupes") { Text(verbatim: "\(Int(model.edits.crossfade.seconds * 1000)) ms") }249        Slider(value: seconds(\.crossfade), in: 0...0.2, step: 0.01).accessibilityLabel("Fondu enchaîné aux coupes")250        if !model.edits.muted.isEmpty {251            SectionTitle("Passages muets").padding(.top, 6)252            ForEach(Array(model.edits.muted.enumerated()), id: \.offset) { i, r in253                HStack {254                    Text(verbatim: "\(MediaTime.clock(r.start)) → \(MediaTime.clock(r.end))").font(.system(.caption, design: .monospaced))255                    Spacer()256                    Button("Rétablir le son") { model.apply { $0.muted.remove(at: i) } }.controlSize(.small)257                }258            }259        }260    }261}262263struct ChaptersPanel: View {264    let model: EditorModel265    var body: some View {266        SectionTitle("Chapitres")267        HStack {268            Button { model.generateChapters() } label: { Label("D'après les diapositives", systemImage: "wand.and.stars") }.accessibilityIdentifier("chapters.generate")269            Button { model.addChapterAtPlayhead() } label: { Label("Ici", systemImage: "plus") }270        }.buttonStyle(.bordered)271        Text("Un chapitre par diapositive affichée au moins 5 secondes, plus vos marqueurs de chapitre. Les titres viennent du texte de la page et restent modifiables.").font(.caption).foregroundStyle(.secondary)272        ForEach(model.edits.chapters) { c in273            HStack(spacing: 6) {274                Button { model.seek(to: c.time) } label: { Text(verbatim: MediaTime.clock(model.map.toOutput(c.time))).font(.system(.caption, design: .monospaced)).frame(width: 52, alignment: .leading) }.buttonStyle(.plain)275                TextField("Titre", text: Binding(get: { c.title }, set: { v in model.apply { e in if let i = e.chapters.firstIndex(where: { $0.id == c.id }) { e.chapters[i].title = v } } }))276                    .textFieldStyle(.roundedBorder)277                Button { model.apply { $0.chapters.removeAll { $0.id == c.id } } } label: { Image(systemName: "minus.circle") }.buttonStyle(.plain).foregroundStyle(.secondary).accessibilityLabel("Supprimer le chapitre")278            }279        }280    }281}282283struct TranscriptPanel: View {284    let model: EditorModel285    let settings: AppSettings286    @State private var choice: TranscriptionChoice = .onDevice287    @State private var confirmDelete = false288    var body: some View {289        SectionTitle("Transcription")290        Picker("Moteur", selection: $choice) {291            Text("Sur l'appareil").tag(TranscriptionChoice.onDevice)292            Text("Serveur configuré").tag(TranscriptionChoice.remote)293        }.pickerStyle(.segmented).labelsHidden()294        Text(choice == .onDevice ? "Reconnaissance vocale du système, entièrement sur cet appareil. Demande le modèle de langue installé."295                                 : "Envoie l'audio en HTTPS au serveur que vous avez configuré dans les réglages. Désactivé tant que vous n'y avez pas consenti.")296            .font(.caption).foregroundStyle(.secondary)297        if let p = model.transcribing {298            ProgressView(value: p) { Text("Transcription en cours…").font(.caption) }299            Button("Annuler") { model.cancelTranscription() }.controlSize(.small)300        } else {301            Button { model.transcribe(using: choice) } label: { Label(model.transcript == nil ? "Transcrire la séance" : "Transcrire de nouveau", systemImage: "captions.bubble") }302                .buttonStyle(.bordered).accessibilityIdentifier("transcript.start")303        }304        if let e = model.transcriptionError { Label { Text(verbatim: e).font(.caption) } icon: { Image(systemName: "info.circle") }.foregroundStyle(DS.paused) }305        if let t = model.transcript {306            HStack {307                Text("\(t.segments.count) segment(s) · \(Locale.current.localizedString(forIdentifier: t.locale) ?? t.locale)").font(.caption).foregroundStyle(.secondary)308                Spacer()309                Button(role: .destructive) { confirmDelete = true } label: { Image(systemName: "trash") }.controlSize(.small).accessibilityLabel("Supprimer la transcription")310            }311            .confirmationDialog("Supprimer la transcription ?", isPresented: $confirmDelete, titleVisibility: .visible) {312                Button("Supprimer", role: .destructive) { model.deleteTranscript() }313                Button("Annuler", role: .cancel) {}314            } message: { Text("Vos corrections manuelles seront perdues. L'audio n'est pas touché.") }315            ForEach(t.segments) { seg in316                VStack(alignment: .leading, spacing: 3) {317                    HStack {318                        Button { model.seek(to: seg.range.start) } label: { Text(verbatim: MediaTime.clock(seg.range.start)).font(.system(.caption2, design: .monospaced)).foregroundStyle(DS.accent) }.buttonStyle(.plain)319                        if !model.map.isKept(seg.range.start) { Text("coupé").font(.caption2).foregroundStyle(DS.recording) }320                        if seg.edited { Image(systemName: "pencil").font(.caption2).foregroundStyle(.secondary) }321                        Spacer()322                        Button { model.apply { $0.addCut(seg.range, origin: .transcript) } } label: { Image(systemName: "scissors") }.buttonStyle(.plain).foregroundStyle(.secondary)323                            .help("Couper ce passage").accessibilityLabel("Couper ce passage")324                    }325                    TextField("Texte", text: Binding(get: { seg.text }, set: { model.updateSegment(seg.id, text: $0) }), axis: .vertical).textFieldStyle(.plain).font(.callout)326                }327                .padding(8).background(DS.card, in: RoundedRectangle(cornerRadius: 6))328            }329        }330    }331}332333struct InkPanel: View {334    let model: EditorModel335    var body: some View {336        SectionTitle("Annotations près de la tête de lecture")337        let near = model.index.allStrokes.filter { abs(($0.stroke.begin - model.playhead).seconds) < 30 }.prefix(12)338        if near.isEmpty { Text("Aucun trait dans les 30 secondes autour de la tête de lecture.").font(.caption).foregroundStyle(.secondary) }339        ForEach(Array(near), id: \.stroke.id) { life in340            HStack(spacing: 6) {341                Circle().fill(Color(life.stroke.color)).frame(width: 10, height: 10)342                Button { model.seek(to: life.stroke.begin) } label: { Text(verbatim: "p. \(life.stroke.page + 1) · \(MediaTime.clock(life.stroke.begin, tenths: true))").font(.system(.caption, design: .monospaced)) }.buttonStyle(.plain)343                Spacer()344                Button { shift(life.stroke.id, -0.5) } label: { Image(systemName: "minus") }.help("Avancer l'apparition de 0,5 s").accessibilityLabel("Faire apparaître plus tôt")345                Button { shift(life.stroke.id, 0.5) } label: { Image(systemName: "plus") }.help("Retarder l'apparition de 0,5 s").accessibilityLabel("Faire apparaître plus tard")346                Button { model.apply { $0.ink.hidden.insert(life.stroke.id) } } label: { Image(systemName: "eye.slash") }.help("Masquer dans la vidéo et le PDF annoté").accessibilityLabel("Masquer ce trait")347            }348            .buttonStyle(.bordered).controlSize(.small)349        }350        if !model.edits.ink.isEmpty {351            Text("\(model.edits.ink.offsets.count) trait(s) décalé(s), \(model.edits.ink.hidden.count) masqué(s)").font(.caption).foregroundStyle(.secondary)352            Button("Rétablir toutes les annotations d'origine") { model.apply { $0.ink = InkAdjustments() } }.controlSize(.small)353        }354        if model.hasCamera {355            SectionTitle("Caméra").padding(.top, 6)356            Toggle("Masquer la caméra dans la vidéo", isOn: Binding(get: { model.edits.cameraHidden }, set: { v in model.apply { $0.cameraHidden = v } }))357            Picker("Position", selection: Binding(get: { model.edits.cameraPlacement?.corner ?? CameraCorner.bottomRight }, set: { v in358                model.apply { var p = $0.cameraPlacement ?? CameraPlacement(); p.corner = v; $0.cameraPlacement = p }359            })) { ForEach(CameraCorner.allCases, id: \.self) { Text(CameraOverlay.name($0)).tag($0) } }360            Slider(value: Binding(get: { model.edits.cameraPlacement?.size ?? 0.22 }, set: { v in361                model.apply { var p = $0.cameraPlacement ?? CameraPlacement(); p.size = v; $0.cameraPlacement = p }362            }), in: 0.12...0.4) { Text("Taille") }363        }364    }365    private func shift(_ id: UUID, _ seconds: Double) {366        model.apply { e in367            let v = (e.ink.offsets[id] ?? 0) + Int64(seconds * 1e9)368            if v == 0 { e.ink.offsets.removeValue(forKey: id) } else { e.ink.offsets[id] = v }369        }370    }371}372
Files main
Menu

Theme