Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

Captions: render the track font and add a font picker

impostazioni6aa4146c1628
diff --git a/crates/captions/src/burn.rs b/crates/captions/src/burn.rs
index 5c43e5251..77c9bf848 100644
--- a/crates/captions/src/burn.rs
+++ b/crates/captions/src/burn.rs
@@ -49,13 +49,10 @@ impl Overlay {
}
}
-/// The caption face: Inter SemiBold at `px`.
-fn caption_style(px: f32) -> TextStyle {
- TextStyle { style: "SemiBold".into(), size: px, ..Default::default() }
-}
-
-fn measure(text: &str, px: f32) -> f32 {
- filmcraft_text::measure(text, &caption_style(px))
+/// The caption face: the track's font family (Inter when empty or not installed) in SemiBold at `px`.
+fn caption_style(font: &str, px: f32) -> TextStyle {
+ let family = if font.trim().is_empty() { filmcraft_text::fonts::DEFAULT_FAMILY } else { font.trim() };
+ TextStyle { family: family.into(), style: "SemiBold".into(), size: px, ..Default::default() }
}
fn lin(c: [u8; 4]) -> [f32; 4] {
@@ -64,12 +61,12 @@ fn lin(c: [u8; 4]) -> [f32; 4] {
}
/// Word-wrap one line to `max_w` pixels.
-fn wrap(line: &str, px: f32, max_w: f32) -> Vec<String> {
+fn wrap(line: &str, ts: &TextStyle, max_w: f32) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
for word in line.split(' ') {
let cand = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") };
- if !cur.is_empty() && measure(&cand, px) > max_w {
+ if !cur.is_empty() && filmcraft_text::measure(&cand, ts) > max_w {
out.push(std::mem::take(&mut cur));
cur = word.to_string();
} else {
@@ -115,16 +112,17 @@ pub fn render_caption(c: &Caption, style: &CaptionStyle, w: usize, h: usize) ->
let scale = h as f32 / 1080.0;
let px = (style.size * scale).max(4.0);
let max_w = w as f32 * 0.9;
+ let ts = caption_style(&style.font, px);
let mut lines: Vec<String> = Vec::new();
// (speaker names are metadata; like Premiere, they are not burned in)
for l in c.plain_lines() {
- lines.extend(wrap(l.trim(), px, max_w));
+ lines.extend(wrap(l.trim(), &ts, max_w));
}
lines.retain(|l| !l.is_empty());
if lines.is_empty() {
return None;
}
- let vm = filmcraft_text::fonts::face(filmcraft_text::resolve("Inter", "SemiBold").face).metrics(px);
+ let vm = filmcraft_text::fonts::face(filmcraft_text::resolve(&ts.family, &ts.style).face).metrics(px);
let (asc, desc) = (vm.ascent, vm.descent);
let lh = px * style.line_spacing.max(0.8);
let pad_x = (px * 0.3).round();
@@ -141,7 +139,7 @@ pub fn render_caption(c: &Caption, style: &CaptionStyle, w: usize, h: usize) ->
.max(0.0)
.round();
let side = w as f32 * 0.05;
- let widths: Vec<f32> = lines.iter().map(|l| measure(l, px)).collect();
+ let widths: Vec<f32> = lines.iter().map(|l| filmcraft_text::measure(l, &ts)).collect();
let xs: Vec<f32> = widths
.iter()
.map(|&lw| match align {
@@ -176,7 +174,7 @@ pub fn render_caption(c: &Caption, style: &CaptionStyle, w: usize, h: usize) ->
}
}
let baseline = lt + (lh - (asc + desc)) / 2.0 + asc;
- let l = layout(line, &caption_style(px), &ParagraphStyle::default());
+ let l = layout(line, &ts, &ParagraphStyle::default());
let mut m = filmcraft_text::Mask { w: ow, h: oh, a: std::mem::take(&mut cover) };
render::draw(&l, &render::at(xs[i], baseline.round()), &mut m, (ox, oy));
cover = m.a;
@@ -305,6 +303,27 @@ mod tests {
assert!(o.px.chunks(4).any(|p| p[0] > 0.9 && p[1] < 0.05 && p[3] > 0.9), "red outline pixels");
}
+ #[test]
+ fn track_font_is_used() {
+ // the style's font used to be ignored (always Inter)
+ let inter = render_caption(&cap("Hello world"), &CaptionStyle::default(), 1920, 1080).unwrap();
+ let serif = CaptionStyle { font: "Noto Serif".into(), ..Default::default() };
+ let serif = render_caption(&cap("Hello world"), &serif, 1920, 1080).unwrap();
+ assert_ne!((inter.w, &inter.px), (serif.w, &serif.px), "Noto Serif renders like Inter");
+ let mono = CaptionStyle { font: "jetbrains mono".into(), ..Default::default() };
+ let mono = render_caption(&cap("Hello world"), &mono, 1920, 1080).unwrap();
+ assert_ne!((inter.w, &inter.px), (mono.w, &mono.px), "JetBrains Mono renders like Inter");
+ }
+
+ #[test]
+ fn unknown_or_empty_font_falls_back_to_inter() {
+ let inter = render_caption(&cap("Hello"), &CaptionStyle::default(), 1280, 720).unwrap();
+ for font in ["", " ", "No Such Font 123"] {
+ let st = CaptionStyle { font: font.into(), ..Default::default() };
+ assert_eq!(render_caption(&cap("Hello"), &st, 1280, 720), Some(inter.clone()), "font {font:?}");
+ }
+ }
+
#[test]
fn hidden_track_draws_nothing() {
let mut t = CaptionTrack::new(TrackId(1), "S".into(), CaptionFormat::Subtitle);
diff --git a/crates/project/src/caption.rs b/crates/project/src/caption.rs
index 013c6efc8..d8236e8bd 100644
--- a/crates/project/src/caption.rs
+++ b/crates/project/src/caption.rs
@@ -74,7 +74,7 @@ pub enum CaptionAnchor {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CaptionStyle {
- /// Font family name. Only the bundled Inter is rendered today; other names fall back to it.
+ /// Font family name (bundled, craft-fonts or system); unknown or empty names fall back to Inter.
pub font: String,
/// Font size in pixels for a 1080-line frame (scaled with the frame height).
pub size: f32,
diff --git a/crates/ui-egui/src/panels/text.rs b/crates/ui-egui/src/panels/text.rs
index 4408779df..e5b83ba66 100644
--- a/crates/ui-egui/src/panels/text.rs
+++ b/crates/ui-egui/src/panels/text.rs
@@ -385,6 +385,22 @@ 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;
+ 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();
+ }
+ // names starting with '.' are macOS-private system faces (UI/fallback fonts, some without a space glyph)
+ for (f, _) in filmcraft_text::families().into_iter().filter(|(f, _)| !f.starts_with('.')) {
+ let resp = ui.selectable_label(f.eq_ignore_ascii_case(&st.font), &f);
+ if ui.is_rect_visible(resp.rect) {
+ app.auto.add(&format!("text.captions.style.font.option.{f}"), resp.rect, &f);
+ }
+ if resp.clicked() {
+ actions.push(("captions.setStyle".into(), json!({"track": tr.id.0, "font": f})));
+ }
+ }
+ });
+ app.auto.add("text.captions.style.font", r.response.rect, "Caption font");
let mut size = st.size;
let resp = ui.add(egui::DragValue::new(&mut size).range(8.0..=200.0).speed(0.5).suffix(" px"));
app.auto.add("text.captions.style.size", resp.rect, "Caption size");
diff --git a/crates/ui-egui/tests/captions_font_ui.rs b/crates/ui-egui/tests/captions_font_ui.rs
new file mode 100644
index 000000000..bd6822d55
--- /dev/null
+++ b/crates/ui-egui/tests/captions_font_ui.rs
@@ -0,0 +1,95 @@
+//! Headless UI test of the caption track font picker in the Text panel's Captions tab: picking a
+//! family sets the track style's font, and macOS-private (`.`-prefixed) faces are not offered.
+
+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>,
+}
+
+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<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 font(&mut self, track: u64) -> String {
+ let r = self.ok("engine.execute", json!({"command": "captions.list", "params": {}}));
+ let t = r["tracks"].as_array().unwrap().iter().find(|t| t["id"] == json!(track)).expect("track").clone();
+ t["style"]["font"].as_str().unwrap().to_string()
+ }
+}
+
+#[test]
+fn caption_font_picker_sets_the_track_font() {
+ 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.add", "params": {"track": track, "text": "Hello", "seconds": 1.0}}));
+ d.frames(2);
+ d.ok("ui.click", json!({"id": "text.tab.Captions"}));
+ d.frames(3);
+ assert_eq!(d.font(track), "Inter");
+
+ d.ok("ui.click", json!({"id": "text.captions.style.font"}));
+ d.frames(3);
+ let options = d.ids("text.captions.style.font.option.");
+ assert!(!options.is_empty(), "the font list is open");
+ assert!(!options.iter().any(|o| o.starts_with("text.captions.style.font.option..")), "private faces offered: {options:?}");
+ // with system fonts the list is long: scroll until the bundled serif is on screen
+ let serif = "text.captions.style.font.option.Noto Serif";
+ for _ in 0..200 {
+ let shown = d.ids("text.captions.style.font.option.");
+ if shown.iter().any(|o| o == serif) {
+ break;
+ }
+ // wheel over a row in the middle (the edge rows are clipped by the popup)
+ let Some(mid) = shown.get(shown.len() / 2) else { break };
+ d.ok("ui.scroll", json!({"id": mid, "dy": -120.0}));
+ d.frames(2);
+ }
+ d.ok("ui.click", json!({"id": serif}));
+ d.frames(3);
+ assert_eq!(d.font(track), "Noto Serif");
+}