Merge pull request #2348 from TheGalitube/codex/fix-issue-2330-caption-style-presets

Caption track style copy, paste, and reusable presets
This commit is contained in:
FredApps authored and GitHub committed 2026-12-02 09:02:31 +01:00
commit fa821300a9
5 files changed
+591

No files matched your search

+279
View File
@@ -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};
@@ -19,6 +23,188 @@ use crate::{EngineError, Result, Session};
type Run = fn(&mut Session, &Value) -> Result<Value>;
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<CaptionStylePreset>,
}
/// User-created caption track styles persisted in the application data directory.
#[derive(Default)]
pub struct CaptionStyleLibrary {
user: Vec<CaptionStylePreset>,
dir: Option<PathBuf>,
load_error: Option<String>,
}
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;
}
};
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());
self.load_error = Some(e.to_string());
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());
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<CaptionStyle> {
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) {
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();
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 {
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(())
}
/// 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<bool, String> {
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> {
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)?;
// 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())
}
}
/// 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<CaptionStyle> {
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()
|| !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<Vec<u8>, 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<Vec<CaptionStylePreset>, 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(style_preset_name_key(&name)) {
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,
@@ -431,6 +617,60 @@ pub fn commands() -> Vec<CommandSpec> {
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,
named: crate::commands::NamedKeys::NONE,
},
spec(
"captions.add",
"Add Caption at Playhead",
@@ -668,3 +908,42 @@ fn show_all(s: &mut Session, on: bool) -> Result<Value> {
#[cfg(test)]
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<Vec<u8>> = (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");
}
}
/// 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);
}
}
+106
View File
@@ -429,3 +429,109 @@ fn caption_export_warns_about_characters_608_and_708_cannot_carry() {
assert_eq!(export(&mut s, "srt")["warnings"], json!([]));
let _ = std::fs::remove_dir_all(&dir);
}
#[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);
}
#[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());
}
+7
View File
@@ -580,6 +580,10 @@ pub struct Session {
pub scene_jobs: Vec<scene_detect::PendingScene>,
/// 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<filmcraft_project::CaptionStyle>,
/// 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).
@@ -688,6 +692,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(),
@@ -741,6 +747,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();
+93
View File
@@ -694,6 +694,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_wrapped(|ui| {
ui.spacing_mut().item_spacing = egui::vec2(6.0, 4.0);
caption_style_actions_menu(app, ui, tr.id.0, actions);
let r =
crate::legacy_dropdown::Dropdown::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() {
@@ -778,9 +779,101 @@ fn style_strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, r: Rect, track_idx: us
}
}
});
caption_style_preset_save_dialog(app, child.ctx(), actions);
child.min_rect().height()
}
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| {
// 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());
});
}
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})));
}
});
}
}
});
}
/// 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 Some((track, epoch)) = ctx.data(|d| d.get_temp::<Option<(u64, u64)>>(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::<String>(name_id)).unwrap_or_default();
let mut close = false;
egui::Window::new(tl!("Save Caption Style Preset"))
.id(egui::Id::unique("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.then_some((track, epoch)));
d.insert_temp(name_id, name);
});
}
fn run(app: &mut FilmcraftApp, ui: &egui::Ui, actions: Vec<(String, Value)>) {
let ctx = ui.ctx().clone();
for (cmd, p) in actions {
@@ -0,0 +1,106 @@
//! 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<ControlRequest>,
// 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| {
filmcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
app
});
let mut d = Driver { harness, tx, _data: data };
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<String> {
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");
}