Skip to content

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

Group ui-egui panel and bench inputs for strict Clippy checks

Dylan M. Taylordb860af30308
diff --git a/crates/ui-egui/examples/bench/playback.rs b/crates/ui-egui/examples/bench/playback.rs
index 94f56d103..4805aeefd 100644
--- a/crates/ui-egui/examples/bench/playback.rs
+++ b/crates/ui-egui/examples/bench/playback.rs
@@ -435,17 +435,8 @@ impl Bench {
/// - `drags` playhead drags: the playhead moves `drag_frames` frames, one step per display
/// refresh (each refresh asks for the frame under the playhead, superseding the previous
/// request), then stops; time from the stop until the frame under it is on screen.
- pub fn scrub(
- &self,
- s: &Session,
- seq: ItemId,
- display: &mut Display,
- scale: f32,
- seeks: usize,
- drags: usize,
- drag_frames: i64,
- timeout: Duration,
- ) -> ScrubReport {
+ pub fn scrub(&self, s: &Session, seq: ItemId, display: &mut Display, scale: f32, plan: ScrubPlan) -> ScrubReport {
+ let ScrubPlan { seeks, drags, drag_frames, timeout } = plan;
let q = s.project.sequence(seq).expect("seq");
let rate = q.settings.frame_rate;
let frames = rate.frame_at(q.duration()).max(1);
@@ -508,6 +499,15 @@ impl Bench {
}
}
+/// What [`Bench::scrub`] does: seek and drag counts, drag length in frames, per-request timeout.
+#[derive(Clone, Copy)]
+pub struct ScrubPlan {
+ pub seeks: usize,
+ pub drags: usize,
+ pub drag_frames: i64,
+ pub timeout: Duration,
+}
+
/// Result of [`Bench::scrub`].
#[derive(Default)]
pub struct ScrubReport {
diff --git a/crates/ui-egui/examples/bench/sections.rs b/crates/ui-egui/examples/bench/sections.rs
index 3f5192bef..391402a67 100644
--- a/crates/ui-egui/examples/bench/sections.rs
+++ b/crates/ui-egui/examples/bench/sections.rs
@@ -256,7 +256,7 @@ pub fn scrub(o: &Opts) -> Vec<Value> {
for _ in 0..o.repeat {
let bench = new_bench(&s, 0.0);
let mut display = Display::new(o.gpu);
- let r = bench.scrub(&s, seq, &mut display, 1.0, seeks, drags, 24, Duration::from_secs(8));
+ let r = bench.scrub(&s, seq, &mut display, 1.0, playback::ScrubPlan { seeks, drags, drag_frames: 24, timeout: Duration::from_secs(8) });
let positions = (seeks + drags) as f64;
let row = json!({
"scenario": scenario,
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 3194219e6..79e586d42 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -166,34 +166,8 @@ fn handle_ui_set(app: &mut FilmcraftApp, ctx: &egui::Context, p: &Value) -> Outc
app.ui.program.res =
PlaybackRes::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r) || format!("{x:?}").eq_ignore_ascii_case(r)).unwrap_or(app.ui.program.res);
}
- if let Some(tl) = p.get("timeline") {
- if let Some(v) = tl.get("pps").and_then(Value::as_f64) {
- app.ui.timeline.target_pps = v;
- }
- if let Some(v) = tl.get("scroll").and_then(Value::as_f64) {
- app.ui.timeline.target_scroll = v;
- }
- if tl.get("fit").and_then(Value::as_bool) == Some(true) {
- app.ui.timeline.fit_pending = true;
- }
- if let Some(v) = tl.get("videoTrackHeight").and_then(Value::as_f64) {
- app.ui.timeline.video_track_h = v as f32;
- }
- if let Some(v) = tl.get("audioTrackHeight").and_then(Value::as_f64) {
- app.ui.timeline.audio_track_h = v as f32;
- }
- // Show Video Thumbnails: "off" or a mode ("head", "headAndTail", "continuous")
- if let Some(m) = tl.get("thumbnails").and_then(Value::as_str) {
- if m.eq_ignore_ascii_case("off") {
- app.ui.timeline.show_thumbnails = false;
- } else {
- let Some(mode) = ThumbnailMode::from_name(m) else {
- return err(format!("unknown thumbnail mode `{m}` (off, head, headAndTail, continuous)"));
- };
- app.ui.timeline.show_thumbnails = true;
- app.ui.timeline.thumbnail_mode = mode;
- }
- }
+ if let Err(e) = set_timeline(app, p) {
+ return err(e);
}
if let Some(q) = s("effectsSearch") {
app.ui.effects_search = q.to_string();
@@ -210,19 +184,8 @@ fn handle_ui_set(app: &mut FilmcraftApp, ctx: &egui::Context, p: &Value) -> Outc
app.ui.program.safe_margins = v;
}
// Monitor view state (serde fields of `MonitorView`), merged into the current state.
- for k in ["program", "source"] {
- let Some(patch) = p.get(k).and_then(Value::as_object) else { continue };
- let mv = if k == "program" { &mut app.ui.program } else { &mut app.ui.source };
- let mut cur = serde_json::to_value(&*mv).unwrap_or_default();
- if let Some(o) = cur.as_object_mut() {
- for (f, v) in patch {
- o.insert(f.clone(), v.clone());
- }
- }
- match serde_json::from_value(cur) {
- Ok(m) => *mv = m,
- Err(e) => return err(format!("`{k}`: {e}")),
- }
+ if let Err(e) = set_monitor_views(app, p) {
+ return err(e);
}
// Export mode state (`panels::export_mode::ExportUi`), deep-merged; `"preset": name`
// applies that preset's settings first
@@ -250,18 +213,8 @@ fn handle_ui_set(app: &mut FilmcraftApp, ctx: &egui::Context, p: &Value) -> Outc
}
}
// Project panel / Media Browser view state (`panels::project`, `panels::media_browser`), merged
- for (k, which) in [("projectPanel", 0), ("mediaBrowser", 1)] {
- let Some(patch) = p.get(k) else { continue };
- let mut cur = if which == 0 { serde_json::to_value(&app.ui.project_panel) } else { serde_json::to_value(&app.ui.media_browser) }.unwrap_or_default();
- merge(&mut cur, patch);
- let r = if which == 0 {
- serde_json::from_value(cur).map(|v| app.ui.project_panel = v)
- } else {
- serde_json::from_value(cur).map(|v| app.ui.media_browser = v)
- };
- if let Err(e) = r {
- return err(format!("`{k}`: {e}"));
- }
+ if let Err(e) = set_panel_views(app, p) {
+ return err(e);
}
// Essential Graphics ▸ Browse and the template / font dialogs (`panels::graphics_templates`), merged
if let Some(patch) = p.get("gfxTemplates") {
@@ -273,51 +226,10 @@ fn handle_ui_set(app: &mut FilmcraftApp, ctx: &egui::Context, p: &Value) -> Outc
}
}
// the Type tool's text editing state: {"clip", "layer", "caret", "anchor"} (byte offsets) or null
- if let Some(v) = p.get("gfxEdit") {
- match serde_json::from_value::<Option<crate::state::GfxEdit>>(v.clone()) {
- Ok(mut e) => {
- // An explicit `ui.set.gfxEdit {clip, layer}` names the layer currently at
- // that index. Resolve its identity from the document instead of inheriting
- // a stale uid/fingerprint from a previous edit session: after a reorder,
- // delete or undo the requested index may now hold a different layer.
- if let Some(new) = e.as_mut() {
- match crate::panels::graphics::current_layer_identity(&app.session, new.clip, new.layer) {
- Some((uid, fingerprint)) => {
- new.uid = uid;
- new.fingerprint = fingerprint;
- }
- None => {
- new.uid = 0;
- new.fingerprint = 0;
- }
- }
- }
- let changed = match (&app.ui.gfx_edit, &e) {
- (None, None) => false,
- (Some(old), Some(new)) => {
- // A stable uid is the owner key. The compact fingerprint only
- // decides identity for a uid-less layer, and zero there means
- // "the requested index" rather than a different owner.
- old.clip != new.clip
- || old.layer != new.layer
- || old.uid != new.uid
- || (new.uid == 0 && old.fingerprint != 0 && old.fingerprint != new.fingerprint)
- }
- _ => true,
- };
- if changed {
- app.restart_ime_target();
- } else if let (Some(old), Some(new)) = (&app.ui.gfx_edit, &e)
- && (old.caret, old.anchor) != (new.caret, new.anchor)
- {
- // Caret is not part of the stable owner. Only a known composition
- // becomes stale; commit-only input without one remains eligible.
- app.invalidate_ime_composition();
- }
- app.ui.gfx_edit = e;
- }
- Err(e) => return err(format!("`gfxEdit`: {e}")),
- }
+ if let Some(v) = p.get("gfxEdit")
+ && let Err(e) = set_gfx_edit(app, v)
+ {
+ return err(e);
}
// fields of the open Edit / Clip / File dialog (`panels::clip_dialogs`)
if let Some(m) = p.get("clipDialog").and_then(Value::as_object) {
@@ -336,6 +248,131 @@ fn handle_ui_set(app: &mut FilmcraftApp, ctx: &egui::Context, p: &Value) -> Outc
ok(Value::Null)
}
+/// The `timeline` part of a `ui.set` payload: playback zoom and scroll, fit, track heights
+/// and the thumbnail mode.
+fn set_timeline(app: &mut FilmcraftApp, p: &Value) -> Result<(), String> {
+ let Some(tl) = p.get("timeline") else { return Ok(()) };
+ if let Some(v) = tl.get("pps").and_then(Value::as_f64) {
+ app.ui.timeline.target_pps = v;
+ }
+ if let Some(v) = tl.get("scroll").and_then(Value::as_f64) {
+ app.ui.timeline.target_scroll = v;
+ }
+ if tl.get("fit").and_then(Value::as_bool) == Some(true) {
+ app.ui.timeline.fit_pending = true;
+ }
+ if let Some(v) = tl.get("videoTrackHeight").and_then(Value::as_f64) {
+ app.ui.timeline.video_track_h = v as f32;
+ }
+ if let Some(v) = tl.get("audioTrackHeight").and_then(Value::as_f64) {
+ app.ui.timeline.audio_track_h = v as f32;
+ }
+ // Show Video Thumbnails: "off" or a mode ("head", "headAndTail", "continuous")
+ if let Some(m) = tl.get("thumbnails").and_then(Value::as_str) {
+ if m.eq_ignore_ascii_case("off") {
+ app.ui.timeline.show_thumbnails = false;
+ } else {
+ let Some(mode) = ThumbnailMode::from_name(m) else {
+ return Err(format!("unknown thumbnail mode `{m}` (off, head, headAndTail, continuous)"));
+ };
+ app.ui.timeline.show_thumbnails = true;
+ app.ui.timeline.thumbnail_mode = mode;
+ }
+ }
+ Ok(())
+}
+
+/// The `gfxEdit` part of a `ui.set` payload: which layer the Type tool edits. Resolves that
+/// layer's identity from the document and refreshes the IME target when it changes.
+fn set_gfx_edit(app: &mut FilmcraftApp, v: &Value) -> Result<(), String> {
+ match serde_json::from_value::<Option<crate::state::GfxEdit>>(v.clone()) {
+ Ok(mut e) => {
+ // An explicit `ui.set.gfxEdit {clip, layer}` names the layer currently at
+ // that index. Resolve its identity from the document instead of inheriting
+ // a stale uid/fingerprint from a previous edit session: after a reorder,
+ // delete or undo the requested index may now hold a different layer.
+ if let Some(new) = e.as_mut() {
+ match crate::panels::graphics::current_layer_identity(&app.session, new.clip, new.layer) {
+ Some((uid, fingerprint)) => {
+ new.uid = uid;
+ new.fingerprint = fingerprint;
+ }
+ None => {
+ new.uid = 0;
+ new.fingerprint = 0;
+ }
+ }
+ }
+ let changed = match (&app.ui.gfx_edit, &e) {
+ (None, None) => false,
+ (Some(old), Some(new)) => {
+ // A stable uid is the owner key. The compact fingerprint only
+ // decides identity for a uid-less layer, and zero there means
+ // "the requested index" rather than a different owner.
+ old.clip != new.clip
+ || old.layer != new.layer
+ || old.uid != new.uid
+ || (new.uid == 0 && old.fingerprint != 0 && old.fingerprint != new.fingerprint)
+ }
+ _ => true,
+ };
+ if changed {
+ app.restart_ime_target();
+ } else if let (Some(old), Some(new)) = (&app.ui.gfx_edit, &e)
+ && (old.caret, old.anchor) != (new.caret, new.anchor)
+ {
+ // Caret is not part of the stable owner. Only a known composition
+ // becomes stale; commit-only input without one remains eligible.
+ app.invalidate_ime_composition();
+ }
+ app.ui.gfx_edit = e;
+ Ok(())
+ }
+ Err(e) => Err(format!("`gfxEdit`: {e}")),
+ }
+}
+
+/// The `program` / `source` parts of a `ui.set` payload: serde fields of `MonitorView`,
+/// merged into the current state.
+fn set_monitor_views(app: &mut FilmcraftApp, p: &Value) -> Result<(), String> {
+ // Monitor view state (serde fields of `MonitorView`), merged into the current state.
+ for k in ["program", "source"] {
+ let Some(patch) = p.get(k).and_then(Value::as_object) else { continue };
+ let mv = if k == "program" { &mut app.ui.program } else { &mut app.ui.source };
+ let mut cur = serde_json::to_value(&*mv).unwrap_or_default();
+ if let Some(o) = cur.as_object_mut() {
+ for (f, v) in patch {
+ o.insert(f.clone(), v.clone());
+ }
+ }
+ match serde_json::from_value(cur) {
+ Ok(m) => *mv = m,
+ Err(e) => return Err(format!("`{k}`: {e}")),
+ }
+ }
+ Ok(())
+}
+
+/// The `projectPanel` / `mediaBrowser` parts of a `ui.set` payload: each panel's view state,
+/// merged.
+fn set_panel_views(app: &mut FilmcraftApp, p: &Value) -> Result<(), String> {
+ // Project panel / Media Browser view state (`panels::project`, `panels::media_browser`), merged
+ for (k, which) in [("projectPanel", 0), ("mediaBrowser", 1)] {
+ let Some(patch) = p.get(k) else { continue };
+ let mut cur = if which == 0 { serde_json::to_value(&app.ui.project_panel) } else { serde_json::to_value(&app.ui.media_browser) }.unwrap_or_default();
+ merge(&mut cur, patch);
+ let r = if which == 0 {
+ serde_json::from_value(cur).map(|v| app.ui.project_panel = v)
+ } else {
+ serde_json::from_value(cur).map(|v| app.ui.media_browser = v)
+ };
+ if let Err(e) = r {
+ return Err(format!("`{k}`: {e}"));
+ }
+ }
+ Ok(())
+}
+
fn handle_synthetic_input(app: &mut FilmcraftApp, p: &Value, method: &str) -> Outcome {
let s = |key: &str| p.get(key).and_then(Value::as_str);
match method {
diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs
index 40a20d89d..ac4f1e528 100644
--- a/crates/ui-egui/src/i18n/tests.rs
+++ b/crates/ui-egui/src/i18n/tests.rs
@@ -433,126 +433,102 @@ fn tl_literals_are_found_and_unescaped() {
assert_eq!(tl_literals(src), ["Save", "Say \"hi\"\n", "{n} file(s)"]);
}
+type App = crate::FilmcraftApp;
+
+fn switch(app: &mut App, ctx: &egui::Context, cmd: &str) -> serde_json::Value {
+ crate::menus::invoke(app, ctx, cmd, serde_json::json!({})).unwrap()
+}
+
+/// The saved UI state round-trips the language (`code` is its serialized tag).
+fn assert_ui_persists(app: &App, lang: Language, code: &str) {
+ let saved = serde_json::to_string(&app.ui).unwrap();
+ assert!(saved.contains(&format!("\"language\":\"{code}\"")), "{saved}");
+ let restored: crate::state::UiState = serde_json::from_str(&saved).unwrap();
+ assert_eq!(restored.language, lang);
+}
+
+/// A restart with the saved prefs comes up in `lang`.
+fn assert_restart_keeps(app: &App, lang: Language) {
+ let prefs = serde_json::to_string(&app.session.prefs).unwrap();
+ let mut restarted = filmcraft_engine::Session::default();
+ restarted.prefs = serde_json::from_str(&prefs).unwrap();
+ assert_eq!(App::new(restarted).ui.language, lang);
+}
+
+/// Only `checked_id` is checked among the language menu items.
+fn assert_only_checked(app: &App, checked_id: &str) {
+ for it in crate::menus::menu_items(app).iter().filter(|it| it.id.starts_with("app.language.")) {
+ assert_eq!(it.checked, Some(it.id == checked_id), "{}", it.id);
+ }
+}
+
+fn assert_menu_checked(app: &App, id: &str) {
+ assert!(crate::menus::menu_items(app).iter().any(|it| it.id == id && it.checked == Some(true)));
+}
+
+fn assert_labels(app: &App, labels: &[(&str, &str)]) {
+ let items = crate::menus::menu_items(app);
+ for (id, want) in labels {
+ assert_eq!(items.iter().find(|it| it.id == *id).map(|it| it.label.as_str()), Some(*want), "{id}");
+ }
+}
+
+/// Switch through the menu command and check everything a language change touches.
+/// `earlier` is a language name from an earlier step: it must still show in its own language.
+fn switch_and_check(app: &mut App, ctx: &egui::Context, name: &str, lang: Language, code: &str, own_name: &str, earlier: Option<(&str, &str)>) {
+ let result = switch(app, ctx, &format!("app.language.{name}"));
+ assert_eq!(result, serde_json::json!(code));
+ assert_eq!((app.ui.language, current()), (lang, lang));
+ assert_eq!(app.session.prefs.general.interface_language, code);
+ assert_only_checked(app, &format!("app.language.{name}"));
+ assert_labels(app, &[("file.saveAs", lang.tr("Save As…")), (&format!("app.language.{name}"), own_name)]);
+ if let Some((id, label)) = earlier {
+ assert_labels(app, &[(id, label)]);
+ }
+ assert_ui_persists(app, lang, code);
+ assert_restart_keeps(app, lang);
+}
+
#[test]
fn language_commands_switch_and_persist_without_a_document() {
- let mut app = crate::FilmcraftApp::new(filmcraft_engine::Session::default());
+ let mut app = App::new(filmcraft_engine::Session::default());
let ctx = egui::Context::default();
// Japanese needs an installed font (see `japanese_needs_an_installed_font`); skip that step without one
if craft_japanese_font() || system_japanese_font().is_some() {
- crate::menus::invoke(&mut app, &ctx, "app.language.japanese", serde_json::json!({})).unwrap();
+ switch(&mut app, &ctx, "app.language.japanese");
assert_eq!(app.ui.language, Language::Ja);
- let saved = serde_json::to_string(&app.ui).unwrap();
- let restored: crate::state::UiState = serde_json::from_str(&saved).unwrap();
- assert_eq!(restored.language, Language::Ja);
+ assert_ui_persists(&app, Language::Ja, "ja");
}
- crate::menus::invoke(&mut app, &ctx, "app.language.spanish", serde_json::json!({})).unwrap();
+ switch(&mut app, &ctx, "app.language.spanish");
assert_eq!(app.ui.language, Language::Es);
- let prefs = serde_json::to_string(&app.session.prefs).unwrap();
- let mut restarted = filmcraft_engine::Session::default();
- restarted.prefs = serde_json::from_str(&prefs).unwrap();
- assert_eq!(crate::FilmcraftApp::new(restarted).ui.language, Language::Es);
- assert!(crate::menus::menu_items(&app).iter().any(|it| it.id == "app.language.spanish" && it.checked == Some(true)));
- crate::menus::invoke(&mut app, &ctx, "app.language.portuguese", serde_json::json!({})).unwrap();
+ assert_restart_keeps(&app, Language::Es);
+ assert_menu_checked(&app, "app.language.spanish");
+ switch(&mut app, &ctx, "app.language.portuguese");
assert_eq!(app.ui.language, Language::PtBr);
assert_eq!(app.session.prefs.general.interface_language, "pt-br");
- assert!(crate::menus::menu_items(&app).iter().any(|it| it.id == "app.language.portuguese" && it.checked == Some(true)));
- let result = crate::menus::invoke(&mut app, &ctx, "app.language.ukrainian", serde_json::json!({})).unwrap();
- assert_eq!(result, serde_json::json!("uk"));
- assert_eq!(app.ui.language, Language::Uk);
- for item in crate::menus::menu_items(&app).iter().filter(|it| it.id.starts_with("app.language.")) {
- assert_eq!(item.checked, Some(item.id == "app.language.ukrainian"), "{}", item.id);
+ assert_menu_checked(&app, "app.language.portuguese");
+ for (name, lang, code, own, earlier) in [
+ ("ukrainian", Language::Uk, "uk", "Українська", None),
+ ("german", Language::De, "de", "Deutsch", Some(("app.language.spanish", "Español"))),
+ ("french", Language::Fr, "fr", "Français", Some(("app.language.german", "Deutsch"))),
+ ("indonesian", Language::Id, "id", "Bahasa Indonesia", Some(("app.language.french", "Français"))),
+ ("italian", Language::It, "it", "Italiano", Some(("app.language.indonesian", "Bahasa Indonesia"))),
+ ] {
+ switch_and_check(&mut app, &ctx, name, lang, code, own, earlier);
}
- let saved = serde_json::to_string(&app.ui).unwrap();
- assert!(saved.contains("\"language\":\"uk\""), "{saved}");
- let restored: crate::state::UiState = serde_json::from_str(&saved).unwrap();
- assert_eq!(restored.language, Language::Uk);
- assert_eq!(app.session.prefs.general.interface_language, "uk");
- let prefs = serde_json::to_string(&app.session.prefs).unwrap();
- let mut restarted = filmcraft_engine::Session::default();
- restarted.prefs = serde_json::from_str(&prefs).unwrap();
- assert_eq!(crate::FilmcraftApp::new(restarted).ui.language, Language::Uk);
- let result = crate::menus::invoke(&mut app, &ctx, "app.language.german", serde_json::json!({})).unwrap();
- assert_eq!(result, serde_json::json!("de"));
- assert_eq!((app.ui.language, current()), (Language::De, Language::De));
- assert_eq!(app.session.prefs.general.interface_language, "de");
- for it in crate::menus::menu_items(&app).iter().filter(|it| it.id.starts_with("app.language.")) {
- assert_eq!(it.checked, Some(it.id == "app.language.german"), "{}", it.id);
- }
- // the menus are drawn in German, the language names in their own language
- let items = crate::menus::menu_items(&app);
- let label = |id: &str| items.iter().find(|it| it.id == id).map(|it| it.label.as_str());
- assert_eq!(label("file.saveAs"), Some(Language::De.tr("Save As…")));
- assert_eq!(label("app.language.spanish"), Some("Español"));
- let saved = serde_json::to_string(&app.ui).unwrap();
- assert!(saved.contains("\"language\":\"de\""), "{saved}");
- let restored: crate::state::UiState = serde_json::from_str(&saved).unwrap();
- assert_eq!(restored.language, Language::De);
- let prefs = serde_json::to_string(&app.session.prefs).unwrap();
- let mut restarted = filmcraft_engine::Session::default();
- restarted.prefs = serde_json::from_str(&prefs).unwrap();
- assert_eq!(crate::FilmcraftApp::new(restarted).ui.language, Language::De);
- let result = crate::menus::invoke(&mut app, &ctx, "app.language.french", serde_json::json!({})).unwrap();
- assert_eq!(result, serde_json::json!("fr"));
- assert_eq!((app.ui.language, current()), (Language::Fr, Language::Fr));
- assert_eq!(app.session.prefs.general.interface_language, "fr");
- for it in crate::menus::menu_items(&app).iter().filter(|it| it.id.starts_with("app.language.")) {
- assert_eq!(it.checked, Some(it.id == "app.language.french"), "{}", it.id);
- }
- let items = crate::menus::menu_items(&app);
- let label = |id: &str| items.iter().find(|it| it.id == id).map(|it| it.label.as_str());
- assert_eq!(label("file.saveAs"), Some(Language::Fr.tr("Save As…")));
- assert_eq!(label("app.language.german"), Some("Deutsch"));
- let saved = serde_json::to_string(&app.ui).unwrap();
- assert!(saved.contains("\"language\":\"fr\""), "{saved}");
- let prefs = serde_json::to_string(&app.session.prefs).unwrap();
- let mut restarted = filmcraft_engine::Session::default();
- restarted.prefs = serde_json::from_str(&prefs).unwrap();
- assert_eq!(crate::FilmcraftApp::new(restarted).ui.language, Language::Fr);
- let result = crate::menus::invoke(&mut app, &ctx, "app.language.indonesian", serde_json::json!({})).unwrap();
- assert_eq!(result, serde_json::json!("id"));
- assert_eq!((app.ui.language, current()), (Language::Id, Language::Id));
- assert_eq!(app.session.prefs.general.interface_language, "id");
- for it in crate::menus::menu_items(&app).iter().filter(|it| it.id.starts_with("app.language.")) {
- assert_eq!(it.checked, Some(it.id == "app.language.indonesian"), "{}", it.id);
- }
- let items = crate::menus::menu_items(&app);
- let label = |id: &str| items.iter().find(|it| it.id == id).map(|it| it.label.as_str());
- assert_eq!(label("file.saveAs"), Some(Language::Id.tr("Save As…")));
- assert_eq!(label("app.language.french"), Some("Français"));
- assert_eq!(label("app.language.indonesian"), Some("Bahasa Indonesia"));
- let saved = serde_json::to_string(&app.ui).unwrap();
- assert!(saved.contains("\"language\":\"id\""), "{saved}");
- let prefs = serde_json::to_string(&app.session.prefs).unwrap();
- let mut restarted = filmcraft_engine::Session::default();
- restarted.prefs = serde_json::from_str(&prefs).unwrap();
- assert_eq!(crate::FilmcraftApp::new(restarted).ui.language, Language::Id);
- let result = crate::menus::invoke(&mut app, &ctx, "app.language.italian", serde_json::json!({})).unwrap();
- assert_eq!(result, serde_json::json!("it"));
- assert_eq!((app.ui.language, current()), (Language::It, Language::It));
- assert_eq!(app.session.prefs.general.interface_language, "it");
- for it in crate::menus::menu_items(&app).iter().filter(|it| it.id.starts_with("app.language.")) {
- assert_eq!(it.checked, Some(it.id == "app.language.italian"), "{}", it.id);
- }
- let items = crate::menus::menu_items(&app);
- let label = |id: &str| items.iter().find(|it| it.id == id).map(|it| it.label.as_str());
- assert_eq!(label("file.saveAs"), Some(Language::It.tr("Save As…")));
- assert_eq!(label("app.language.indonesian"), Some("Bahasa Indonesia"));
- assert_eq!(label("app.language.italian"), Some("Italiano"));
- let saved = serde_json::to_string(&app.ui).unwrap();
- assert!(saved.contains("\"language\":\"it\""), "{saved}");
- let prefs = serde_json::to_string(&app.session.prefs).unwrap();
- let mut restarted = filmcraft_engine::Session::default();
- restarted.prefs = serde_json::from_str(&prefs).unwrap();
- assert_eq!(crate::FilmcraftApp::new(restarted).ui.language, Language::It);
- crate::menus::invoke(&mut app, &ctx, "app.language.english", serde_json::json!({})).unwrap();
+ switch(&mut app, &ctx, "app.language.english");
assert_eq!(app.ui.language, Language::En);
set_current(Language::En);
}
+fn locales(tags: &[&str]) -> Language {
+ Language::from_locales(&tags.iter().map(|t| t.to_string()).collect::<Vec<_>>())
+}
+
/// #218: System Language picks the first of the user's preferred languages the interface has.
#[test]
fn system_language_follows_the_preferred_locales() {
- let l = |tags: &[&str]| Language::from_locales(&tags.iter().map(|t| t.to_string()).collect::<Vec<_>>());
+ let l = locales;
assert_eq!(l(&["es_ES.UTF-8"]), Language::Es);
assert_eq!(l(&["es-419"]), Language::Es);
assert_eq!(l(&["ES"]), Language::Es);
@@ -569,6 +545,11 @@ fn system_language_follows_the_preferred_locales() {
assert_eq!(l(&[tag]), Language::En, "{tag}: Traditional Chinese has no catalog");
}
assert_eq!(l(&["zh-TW", "ja-JP"]), Language::Ja);
+}
+
+#[test]
+fn system_language_picks_german_french_indonesian() {
+ let l = locales;
for tag in ["de", "DE", "de-DE", "de-AT", "de-CH", "de-LI", "de-LU", "de_DE.UTF-8", "de_AT.UTF-8@euro", "de_CH"] {
assert_eq!(l(&[tag]), Language::De, "{tag}");
}
@@ -582,6 +563,11 @@ fn system_language_follows_the_preferred_locales() {
for none in [&["ind"][..], &["i"], &["-id"], &["ms"], &["ms-ID"], &["jv"]] {
assert_eq!(l(none), Language::En, "{none:?}");
}
+}
+
+#[test]
+fn system_language_picks_italian_korean_and_the_first_known() {
+ let l = locales;
for tag in ["it", "IT", "it-IT", "it-CH", "it-SM", "it_IT.UTF-8", "it_IT.UTF-8@euro", "it_CH"] {
assert_eq!(l(&[tag]), Language::It, "{tag}");
}
diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs
index 0e91c62c9..5525c0525 100644
--- a/crates/ui-egui/src/panels/effect_controls.rs
+++ b/crates/ui-egui/src/panels/effect_controls.rs
@@ -599,37 +599,102 @@ pub(crate) fn param_row(
.layout(egui::Layout::left_to_right(egui::Align::Center)),
);
let id = egui::Id::unique(("pv", clip.0, idx, pkey));
+ let set = param_value_widget(app, &mut vui, e, pd, &value, clip, idx, mask, pkey, id, t, actions);
+ if let Some(v) = set {
+ actions.push(("effects.setParam".into(), with_mask(json!({"clip": clip.0, "effect": idx, "param": pd.id, "value": v}))));
+ }
+ // keyframe navigator ◀ ◆ ▶ (when animated)
+ let eff_json = json!(idx);
+ if pd.animatable && param.is_animated() {
+ let at = pos2(r.max.x - 42.0, r.center().y);
+ let auto = format!("effectControls.{}.{}", e.effect, pkey);
+ if keyframe_nav(app, ui, at, Some(param), mt, it, egui::Id::unique(("knav", clip.0, idx, pkey)), &auto, "Add/Remove Keyframe", actions) {
+ actions.push(("effects.addKeyframe".into(), with_mask(json!({"clip": clip.0, "effect": eff_json, "param": pd.id}))));
+ }
+ }
+ // reset to the default, under the effect's own reset button (an animated parameter keeps its
+ // keyframes and gets one at the playhead)
+ if mask.is_none() {
+ let rr = Rect::from_center_size(pos2(r.max.x - 14.0, r.center().y), vec2(12.0, 12.0));
+ let rresp = ui.interact(rr, egui::Id::unique(("param-reset", clip.0, idx, pkey)), Sense::click()).on_hover_text(tl!("Reset Parameter"));
+ icons::paint(ui.painter(), rr, Icon::Reset, if rresp.hovered() { t.text } else { t.text_dim });
+ app.auto.add(&format!("effectControls.{}.{}.reset", e.effect, pkey), rr, "Reset Parameter");
+ if rresp.clicked() {
+ actions.push(("effects.resetParam".into(), json!({"clip": clip.0, "effect": eff_json, "param": pd.id})));
+ }
+ }
+ // keyframes in the lane: draggable diamonds; right-click for interpolation
+ if param.is_animated() {
+ let y = r.center().y;
+ let dur = it.duration.0.max(1) as f64;
+ for k in &param.keyframes {
+ let tl = timeline_time_of(it, k.time);
+ let f = ((tl - it.start).0 as f64 / dur) as f32;
+ if !(-0.01..=1.01).contains(&f) {
+ continue;
+ }
+ let id = egui::Id::unique(("kf", clip.0, idx, pkey, k.time.0));
+ let original = Rect::from_center_size(pos2(lane.min.x + f * lane.width(), y), vec2(15.0, 15.0));
+ let resp = ui.interact(original.expand(2.0), id, Sense::click_and_drag());
+ let reference = KeyframeRef { clip: clip.0, effect: idx, param: pd.id.to_string(), mask, time: k.time };
+ let kr = keys.key(app, ui, reference.clone(), it, *lane, original, &resp, k.interp);
+ app.auto.add(&format!("effectControls.{}.{}.keyframe.{}", e.effect, pkey, k.time.0), kr, "keyframe");
+ let selected = app.ui.keyframe_selection.contains(&reference);
+ let col = if selected { t.hot_text } else { Color32::from_rgb(0xb0, 0xb0, 0xb0) };
+ selection::paint(ui.painter(), kr, k.interp, col);
+ if resp.clicked_by(egui::PointerButton::Primary) {
+ actions.push(("playhead.set".into(), json!({"time": tl.0})));
+ }
+ resp.context_menu(|ui| {
+ keyframe_menu(app, ui, KeyframeRef { clip: clip.0, effect: idx, param: pd.id.to_string(), mask, time: k.time }, actions);
+ });
+ }
+ }
+}
+
+/// The value editor of one parameter row: number, point, checkbox, choice, colour (with the
+/// eyedropper), path or text field. Returns the edited value, if any.
+#[allow(clippy::too_many_arguments)]
+fn param_value_widget(
+ app: &mut FilmcraftApp,
+ vui: &mut egui::Ui,
+ e: &EffectInstance,
+ pd: &filmcraft_project::ParamDef,
+ value: &ParamValue,
+ clip: ClipId,
+ idx: usize,
+ mask: Option<usize>,
+ pkey: &str,
+ id: egui::Id,
+ t: Tokens,
+ actions: &mut Vec<(String, Value)>,
+) -> Option<Value> {
let mut set: Option<Value> = None;
- match (&pd.kind, &value) {
+ match (&pd.kind, value) {
(ParamKind::Float { min, max, soft_min, soft_max, unit, decimals }, ParamValue::Float(v)) => {
let speed = ((soft_max - soft_min) / 400.0).max(0.01);
- let (_, nv) = crate::widgets::hot_number(
- &mut vui,
- crate::i18n::t(pd.label),
- id,
- *v,
- HotNumberOptions::new(speed, (*min, *max), *decimals as usize, unit, &t),
- );
+ let (_, nv) =
+ crate::widgets::hot_number(vui, crate::i18n::t(pd.label), id, *v, HotNumberOptions::new(speed, (*min, *max), *decimals as usize, unit, &t));
if let Some(nv) = nv {
set = Some(json!(nv));
}
}
(ParamKind::Angle, ParamValue::Float(v)) => {
- let (_, nv) = crate::widgets::hot_number(&mut vui, crate::i18n::t(pd.label), id, *v, HotNumberOptions::new(0.5, (-36000.0, 36000.0), 1, "°", &t));
+ let (_, nv) = crate::widgets::hot_number(vui, crate::i18n::t(pd.label), id, *v, HotNumberOptions::new(0.5, (-36000.0, 36000.0), 1, "°", &t));
if let Some(nv) = nv {
set = Some(json!(nv));
}
}
(ParamKind::Point, ParamValue::Vec2(p)) => {
let (_, nx) = crate::widgets::hot_number(
- &mut vui,
+ vui,
&format!("{} X", crate::i18n::t(pd.label)),
id.with("x"),
p.x,
HotNumberOptions::new(1.0, (-100_000.0, 100_000.0), 1, "", &t),
);
let (_, ny) = crate::widgets::hot_number(
- &mut vui,
+ vui,
&format!("{} Y", crate::i18n::t(pd.label)),
id.with("y"),
p.y,
@@ -641,17 +706,17 @@ pub(crate) fn param_row(
}
(ParamKind::Bool, ParamValue::Bool(b)) => {
let mut v = *b;
- fit_to_row(&mut vui);
+ fit_to_row(vui);
if crate::widgets::accessible_name(vui.checkbox(&mut v, ""), crate::i18n::t(pd.label)).changed() {
set = Some(json!(v));
}
}
(ParamKind::Choice(opts), ParamValue::Choice(c)) => {
let mut sel = *c as usize;
- fit_to_row(&mut vui);
+ fit_to_row(vui);
// (narrower when the effect list is narrow, so it stays left of the divider)
let w = vui.available_width().min(130.0);
- let combo = craft_ui::ComboBox::from_id_salt(id).selected_text(opts.get(sel).map_or("", |o| crate::i18n::t(o))).width(w).show_ui(&mut vui, |ui| {
+ let combo = craft_ui::ComboBox::from_id_salt(id).selected_text(opts.get(sel).map_or("", |o| crate::i18n::t(o))).width(w).show_ui(vui, |ui| {
for (i, o) in opts.iter().enumerate() {
if ui.selectable_value(&mut sel, i, crate::i18n::t(o)).changed() {
set = Some(json!(i));
@@ -662,20 +727,20 @@ pub(crate) fn param_row(
}
(ParamKind::Color, ParamValue::Color(c)) => {
let mut rgba = egui::Rgba::from_rgba_unmultiplied(c[0], c[1], c[2], c[3]);
- if egui::color_picker::color_edit_button_rgba(&mut vui, &mut rgba, egui::color_picker::Alpha::Opaque).changed() {
+ if egui::color_picker::color_edit_button_rgba(vui, &mut rgba, egui::color_picker::Alpha::Opaque).changed() {
set = Some(json!([rgba.r(), rgba.g(), rgba.b(), rgba.a()]));
}
// Eyedropper: arm it, then click a pixel in the Program monitor (Esc cancels)
let target = crate::state::Eyedropper { clip: clip.0, effect: idx, param: pd.id.to_string(), mask };
let armed = app.ui.eyedropper.as_ref() == Some(&target);
- let drop = icons::button(&mut vui, Icon::Eyedropper, 18.0, armed, &t, tl!("Eyedropper (pick a color from the Program monitor)"));
+ let drop = icons::button(vui, Icon::Eyedropper, 18.0, armed, &t, tl!("Eyedropper (pick a color from the Program monitor)"));
app.auto.add(&format!("effectControls.{}.{}.eyedropper", e.effect, pkey), drop.rect, "Eyedropper");
if drop.clicked() {
app.ui.eyedropper = if armed { None } else { Some(target) };
}
}
(ParamKind::Path, _) => {
- crate::panels::masks::path_value(app, &mut vui, clip, idx, mask, actions);
+ crate::panels::masks::path_value(app, vui, clip, idx, mask, actions);
}
(ParamKind::Text, ParamValue::Text(s)) if !pd.id.ends_with("_lut") => {
// edited in a buffer; committed (one undo step) when the field loses focus
@@ -694,59 +759,10 @@ pub(crate) fn param_row(
}
}
_ => {
- vui.label(param_text(&app.session.project, pd.id, &value));
- }
- }
- if let Some(v) = set {
- actions.push(("effects.setParam".into(), with_mask(json!({"clip": clip.0, "effect": idx, "param": pd.id, "value": v}))));
- }
- // keyframe navigator ◀ ◆ ▶ (when animated)
- let eff_json = json!(idx);
- if pd.animatable && param.is_animated() {
- let at = pos2(r.max.x - 42.0, r.center().y);
- let auto = format!("effectControls.{}.{}", e.effect, pkey);
- if keyframe_nav(app, ui, at, Some(param), mt, it, egui::Id::unique(("knav", clip.0, idx, pkey)), &auto, "Add/Remove Keyframe", actions) {
- actions.push(("effects.addKeyframe".into(), with_mask(json!({"clip": clip.0, "effect": eff_json, "param": pd.id}))));
- }
- }
- // reset to the default, under the effect's own reset button (an animated parameter keeps its
- // keyframes and gets one at the playhead)
- if mask.is_none() {
- let rr = Rect::from_center_size(pos2(r.max.x - 14.0, r.center().y), vec2(12.0, 12.0));
- let rresp = ui.interact(rr, egui::Id::unique(("param-reset", clip.0, idx, pkey)), Sense::click()).on_hover_text(tl!("Reset Parameter"));
- icons::paint(ui.painter(), rr, Icon::Reset, if rresp.hovered() { t.text } else { t.text_dim });
- app.auto.add(&format!("effectControls.{}.{}.reset", e.effect, pkey), rr, "Reset Parameter");
- if rresp.clicked() {
- actions.push(("effects.resetParam".into(), json!({"clip": clip.0, "effect": eff_json, "param": pd.id})));
- }
- }
- // keyframes in the lane: draggable diamonds; right-click for interpolation
- if param.is_animated() {
- let y = r.center().y;
- let dur = it.duration.0.max(1) as f64;
- for k in &param.keyframes {
- let tl = timeline_time_of(it, k.time);
- let f = ((tl - it.start).0 as f64 / dur) as f32;
- if !(-0.01..=1.01).contains(&f) {
- continue;
- }
- let id = egui::Id::unique(("kf", clip.0, idx, pkey, k.time.0));
- let original = Rect::from_center_size(pos2(lane.min.x + f * lane.width(), y), vec2(15.0, 15.0));
- let resp = ui.interact(original.expand(2.0), id, Sense::click_and_drag());
- let reference = KeyframeRef { clip: clip.0, effect: idx, param: pd.id.to_string(), mask, time: k.time };
- let kr = keys.key(app, ui, reference.clone(), it, *lane, original, &resp, k.interp);
- app.auto.add(&format!("effectControls.{}.{}.keyframe.{}", e.effect, pkey, k.time.0), kr, "keyframe");
- let selected = app.ui.keyframe_selection.contains(&reference);
- let col = if selected { t.hot_text } else { Color32::from_rgb(0xb0, 0xb0, 0xb0) };
- selection::paint(ui.painter(), kr, k.interp, col);
- if resp.clicked_by(egui::PointerButton::Primary) {
- actions.push(("playhead.set".into(), json!({"time": tl.0})));
- }
- resp.context_menu(|ui| {
- keyframe_menu(app, ui, KeyframeRef { clip: clip.0, effect: idx, param: pd.id.to_string(), mask, time: k.time }, actions);
- });
+ vui.label(param_text(&app.session.project, pd.id, value));
}
}
+ set
}
/// Shared by the lane diamonds and graph points: commands use media time and preserve the mask.
@@ -1151,12 +1167,6 @@ pub(crate) fn graph_rows(
it: &TrackItem,
actions: &mut Vec<(String, Value)>,
) {
- let with_mask = |mut v: Value| -> Value {
- if let Some(k) = mask {
- v["mask"] = json!(k);
- }
- v
- };
let t = app.tokens;
let (vr, _) = ui.allocate_exact_size(vec2(body.width(), 110.0), Sense::hover());
let (velr, _) = ui.allocate_exact_size(vec2(body.width(), 64.0), Sense::hover());
@@ -1164,7 +1174,6 @@ pub(crate) fn graph_rows(
let speed = it.speed.abs().max(1e-6);
let dur = it.duration.0.max(1) as f64;
let to_media = |f: f64| it.source_in + Tick((f * dur * speed) as i64);
- let to_f = |m: Tick| ((m - it.source_in).0 as f64 / speed / dur) as f32;
let x_of = |f: f32| lane.min.x + f * lane.width();
// samples: one row of curve values per sample (a point's NaN "auto" coordinate is skipped)
let n = (lane.width() / 2.0).max(8.0) as usize;
@@ -1197,7 +1206,6 @@ pub(crate) fn graph_rows(
ui.data_mut(|d| d.insert_temp(range_id, (lo, hi, frame)));
let area = Rect::from_min_max(pos2(lane.min.x, vr.min.y + 4.0), pos2(lane.max.x, vr.max.y - 4.0));
let y_of = |v: f64| area.max.y - ((v - lo) / (hi - lo)) as f32 * area.height();
- let v_of = |y: f32| lo + ((area.max.y - y) / area.height()) as f64 * (hi - lo);
let p = ui.painter();
p.rect_filled(area, 0.0, t.keyframe_plot_bg);
for g in 1..4 {
@@ -1243,6 +1251,42 @@ pub(crate) fn graph_rows(
p.text(pos2(velr.max.x - 30.0, varea.min.y + 6.0), Align2::RIGHT_CENTER, format!("{vmax:.1}/s"), Tokens::ui(10.0), t.text_dim);
let p = p.clone();
// keyframes + handles
+ draw_graph_keyframes(app, ui, &p, clip, idx, mask, pd, param, it, lane, lo, hi, area, actions);
+}
+
+/// One parameter's keyframe diamonds on its graph, with the Bezier influence handles.
+#[allow(clippy::too_many_arguments)]
+fn draw_graph_keyframes(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ p: &egui::Painter,
+ clip: ClipId,
+ idx: usize,
+ mask: Option<usize>,
+ pd: &filmcraft_project::ParamDef,
+ param: &filmcraft_project::Param,
+ it: &TrackItem,
+ lane: &Rect,
+ lo: f64,
+ hi: f64,
+ area: Rect,
+ actions: &mut Vec<(String, Value)>,
+) {
+ let t = app.tokens;
+ let speed = it.speed.abs().max(1e-6);
+ let dur = it.duration.0.max(1) as f64;
+ let to_f = |m: Tick| ((m - it.source_in).0 as f64 / speed / dur) as f32;
+ let x_of = |f: f32| lane.min.x + f * lane.width();
+ let y_of = |v: f64| area.max.y - ((v - lo) / (hi - lo)) as f32 * area.height();
+ let v_of = |y: f32| lo + ((area.max.y - y) / area.height()) as f64 * (hi - lo);
+ let dec = if let ParamKind::Float { decimals, .. } = pd.kind { decimals as usize } else { 1 };
+ let with_mask = |mut v: Value| -> Value {
+ if let Some(k) = mask {
+ v["mask"] = json!(k);
+ }
+ v
+ };
+ // keyframes + handles
let ks = &param.keyframes;
for (i, k) in ks.iter().enumerate() {
let f = to_f(k.time);
diff --git a/crates/ui-egui/src/panels/graphics/overlay.rs b/crates/ui-egui/src/panels/graphics/overlay.rs
index a02db9a0e..f2129fce5 100644
--- a/crates/ui-egui/src/panels/graphics/overlay.rs
+++ b/crates/ui-egui/src/panels/graphics/overlay.rs
@@ -106,6 +106,53 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
let editing = app.ui.gfx_edit.clone();
// ---- boxes and handles
let graphics_tool = matches!(tool, Tool::Selection | Tool::Type | Tool::VerticalType | Tool::Rectangle | Tool::Ellipse | Tool::Pen);
+ draw_boxes(app, &painter, &views, sel_clip, &sel_layers, &editing, graphics_tool);
+ let id = egui::Id::unique("gfx-overlay");
+ let resp = ui.interact(pic, id, if graphics_tool { Sense::click_and_drag() } else { Sense::hover() });
+ let hover = resp.hover_pos();
+ let mut actions: Vec<(String, Value)> = Vec::new();
+ let drag_id = id.with("drag");
+ let mut drag: Option<DragState> = ui.data(|d| d.get_temp(drag_id));
+
+ // cursors
+ set_hover_cursor(ui, hover, tool, &views, sel_clip, &sel_layers, &editing);
+
+ // ---- text editing
+ if let Some(ed) = editing.clone() {
+ match views.iter().find(|v| v.clip.0 == ed.clip && v.layer == ed.layer && v.is_text()) {
+ Some(v) => text_edit(app, ui, v, ed, &resp),
+ None => end_edit(app, ui),
+ }
+ }
+ let editing = app.ui.gfx_edit.clone();
+ let edit_view = editing.as_ref().and_then(|e| views.iter().find(|v| v.clip.0 == e.clip && v.layer == e.layer));
+
+ // ---- presses (the left button only: a middle or right drag leaves the layers alone)
+ press(app, ui, &resp, graphics_tool, pic, tool, &views, sel_clip, &sel_layers, &editing, edit_view, drag_id, &mut drag, &mut actions);
+ // ---- drag feedback / commit
+ drag_step(app, ui, &painter, &resp, hover, pic, frame, tool, &views, drag, drag_id, &mut actions);
+ // ---- clicks
+ click(app, ui, &resp, graphics_tool, drag, pic, frame, tool, &views, &editing, edit_view, &mut actions);
+ // ---- pen path in progress
+ pen_path(app, ui, &painter, pic, frame, tool, hover, accent, &mut actions);
+ // ---- run accepted actions before drawing the caret
+ run_actions(app, actions);
+ draw_caret(app, ui, &painter, pic, frame);
+}
+/// The selection boxes, resize/scale handles, corner-radius handles and anchor points of the
+/// selected (or being-edited) graphic layers.
+#[allow(clippy::too_many_arguments)]
+fn draw_boxes(
+ app: &mut FilmcraftApp,
+ painter: &egui::Painter,
+ views: &[LayerView],
+ sel_clip: Option<ClipId>,
+ sel_layers: &[usize],
+ editing: &Option<GfxEdit>,
+ graphics_tool: bool,
+) {
+ let t = app.tokens;
+ let accent = t.accent;
if graphics_tool {
for v in views.iter().filter(|v| Some(v.clip) == sel_clip) {
let q = v.quad();
@@ -153,13 +200,19 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
}
}
}
- let id = egui::Id::unique("gfx-overlay");
- let resp = ui.interact(pic, id, if graphics_tool { Sense::click_and_drag() } else { Sense::hover() });
- let hover = resp.hover_pos();
- let mut actions: Vec<(String, Value)> = Vec::new();
- let drag_id = id.with("drag");
- let mut drag: Option<DragState> = ui.data(|d| d.get_temp(drag_id));
+}
+/// The cursor over the picture: text, crosshair, a resize/scale handle, or the move icon.
+#[allow(clippy::too_many_arguments)]
+fn set_hover_cursor(
+ ui: &egui::Ui,
+ hover: Option<Pos2>,
+ tool: Tool,
+ views: &[LayerView],
+ sel_clip: Option<ClipId>,
+ sel_layers: &[usize],
+ editing: &Option<GfxEdit>,
+) {
// cursors
if let Some(p) = hover {
match tool {
@@ -185,24 +238,35 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
_ => {}
}
}
+}
- // ---- text editing
- if let Some(ed) = editing.clone() {
- match views.iter().find(|v| v.clip.0 == ed.clip && v.layer == ed.layer && v.is_text()) {
- Some(v) => text_edit(app, ui, v, ed, &resp),
- None => end_edit(app, ui),
- }
- }
- let editing = app.ui.gfx_edit.clone();
- let edit_view = editing.as_ref().and_then(|e| views.iter().find(|v| v.clip.0 == e.clip && v.layer == e.layer));
-
+/// Where the left button went down: start dragging a handle, an anchor or a layer, or put the
+/// caret into the text under the pointer. Presses only (a middle or right drag leaves the
+/// layers alone).
+#[allow(clippy::too_many_arguments)]
+fn press(
+ app: &mut FilmcraftApp,
+ ui: &egui::Ui,
+ resp: &egui::Response,
+ graphics_tool: bool,
+ pic: Rect,
+ tool: Tool,
+ views: &[LayerView],
+ sel_clip: Option<ClipId>,
+ sel_layers: &[usize],
+ editing: &Option<GfxEdit>,
+ edit_view: Option<&LayerView>,
+ drag_id: egui::Id,
+ drag: &mut Option<DragState>,
+ actions: &mut Vec<(String, Value)>,
+) {
// ---- presses (the left button only: a middle or right drag leaves the layers alone)
if graphics_tool && resp.drag_started_by(egui::PointerButton::Primary) {
// where the button went down (a drag starts only after the pointer has moved a little)
let p = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()).unwrap_or(pic.center());
let shift = ui.input(|i| i.modifiers.shift);
let in_edit = edit_view.is_some_and(|v| v.hit(p));
- drag = None;
+ *drag = None;
if in_edit {
if let (Some(v), Some(mut ed)) = (edit_view, editing.clone())
&& let Some(tp) = text_of(&v.spec)
@@ -219,7 +283,7 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
}
app.ui.gfx_edit = Some(ed);
}
- drag = Some(DragState { kind: DragKind::TextSelect, clip: v.clip, layer: v.layer, start: p });
+ *drag = Some(DragState { kind: DragKind::TextSelect, clip: v.clip, layer: v.layer, start: p });
}
} else {
match tool {
@@ -231,13 +295,13 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
let corner = selected()
.find_map(|v| corner_handles(v).and_then(|(_, pts)| pts.iter().position(|c| (*c - p).length() <= 6.0)).map(|n| (v.clip, v.layer, n)));
if let Some(v) = anchor {
- drag = Some(DragState { kind: DragKind::Anchor, clip: v.clip, layer: v.layer, start: p });
+ *drag = Some(DragState { kind: DragKind::Anchor, clip: v.clip, layer: v.layer, start: p });
} else if let Some((c, l, n)) = handle {
- drag = Some(DragState { kind: DragKind::Handle(n), clip: c, layer: l, start: p });
+ *drag = Some(DragState { kind: DragKind::Handle(n), clip: c, layer: l, start: p });
} else if let Some((c, l, n)) = corner {
- drag = Some(DragState { kind: DragKind::Corner(n), clip: c, layer: l, start: p });
+ *drag = Some(DragState { kind: DragKind::Corner(n), clip: c, layer: l, start: p });
} else if tool == Tool::Type && !views.iter().any(|v| v.is_text() && v.hit(p)) {
- drag = Some(DragState { kind: DragKind::NewTextBox, clip: ClipId(0), layer: 0, start: p });
+ *drag = Some(DragState { kind: DragKind::NewTextBox, clip: ClipId(0), layer: 0, start: p });
} else if tool == Tool::Selection
&& let Some(v) = views.iter().find(|v| v.hit(p))
{
@@ -247,23 +311,43 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
if !(Some(v.clip) == sel_clip && sel_layers.contains(&v.layer)) {
actions.push(("graphics.selectLayer".into(), json!({"clip": v.clip.0, "layers": [v.layer]})));
}
- drag = Some(DragState { kind: DragKind::Move, clip: v.clip, layer: v.layer, start: p });
+ *drag = Some(DragState { kind: DragKind::Move, clip: v.clip, layer: v.layer, start: p });
}
}
Tool::Rectangle | Tool::Ellipse => {
- drag = Some(DragState { kind: DragKind::NewShape, clip: ClipId(0), layer: 0, start: p });
+ *drag = Some(DragState { kind: DragKind::NewShape, clip: ClipId(0), layer: 0, start: p });
}
_ => {}
}
}
ui.data_mut(|dd| {
- if let Some(d) = drag {
+ if let Some(d) = *drag {
dd.insert_temp(drag_id, d);
} else {
dd.remove::<DragState>(drag_id);
}
});
}
+}
+
+/// Draw the in-flight drag (a ghost box, the moved outline, snap lines) and, when the button
+/// comes up, commit it as actions.
+#[allow(clippy::too_many_arguments)]
+fn drag_step(
+ app: &mut FilmcraftApp,
+ ui: &egui::Ui,
+ painter: &egui::Painter,
+ resp: &egui::Response,
+ hover: Option<Pos2>,
+ pic: Rect,
+ frame: (u32, u32),
+ tool: Tool,
+ views: &[LayerView],
+ drag: Option<DragState>,
+ drag_id: egui::Id,
+ actions: &mut Vec<(String, Value)>,
+) {
+ let t = app.tokens;
// ---- drag feedback / commit
if let Some(d) = drag {
let cur = resp.interact_pointer_pos().or(hover).unwrap_or(d.start);
@@ -280,7 +364,7 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
if let Some(v) = v {
let off = snap_off.0;
painter.add(egui::Shape::closed_line(v.quad().iter().map(|q| *q + off).collect(), Stroke::new(1.0, Color32::WHITE)));
- crate::panels::monitor_view::draw_snap_lines(&painter, pic, &snap_off.1);
+ crate::panels::monitor_view::draw_snap_lines(painter, pic, &snap_off.1);
}
}
DragKind::Handle(n) => {
@@ -399,6 +483,24 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
}
}
}
+}
+
+/// A click of the graphics tools on the picture: edit text, select a layer, add a pen point.
+#[allow(clippy::too_many_arguments)]
+fn click(
+ app: &mut FilmcraftApp,
+ ui: &egui::Ui,
+ resp: &egui::Response,
+ graphics_tool: bool,
+ drag: Option<DragState>,
+ pic: Rect,
+ frame: (u32, u32),
+ tool: Tool,
+ views: &[LayerView],
+ editing: &Option<GfxEdit>,
+ edit_view: Option<&LayerView>,
+ actions: &mut Vec<(String, Value)>,
+) {
// ---- clicks
if graphics_tool && resp.clicked() && drag.is_none_or(|d| !matches!(d.kind, DragKind::TextSelect)) {
let p = resp.interact_pointer_pos().unwrap_or(pic.center());
@@ -424,7 +526,7 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
}
Tool::Type | Tool::VerticalType => {
if let Some(v) = views.iter().find(|v| v.is_text() && v.hit(p)) {
- start_edit_at(app, ui, v, p, &mut actions);
+ start_edit_at(app, ui, v, p, actions);
} else {
end_edit(app, ui);
let (command, prm) = new_text_action(app, pic, frame, p, None);
@@ -436,7 +538,7 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
Tool::Selection => {
if resp.double_clicked() {
if let Some(v) = views.iter().find(|v| v.is_text() && v.hit(p)) {
- start_edit_at(app, ui, v, p, &mut actions);
+ start_edit_at(app, ui, v, p, actions);
// double-click selects all the text so typing replaces it, as in Premiere
if let (Some(tp), Some(e)) = (text_of(&v.spec), app.ui.gfx_edit.as_mut()) {
(e.anchor, e.caret) = (0, tp.text.len());
@@ -460,7 +562,7 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
(pos2(fs.x as f32, fs.y as f32) - p).length() <= 8.0
});
if close {
- finish_pen(app, pic, frame, &mut actions);
+ finish_pen(app, pic, frame, actions);
} else {
app.ui.pen_points.push([c.x, c.y]);
}
@@ -468,6 +570,21 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
_ => {}
}
}
+}
+
+/// Draw the pen path being traced, and finish it on Enter (Escape drops it).
+#[allow(clippy::too_many_arguments)]
+fn pen_path(
+ app: &mut FilmcraftApp,
+ ui: &egui::Ui,
+ painter: &egui::Painter,
+ pic: Rect,
+ frame: (u32, u32),
+ tool: Tool,
+ hover: Option<Pos2>,
+ accent: Color32,
+ actions: &mut Vec<(String, Value)>,
+) {
// ---- pen path in progress
if tool == Tool::Pen && !app.ui.pen_points.is_empty() {
let (_, m) = canvas_target(app, pic, frame);
@@ -481,13 +598,18 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
}
let (enter, esc) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)));
if enter && app.ui.pen_points.len() >= 3 {
- finish_pen(app, pic, frame, &mut actions);
+ finish_pen(app, pic, frame, actions);
} else if esc {
app.ui.pen_points.clear();
}
} else if tool != Tool::Pen && !app.ui.pen_points.is_empty() {
app.ui.pen_points.clear();
}
+}
+
+/// Run the overlay's accepted `graphics.*` commands in order; `#edit` opens the text edit on
+/// the layer the command created or selected.
+fn run_actions(app: &mut FilmcraftApp, actions: Vec<(String, Value)>) {
// ---- run accepted actions before drawing the caret
for (cmd, p) in actions {
let (cmd, then_edit) = match cmd.strip_suffix("#edit") {
@@ -506,6 +628,11 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
Err(e) => app.ui.status = e.to_string(),
}
}
+}
+
+/// Draw the post-action caret, selection highlight and IME preedit of the text being edited
+/// (the model may already have changed), and note the editor's IME target.
+fn draw_caret(app: &mut FilmcraftApp, ui: &egui::Ui, painter: &egui::Painter, pic: Rect, frame: (u32, u32)) {
// The model may have changed above; draw the post-action caret and committed text.
let views = visible_layers(app, pic, frame);
if let Some(ed) = app.ui.gfx_edit.clone()
@@ -526,7 +653,7 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
let sequence = app.session.state.active_sequence.map_or(0, |sequence| sequence.0);
let target = graphics_ime_target(sequence, v.clip.0, v.layer, v.spec.uid, app.ime_replacement_epoch);
let live = composing_live(app, ui.ctx(), target);
- match app.ime_composer.preedit().filter(|_| live).map(|preedit| draw_preedit(&painter, a, b, preedit)) {
+ match app.ime_composer.preedit().filter(|_| live).map(|preedit| draw_preedit(painter, a, b, preedit)) {
Some(drawn) => {
app.auto.add("program.textEdit.preedit", drawn.plate, &drawn.text);
if let Some((rect, clause)) = drawn.clause {
diff --git a/crates/ui-egui/src/panels/graphics/properties.rs b/crates/ui-egui/src/panels/graphics/properties.rs
index 6336b2569..52f11db1b 100644
--- a/crates/ui-egui/src/panels/graphics/properties.rs
+++ b/crates/ui-egui/src/panels/graphics/properties.rs
@@ -103,7 +103,8 @@ impl Ctx<'_> {
}
/// Draw a labeled hot number for this clip/layer/`id`, register it for automation and emit the changed value through `Ctx::set`; `range` bounds typed and
/// dragged input.
- fn number(&mut self, ui: &mut egui::Ui, label: &str, id: &str, speed: f64, range: (f64, f64), dec: usize, unit: &str) {
+ fn number(&mut self, ui: &mut egui::Ui, label: &str, field: NumberField<'_>) {
+ let NumberField { id, speed, range, decimals: dec, unit } = field;
let v = pv(self.e, id, self.mt).as_f64().unwrap_or(0.0);
let (r, mut vui) = self.row(ui, label);
let (resp, nv) = crate::widgets::hot_number(
@@ -322,6 +323,117 @@ fn letter_button(ui: &mut egui::Ui, text: &str, tip: &str, on: bool, t: &Tokens,
}
/// The graphic editor (Properties panel / Essential Graphics ▸ Edit).
+/// The Layers section of the Essential Graphics panel: new-layer buttons, arrange and delete,
+/// and the front-first list of the clip's layers.
+#[allow(clippy::too_many_arguments)]
+fn layers_section(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ clip: ClipId,
+ it: &TrackItem,
+ sel: Option<usize>,
+ autos: &mut Vec<(String, Rect, String)>,
+ actions: &mut Vec<(String, Value)>,
+) {
+ let t = app.tokens;
+ let idx = layer_indices(&it.effects);
+ // ---- layers (front first)
+ if section(ui, app, "Layers", &t) {
+ ui.horizontal(|ui| {
+ ui.add_space(14.0);
+ for (label, key, tip, cmd, p) in [
+ ("T", "NewTextLayer", tl!("New Text Layer"), "graphics.newText", json!({"clip": clip.0, "text": tl!("New Text")})),
+ ("", "NewRectangle", tl!("New Rectangle"), "graphics.newShape", json!({"clip": clip.0, "shape": "rectangle"})),
+ ("", "NewEllipse", tl!("New Ellipse"), "graphics.newShape", json!({"clip": clip.0, "shape": "ellipse", "size": [200, 200]})),
+ ] {
+ let r = letter_button(ui, label, tip, false, &t, Tokens::semibold(13.0));
+ if label.is_empty() {
+ let ir = Rect::from_center_size(r.rect.center(), vec2(14.0, 14.0));
+ icons::paint(ui.painter(), ir, if key == "NewRectangle" { Icon::Rectangle } else { Icon::Ellipse }, t.text_dim);
+ }
+ autos.push((format!("graphics.{key}"), r.rect, tip.into()));
+ if r.clicked() {
+ actions.push((cmd.into(), p));
+ }
+ }
+ ui.add_space(8.0);
+ if let Some(l) = sel {
+ for (label, tip, to) in [("↑", tl!("Bring Forward"), "forward"), ("↓", tl!("Send Backward"), "backward")] {
+ let r = letter_button(ui, label, tip, false, &t, Tokens::ui(13.0));
+ autos.push((format!("graphics.arrange.{to}"), r.rect, tip.into()));
+ if r.clicked() {
+ actions.push(("graphics.arrangeLayer".into(), json!({"clip": clip.0, "layer": l, "to": to})));
+ }
+ }
+ let (dr, dresp) = ui.allocate_exact_size(vec2(24.0, 22.0), Sense::click());
+ icons::paint(ui.painter(), dr.shrink(4.0), Icon::Trash, if dresp.hovered() { t.text } else { t.text_dim });
+ autos.push(("graphics.deleteLayer".into(), dr, "Delete Layer".into()));
+ if dresp.on_hover_text(tl!("Delete Layer")).clicked() {
+ actions.push(("graphics.deleteLayer".into(), json!({"clip": clip.0, "layer": l})));
+ }
+ }
+ });
+ for (li, &ei) in idx.iter().enumerate().rev() {
+ let e = &it.effects[ei];
+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click());
+ let on = sel == Some(li);
+ if on {
+ ui.painter().rect_filled(r, 2.0, Color32::from_rgb(0x2e, 0x3d, 0x55));
+ } else if resp.hovered() {
+ ui.painter().rect_filled(r, 2.0, t.hover);
+ }
+ let kind = if e.effect == graphic::TEXT_LAYER { "T" } else { "◆" };
+ ui.painter().text(pos2(r.min.x + 22.0, r.center().y), Align2::CENTER_CENTER, kind, Tokens::semibold(12.0), t.text_dim);
+ ui.painter().text(pos2(r.min.x + 38.0, r.center().y), Align2::LEFT_CENTER, layer_display_name(e, li), Tokens::ui(12.0), t.text);
+ // visibility
+ let er = Rect::from_center_size(pos2(r.max.x - 14.0, r.center().y), vec2(16.0, 16.0));
+ let eresp = ui.interact(er, egui::Id::unique(("gfx-eye", clip.0, li)), Sense::click());
+ icons::paint(ui.painter(), er.shrink(2.0), if e.enabled { Icon::Eye } else { Icon::EyeOff }, t.text_dim);
+ autos.push((format!("graphics.layers.{li}.visible"), er, "Toggle visibility".into()));
+ autos.push((format!("graphics.layers.{li}"), r, layer_display_name(e, li)));
+ if eresp.clicked() {
+ actions.push(("graphics.set".into(), json!({"clip": clip.0, "layer": li, "props": {"enabled": !e.enabled}})));
+ } else if resp.clicked() {
+ actions.push(("graphics.selectLayer".into(), json!({"clip": clip.0, "layers": [li]})));
+ }
+ }
+ }
+}
+
+/// The Text section header and its wrench: opens the Text Properties dialog and reports
+/// whether the section itself is open.
+#[allow(clippy::too_many_arguments)]
+fn text_section_header(
+ ui: &mut egui::Ui,
+ app: &mut FilmcraftApp,
+ clip: ClipId,
+ l: usize,
+ e: &EffectInstance,
+ mt: Tick,
+ autos: &mut Vec<(String, Rect, String)>,
+) -> bool {
+ let t = app.tokens;
+ let (open, head) = section_header(ui, app, "Text", &t);
+ // Text Properties: the layer type (point / paragraph) and text styling
+ let wr = Rect::from_center_size(pos2(head.max.x - 16.0, head.center().y), vec2(22.0, 22.0));
+ let wresp = ui.interact(wr, egui::Id::unique(("gfx-text-props", clip.0, l)), Sense::click());
+ icons::paint(ui.painter(), wr.shrink(4.0), Icon::Wrench, if wresp.hovered() { t.text } else { t.text_dim });
+ autos.push(("graphics.textProperties".into(), wr, "Text Properties".into()));
+ if wresp.on_hover_text(tl!("Text Properties")).clicked() {
+ let flag = |id: &str| pv(e, id, mt).as_bool().unwrap_or(false);
+ let ligatures = flag("ligatures");
+ app.ui.text_props_dialog = Some(TextPropsDialog {
+ clip: clip.0,
+ layer: l,
+ paragraph: pv(e, "box_width", mt).as_f64().unwrap_or(0.0) > 0.0 && !flag("vertical"),
+ vertical: flag("vertical"),
+ ligatures,
+ ligatures_was: ligatures,
+ });
+ }
+ open
+}
+
pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let Some((clip, it)) = selected_graphic(app) else {
@@ -351,66 +463,7 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
ui.painter().rect_filled(Rect::from_center_size(pos2(hr.min.x + 8.0, hr.center().y), vec2(12.0, 12.0)), 2.0, Color32::from_rgb(lc[0], lc[1], lc[2]));
ui.painter().text(pos2(hr.min.x + 22.0, hr.center().y), Align2::LEFT_CENTER, &it.name, Tokens::semibold(12.5), t.text);
// ---- layers (front first)
- if section(ui, app, "Layers", &t) {
- ui.horizontal(|ui| {
- ui.add_space(14.0);
- for (label, key, tip, cmd, p) in [
- ("T", "NewTextLayer", tl!("New Text Layer"), "graphics.newText", json!({"clip": clip.0, "text": tl!("New Text")})),
- ("", "NewRectangle", tl!("New Rectangle"), "graphics.newShape", json!({"clip": clip.0, "shape": "rectangle"})),
- ("", "NewEllipse", tl!("New Ellipse"), "graphics.newShape", json!({"clip": clip.0, "shape": "ellipse", "size": [200, 200]})),
- ] {
- let r = letter_button(ui, label, tip, false, &t, Tokens::semibold(13.0));
- if label.is_empty() {
- let ir = Rect::from_center_size(r.rect.center(), vec2(14.0, 14.0));
- icons::paint(ui.painter(), ir, if key == "NewRectangle" { Icon::Rectangle } else { Icon::Ellipse }, t.text_dim);
- }
- autos.push((format!("graphics.{key}"), r.rect, tip.into()));
- if r.clicked() {
- actions.push((cmd.into(), p));
- }
- }
- ui.add_space(8.0);
- if let Some(l) = sel {
- for (label, tip, to) in [("↑", tl!("Bring Forward"), "forward"), ("↓", tl!("Send Backward"), "backward")] {
- let r = letter_button(ui, label, tip, false, &t, Tokens::ui(13.0));
- autos.push((format!("graphics.arrange.{to}"), r.rect, tip.into()));
- if r.clicked() {
- actions.push(("graphics.arrangeLayer".into(), json!({"clip": clip.0, "layer": l, "to": to})));
- }
- }
- let (dr, dresp) = ui.allocate_exact_size(vec2(24.0, 22.0), Sense::click());
- icons::paint(ui.painter(), dr.shrink(4.0), Icon::Trash, if dresp.hovered() { t.text } else { t.text_dim });
- autos.push(("graphics.deleteLayer".into(), dr, "Delete Layer".into()));
- if dresp.on_hover_text(tl!("Delete Layer")).clicked() {
- actions.push(("graphics.deleteLayer".into(), json!({"clip": clip.0, "layer": l})));
- }
- }
- });
- for (li, &ei) in idx.iter().enumerate().rev() {
- let e = &it.effects[ei];
- let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click());
- let on = sel == Some(li);
- if on {
- ui.painter().rect_filled(r, 2.0, Color32::from_rgb(0x2e, 0x3d, 0x55));
- } else if resp.hovered() {
- ui.painter().rect_filled(r, 2.0, t.hover);
- }
- let kind = if e.effect == graphic::TEXT_LAYER { "T" } else { "◆" };
- ui.painter().text(pos2(r.min.x + 22.0, r.center().y), Align2::CENTER_CENTER, kind, Tokens::semibold(12.0), t.text_dim);
- ui.painter().text(pos2(r.min.x + 38.0, r.center().y), Align2::LEFT_CENTER, layer_display_name(e, li), Tokens::ui(12.0), t.text);
- // visibility
- let er = Rect::from_center_size(pos2(r.max.x - 14.0, r.center().y), vec2(16.0, 16.0));
- let eresp = ui.interact(er, egui::Id::unique(("gfx-eye", clip.0, li)), Sense::click());
- icons::paint(ui.painter(), er.shrink(2.0), if e.enabled { Icon::Eye } else { Icon::EyeOff }, t.text_dim);
- autos.push((format!("graphics.layers.{li}.visible"), er, "Toggle visibility".into()));
- autos.push((format!("graphics.layers.{li}"), r, layer_display_name(e, li)));
- if eresp.clicked() {
- actions.push(("graphics.set".into(), json!({"clip": clip.0, "layer": li, "props": {"enabled": !e.enabled}})));
- } else if resp.clicked() {
- actions.push(("graphics.selectLayer".into(), json!({"clip": clip.0, "layers": [li]})));
- }
- }
- }
+ layers_section(app, ui, clip, &it, sel, &mut autos, &mut actions);
// ---- template properties (a graphic made from a graphics template)
if it.graphic.as_ref().is_some_and(|m| m.template.is_some()) && section(ui, app, "Template Properties", &t) {
crate::panels::graphics_templates::template_controls(app, ui, clip, &it, mt, &mut autos, &mut actions);
@@ -466,32 +519,12 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
});
cx.point(ui, tl!("Position"), "position");
cx.point(ui, tl!("Anchor point"), "anchor");
- cx.number(ui, tl!("Scale"), "scale", 0.5, (0.0, 100_000.0), 0, " %");
- cx.number(ui, tl!("Rotation"), "rotation", 0.5, (-36_000.0, 36_000.0), 1, " °");
- cx.number(ui, tl!("Opacity"), "opacity", 0.5, (0.0, 100.0), 0, " %");
+ cx.number(ui, tl!("Scale"), NumberField { id: "scale", speed: 0.5, range: (0.0, 100_000.0), decimals: 0, unit: " %" });
+ cx.number(ui, tl!("Rotation"), NumberField { id: "rotation", speed: 0.5, range: (-36_000.0, 36_000.0), decimals: 1, unit: " °" });
+ cx.number(ui, tl!("Opacity"), NumberField { id: "opacity", speed: 0.5, range: (0.0, 100.0), decimals: 0, unit: " %" });
}
// ---- text
- let text_open = e.effect == graphic::TEXT_LAYER && {
- let (open, head) = section_header(ui, app, "Text", &t);
- // Text Properties: the layer type (point / paragraph) and text styling
- let wr = Rect::from_center_size(pos2(head.max.x - 16.0, head.center().y), vec2(22.0, 22.0));
- let wresp = ui.interact(wr, egui::Id::unique(("gfx-text-props", clip.0, l)), Sense::click());
- icons::paint(ui.painter(), wr.shrink(4.0), Icon::Wrench, if wresp.hovered() { t.text } else { t.text_dim });
- cx.autos.push(("graphics.textProperties".into(), wr, "Text Properties".into()));
- if wresp.on_hover_text(tl!("Text Properties")).clicked() {
- let flag = |id: &str| pv(e, id, mt).as_bool().unwrap_or(false);
- let ligatures = flag("ligatures");
- app.ui.text_props_dialog = Some(TextPropsDialog {
- clip: clip.0,
- layer: l,
- paragraph: pv(e, "box_width", mt).as_f64().unwrap_or(0.0) > 0.0 && !flag("vertical"),
- vertical: flag("vertical"),
- ligatures,
- ligatures_was: ligatures,
- });
- }
- open
- };
+ let text_open = e.effect == graphic::TEXT_LAYER && text_section_header(ui, app, clip, l, e, mt, &mut cx.autos);
if text_open {
// source text (multi-line), committed as it is typed
let mut s = match pv(e, "text", mt) {
@@ -553,7 +586,7 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
});
let response = crate::widgets::accessible_name(r.response, "Font Style");
cx.auto("font_style", response.rect, "Font Style");
- cx.number(ui, tl!("Font Size"), "size", 0.5, (1.0, 2000.0), 0, "");
+ cx.number(ui, tl!("Font Size"), NumberField { id: "size", speed: 0.5, range: (1.0, 2000.0), decimals: 0, unit: "" });
let align = match pv(e, "align", mt) {
ParamValue::Choice(c) => c,
_ => 0,
@@ -568,9 +601,9 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
cx.set("align", json!(i));
}
}
- cx.number(ui, tl!("Tracking"), "tracking", 1.0, (-1000.0, 10_000.0), 0, "");
- cx.number(ui, tl!("Leading"), "leading", 0.5, (-5000.0, 5000.0), 0, "");
- cx.number(ui, tl!("Baseline Shift"), "baseline_shift", 0.5, (-5000.0, 5000.0), 0, "");
+ cx.number(ui, tl!("Tracking"), NumberField { id: "tracking", speed: 1.0, range: (-1000.0, 10_000.0), decimals: 0, unit: "" });
+ cx.number(ui, tl!("Leading"), NumberField { id: "leading", speed: 0.5, range: (-5000.0, 5000.0), decimals: 0, unit: "" });
+ cx.number(ui, tl!("Baseline Shift"), NumberField { id: "baseline_shift", speed: 0.5, range: (-5000.0, 5000.0), decimals: 0, unit: "" });
let vertical = pv(e, "vertical", mt).as_bool().unwrap_or(false);
let (_, mut vui) = cx.row(ui, tl!("Orientation"));
let mut value = vertical;
@@ -579,8 +612,8 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
if response.changed() {
cx.set("vertical", json!(value));
}
- cx.number(ui, tl!("Text Box Width"), "box_width", 2.0, (0.0, 100_000.0), 0, "");
- cx.number(ui, tl!("Text Box Height"), "box_height", 2.0, (0.0, 100_000.0), 0, "");
+ cx.number(ui, tl!("Text Box Width"), NumberField { id: "box_width", speed: 2.0, range: (0.0, 100_000.0), decimals: 0, unit: "" });
+ cx.number(ui, tl!("Text Box Height"), NumberField { id: "box_height", speed: 2.0, range: (0.0, 100_000.0), decimals: 0, unit: "" });
let (_, mut vui) = cx.row(ui, tl!("Style"));
let flag = |id: &str| pv(e, id, mt).as_bool().unwrap_or(false);
let caps = match pv(e, "caps", mt) {
@@ -617,8 +650,8 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let (_, mut vui) = cx.row(ui, tl!("Shape"));
cx.choice(&mut vui, "shape", tl!("Shape"), graphic::SHAPE_OPTS, 120.0);
cx.point(ui, tl!("Size"), "size");
- cx.number(ui, tl!("Corner Radius"), "corner_radius", 0.5, (0.0, 10_000.0), 0, "");
- cx.number(ui, tl!("Polygon Sides"), "sides", 0.05, (3.0, 64.0), 0, "");
+ cx.number(ui, tl!("Corner Radius"), NumberField { id: "corner_radius", speed: 0.5, range: (0.0, 10_000.0), decimals: 0, unit: "" });
+ cx.number(ui, tl!("Polygon Sides"), NumberField { id: "sides", speed: 0.05, range: (3.0, 64.0), decimals: 0, unit: "" });
}
// ---- appearance
if section(ui, app, "Appearance", &t) {
@@ -637,7 +670,7 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let (_, mut vui) = cx.row(ui, tl!("Gradient"));
cx.color(&mut vui, "gradient_start");
cx.color(&mut vui, "gradient_end");
- cx.number(ui, tl!(" Angle"), "gradient_angle", 0.5, (-3600.0, 3600.0), 0, " °");
+ cx.number(ui, tl!(" Angle"), NumberField { id: "gradient_angle", speed: 0.5, range: (-3600.0, 3600.0), decimals: 0, unit: " °" });
}
for (on, col, w, kind, label, width_label, type_label) in [
("stroke", "stroke_color", "stroke_width", "stroke_type", tl!("Stroke"), tl!("Stroke Width"), tl!("Stroke Type")),
@@ -655,19 +688,19 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let bg = cx.check(&mut vui, "background", "");
cx.color(&mut vui, "background_color");
if bg {
- cx.number(ui, tl!(" Opacity"), "background_opacity", 0.5, (0.0, 100.0), 0, " %");
- cx.number(ui, tl!(" Size"), "background_size", 0.5, (0.0, 1000.0), 0, "");
- cx.number(ui, tl!(" Corner Radius"), "background_radius", 0.5, (0.0, 1000.0), 0, "");
+ cx.number(ui, tl!(" Opacity"), NumberField { id: "background_opacity", speed: 0.5, range: (0.0, 100.0), decimals: 0, unit: " %" });
+ cx.number(ui, tl!(" Size"), NumberField { id: "background_size", speed: 0.5, range: (0.0, 1000.0), decimals: 0, unit: "" });
+ cx.number(ui, tl!(" Corner Radius"), NumberField { id: "background_radius", speed: 0.5, range: (0.0, 1000.0), decimals: 0, unit: "" });
}
let (_, mut vui) = cx.row(ui, tl!("Shadow"));
let sh = cx.check(&mut vui, "shadow", "");
cx.color(&mut vui, "shadow_color");
if sh {
- cx.number(ui, tl!(" Opacity"), "shadow_opacity", 0.5, (0.0, 100.0), 0, " %");
- cx.number(ui, tl!(" Angle"), "shadow_angle", 0.5, (-36_000.0, 36_000.0), 0, " °");
- cx.number(ui, tl!(" Distance"), "shadow_distance", 0.5, (0.0, 1000.0), 0, "");
- cx.number(ui, tl!(" Size"), "shadow_size", 0.5, (0.0, 1000.0), 0, "");
- cx.number(ui, tl!(" Blur"), "shadow_blur", 0.5, (0.0, 1000.0), 0, "");
+ cx.number(ui, tl!(" Opacity"), NumberField { id: "shadow_opacity", speed: 0.5, range: (0.0, 100.0), decimals: 0, unit: " %" });
+ cx.number(ui, tl!(" Angle"), NumberField { id: "shadow_angle", speed: 0.5, range: (-36_000.0, 36_000.0), decimals: 0, unit: " °" });
+ cx.number(ui, tl!(" Distance"), NumberField { id: "shadow_distance", speed: 0.5, range: (0.0, 1000.0), decimals: 0, unit: "" });
+ cx.number(ui, tl!(" Size"), NumberField { id: "shadow_size", speed: 0.5, range: (0.0, 1000.0), decimals: 0, unit: "" });
+ cx.number(ui, tl!(" Blur"), NumberField { id: "shadow_blur", speed: 0.5, range: (0.0, 1000.0), decimals: 0, unit: "" });
}
}
actions.append(&mut cx.actions);
diff --git a/crates/ui-egui/src/panels/masks.rs b/crates/ui-egui/src/panels/masks.rs
index aea4ac1ea..3b76219fa 100644
--- a/crates/ui-egui/src/panels/masks.rs
+++ b/crates/ui-egui/src/panels/masks.rs
@@ -256,7 +256,6 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
let path = m.path_at(mt);
let feather = m.feather.f64_at(mt).max(0.0);
let expansion = m.expansion.f64_at(mt);
- let t = app.tokens;
let col = Color32::from_rgb(0x5a, 0xb4, 0xff);
let painter = ui.painter().with_clip_rect(pic.expand(16.0));
let flat = path.flatten(0.5);
@@ -345,22 +344,128 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
ui.ctx().set_cursor_icon(egui::CursorIcon::Move);
}
// ---- feather (top) and expansion (bottom) handles
+ feather_expansion_handles(app, ui, &painter, &flat, &to_screen, &lin_inv, expansion, feather, &target, gesture, &mut actions);
+ // ---- corner roundness (masks with sharp corners: rectangles, polygons)
+ actions.extend(roundness_handle(app, ui, &painter, &path, &to_screen, &target));
+ // ---- tangent handles and vertices
+ let sel_v_id = egui::Id::unique(("mask-sel-vertex", sel.clip.0, sel.effect, sel.mask));
+ let n_v = path.vertices.len();
+ // (stored with the vertex count: once a vertex is added or deleted, by any edit or by undo, the
+ // indices name other vertices and the selection goes)
+ let mut sel_vs: Vec<usize> = ui.data(|d| d.get_temp::<(usize, Vec<usize>)>(sel_v_id)).filter(|(n, _)| *n == n_v).map(|(_, v)| v).unwrap_or_default();
+ let alt = ui.input(|i| i.modifiers.alt);
+ let cmd = ui.input(|i| i.modifiers.command);
+ let shift = ui.input(|i| i.modifiers.shift);
+ // ---- tangent handles
+ tangent_handles(app, ui, &painter, &path, &to_screen, &lin_inv, &target, alt, gesture, &mut actions);
+ // ---- vertices
+ vertex_handles(app, ui, &painter, &path, &to_screen, &lin_inv, &target, &mut sel_vs, sel_v_id, n_v, gesture, &mut actions);
+ // the marquee selects the vertices inside it on release (Shift adds them to the selection)
+ let mq = marquee.iter().chain(body_marquee.then_some(&body));
+ let (started, dragging, stopped) =
+ mq.fold((false, false, false), |(a, b, c), r| (a || r.drag_started_by(LEFT), b || r.dragged_by(LEFT), c || r.drag_stopped_by(LEFT)));
+ if started && let Some(o) = ui.input(|i| i.pointer.press_origin()) {
+ ui.data_mut(|d| d.insert_temp(marquee_from, o));
+ }
+ let from: Option<Pos2> = ui.data(|d| d.get_temp(marquee_from));
+ if let (Some(o), Some(p)) = (from.filter(|_| dragging || stopped), ui.input(|i| i.pointer.latest_pos())) {
+ let r = Rect::from_two_pos(o, p);
+ if stopped {
+ ui.data_mut(|d| d.remove::<Pos2>(marquee_from));
+ if !shift {
+ sel_vs.clear();
+ }
+ for (i, v) in path.vertices.iter().enumerate() {
+ if r.contains(sp(&to_screen, v.p)) && !sel_vs.contains(&i) {
+ sel_vs.push(i);
+ }
+ }
+ ui.data_mut(|d| d.insert_temp(sel_v_id, (n_v, sel_vs.clone())));
+ } else {
+ painter.rect_filled(r, 0.0, col.gamma_multiply(0.15));
+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, col), egui::StrokeKind::Middle);
+ }
+ }
+ // Cmd-click on an edge adds a vertex there
+ if cmd
+ && body.clicked()
+ && let Some(pp) = body.interact_pointer_pos()
+ {
+ let n = path.vertices.len();
+ let best = (0..n)
+ .map(|i| {
+ let seg = MaskPath { vertices: vec![path.vertices[i], path.vertices[(i + 1) % n]], closed: false }.flatten(0.5);
+ let d = seg.windows(2).map(|w| seg_dist(pp, sp(&to_screen, w[0]), sp(&to_screen, w[1]))).fold(f32::INFINITY, f32::min);
+ (i, d)
+ })
+ .min_by(|a, b| a.1.total_cmp(&b.1));
+ if let Some((i, d)) = best
+ && d < 8.0
+ {
+ let c = to_clip.apply(Vec2::new(pp.x as f64, pp.y as f64));
+ actions.retain(|(c, _)| c != "masks.select");
+ actions.push(("masks.addVertex".into(), with(json!({"after": i, "at": [c.x, c.y]}))));
+ }
+ }
+ if ui.input(|i| i.key_pressed(egui::Key::Escape)) && ui.ctx().memory(|m| m.focused().is_none()) {
+ actions.push(("masks.select".into(), json!({"none": true})));
+ }
+ for (c, p) in actions {
+ if let Err(e) = app.session.execute(&c, p) {
+ app.ui.status = e.to_string();
+ }
+ }
+}
+
+/// The feather (top) and expansion (bottom) handles on the selected mask's contour: their
+/// stems, glyphs and the drag that moves them.
+#[allow(clippy::too_many_arguments)]
+fn feather_expansion_handles(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ painter: &egui::Painter,
+ flat: &[Vec2],
+ to_screen: &Affine,
+ lin_inv: &Affine,
+ expansion: f64,
+ feather: f64,
+ target: &Value,
+ gesture: u64,
+ actions: &mut Vec<(String, Value)>,
+) {
+ let t = app.tokens;
+ let screen: Vec<Pos2> = flat.iter().map(|v| sp(to_screen, *v)).collect();
+ let col = Color32::from_rgb(0x5a, 0xb4, 0xff);
+ let with = |extra: Value| -> Value {
+ let mut v = target.clone();
+ if let (Some(o), Some(x)) = (v.as_object_mut(), extra.as_object()) {
+ for (k, val) in x {
+ o.insert(k.clone(), val.clone());
+ }
+ }
+ v
+ };
+ let clip_delta = |d: egui::Vec2| -> [f64; 2] {
+ let v = lin_inv.apply(Vec2::new(d.x as f64, d.y as f64));
+ [v.x, v.y]
+ };
+ // ---- feather (top) and expansion (bottom) handles
let top = (0..flat.len()).min_by(|a, b| screen[*a].y.total_cmp(&screen[*b].y));
let bottom = (0..flat.len()).max_by(|a, b| screen[*a].y.total_cmp(&screen[*b].y));
if let (Some(ti), Some(bi)) = (top, bottom) {
let unit_n = |i: usize| {
- let o = offset(&flat, 1.0)[i] - flat[i];
+ let o = offset(flat, 1.0)[i] - flat[i];
o * (1.0 / o.length().max(1e-9))
};
for (which, i, dist) in [("feather", ti, expansion + feather / 2.0), ("expansion", bi, expansion)] {
let n = unit_n(i);
- let anchor = sp(&to_screen, flat[i]);
- let hp = sp(&to_screen, flat[i] + n * dist);
+ let anchor = sp(to_screen, flat[i]);
+ let hp = sp(to_screen, flat[i] + n * dist);
// keep the handle visible off the contour: a short stem outward
- let stem = egui::Vec2::new((sp(&to_screen, flat[i] + n) - anchor).x, (sp(&to_screen, flat[i] + n) - anchor).y);
+ let stem = egui::Vec2::new((sp(to_screen, flat[i] + n) - anchor).x, (sp(to_screen, flat[i] + n) - anchor).y);
let stem = if stem.length() > 1e-6 { stem.normalized() } else { egui::Vec2::new(0.0, -1.0) };
let hp = hp + stem * 14.0;
- painter.line_segment([sp(&to_screen, flat[i] + n * dist), hp], Stroke::new(1.0, col));
+ painter.line_segment([sp(to_screen, flat[i] + n * dist), hp], Stroke::new(1.0, col));
let hr = Rect::from_center_size(hp, vec2(9.0, 9.0));
if which == "feather" {
painter.circle_filled(hp, 4.0, col);
@@ -382,24 +487,43 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
}
}
}
- // ---- corner roundness (masks with sharp corners: rectangles, polygons)
- actions.extend(roundness_handle(app, ui, &painter, &path, &to_screen, &target));
- // ---- tangent handles and vertices
- let sel_v_id = egui::Id::unique(("mask-sel-vertex", sel.clip.0, sel.effect, sel.mask));
- let n_v = path.vertices.len();
- // (stored with the vertex count: once a vertex is added or deleted, by any edit or by undo, the
- // indices name other vertices and the selection goes)
- let mut sel_vs: Vec<usize> = ui.data(|d| d.get_temp::<(usize, Vec<usize>)>(sel_v_id)).filter(|(n, _)| *n == n_v).map(|(_, v)| v).unwrap_or_default();
- let alt = ui.input(|i| i.modifiers.alt);
- let cmd = ui.input(|i| i.modifiers.command);
- let shift = ui.input(|i| i.modifiers.shift);
+}
+
+/// The selected mask's Bezier tangent handles, one pair per smooth vertex.
+#[allow(clippy::too_many_arguments)]
+fn tangent_handles(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ painter: &egui::Painter,
+ path: &MaskPath,
+ to_screen: &Affine,
+ lin_inv: &Affine,
+ target: &Value,
+ alt: bool,
+ gesture: u64,
+ actions: &mut Vec<(String, Value)>,
+) {
+ let col = Color32::from_rgb(0x5a, 0xb4, 0xff);
+ let with = |extra: Value| -> Value {
+ let mut v = target.clone();
+ if let (Some(o), Some(x)) = (v.as_object_mut(), extra.as_object()) {
+ for (k, val) in x {
+ o.insert(k.clone(), val.clone());
+ }
+ }
+ v
+ };
+ let clip_delta = |d: egui::Vec2| -> [f64; 2] {
+ let v = lin_inv.apply(Vec2::new(d.x as f64, d.y as f64));
+ [v.x, v.y]
+ };
for (i, v) in path.vertices.iter().enumerate() {
if v.is_corner() {
continue;
}
- let p = sp(&to_screen, v.p);
+ let p = sp(to_screen, v.p);
for (which, tan) in [("in", v.t_in), ("out", v.t_out)] {
- let h = sp(&to_screen, v.p + tan);
+ let h = sp(to_screen, v.p + tan);
painter.line_segment([p, h], Stroke::new(1.0, col.gamma_multiply(0.8)));
painter.circle_filled(h, 3.5, Color32::WHITE);
painter.circle_stroke(h, 3.5, Stroke::new(1.0, col));
@@ -414,8 +538,44 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
}
}
}
+}
+
+/// The mask's vertices: drag moves them (the whole selection when several are selected),
+/// Alt-click toggles a corner, Cmd-click deletes, click selects (Shift adds or removes).
+#[allow(clippy::too_many_arguments)]
+fn vertex_handles(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ painter: &egui::Painter,
+ path: &MaskPath,
+ to_screen: &Affine,
+ lin_inv: &Affine,
+ target: &Value,
+ sel_vs: &mut Vec<usize>,
+ sel_v_id: egui::Id,
+ n_v: usize,
+ gesture: u64,
+ actions: &mut Vec<(String, Value)>,
+) {
+ let col = Color32::from_rgb(0x5a, 0xb4, 0xff);
+ let alt = ui.input(|i| i.modifiers.alt);
+ let cmd = ui.input(|i| i.modifiers.command);
+ let shift = ui.input(|i| i.modifiers.shift);
+ let with = |extra: Value| -> Value {
+ let mut v = target.clone();
+ if let (Some(o), Some(x)) = (v.as_object_mut(), extra.as_object()) {
+ for (k, val) in x {
+ o.insert(k.clone(), val.clone());
+ }
+ }
+ v
+ };
+ let clip_delta = |d: egui::Vec2| -> [f64; 2] {
+ let v = lin_inv.apply(Vec2::new(d.x as f64, d.y as f64));
+ [v.x, v.y]
+ };
for (i, v) in path.vertices.iter().enumerate() {
- let p = sp(&to_screen, v.p);
+ let p = sp(to_screen, v.p);
let vr = Rect::from_center_size(p, vec2(7.0, 7.0));
let selected = sel_vs.contains(&i);
painter.rect_filled(vr, 0.0, if selected { col } else { Color32::WHITE });
@@ -463,61 +623,6 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
}
}
}
- // the marquee selects the vertices inside it on release (Shift adds them to the selection)
- let mq = marquee.iter().chain(body_marquee.then_some(&body));
- let (started, dragging, stopped) =
- mq.fold((false, false, false), |(a, b, c), r| (a || r.drag_started_by(LEFT), b || r.dragged_by(LEFT), c || r.drag_stopped_by(LEFT)));
- if started && let Some(o) = ui.input(|i| i.pointer.press_origin()) {
- ui.data_mut(|d| d.insert_temp(marquee_from, o));
- }
- let from: Option<Pos2> = ui.data(|d| d.get_temp(marquee_from));
- if let (Some(o), Some(p)) = (from.filter(|_| dragging || stopped), ui.input(|i| i.pointer.latest_pos())) {
- let r = Rect::from_two_pos(o, p);
- if stopped {
- ui.data_mut(|d| d.remove::<Pos2>(marquee_from));
- if !shift {
- sel_vs.clear();
- }
- for (i, v) in path.vertices.iter().enumerate() {
- if r.contains(sp(&to_screen, v.p)) && !sel_vs.contains(&i) {
- sel_vs.push(i);
- }
- }
- ui.data_mut(|d| d.insert_temp(sel_v_id, (n_v, sel_vs.clone())));
- } else {
- painter.rect_filled(r, 0.0, col.gamma_multiply(0.15));
- painter.rect_stroke(r, 0.0, Stroke::new(1.0, col), egui::StrokeKind::Middle);
- }
- }
- // Cmd-click on an edge adds a vertex there
- if cmd
- && body.clicked()
- && let Some(pp) = body.interact_pointer_pos()
- {
- let n = path.vertices.len();
- let best = (0..n)
- .map(|i| {
- let seg = MaskPath { vertices: vec![path.vertices[i], path.vertices[(i + 1) % n]], closed: false }.flatten(0.5);
- let d = seg.windows(2).map(|w| seg_dist(pp, sp(&to_screen, w[0]), sp(&to_screen, w[1]))).fold(f32::INFINITY, f32::min);
- (i, d)
- })
- .min_by(|a, b| a.1.total_cmp(&b.1));
- if let Some((i, d)) = best
- && d < 8.0
- {
- let c = to_clip.apply(Vec2::new(pp.x as f64, pp.y as f64));
- actions.retain(|(c, _)| c != "masks.select");
- actions.push(("masks.addVertex".into(), with(json!({"after": i, "at": [c.x, c.y]}))));
- }
- }
- if ui.input(|i| i.key_pressed(egui::Key::Escape)) && ui.ctx().memory(|m| m.focused().is_none()) {
- actions.push(("masks.select".into(), json!({"none": true})));
- }
- for (c, p) in actions {
- if let Err(e) = app.session.execute(&c, p) {
- app.ui.status = e.to_string();
- }
- }
}
fn seg_dist(p: Pos2, a: Pos2, b: Pos2) -> f32 {
diff --git a/crates/ui-egui/src/panels/mixer.rs b/crates/ui-egui/src/panels/mixer.rs
index e935a3cb4..b76583d35 100644
--- a/crates/ui-egui/src/panels/mixer.rs
+++ b/crates/ui-egui/src/panels/mixer.rs
@@ -418,21 +418,18 @@ fn run_actions(app: &mut FilmcraftApp, ctx: &egui::Context, acts: Vec<(String, V
}
}
-/// Draw one mixer strip. A missing track is a no-op; automation ids use `mixer.<label>`; the master strip has `MASTER_STRIP` handling.
-fn strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, sr: Rect, meter: &[[f32; 2]]) {
+/// The effect and send slots at the top of a mixer strip: their popups (bypass, post-fader,
+/// level, routing, submixes) and the double-click that opens the effect editor. Returns the
+/// `y` below them.
+#[allow(clippy::too_many_arguments)]
+fn mixer_slots(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, x: f32, w: f32, mut y: f32) -> f32 {
let t = cx.t;
let seq = cx.seq;
- let Some(tr) = seq.strip(id).map(|c| c.into_owned()) else { return };
+ let Some(tr) = seq.strip(id).map(|c| c.into_owned()) else { return y };
let label = strip_label(seq, id);
let ap = format!("mixer.{label}");
let is_master = id == MASTER_STRIP;
let sid = json!(id.0);
- ui.painter().rect_filled(sr, 3.0, t.control_surface);
- ui.painter().line_segment([pos2(sr.max.x + 1.0, sr.min.y), pos2(sr.max.x + 1.0, sr.max.y)], Stroke::new(1.0, t.separator));
- let x = sr.min.x;
- let w = sr.width();
- let mut y = sr.min.y + 4.0;
-
// ---- effect and send slots
if app.ui.mixer_fx_open {
let mut open_editor = None;
@@ -594,6 +591,26 @@ fn strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, s
y += 6.0;
}
+ y
+}
+
+/// Draw one mixer strip. A missing track is a no-op; automation ids use `mixer.<label>`; the master strip has `MASTER_STRIP` handling.
+fn strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, sr: Rect, meter: &[[f32; 2]]) {
+ let t = cx.t;
+ let seq = cx.seq;
+ let Some(tr) = seq.strip(id).map(|c| c.into_owned()) else { return };
+ let label = strip_label(seq, id);
+ let ap = format!("mixer.{label}");
+ let is_master = id == MASTER_STRIP;
+ let sid = json!(id.0);
+ ui.painter().rect_filled(sr, 3.0, t.control_surface);
+ ui.painter().line_segment([pos2(sr.max.x + 1.0, sr.min.y), pos2(sr.max.x + 1.0, sr.max.y)], Stroke::new(1.0, t.separator));
+ let x = sr.min.x;
+ let w = sr.width();
+ let mut y = sr.min.y + 4.0;
+
+ y = mixer_slots(app, ui, cx, id, x, w, y);
+
// ---- input / output
if !is_master {
let ir = Rect::from_min_size(pos2(x + 4.0, y), vec2(w - 8.0, 20.0));
@@ -634,45 +651,7 @@ fn strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, s
pan51_panner(app, ui, cx, &tr, &ap, &sid, Rect::from_min_size(pos2(x + 4.0, y), vec2(w - 8.0, 62.0)));
y += 62.0;
} else {
- // ---- pan knob
- let pan = shown(app, &tr, LANE_PAN, cx.now);
- let kc = pos2(sr.center().x, y + 20.0);
- let kr = Rect::from_center_size(kc, vec2(38.0, 38.0));
- let kresp =
- ui.interact(kr, egui::Id::unique((&ap, "pan")), Sense::click_and_drag()).on_hover_text(tl!("Pan / balance (drag; double-click: centre)"));
- let ring = if kresp.hovered() || kresp.dragged() { t.tab_text_active } else { t.control_handle_dim };
- ui.painter().circle_stroke(kc, 16.0, Stroke::new(2.0, ring));
- let ang = (pan / 100.0) as f32 * 135f32.to_radians();
- ui.painter().line_segment([kc, kc + vec2(ang.sin(), -ang.cos()) * 14.0], Stroke::new(2.0, ring));
- small_text(ui, pos2(kc.x - 22.0, kc.y + 17.0), Align2::CENTER_CENTER, "L", 11.0, t.hot_text);
- small_text(ui, pos2(kc.x + 22.0, kc.y + 17.0), Align2::CENTER_CENTER, "R", 11.0, t.hot_text);
- app.auto.add(&format!("{ap}.pan"), kr, "Pan");
- if kresp.dragged() {
- let d = kresp.drag_delta();
- let np = (pan + (d.x - d.y) as f64).clamp(-100.0, 100.0);
- if np != pan {
- cx.cmd("mixer.touch", json!({"strip": sid, "lane": LANE_PAN, "value": np, "time": cx.now.0}));
- }
- }
- if kresp.drag_stopped() {
- cx.cmd("mixer.release", json!({"strip": sid, "lane": LANE_PAN, "time": cx.now.0}));
- }
- if kresp.double_clicked() {
- cx.cmd("mixer.setValue", json!({"strip": sid, "lane": LANE_PAN, "value": 0.0}));
- }
- let vr = Rect::from_center_size(pos2(kc.x, y + 48.0), vec2(56.0, 16.0));
- let mut vui = ui.new_child(egui::UiBuilder::new().max_rect(vr).layout(egui::Layout::top_down(egui::Align::Center)));
- let (vresp, nv) = crate::widgets::hot_number(
- &mut vui,
- tl!("Pan"),
- egui::Id::unique((&ap, "panValue")),
- pan,
- HotNumberOptions::new(1.0, (-100.0, 100.0), 1, "", &t),
- );
- app.auto.add(&format!("{ap}.panValue"), vresp.rect, &format!("{pan:.1}"));
- if let Some(v) = nv {
- cx.cmd("mixer.setValue", json!({"strip": sid, "lane": LANE_PAN, "value": v}));
- }
+ pan_knob(app, ui, cx, id, sr, y);
y += 62.0;
}
} else {
@@ -829,6 +808,50 @@ fn strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, s
app.auto.add(&format!("{ap}.name"), nr, &tr.name);
}
+/// The pan knob under a strip's output row: drag to pan (heard live), double-click to centre,
+/// with the numeric pan value below it.
+fn pan_knob(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, sr: Rect, y: f32) {
+ let seq = cx.seq;
+ let Some(tr) = seq.strip(id).map(|c| c.into_owned()) else { return };
+ let label = strip_label(seq, id);
+ let ap = format!("mixer.{label}");
+ let sid = json!(id.0);
+ let t = cx.t;
+ // ---- pan knob
+ let pan = shown(app, &tr, LANE_PAN, cx.now);
+ let kc = pos2(sr.center().x, y + 20.0);
+ let kr = Rect::from_center_size(kc, vec2(38.0, 38.0));
+ let kresp = ui.interact(kr, egui::Id::unique((&ap, "pan")), Sense::click_and_drag()).on_hover_text(tl!("Pan / balance (drag; double-click: centre)"));
+ let ring = if kresp.hovered() || kresp.dragged() { t.tab_text_active } else { t.control_handle_dim };
+ ui.painter().circle_stroke(kc, 16.0, Stroke::new(2.0, ring));
+ let ang = (pan / 100.0) as f32 * 135f32.to_radians();
+ ui.painter().line_segment([kc, kc + vec2(ang.sin(), -ang.cos()) * 14.0], Stroke::new(2.0, ring));
+ small_text(ui, pos2(kc.x - 22.0, kc.y + 17.0), Align2::CENTER_CENTER, "L", 11.0, t.hot_text);
+ small_text(ui, pos2(kc.x + 22.0, kc.y + 17.0), Align2::CENTER_CENTER, "R", 11.0, t.hot_text);
+ app.auto.add(&format!("{ap}.pan"), kr, "Pan");
+ if kresp.dragged() {
+ let d = kresp.drag_delta();
+ let np = (pan + (d.x - d.y) as f64).clamp(-100.0, 100.0);
+ if np != pan {
+ cx.cmd("mixer.touch", json!({"strip": sid, "lane": LANE_PAN, "value": np, "time": cx.now.0}));
+ }
+ }
+ if kresp.drag_stopped() {
+ cx.cmd("mixer.release", json!({"strip": sid, "lane": LANE_PAN, "time": cx.now.0}));
+ }
+ if kresp.double_clicked() {
+ cx.cmd("mixer.setValue", json!({"strip": sid, "lane": LANE_PAN, "value": 0.0}));
+ }
+ let vr = Rect::from_center_size(pos2(kc.x, y + 48.0), vec2(56.0, 16.0));
+ let mut vui = ui.new_child(egui::UiBuilder::new().max_rect(vr).layout(egui::Layout::top_down(egui::Align::Center)));
+ let (vresp, nv) =
+ crate::widgets::hot_number(&mut vui, tl!("Pan"), egui::Id::unique((&ap, "panValue")), pan, HotNumberOptions::new(1.0, (-100.0, 100.0), 1, "", &t));
+ app.auto.add(&format!("{ap}.panValue"), vresp.rect, &format!("{pan:.1}"));
+ if let Some(v) = nv {
+ cx.cmd("mixer.setValue", json!({"strip": sid, "lane": LANE_PAN, "value": v}));
+ }
+}
+
/// The 5.1 panner: a puck in the listening square (x left … right, y rear … front; speakers drawn
/// at L, C, R, Ls, Rs), and the Center % and LFE values. Drags are `mixer.touch` / `mixer.release`
/// on the `pan51.x` / `pan51.y` lanes, so they are heard live and recorded like the pan knob.
diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rs
index 018a2cd44..ecaa70fae 100644
--- a/crates/ui-egui/src/panels/monitor.rs
+++ b/crates/ui-egui/src/panels/monitor.rs
@@ -25,6 +25,165 @@ pub enum Which {
Program,
}
+/// What the monitor's picture block draws this frame.
+struct PictureCtx {
+ target: Target,
+ frame_size: (u32, u32),
+ rate: filmcraft_time::FrameRate,
+ time: Tick,
+ duration: Tick,
+ drop_frame: bool,
+ compare: bool,
+ ref_area: Option<Rect>,
+ pic: Rect,
+ video_area: Rect,
+ prefix: &'static str,
+}
+
+/// The picture block: schedules this frame's render request (GPU or CPU), shows the texture
+/// that is ready, and draws the safe margins, comparison reference and display-mode label.
+fn draw_picture(app: &mut FilmcraftApp, ui: &mut egui::Ui, which: Which, mv: &crate::state::MonitorView, pc: PictureCtx) {
+ let PictureCtx { target, frame_size, rate, time, duration, drop_frame, compare, ref_area, pic, video_area, prefix } = pc;
+ let t = app.tokens;
+ let ctx = ui.ctx().clone();
+ let display = mv.display_mode().unwrap_or(DisplayMode::Composite);
+ let display_w = (frame_size.0 as f64 * monitor_view::pixel_aspect(app, which)) as f32;
+ let ppp = ctx.pixels_per_point();
+ if mv.transparency_grid {
+ monitor_view::transparency_grid(ui.painter(), pic, ui.clip_rect());
+ } else {
+ ui.painter().rect_filled(pic, 0.0, t.monitor_bg);
+ }
+ let playing = if which == Which::Program { app.playback.playing } else { app.source_playback.clock.playing };
+ let res = mv.effective_res(playing);
+ // frame pixels per screen pixel along the axis that needs the most of them
+ let screen_scale = (pic.width() * ppp / frame_size.0.max(1) as f32).max(pic.height() * ppp / frame_size.1.max(1) as f32).min(1.0);
+ let scale = quantize_scale(res.scale().min(screen_scale.max(1.0 / 32.0)));
+ let frame = rate.frame_at(time);
+ let rev = match target {
+ Target::Item(i) => app.item_revision(i),
+ _ => app.session.revision,
+ };
+ let size_key = (scale * 1000.0) as u32;
+ let channel = display.is_channel();
+ // the GPU compositor's output is opaque, so the Transparency Grid takes the CPU frames
+ let grid = mv.transparency_grid && !channel;
+ let use_gpu = which == Which::Program && app.gpu.is_some() && !channel && !grid && !crate::panels::menu_dialogs::software_renderer(app);
+ // render previews are opaque, so the grid and Display Mode ▸ Alpha take live renders
+ let live = grid || display == DisplayMode::Alpha;
+ let cpu_target = target;
+ let target = match (use_gpu, target) {
+ (true, Target::Sequence(s)) => Target::SequencePlan(s),
+ (false, Target::Sequence(s)) if live => Target::SequenceLive(s),
+ (_, t) => t,
+ };
+ // Draft decoding (opt-in): only while playing at 1/2 resolution or lower.
+ let draft = crate::frames::draft_playback(playing, scale, app.session.prefs.playback.draft_decode);
+ let key = FrameKey { target, frame, size: size_key, revision: rev, draft };
+ let project = app.session.project.clone();
+ if playing {
+ let preroll = which == Which::Program && app.playback.preroll.is_some();
+ let speed = if which == Which::Program { app.playback.speed } else { app.source_playback.clock.speed };
+ app.frames.schedule_playback(key, rate, scale, &project, speed, preroll);
+ if preroll {
+ app.playback.preroll_ready = app.frames.preroll_ready(key, app.playback.speed, rate.frame_at(duration) - 1);
+ }
+ } else {
+ app.frames.request(key, rate.tick_of(frame), scale, &project, 0);
+ }
+ let asked = asked_before(app, prefix, key, playing);
+ let tex_name = if channel {
+ format!("monitor-{prefix}-{display:?}")
+ } else if grid {
+ format!("monitor-{prefix}-grid")
+ } else {
+ format!("monitor-{prefix}")
+ };
+ let (shown, on_screen) = if use_gpu {
+ let found = app
+ .frames
+ .get_plan(&key)
+ .map(|p| (key, p))
+ .or_else(|| app.frames.nearest_plan(key, 6))
+ .or_else(|| asked.iter().find_map(|k| app.frames.get_plan(k).map(|p| (*k, p))));
+ match found {
+ Some((k, plan)) => (app.gpu_present(k, &plan).map(|(id, _)| id), Some(k)),
+ None => (app.gpu.as_ref().and_then(|g| g.texture), app.gpu.as_ref().and_then(|g| g.last_key)),
+ }
+ } else if grid {
+ cpu_texture_as(app, &ctx, &tex_name, key, &asked, display, true)
+ } else {
+ cpu_texture(app, &ctx, &tex_name, key, &asked, display)
+ };
+ let exact = on_screen == Some(key);
+ if which == Which::Program {
+ app.program_shown = on_screen;
+ }
+ if !playing && !exact {
+ app.monitor_inexact = true;
+ }
+ if playing {
+ let clock = if which == Which::Program { &mut app.playback } else { &mut app.source_playback.clock };
+ if std::mem::take(&mut clock.hidden) {
+ clock.meter.resync(frame, exact);
+ } else {
+ clock.meter.refresh(frame, exact);
+ }
+ }
+ if let Some(tex) = shown {
+ ui.painter().image(tex, pic, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ if let Some(ra) = ref_area {
+ // the reference frame (CPU path)
+ let rf = rate.frame_at(Tick(mv.compare_ref.unwrap_or(time.0)));
+ let rtarget = match cpu_target {
+ Target::Sequence(s) if mv.transparency_grid => Target::SequenceLive(s),
+ t => t,
+ };
+ let rkey = FrameKey { target: rtarget, frame: rf, size: size_key, revision: rev, draft: false };
+ app.frames.request(rkey, rate.tick_of(rf), scale, &project, 1);
+ let rpic = fit(ra, display_w, frame_size.1 as f32);
+ if mv.transparency_grid {
+ monitor_view::transparency_grid(ui.painter(), rpic, ui.clip_rect());
+ } else {
+ ui.painter().rect_filled(rpic, 0.0, t.monitor_bg);
+ }
+ let (reference, _) = if mv.transparency_grid {
+ cpu_texture_as(app, &ctx, &format!("monitor-{prefix}-ref-grid"), rkey, &[], DisplayMode::Composite, true)
+ } else {
+ cpu_texture(app, &ctx, &format!("monitor-{prefix}-ref"), rkey, &[], DisplayMode::Composite)
+ };
+ if let Some(tex) = reference {
+ ui.painter().image(tex, rpic, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ app.auto.add("program.compare.reference", rpic, "reference frame");
+ let bar = Rect::from_min_max(pos2(ra.min.x, ra.max.y + 2.0), pos2(video_area.max.x, ra.max.y + 22.0));
+ monitor_view::compare_bar(app, ui, bar, rate, drop_frame);
+ }
+ if mv.safe_margins {
+ for (f, c) in [(0.9, Color32::from_white_alpha(120)), (0.8, Color32::from_white_alpha(90))] {
+ let r = Rect::from_center_size(pic.center(), pic.size() * f);
+ ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, c), StrokeKind::Middle);
+ }
+ let c = pic.center();
+ ui.painter().line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::from_white_alpha(120)));
+ ui.painter().line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::from_white_alpha(120)));
+ }
+ if display != DisplayMode::Composite && !compare {
+ let label = match display {
+ DisplayMode::Composite => tl!("Composite"),
+ DisplayMode::Alpha => tl!("Alpha"),
+ DisplayMode::Red => tl!("Red"),
+ DisplayMode::Green => tl!("Green"),
+ DisplayMode::Blue => tl!("Blue"),
+ DisplayMode::AudioWaveform => tl!("Audio Waveform"),
+ DisplayMode::Comparison => tl!("Comparison"),
+ DisplayMode::VideoAndWaveform => tl!("Video and Waveform"),
+ };
+ ui.painter().text(pos2(video_area.max.x - 8.0, video_area.min.y + 6.0), Align2::RIGHT_TOP, label, Tokens::ui(10.0), t.text_dim);
+ }
+}
+
pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which) {
let t = app.tokens;
let ctx = ui.ctx().clone();
@@ -174,139 +333,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
let saved_clip = ui.clip_rect();
ui.set_clip_rect(saved_clip.intersect(if mv.zoom.is_some() && !compare { video_area } else { picture_area.expand(12.0) }));
if show_picture {
- if mv.transparency_grid {
- monitor_view::transparency_grid(ui.painter(), pic, ui.clip_rect());
- } else {
- ui.painter().rect_filled(pic, 0.0, t.monitor_bg);
- }
- let playing = if which == Which::Program { app.playback.playing } else { app.source_playback.clock.playing };
- let res = mv.effective_res(playing);
- // frame pixels per screen pixel along the axis that needs the most of them
- let screen_scale = (pic.width() * ppp / frame_size.0.max(1) as f32).max(pic.height() * ppp / frame_size.1.max(1) as f32).min(1.0);
- let scale = quantize_scale(res.scale().min(screen_scale.max(1.0 / 32.0)));
- let frame = rate.frame_at(time);
- let rev = match target {
- Target::Item(i) => app.item_revision(i),
- _ => app.session.revision,
- };
- let size_key = (scale * 1000.0) as u32;
- let channel = display.is_channel();
- // the GPU compositor's output is opaque, so the Transparency Grid takes the CPU frames
- let grid = mv.transparency_grid && !channel;
- let use_gpu = which == Which::Program && app.gpu.is_some() && !channel && !grid && !crate::panels::menu_dialogs::software_renderer(app);
- // render previews are opaque, so the grid and Display Mode ▸ Alpha take live renders
- let live = grid || display == DisplayMode::Alpha;
- let cpu_target = target;
- let target = match (use_gpu, target) {
- (true, Target::Sequence(s)) => Target::SequencePlan(s),
- (false, Target::Sequence(s)) if live => Target::SequenceLive(s),
- (_, t) => t,
- };
- // Draft decoding (opt-in): only while playing at 1/2 resolution or lower.
- let draft = crate::frames::draft_playback(playing, scale, app.session.prefs.playback.draft_decode);
- let key = FrameKey { target, frame, size: size_key, revision: rev, draft };
- let project = app.session.project.clone();
- if playing {
- let preroll = which == Which::Program && app.playback.preroll.is_some();
- let speed = if which == Which::Program { app.playback.speed } else { app.source_playback.clock.speed };
- app.frames.schedule_playback(key, rate, scale, &project, speed, preroll);
- if preroll {
- app.playback.preroll_ready = app.frames.preroll_ready(key, app.playback.speed, rate.frame_at(duration) - 1);
- }
- } else {
- app.frames.request(key, rate.tick_of(frame), scale, &project, 0);
- }
- let asked = asked_before(app, prefix, key, playing);
- let tex_name = if channel {
- format!("monitor-{prefix}-{display:?}")
- } else if grid {
- format!("monitor-{prefix}-grid")
- } else {
- format!("monitor-{prefix}")
- };
- let (shown, on_screen) = if use_gpu {
- let found = app
- .frames
- .get_plan(&key)
- .map(|p| (key, p))
- .or_else(|| app.frames.nearest_plan(key, 6))
- .or_else(|| asked.iter().find_map(|k| app.frames.get_plan(k).map(|p| (*k, p))));
- match found {
- Some((k, plan)) => (app.gpu_present(k, &plan).map(|(id, _)| id), Some(k)),
- None => (app.gpu.as_ref().and_then(|g| g.texture), app.gpu.as_ref().and_then(|g| g.last_key)),
- }
- } else if grid {
- cpu_texture_as(app, &ctx, &tex_name, key, &asked, display, true)
- } else {
- cpu_texture(app, &ctx, &tex_name, key, &asked, display)
- };
- let exact = on_screen == Some(key);
- if which == Which::Program {
- app.program_shown = on_screen;
- }
- if !playing && !exact {
- app.monitor_inexact = true;
- }
- if playing {
- let clock = if which == Which::Program { &mut app.playback } else { &mut app.source_playback.clock };
- if std::mem::take(&mut clock.hidden) {
- clock.meter.resync(frame, exact);
- } else {
- clock.meter.refresh(frame, exact);
- }
- }
- if let Some(tex) = shown {
- ui.painter().image(tex, pic, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
- }
- if let Some(ra) = ref_area {
- // the reference frame (CPU path)
- let rf = rate.frame_at(Tick(mv.compare_ref.unwrap_or(time.0)));
- let rtarget = match cpu_target {
- Target::Sequence(s) if mv.transparency_grid => Target::SequenceLive(s),
- t => t,
- };
- let rkey = FrameKey { target: rtarget, frame: rf, size: size_key, revision: rev, draft: false };
- app.frames.request(rkey, rate.tick_of(rf), scale, &project, 1);
- let rpic = fit(ra, display_w, frame_size.1 as f32);
- if mv.transparency_grid {
- monitor_view::transparency_grid(ui.painter(), rpic, ui.clip_rect());
- } else {
- ui.painter().rect_filled(rpic, 0.0, t.monitor_bg);
- }
- let (reference, _) = if mv.transparency_grid {
- cpu_texture_as(app, &ctx, &format!("monitor-{prefix}-ref-grid"), rkey, &[], DisplayMode::Composite, true)
- } else {
- cpu_texture(app, &ctx, &format!("monitor-{prefix}-ref"), rkey, &[], DisplayMode::Composite)
- };
- if let Some(tex) = reference {
- ui.painter().image(tex, rpic, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
- }
- app.auto.add("program.compare.reference", rpic, "reference frame");
- let bar = Rect::from_min_max(pos2(ra.min.x, ra.max.y + 2.0), pos2(video_area.max.x, ra.max.y + 22.0));
- monitor_view::compare_bar(app, ui, bar, rate, drop_frame);
- }
- if mv.safe_margins {
- for (f, c) in [(0.9, Color32::from_white_alpha(120)), (0.8, Color32::from_white_alpha(90))] {
- let r = Rect::from_center_size(pic.center(), pic.size() * f);
- ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, c), StrokeKind::Middle);
- }
- let c = pic.center();
- ui.painter().line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::from_white_alpha(120)));
- ui.painter().line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::from_white_alpha(120)));
- }
- if display != DisplayMode::Composite && !compare {
- let label = match display {
- DisplayMode::Composite => tl!("Composite"),
- DisplayMode::Alpha => tl!("Alpha"),
- DisplayMode::Red => tl!("Red"),
- DisplayMode::Green => tl!("Green"),
- DisplayMode::Blue => tl!("Blue"),
- DisplayMode::AudioWaveform => tl!("Audio Waveform"),
- DisplayMode::Comparison => tl!("Comparison"),
- DisplayMode::VideoAndWaveform => tl!("Video and Waveform"),
- };
- ui.painter().text(pos2(video_area.max.x - 8.0, video_area.min.y + 6.0), Align2::RIGHT_TOP, label, Tokens::ui(10.0), t.text_dim);
- }
+ draw_picture(app, ui, which, &mv, PictureCtx { target, frame_size, rate, time, duration, drop_frame, compare, ref_area, pic, video_area, prefix });
}
// Dropped-frame indicator (Program only)
if which == Which::Program && app.playback.playing {
@@ -351,6 +378,42 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
app.ui.status = name.clone();
}
+ // ---- controls row: timecode | zoom | res | wrench | duration
+ let dur_tc = format_time(mark_out.map(|o| o + rate.frame_duration()).unwrap_or(duration) - range_start, rate, drop_frame, TimeDisplay::Timecode, 48000);
+ let (bar, zoom_bar) = controls_row(app, ui, rect, which, time, rate, drop_frame, origin, &dur_tc);
+
+ // ---- mini timeline / scrub bar
+ follow_playhead(app, which, origin, duration, time);
+ time_zoom_bar(app, ui, zoom_bar, which, origin, duration, rate);
+ mini_timeline(app, ui, bar, which, origin, time, duration, rate, mark_in, mark_out);
+
+ // ---- transport buttons
+ let row3 = Rect::from_min_size(pos2(rect.min.x, zoom_bar.max.y + 4.0), vec2(rect.width(), 32.0));
+ transport(app, ui, row3, which);
+}
+
+/// The controls row under the picture: timecode, duration, zoom, resolution, the wrench menu
+/// and the source-drag controls. Returns the mini-timeline and zoom bars below it.
+#[allow(clippy::too_many_arguments)]
+fn controls_row(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ rect: Rect,
+ which: Which,
+ time: Tick,
+ rate: filmcraft_time::FrameRate,
+ drop_frame: bool,
+ origin: Tick,
+ dur_tc: &str,
+) -> (Rect, Rect) {
+ let t = app.tokens;
+ let ctx = ui.ctx().clone();
+ let mv = monitor_view::view(app, which).clone();
+ let prefix = if which == Which::Program { "program" } else { "source" };
+ let stacked_controls = rect.width() < 540.0;
+ let separate_source_drag = which == Which::Source && stacked_controls && rect.width() < 310.0;
+ let source_drag_h = if separate_source_drag { 26.0 } else { 0.0 };
+ let controls_h = 28.0 + 24.0 + 15.0 + 36.0 + if stacked_controls { 26.0 } else { 0.0 } + source_drag_h;
// ---- controls row: timecode | zoom | res | wrench | duration
let row1 = Rect::from_min_size(pos2(rect.min.x + 14.0, rect.max.y - controls_h + 2.0), vec2(rect.width() - 28.0, 26.0));
let tc = format_time(time, rate, drop_frame, TimeDisplay::Timecode, 48000);
@@ -367,8 +430,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
None => {}
}
app.auto.add(&format!("{prefix}.timecode"), tc_rect, &tc);
- let dur_tc = format_time(mark_out.map(|o| o + rate.frame_duration()).unwrap_or(duration) - range_start, rate, drop_frame, TimeDisplay::Timecode, 48000);
- ui.painter().text(pos2(row1.max.x, row1.center().y), Align2::RIGHT_CENTER, &dur_tc, Tokens::timecode(), t.text_dim);
+ ui.painter().text(pos2(row1.max.x, row1.center().y), Align2::RIGHT_CENTER, dur_tc, Tokens::timecode(), t.text_dim);
// At compact widths, timecodes and view settings need separate rows.
let settings_y = row1.min.y + if stacked_controls { 26.0 } else { 0.0 };
let zoom_x = if stacked_controls && which == Which::Source && !separate_source_drag {
@@ -465,16 +527,9 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
}
}
});
- // ---- mini timeline / scrub bar
let bar = Rect::from_min_size(pos2(rect.min.x + 14.0, settings_y + 28.0 + source_drag_h), vec2(rect.width() - 28.0, 22.0));
let zoom_bar = Rect::from_min_size(pos2(bar.min.x, bar.max.y + 2.0), vec2(bar.width(), 13.0));
- follow_playhead(app, which, origin, duration, time);
- time_zoom_bar(app, ui, zoom_bar, which, origin, duration, rate);
- mini_timeline(app, ui, bar, which, origin, time, duration, rate, mark_in, mark_out);
-
- // ---- transport buttons
- let row3 = Rect::from_min_size(pos2(rect.min.x, zoom_bar.max.y + 4.0), vec2(rect.width(), 32.0));
- transport(app, ui, row3, which);
+ (bar, zoom_bar)
}
/// How many of a paused monitor's latest requests are remembered ([`asked_before`]): about a
diff --git a/crates/ui-egui/src/panels/project_views.rs b/crates/ui-egui/src/panels/project_views.rs
index 2227c526c..84e2f014d 100644
--- a/crates/ui-egui/src/panels/project_views.rs
+++ b/crates/ui-egui/src/panels/project_views.rs
@@ -1170,7 +1170,7 @@ fn card_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, v: &View, item: u64, act
}
fn canvas_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, v: &View, bin: Option<u64>, actions: &mut Actions) {
- fn entry(app: &mut FilmcraftApp, ui: &mut egui::Ui, v: &View, actions: &mut Actions, id: &str, label: &str, cmd: &str, p: serde_json::Value) {
+ fn entry(app: &mut FilmcraftApp, ui: &mut egui::Ui, v: &View, actions: &mut Actions, id: &str, label: &str, (cmd, p): (&str, serde_json::Value)) {
let b = ui.button(label);
app.auto.add(&format!("{}.canvasMenu.{id}", v.prefix), b.rect, label);
if b.clicked() {
@@ -1178,10 +1178,10 @@ fn canvas_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, v: &View, bin: Option<
ui.close();
}
}
- entry(app, ui, v, actions, "alignToGrid", tl!("Align to Grid"), "project.freeform.alignToGrid", json!({"bin": bin}));
- entry(app, ui, v, actions, "resetToGrid", tl!("Reset to Grid"), "project.freeform.reset", json!({"bin": bin}));
+ entry(app, ui, v, actions, "alignToGrid", tl!("Align to Grid"), ("project.freeform.alignToGrid", json!({"bin": bin})));
+ entry(app, ui, v, actions, "resetToGrid", tl!("Reset to Grid"), ("project.freeform.reset", json!({"bin": bin})));
ui.separator();
- entry(app, ui, v, actions, "saveArrangement", tl!("Save Arrangement…"), "projectPanel.saveArrangement", json!({}));
+ entry(app, ui, v, actions, "saveArrangement", tl!("Save Arrangement…"), ("projectPanel.saveArrangement", json!({})));
let names: Vec<String> = app
.session
.execute("project.freeform.arrangements", json!({"bin": bin}))
@@ -1207,7 +1207,7 @@ fn canvas_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, v: &View, bin: Option<
});
});
ui.separator();
- entry(app, ui, v, actions, "options", "Freeform View Options…", "projectPanel.freeformOptions", json!({}));
+ entry(app, ui, v, actions, "options", "Freeform View Options…", ("projectPanel.freeformOptions", json!({})));
ui.separator();
background_menu(app, ui, v, bin.filter(|b| *b != app.session.project.root.id.0), actions);
}
diff --git a/crates/ui-egui/src/panels/source_range.rs b/crates/ui-egui/src/panels/source_range.rs
index f5bd98237..9518bde45 100644
--- a/crates/ui-egui/src/panels/source_range.rs
+++ b/crates/ui-egui/src/panels/source_range.rs
@@ -73,6 +73,14 @@ pub fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, bar: Rect, which: Whi
let xof = |t: Tick| bar.min.x + (t.0.saturating_sub(shown.0.0) as f64 / span).clamp(0.0, 1.0) as f32 * bar.width();
// what is off a zoomed bar has no handle (past either end of it all, it sits at that end)
let shows = |t: Tick| (t >= shown.0 || shown.0 <= view.start) && (t <= shown.1 || shown.1 >= view.end);
+ // a hand on the movable band, a horizontal-resize arrow on the In/Out handles
+ let cursor_for = |edge: RangeEdge| {
+ if edge == RangeEdge::Move {
+ if cfg!(windows) { egui::CursorIcon::PointingHand } else { egui::CursorIcon::Grab }
+ } else {
+ egui::CursorIcon::ResizeHorizontal
+ }
+ };
let (a, b) = (xof(selected.start), xof(selected.end()));
let mid = (a + b) * 0.5;
let band = Rect::from_min_max(pos2(a, bar.min.y + 8.0), pos2(b, bar.max.y));
@@ -105,18 +113,13 @@ pub fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, bar: Rect, which: Whi
app.auto.add(id, rect, label);
let response =
ui.add_enabled_ui(enabled && rect.width() > 0.0, |ui| ui.interact(rect, egui::Id::unique(id), Sense::click_and_drag())).inner.on_hover_text(label);
- let cursor = if edge == RangeEdge::Move {
- if cfg!(windows) { egui::CursorIcon::PointingHand } else { egui::CursorIcon::Grab }
- } else {
- egui::CursorIcon::ResizeHorizontal
- };
+ let cursor = cursor_for(edge);
let response = response.on_hover_cursor(cursor);
result.handled |= response.hovered() || response.dragged() || response.clicked();
- if edge == RangeEdge::In {
- result.in_hot = response.hovered();
- }
- if edge == RangeEdge::Out {
- result.out_hot = response.hovered();
+ match edge {
+ RangeEdge::In => result.in_hot = response.hovered(),
+ RangeEdge::Out => result.out_hot = response.hovered(),
+ RangeEdge::Move => {}
}
if response.drag_started() {
let Some(pointer) = ctx.input(|i| i.pointer.press_origin()) else { continue };
@@ -158,11 +161,10 @@ pub fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, bar: Rect, which: Whi
}
}
}
- if edge == RangeEdge::In {
- result.in_hot = true;
- }
- if edge == RangeEdge::Out {
- result.out_hot = true;
+ match edge {
+ RangeEdge::In => result.in_hot = true,
+ RangeEdge::Out => result.out_hot = true,
+ RangeEdge::Move => {}
}
if response.drag_stopped() {
clear(&ctx, which);
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 197491794..206086e91 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -276,7 +276,6 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
return;
};
let rate = seq.settings.frame_rate;
- let dt = ctx.input(|i| i.stable_dt).min(0.05) as f64;
let header_w = app.ui.timeline.header_w;
let content = Rect::from_min_max(pos2(rect.min.x + header_w, rect.min.y + TOP_H), pos2(rect.max.x - SCROLLBAR_H, rect.max.y - SCROLLBAR_H));
let ruler = Rect::from_min_max(pos2(content.min.x, rect.min.y + TOP_H - RULER_H), pos2(content.max.x, rect.min.y + TOP_H));
@@ -286,6 +285,188 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
// ---- sequence tabs strip (top-left header block)
// ---- animated zoom / scroll
+ animate_view(app, &ctx, content, seq_id, seq);
+ let pps = app.ui.timeline.pps;
+ let scroll = app.ui.timeline.scroll;
+
+ // ---- rows
+ // caption tracks sit in their own area above the video tracks
+ let cap_n = seq.caption_tracks.len();
+ let caption_area = Rect::from_min_max(pos2(rect.min.x, content.min.y), pos2(content.max.x, content.min.y + cap_n as f32 * super::timeline_captions::ROW_H));
+ let cap_h = if cap_n > 0 { caption_area.height() + DIVIDER_H } else { 0.0 };
+ let tracks_area = Rect::from_min_max(pos2(content.min.x, content.min.y + cap_h), content.max);
+ let split_y = tracks_area.min.y + (tracks_area.height() - DIVIDER_H) * app.ui.timeline.split;
+ let video_area = Rect::from_min_max(pos2(rect.min.x, tracks_area.min.y), pos2(content.max.x, split_y));
+ let audio_area = Rect::from_min_max(pos2(rect.min.x, split_y + DIVIDER_H), pos2(content.max.x, tracks_area.max.y - MASTER_H));
+ let vh = app.ui.timeline.video_track_h;
+ let ah = app.ui.timeline.audio_track_h;
+ let mut rows = Vec::new();
+ let nv = seq.video_tracks.len();
+ let (video_tops, max_vs) = video_row_tops(video_area, nv, vh, &mut app.ui.timeline.v_scroll);
+ for ((i, tr), top) in seq.video_tracks.iter().enumerate().zip(video_tops) {
+ let rect = Rect::from_min_max(pos2(content.min.x, top), pos2(content.max.x, top + vh));
+ rows.push(Row { track: tr.id, kind: TrackKind::Video, index: i, rect, lane: false });
+ }
+ let na = seq.audio_tracks.len();
+ let max_as = (na as f32 * ah - audio_area.height()).max(0.0);
+ app.ui.timeline.a_scroll = app.ui.timeline.a_scroll.clamp(0.0, max_as);
+ for (i, tr) in seq.audio_tracks.iter().enumerate() {
+ let top = audio_area.min.y + i as f32 * ah - app.ui.timeline.a_scroll;
+ let rect = Rect::from_min_max(pos2(content.min.x, top), pos2(content.max.x, top + ah));
+ rows.push(Row { track: tr.id, kind: TrackKind::Audio, index: i, rect, lane: app.ui.timeline.track_lanes.contains_key(&tr.id.0) });
+ }
+ let layout = Layout { content, ruler, rows: rows.clone(), pps, scroll, split_y };
+ app.tl.layout = Some(layout.clone());
+
+ // ---- backgrounds
+ painter.rect_filled(Rect::from_min_max(pos2(content.min.x, content.min.y), content.max), 0.0, t.tl_bg);
+ let vclip = Rect::from_min_max(pos2(rect.min.x, video_area.min.y), video_area.max);
+ let aclip = Rect::from_min_max(pos2(rect.min.x, audio_area.min.y), audio_area.max);
+ for r in &rows {
+ let clip = if r.kind == TrackKind::Video { vclip } else { aclip };
+ let row = r.rect.intersect(clip);
+ if row.height() <= 0.0 {
+ continue;
+ }
+ 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 {
+ painter.line_segment([pos2(row.min.x, r.rect.min.y + 0.5), pos2(row.max.x, r.rect.min.y + 0.5)], Stroke::new(1.0, t.separator));
+ }
+ }
+ // in/out shading across tracks
+ if seq.mark_in.is_some() || seq.mark_out.is_some() {
+ let a = layout.x_of(seq.mark_in.unwrap_or(Tick::ZERO)).max(content.min.x);
+ let b = layout.x_of(seq.mark_out.map(|o| o + rate.frame_duration()).unwrap_or(seq.duration())).min(content.max.x);
+ if b > a {
+ painter.rect_filled(Rect::from_min_max(pos2(a, content.min.y), pos2(b, content.max.y)), 0.0, t.in_out_shade);
+ }
+ }
+
+ // ---- clips
+ draw_clips(app, &ctx, &painter, seq, seq_id, &rows, &layout, content, vclip, aclip, rate, t);
+
+ // An existing clip dragged past the outer row previews its new destination (#1187).
+ if let Some(Drag::Move { clips, offset, new_track: Some((kind, band)), .. }) = app.tl.drag.clone() {
+ let preview = painter.with_clip_rect(band.intersect(content));
+ for clip in clips {
+ if let Some((track, it)) = seq.find_item(clip)
+ && seq.track(track).is_some_and(|t| t.kind == kind)
+ {
+ let start = (it.start + offset).max(Tick::ZERO);
+ let body = Rect::from_min_max(pos2(layout.x_of(start), band.min.y + 1.0), pos2(layout.x_of(start + it.duration), band.max.y - 1.0));
+ preview.rect_filled(body, 3.0, t.accent.gamma_multiply(0.4));
+ preview.rect_stroke(body, 3.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
+ if body.height() >= 20.0 {
+ preview.text(body.left_top() + vec2(4.0, 2.0), Align2::LEFT_TOP, &it.name, Tokens::ui(11.0), t.text);
+ }
+ app.auto.add(&format!("timeline.newTrackPreview.{}", clip.0), body.intersect(band), &it.name);
+ }
+ }
+ }
+
+ // ---- track headers
+ draw_headers(app, ui, seq, &rows, rect, vclip, aclip, &t);
+ // divider between video and audio
+ let div = Rect::from_min_max(pos2(rect.min.x, split_y), pos2(content.max.x, split_y + DIVIDER_H));
+ painter.rect_filled(div, 0.0, t.app_bg);
+ let div_resp = ui.interact(div, egui::Id::unique("tl-divider"), Sense::drag());
+ if div_resp.hovered() || div_resp.dragged() {
+ ctx.set_cursor_icon(CursorIcon::ResizeVertical);
+ }
+ if div_resp.dragged() {
+ let f = app.ui.timeline.split + div_resp.drag_delta().y / (tracks_area.height() - DIVIDER_H).max(1.0);
+ app.ui.timeline.split = f.clamp(0.1, 0.9);
+ }
+ // master track
+ let master = Rect::from_min_max(pos2(rect.min.x, tracks_area.max.y - MASTER_H), pos2(content.max.x, tracks_area.max.y));
+ painter.rect_filled(master, 0.0, t.tl_header_bg);
+ painter.text(pos2(rect.min.x + 44.0, master.center().y), Align2::LEFT_CENTER, tl!("Mix"), Tokens::ui(11.5), t.text);
+ painter.text(
+ pos2(rect.min.x + header_w - 12.0, master.center().y),
+ Align2::RIGHT_CENTER,
+ format!("{:.1}", seq.master_volume_db),
+ Tokens::ui(11.5),
+ t.hot_text,
+ );
+
+ // ---- caption tracks
+ if cap_n > 0 {
+ painter.rect_filled(Rect::from_min_max(pos2(rect.min.x, caption_area.max.y), pos2(content.max.x, caption_area.max.y + DIVIDER_H)), 0.0, t.app_bg);
+ super::timeline_captions::paint(app, ui, seq, caption_area, &layout, &t);
+ }
+
+ // ---- top block: timecode + toggles, ruler
+ draw_top(app, ui, rect, seq, &layout, &t, seq_id);
+
+ // ---- playhead
+ let ph = app.session.playhead();
+ let px = layout.x_of(ph);
+ if px >= content.min.x - 1.0 && px <= content.max.x + 1.0 {
+ // a short head on the tick row, as in Effect Controls, so it leaves the markers and timecodes clear
+ let (top, tip) = (ruler.max.y - 13.0, ruler.max.y);
+ let head = [pos2(px - 5.0, top), pos2(px + 5.0, top), pos2(px + 5.0, tip - 5.0), pos2(px, tip), pos2(px - 5.0, tip - 5.0)];
+ painter.add(egui::Shape::convex_polygon(head.to_vec(), t.playhead, Stroke::NONE));
+ painter.line_segment([pos2(px, tip), pos2(px, content.max.y)], Stroke::new(1.0, t.playhead));
+ }
+ // snap indicator
+ if let Some(sx) = app.tl.snap_x.take() {
+ painter.line_segment([pos2(sx, ruler.max.y), pos2(sx, content.max.y)], Stroke::new(1.0, Color32::from_rgb(250, 250, 250)));
+ for y in [ruler.max.y, content.max.y] {
+ let d = if y == ruler.max.y { 1.0 } else { -1.0 };
+ painter.add(egui::Shape::convex_polygon(vec![pos2(sx - 4.0, y), pos2(sx + 4.0, y), pos2(sx, y + 5.0 * d)], Color32::WHITE, Stroke::NONE));
+ }
+ }
+
+ // ---- scroll bars
+ zoom_scrollbar(
+ app,
+ ui,
+ Rect::from_min_max(pos2(content.min.x, rect.max.y - SCROLLBAR_H + 2.0), pos2(content.max.x, rect.max.y - 2.0)),
+ seq.duration().seconds(),
+ &t,
+ );
+ vertical_scrollbar(
+ ui,
+ Rect::from_min_max(pos2(content.max.x, video_area.min.y), pos2(rect.max.x, video_area.max.y)),
+ &mut app.ui.timeline.v_scroll,
+ max_vs,
+ true,
+ &t,
+ "vs",
+ );
+ vertical_scrollbar(
+ ui,
+ Rect::from_min_max(pos2(content.max.x, audio_area.min.y), pos2(rect.max.x, audio_area.max.y)),
+ &mut app.ui.timeline.a_scroll,
+ max_as,
+ false,
+ &t,
+ "as",
+ );
+
+ // ---- interaction
+ interact(app, ui, seq, &layout, rect);
+ super::timeline_volume::interact(app, ui, seq, &layout, aclip);
+ // track keyframes (drawn and edited on top of the clips)
+ super::timeline_automation::show(app, ui, seq, &layout, aclip);
+ if cap_n > 0 {
+ super::timeline_captions::interact(app, ui, seq, caption_area, &layout);
+ }
+ let _ = TICKS_PER_SECOND;
+}
+
+/// The timeline view's animated state: eases zoom and scroll toward their targets (or jumps
+/// with animations off, #2325), follows the playhead while playing, brings it into view after a
+/// jump while stopped, and keeps the view inside the sequence's extent.
+fn animate_view(app: &mut FilmcraftApp, ctx: &egui::Context, content: Rect, seq_id: ItemId, seq: &Sequence) {
+ let dt = ctx.input(|i| i.stable_dt).min(0.05) as f64;
let empty = seq.duration().seconds() <= 0.0;
let dur_s = seq.duration().seconds().max(1.0);
{
@@ -374,69 +555,26 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
v.scroll = v.scroll.clamp(0.0, max_scroll(seconds, content.width(), v.pps));
v.target_scroll = v.target_scroll.clamp(0.0, max_scroll(seconds, content.width(), v.target_pps));
}
- let pps = app.ui.timeline.pps;
- let scroll = app.ui.timeline.scroll;
-
- // ---- rows
- // caption tracks sit in their own area above the video tracks
- let cap_n = seq.caption_tracks.len();
- let caption_area = Rect::from_min_max(pos2(rect.min.x, content.min.y), pos2(content.max.x, content.min.y + cap_n as f32 * super::timeline_captions::ROW_H));
- let cap_h = if cap_n > 0 { caption_area.height() + DIVIDER_H } else { 0.0 };
- let tracks_area = Rect::from_min_max(pos2(content.min.x, content.min.y + cap_h), content.max);
- let split_y = tracks_area.min.y + (tracks_area.height() - DIVIDER_H) * app.ui.timeline.split;
- let video_area = Rect::from_min_max(pos2(rect.min.x, tracks_area.min.y), pos2(content.max.x, split_y));
- let audio_area = Rect::from_min_max(pos2(rect.min.x, split_y + DIVIDER_H), pos2(content.max.x, tracks_area.max.y - MASTER_H));
- let vh = app.ui.timeline.video_track_h;
- let ah = app.ui.timeline.audio_track_h;
- let mut rows = Vec::new();
- let nv = seq.video_tracks.len();
- let (video_tops, max_vs) = video_row_tops(video_area, nv, vh, &mut app.ui.timeline.v_scroll);
- for ((i, tr), top) in seq.video_tracks.iter().enumerate().zip(video_tops) {
- let rect = Rect::from_min_max(pos2(content.min.x, top), pos2(content.max.x, top + vh));
- rows.push(Row { track: tr.id, kind: TrackKind::Video, index: i, rect, lane: false });
- }
- let na = seq.audio_tracks.len();
- let max_as = (na as f32 * ah - audio_area.height()).max(0.0);
- app.ui.timeline.a_scroll = app.ui.timeline.a_scroll.clamp(0.0, max_as);
- for (i, tr) in seq.audio_tracks.iter().enumerate() {
- let top = audio_area.min.y + i as f32 * ah - app.ui.timeline.a_scroll;
- let rect = Rect::from_min_max(pos2(content.min.x, top), pos2(content.max.x, top + ah));
- rows.push(Row { track: tr.id, kind: TrackKind::Audio, index: i, rect, lane: app.ui.timeline.track_lanes.contains_key(&tr.id.0) });
- }
- let layout = Layout { content, ruler, rows: rows.clone(), pps, scroll, split_y };
- app.tl.layout = Some(layout.clone());
-
- // ---- backgrounds
- painter.rect_filled(Rect::from_min_max(pos2(content.min.x, content.min.y), content.max), 0.0, t.tl_bg);
- let vclip = Rect::from_min_max(pos2(rect.min.x, video_area.min.y), video_area.max);
- let aclip = Rect::from_min_max(pos2(rect.min.x, audio_area.min.y), audio_area.max);
- for r in &rows {
- let clip = if r.kind == TrackKind::Video { vclip } else { aclip };
- let row = r.rect.intersect(clip);
- if row.height() <= 0.0 {
- continue;
- }
- 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 {
- painter.line_segment([pos2(row.min.x, r.rect.min.y + 0.5), pos2(row.max.x, r.rect.min.y + 0.5)], Stroke::new(1.0, t.separator));
- }
- }
- // in/out shading across tracks
- if seq.mark_in.is_some() || seq.mark_out.is_some() {
- let a = layout.x_of(seq.mark_in.unwrap_or(Tick::ZERO)).max(content.min.x);
- let b = layout.x_of(seq.mark_out.map(|o| o + rate.frame_duration()).unwrap_or(seq.duration())).min(content.max.x);
- if b > a {
- painter.rect_filled(Rect::from_min_max(pos2(a, content.min.y), pos2(b, content.max.y)), 0.0, t.in_out_shade);
- }
- }
+}
+/// The clips in the visible rows: each track's items (with their drag previews, copies,
+/// waveforms and thumbnails), duplicate-frame stripes, empty nested-sequence overhangs,
+/// through edits, transitions and the locked-track hatch.
+#[allow(clippy::too_many_arguments)]
+fn draw_clips(
+ app: &mut FilmcraftApp,
+ ctx: &egui::Context,
+ painter: &egui::Painter,
+ seq: &Sequence,
+ seq_id: ItemId,
+ rows: &[Row],
+ layout: &Layout,
+ content: Rect,
+ vclip: Rect,
+ aclip: Rect,
+ rate: filmcraft_time::FrameRate,
+ t: Tokens,
+) {
// ---- clips
let visible = (layout.tick_at(content.min.x - 2.0), layout.tick_at(content.max.x + 2.0));
let selection: Vec<ClipId> = app.session.state.selection.clone();
@@ -451,8 +589,8 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
if copying {
ctx.set_cursor_icon(CursorIcon::Copy);
}
- let duplicates = if app.session.state.show_duplicate_frame_markers { duplicate_markers(app, &ctx, seq_id, seq) } else { Arc::default() };
- for r in &rows {
+ let duplicates = if app.session.state.show_duplicate_frame_markers { duplicate_markers(app, ctx, seq_id, seq) } else { Arc::default() };
+ for r in rows {
let Some(tr) = seq.track(r.track) else { continue };
let clip_rect = if r.kind == TrackKind::Video { vclip } else { aclip };
let row = r.rect.intersect(clip_rect);
@@ -483,7 +621,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let x0 = layout.x_of(start);
let x1 = layout.x_of(start + dur);
let body = Rect::from_min_max(pos2(x0, r.rect.min.y + 1.0), pos2(x1.max(x0 + 1.0), r.rect.max.y - 1.0));
- draw_clip(app, &ctx, &p, body, it, r.kind, selection.contains(&it.id), &t, rate);
+ draw_clip(app, ctx, &p, body, it, r.kind, selection.contains(&it.id), &t, rate);
if volume_line {
super::timeline_volume::paint(&p, body, it);
}
@@ -493,7 +631,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let col = DUPLICATE_FRAME_COLORS.get(d.color).or(DUPLICATE_FRAME_COLORS.last()).copied().unwrap_or(Color32::WHITE);
// kept inside the clip while a trim drag shortens it
let inside = p.with_clip_rect(body.intersect(p.clip_rect()));
- paint_duplicate_stripes(app, &inside, &layout, &d.ranges, start - it.start, (body.max.y - 3.0, body.max.y), visible, col, it.id);
+ paint_duplicate_stripes(app, &inside, layout, &d.ranges, start - it.start, (body.max.y - 3.0, body.max.y), visible, col, it.id);
}
app.auto.add(&format!("timeline.clip.{}", it.id.0), body.intersect(content), &it.name);
// a nest that runs past the end of its sequence's contents: that part is empty
@@ -515,7 +653,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
&& let Some((_, it)) = seq.find_item(*cid)
{
let body = Rect::from_min_max(pos2(layout.x_of(*start), r.rect.min.y + 1.0), pos2(layout.x_of(*start + *dur), r.rect.max.y - 1.0));
- draw_clip(app, &ctx, &p, body, it, r.kind, true, &t, rate);
+ draw_clip(app, ctx, &p, body, it, r.kind, true, &t, rate);
if volume_line {
super::timeline_volume::paint(&p, body, it);
}
@@ -526,10 +664,37 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
&& mt.unwrap_or(home) == r.track
{
let body = Rect::from_min_max(pos2(layout.x_of(*start), r.rect.min.y + 1.0), pos2(layout.x_of(*start + *dur), r.rect.max.y - 1.0));
- draw_clip(app, &ctx, &p, body, it, r.kind, true, &t, rate);
+ draw_clip(app, ctx, &p, body, it, r.kind, true, &t, rate);
app.auto.add(&format!("timeline.clip.{}.copy", cid.0), body.intersect(content), &it.name);
}
}
+ paint_track_edits(app, painter, seq, rows, layout, content, vclip, aclip, t, copying);
+ }
+}
+
+/// Per-track details over the clips: through-edit bow-ties, the selected edit points, the
+/// transitions (including the ones a drag carries) and the locked-track hatch.
+#[allow(clippy::too_many_arguments)]
+fn paint_track_edits(
+ app: &mut FilmcraftApp,
+ painter: &egui::Painter,
+ seq: &Sequence,
+ rows: &[Row],
+ layout: &Layout,
+ content: Rect,
+ vclip: Rect,
+ aclip: Rect,
+ t: Tokens,
+ copying: bool,
+) {
+ for r in rows {
+ let Some(tr) = seq.track(r.track) else { continue };
+ let clip = if r.kind == TrackKind::Video { vclip } else { aclip };
+ let row = r.rect.intersect(clip);
+ if row.height() <= 0.0 {
+ continue;
+ }
+ let p = painter.with_clip_rect(Rect::from_min_max(pos2(content.min.x, row.min.y), pos2(content.max.x, row.max.y)));
// Show Through Edits: a small bow-tie on cuts between continuous pieces of one clip
if app.session.state.show_through_edits {
for te in filmcraft_edit::through::track_through_edits(tr) {
@@ -542,7 +707,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
// selected edit points (trim mode): red brackets for ripple, yellow for roll / regular trim
- super::trim_monitor::paint_edit_points(app, &p, seq, tr, r, &layout);
+ super::trim_monitor::paint_edit_points(app, &p, seq, tr, r, layout);
// transitions (one being dragged where the drag puts it; the selected ones outlined). A
// clip drag also shows where the drop will carry its transitions (those whose clips all
// move to one track by one offset): a plain move draws them on their destination track
@@ -586,115 +751,6 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
-
- // An existing clip dragged past the outer row previews its new destination (#1187).
- if let Some(Drag::Move { clips, offset, new_track: Some((kind, band)), .. }) = app.tl.drag.clone() {
- let preview = painter.with_clip_rect(band.intersect(content));
- for clip in clips {
- if let Some((track, it)) = seq.find_item(clip)
- && seq.track(track).is_some_and(|t| t.kind == kind)
- {
- let start = (it.start + offset).max(Tick::ZERO);
- let body = Rect::from_min_max(pos2(layout.x_of(start), band.min.y + 1.0), pos2(layout.x_of(start + it.duration), band.max.y - 1.0));
- preview.rect_filled(body, 3.0, t.accent.gamma_multiply(0.4));
- preview.rect_stroke(body, 3.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
- if body.height() >= 20.0 {
- preview.text(body.left_top() + vec2(4.0, 2.0), Align2::LEFT_TOP, &it.name, Tokens::ui(11.0), t.text);
- }
- app.auto.add(&format!("timeline.newTrackPreview.{}", clip.0), body.intersect(band), &it.name);
- }
- }
- }
-
- // ---- track headers
- draw_headers(app, ui, seq, &rows, rect, vclip, aclip, &t);
- // divider between video and audio
- let div = Rect::from_min_max(pos2(rect.min.x, split_y), pos2(content.max.x, split_y + DIVIDER_H));
- painter.rect_filled(div, 0.0, t.app_bg);
- let div_resp = ui.interact(div, egui::Id::unique("tl-divider"), Sense::drag());
- if div_resp.hovered() || div_resp.dragged() {
- ctx.set_cursor_icon(CursorIcon::ResizeVertical);
- }
- if div_resp.dragged() {
- let f = app.ui.timeline.split + div_resp.drag_delta().y / (tracks_area.height() - DIVIDER_H).max(1.0);
- app.ui.timeline.split = f.clamp(0.1, 0.9);
- }
- // master track
- let master = Rect::from_min_max(pos2(rect.min.x, tracks_area.max.y - MASTER_H), pos2(content.max.x, tracks_area.max.y));
- painter.rect_filled(master, 0.0, t.tl_header_bg);
- painter.text(pos2(rect.min.x + 44.0, master.center().y), Align2::LEFT_CENTER, tl!("Mix"), Tokens::ui(11.5), t.text);
- painter.text(
- pos2(rect.min.x + header_w - 12.0, master.center().y),
- Align2::RIGHT_CENTER,
- format!("{:.1}", seq.master_volume_db),
- Tokens::ui(11.5),
- t.hot_text,
- );
-
- // ---- caption tracks
- if cap_n > 0 {
- painter.rect_filled(Rect::from_min_max(pos2(rect.min.x, caption_area.max.y), pos2(content.max.x, caption_area.max.y + DIVIDER_H)), 0.0, t.app_bg);
- super::timeline_captions::paint(app, ui, seq, caption_area, &layout, &t);
- }
-
- // ---- top block: timecode + toggles, ruler
- draw_top(app, ui, rect, seq, &layout, &t, seq_id);
-
- // ---- playhead
- let ph = app.session.playhead();
- let px = layout.x_of(ph);
- if px >= content.min.x - 1.0 && px <= content.max.x + 1.0 {
- // a short head on the tick row, as in Effect Controls, so it leaves the markers and timecodes clear
- let (top, tip) = (ruler.max.y - 13.0, ruler.max.y);
- let head = [pos2(px - 5.0, top), pos2(px + 5.0, top), pos2(px + 5.0, tip - 5.0), pos2(px, tip), pos2(px - 5.0, tip - 5.0)];
- painter.add(egui::Shape::convex_polygon(head.to_vec(), t.playhead, Stroke::NONE));
- painter.line_segment([pos2(px, tip), pos2(px, content.max.y)], Stroke::new(1.0, t.playhead));
- }
- // snap indicator
- if let Some(sx) = app.tl.snap_x.take() {
- painter.line_segment([pos2(sx, ruler.max.y), pos2(sx, content.max.y)], Stroke::new(1.0, Color32::from_rgb(250, 250, 250)));
- for y in [ruler.max.y, content.max.y] {
- let d = if y == ruler.max.y { 1.0 } else { -1.0 };
- painter.add(egui::Shape::convex_polygon(vec![pos2(sx - 4.0, y), pos2(sx + 4.0, y), pos2(sx, y + 5.0 * d)], Color32::WHITE, Stroke::NONE));
- }
- }
-
- // ---- scroll bars
- zoom_scrollbar(
- app,
- ui,
- Rect::from_min_max(pos2(content.min.x, rect.max.y - SCROLLBAR_H + 2.0), pos2(content.max.x, rect.max.y - 2.0)),
- seq.duration().seconds(),
- &t,
- );
- vertical_scrollbar(
- ui,
- Rect::from_min_max(pos2(content.max.x, video_area.min.y), pos2(rect.max.x, video_area.max.y)),
- &mut app.ui.timeline.v_scroll,
- max_vs,
- true,
- &t,
- "vs",
- );
- vertical_scrollbar(
- ui,
- Rect::from_min_max(pos2(content.max.x, audio_area.min.y), pos2(rect.max.x, audio_area.max.y)),
- &mut app.ui.timeline.a_scroll,
- max_as,
- false,
- &t,
- "as",
- );
-
- // ---- interaction
- interact(app, ui, seq, &layout, rect);
- super::timeline_volume::interact(app, ui, seq, &layout, aclip);
- // track keyframes (drawn and edited on top of the clips)
- super::timeline_automation::show(app, ui, seq, &layout, aclip);
- if cap_n > 0 {
- super::timeline_captions::interact(app, ui, seq, caption_area, &layout);
- }
- let _ = (visible, TICKS_PER_SECOND);
}
/// Shown when no sequence is open: offers the demo project and accepts project or OS-file drops to create a sequence.
diff --git a/crates/ui-egui/src/panels/timeline/headers.rs b/crates/ui-egui/src/panels/timeline/headers.rs
index 86d25e82a..ce573efe2 100644
--- a/crates/ui-egui/src/panels/timeline/headers.rs
+++ b/crates/ui-egui/src/panels/timeline/headers.rs
@@ -108,7 +108,6 @@ pub(super) fn draw_headers(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequ
}
// 2. track lock
let small = |x: f32, y: f32| Rect::from_center_size(pos2(hrect.min.x + x, y), vec2(18.0, 18.0));
- let upper_y = hrect.min.y + (16.0f32).min(hrect.height() / 2.0);
let lock_r = small(49.0, hrect.center().y);
let lresp = crate::widgets::icon_toggle(
ui,
@@ -148,73 +147,7 @@ pub(super) fn draw_headers(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequ
actions.push(("timeline.setTargeting".into(), json!({"track": r.track.0, "targeted": !targeted})));
}
// 4. upper line icons
- let mut x = 102.0;
- let sr = small(x, upper_y);
- let sresp = crate::widgets::icon_toggle(
- ui,
- sr.intersect(visible),
- Icon::SyncLock,
- tr.sync_lock,
- t,
- egui::Id::unique(("syncLock", r.track.0)),
- Some(t.text_dim),
- );
- app.auto.add(&format!("timeline.track.{label}.syncLock"), sr, "Toggle Sync Lock");
- if sresp.clicked() {
- actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "syncLock": !tr.sync_lock})));
- }
- x += 24.0;
- if r.kind == TrackKind::Video {
- let er = small(x, upper_y);
- let eresp = crate::widgets::icon_toggle(
- ui,
- er.intersect(visible),
- if tr.enabled { Icon::Eye } else { Icon::EyeOff },
- true,
- t,
- egui::Id::unique(("enabled", r.track.0)),
- Some(t.text_dim),
- );
- app.auto.add(&format!("timeline.track.{label}.enabled"), er, "Toggle Track Output");
- if eresp.clicked() {
- actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "enabled": !tr.enabled})));
- }
- } else {
- let mr = Rect::from_center_size(pos2(hrect.min.x + x, upper_y), vec2(14.0, 14.0));
- let mresp = crate::widgets::letter_toggle(
- ui,
- mr.intersect(visible),
- "M",
- tr.muted,
- Color32::from_rgb(0x2d, 0x9d, 0x78),
- t,
- egui::Id::unique(("mute", r.track.0)),
- );
- app.auto.add(&format!("timeline.track.{label}.muted"), mr, "Mute Track");
- if mresp.clicked() {
- actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "muted": !tr.muted})));
- }
- let s2 = Rect::from_center_size(pos2(hrect.min.x + x + 20.0, upper_y), vec2(14.0, 14.0));
- let so = crate::widgets::letter_toggle(
- ui,
- s2.intersect(visible),
- "S",
- tr.solo,
- Color32::from_rgb(0xf0, 0xf0, 0x4f),
- t,
- egui::Id::unique(("solo", r.track.0)),
- );
- app.auto.add(&format!("timeline.track.{label}.solo"), s2, "Solo Track");
- if so.clicked() {
- actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "solo": !tr.solo})));
- }
- let vr = small(x + 42.0, upper_y);
- if let Some(a) = crate::panels::voiceover::header_button(app, ui, r.track, vr, visible, &label, t) {
- vo_action = Some(a);
- }
- let kr = small(x + 64.0, upper_y);
- crate::panels::timeline_automation::header_button(app, ui, seq, r, kr, visible, &label, t);
- }
+ header_line_buttons(app, ui, seq, r, tr, visible, hrect, &label, t, &mut actions, &mut vo_action);
// 5. name on the lower line (or inline when short)
if hrect.height() >= 40.0 {
p.text(pos2(hrect.min.x + 94.0, hrect.min.y + 34.0), Align2::LEFT_CENTER, &tr.name, Tokens::ui(11.0), t.text_dim);
@@ -262,3 +195,83 @@ pub(super) fn draw_headers(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequ
crate::panels::voiceover::run(app, &ui.ctx().clone(), a);
}
}
+
+/// A track header's upper line: sync-lock, then output enable for a video track, or mute,
+/// solo, voiceover and automation for an audio track.
+#[allow(clippy::too_many_arguments)]
+fn header_line_buttons(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ seq: &Sequence,
+ r: &Row,
+ tr: &filmcraft_project::Track,
+ visible: Rect,
+ hrect: Rect,
+ label: &str,
+ t: &Tokens,
+ actions: &mut Vec<(String, Value)>,
+ vo_action: &mut Option<crate::panels::voiceover::Action>,
+) {
+ let upper_y = hrect.min.y + (16.0f32).min(hrect.height() / 2.0);
+ let small = |x: f32, y: f32| Rect::from_center_size(pos2(hrect.min.x + x, y), vec2(18.0, 18.0));
+ let mut x = 102.0;
+ let sr = small(x, upper_y);
+ let sresp =
+ crate::widgets::icon_toggle(ui, sr.intersect(visible), Icon::SyncLock, tr.sync_lock, t, egui::Id::unique(("syncLock", r.track.0)), Some(t.text_dim));
+ app.auto.add(&format!("timeline.track.{label}.syncLock"), sr, "Toggle Sync Lock");
+ if sresp.clicked() {
+ actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "syncLock": !tr.sync_lock})));
+ }
+ x += 24.0;
+ if r.kind == TrackKind::Video {
+ let er = small(x, upper_y);
+ let eresp = crate::widgets::icon_toggle(
+ ui,
+ er.intersect(visible),
+ if tr.enabled { Icon::Eye } else { Icon::EyeOff },
+ true,
+ t,
+ egui::Id::unique(("enabled", r.track.0)),
+ Some(t.text_dim),
+ );
+ app.auto.add(&format!("timeline.track.{label}.enabled"), er, "Toggle Track Output");
+ if eresp.clicked() {
+ actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "enabled": !tr.enabled})));
+ }
+ } else {
+ let mr = Rect::from_center_size(pos2(hrect.min.x + x, upper_y), vec2(14.0, 14.0));
+ let mresp = crate::widgets::letter_toggle(
+ ui,
+ mr.intersect(visible),
+ "M",
+ tr.muted,
+ Color32::from_rgb(0x2d, 0x9d, 0x78),
+ t,
+ egui::Id::unique(("mute", r.track.0)),
+ );
+ app.auto.add(&format!("timeline.track.{label}.muted"), mr, "Mute Track");
+ if mresp.clicked() {
+ actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "muted": !tr.muted})));
+ }
+ let s2 = Rect::from_center_size(pos2(hrect.min.x + x + 20.0, upper_y), vec2(14.0, 14.0));
+ let so = crate::widgets::letter_toggle(
+ ui,
+ s2.intersect(visible),
+ "S",
+ tr.solo,
+ Color32::from_rgb(0xf0, 0xf0, 0x4f),
+ t,
+ egui::Id::unique(("solo", r.track.0)),
+ );
+ app.auto.add(&format!("timeline.track.{label}.solo"), s2, "Solo Track");
+ if so.clicked() {
+ actions.push(("timeline.setTrack".into(), json!({"track": r.track.0, "solo": !tr.solo})));
+ }
+ let vr = small(x + 42.0, upper_y);
+ if let Some(a) = crate::panels::voiceover::header_button(app, ui, r.track, vr, visible, label, t) {
+ *vo_action = Some(a);
+ }
+ let kr = small(x + 64.0, upper_y);
+ crate::panels::timeline_automation::header_button(app, ui, seq, r, kr, visible, label, t);
+ }
+}
diff --git a/crates/ui-egui/src/panels/timeline/interact.rs b/crates/ui-egui/src/panels/timeline/interact.rs
index 559126dbe..8f2f27aa5 100644
--- a/crates/ui-egui/src/panels/timeline/interact.rs
+++ b/crates/ui-egui/src/panels/timeline/interact.rs
@@ -209,36 +209,11 @@ fn scrub_playhead(app: &mut FilmcraftApp, seq: &Sequence, layout: &Layout, p: Po
app.session.set_playhead(tt);
}
-/// Handle Timeline pointer input: remember the grab from the press frame, jump the playhead on a ruler press, select a marker on its press, and reset the
-/// cancel flag once the button is released.
-pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &Layout, rect: Rect) {
+/// Wheel input over the Timeline, as in Premiere Pro on macOS (checked in 26.5.2): the wheel
+/// moves the tracks under the pointer, Cmd + wheel the Timeline sideways, Option + wheel
+/// zooms about the pointer.
+fn wheel_scroll(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, layout: &Layout, seq: &Sequence) {
let ctx = ui.ctx().clone();
- let area = Rect::from_min_max(pos2(layout.content.min.x, layout.ruler.min.y), layout.content.max);
- let resp = ui.interact(area, egui::Id::unique("timeline-area"), Sense::click_and_drag());
- let pos = resp.hover_pos().or(resp.interact_pointer_pos());
- let mods = ctx.input(|i| i.modifiers);
- let tool = app.ui.tool;
- let rate = seq.settings.frame_rate;
- let roll_ripple = app.session.prefs.trim.selection_tool_roll_ripple;
-
- // ---- what the button went down on (#259): kept from the press frame until it comes up
- if ctx.input(|i| !i.pointer.any_down() && !i.pointer.any_released()) {
- app.tl.pressed = None;
- app.tl.cancelled = false;
- }
- if resp.is_pointer_button_down_on()
- && ctx.input(|i| i.pointer.primary_pressed())
- && let Some(p) = ctx.input(|i| i.pointer.press_origin())
- {
- app.tl.cancelled = false;
- let grab = grab_at(seq, layout, p, tool, mods, roll_ripple);
- // the playhead jumps to a press on the ruler at once, not only once the pointer has moved (#1090)
- if matches!(grab, Grab::Other(Hit::Ruler)) {
- scrub_playhead(app, seq, layout, p, mods.shift);
- }
- app.tl.pressed = Some(Pressed { pos: p, tick: layout.tick_at(p.x), grab });
- }
-
// ---- wheel, as in Premiere Pro on macOS (checked in 26.5.2):
// wheel the tracks under the pointer, up and down
// Cmd + wheel the Timeline, sideways
@@ -278,7 +253,17 @@ pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence
}
}
}
+}
+/// Cursor feedback: what a press here would grab (#259) — the cursor for it, the trim
+/// bracket on an edge, and the razor's preview line.
+fn hover_cursor(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &Layout, pos: Option<Pos2>) {
+ let ctx = ui.ctx().clone();
+ let area = Rect::from_min_max(pos2(layout.content.min.x, layout.ruler.min.y), layout.content.max);
+ let mods = ctx.input(|i| i.modifiers);
+ let tool = app.ui.tool;
+ let rate = seq.settings.frame_rate;
+ let roll_ripple = app.session.prefs.trim.selection_tool_roll_ripple;
// ---- cursor feedback: what a press here would grab (#259)
if app.tl.drag.is_none()
&& let Some(p) = pos
@@ -332,14 +317,22 @@ pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence
ui.painter().line_segment([pos2(x, row.rect.min.y), pos2(x, row.rect.max.y)], Stroke::new(1.0, Color32::WHITE));
}
}
+}
+/// The press frame: remember what was under the pointer, jump the playhead on a ruler press,
+/// select a marker, and start the drag the press implies. Returns whether `interact` should
+/// stop (a press with no pointer position: nothing more can be handled this frame).
+fn press_action(app: &mut FilmcraftApp, ctx: &egui::Context, resp: &egui::Response, seq: &Sequence, layout: &Layout) -> bool {
+ let tool = app.ui.tool;
+ let mods = ctx.input(|i| i.modifiers);
+ let roll_ripple = app.session.prefs.trim.selection_tool_roll_ripple;
// ---- press: act on what was under the pointer when the button went down (#259)
if !app.tl.cancelled && (resp.drag_started() || (resp.clicked() && app.tl.drag.is_none())) {
let pressed = match app.tl.pressed.take() {
Some(pr) => pr,
// a press and release in the same frame is never stored: it happened where egui says
None => {
- let Some(p) = resp.interact_pointer_pos() else { return };
+ let Some(p) = resp.interact_pointer_pos() else { return true };
Pressed { pos: p, tick: layout.tick_at(p.x), grab: grab_at(seq, layout, p, tool, mods, roll_ripple) }
}
};
@@ -350,174 +343,187 @@ pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence
Grab::Volume { .. } if resp.clicked() && !adding => Grab::Other(pressed.grab.hit()),
g => g,
};
- let started = match (tool, grab) {
- // a middle-button drag pans whatever the tool and whatever it starts on, as in the
- // monitors (#824) and DaVinci Resolve (#1490); only a primary press is kept in
- // `pressed`, so the pan starts from where the button went down
- _ if resp.drag_started_by(egui::PointerButton::Middle) => {
- let last = ctx.input(|i| i.pointer.press_origin()).unwrap_or(p);
- Some(Drag::Pan { last, start_scroll: app.ui.timeline.target_scroll, start_v: app.ui.timeline.v_scroll })
- }
- (_, Grab::Other(Hit::Ruler)) => Some(Drag::Scrub { initial: app.session.playhead() }),
- (_, Grab::Other(Hit::WorkArea { edge })) => {
- seq.work_area.filter(|_| resp.drag_started()).map(|w| Drag::WorkArea { edge, from: t, start: w.start, end: w.end() })
- }
- (Tool::Hand, _) => Some(Drag::Pan { last: p, start_scroll: app.ui.timeline.target_scroll, start_v: app.ui.timeline.v_scroll }),
- (Tool::Zoom, _) => {
- if resp.clicked() {
- let f = if mods.alt { 1.0 / 2.0 } else { 2.0 };
- app.ui.timeline.target_pps = (app.ui.timeline.target_pps * f).clamp(0.05, 24_000.0);
- app.tl.zoom_anchor = Some((t.seconds(), p.x));
- }
- None
- }
- (Tool::Razor, Grab::Other(Hit::Clip { clip, .. })) => {
- if resp.clicked() || resp.drag_started() {
- let tt = snap(app, seq, layout, rate.snap_nearest(t), &[]);
- let r = if mods.shift {
- app.session.execute("timeline.razor", json!({"time": tt.0}))
- } else {
- app.session.execute("timeline.razor", json!({"time": tt.0, "clip": clip.0}))
- };
- if let Err(e) = r {
- app.ui.status = e.to_string();
- }
- }
- None
+ start_drag(app, ctx, resp, seq, layout, grab, p, t);
+ }
+
+ false
+}
+
+/// What a press does: the drag it starts (or the tool's click action), the playhead jump a
+/// ruler press makes, and the selection a tool change makes first.
+#[allow(clippy::too_many_arguments)]
+fn start_drag(app: &mut FilmcraftApp, ctx: &egui::Context, resp: &egui::Response, seq: &Sequence, layout: &Layout, grab: Grab, p: Pos2, t: Tick) {
+ let tool = app.ui.tool;
+ let mods = ctx.input(|i| i.modifiers);
+ let rate = seq.settings.frame_rate;
+ let roll_ripple = app.session.prefs.trim.selection_tool_roll_ripple;
+ let started = match (tool, grab) {
+ // a middle-button drag pans whatever the tool and whatever it starts on, as in the
+ // monitors (#824) and DaVinci Resolve (#1490); only a primary press is kept in
+ // `pressed`, so the pan starts from where the button went down
+ _ if resp.drag_started_by(egui::PointerButton::Middle) => {
+ let last = ctx.input(|i| i.pointer.press_origin()).unwrap_or(p);
+ Some(Drag::Pan { last, start_scroll: app.ui.timeline.target_scroll, start_v: app.ui.timeline.v_scroll })
+ }
+ (_, Grab::Other(Hit::Ruler)) => Some(Drag::Scrub { initial: app.session.playhead() }),
+ (_, Grab::Other(Hit::WorkArea { edge })) => {
+ seq.work_area.filter(|_| resp.drag_started()).map(|w| Drag::WorkArea { edge, from: t, start: w.start, end: w.end() })
+ }
+ (Tool::Hand, _) => Some(Drag::Pan { last: p, start_scroll: app.ui.timeline.target_scroll, start_v: app.ui.timeline.v_scroll }),
+ (Tool::Zoom, _) => {
+ if resp.clicked() {
+ let f = if mods.alt { 1.0 / 2.0 } else { 2.0 };
+ app.ui.timeline.target_pps = (app.ui.timeline.target_pps * f).clamp(0.05, 24_000.0);
+ app.tl.zoom_anchor = Some((t.seconds(), p.x));
}
- // a transition over a cut counts as its track, as the clips under it do
- (
- Tool::TrackSelectForward | Tool::TrackSelectBackward,
- Grab::Other(Hit::Clip { track, .. } | Hit::Transition { track, .. } | Hit::Empty { track }),
- ) => {
- let fwd = tool == Tool::TrackSelectForward;
- let ids: Vec<u64> = seq
- .all_tracks()
- .filter(|tr| !mods.shift || tr.id == track)
- .flat_map(|tr| tr.items.iter())
- .filter(|i| if fwd { i.end() > t } else { i.start < t })
- .map(|i| i.id.0)
- .collect();
- let _ = app.session.execute("timeline.select", json!({"clips": ids}));
- // as in Premiere Pro, a drag with the tool moves what it just selected
- if resp.drag_started() {
- let clips = app.session.state.selection.clone();
- (!clips.is_empty()).then_some(Drag::Move {
- clips,
- grab_tick: t,
- start_track: track,
- offset: Tick::ZERO,
- track_delta: 0,
- new_track: None,
- copy: mods.alt,
- })
+ None
+ }
+ (Tool::Razor, Grab::Other(Hit::Clip { clip, .. })) => {
+ if resp.clicked() || resp.drag_started() {
+ let tt = snap(app, seq, layout, rate.snap_nearest(t), &[]);
+ let r = if mods.shift {
+ app.session.execute("timeline.razor", json!({"time": tt.0}))
} else {
- None
- }
- }
- (Tool::Selection | Tool::Ripple | Tool::Rolling, Grab::Edge { clip, edge, track, .. }) if resp.clicked() => {
- // click an edge = select it as an edit point (trim mode); Shift adds
- let kind = match tool {
- Tool::Rolling => "roll",
- Tool::Ripple => "ripple",
- _ => {
- let (dist, neighbour) = edge_geometry(seq, layout, track, clip, edge, p.x);
- selection_trim_kind(roll_ripple, mods.command, mods.shift, dist, neighbour)
- }
+ app.session.execute("timeline.razor", json!({"time": tt.0, "clip": clip.0}))
};
- let e = if edge == filmcraft_edit::Edge::In { "in" } else { "out" };
- let r = app.session.execute("trim.selectEditPoint", json!({"clip": clip.0, "edge": e, "kind": kind, "add": mods.shift && !mods.command}));
if let Err(e) = r {
app.ui.status = e.to_string();
}
- None
}
- (_, Grab::Edge { clip, edge, kind, .. }) => Some(match kind {
- EdgeKind::Trim => Drag::Trim { clip, edge, mode: filmcraft_edit::TrimMode::Regular, delta: Tick::ZERO, from: t, linked: !mods.alt },
- EdgeKind::Ripple => Drag::Trim { clip, edge, mode: filmcraft_edit::TrimMode::Ripple, delta: Tick::ZERO, from: t, linked: !mods.alt },
- EdgeKind::Roll { left, right } => Drag::Roll { left, right, delta: Tick::ZERO, from: t },
- EdgeKind::Stretch => Drag::Stretch { clip, edge, delta: Tick::ZERO, from: t, linked: !mods.alt },
- EdgeKind::Remix => Drag::Remix { clip, delta: Tick::ZERO, from: t },
- }),
- (_, Grab::Volume { clip, .. }) if resp.drag_started() => crate::panels::timeline_volume::start(seq, layout, clip, p).map(Drag::Volume),
- (_, Grab::Volume { clip, .. }) => {
- crate::panels::timeline_volume::add_keyframe(app, seq, layout, clip, p.x);
+ None
+ }
+ // a transition over a cut counts as its track, as the clips under it do
+ (Tool::TrackSelectForward | Tool::TrackSelectBackward, Grab::Other(Hit::Clip { track, .. } | Hit::Transition { track, .. } | Hit::Empty { track })) => {
+ let fwd = tool == Tool::TrackSelectForward;
+ let ids: Vec<u64> = seq
+ .all_tracks()
+ .filter(|tr| !mods.shift || tr.id == track)
+ .flat_map(|tr| tr.items.iter())
+ .filter(|i| if fwd { i.end() > t } else { i.start < t })
+ .map(|i| i.id.0)
+ .collect();
+ let _ = app.session.execute("timeline.select", json!({"clips": ids}));
+ // as in Premiere Pro, a drag with the tool moves what it just selected
+ if resp.drag_started() {
+ let clips = app.session.state.selection.clone();
+ (!clips.is_empty()).then_some(Drag::Move {
+ clips,
+ grab_tick: t,
+ start_track: track,
+ offset: Tick::ZERO,
+ track_delta: 0,
+ new_track: None,
+ copy: mods.alt,
+ })
+ } else {
None
}
- (Tool::Slip, Grab::Other(Hit::Clip { clip, .. })) => Some(Drag::Slip { clip, delta: Tick::ZERO }),
- (Tool::Slide, Grab::Other(Hit::Clip { clip, .. })) => Some(Drag::Slide { clip, delta: Tick::ZERO }),
- (_, Grab::Other(Hit::Clip { clip, track, .. })) => {
- // select (shift toggles; alt selects one side of a link)
- let sel = &app.session.state.selection;
- if mods.shift {
- let _ = app.session.execute("timeline.select", json!({"clips": [clip.0], "toggle": true, "linked": !mods.alt}));
- } else if !sel.contains(&clip) || (mods.alt && resp.clicked()) {
- // Alt-click isolates one side; Alt-drag keeps the selected group to copy.
- let _ = app.session.execute("timeline.select", json!({"clips": [clip.0], "linked": !mods.alt}));
- }
- if resp.drag_started() {
- let clips = app.session.state.selection.clone();
- Some(Drag::Move { clips, grab_tick: t, start_track: track, offset: Tick::ZERO, track_delta: 0, new_track: None, copy: mods.alt })
- } else {
- None
+ }
+ (Tool::Selection | Tool::Ripple | Tool::Rolling, Grab::Edge { clip, edge, track, .. }) if resp.clicked() => {
+ // click an edge = select it as an edit point (trim mode); Shift adds
+ let kind = match tool {
+ Tool::Rolling => "roll",
+ Tool::Ripple => "ripple",
+ _ => {
+ let (dist, neighbour) = edge_geometry(seq, layout, track, clip, edge, p.x);
+ selection_trim_kind(roll_ripple, mods.command, mods.shift, dist, neighbour)
}
+ };
+ let e = if edge == filmcraft_edit::Edge::In { "in" } else { "out" };
+ let r = app.session.execute("trim.selectEditPoint", json!({"clip": clip.0, "edge": e, "kind": kind, "add": mods.shift && !mods.command}));
+ if let Err(e) = r {
+ app.ui.status = e.to_string();
}
- // click a transition to select it (Shift adds / removes); drag an end to change its
- // duration or its middle to slide it over the cut (#430, #224)
- (Tool::Selection, Grab::Other(Hit::Transition { id, edge, .. })) => {
- // a drag of a selected transition (Shift too) moves it rather than toggling it out first
- if !(app.session.state.transition_selection.contains(&id) && resp.drag_started()) {
- let r = app.session.execute("timeline.select", json!({"transitions": [id.0], "toggle": mods.shift}));
- if let Err(e) = r {
- app.ui.status = e.to_string();
- }
- }
- let span = seq.all_tracks().find_map(|tr| tr.transitions.iter().find(|x| x.id == id)).map(|x| (x.start, x.duration));
- match span {
- Some((start, duration)) if resp.drag_started() => Some(Drag::Transition { id, edge, from: t, start, duration }),
- _ => None,
- }
+ None
+ }
+ (_, Grab::Edge { clip, edge, kind, .. }) => Some(match kind {
+ EdgeKind::Trim => Drag::Trim { clip, edge, mode: filmcraft_edit::TrimMode::Regular, delta: Tick::ZERO, from: t, linked: !mods.alt },
+ EdgeKind::Ripple => Drag::Trim { clip, edge, mode: filmcraft_edit::TrimMode::Ripple, delta: Tick::ZERO, from: t, linked: !mods.alt },
+ EdgeKind::Roll { left, right } => Drag::Roll { left, right, delta: Tick::ZERO, from: t },
+ EdgeKind::Stretch => Drag::Stretch { clip, edge, delta: Tick::ZERO, from: t, linked: !mods.alt },
+ EdgeKind::Remix => Drag::Remix { clip, delta: Tick::ZERO, from: t },
+ }),
+ (_, Grab::Volume { clip, .. }) if resp.drag_started() => crate::panels::timeline_volume::start(seq, layout, clip, p).map(Drag::Volume),
+ (_, Grab::Volume { clip, .. }) => {
+ crate::panels::timeline_volume::add_keyframe(app, seq, layout, clip, p.x);
+ None
+ }
+ (Tool::Slip, Grab::Other(Hit::Clip { clip, .. })) => Some(Drag::Slip { clip, delta: Tick::ZERO }),
+ (Tool::Slide, Grab::Other(Hit::Clip { clip, .. })) => Some(Drag::Slide { clip, delta: Tick::ZERO }),
+ (_, Grab::Other(Hit::Clip { clip, track, .. })) => {
+ // select (shift toggles; alt selects one side of a link)
+ let sel = &app.session.state.selection;
+ if mods.shift {
+ let _ = app.session.execute("timeline.select", json!({"clips": [clip.0], "toggle": true, "linked": !mods.alt}));
+ } else if !sel.contains(&clip) || (mods.alt && resp.clicked()) {
+ // Alt-click isolates one side; Alt-drag keeps the selected group to copy.
+ let _ = app.session.execute("timeline.select", json!({"clips": [clip.0], "linked": !mods.alt}));
}
- (_, Grab::Other(Hit::Transition { .. })) => None,
- // empty space: an empty stretch of a track, or no track at all (below the tracks, between
- // the video and audio tracks, #683)
- (_, Grab::Other(hit @ (Hit::Empty { .. } | Hit::None))) if layout.content.contains(p) => {
- if resp.drag_started() {
- Some(Drag::Marquee { start: p, before: app.session.state.selection.clone(), add: mods.shift || mods.command, individual: mods.alt })
- } else {
- app.session.state.selection.clear();
- app.session.state.edit_points.clear();
- app.session.state.transition_selection.clear();
- // empty time between clips: select the gap, for Delete to close it (#648, #668)
- let gap = match hit {
- Hit::Empty { track } => app.session.execute("timeline.selectGap", json!({"track": track.0, "time": t.0})).is_ok(),
- _ => false,
- };
- if !gap {
- app.session.state.gap_selection = None;
- }
- None
- }
+ if resp.drag_started() {
+ let clips = app.session.state.selection.clone();
+ Some(Drag::Move { clips, grab_tick: t, start_track: track, offset: Tick::ZERO, track_delta: 0, new_track: None, copy: mods.alt })
+ } else {
+ None
}
- (_, Grab::Other(Hit::Empty { .. } | Hit::None)) => None,
- };
- let started = started.filter(|drag| {
- let blocked = drag_is_locked(&app.session, seq, drag);
- if blocked {
- ctx.set_cursor_icon(CursorIcon::NotAllowed);
+ }
+ // click a transition to select it (Shift adds / removes); drag an end to change its
+ // duration or its middle to slide it over the cut (#430, #224)
+ (Tool::Selection, Grab::Other(Hit::Transition { id, edge, .. })) => {
+ // a drag of a selected transition (Shift too) moves it rather than toggling it out first
+ if !(app.session.state.transition_selection.contains(&id) && resp.drag_started()) {
+ let r = app.session.execute("timeline.select", json!({"transitions": [id.0], "toggle": mods.shift}));
+ if let Err(e) = r {
+ app.ui.status = e.to_string();
+ }
}
- !blocked
- });
- if let Some(d) = started {
- if matches!(d, Drag::Scrub { .. }) {
- scrub_playhead(app, seq, layout, p, mods.shift);
+ let span = seq.all_tracks().find_map(|tr| tr.transitions.iter().find(|x| x.id == id)).map(|x| (x.start, x.duration));
+ match span {
+ Some((start, duration)) if resp.drag_started() => Some(Drag::Transition { id, edge, from: t, start, duration }),
+ _ => None,
}
+ }
+ (_, Grab::Other(Hit::Transition { .. })) => None,
+ // empty space: an empty stretch of a track, or no track at all (below the tracks, between
+ // the video and audio tracks, #683)
+ (_, Grab::Other(hit @ (Hit::Empty { .. } | Hit::None))) if layout.content.contains(p) => {
if resp.drag_started() {
- app.tl.drag = Some(d);
+ Some(Drag::Marquee { start: p, before: app.session.state.selection.clone(), add: mods.shift || mods.command, individual: mods.alt })
+ } else {
+ app.session.state.selection.clear();
+ app.session.state.edit_points.clear();
+ app.session.state.transition_selection.clear();
+ // empty time between clips: select the gap, for Delete to close it (#648, #668)
+ let gap = match hit {
+ Hit::Empty { track } => app.session.execute("timeline.selectGap", json!({"track": track.0, "time": t.0})).is_ok(),
+ _ => false,
+ };
+ if !gap {
+ app.session.state.gap_selection = None;
+ }
+ None
}
}
+ (_, Grab::Other(Hit::Empty { .. } | Hit::None)) => None,
+ };
+ let started = started.filter(|drag| {
+ let blocked = drag_is_locked(&app.session, seq, drag);
+ if blocked {
+ ctx.set_cursor_icon(CursorIcon::NotAllowed);
+ }
+ !blocked
+ });
+ if let Some(d) = started {
+ if matches!(d, Drag::Scrub { .. }) {
+ scrub_playhead(app, seq, layout, p, mods.shift);
+ }
+ if resp.drag_started() {
+ app.tl.drag = Some(d);
+ }
}
+}
+/// Escape cancels an ongoing drag or press (#580): the release commits nothing.
+fn escape_cancel(app: &mut FilmcraftApp, ctx: &egui::Context) {
// Escape cancels an ongoing drag or press (#580): the release commits nothing
if (app.tl.drag.is_some() || app.tl.pressed.is_some()) && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if let Some(d) = app.tl.drag.take() {
@@ -546,7 +552,15 @@ pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence
app.tl.pressed = None;
app.tl.cancelled = true;
}
+}
+/// An ongoing drag: recomputes its state under the pointer (snapping, the destination track,
+/// the marquee box), refuses it when it would land on locked tracks, and auto-scrolls near
+/// the edges.
+fn drag_update(app: &mut FilmcraftApp, ui: &mut egui::Ui, resp: &egui::Response, seq: &Sequence, layout: &Layout) {
+ let ctx = ui.ctx().clone();
+ let rate = seq.settings.frame_rate;
+ let mods = ctx.input(|i| i.modifiers);
// ---- drag
if !app.tl.cancelled
&& resp.dragged()
@@ -694,7 +708,12 @@ pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence
}
}
}
+}
+/// Release: commit exactly one command for the drag that just ended, or drop it when the
+/// drag moved nothing (or Escape cancelled it).
+fn commit_drag(app: &mut FilmcraftApp, ctx: &egui::Context, resp: &egui::Response, seq: &Sequence, layout: &Layout) {
+ let mods = ctx.input(|i| i.modifiers);
// ---- release: commit exactly one command
if resp.drag_stopped() {
// a drag Escape cancelled (#580) commits nothing
@@ -753,44 +772,294 @@ pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence
app.tl.drag = None;
}
}
+}
- // ---- double-click the work area bar: it spans the part of the sequence the ruler shows
- if resp.double_clicked()
- && let Some(p) = resp.interact_pointer_pos()
- && let Hit::WorkArea { .. } = hit(seq, layout, p)
+/// Project items, graphics templates, effects and OS files dragged over the Timeline: the
+/// preview of where they would land while hovering, and the command that places them on
+/// release.
+fn drop_targets(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &Layout) {
+ let ctx = ui.ctx().clone();
+ let rate = seq.settings.frame_rate;
+ let mods = ctx.input(|i| i.modifiers);
+ // ---- drops: project items and effects
+ if let Some(item) = crate::panels::dragged_project_item(ui)
+ && let Some(p) = ctx.pointer_hover_pos()
+ && layout.content.contains(p)
+ && app.timeline_drop_target(ui.ctx(), p)
{
- let start = rate.snap_nearest(layout.tick_at(layout.content.min.x).max(Tick::ZERO));
- let end = rate.snap_nearest(layout.tick_at(layout.content.max.x)).min(seq.duration());
- // a ruler scrolled past the end of the sequence leaves the bar as it is
- if end > start
- && let Err(e) = app.session.execute("sequence.setWorkArea", json!({"start": start.0, "end": end.0}))
+ let source = crate::panels::dragged_source(ui);
+ let row = layout.row_at(p.y).cloned().filter(|r| {
+ source.is_none_or(|s| match r.kind {
+ TrackKind::Video => s.video,
+ TrackKind::Audio => s.audio,
+ })
+ });
+ let t = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
+ let still = app.session.prefs.timeline.still_duration(rate);
+ let is_still = app.session.project.item(item).and_then(|i| i.as_media()).is_some_and(|m| m.info.kind == filmcraft_media::MediaKind::Still);
+ let dur = source
+ .map(|s| s.range.duration)
+ .unwrap_or_else(|| app.session.project.item(item).map(|i| i.duration()).filter(|d| d.0 > 0 && !is_still).unwrap_or(still));
+ // #483: in the empty space above the top video track or below the last audio track, a new track
+ let new_track = if row.is_some() { None } else { new_track_at(seq, layout, p.y, app.ui.timeline.video_track_h, app.ui.timeline.audio_track_h) }.filter(
+ |(kind, _)| {
+ let carries = app.session.project.item(item).is_some_and(|i| if *kind == TrackKind::Video { i.has_video() } else { i.has_audio() });
+ carries && source.is_none_or(|s| if *kind == TrackKind::Video { s.video } else { s.audio })
+ },
+ );
+ if let Some(band) = row.as_ref().map(|r| r.rect).or(new_track.map(|(_, band)| band)) {
+ let r = Rect::from_min_max(pos2(layout.x_of(t), band.min.y + 1.0), pos2(layout.x_of(t + dur), band.max.y - 1.0));
+ ui.painter().rect_filled(r, 3.0, Color32::from_white_alpha(40));
+ ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside);
+ if mods.command {
+ ui.painter().text(r.left_top() + vec2(4.0, -2.0), Align2::LEFT_BOTTOM, tl!("Insert"), Tokens::ui(10.0), Color32::WHITE);
+ }
+ }
+ let target = match (&row, new_track) {
+ (Some(row), _) => Some(match row.kind {
+ TrackKind::Video => (json!(row.track.0), json!(seq.audio_tracks.get(row.index).or(seq.audio_tracks.first()).map(|t| t.id.0))),
+ TrackKind::Audio => (json!(seq.video_tracks.get(row.index).or(seq.video_tracks.first()).map(|t| t.id.0)), json!(row.track.0)),
+ }),
+ // the other stream goes on the track of the same number, or on a new one as well
+ (None, Some((TrackKind::Video, _))) => Some((json!("new"), seq.audio_tracks.get(seq.video_tracks.len()).map_or(json!("new"), |t| json!(t.id.0)))),
+ (None, Some((TrackKind::Audio, _))) => Some((seq.video_tracks.get(seq.audio_tracks.len()).map_or(json!("new"), |t| json!(t.id.0)), json!("new"))),
+ (None, None) => None,
+ };
+ if ctx.input(|i| i.pointer.any_released())
+ && let Some((vt, at)) = target
{
- app.ui.status = e.to_string();
+ // dragging one of several selected project items places them all, back to back, as one edit
+ let items = match source {
+ None => crate::panels::dragged_selection(app, item),
+ Some(_) => vec![item],
+ };
+ let mut params = json!({"track": vt, "audioTrack": at, "time": t.0, "insert": mods.command});
+ match items.as_slice() {
+ [one] => params["item"] = json!(one.0),
+ many => params["items"] = json!(many.iter().map(|i| i.0).collect::<Vec<_>>()),
+ }
+ if let Some(source) = source {
+ params["sourceIn"] = json!(source.range.start.0);
+ params["duration"] = json!(source.range.duration.0);
+ params["video"] = json!(source.video);
+ params["audio"] = json!(source.audio);
+ }
+ if let Err(e) = app.session.execute("timeline.place", params) {
+ app.ui.status = e.to_string();
+ }
+ crate::panels::clear_drag(ui);
}
}
-
- // ---- double-click a transition: Set Transition Duration (Premiere)
- if resp.double_clicked()
- && tool == Tool::Selection
- && let Some(p) = resp.interact_pointer_pos()
- && let Hit::Transition { id, .. } = hit(seq, layout, p)
+ // graphics templates from Essential Graphics ▸ Browse: placed on the video track under the pointer
+ if let Some(template) = crate::panels::dragged_template(ui)
+ && let Some(p) = ctx.pointer_hover_pos()
+ && layout.content.contains(p)
+ && app.timeline_drop_target(ui.ctx(), p)
{
- crate::panels::transition_controls::open_duration(app, id);
+ let t = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
+ let row = layout.row_at(p.y).cloned().filter(|r| r.kind == TrackKind::Video);
+ if let Some(row) = &row {
+ let r = Rect::from_min_max(pos2(layout.x_of(t), row.rect.min.y + 1.0), pos2(layout.x_of(t) + 60.0, row.rect.max.y - 1.0));
+ ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside);
+ }
+ if ctx.input(|i| i.pointer.any_released()) {
+ let mut q = json!({"template": template, "time": t.0});
+ if let Some(row) = row {
+ q["track"] = json!(row.index);
+ }
+ if let Err(e) = app.session.execute("graphics.template.apply", q) {
+ app.ui.status = e.to_string();
+ }
+ crate::panels::clear_drag(ui);
+ }
}
-
- // ---- double-click a nested sequence clip: open it in its own Timeline tab
- if resp.double_clicked()
- && tool == Tool::Selection
- && let Some(p) = resp.interact_pointer_pos()
- && let Hit::Clip { clip, .. } = hit(seq, layout, p)
- && seq.find_item(clip).is_some_and(|(_, it)| app.session.project.sequence(it.item).is_some())
+ effect_drop_preview(app, ui, seq, layout);
+ // ---- OS file drops imported with "drop imports to the timeline": placed at the drop point, one after another
+ if let Some((items, p, viewport)) = app.pending_timeline_drop.clone()
+ && viewport == ui.ctx().viewport_id()
+ && layout.content.contains(p)
+ && app.timeline_drop_target(ui.ctx(), p)
{
- let _ = app.session.execute("timeline.select", json!({"clips": [clip.0]}));
- if let Err(e) = app.session.execute("sequence.revealNested", json!({})) {
- app.ui.status = e.to_string();
+ app.pending_timeline_drop = None;
+ let row = layout.row_at(p.y).cloned().or_else(|| layout.rows.iter().find(|r| r.kind == TrackKind::Video).cloned());
+ if let Some(row) = row {
+ let (vt, at) = match row.kind {
+ TrackKind::Video => (Some(row.track.0), seq.audio_tracks.get(row.index).or(seq.audio_tracks.first()).map(|t| t.id.0)),
+ TrackKind::Audio => (seq.video_tracks.get(row.index).or(seq.video_tracks.first()).map(|t| t.id.0), Some(row.track.0)),
+ };
+ let start = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
+ // one command, one undo step: the files go end to end from the drop point
+ let ids: Vec<u64> = items.iter().map(|i| i.0).collect();
+ let params = json!({"items": ids, "track": vt, "audioTrack": at, "time": start.0, "insert": false});
+ if let Err(e) = app.session.execute("timeline.place", params) {
+ app.ui.status = e.to_string();
+ }
}
}
-
+ // preview of OS files being dragged over the Timeline: a placeholder where the drop would start
+ if let Some((count, p, viewport)) = app.file_drag_hover
+ && viewport == ui.ctx().viewport_id()
+ && layout.content.contains(p)
+ && app.timeline_drop_target(ui.ctx(), p)
+ {
+ let row = layout.row_at(p.y).cloned().or_else(|| layout.rows.iter().find(|r| r.kind == TrackKind::Video).cloned());
+ if let Some(row) = row {
+ let t = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
+ let x = layout.x_of(t);
+ let r = Rect::from_min_max(pos2(x, row.rect.min.y + 1.0), pos2((x + 120.0).min(layout.content.max.x), row.rect.max.y - 1.0));
+ ui.painter().rect_filled(r, 3.0, Color32::from_white_alpha(40));
+ ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside);
+ app.auto.add("timeline.fileDropPreview", r, "tracks");
+ let label = if count == 1 { tl!("1 file").to_string() } else { tlf!("{n} files", n = count) };
+ ui.painter().text(r.left_top() + vec2(4.0, 2.0), Align2::LEFT_TOP, label, Tokens::ui(10.0), Color32::WHITE);
+ }
+ }
+}
+
+/// An effect or transition dragged over a clip: previews where it would land (the transition
+/// spanning the nearest edge, the effect covering the clip) and applies it on release.
+fn effect_drop_preview(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &Layout) {
+ let ctx = ui.ctx().clone();
+ if let Some(effect) = crate::panels::dragged_effect(ui)
+ && let Some(p) = ctx.pointer_hover_pos()
+ && layout.content.contains(p)
+ && app.timeline_drop_target(ui.ctx(), p)
+ && let Hit::Clip { clip, .. } = hit(seq, layout, p)
+ && let Some((tid, it)) = seq.find_item(clip)
+ && let Some(row) = layout.rows.iter().find(|r| r.track == tid)
+ {
+ {
+ let transition_kind = filmcraft_project::find_effect(&effect).and_then(|d| match d.kind {
+ filmcraft_project::EffectKind::VideoTransition => Some(TrackKind::Video),
+ filmcraft_project::EffectKind::AudioTransition => Some(TrackKind::Audio),
+ _ => None,
+ });
+ let edge = if p.x - layout.x_of(it.start) < layout.x_of(it.end()) - p.x { "in" } else { "out" };
+ let params = json!({"effect": effect, "clip": clip.0, "edge": edge});
+ if let Some(kind) = transition_kind {
+ if let Ok((_, tr)) = filmcraft_engine::commands::preview_transition(&app.session, &params, kind) {
+ let r = Rect::from_min_max(pos2(layout.x_of(tr.start), row.rect.min.y + 1.0), pos2(layout.x_of(tr.end()), row.rect.max.y - 1.0));
+ let painter = ui.painter().with_clip_rect(layout.content);
+ painter.rect_filled(r, 2.0, app.tokens.accent.gamma_multiply(0.35));
+ paint_hatch(&painter, r.intersect(layout.content));
+ painter.rect_stroke(r, 2.0, Stroke::new(2.0, app.tokens.accent), StrokeKind::Inside);
+ let cut = if edge == "in" { it.start } else { it.end() };
+ let x = layout.x_of(cut);
+ painter.line_segment([pos2(x, r.top()), pos2(x, r.bottom())], Stroke::new(3.0, app.tokens.accent));
+ // Keep the edge label readable even when the clip/transition is only a few pixels wide.
+ let label = if edge == "in" { tl!("In") } else { tl!("Out") };
+ let label_width = painter.layout_no_wrap(label.to_string(), Tokens::ui(11.0), app.tokens.accent).size().x + 8.0;
+ let label_rect = Rect::from_center_size(pos2(p.x, row.rect.top() + 10.0), vec2(label_width, 15.0));
+ painter.rect_filled(label_rect, 2.0, app.tokens.panel_bg);
+ painter.text(label_rect.center(), Align2::CENTER_CENTER, label, Tokens::ui(11.0), app.tokens.accent);
+ app.auto.add("timeline.transitionDropPreview", r.intersect(layout.content), edge);
+ }
+ } else {
+ let r = Rect::from_min_max(pos2(layout.x_of(it.start), row.rect.min.y), pos2(layout.x_of(it.end()), row.rect.max.y));
+ ui.painter().rect_stroke(r, 3.0, Stroke::new(2.0, app.tokens.accent), StrokeKind::Inside);
+ }
+ if ctx.input(|i| i.pointer.any_released()) {
+ let r = if let Some(name) = effect.strip_prefix("preset:") {
+ app.session.execute("presets.apply", json!({"preset": name, "clips": [clip.0]}))
+ } else if let Some(name) = effect.strip_prefix(crate::panels::LUMETRI_PRESET_PREFIX) {
+ app.session.execute("lumetri.applyPreset", json!({"name": name, "clips": [clip.0]}))
+ } else if transition_kind.is_some() {
+ app.session.execute("effects.apply", params)
+ } else {
+ app.session.execute("effects.apply", json!({"effect": effect, "clips": [clip.0]}))
+ };
+ if let Err(e) = r {
+ app.ui.status = e.to_string();
+ } else {
+ let _ = app.session.execute("timeline.select", json!({"clips": [clip.0]}));
+ }
+ crate::panels::clear_drag(ui);
+ }
+ }
+ }
+}
+
+/// Handle Timeline pointer input: remember the grab from the press frame, jump the playhead on a ruler press, select a marker on its press, and reset the
+/// cancel flag once the button is released.
+pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &Layout, rect: Rect) {
+ let ctx = ui.ctx().clone();
+ let area = Rect::from_min_max(pos2(layout.content.min.x, layout.ruler.min.y), layout.content.max);
+ let resp = ui.interact(area, egui::Id::unique("timeline-area"), Sense::click_and_drag());
+ let pos = resp.hover_pos().or(resp.interact_pointer_pos());
+ let mods = ctx.input(|i| i.modifiers);
+ let tool = app.ui.tool;
+ let rate = seq.settings.frame_rate;
+ let roll_ripple = app.session.prefs.trim.selection_tool_roll_ripple;
+
+ // ---- what the button went down on (#259): kept from the press frame until it comes up
+ if ctx.input(|i| !i.pointer.any_down() && !i.pointer.any_released()) {
+ app.tl.pressed = None;
+ app.tl.cancelled = false;
+ }
+ if resp.is_pointer_button_down_on()
+ && ctx.input(|i| i.pointer.primary_pressed())
+ && let Some(p) = ctx.input(|i| i.pointer.press_origin())
+ {
+ app.tl.cancelled = false;
+ let grab = grab_at(seq, layout, p, tool, mods, roll_ripple);
+ // the playhead jumps to a press on the ruler at once, not only once the pointer has moved (#1090)
+ if matches!(grab, Grab::Other(Hit::Ruler)) {
+ scrub_playhead(app, seq, layout, p, mods.shift);
+ }
+ app.tl.pressed = Some(Pressed { pos: p, tick: layout.tick_at(p.x), grab });
+ }
+
+ wheel_scroll(app, ui, rect, layout, seq);
+
+ hover_cursor(app, ui, seq, layout, pos);
+
+ if press_action(app, &ctx, &resp, seq, layout) {
+ return;
+ }
+
+ escape_cancel(app, &ctx);
+
+ drag_update(app, ui, &resp, seq, layout);
+
+ commit_drag(app, &ctx, &resp, seq, layout);
+
+ // ---- double-click the work area bar: it spans the part of the sequence the ruler shows
+ if resp.double_clicked()
+ && let Some(p) = resp.interact_pointer_pos()
+ && let Hit::WorkArea { .. } = hit(seq, layout, p)
+ {
+ let start = rate.snap_nearest(layout.tick_at(layout.content.min.x).max(Tick::ZERO));
+ let end = rate.snap_nearest(layout.tick_at(layout.content.max.x)).min(seq.duration());
+ // a ruler scrolled past the end of the sequence leaves the bar as it is
+ if end > start
+ && let Err(e) = app.session.execute("sequence.setWorkArea", json!({"start": start.0, "end": end.0}))
+ {
+ app.ui.status = e.to_string();
+ }
+ }
+
+ // ---- double-click a transition: Set Transition Duration (Premiere)
+ if resp.double_clicked()
+ && tool == Tool::Selection
+ && let Some(p) = resp.interact_pointer_pos()
+ && let Hit::Transition { id, .. } = hit(seq, layout, p)
+ {
+ crate::panels::transition_controls::open_duration(app, id);
+ }
+
+ // ---- double-click a nested sequence clip: open it in its own Timeline tab
+ if resp.double_clicked()
+ && tool == Tool::Selection
+ && let Some(p) = resp.interact_pointer_pos()
+ && let Hit::Clip { clip, .. } = hit(seq, layout, p)
+ && seq.find_item(clip).is_some_and(|(_, it)| app.session.project.sequence(it.item).is_some())
+ {
+ let _ = app.session.execute("timeline.select", json!({"clips": [clip.0]}));
+ if let Err(e) = app.session.execute("sequence.revealNested", json!({})) {
+ app.ui.status = e.to_string();
+ }
+ }
+
// ---- double-click any other clip (not on its edge): open its media in the Source monitor at
// the matching frame (Premiere); graphic clips have no source to show
if resp.double_clicked()
@@ -939,194 +1208,7 @@ pub(super) fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence
});
});
- // ---- drops: project items and effects
- if let Some(item) = crate::panels::dragged_project_item(ui)
- && let Some(p) = ctx.pointer_hover_pos()
- && layout.content.contains(p)
- && app.timeline_drop_target(ui.ctx(), p)
- {
- let source = crate::panels::dragged_source(ui);
- let row = layout.row_at(p.y).cloned().filter(|r| {
- source.is_none_or(|s| match r.kind {
- TrackKind::Video => s.video,
- TrackKind::Audio => s.audio,
- })
- });
- let t = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
- let still = app.session.prefs.timeline.still_duration(rate);
- let is_still = app.session.project.item(item).and_then(|i| i.as_media()).is_some_and(|m| m.info.kind == filmcraft_media::MediaKind::Still);
- let dur = source
- .map(|s| s.range.duration)
- .unwrap_or_else(|| app.session.project.item(item).map(|i| i.duration()).filter(|d| d.0 > 0 && !is_still).unwrap_or(still));
- // #483: in the empty space above the top video track or below the last audio track, a new track
- let new_track = if row.is_some() { None } else { new_track_at(seq, layout, p.y, app.ui.timeline.video_track_h, app.ui.timeline.audio_track_h) }.filter(
- |(kind, _)| {
- let carries = app.session.project.item(item).is_some_and(|i| if *kind == TrackKind::Video { i.has_video() } else { i.has_audio() });
- carries && source.is_none_or(|s| if *kind == TrackKind::Video { s.video } else { s.audio })
- },
- );
- if let Some(band) = row.as_ref().map(|r| r.rect).or(new_track.map(|(_, band)| band)) {
- let r = Rect::from_min_max(pos2(layout.x_of(t), band.min.y + 1.0), pos2(layout.x_of(t + dur), band.max.y - 1.0));
- ui.painter().rect_filled(r, 3.0, Color32::from_white_alpha(40));
- ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside);
- if mods.command {
- ui.painter().text(r.left_top() + vec2(4.0, -2.0), Align2::LEFT_BOTTOM, tl!("Insert"), Tokens::ui(10.0), Color32::WHITE);
- }
- }
- let target = match (&row, new_track) {
- (Some(row), _) => Some(match row.kind {
- TrackKind::Video => (json!(row.track.0), json!(seq.audio_tracks.get(row.index).or(seq.audio_tracks.first()).map(|t| t.id.0))),
- TrackKind::Audio => (json!(seq.video_tracks.get(row.index).or(seq.video_tracks.first()).map(|t| t.id.0)), json!(row.track.0)),
- }),
- // the other stream goes on the track of the same number, or on a new one as well
- (None, Some((TrackKind::Video, _))) => Some((json!("new"), seq.audio_tracks.get(seq.video_tracks.len()).map_or(json!("new"), |t| json!(t.id.0)))),
- (None, Some((TrackKind::Audio, _))) => Some((seq.video_tracks.get(seq.audio_tracks.len()).map_or(json!("new"), |t| json!(t.id.0)), json!("new"))),
- (None, None) => None,
- };
- if ctx.input(|i| i.pointer.any_released())
- && let Some((vt, at)) = target
- {
- // dragging one of several selected project items places them all, back to back, as one edit
- let items = match source {
- None => crate::panels::dragged_selection(app, item),
- Some(_) => vec![item],
- };
- let mut params = json!({"track": vt, "audioTrack": at, "time": t.0, "insert": mods.command});
- match items.as_slice() {
- [one] => params["item"] = json!(one.0),
- many => params["items"] = json!(many.iter().map(|i| i.0).collect::<Vec<_>>()),
- }
- if let Some(source) = source {
- params["sourceIn"] = json!(source.range.start.0);
- params["duration"] = json!(source.range.duration.0);
- params["video"] = json!(source.video);
- params["audio"] = json!(source.audio);
- }
- if let Err(e) = app.session.execute("timeline.place", params) {
- app.ui.status = e.to_string();
- }
- crate::panels::clear_drag(ui);
- }
- }
- // graphics templates from Essential Graphics ▸ Browse: placed on the video track under the pointer
- if let Some(template) = crate::panels::dragged_template(ui)
- && let Some(p) = ctx.pointer_hover_pos()
- && layout.content.contains(p)
- && app.timeline_drop_target(ui.ctx(), p)
- {
- let t = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
- let row = layout.row_at(p.y).cloned().filter(|r| r.kind == TrackKind::Video);
- if let Some(row) = &row {
- let r = Rect::from_min_max(pos2(layout.x_of(t), row.rect.min.y + 1.0), pos2(layout.x_of(t) + 60.0, row.rect.max.y - 1.0));
- ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside);
- }
- if ctx.input(|i| i.pointer.any_released()) {
- let mut q = json!({"template": template, "time": t.0});
- if let Some(row) = row {
- q["track"] = json!(row.index);
- }
- if let Err(e) = app.session.execute("graphics.template.apply", q) {
- app.ui.status = e.to_string();
- }
- crate::panels::clear_drag(ui);
- }
- }
- if let Some(effect) = crate::panels::dragged_effect(ui)
- && let Some(p) = ctx.pointer_hover_pos()
- && layout.content.contains(p)
- && app.timeline_drop_target(ui.ctx(), p)
- && let Hit::Clip { clip, .. } = hit(seq, layout, p)
- && let Some((tid, it)) = seq.find_item(clip)
- && let Some(row) = layout.rows.iter().find(|r| r.track == tid)
- {
- {
- let transition_kind = filmcraft_project::find_effect(&effect).and_then(|d| match d.kind {
- filmcraft_project::EffectKind::VideoTransition => Some(TrackKind::Video),
- filmcraft_project::EffectKind::AudioTransition => Some(TrackKind::Audio),
- _ => None,
- });
- let edge = if p.x - layout.x_of(it.start) < layout.x_of(it.end()) - p.x { "in" } else { "out" };
- let params = json!({"effect": effect, "clip": clip.0, "edge": edge});
- if let Some(kind) = transition_kind {
- if let Ok((_, tr)) = filmcraft_engine::commands::preview_transition(&app.session, &params, kind) {
- let r = Rect::from_min_max(pos2(layout.x_of(tr.start), row.rect.min.y + 1.0), pos2(layout.x_of(tr.end()), row.rect.max.y - 1.0));
- let painter = ui.painter().with_clip_rect(layout.content);
- painter.rect_filled(r, 2.0, app.tokens.accent.gamma_multiply(0.35));
- paint_hatch(&painter, r.intersect(layout.content));
- painter.rect_stroke(r, 2.0, Stroke::new(2.0, app.tokens.accent), StrokeKind::Inside);
- let cut = if edge == "in" { it.start } else { it.end() };
- let x = layout.x_of(cut);
- painter.line_segment([pos2(x, r.top()), pos2(x, r.bottom())], Stroke::new(3.0, app.tokens.accent));
- // Keep the edge label readable even when the clip/transition is only a few pixels wide.
- let label = if edge == "in" { tl!("In") } else { tl!("Out") };
- let label_width = painter.layout_no_wrap(label.to_string(), Tokens::ui(11.0), app.tokens.accent).size().x + 8.0;
- let label_rect = Rect::from_center_size(pos2(p.x, row.rect.top() + 10.0), vec2(label_width, 15.0));
- painter.rect_filled(label_rect, 2.0, app.tokens.panel_bg);
- painter.text(label_rect.center(), Align2::CENTER_CENTER, label, Tokens::ui(11.0), app.tokens.accent);
- app.auto.add("timeline.transitionDropPreview", r.intersect(layout.content), edge);
- }
- } else {
- let r = Rect::from_min_max(pos2(layout.x_of(it.start), row.rect.min.y), pos2(layout.x_of(it.end()), row.rect.max.y));
- ui.painter().rect_stroke(r, 3.0, Stroke::new(2.0, app.tokens.accent), StrokeKind::Inside);
- }
- if ctx.input(|i| i.pointer.any_released()) {
- let r = if let Some(name) = effect.strip_prefix("preset:") {
- app.session.execute("presets.apply", json!({"preset": name, "clips": [clip.0]}))
- } else if let Some(name) = effect.strip_prefix(crate::panels::LUMETRI_PRESET_PREFIX) {
- app.session.execute("lumetri.applyPreset", json!({"name": name, "clips": [clip.0]}))
- } else if transition_kind.is_some() {
- app.session.execute("effects.apply", params)
- } else {
- app.session.execute("effects.apply", json!({"effect": effect, "clips": [clip.0]}))
- };
- if let Err(e) = r {
- app.ui.status = e.to_string();
- } else {
- let _ = app.session.execute("timeline.select", json!({"clips": [clip.0]}));
- }
- crate::panels::clear_drag(ui);
- }
- }
- }
- // ---- OS file drops imported with "drop imports to the timeline": placed at the drop point, one after another
- if let Some((items, p, viewport)) = app.pending_timeline_drop.clone()
- && viewport == ui.ctx().viewport_id()
- && layout.content.contains(p)
- && app.timeline_drop_target(ui.ctx(), p)
- {
- app.pending_timeline_drop = None;
- let row = layout.row_at(p.y).cloned().or_else(|| layout.rows.iter().find(|r| r.kind == TrackKind::Video).cloned());
- if let Some(row) = row {
- let (vt, at) = match row.kind {
- TrackKind::Video => (Some(row.track.0), seq.audio_tracks.get(row.index).or(seq.audio_tracks.first()).map(|t| t.id.0)),
- TrackKind::Audio => (seq.video_tracks.get(row.index).or(seq.video_tracks.first()).map(|t| t.id.0), Some(row.track.0)),
- };
- let start = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
- // one command, one undo step: the files go end to end from the drop point
- let ids: Vec<u64> = items.iter().map(|i| i.0).collect();
- let params = json!({"items": ids, "track": vt, "audioTrack": at, "time": start.0, "insert": false});
- if let Err(e) = app.session.execute("timeline.place", params) {
- app.ui.status = e.to_string();
- }
- }
- }
- // preview of OS files being dragged over the Timeline: a placeholder where the drop would start
- if let Some((count, p, viewport)) = app.file_drag_hover
- && viewport == ui.ctx().viewport_id()
- && layout.content.contains(p)
- && app.timeline_drop_target(ui.ctx(), p)
- {
- let row = layout.row_at(p.y).cloned().or_else(|| layout.rows.iter().find(|r| r.kind == TrackKind::Video).cloned());
- if let Some(row) = row {
- let t = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
- let x = layout.x_of(t);
- let r = Rect::from_min_max(pos2(x, row.rect.min.y + 1.0), pos2((x + 120.0).min(layout.content.max.x), row.rect.max.y - 1.0));
- ui.painter().rect_filled(r, 3.0, Color32::from_white_alpha(40));
- ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside);
- app.auto.add("timeline.fileDropPreview", r, "tracks");
- let label = if count == 1 { tl!("1 file").to_string() } else { tlf!("{n} files", n = count) };
- ui.painter().text(r.left_top() + vec2(4.0, 2.0), Align2::LEFT_TOP, label, Tokens::ui(10.0), Color32::WHITE);
- }
- }
+ drop_targets(app, ui, seq, layout);
+
app.auto.add("timeline.tracks", layout.content, "tracks");
}
diff --git a/crates/ui-egui/src/panels/timeline/ruler.rs b/crates/ui-egui/src/panels/timeline/ruler.rs
index 8a03e764d..c3c7186a8 100644
--- a/crates/ui-egui/src/panels/timeline/ruler.rs
+++ b/crates/ui-egui/src/panels/timeline/ruler.rs
@@ -73,51 +73,12 @@ pub(super) fn draw_top(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, se
};
}
if key == "settings" {
- egui::Popup::menu(&resp).show(|ui| {
- let c = ui.checkbox(&mut app.ui.timeline.show_thumbnails, tl!("Show Video Thumbnails"));
- app.auto.add("timeline.settings.showThumbnails", c.rect, "Show Video Thumbnails");
- let on = app.ui.timeline.show_thumbnails;
- ui.indent("timeline.settings.thumbnails", |ui| {
- for (mode, label) in
- [(ThumbnailMode::Head, tl!("Head")), (ThumbnailMode::HeadAndTail, tl!("Head and Tail")), (ThumbnailMode::Continuous, tl!("Continuous"))]
- {
- let r = ui.add_enabled(on, egui::RadioButton::new(app.ui.timeline.thumbnail_mode == mode, label));
- app.auto.add(&format!("timeline.settings.thumbnails.{}", mode.name()), r.rect, label);
- if r.clicked() {
- app.ui.timeline.thumbnail_mode = mode;
- }
- }
- });
- ui.checkbox(&mut app.ui.timeline.show_waveforms, tl!("Show Audio Waveform"));
- ui.separator();
- let mut te = app.session.state.show_through_edits;
- let c = ui.checkbox(&mut te, tl!("Show Through Edits"));
- app.auto.add("timeline.settings.showThroughEdits", c.rect, "Show Through Edits");
- if c.changed() {
- let _ = app.session.execute("sequence.showThroughEdits", json!({"on": te}));
- }
- let mut df = app.session.state.show_duplicate_frame_markers;
- let c = ui.checkbox(&mut df, tl!("Show Duplicate Frame Markers"));
- app.auto.add("timeline.settings.showDuplicateFrameMarkers", c.rect, "Show Duplicate Frame Markers");
- if c.changed() {
- let _ = app.session.execute("sequence.showDuplicateFrameMarkers", json!({"on": df}));
- }
- ui.separator();
- if ui.button(tl!("Expand All Tracks")).clicked() {
- app.ui.timeline.video_track_h = 64.0;
- app.ui.timeline.audio_track_h = 64.0;
- }
- if ui.button(tl!("Minimize All Tracks")).clicked() {
- app.ui.timeline.video_track_h = 26.0;
- app.ui.timeline.audio_track_h = 26.0;
- }
- });
+ egui::Popup::menu(&resp).show(|ui| timeline_settings(app, ui));
}
x += 30.0;
}
// ----- ruler: markers row · labels · ticks · 2 pt render bar
let clip = p.with_clip_rect(ruler);
- let marker_y = ruler.min.y + 2.0;
let label_y = ruler.min.y + 24.0;
let tick_base = ruler.max.y - 3.0;
let (minor, label_step) = ruler_steps(layout.pps / rate.as_f64(), rate.timecode_base());
@@ -206,6 +167,14 @@ pub(super) fn draw_top(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, se
}
}
// markers: 8 × 12 pt pentagons in the marker colour, on the top row
+ draw_markers(app, ui, &clip, layout, seq);
+ app.auto.add("timeline.ruler", ruler, "time ruler");
+}
+
+/// The ruler's marker row: one pentagon per marker in its colour, its range band behind it and,
+/// on hover, its name.
+fn draw_markers(app: &mut FilmcraftApp, ui: &egui::Ui, clip: &egui::Painter, layout: &Layout, seq: &Sequence) {
+ let marker_y = layout.ruler.min.y + 2.0;
for m in &seq.markers {
let x = layout.x_of(m.start);
let c = m.color.marker_rgb();
@@ -225,5 +194,46 @@ pub(super) fn draw_top(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, se
});
}
}
- app.auto.add("timeline.ruler", ruler, "time ruler");
+}
+
+/// The Timeline Display Settings popup from the ruler toolbar: thumbnails, waveforms, edit
+/// markers and the track-height presets.
+fn timeline_settings(app: &mut FilmcraftApp, ui: &mut egui::Ui) {
+ let c = ui.checkbox(&mut app.ui.timeline.show_thumbnails, tl!("Show Video Thumbnails"));
+ app.auto.add("timeline.settings.showThumbnails", c.rect, "Show Video Thumbnails");
+ let on = app.ui.timeline.show_thumbnails;
+ ui.indent("timeline.settings.thumbnails", |ui| {
+ for (mode, label) in
+ [(ThumbnailMode::Head, tl!("Head")), (ThumbnailMode::HeadAndTail, tl!("Head and Tail")), (ThumbnailMode::Continuous, tl!("Continuous"))]
+ {
+ let r = ui.add_enabled(on, egui::RadioButton::new(app.ui.timeline.thumbnail_mode == mode, label));
+ app.auto.add(&format!("timeline.settings.thumbnails.{}", mode.name()), r.rect, label);
+ if r.clicked() {
+ app.ui.timeline.thumbnail_mode = mode;
+ }
+ }
+ });
+ ui.checkbox(&mut app.ui.timeline.show_waveforms, tl!("Show Audio Waveform"));
+ ui.separator();
+ let mut te = app.session.state.show_through_edits;
+ let c = ui.checkbox(&mut te, tl!("Show Through Edits"));
+ app.auto.add("timeline.settings.showThroughEdits", c.rect, "Show Through Edits");
+ if c.changed() {
+ let _ = app.session.execute("sequence.showThroughEdits", json!({"on": te}));
+ }
+ let mut df = app.session.state.show_duplicate_frame_markers;
+ let c = ui.checkbox(&mut df, tl!("Show Duplicate Frame Markers"));
+ app.auto.add("timeline.settings.showDuplicateFrameMarkers", c.rect, "Show Duplicate Frame Markers");
+ if c.changed() {
+ let _ = app.session.execute("sequence.showDuplicateFrameMarkers", json!({"on": df}));
+ }
+ ui.separator();
+ if ui.button(tl!("Expand All Tracks")).clicked() {
+ app.ui.timeline.video_track_h = 64.0;
+ app.ui.timeline.audio_track_h = 64.0;
+ }
+ if ui.button(tl!("Minimize All Tracks")).clicked() {
+ app.ui.timeline.video_track_h = 26.0;
+ app.ui.timeline.audio_track_h = 26.0;
+ }
}
diff --git a/crates/ui-egui/tests/it/media_ui.rs b/crates/ui-egui/tests/it/media_ui.rs
index c36dc8ca4..cbec43510 100644
--- a/crates/ui-egui/tests/it/media_ui.rs
+++ b/crates/ui-egui/tests/it/media_ui.rs
@@ -43,7 +43,7 @@ fn make_movie(path: &Path, scene: DemoScene, w: u32, h: u32, frames: i64) {
identity: None,
};
let mut p = Project::new("fixture");
- let item = p.add_item("scene", Label::Iris, ItemKind::Media(clip), None);
+ let item = p.add_item("scene", Label::Iris, ItemKind::Media(Box::new(clip)), None);
let seq = p.new_sequence("s", SequenceSettings { width: w, height: h, frame_rate: rate, ..Default::default() }, 1, 0, None);
let mut v = p.make_track_item(item, TrackKind::Video, Tick::ZERO, TimeRange::new(Tick::ZERO, dur), rate).unwrap();
for e in &mut v.effects {
@@ -189,7 +189,7 @@ fn source_transport_steps_every_frame_at_a_fractional_tick_rate() {
let item = Arc::make_mut(&mut session.project).add_item(
"31 fps source",
Label::Iris,
- ItemKind::Media(MediaClip {
+ ItemKind::Media(Box::new(MediaClip {
media: MediaRef::Generator(generator),
info: src.info().clone(),
interpret: Default::default(),
@@ -199,7 +199,7 @@ fn source_transport_steps_every_frame_at_a_fractional_tick_rate() {
offline: false,
proxy: None,
identity: None,
- }),
+ })),
None,
);
session.execute("source.open", json!({"item": item.0})).unwrap();
@@ -232,7 +232,7 @@ fn source_menu_steps_use_ordinals_for_explicit_targets_and_focus() {
let item = Arc::make_mut(&mut session.project).add_item(
"31 fps menu source",
Label::Iris,
- ItemKind::Media(MediaClip {
+ ItemKind::Media(Box::new(MediaClip {
media: MediaRef::Generator(generator),
info: src.info().clone(),
interpret: Default::default(),
@@ -242,7 +242,7 @@ fn source_menu_steps_use_ordinals_for_explicit_targets_and_focus() {
offline: false,
proxy: None,
identity: None,
- }),
+ })),
None,
);
session.execute("source.open", json!({"item": item.0})).unwrap();
@@ -308,7 +308,7 @@ fn zero_tick_frame_duration_source() -> (Driver, Tick) {
let item = Arc::make_mut(&mut session.project).add_item(
"Source with less than one tick per frame",
Label::Iris,
- ItemKind::Media(MediaClip {
+ ItemKind::Media(Box::new(MediaClip {
media: MediaRef::Generator(generator),
info: src.info().clone(),
interpret: Default::default(),
@@ -318,7 +318,7 @@ fn zero_tick_frame_duration_source() -> (Driver, Tick) {
offline: false,
proxy: None,
identity: None,
- }),
+ })),
None,
);
assert_eq!(filmcraft_engine::clip_ops::source_view(&session, item).unwrap().rate, rate);
@@ -362,7 +362,7 @@ fn link_media_large_lists_and_long_paths_keep_actions_on_screen() {
let mut media = template.clone();
media.media = MediaRef::File { path: format!("/missing/{}/clip-{n}.mov", "long-project-directory/".repeat(20)) };
media.offline = true;
- let id = p.add_item(&format!("Missing clip {n}"), Label::Iris, ItemKind::Media(media), None);
+ let id = p.add_item(&format!("Missing clip {n}"), Label::Iris, ItemKind::Media(Box::new(media)), None);
s.offline.missing.push(id);
}
s.project = Arc::new(p);
diff --git a/crates/ui-egui/tests/it/multicam_ui.rs b/crates/ui-egui/tests/it/multicam_ui.rs
index d726fb620..109ef7816 100644
--- a/crates/ui-egui/tests/it/multicam_ui.rs
+++ b/crates/ui-egui/tests/it/multicam_ui.rs
@@ -46,7 +46,7 @@ fn make_movie(path: &Path, scene: DemoScene, frames: i64) {
identity: None,
};
let mut p = Project::new("fixture");
- let item = p.add_item("scene", Label::Iris, ItemKind::Media(clip), None);
+ let item = p.add_item("scene", Label::Iris, ItemKind::Media(Box::new(clip)), None);
let seq = p.new_sequence("s", SequenceSettings { width: W, height: H, frame_rate: rate, ..Default::default() }, 1, 0, None);
let mut v = p.make_track_item(item, TrackKind::Video, Tick::ZERO, TimeRange::new(Tick::ZERO, dur), rate).unwrap();
for e in &mut v.effects {
diff --git a/crates/ui-egui/tests/it/shared_docking_ui.rs b/crates/ui-egui/tests/it/shared_docking_ui.rs
index 1d2fa0a28..278b46f32 100644
--- a/crates/ui-egui/tests/it/shared_docking_ui.rs
+++ b/crates/ui-egui/tests/it/shared_docking_ui.rs
@@ -187,6 +187,46 @@ fn drag(h: &mut Harness<'_, FilmcraftApp>, from: egui::Pos2, to: egui::Pos2, mod
}
}
+fn keyboard_resize(h: &mut Harness<'_, FilmcraftApp>, grip_id: egui::Id) {
+ let before_keys = h.state().ui.dock.floating[0].rect;
+ for key in [egui::Key::ArrowRight, egui::Key::ArrowDown] {
+ for pressed in [true, false] {
+ h.event(Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE });
+ step(h);
+ }
+ }
+ assert_eq!(h.state().ui.dock.floating[0].rect[2], before_keys[2] + 8.0);
+ assert_eq!(h.state().ui.dock.floating[0].rect[3], before_keys[3] + 8.0);
+ h.event(Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
+ step(h);
+ h.event(Event::Key { key: egui::Key::Tab, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
+ for _ in 0..3 {
+ step(h);
+ }
+ assert_ne!(h.ctx.memory(|memory| memory.focused()), Some(grip_id));
+}
+
+fn maximize_frame_round_trip(h: &mut Harness<'_, FilmcraftApp>, action_log: &mut Vec<serde_json::Value>) {
+ let saved_root = h.state().ui.dock.clone();
+ let saved_floating = h.state().ui.dock.floating.clone();
+ let ctx = h.ctx.clone();
+ // Maximize Frame fills the area with a docked frame
+ h.state_mut().ui.focused = PanelKind::Program;
+ menus::invoke(h.state_mut(), &ctx, "window.maximizeFrame", json!({})).unwrap();
+ for _ in 0..3 {
+ step(h);
+ }
+ assert!(rect(h, "panel.Program").width() > 1000.0);
+ action_log.push(action_state(h, "maximized"));
+ assert_eq!(h.state().ui.dock, saved_root);
+ assert_eq!(h.state().ui.dock.floating, saved_floating);
+ menus::invoke(h.state_mut(), &ctx, "window.maximizeFrame", json!({})).unwrap();
+ for _ in 0..3 {
+ step(h);
+ }
+ assert_eq!(h.state().ui.dock.floating, saved_floating);
+}
+
#[test]
fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents() {
let mut session = Session::default();
@@ -249,22 +289,7 @@ fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents()
h.ctx.memory_mut(|memory| memory.request_focus(grip_id));
step(&mut h);
assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(grip_id));
- let before_keys = h.state().ui.dock.floating[0].rect;
- for key in [egui::Key::ArrowRight, egui::Key::ArrowDown] {
- for pressed in [true, false] {
- h.event(Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE });
- step(&mut h);
- }
- }
- assert_eq!(h.state().ui.dock.floating[0].rect[2], before_keys[2] + 8.0);
- assert_eq!(h.state().ui.dock.floating[0].rect[3], before_keys[3] + 8.0);
- h.event(Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
- step(&mut h);
- h.event(Event::Key { key: egui::Key::Tab, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
- for _ in 0..3 {
- step(&mut h);
- }
- assert_ne!(h.ctx.memory(|memory| memory.focused()), Some(grip_id));
+ keyboard_resize(&mut h, grip_id);
action_log.push(action_state(&h, "keyboard-resized"));
let resized = h.state().ui.dock.floating[0].rect;
let header = rect(&h, "panel.float.0.move");
@@ -273,24 +298,7 @@ fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents()
assert!(h.state().ui.dock.floating[0].rect[0] < resized[0] - 15.0);
assert!(h.state().ui.dock.floating[0].rect[1] < resized[1] - 10.0);
action_log.push(action_state(&h, "moved"));
- let saved_root = h.state().ui.dock.clone();
- let saved_floating = h.state().ui.dock.floating.clone();
- let ctx = h.ctx.clone();
- // Maximize Frame fills the area with a docked frame
- h.state_mut().ui.focused = PanelKind::Program;
- menus::invoke(h.state_mut(), &ctx, "window.maximizeFrame", json!({})).unwrap();
- for _ in 0..3 {
- step(&mut h);
- }
- assert!(rect(&h, "panel.Program").width() > 1000.0);
- action_log.push(action_state(&h, "maximized"));
- assert_eq!(h.state().ui.dock, saved_root);
- assert_eq!(h.state().ui.dock.floating, saved_floating);
- menus::invoke(h.state_mut(), &ctx, "window.maximizeFrame", json!({})).unwrap();
- for _ in 0..3 {
- step(&mut h);
- }
- assert_eq!(h.state().ui.dock.floating, saved_floating);
+ maximize_frame_round_trip(&mut h, &mut action_log);
if let Some(directory) = &snapshots {
std::fs::create_dir_all(directory).unwrap();
diff --git a/crates/ui-egui/tests/it/workspaces_ui.rs b/crates/ui-egui/tests/it/workspaces_ui.rs
index 16d554037..26374a5b5 100644
--- a/crates/ui-egui/tests/it/workspaces_ui.rs
+++ b/crates/ui-egui/tests/it/workspaces_ui.rs
@@ -145,6 +145,20 @@ fn saved_file(data: &Path) -> Value {
serde_json::from_slice(&std::fs::read(data.join("workspaces.json")).expect("workspaces.json written")).unwrap()
}
+fn built_in_keeps_saved_changes_and_restores(d: &mut Driver) {
+ // Save Changes to this Workspace on a built-in; it can't be deleted, only restored
+ d.ok("ui.set", json!({"workspace": "Assembly"}));
+ d.ok("ui.panel.close", json!({"panel": "History"}));
+ d.menu("window.workspace.saveChanges", json!({}));
+ d.ok("ui.set", json!({"workspace": "Cutting"}));
+ d.ok("ui.set", json!({"workspace": "Assembly"}));
+ assert!(!d.shows(PanelKind::History), "the built-in keeps its saved changes");
+ assert_eq!(d.menu("window.workspace.delete", json!({"name": "Assembly"}))["restored"], "Assembly");
+ assert!(d.shows(PanelKind::History), "restoring the current built-in shows its original layout");
+ assert!(d.menu_err("window.workspace.delete", json!({"name": "Assembly"})).contains("can't be deleted"));
+ assert!(d.menu_err("window.workspace.rename", json!({"from": "Assembly", "to": "Mine"})).contains("keeps its name"));
+}
+
#[test]
fn save_switch_reset_rename_delete_and_restart() {
let data = data_dir("cycle");
@@ -201,17 +215,7 @@ fn save_switch_reset_rename_delete_and_restart() {
d.menu("window.workspace.reset", json!({}));
assert!(d.shows(PanelKind::Project) && !d.shows(PanelKind::Metadata));
- // Save Changes to this Workspace on a built-in; it can't be deleted, only restored
- d.ok("ui.set", json!({"workspace": "Assembly"}));
- d.ok("ui.panel.close", json!({"panel": "History"}));
- d.menu("window.workspace.saveChanges", json!({}));
- d.ok("ui.set", json!({"workspace": "Cutting"}));
- d.ok("ui.set", json!({"workspace": "Assembly"}));
- assert!(!d.shows(PanelKind::History), "the built-in keeps its saved changes");
- assert_eq!(d.menu("window.workspace.delete", json!({"name": "Assembly"}))["restored"], "Assembly");
- assert!(d.shows(PanelKind::History), "restoring the current built-in shows its original layout");
- assert!(d.menu_err("window.workspace.delete", json!({"name": "Assembly"})).contains("can't be deleted"));
- assert!(d.menu_err("window.workspace.rename", json!({"from": "Assembly", "to": "Mine"})).contains("keeps its name"));
+ built_in_keeps_saved_changes_and_restores(&mut d);
// rename follows the current workspace
d.ok("ui.set", json!({"workspace": "Cutting"}));