Skip to content

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

Timeline: colour labels for tracks (#1186)

irgendwasmitfelix7ac0269d2c9c
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index f7737f571..65582993a 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -2860,10 +2860,17 @@ fn build() -> Vec<CommandSpec> {
"Track Settings",
[],
None,
- r#"{"track":"V1"|id,"locked":bool?,"syncLock":bool?,"enabled":bool?,"muted":bool?,"solo":bool?,"name":str?,"volumeDb":f64?,"pan":f64?}"#,
+ r#"{"track":"V1"|id,"locked":bool?,"syncLock":bool?,"enabled":bool?,"muted":bool?,"solo":bool?,"name":str?,"volumeDb":f64?,"pan":f64?,"label":"Violet|Iris|…"|""|null?}"#,
has_seq,
|s, p| {
let tr = track_p(s, p, "track", "timeline.setTrack")?.ok_or_else(|| bad("timeline.setTrack", "need `track`"))?;
+ // colour label: a label name, or "" / "None" / null for no colour
+ let label = match p.get("label") {
+ None => None,
+ Some(Value::Null) => Some(None),
+ Some(Value::String(n)) if n.is_empty() || n.eq_ignore_ascii_case("none") => Some(None),
+ Some(v) => Some(Some(v.as_str().and_then(Label::from_name).ok_or_else(|| bad("timeline.setTrack", format!("unknown label {v}")))?)),
+ };
let p = p.clone();
s.edit_sequence("Track Settings", |q, _, _| {
let t = q.track_mut(tr).ok_or(filmcraft_edit::EditError::NoTrack(tr))?;
@@ -2891,6 +2898,9 @@ fn build() -> Vec<CommandSpec> {
if let Some(v) = f64_p(&p, "pan") {
t.pan = v.clamp(-100.0, 100.0);
}
+ if let Some(l) = label {
+ t.label = l;
+ }
Ok(())
})?;
Ok(Value::Null)
@@ -4259,6 +4269,7 @@ pub fn inspect_sequence(s: &Session, id: ItemId, q: &filmcraft_project::Sequence
let tr = |t: &filmcraft_project::Track| {
json!({
"id": t.id.0, "name": t.name, "locked": t.locked, "syncLock": t.sync_lock, "enabled": t.enabled, "muted": t.muted, "solo": t.solo,
+ "label": t.label.map(|l| l.name()),
"items": t.items.iter().map(|i| json!({
"clip": i.id.0, "item": i.item.0, "name": i.name, "start": i.start.0, "duration": i.duration.0,
"startFrame": rate.frame_at(i.start), "durationFrames": rate.frame_at(i.duration), "sourceIn": i.source_in.0, "speed": i.speed, "reverse": i.reverse,
diff --git a/crates/engine/src/track_params_tests.rs b/crates/engine/src/track_params_tests.rs
index 6c243dfa5..707ad38cc 100644
--- a/crates/engine/src/track_params_tests.rs
+++ b/crates/engine/src/track_params_tests.rs
@@ -114,3 +114,38 @@ fn place_on_an_audio_track_places_the_sound_there_and_nothing_else() {
s.execute("timeline.place", json!({"item": with_picture.0, "seconds": 600.0})).unwrap();
assert_eq!(counts(&s), [2, 1, 2, 2]);
}
+
+/// Track colour labels (#1186): set, shown by `sequence.inspect`, saved with the project,
+/// cleared with "" / null, one undo step each; unknown names are refused.
+#[test]
+fn a_track_carries_a_colour_label() {
+ let mut s = demo();
+ let label = |s: &mut Session, kind: &str| s.execute("sequence.inspect", json!({})).unwrap()[kind][0]["label"].clone();
+ assert_eq!(label(&mut s, "video"), json!(null));
+ s.execute("timeline.setTrack", json!({"track": "V1", "label": "Forest"})).unwrap();
+ s.execute("timeline.setTrack", json!({"track": "A1", "label": "Mango"})).unwrap();
+ assert_eq!(label(&mut s, "video"), json!("Forest"));
+ assert_eq!(label(&mut s, "audio"), json!("Mango"));
+ // saved with the project, and a project from before the field still loads
+ let text = serde_json::to_string(&*s.project).unwrap();
+ let back: filmcraft_project::Project = serde_json::from_str(&text).unwrap();
+ let q = back.sequence(s.state.active_sequence.unwrap()).unwrap();
+ assert_eq!(q.video_tracks[0].label, Some(filmcraft_project::Label::Forest));
+ let mut old = serde_json::to_value(&q.video_tracks[0]).unwrap();
+ old.as_object_mut().unwrap().remove("label");
+ let old: filmcraft_project::Track = serde_json::from_value(old).unwrap();
+ assert_eq!(old.label, None);
+ // a plain track does not write the key at all
+ assert!(serde_json::to_value(&q.video_tracks[1]).unwrap().get("label").is_none());
+ // clear, undo, refuse
+ s.execute("timeline.setTrack", json!({"track": "V1", "label": ""})).unwrap();
+ assert_eq!(label(&mut s, "video"), json!(null));
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(label(&mut s, "video"), json!("Forest"));
+ s.execute("timeline.setTrack", json!({"track": "V1", "label": null})).unwrap();
+ assert_eq!(label(&mut s, "video"), json!(null));
+ assert!(matches!(s.execute("timeline.setTrack", json!({"track": "V1", "label": "Chartreuse"})), Err(EngineError::BadParams { .. })));
+ // other settings leave the label alone
+ s.execute("timeline.setTrack", json!({"track": "A1", "muted": true})).unwrap();
+ assert_eq!(label(&mut s, "audio"), json!("Mango"));
+}
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index fb55786db..5d95c5b80 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -760,6 +760,9 @@ pub struct Track {
/// Audio Track Mixer state: automation mode and lanes, sends, output, record arm.
#[serde(default)]
pub mixer: MixerStrip,
+ /// Colour label tinting the track's header and lane background (`None` = no colour).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub label: Option<Label>,
}
impl Track {
@@ -780,6 +783,7 @@ impl Track {
pan: 0.0,
effects: Vec::new(),
mixer: MixerStrip::default(),
+ label: None,
}
}
pub fn end(&self) -> Tick {
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 0af8835d1..18212ecf8 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -3610,3 +3610,4 @@
Shows the version, community links and credits in a FilmCraft window. Muestra la versión, los enlaces de la comunidad y los créditos en una ventana de FilmCraft.
Couldn't open your web browser No se pudo abrir el navegador web
Open this address in your browser yourself: Abre esta dirección tú mismo en el navegador:
+ Track Color Color de pista
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 1075b0c15..f6c30c44a 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -3577,3 +3577,4 @@
Export the labels to a preset file… Exporter les étiquettes dans un fichier de paramètre prédéfini…
Show the presets folder Afficher le dossier des paramètres prédéfinis
Delete this preset Supprimer ce paramètre prédéfini
+ Track Color Couleur de la piste
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 508a6e9d4..c5e21b8ab 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -3575,3 +3575,4 @@
Appearance Settings… Pengaturan Tampilan…
Add to favorites Tambahkan ke favorit
Remove from favorites Hapus dari favorit
+ Track Color Warna Trek
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 22d47ccbd..195e23c27 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -3601,3 +3601,4 @@
Shows the version, community links and credits in a FilmCraft window. Mostra la versione, i link della community e i riconoscimenti in una finestra di FilmCraft.
Couldn't open your web browser Impossibile aprire il browser web
Open this address in your browser yourself: Apri tu questo indirizzo nel browser:
+ Track Color Colore traccia
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index b6a7fb8a2..e836f30fc 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3609,3 +3609,4 @@
Shows the version, community links and credits in a FilmCraft window. バージョン、コミュニティへのリンク、クレジットを FilmCraft のウィンドウに表示します。
Couldn't open your web browser ウェブブラウザーを開けませんでした
Open this address in your browser yourself: このアドレスをご自身でブラウザーで開いてください:
+ Track Color トラックカラー
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 20341b9a6..254178be4 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -3596,3 +3596,4 @@
Shows the version, community links and credits in a FilmCraft window. FilmCraft 창에 버전, 커뮤니티 링크, 제작진을 보여 줍니다.
Couldn't open your web browser 웹 브라우저를 열 수 없습니다
Open this address in your browser yourself: 이 주소를 브라우저에서 직접 여세요:
+ Track Color 트랙 색상
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index aeb0e0691..98f77f999 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -3578,3 +3578,4 @@
# The native macOS application menu (Settings…).
Settings Preferências
+ Track Color Cor da trilha
diff --git a/crates/ui-egui/src/i18n/zh-cn.tsv b/crates/ui-egui/src/i18n/zh-cn.tsv
index 066279eef..ab60b8578 100644
--- a/crates/ui-egui/src/i18n/zh-cn.tsv
+++ b/crates/ui-egui/src/i18n/zh-cn.tsv
@@ -3585,3 +3585,4 @@
Shows the version, community links and credits in a FilmCraft window. 在 FilmCraft 窗口中显示版本、社区链接和致谢。
Couldn't open your web browser 无法打开网页浏览器
Open this address in your browser yourself: 请自行在浏览器中打开此地址:
+ Track Color 轨道颜色
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index c4c369298..1159ec0a5 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -294,6 +294,10 @@ pub fn zoom_about(v: &mut TimelineView, factor: f64, anchor_secs: f64, width: f3
v.target_scroll = (anchor_secs - x as f64 / new).max(0.0);
}
+/// How strongly a track's colour label tints its header and its lane.
+const TRACK_HEADER_TINT: f32 = 0.18;
+const TRACK_LANE_TINT: f32 = 0.10;
+
fn label_color(app: &FilmcraftApp, l: filmcraft_project::Label) -> Color32 {
crate::panels::settings::label_color(app, l)
}
@@ -455,6 +459,10 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
let bg = if r.index % 2 == 0 { t.tl_track_bg } else { t.tl_track_bg_alt };
painter.rect_filled(row, 0.0, bg);
+ // a track's colour label tints its lane (#1186)
+ if let Some(l) = seq.track(r.track).and_then(|tr| tr.label) {
+ painter.rect_filled(row, 0.0, label_color(app, l).gamma_multiply(TRACK_LANE_TINT));
+ }
painter.line_segment([pos2(row.min.x, r.rect.max.y - 0.5), pos2(row.max.x, r.rect.max.y - 0.5)], Stroke::new(1.0, t.separator));
// the top video track also gets a line above it
if r.kind == TrackKind::Video && r.index + 1 == nv {
@@ -1258,6 +1266,36 @@ fn draw_headers(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, rows:
}
let p = ui.painter().with_clip_rect(visible);
p.rect_filled(hrect, 0.0, t.tl_header_bg);
+ // 0. colour label (#1186): a tint over the header, and the strip at its left edge, which
+ // opens the colour menu
+ let strip = Rect::from_min_max(hrect.min, pos2(hrect.min.x + 9.0, hrect.max.y));
+ if let Some(l) = tr.label {
+ let c = label_color(app, l);
+ p.rect_filled(hrect, 0.0, c.gamma_multiply(TRACK_HEADER_TINT));
+ p.rect_filled(Rect::from_min_max(strip.min, pos2(strip.min.x + 5.0, strip.max.y)), 0.0, c);
+ }
+ let cresp = ui.interact(strip.intersect(visible), egui::Id::new(("trackColor", r.track.0)), Sense::click()).on_hover_text(tl!("Track Color"));
+ app.auto.add(&format!("timeline.track.{}{}.color", if r.kind == TrackKind::Video { "V" } else { "A" }, r.index + 1), strip, "Track Color");
+ if cresp.hovered() && tr.label.is_none() {
+ p.rect_filled(Rect::from_min_max(strip.min, pos2(strip.min.x + 5.0, strip.max.y)), 0.0, t.hover);
+ }
+ egui::Popup::menu(&cresp).show(|ui| {
+ let prefix = format!("timeline.track.{}{}.color", if r.kind == TrackKind::Video { "V" } else { "A" }, r.index + 1);
+ let none = ui.selectable_label(tr.label.is_none(), tl!("None"));
+ app.auto.add(&format!("{prefix}.None"), none.rect, "None");
+ if none.clicked() {
+ actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "label": ""})));
+ ui.close();
+ }
+ // the user's label names and colours, as in Edit ▸ Label
+ let labels = app.session.prefs.labels.clone();
+ for l in filmcraft_project::Label::ALL {
+ if crate::menus::label_choice(ui, &mut app.auto, &labels, l, &prefix).clicked() {
+ actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "label": l.name()})));
+ ui.close();
+ }
+ }
+ });
p.line_segment([pos2(hrect.min.x, hrect.max.y - 0.5), pos2(hrect.max.x, hrect.max.y - 0.5)], Stroke::new(1.0, t.separator));
if r.kind == TrackKind::Video && r.index + 1 == seq.video_tracks.len() {
p.line_segment([pos2(hrect.min.x, hrect.min.y + 0.5), pos2(hrect.max.x, hrect.min.y + 0.5)], Stroke::new(1.0, t.separator));
diff --git a/crates/ui-egui/tests/track_color_ui.rs b/crates/ui-egui/tests/track_color_ui.rs
new file mode 100644
index 000000000..f20d76899
--- /dev/null
+++ b/crates/ui-egui/tests/track_color_ui.rs
@@ -0,0 +1,161 @@
+//! Headless UI test of track colour labels (#1186): the strip at the left edge of a track header
+//! opens the colour menu; the label tints the header and the lane and is an undoable track setting.
+//!
+//! Set `FILMCRAFT_UI_SNAPSHOT_DIR=<dir>` to also render offscreen with wgpu and write `track-color-*.png`.
+
+#![allow(dead_code)]
+
+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>,
+ snapshots: Option<std::path::PathBuf>,
+}
+
+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 snapshots = std::env::var_os("FILMCRAFT_UI_SNAPSHOT_DIR").map(std::path::PathBuf::from);
+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000);
+ if snapshots.is_some() {
+ b = b.wgpu();
+ }
+ let harness = b.build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, snapshots };
+ 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 call(&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() {
+ return v;
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+
+ fn ok(&mut self, method: &str, params: Value) -> Value {
+ let v = self.call(method, params.clone());
+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");
+ v["result"].clone()
+ }
+
+ fn exec(&mut self, command: &str, params: Value) -> Value {
+ self.ok("engine.execute", json!({"command": command, "params": params}))
+ }
+
+ fn click(&mut self, id: &str) {
+ self.ok("ui.click", json!({"id": id}));
+ self.frames(2);
+ }
+
+ fn element(&mut self, id: &str) -> Option<[f32; 4]> {
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ v.as_array()?.iter().find(|e| e["id"] == id).map(|e| {
+ let r = &e["rect"];
+ [r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32, r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32]
+ })
+ }
+
+ 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()
+ }
+
+ /// Offscreen render of the window (or the bounding box of the elements under `prefix`).
+ fn snapshot(&mut self, name: &str, prefix: Option<&str>) {
+ let Some(dir) = self.snapshots.clone() else { return };
+ let crop = prefix.map(|p| {
+ let v = self.ok("ui.elements", json!({"prefix": p}));
+ let mut bb = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
+ for e in v.as_array().unwrap() {
+ let r = &e["rect"];
+ let (x, y, w, h) = (r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32, r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32);
+ bb = [bb[0].min(x), bb[1].min(y), bb[2].max(x + w), bb[3].max(y + h)];
+ }
+ bb
+ });
+ self.frames(2);
+ let img = match self.harness.render() {
+ Ok(i) => i,
+ Err(e) => {
+ eprintln!("snapshot {name} skipped: {e}");
+ return;
+ }
+ };
+ let ppp = img.width() as f32 / 1600.0;
+ let img = match crop {
+ Some(bb) => {
+ let x0 = ((bb[0] - 24.0) * ppp).max(0.0) as u32;
+ let y0 = ((bb[1] - 30.0) * ppp).max(0.0) as u32;
+ let x1 = (((bb[2] + 16.0) * ppp) as u32).min(img.width());
+ let y1 = (((bb[3] + 46.0) * ppp) as u32).min(img.height());
+ image::imageops::crop_imm(&img, x0, y0, x1 - x0, y1 - y0).to_image()
+ }
+ None => img,
+ };
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join(format!("{name}.png"));
+ img.save(&path).unwrap();
+ eprintln!("snapshot: {}", path.display());
+ }
+}
+
+fn label(d: &mut Driver, kind: &str, index: usize) -> Value {
+ d.exec("sequence.inspect", json!({}))[kind][index]["label"].clone()
+}
+
+#[test]
+fn the_track_header_strip_sets_a_colour_label() {
+ let mut d = Driver::demo();
+ assert_eq!(label(&mut d, "video", 0), json!(null));
+ let ids = d.ids("timeline.track.");
+ for id in ["timeline.track.V1.color", "timeline.track.A1.color"] {
+ assert!(ids.iter().any(|i| i == id), "{id} missing from {ids:?}");
+ }
+ // the strip sits left of the source patch, inside the header
+ let strip = d.element("timeline.track.V1.color").unwrap();
+ let patch = d.element("timeline.track.V1.sourcePatch").unwrap();
+ assert!(strip[0] + strip[2] <= patch[0], "strip {strip:?} overlaps the source patch {patch:?}");
+ d.click("timeline.track.V1.color");
+ let menu = d.ids("timeline.track.V1.color.");
+ assert!(menu.iter().any(|i| i == "timeline.track.V1.color.Forest") && menu.iter().any(|i| i == "timeline.track.V1.color.None"), "{menu:?}");
+ d.click("timeline.track.V1.color.Forest");
+ assert_eq!(label(&mut d, "video", 0), json!("Forest"));
+ assert!(!d.ids("timeline.track.V1.color.").iter().any(|i| i == "timeline.track.V1.color.Forest"), "the menu closes");
+ // audio tracks too
+ d.click("timeline.track.A1.color");
+ d.click("timeline.track.A1.color.Mango");
+ assert_eq!(label(&mut d, "audio", 0), json!("Mango"));
+ d.snapshot("track-color-labels", None);
+ // None clears; undo brings it back
+ d.click("timeline.track.V1.color");
+ d.click("timeline.track.V1.color.None");
+ assert_eq!(label(&mut d, "video", 0), json!(null));
+ d.exec("edit.undo", json!({}));
+ assert_eq!(label(&mut d, "video", 0), json!("Forest"));
+}