From 37b60623ad413d8814f4a0203cae79915107bd18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Mittelst=C3=A4dt?= Date: Sun, 18 Oct 2026 12:28:46 +0200 Subject: [PATCH 1/3] #2330: add reusable caption track style presets --- crates/engine/src/captions.rs | 238 ++++++++++++++++++ crates/engine/src/captions_tests.rs | 58 +++++ crates/engine/src/lib.rs | 7 + crates/ui-egui/src/panels/text.rs | 88 +++++++ .../ui-egui/tests/caption_style_presets_ui.rs | 99 ++++++++ 5 files changed, 490 insertions(+) create mode 100644 crates/ui-egui/tests/caption_style_presets_ui.rs diff --git a/crates/engine/src/captions.rs b/crates/engine/src/captions.rs index d048a5677..95127231a 100644 --- a/crates/engine/src/captions.rs +++ b/crates/engine/src/captions.rs @@ -5,6 +5,10 @@ //! selection (`EditorState::caption_selection`) or the caption under the playhead. Caption tracks //! are addressed by id or `"C1"`, `"C2"`… (top first); the default is the first caption track. +use std::io::Read; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use filmcraft_captions::{Document, Format, WriteOptions}; @@ -19,6 +23,162 @@ use crate::{EngineError, Result, Session}; type Run = fn(&mut Session, &Value) -> Result; type Enabled = fn(&Session) -> std::result::Result<(), String>; +const STYLE_PRESET_FILE: &str = "caption-style-presets.json"; +const STYLE_PRESET_FORMAT: &str = "filmcraft.caption-style-presets"; +const MAX_STYLE_PRESETS: usize = 100; +const MAX_STYLE_PRESET_FILE_BYTES: u64 = 1024 * 1024; +const MAX_STYLE_PRESET_NAME_CHARS: usize = 100; +const MAX_STYLE_FONT_BYTES: usize = 1024; + +/// A named, reusable caption track appearance. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CaptionStylePreset { + pub name: String, + pub style: CaptionStyle, +} + +#[derive(Serialize, Deserialize)] +struct CaptionStylePresetFile { + format: String, + version: u32, + presets: Vec, +} + +/// User-created caption track styles persisted in the application data directory. +#[derive(Default)] +pub struct CaptionStyleLibrary { + user: Vec, + dir: Option, +} + +impl CaptionStyleLibrary { + /// Load saved styles from the app data directory. Invalid files are left untouched and reported. + pub fn set_dir(&mut self, data_dir: &Path) { + self.dir = Some(data_dir.to_path_buf()); + let path = data_dir.join(STYLE_PRESET_FILE); + let file = match std::fs::File::open(&path) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return, + Err(e) => { + log::warn!("{}: {e}", path.display()); + return; + } + }; + let mut bytes = Vec::new(); + let read = file.take(MAX_STYLE_PRESET_FILE_BYTES.saturating_add(1)).read_to_end(&mut bytes); + if let Err(e) = read { + log::warn!("{}: {e}", path.display()); + return; + } + match if bytes.len() as u64 > MAX_STYLE_PRESET_FILE_BYTES { + Err("caption style preset file exceeds the 1 MiB limit".into()) + } else { + parse_style_presets(&bytes) + } { + Ok(presets) => self.user = presets, + Err(e) => log::warn!("{}: {e}", path.display()), + } + } + + pub fn all(&self) -> &[CaptionStylePreset] { + &self.user + } + + pub fn find(&self, name: &str) -> Option { + self.user.iter().find(|p| p.name == name).map(|p| p.style.clone()) + } + + pub fn save(&mut self, name: &str, style: CaptionStyle) -> std::result::Result<(), String> { + let name = name.trim(); + if name.is_empty() || name.chars().count() > MAX_STYLE_PRESET_NAME_CHARS || name.chars().any(char::is_control) { + return Err(format!("preset name must be 1–{MAX_STYLE_PRESET_NAME_CHARS} printable characters")); + } + let style = normalize_style(style).ok_or_else(|| "caption style has an invalid font or non-finite value".to_string())?; + let mut next = self.user.clone(); + if let Some(preset) = next.iter_mut().find(|p| p.name.eq_ignore_ascii_case(name)) { + preset.name = name.to_string(); + preset.style = style; + } else { + if next.len() >= MAX_STYLE_PRESETS { + return Err(format!("caption style preset limit ({MAX_STYLE_PRESETS}) reached")); + } + next.push(CaptionStylePreset { name: name.to_string(), style }); + } + self.persist(&next)?; + self.user = next; + Ok(()) + } + + pub fn delete(&mut self, name: &str) -> std::result::Result { + let Some(index) = self.user.iter().position(|p| p.name == name) else { return Ok(false) }; + let mut next = self.user.clone(); + next.remove(index); + self.persist(&next)?; + self.user = next; + Ok(true) + } + + fn persist(&self, presets: &[CaptionStylePreset]) -> std::result::Result<(), String> { + let Some(dir) = &self.dir else { return Ok(()) }; + std::fs::create_dir_all(dir).map_err(|e| format!("could not create caption style preset directory: {e}"))?; + let bytes = style_preset_file_bytes(presets)?; + filmcraft_format::atomic_write(&dir.join(STYLE_PRESET_FILE), &bytes).map_err(|e| e.to_string()) + } +} + +fn normalize_style(mut style: CaptionStyle) -> Option { + if style.font.len() > MAX_STYLE_FONT_BYTES + || !style.size.is_finite() + || !style.margin.is_finite() + || !style.line_spacing.is_finite() + || !style.outline.is_finite() + { + return None; + } + style.size = style.size.clamp(4.0, 400.0); + style.margin = style.margin.clamp(0.0, 0.45); + style.line_spacing = style.line_spacing.clamp(0.8, 4.0); + style.outline = style.outline.clamp(0.0, 40.0); + Some(style) +} + +fn style_preset_file_bytes(presets: &[CaptionStylePreset]) -> std::result::Result, String> { + serde_json::to_vec_pretty(&CaptionStylePresetFile { format: STYLE_PRESET_FORMAT.into(), version: 1, presets: presets.to_vec() }) + .map_err(|e| format!("could not serialize caption style presets: {e}")) +} + +fn parse_style_presets(bytes: &[u8]) -> std::result::Result, String> { + if bytes.len() as u64 > MAX_STYLE_PRESET_FILE_BYTES { + return Err("caption style preset file exceeds the 1 MiB limit".into()); + } + let file: CaptionStylePresetFile = serde_json::from_slice(bytes).map_err(|e| format!("invalid caption style preset file: {e}"))?; + if file.format != STYLE_PRESET_FORMAT { + return Err(format!("not a caption style preset file (format `{}`)", file.format)); + } + if file.version != 1 { + return Err(format!("unsupported caption style preset version {}", file.version)); + } + if file.presets.len() > MAX_STYLE_PRESETS { + return Err(format!("caption style preset file exceeds the {MAX_STYLE_PRESETS} preset limit")); + } + let mut names = std::collections::HashSet::new(); + let mut presets = Vec::with_capacity(file.presets.len()); + for mut preset in file.presets { + let name = preset.name.trim().to_string(); + if name.is_empty() || name.chars().count() > MAX_STYLE_PRESET_NAME_CHARS || name.chars().any(char::is_control) { + return Err("caption style preset file contains an invalid name".into()); + } + if !names.insert(name.to_lowercase()) { + return Err("caption style preset file contains duplicate names".into()); + } + preset.name = name.clone(); + preset.style = normalize_style(preset.style).ok_or_else(|| format!("caption style preset `{name}` has an invalid style"))?; + presets.push(preset); + } + Ok(presets) +} + fn spec( id: &'static str, label: &'static str, @@ -362,6 +522,59 @@ pub fn commands() -> Vec { Ok(Value::Null) }, ), + spec("captions.copyStyle", "Copy Caption Track Style", &[], None, r#"{"track":id|"C1"?}"#, has_caption_track, |s, p| { + let tid = track_param(s, p).ok_or_else(|| bad("captions.copyStyle", "no such caption track"))?; + let style = s.active_sequence().and_then(|q| q.caption_track(tid)).map(|t| t.style.clone()).ok_or(EngineError::NoSequence)?; + s.caption_style_clipboard = Some(style); + Ok(json!({"track": tid.0, "copied": true})) + }), + spec("captions.pasteStyle", "Paste Caption Track Style", &[], None, r#"{"track":id|"C1"?}"#, has_caption_track, |s, p| { + let tid = track_param(s, p).ok_or_else(|| bad("captions.pasteStyle", "no such caption track"))?; + let style = s.caption_style_clipboard.clone().ok_or_else(|| bad("captions.pasteStyle", "copy a caption track style first"))?; + s.edit_sequence("Paste Caption Track Style", move |q, _, _| { + let track = q.caption_track_mut(tid).ok_or_else(|| bad("captions.pasteStyle", "no such caption track"))?; + track.style = style; + Ok(()) + })?; + Ok(json!({"track": tid.0, "pasted": true})) + }), + spec("captions.stylePreset.save", "Save Caption Style Preset", &[], None, r#"{"name":str,"track":id|"C1"?}"#, has_caption_track, |s, p| { + let name = str_p(p, "name").ok_or_else(|| bad("captions.stylePreset.save", "need `name`"))?; + let tid = track_param(s, p).ok_or_else(|| bad("captions.stylePreset.save", "no such caption track"))?; + let style = s.active_sequence().and_then(|q| q.caption_track(tid)).map(|t| t.style.clone()).ok_or(EngineError::NoSequence)?; + s.caption_style_presets.save(name, style).map_err(|e| bad("captions.stylePreset.save", e))?; + Ok(json!({"name": name.trim()})) + }), + spec("captions.stylePreset.apply", "Apply Caption Style Preset", &[], None, r#"{"name":str,"track":id|"C1"?}"#, has_caption_track, |s, p| { + let name = str_p(p, "name").ok_or_else(|| bad("captions.stylePreset.apply", "need `name`"))?; + let tid = track_param(s, p).ok_or_else(|| bad("captions.stylePreset.apply", "no such caption track"))?; + let style = + s.caption_style_presets.find(name).ok_or_else(|| bad("captions.stylePreset.apply", format!("no caption style preset named `{name}`")))?; + s.edit_sequence("Apply Caption Style Preset", move |q, _, _| { + let track = q.caption_track_mut(tid).ok_or_else(|| bad("captions.stylePreset.apply", "no such caption track"))?; + track.style = style; + Ok(()) + })?; + Ok(json!({"name": name, "track": tid.0})) + }), + spec("captions.stylePreset.delete", "Delete Caption Style Preset", &[], None, r#"{"name":str}"#, always, |s, p| { + let name = str_p(p, "name").ok_or_else(|| bad("captions.stylePreset.delete", "need `name`"))?; + let deleted = s.caption_style_presets.delete(name).map_err(|e| bad("captions.stylePreset.delete", e))?; + if !deleted { + return Err(bad("captions.stylePreset.delete", format!("no caption style preset named `{name}`"))); + } + Ok(json!({"name": name, "deleted": true})) + }), + CommandSpec { + id: "captions.stylePreset.list", + label: "List Caption Style Presets", + menu: &[], + shortcut: None, + params: "{}", + enabled: always, + run: |s, _| Ok(json!({"presets": s.caption_style_presets.all()})), + journal: false, + }, spec( "captions.add", "Add Caption at Playhead", @@ -561,3 +774,28 @@ fn show_all(s: &mut Session, on: bool) -> Result { #[cfg(test)] #[path = "captions_tests.rs"] mod tests; + +#[cfg(test)] +mod preset_file_tests { + use super::*; + + #[test] + fn caption_style_preset_parser_survives_truncation_and_bit_flips() { + let valid = style_preset_file_bytes(&[CaptionStylePreset { name: "Safe".into(), style: CaptionStyle::default() }]).expect("valid preset serializes"); + let mut candidates: Vec> = (0..valid.len()).map(|length| valid[..length].to_vec()).collect(); + candidates.push(valid.clone()); + for index in 0..valid.len() { + for bit in 0..8 { + let mut changed = valid.clone(); + changed[index] ^= 1 << bit; + candidates.push(changed); + } + } + candidates.push(vec![b' '; MAX_STYLE_PRESET_FILE_BYTES as usize + 1]); + + for candidate in candidates { + let parsed = std::panic::catch_unwind(|| parse_style_presets(&candidate)); + assert!(parsed.is_ok(), "malformed preset data must return an error instead of panicking"); + } + } +} diff --git a/crates/engine/src/captions_tests.rs b/crates/engine/src/captions_tests.rs index feb65c175..79317a243 100644 --- a/crates/engine/src/captions_tests.rs +++ b/crates/engine/src/captions_tests.rs @@ -158,3 +158,61 @@ fn caption_list_track_filter_never_falls_back_to_every_track() { assert!(s.execute("captions.list", json!({"track": sel})).is_err(), "{sel} names no caption track"); } } + +#[test] +fn caption_track_styles_copy_paste_and_saved_presets_are_undoable_and_persisted() { + let dir = std::env::temp_dir().join(format!("fc-caption-style-presets-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = demo(); + s.caption_style_presets.set_dir(&dir); + let first = s.execute("captions.newTrack", json!({"name": "First"})).unwrap()["track"].as_u64().unwrap(); + let second = s.execute("captions.newTrack", json!({"name": "Second"})).unwrap()["track"].as_u64().unwrap(); + s.execute("playhead.set", json!({"seconds": 1.0})).unwrap(); + s.execute("captions.add", json!({"track": first, "text": "Keep my timing"})).unwrap(); + s.execute("playhead.set", json!({"seconds": 4.0})).unwrap(); + s.execute("captions.add", json!({"track": second, "text": "Also keep mine"})).unwrap(); + s.execute("captions.setStyle", json!({"track": first, "font": "Inter", "size": 42.0, "color": "#22aaff", "anchor": "top"})).unwrap(); + let first_style = s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == first).unwrap().style.clone(); + let second_captions = s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == second).unwrap().captions.clone(); + + s.execute("captions.copyStyle", json!({"track": first})).unwrap(); + s.execute("captions.setStyle", json!({"track": second, "size": 24.0, "anchor": "bottom"})).unwrap(); + s.execute("captions.pasteStyle", json!({"track": second})).unwrap(); + let target = s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == second).unwrap(); + assert_eq!(target.style, first_style); + assert_eq!(target.captions, second_captions, "style paste preserves caption text and timing"); + s.execute("edit.undo", json!({})).unwrap(); + let target = s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == second).unwrap(); + assert_eq!(target.style.size, 24.0, "pasting a style is one undo step"); + + s.execute("captions.stylePreset.save", json!({"track": first, "name": "Broadcast Blue"})).unwrap(); + s.execute("captions.setStyle", json!({"track": first, "size": 18.0})).unwrap(); + s.execute("captions.stylePreset.apply", json!({"track": first, "name": "Broadcast Blue"})).unwrap(); + assert_eq!(s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == first).unwrap().style, first_style); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == first).unwrap().style.size, 18.0); + let list = s.execute("captions.stylePreset.list", json!({})).unwrap(); + assert_eq!(list["presets"][0]["name"], "Broadcast Blue"); + + let mut loaded = crate::captions::CaptionStyleLibrary::default(); + loaded.set_dir(&dir); + assert_eq!(loaded.find("Broadcast Blue"), Some(first_style)); + assert!(loaded.delete("Broadcast Blue").unwrap()); + assert!(loaded.find("Broadcast Blue").is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn caption_style_preset_commands_reject_hostile_parameters_without_mutation() { + let mut s = demo(); + s.execute("captions.newTrack", json!({"name": "Hostile test"})).unwrap(); + let original_style = s.active_sequence().unwrap().caption_tracks[0].style.clone(); + for name in [String::new(), "x".repeat(101), "line\nbreak".to_string()] { + assert!(s.execute("captions.stylePreset.save", json!({"track": "C1", "name": name})).is_err()); + } + assert!(s.execute("captions.stylePreset.apply", json!({"track": "C1", "name": "missing"})).is_err()); + assert!(s.execute("captions.stylePreset.delete", json!({"name": "missing"})).is_err()); + assert!(s.execute("captions.pasteStyle", json!({"track": "C1"})).is_err()); + assert!(s.caption_style_presets.all().is_empty()); + assert_eq!(s.active_sequence().unwrap().caption_tracks[0].style, original_style); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5d0a044d0..210524885 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -428,6 +428,10 @@ pub struct Session { pub scene_jobs: Vec, /// Effect presets (built-in + the user's, persisted in the data directory). pub presets: presets::PresetLibrary, + /// User-saved caption track styles, persisted in the data directory. + pub caption_style_presets: captions::CaptionStyleLibrary, + /// Caption style copied for use on another track in this session. + pub caption_style_clipboard: Option, /// Export presets (built-in + the user's, persisted in the data directory) and favourites. pub export_presets: export_tools::ExportPresetLibrary, /// The export queue (session state, not saved with the project). @@ -531,6 +535,8 @@ impl Session { mask_jobs: Vec::new(), scene_jobs: Vec::new(), presets: Default::default(), + caption_style_presets: Default::default(), + caption_style_clipboard: None, export_presets: Default::default(), export_queue: Default::default(), stepped: Vec::new(), @@ -581,6 +587,7 @@ impl Session { self.media.set_use_proxies(self.prefs.media.enable_proxies); self.shortcuts.set_dir(&cfg.data_dir); self.presets.set_dir(&cfg.data_dir); + self.caption_style_presets.set_dir(&cfg.data_dir); self.export_presets.set_dir(&cfg.data_dir); self.prefs_path = Some(prefs_path); self.apply_media_cache(); diff --git a/crates/ui-egui/src/panels/text.rs b/crates/ui-egui/src/panels/text.rs index 6de9c6139..b2a4c56e2 100644 --- a/crates/ui-egui/src/panels/text.rs +++ b/crates/ui-egui/src/panels/text.rs @@ -477,6 +477,7 @@ fn style_strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, r: Rect, track_idx: us let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r).id_salt("caption-style")); child.horizontal_centered(|ui| { ui.spacing_mut().item_spacing.x = 6.0; + caption_style_actions_menu(app, ui, tr.id.0, actions); let r = egui::ComboBox::from_id_salt(("caption-font", tr.id.0)).selected_text(&st.font).width(130.0).height(400.0).show_ui(ui, |ui| { if !filmcraft_text::fonts::system_scanned() { filmcraft_text::fonts::scan_system(); @@ -541,6 +542,93 @@ fn style_strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, r: Rect, track_idx: us } } }); + caption_style_preset_save_dialog(app, child.ctx(), tr.id.0, actions); +} + +fn caption_style_actions_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, track: u64, actions: &mut Vec<(String, Value)>) { + let menu = ui.button(tl!("Style")).on_hover_text(tl!("Caption style actions and presets")); + app.auto.add("text.captions.style.menu", menu.rect, "Caption style actions and presets"); + egui::Popup::menu(&menu).show(|ui| { + let copy = ui.button(tl!("Copy Track Style")); + app.auto.add("text.captions.style.copy", copy.rect, "Copy caption track style"); + if copy.clicked() { + actions.push(("captions.copyStyle".into(), json!({"track": track}))); + } + let can_paste = app.session.caption_style_clipboard.is_some(); + let paste = ui.add_enabled(can_paste, egui::Button::new(tl!("Paste Track Style"))); + app.auto.add("text.captions.style.paste", paste.rect, "Paste caption track style"); + if paste.clicked() { + actions.push(("captions.pasteStyle".into(), json!({"track": track}))); + } + ui.separator(); + let save_as = ui.button(tl!("Save Current Style as Preset…")); + app.auto.add("text.captions.style.preset.openSave", save_as.rect, "Save current caption style as a preset"); + if save_as.clicked() { + ui.ctx().data_mut(|d| { + d.insert_temp(egui::Id::new("caption-style-preset-save-open"), true); + d.insert_temp(egui::Id::new("caption-style-preset-name"), String::new()); + }); + } + let presets = app.session.caption_style_presets.all().to_vec(); + if !presets.is_empty() { + ui.separator(); + for (index, preset) in presets.iter().enumerate() { + ui.horizontal(|ui| { + let apply = ui.selectable_label(false, &preset.name); + app.auto.add(&format!("text.captions.style.preset.{index}.apply"), apply.rect, &preset.name); + if apply.clicked() { + actions.push(("captions.stylePreset.apply".into(), json!({"track": track, "name": preset.name}))); + } + let delete = ui.small_button("×").on_hover_text(tl!("Delete preset")); + app.auto.add(&format!("text.captions.style.preset.{index}.delete"), delete.rect, "Delete caption style preset"); + if delete.clicked() { + actions.push(("captions.stylePreset.delete".into(), json!({"name": preset.name}))); + } + }); + } + } + }); +} + +fn caption_style_preset_save_dialog(app: &mut FilmcraftApp, ctx: &egui::Context, track: u64, actions: &mut Vec<(String, Value)>) { + let open_id = egui::Id::new("caption-style-preset-save-open"); + let name_id = egui::Id::new("caption-style-preset-name"); + let mut open = ctx.data(|d| d.get_temp::(open_id)).unwrap_or(false); + if !open { + return; + } + let mut name = ctx.data(|d| d.get_temp::(name_id)).unwrap_or_default(); + let mut close = false; + egui::Window::new(tl!("Save Caption Style Preset")) + .id(egui::Id::new("caption-style-preset-save-window")) + .collapsible(false) + .resizable(false) + .open(&mut open) + .show(ctx, |ui| { + let edit = ui.add(egui::TextEdit::singleline(&mut name).hint_text(tl!("Preset name")).desired_width(240.0)); + app.auto.add("text.captions.style.preset.name", edit.rect, "Caption style preset name"); + ui.horizontal(|ui| { + let save = ui.add_enabled(!name.trim().is_empty(), egui::Button::new(tl!("Save"))); + app.auto.add("text.captions.style.preset.save", save.rect, "Save caption style preset"); + if save.clicked() { + actions.push(("captions.stylePreset.save".into(), json!({"track": track, "name": name.trim()}))); + close = true; + name.clear(); + } + let cancel = ui.button(tl!("Cancel")); + app.auto.add("text.captions.style.preset.cancel", cancel.rect, "Cancel saving caption style preset"); + if cancel.clicked() { + close = true; + } + }); + }); + if close { + open = false; + } + ctx.data_mut(|d| { + d.insert_temp(open_id, open); + d.insert_temp(name_id, name); + }); } fn run(app: &mut FilmcraftApp, ui: &egui::Ui, actions: Vec<(String, Value)>) { diff --git a/crates/ui-egui/tests/caption_style_presets_ui.rs b/crates/ui-egui/tests/caption_style_presets_ui.rs new file mode 100644 index 000000000..32d546bd1 --- /dev/null +++ b/crates/ui-egui/tests/caption_style_presets_ui.rs @@ -0,0 +1,99 @@ +//! Headless UI test for copying caption track styles and saving reusable presets. + +use std::sync::mpsc::{Sender, channel}; + +use egui_kittest::Harness; +use filmcraft_engine::Session; +use filmcraft_ui_egui::FilmcraftApp; +use filmcraft_ui_egui::control::ControlRequest; +use serde_json::{Value, json}; + +struct Driver { + harness: Harness<'static, FilmcraftApp>, + tx: Sender, +} + +impl Driver { + fn demo() -> Self { + let mut session = Session::default(); + session.execute("file.openDemoProject", json!({})).expect("demo project"); + let (tx, rx) = channel(); + let app = FilmcraftApp::new(session).with_control(rx); + let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app); + let mut d = Driver { harness, tx }; + d.frames(4); + d + } + + fn frames(&mut self, n: usize) { + for _ in 0..n { + let ctx = self.harness.ctx.clone(); + let mut raw = std::mem::take(self.harness.input_mut()); + eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw); + *self.harness.input_mut() = raw; + self.harness.step(); + } + } + + fn ok(&mut self, method: &str, params: Value) -> Value { + let (req, reply) = ControlRequest::new(method, params.clone()); + self.tx.send(req).unwrap(); + for _ in 0..600 { + self.frames(1); + if let Ok(v) = reply.try_recv() { + assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}"); + return v["result"].clone(); + } + } + panic!("no reply to {method} {params}"); + } + + fn ids(&mut self, prefix: &str) -> Vec { + let v = self.ok("ui.elements", json!({"prefix": prefix})); + v.as_array().unwrap().iter().filter_map(|e| e["id"].as_str().map(str::to_string)).collect() + } + + fn size(&mut self, track: u64) -> f64 { + let r = self.ok("engine.execute", json!({"command": "captions.list", "params": {}})); + r["tracks"].as_array().unwrap().iter().find(|t| t["id"] == json!(track)).expect("track")["style"]["size"].as_f64().unwrap() + } +} + +#[test] +fn caption_style_menu_copies_and_saves_reusable_styles() { + let mut d = Driver::demo(); + d.ok("ui.set", json!({"workspace": "Captions and Graphics"})); + let track = d.ok("engine.execute", json!({"command": "captions.newTrack", "params": {"format": "Subtitle"}}))["track"].as_u64().unwrap(); + d.ok("engine.execute", json!({"command": "captions.setStyle", "params": {"track": track, "size": 42.0}})); + d.frames(2); + d.ok("ui.click", json!({"id": "text.tab.Captions"})); + d.frames(3); + + d.ok("ui.click", json!({"id": "text.captions.style.menu"})); + d.frames(2); + assert!(d.ids("text.captions.style.copy").iter().any(|id| id == "text.captions.style.copy"), "copy action appears in the style menu"); + d.ok("ui.click", json!({"id": "text.captions.style.copy"})); + d.frames(2); + d.ok("engine.execute", json!({"command": "captions.setStyle", "params": {"track": track, "size": 18.0}})); + d.ok("ui.click", json!({"id": "text.captions.style.menu"})); + d.frames(2); + d.ok("ui.click", json!({"id": "text.captions.style.paste"})); + d.frames(3); + assert_eq!(d.size(track), 42.0, "paste restores the copied style"); + + d.ok("ui.click", json!({"id": "text.captions.style.menu"})); + d.frames(2); + d.ok("ui.click", json!({"id": "text.captions.style.preset.openSave"})); + d.frames(2); + d.ok("ui.click", json!({"id": "text.captions.style.preset.name"})); + d.ok("ui.type", json!({"text": "Broadcast Blue"})); + d.frames(2); + d.ok("ui.click", json!({"id": "text.captions.style.preset.save"})); + d.frames(3); + d.ok("engine.execute", json!({"command": "captions.setStyle", "params": {"track": track, "size": 22.0}})); + d.ok("ui.click", json!({"id": "text.captions.style.menu"})); + d.frames(2); + d.ok("ui.click", json!({"id": "text.captions.style.preset.0.apply"})); + d.frames(3); + assert_eq!(d.size(track), 42.0, "saved style can be applied again"); +} From 5925c56f375b046401a1182fbe4667e3af662ea9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Mittelst=C3=A4dt?= Date: Thu, 22 Oct 2026 23:38:59 +0200 Subject: [PATCH 2/3] Fix CodeRabbit findings on caption presets --- crates/engine/src/captions.rs | 29 ++++++++++++++--- crates/engine/src/captions_tests.rs | 48 +++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/captions.rs b/crates/engine/src/captions.rs index 95127231a..463d26e8c 100644 --- a/crates/engine/src/captions.rs +++ b/crates/engine/src/captions.rs @@ -50,18 +50,22 @@ struct CaptionStylePresetFile { pub struct CaptionStyleLibrary { user: Vec, dir: Option, + load_error: Option, } impl CaptionStyleLibrary { /// Load saved styles from the app data directory. Invalid files are left untouched and reported. pub fn set_dir(&mut self, data_dir: &Path) { self.dir = Some(data_dir.to_path_buf()); + self.user.clear(); + self.load_error = None; let path = data_dir.join(STYLE_PRESET_FILE); let file = match std::fs::File::open(&path) { Ok(file) => file, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return, Err(e) => { log::warn!("{}: {e}", path.display()); + self.load_error = Some(e.to_string()); return; } }; @@ -69,6 +73,7 @@ impl CaptionStyleLibrary { let read = file.take(MAX_STYLE_PRESET_FILE_BYTES.saturating_add(1)).read_to_end(&mut bytes); if let Err(e) = read { log::warn!("{}: {e}", path.display()); + self.load_error = Some(e.to_string()); return; } match if bytes.len() as u64 > MAX_STYLE_PRESET_FILE_BYTES { @@ -77,18 +82,24 @@ impl CaptionStyleLibrary { parse_style_presets(&bytes) } { Ok(presets) => self.user = presets, - Err(e) => log::warn!("{}: {e}", path.display()), + Err(e) => { + log::warn!("{}: {e}", path.display()); + self.load_error = Some(e); + } } } + /// Return all user-saved caption track style presets. pub fn all(&self) -> &[CaptionStylePreset] { &self.user } + /// Find a saved preset by its exact display name. pub fn find(&self, name: &str) -> Option { self.user.iter().find(|p| p.name == name).map(|p| p.style.clone()) } + /// Save or replace a preset, persisting it before changing the in-memory list. pub fn save(&mut self, name: &str, style: CaptionStyle) -> std::result::Result<(), String> { let name = name.trim(); if name.is_empty() || name.chars().count() > MAX_STYLE_PRESET_NAME_CHARS || name.chars().any(char::is_control) { @@ -96,7 +107,8 @@ impl CaptionStyleLibrary { } let style = normalize_style(style).ok_or_else(|| "caption style has an invalid font or non-finite value".to_string())?; let mut next = self.user.clone(); - if let Some(preset) = next.iter_mut().find(|p| p.name.eq_ignore_ascii_case(name)) { + let key = style_preset_name_key(name); + if let Some(preset) = next.iter_mut().find(|p| style_preset_name_key(&p.name) == key) { preset.name = name.to_string(); preset.style = style; } else { @@ -110,6 +122,7 @@ impl CaptionStyleLibrary { Ok(()) } + /// Delete a preset by its exact display name, persisting the change before removing it in memory. pub fn delete(&mut self, name: &str) -> std::result::Result { let Some(index) = self.user.iter().position(|p| p.name == name) else { return Ok(false) }; let mut next = self.user.clone(); @@ -120,13 +133,21 @@ impl CaptionStyleLibrary { } fn persist(&self, presets: &[CaptionStylePreset]) -> std::result::Result<(), String> { - let Some(dir) = &self.dir else { return Ok(()) }; + if let Some(error) = &self.load_error { + return Err(format!("cannot save caption style presets because the existing file failed to load: {error}")); + } + let Some(dir) = &self.dir else { return Err("caption style preset persistence is not configured".into()) }; std::fs::create_dir_all(dir).map_err(|e| format!("could not create caption style preset directory: {e}"))?; let bytes = style_preset_file_bytes(presets)?; filmcraft_format::atomic_write(&dir.join(STYLE_PRESET_FILE), &bytes).map_err(|e| e.to_string()) } } +/// Normalize preset names with the same Unicode case-folding rule for saves and file validation. +fn style_preset_name_key(name: &str) -> String { + name.trim().to_lowercase() +} + fn normalize_style(mut style: CaptionStyle) -> Option { if style.font.len() > MAX_STYLE_FONT_BYTES || !style.size.is_finite() @@ -169,7 +190,7 @@ fn parse_style_presets(bytes: &[u8]) -> std::result::Result MAX_STYLE_PRESET_NAME_CHARS || name.chars().any(char::is_control) { return Err("caption style preset file contains an invalid name".into()); } - if !names.insert(name.to_lowercase()) { + if !names.insert(style_preset_name_key(&name)) { return Err("caption style preset file contains duplicate names".into()); } preset.name = name.clone(); diff --git a/crates/engine/src/captions_tests.rs b/crates/engine/src/captions_tests.rs index 79317a243..5f1e4f230 100644 --- a/crates/engine/src/captions_tests.rs +++ b/crates/engine/src/captions_tests.rs @@ -216,3 +216,51 @@ fn caption_style_preset_commands_reject_hostile_parameters_without_mutation() { assert!(s.caption_style_presets.all().is_empty()); assert_eq!(s.active_sequence().unwrap().caption_tracks[0].style, original_style); } + +#[test] +fn caption_style_preset_save_does_not_replace_a_file_that_failed_to_load() { + let dir = std::env::temp_dir().join(format!("fc-caption-style-presets-invalid-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("caption-style-presets.json"); + let original = b"not a valid preset file"; + std::fs::write(&path, original).unwrap(); + + let mut library = crate::captions::CaptionStyleLibrary::default(); + library.set_dir(&dir); + assert!(library.save("Replacement", Default::default()).is_err()); + assert!(library.all().is_empty()); + assert_eq!(std::fs::read(&path).unwrap(), original); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn caption_style_preset_save_and_load_share_unicode_name_normalization() { + let dir = std::env::temp_dir().join(format!("fc-caption-style-presets-unicode-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut library = crate::captions::CaptionStyleLibrary::default(); + library.set_dir(&dir); + library.save("Café", Default::default()).unwrap(); + library.save("CAFÉ", Default::default()).unwrap(); + assert_eq!(library.all().len(), 1); + + let mut loaded = crate::captions::CaptionStyleLibrary::default(); + loaded.set_dir(&dir); + assert_eq!(loaded.all().len(), 1); + assert!(loaded.find("CAFÉ").is_some()); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn caption_style_preset_save_requires_a_persistence_directory() { + let mut library = crate::captions::CaptionStyleLibrary::default(); + assert!(library.save("Temporary", Default::default()).is_err()); + assert!(library.all().is_empty()); + + let mut session = demo(); + session.execute("captions.newTrack", json!({"name": "No persistence"})).unwrap(); + assert!(session.execute("captions.stylePreset.save", json!({"track": "C1", "name": "Temporary"})).is_err()); + assert!(session.caption_style_presets.all().is_empty()); +} From bf96677ccd3b9deced460b9ddb308228999a0ca7 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:30:09 +0700 Subject: [PATCH 3/3] Caption style presets: bound font style, file-size check on save, save dialog bound to its track - normalize_style bounds font_style like font, and persist refuses a file over MAX_STYLE_PRESET_FILE_BYTES before writing it, so a saved library always loads again; - the Save Caption Style Preset dialog keeps the track and document epoch it was opened for: Save uses that track, and a replaced document closes it; - the UI test installs the headless runtime main now needs and gives the session a temporary data directory, without which a save has nowhere to go. --- crates/engine/src/captions.rs | 19 +++++++++++++++++++ crates/ui-egui/src/panels/text.rs | 17 +++++++++++------ .../ui-egui/tests/caption_style_presets_ui.rs | 11 +++++++++-- 3 files changed, 39 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/captions.rs b/crates/engine/src/captions.rs index 835d23eef..8d42db2e0 100644 --- a/crates/engine/src/captions.rs +++ b/crates/engine/src/captions.rs @@ -139,6 +139,10 @@ impl CaptionStyleLibrary { let Some(dir) = &self.dir else { return Err("caption style preset persistence is not configured".into()) }; std::fs::create_dir_all(dir).map_err(|e| format!("could not create caption style preset directory: {e}"))?; let bytes = style_preset_file_bytes(presets)?; + // what loads again: a file over the limit would be refused on the next launch + if bytes.len() as u64 > MAX_STYLE_PRESET_FILE_BYTES { + return Err("caption style presets would exceed the 1 MiB file limit".into()); + } filmcraft_format::atomic_write(&dir.join(STYLE_PRESET_FILE), &bytes).map_err(|e| e.to_string()) } } @@ -150,6 +154,7 @@ fn style_preset_name_key(name: &str) -> String { fn normalize_style(mut style: CaptionStyle) -> Option { if style.font.len() > MAX_STYLE_FONT_BYTES + || style.font_style.len() > MAX_STYLE_FONT_BYTES || !style.size.is_finite() || !style.margin.is_finite() || !style.line_spacing.is_finite() @@ -927,4 +932,18 @@ mod preset_file_tests { assert!(parsed.is_ok(), "malformed preset data must return an error instead of panicking"); } } + + /// A style the file couldn't load again is refused on save: the font style is bounded like the font. + #[test] + fn a_preset_with_an_oversized_font_style_is_refused_and_not_written() { + let dir = tempfile::tempdir().expect("temp dir"); + let mut library = CaptionStyleLibrary::default(); + library.set_dir(dir.path()); + let style = CaptionStyle { font_style: "x".repeat(MAX_STYLE_FONT_BYTES + 1), ..CaptionStyle::default() }; + assert!(library.save("Long", style).is_err()); + assert!(library.all().is_empty()); + assert!(!dir.path().join(STYLE_PRESET_FILE).exists()); + library.save("Fine", CaptionStyle::default()).expect("a normal preset saves"); + assert_eq!(library.all().len(), 1); + } } diff --git a/crates/ui-egui/src/panels/text.rs b/crates/ui-egui/src/panels/text.rs index 8213f9c4c..5efdc31e1 100644 --- a/crates/ui-egui/src/panels/text.rs +++ b/crates/ui-egui/src/panels/text.rs @@ -779,7 +779,7 @@ fn style_strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, r: Rect, track_idx: us } } }); - caption_style_preset_save_dialog(app, child.ctx(), tr.id.0, actions); + caption_style_preset_save_dialog(app, child.ctx(), actions); child.min_rect().height() } @@ -803,7 +803,8 @@ fn caption_style_actions_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, track: app.auto.add("text.captions.style.preset.openSave", save_as.rect, "Save current caption style as a preset"); if save_as.clicked() { ui.ctx().data_mut(|d| { - d.insert_temp(egui::Id::unique("caption-style-preset-save-open"), true); + // the track and document it was opened for: Save keeps that track's style + d.insert_temp(egui::Id::unique("caption-style-preset-save-open"), Some((track, app.session.document_epoch))); d.insert_temp(egui::Id::unique("caption-style-preset-name"), String::new()); }); } @@ -828,13 +829,17 @@ fn caption_style_actions_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, track: }); } -fn caption_style_preset_save_dialog(app: &mut FilmcraftApp, ctx: &egui::Context, track: u64, actions: &mut Vec<(String, Value)>) { +/// The Save Caption Style Preset dialog, bound to the track (and document) it was opened for: picking +/// another track meanwhile doesn't change what it saves, and a replaced document closes it. +fn caption_style_preset_save_dialog(app: &mut FilmcraftApp, ctx: &egui::Context, actions: &mut Vec<(String, Value)>) { let open_id = egui::Id::unique("caption-style-preset-save-open"); let name_id = egui::Id::unique("caption-style-preset-name"); - let mut open = ctx.data(|d| d.get_temp::(open_id)).unwrap_or(false); - if !open { + let Some((track, epoch)) = ctx.data(|d| d.get_temp::>(open_id)).flatten() else { return }; + if epoch != app.session.document_epoch { + ctx.data_mut(|d| d.insert_temp(open_id, None::<(u64, u64)>)); return; } + let mut open = true; let mut name = ctx.data(|d| d.get_temp::(name_id)).unwrap_or_default(); let mut close = false; egui::Window::new(tl!("Save Caption Style Preset")) @@ -864,7 +869,7 @@ fn caption_style_preset_save_dialog(app: &mut FilmcraftApp, ctx: &egui::Context, open = false; } ctx.data_mut(|d| { - d.insert_temp(open_id, open); + d.insert_temp(open_id, open.then_some((track, epoch))); d.insert_temp(name_id, name); }); } diff --git a/crates/ui-egui/tests/caption_style_presets_ui.rs b/crates/ui-egui/tests/caption_style_presets_ui.rs index 32d546bd1..8c137cbc0 100644 --- a/crates/ui-egui/tests/caption_style_presets_ui.rs +++ b/crates/ui-egui/tests/caption_style_presets_ui.rs @@ -11,16 +11,23 @@ use serde_json::{Value, json}; struct Driver { harness: Harness<'static, FilmcraftApp>, tx: Sender, + // presets are saved in the app data directory; the test's own, removed with it + _data: tempfile::TempDir, } impl Driver { fn demo() -> Self { let mut session = Session::default(); session.execute("file.openDemoProject", json!({})).expect("demo project"); + let data = tempfile::tempdir().expect("temp data dir"); + session.caption_style_presets.set_dir(data.path()); let (tx, rx) = channel(); let app = FilmcraftApp::new(session).with_control(rx); - let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app); - let mut d = Driver { harness, tx }; + let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |cc| { + filmcraft_ui_egui::framework::install_headless(&cc.egui_ctx); + app + }); + let mut d = Driver { harness, tx, _data: data }; d.frames(4); d }