FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
program monitor, effect controls: on-screen transform handles for Motion and Transform (#639)
ReReddoee6415a1dd98
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 20925268f..a88405b47 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -2717,6 +2717,16 @@ fn build() -> Vec<CommandSpec> {cmd!("effects.remove", "Remove Effect", [], None, r#"{"clip":id,"index":n}"#, has_seq, |s, p| {let c = clip_p(p, "clip").ok_or_else(|| bad("effects.remove", "need `clip`"))?;let idx = u64_p(p, "index").ok_or_else(|| bad("effects.remove", "need `index`"))? as usize;+ // the selected effect: where it is, and its selection once the effect at `idx` is gone+ let effects = s.active_sequence().and_then(|q| q.find_item(c)).map(|(_, it)| it.effects.clone()).unwrap_or_default();+ let sel = s.state.selected_effect.clone().filter(|e| e.clip == c).and_then(|e| e.index(&effects));+ let after = sel.filter(|i| *i != idx).and_then(|i| {+ let mut rest = effects;+ if idx < rest.len() {+ rest.remove(idx);+ }+ crate::EffectSel::of(c, &rest, if i > idx { i - 1 } else { i })+ });s.edit_sequence("Remove Effect", |q, _, _| {let (_, it) = q.find_item_mut(c).ok_or(filmcraft_edit::EditError::NoItem(c))?;if it.effects.get(idx).and_then(|e| e.def()).is_some_and(|d| d.intrinsic) {@@ -2727,14 +2737,27 @@ fn build() -> Vec<CommandSpec> {}Ok(())})?;+ if sel.is_some() {+ s.state.selected_effect = after;+ }Ok(Value::Null)}),+ CommandSpec {+ id: "effects.select",+ label: "Select Effect",+ menu: &[],+ shortcut: None,+ params: r#"{"clip":id,"effect":index|id}|{"none":true}"#,+ enabled: has_seq,+ run: select_effect,+ journal: false,+ },cmd!("effects.setParam","Set Effect Parameter",[],None,- r##"{"clip":id,"effect":"motion"|index,"param":str,"mask":n?,"value":num|[x,y]|"#rrggbb"|bool|path|"option name" (a choice takes its index or its name),"time":ticks? (where the keyframe goes when the parameter is animated, kept there even outside the clip; default: the playhead, pinned to the clip; a parameter that is not animated gets a new static value whatever the time),"keyframe":bool? (true: write a keyframe at `time` and animate the parameter),"merge":bool?,"begin":bool?}"##,+ r##"{"clip":id,"effect":"motion"|index,"param":str,"mask":n?,"value":num|[x,y]|"#rrggbb"|bool|path|"option name" (a choice takes its index or its name),"time":ticks? (where the keyframe goes when the parameter is animated, kept there even outside the clip; default: the playhead, pinned to the clip; a parameter that is not animated gets a new static value whatever the time),"keyframe":bool? (true: write a keyframe at `time` and animate the parameter),"merge":bool|key?,"begin":bool?}"##,has_seq,|s, p| {let c = clip_p(p, "clip").ok_or_else(|| bad("effects.setParam", "need `clip`"))?;@@ -2747,8 +2770,12 @@ fn build() -> Vec<CommandSpec> {let at = time_p(s, p, "");let ph = s.playhead();let pq = p.clone();- // `merge`: a drag of one parameter is one undo step (#201); `begin` starts a new one- let merge = bool_p(p, "merge").unwrap_or(false).then(|| format!("setParam:{}:{eff}:{pid}:{}", c.0, p.get("mask").unwrap_or(&Value::Null)));+ // `merge`: a drag of one parameter is one undo step (#201), and a key makes one of a+ // drag that changes several (the Program monitor's handles); `begin` starts a new one+ let merge = match p.get("merge") {+ Some(Value::String(key)) => Some(format!("setParam:{}:{key}", c.0)),+ _ => bool_p(p, "merge").unwrap_or(false).then(|| format!("setParam:{}:{eff}:{pid}:{}", c.0, p.get("mask").unwrap_or(&Value::Null))),+ };if bool_p(p, "begin").unwrap_or(false) {s.history.merge_key = None;}@@ -3629,6 +3656,28 @@ fn transition_ids_p(v: &Value) -> Option<Vec<TransitionId>> {}}+/// `effects.select`: the effect selected in Effect Controls (`effect`: index, or the id of the+/// clip's first effect of that kind). It replaces the mask selection.+fn select_effect(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "effects.select";+ if bool_p(p, "none") == Some(true) {+ s.state.selected_effect = None;+ return Ok(Value::Null);+ }+ let clip = clip_p(p, "clip").ok_or_else(|| bad(CMD, "need `clip` (or `none`)"))?;+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let (_, it) = q.find_item(clip).ok_or_else(|| bad(CMD, "no such clip"))?;+ let effect = match p.get("effect") {+ Some(Value::Number(n)) => n.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < it.effects.len()),+ Some(Value::String(id)) => it.effects.iter().position(|e| &e.effect == id),+ _ => None,+ }+ .ok_or_else(|| bad(CMD, "no such effect on clip"))?;+ s.state.selected_effect = crate::EffectSel::of(clip, &it.effects, effect);+ s.state.selected_mask = None;+ Ok(Value::Null)+}+/// `timeline.select {"transitions": […]}`: select transitions (clicking one in the Timeline). It/// replaces the clip, edit point and caption selections, as a clip selection replaces it.fn select_transitions(s: &mut Session, ids: &Value, add: bool, toggle: bool) -> Result<Value> {diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 2e265707c..b6b85243b 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -234,6 +234,29 @@ pub struct GapSelection {pub range: TimeRange,}+/// An effect of a clip (`effects.select`): its id and which of the clip's effects with that id it+/// is (0 = the first). Not its index, which applying an effect shifts (standard effects go first).+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct EffectSel {+ pub clip: ClipId,+ pub effect: String,+ pub instance: usize,+}++impl EffectSel {+ /// The selection of `effects[index]` of `clip`.+ pub fn of(clip: ClipId, effects: &[filmcraft_project::EffectInstance], index: usize) -> Option<Self> {+ let id = &effects.get(index)?.effect;+ let instance = effects.iter().take(index).filter(|e| &e.effect == id).count();+ Some(Self { clip, effect: id.clone(), instance })+ }++ /// Where the selected effect is in the clip's `effects`.+ pub fn index(&self, effects: &[filmcraft_project::EffectInstance]) -> Option<usize> {+ effects.iter().enumerate().filter(|(_, e)| e.effect == self.effect).nth(self.instance).map(|(i, _)| i)+ }+}+/// Editing state that commands depend on (not project data, but headless-relevant).#[derive(Clone, Debug, Default, Serialize, Deserialize)]pub struct EditorState {@@ -295,6 +318,11 @@ pub struct EditorState {/// The mask being edited on the Program monitor (Effect Controls selection).#[serde(default)]pub selected_mask: Option<masks::MaskSel>,+ /// The effect selected in Effect Controls (its header or one of its properties): Motion and+ /// Transform show their handles on the Program monitor. Selecting a mask clears it, and+ /// selecting an effect clears the mask selection.+ #[serde(default)]+ pub selected_effect: Option<EffectSel>,/// Multi-Camera Audio Follows Video: switching a multi-camera clip's angle switches its linked/// audio clips too.#[serde(default)]@@ -940,6 +968,11 @@ impl Session {self.state.selected_mask = None;}}+ if let Some(e) = &self.state.selected_effect+ && self.active_sequence().and_then(|q| q.find_item(e.clip)).and_then(|(_, it)| e.index(&it.effects)).is_none()+ {+ self.state.selected_effect = None;+ }if let Some(s) = self.state.active_sequence&& p.sequence(s).is_none(){diff --git a/crates/engine/src/masks.rs b/crates/engine/src/masks.rsindex 37da8ac09..7dedd9c35 100644--- a/crates/engine/src/masks.rs+++ b/crates/engine/src/masks.rs@@ -247,6 +247,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {e.masks.push(Mask::new(name.clone(), path));let mi = e.masks.len() - 1;st.selected_mask = Some(MaskSel { clip, effect: ei, mask: mi });+ st.selected_effect = None;Ok((ei, mi, name))})?;Ok(json!({"clip": clip.0, "effect": ei, "mask": mi, "name": name}))@@ -511,6 +512,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad("masks.select", format!("no mask {mi}")));}s.state.selected_mask = Some(MaskSel { clip, effect: ei, mask: mi });+ s.state.selected_effect = None;Ok(Value::Null)}diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex c95b5ac0c..fe3e35133 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -870,6 +870,81 @@ fn dragging_an_effect_parameter_is_one_undo_step() {assert_eq!(opacity(&s), start, "and then the whole first one");}+/// #639: a drag that changes several parameters (the anchor point and the position) shares one+/// undo step when its changes carry the same `merge` key.+#[test]+fn a_merge_key_folds_several_parameters_into_one_undo_step() {+ let mut s = demo_unlocked();+ let id = v1(&s)[0].0;+ let motion = |s: &Session| {+ let it = s.active_sequence().unwrap().find_item(ClipId(id)).unwrap().1.clone();+ let e = it.effect("motion").unwrap().clone();+ (e.params["anchor"].value.clone(), e.params["position"].value.clone())+ };+ let start = motion(&s);+ let undo = s.history.undo.len();+ for (i, d) in [10.0, 20.0, 30.0].into_iter().enumerate() {+ for param in ["anchor", "position"] {+ let p = json!({"clip": id, "effect": "motion", "param": param, "value": [500.0 + d, 300.0 + d], "merge": "programTransform", "begin": i == 0 && param == "anchor"});+ s.execute("effects.setParam", p).unwrap();+ }+ }+ assert_eq!(s.history.undo.len(), undo + 1);+ assert_eq!(motion(&s).1, filmcraft_project::ParamValue::Vec2(filmcraft_geom::Vec2::new(530.0, 330.0)));+ s.undo();+ assert_eq!(motion(&s), start);+}++/// #639: `effects.select` names the effect whose handles the Program monitor shows. It and the+/// mask selection replace each other; undo or removal that takes the effect away clears it.+#[test]+fn selecting_an_effect_replaces_the_mask_selection() {+ let mut s = demo_unlocked();+ let id = v1(&s)[0].0;+ let motion_sel = Some(EffectSel { clip: ClipId(id), effect: "motion".into(), instance: 0 });+ s.execute("effects.select", json!({"clip": id, "effect": "motion"})).unwrap();+ assert_eq!(s.state.selected_effect, motion_sel);+ // applying an effect puts it first; Motion stays the selected effect+ s.execute("effects.apply", json!({"clips": [id], "effect": "gaussian_blur"})).unwrap();+ assert_eq!(s.state.selected_effect, motion_sel);+ s.execute("effects.remove", json!({"clip": id, "index": 0})).unwrap();+ assert_eq!(s.state.selected_effect, motion_sel, "and when one before it is removed");+ let motion = s.active_sequence().unwrap().find_item(ClipId(id)).unwrap().1.effects.iter().position(|e| e.effect == "motion").unwrap();+ s.execute("masks.add", json!({"clip": id, "shape": "ellipse"})).unwrap();+ assert!(s.state.selected_effect.is_none(), "a new mask is selected instead");+ s.execute("effects.select", json!({"clip": id, "effect": motion})).unwrap();+ assert!(s.state.selected_mask.is_none());+ s.execute("masks.select", json!({"clip": id, "effect": "opacity", "mask": 0})).unwrap();+ assert!(s.state.selected_effect.is_none());+ s.execute("effects.select", json!({"none": true})).unwrap();+ assert!(s.state.selected_effect.is_none());+ // an applied effect that undo takes away, and one removed+ s.execute("effects.apply", json!({"clips": [id], "effect": "transform"})).unwrap();+ s.execute("effects.select", json!({"clip": id, "effect": "transform"})).unwrap();+ assert!(s.state.selected_effect.is_some());+ s.undo();+ assert!(s.state.selected_effect.is_none(), "selection follows undo");+ s.redo();+ s.execute("effects.select", json!({"clip": id, "effect": "transform"})).unwrap();+ let effects = s.active_sequence().unwrap().find_item(ClipId(id)).unwrap().1.effects.clone();+ let index = s.state.selected_effect.as_ref().unwrap().index(&effects).unwrap();+ s.execute("effects.remove", json!({"clip": id, "index": index})).unwrap();+ assert!(s.state.selected_effect.is_none());+ // hostile parameters are errors, not panics+ for p in [+ json!({}),+ json!({"clip": id}),+ json!({"clip": id, "effect": 9999}),+ json!({"clip": id, "effect": -1}),+ json!({"clip": id, "effect": u64::MAX}),+ json!({"clip": id, "effect": "no_such_effect"}),+ json!({"clip": u64::MAX, "effect": 0}),+ json!({"clip": "x", "effect": 0}),+ ] {+ assert!(s.execute("effects.select", p.clone()).is_err(), "{p}");+ }+}+/// The demo's first video transition between two clips: (id, start, duration, cut).fn demo_crossing(s: &Session) -> (u64, Tick, Tick, Tick) {let q = s.active_sequence().unwrap();diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rsindex 72d676163..fa5dd791e 100644--- a/crates/ui-egui/src/panels/effect_controls.rs+++ b/crates/ui-egui/src/panels/effect_controls.rs@@ -157,17 +157,19 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {let Some(def) = e.def() else { continue };let key = format!("{}:{}", clip.0, idx);let open = !app.ui.collapsed_fx.contains(&key);+ let selected = app.session.state.selected_effect.as_ref().is_some_and(|s| s.clip == clip && s.index(&it.effects) == Some(idx));let (r, resp) = bui.allocate_exact_size(vec2(body.width(), ROW_H), Sense::click());- if resp.hovered() {+ if selected {+ bui.painter().rect_filled(r, 0.0, t.row_selected);+ } else if resp.hovered() {bui.painter().rect_filled(r, 0.0, t.hover);}row_line(bui, r, &lane, &t);- icons::paint(- bui.painter(),- Rect::from_center_size(pos2(r.min.x + 10.0, r.center().y), vec2(10.0, 10.0)),- if open { Icon::ChevronDown } else { Icon::ChevronRight },- t.text_dim,- );+ // only the arrow twirls the effect open or shut; the rest of the header selects it+ let tw = Rect::from_center_size(pos2(r.min.x + 10.0, r.center().y), vec2(10.0, 10.0));+ icons::paint(bui.painter(), tw, if open { Icon::ChevronDown } else { Icon::ChevronRight }, t.text_dim);+ let twresp = bui.interact(tw.expand(3.0), egui::Id::new(("fx-twirl", clip.0, idx)), Sense::click());+ app.auto.add(&format!("effectControls.effect.{}.twirl", e.effect), tw, "twirl");// fx enable togglelet fxr = Rect::from_center_size(pos2(r.min.x + 28.0, r.center().y), vec2(18.0, 14.0));let fxresp = bui.interact(fxr, egui::Id::new(("fxen", clip.0, idx)), Sense::click());@@ -188,12 +190,14 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {actions.push(("effects.reset".into(), json!({"clip": clip.0, "index": idx})));}app.auto.add(&format!("effectControls.effect.{}", e.effect), r, def.name);- if resp.clicked() && !fxresp.clicked() && !rresp.clicked() {+ if twresp.clicked() {if open {app.ui.collapsed_fx.push(key.clone());} else {app.ui.collapsed_fx.retain(|k| *k != key);}+ } else if resp.clicked() && !fxresp.clicked() && !rresp.clicked() {+ actions.push(("effects.select".into(), json!({"clip": clip.0, "effect": idx})));}let mut save_preset = false;let fx_id = e.effect.clone();@@ -490,8 +494,12 @@ pub(crate) fn param_row(}v};- let (r, _) = ui.allocate_exact_size(vec2(body.width(), ROW_H), Sense::hover());+ let (r, row) = ui.allocate_exact_size(vec2(body.width(), ROW_H), if mask.is_none() { Sense::click() } else { Sense::hover() });row_line(ui, r, lane, &t);+ // clicking one of an effect's properties selects the effect, as clicking its header does+ if row.clicked() {+ actions.push(("effects.select".into(), json!({"clip": clip.0, "effect": idx})));+ }let mut x = r.min.x + 26.0;// twirl-down for the value/velocity graphs (animated scalar and point params)if param.is_animated() && graphable(¶m.value) {@@ -979,7 +987,9 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {/// press begins (#201); typed values and clicks stay separate steps. A drag value only changes once/// the mouse moves, after the press frame, so the press that already began a step is remembered by/// its start time. That memory is refreshed on every frame the button stays down — including frames-/// with no value change — so a Scale scrub that pauses between percents is still one undo (#887).+/// with no value change — so a Scale scrub that pauses between percents is still one undo (#887). A+/// change that brings its own `merge` key (a Program monitor handle changing several parameters)+/// keeps it.pub(crate) fn run(app: &mut FilmcraftApp, ctx: &egui::Context, actions: Vec<(String, Value)>) {let (down, press) = ctx.input(|i| (i.pointer.any_down(), i.pointer.press_start_time()));let key = egui::Id::new("effect-controls-drag-step");@@ -987,7 +997,9 @@ pub(crate) fn run(app: &mut FilmcraftApp, ctx: &egui::Context, actions: Vec<(Strlet mut wrote = false;for (cmd, mut p) in actions {if cmd == "effects.setParam" && down {- p["merge"] = json!(true);+ if p.get("merge").is_none() {+ p["merge"] = json!(true);+ }p["begin"] = json!(begun != press);wrote = true;}diff --git a/crates/ui-egui/src/panels/graphics.rs b/crates/ui-egui/src/panels/graphics.rsindex 5a27ba074..ec813378f 100644--- a/crates/ui-egui/src/panels/graphics.rs+++ b/crates/ui-egui/src/panels/graphics.rs@@ -54,11 +54,11 @@ impl LayerView {let v = self.to_screen.inverse()?.apply(Vec2::new(p.x as f64, p.y as f64));Some((v.x as f32, v.y as f32))}- fn hit(&self, p: Pos2) -> bool {+ pub(crate) fn hit(&self, p: Pos2) -> bool {let pad = 4.0 / screen_scale(&self.to_screen).max(1e-6);self.to_local(p).is_some_and(|(x, y)| x >= self.local[0] - pad && x <= self.local[2] + pad && y >= self.local[1] - pad && y <= self.local[3] + pad)}- fn is_text(&self) -> bool {+ pub(crate) fn is_text(&self) -> bool {matches!(self.spec.content, LayerContent::Text(_))}}@@ -91,7 +91,7 @@ pub fn selected_graphic(app: &FilmcraftApp) -> Option<(ClipId, TrackItem)> {/// visibility is off is not in the picture, so it has no box and cannot be clicked either./// Sequence pixels → screen points on the monitor picture `pic`. The picture shows the frame at its/// display aspect, so with non-square sequence pixels the two axes scale differently.-fn frame_to_screen(pic: Rect, frame: (u32, u32)) -> Affine {+pub(crate) fn frame_to_screen(pic: Rect, frame: (u32, u32)) -> Affine {let (kx, ky) = (pic.width() as f64 / frame.0.max(1) as f64, pic.height() as f64 / frame.1.max(1) as f64);Affine::translate(pic.min.x as f64, pic.min.y as f64).then_apply(&Affine::scale(kx, ky))}@@ -184,7 +184,7 @@ struct DragState {/// The eight handles of a layer's box `quad` (TL, TR, BR, BL): the corners (0–3), then the middles/// of the top, right, bottom and left edges (4–7).-fn handle_points(quad: &[Pos2; 4]) -> [Pos2; 8] {+pub(crate) fn handle_points(quad: &[Pos2; 4]) -> [Pos2; 8] {let mid = |i: usize| quad[i] + (quad[(i + 1) % 4] - quad[i]) * 0.5;[quad[0], quad[1], quad[2], quad[3], mid(0), mid(1), mid(2), mid(3)]}@@ -470,7 +470,7 @@ fn anchor_screen(v: &LayerView) -> Pos2 {}/// A screen offset in the units `m` maps to the screen (its translation left out).-fn unscale(m: &Affine, off: egui::Vec2) -> Vec2 {+pub(crate) fn unscale(m: &Affine, off: egui::Vec2) -> Vec2 {Affine { e: 0.0, f: 0.0, ..*m }.inverse().map(|i| i.apply(Vec2::new(off.x as f64, off.y as f64))).unwrap_or_default()}diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex cc8926ffe..e1d8aef74 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -49,6 +49,7 @@ pub mod timeline_captions;pub mod timeline_hit;pub mod timeline_volume;pub mod tools;+pub mod transform_handles;pub mod transition_controls;pub mod trim_monitor;pub mod tts;diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rsindex 8f565a138..ec00e5cc3 100644--- a/crates/ui-egui/src/panels/monitor.rs+++ b/crates/ui-egui/src/panels/monitor.rs@@ -298,6 +298,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)eyedropper(app, ui, &pic_resp, pic, target, rate, time);crate::panels::graphics::monitor_overlay(app, ui, pic, frame_size);crate::panels::masks::monitor_overlay(app, ui, pic, frame_size);+ crate::panels::transform_handles::monitor_overlay(app, ui, pic, frame_size);}if show_picture {monitor_view::guides(app, ui, which, video_area, pic, frame_size);diff --git a/crates/ui-egui/src/panels/transform_handles.rs b/crates/ui-egui/src/panels/transform_handles.rsnew file mode 100644index 000000000..4d713aa93--- /dev/null+++ b/crates/ui-egui/src/panels/transform_handles.rs@@ -0,0 +1,394 @@+//! On-screen transform handles on the Program monitor (#639). Selecting Motion in Effect Controls+//! (its header or one of its properties), or double-clicking a clip's picture in the Program+//! monitor, draws a box around the clip's picture with eight handles and the anchor point. The+//! Transform effect gets the same box for its own properties while it is the selected effect.+//!+//! Dragging inside the box changes Position. A handle changes Scale about the anchor point; with+//! Uniform Scale off a side handle changes only the width and a top or bottom handle only the+//! height. Dragging just outside a corner changes Rotation. The anchor point moves without moving+//! the picture: Position changes by the same amount. The values go through `effects.setParam` at+//! the playhead while the drag goes on, as dragging them in Effect Controls does, so a property+//! with its stopwatch on gets a keyframe there, and one drag is one undo step.+//!+//! Automation ids: `program.transform.box`, `program.transform.handle.<n>` (0–3 the corners TL,+//! TR, BR, BL, 4–7 the middles of the top, right, bottom and left edges, as for graphic layers),+//! `program.transform.rotate.<n>` (just outside corner `n`), `program.transform.anchor`.++use egui::{Color32, CursorIcon, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};+use filmcraft_geom::{Affine, Vec2};+use filmcraft_project::{ClipId, EffectDef, EffectInstance, TrackItem};+use filmcraft_time::Tick;+use serde_json::{Value, json};++use crate::FilmcraftApp;+use crate::icons::{self, Icon};+use crate::panels::graphics::{frame_to_screen, handle_points, unscale};+use crate::state::Tool;++/// How close (in points) the pointer must be to a handle or the anchor point to grab it: well+/// beyond the drawn squares, so the small handles stay easy to take hold of.+const GRAB: f32 = 8.0;+/// The drawn handles, a little smaller than the graphic layers' (7 and 5 points) for precision:+/// the side of a corner square and of an edge square, and the anchor point's circle radius and+/// cross arm.+const CORNER: f32 = 5.0;+const EDGE: f32 = 4.0;+const ANCHOR_RADIUS: f32 = 3.0;+const ANCHOR_ARM: f32 = 5.0;+/// How far from a corner, outside the box, the pointer rotates the picture.+const ROTATE_REACH: f32 = 24.0;+/// The `merge` key of a drag's changes: one undo step, whichever parameters the drag changes.+const MERGE: &str = "programTransform";++/// What a press on the box takes hold of.+#[derive(Clone, Copy, Debug, PartialEq)]+enum Grab {+ Move,+ /// Handle `n` (see [`handle_points`]).+ Handle(usize),+ Rotate,+ Anchor,+}++/// The selected effect's box on the monitor and the values it is drawn from.+#[derive(Clone, Copy, Debug)]+struct Placement {+ /// Where the effect's Position is measured → screen: the sequence frame for Motion, the clip+ /// (through Motion) for Transform.+ outer: Affine,+ /// Clip pixels → screen.+ to_screen: Affine,+ /// The picture's box: TL, TR, BR, BL.+ quad: [Pos2; 4],+ anchor_at: Pos2,+ position: Vec2,+ anchor: Vec2,+ /// Scale (Motion) or Scale Height (Transform), and Scale Width, in percent.+ height: f64,+ width: f64,+ rotation: f64,+ uniform: bool,+}++/// A clip and the index of one of its effects.+type Target = (ClipId, usize);++#[derive(Clone, Copy, Debug)]+struct Drag {+ sel: Target,+ grab: Grab,+ /// Where the button went down, and the box then: every frame of the drag sets the values the+ /// pointer's travel from there gives.+ start: Pos2,+ from: Placement,+ /// Rotate: the pointer's angle about the anchor point last frame and the turn so far, in+ /// degrees (a drag can go round more than once).+ angle: f64,+ turned: f64,+}++/// Scale's parameter: Motion's `scale` is the height when Uniform Scale is off.+fn height_param(effect: &str) -> &'static str {+ if effect == "transform" { "scale_height" } else { "scale" }+}++fn sp(m: &Affine, v: Vec2) -> Pos2 {+ let q = m.apply(v);+ pos2(q.x as f32, q.y as f32)+}++/// The box of a clip `size` pixels large that `m` places on the screen.+fn quad_of(m: &Affine, size: (u32, u32)) -> [Pos2; 4] {+ let (w, h) = (f64::from(size.0), f64::from(size.1));+ [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| sp(m, Vec2::new(x, y)))+}++fn inside(quad: &[Pos2; 4], p: Pos2) -> bool {+ let sides = quad.iter().zip(quad.iter().cycle().skip(1)).map(|(a, b)| (*b - *a).x * (p - *a).y - (*b - *a).y * (p - *a).x);+ let (mut pos, mut neg) = (false, false);+ for s in sides {+ pos |= s > 0.0;+ neg |= s < 0.0;+ }+ pos != neg+}++/// The box of effect `e` (Motion or Transform) of clip `it` at media time `mt`, on the monitor+/// picture `pic` showing a `frame`-sized sequence.+fn placement(app: &FilmcraftApp, it: &TrackItem, e: &EffectInstance, mt: Tick, pic: Rect, frame: (u32, u32)) -> Option<Placement> {+ let seq = app.session.active_sequence()?;+ let project = &app.session.project;+ let size = filmcraft_render::source_size(project, it.item).unwrap_or(frame);+ let view = frame_to_screen(pic, frame);+ let motion = view.then_apply(&filmcraft_render::motion_matrix(seq, it, size, filmcraft_render::source_par(project, it.item), mt));+ // "auto" points (NaN) are where the render puts them+ let point = |id: &str, auto: Vec2| {+ let v = e.param(id).map_or(auto, |p| p.vec2_at(mt));+ Vec2::new(if v.x.is_nan() { auto.x } else { v.x }, if v.y.is_nan() { auto.y } else { v.y })+ };+ let centre = Vec2::new(f64::from(size.0) / 2.0, f64::from(size.1) / 2.0);+ let uniform = e.param("uniform_scale").and_then(|p| p.value.as_bool()).unwrap_or(true);+ let (height, width, rotation) = (e.f64_at(height_param(&e.effect), mt), e.f64_at("scale_width", mt), e.f64_at("rotation", mt));+ let (outer, to_screen, position, anchor) = if e.effect == "transform" {+ let (anchor, position) = (point("anchor", centre), point("position", centre));+ let (sh, sw) = (height / 100.0, if uniform { height } else { width } / 100.0);+ // as the render places it (`filmcraft_render::gpufx`, "transform")+ let axis = e.f64_at("skew_axis", mt);+ let shear = Affine { c: e.f64_at("skew", mt).to_radians().tan(), ..Affine::IDENTITY };+ let skew = Affine::rotate_deg(axis).then_apply(&shear).then_apply(&Affine::rotate_deg(-axis));+ let own = Affine::translate(position.x, position.y)+ .then_apply(&Affine::rotate_deg(rotation))+ .then_apply(&skew)+ .then_apply(&Affine::scale(sw, sh))+ .then_apply(&Affine::translate(-anchor.x, -anchor.y));+ (motion, motion.then_apply(&own), position, anchor)+ } else {+ let frame_centre = Vec2::new(f64::from(seq.settings.width) / 2.0, f64::from(seq.settings.height) / 2.0);+ (view, motion, point("position", frame_centre), point("anchor", centre))+ };+ let quad = quad_of(&to_screen, size);+ let anchor_at = sp(&to_screen, anchor);+ quad.iter().chain([&anchor_at]).all(|p| p.x.is_finite() && p.y.is_finite()).then_some(Placement {+ outer,+ to_screen,+ quad,+ anchor_at,+ position,+ anchor,+ height,+ width,+ rotation,+ uniform,+ })+}++/// The selected effect (its clip and index) and its box, while it is Motion or Transform of a+/// selected clip under the playhead.+fn selected_placement(app: &FilmcraftApp, pic: Rect, frame: (u32, u32)) -> Option<(Target, &'static EffectDef, Placement)> {+ let sel = app.session.state.selected_effect.as_ref()?;+ if !app.session.state.selection.contains(&sel.clip) {+ return None;+ }+ let seq = app.session.active_sequence()?;+ let ph = app.session.playhead();+ let (_, it) = seq.find_item(sel.clip)?;+ if !it.range().contains(ph) {+ return None;+ }+ let index = sel.index(&it.effects)?;+ let e = it.effects.get(index).filter(|e| e.enabled)?;+ let def = e.def().filter(|d| d.id == "motion" || d.id == "transform")?;+ let pl = placement(app, it, e, it.source_time_at(ph), pic, frame)?;+ Some(((sel.clip, index), def, pl))+}++fn grab_at(pl: &Placement, p: Pos2) -> Option<Grab> {+ if (pl.anchor_at - p).length() <= GRAB {+ return Some(Grab::Anchor);+ }+ if let Some(n) = handle_points(&pl.quad).iter().position(|h| (*h - p).length() <= GRAB) {+ return Some(Grab::Handle(n));+ }+ if inside(&pl.quad, p) {+ return Some(Grab::Move);+ }+ pl.quad.iter().any(|c| (*c - p).length() <= ROTATE_REACH).then_some(Grab::Rotate)+}++/// The scale factors (width, height) dragging handle `n` from `start` to `cur` gives: the+/// pointer's distance from the anchor point along the box's sides, relative to where it started.+fn scale_factors(pl: &Placement, n: usize, start: Pos2, cur: Pos2) -> (f64, f64) {+ let [tl, tr, _, bl] = pl.quad;+ let (ux, uy) = ((tr - tl).normalized(), (bl - tl).normalized());+ let (from, to) = (start - pl.anchor_at, cur - pl.anchor_at);+ let along = |dir: egui::Vec2| {+ let a = from.dot(dir);+ if a.abs() < 1.0 { 1.0 } else { f64::from((to.dot(dir) / a).max(0.0)) }+ };+ match (n, pl.uniform) {+ (0..=3, true) => {+ let f = along(from.normalized());+ (f, f)+ }+ (0..=3, false) => (along(ux), along(uy)),+ (4 | 6, true) => (along(uy), along(uy)),+ (4 | 6, false) => (1.0, along(uy)),+ (_, true) => (along(ux), along(ux)),+ (_, false) => (along(ux), 1.0),+ }+}++/// The parameter values a drag sets with the pointer at `cur`.+fn changes(d: &Drag, effect: &str, cur: Pos2) -> Vec<(&'static str, Value)> {+ let pl = &d.from;+ let moved = cur - d.start;+ // the ranges Effect Controls' fields take+ let point = |v: Vec2| (v.x.is_finite() && v.y.is_finite()).then(|| json!([v.x.clamp(-100_000.0, 100_000.0), v.y.clamp(-100_000.0, 100_000.0)]));+ let number = |v: f64, max: f64| v.is_finite().then(|| json!(v.clamp(-max, max)));+ let scale = |v: f64| v.is_finite().then(|| json!(v.clamp(0.0, 10_000.0)));+ let out = match d.grab {+ Grab::Move => vec![("position", point(pl.position + unscale(&pl.outer, moved)))],+ Grab::Anchor => vec![("anchor", point(pl.anchor + unscale(&pl.to_screen, moved))), ("position", point(pl.position + unscale(&pl.outer, moved)))],+ Grab::Handle(n) => {+ let (fx, fy) = scale_factors(pl, n, d.start, cur);+ let (height, width) = (height_param(effect), "scale_width");+ match n {+ _ if pl.uniform => vec![(height, scale(pl.height * fy))],+ 4 | 6 => vec![(height, scale(pl.height * fy))],+ 5 | 7 => vec![(width, scale(pl.width * fx))],+ _ => vec![(height, scale(pl.height * fy)), (width, scale(pl.width * fx))],+ }+ }+ Grab::Rotate => vec![("rotation", number(pl.rotation + d.turned, 36_000.0))],+ };+ out.into_iter().filter_map(|(param, v)| Some((param, v?))).collect()+}++/// The resize cursor for a handle in direction `v` from the box's centre.+fn resize_cursor(v: egui::Vec2) -> CursorIcon {+ let deg = v.y.atan2(v.x).to_degrees().rem_euclid(180.0);+ if !(22.5..157.5).contains(°) {+ CursorIcon::ResizeHorizontal+ } else if deg < 67.5 {+ CursorIcon::ResizeNwSe+ } else if deg < 112.5 {+ CursorIcon::ResizeVertical+ } else {+ CursorIcon::ResizeNeSw+ }+}++fn centre(quad: &[Pos2; 4]) -> Pos2 {+ let [tl, _, br, _] = *quad;+ tl + (br - tl) * 0.5+}++fn angle_deg(v: egui::Vec2) -> f64 {+ f64::from(v.y.atan2(v.x).to_degrees())+}++fn draw(app: &mut FilmcraftApp, ui: &egui::Ui, pl: &Placement, pic: Rect, name: &str) {+ let accent = app.tokens.accent;+ let painter = ui.painter().with_clip_rect(pic.expand(12.0));+ painter.add(egui::Shape::closed_line(pl.quad.to_vec(), Stroke::new(1.0, accent)));+ app.auto.add("program.transform.box", Rect::from_points(&pl.quad), name);+ let mid = centre(&pl.quad);+ // automation rects: the square inside the circle a press grabs in+ let grab = vec2(GRAB, GRAB) * std::f32::consts::SQRT_2;+ for (n, c) in pl.quad.iter().enumerate() {+ let hr = Rect::from_center_size(*c, vec2(CORNER, CORNER));+ painter.rect_filled(hr, 0.0, Color32::WHITE);+ painter.rect_stroke(hr, 0.0, Stroke::new(1.0, accent), StrokeKind::Middle);+ app.auto.add(&format!("program.transform.handle.{n}"), Rect::from_center_size(*c, grab), "scale handle");+ // just outside the corner, away from the box's centre+ let out = (*c - mid).normalized();+ app.auto.add(&format!("program.transform.rotate.{n}"), Rect::from_center_size(*c + out * 14.0, vec2(10.0, 10.0)), "rotate");+ }+ for (n, m) in handle_points(&pl.quad).iter().enumerate().skip(4) {+ painter.rect_filled(Rect::from_center_size(*m, vec2(EDGE, EDGE)), 0.0, Color32::WHITE);+ app.auto.add(&format!("program.transform.handle.{n}"), Rect::from_center_size(*m, grab), "scale handle");+ }+ let a = pl.anchor_at;+ painter.circle_stroke(a, ANCHOR_RADIUS, Stroke::new(1.0, accent));+ painter.line_segment([a - vec2(ANCHOR_ARM, 0.0), a + vec2(ANCHOR_ARM, 0.0)], Stroke::new(1.0, accent));+ painter.line_segment([a - vec2(0.0, ANCHOR_ARM), a + vec2(0.0, ANCHOR_ARM)], Stroke::new(1.0, accent));+ app.auto.add("program.transform.anchor", Rect::from_center_size(a, grab), "anchor point");+}++/// The pointer for what it would take hold of at `at` (or has hold of). There is no system+/// cursor for rotating, so a code-drawn one replaces it there.+fn cursor(ui: &egui::Ui, pl: &Placement, grab: Grab, at: Pos2, pic: Rect) {+ let icon = match grab {+ Grab::Move | Grab::Anchor => CursorIcon::Move,+ Grab::Handle(n) => handle_points(&pl.quad).get(n).map_or(CursorIcon::Move, |h| resize_cursor(*h - centre(&pl.quad))),+ Grab::Rotate => {+ let painter = ui.painter().with_clip_rect(pic.expand(16.0));+ let r = Rect::from_center_size(at, vec2(16.0, 16.0));+ icons::paint(&painter, r.translate(vec2(1.0, 1.0)), Icon::Reset, Color32::BLACK);+ icons::paint(&painter, r, Icon::Reset, Color32::WHITE);+ CursorIcon::None+ }+ };+ ui.ctx().set_cursor_icon(icon);+}++/// The top-most clip at the playhead whose picture is under `p`.+fn clip_under(app: &FilmcraftApp, pic: Rect, frame: (u32, u32), p: Pos2) -> Option<ClipId> {+ let seq = app.session.active_sequence()?;+ let t = app.session.playhead();+ let view = frame_to_screen(pic, frame);+ let project = &app.session.project;+ seq.video_tracks.iter().rev().filter(|tr| tr.enabled).filter_map(|tr| tr.item_at(t)).filter(|it| it.enabled).find_map(|it| {+ let size = filmcraft_render::source_size(project, it.item).unwrap_or(frame);+ let m = view.then_apply(&filmcraft_render::motion_matrix(seq, it, size, filmcraft_render::source_par(project, it.item), it.source_time_at(t)));+ inside(&quad_of(&m, size), p).then_some(it.id)+ })+}++/// The selected effect's box on the Program monitor picture `pic`, and double-clicking a clip's+/// picture to select its Motion.+pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, frame: (u32, u32)) {+ if app.ui.tool != Tool::Selection || app.ui.mask_pen.is_some() {+ return;+ }+ let mut actions: Vec<(String, Value)> = Vec::new();+ let id = egui::Id::new("program-transform");+ let drag_id = id.with("drag");+ let double = ui.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary));+ if let Some((sel, def, pl)) = selected_placement(app, pic, frame) {+ draw(app, ui, &pl, pic, def.name);+ let resp = ui.interact(Rect::from_points(&pl.quad).expand(ROTATE_REACH), id, Sense::click_and_drag());+ if resp.drag_started() {+ // 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(pl.anchor_at);+ match grab_at(&pl, p) {+ Some(grab) => {+ let angle = angle_deg(p - pl.anchor_at);+ ui.data_mut(|d| d.insert_temp(drag_id, Drag { sel, grab, start: p, from: pl, angle, turned: 0.0 }));+ }+ None => ui.data_mut(|d| d.remove::<Drag>(drag_id)),+ }+ }+ let drag: Option<Drag> = ui.data(|d| d.get_temp(drag_id)).filter(|d: &Drag| d.sel == sel);+ if let Some(mut d) = drag+ && resp.dragged()+ {+ let cur = resp.interact_pointer_pos().unwrap_or(d.start);+ let off = cur - d.from.anchor_at;+ if d.grab == Grab::Rotate && off.length() >= 1.0 {+ let a = angle_deg(off);+ d.turned += (a - d.angle + 180.0).rem_euclid(360.0) - 180.0;+ d.angle = a;+ ui.data_mut(|m| m.insert_temp(drag_id, d));+ }+ if resp.drag_started() || resp.drag_delta() != egui::Vec2::ZERO {+ for (param, value) in changes(&d, def.id, cur) {+ actions.push(("effects.setParam".into(), json!({"clip": sel.0.0, "effect": sel.1, "param": param, "value": value, "merge": MERGE})));+ }+ }+ cursor(ui, &pl, d.grab, cur, pic);+ } else if let Some(p) = resp.hover_pos()+ && let Some(grab) = grab_at(&pl, p)+ {+ cursor(ui, &pl, grab, p, pic);+ }+ if resp.drag_stopped() {+ ui.data_mut(|d| d.remove::<Drag>(drag_id));+ }+ // a click beside the box (not on it, a handle or a corner's rotate zone) lets go of it+ if resp.clicked() && !double && resp.interact_pointer_pos().is_some_and(|p| grab_at(&pl, p).is_none()) {+ actions.push(("effects.select".into(), json!({"none": true})));+ }+ }+ if double+ && app.ui.gfx_edit.is_none()+ && let Some(p) = ui.input(|i| i.pointer.interact_pos()).filter(|p| pic.contains(*p) && ui.rect_contains_pointer(pic))+ && let Some(clip) = clip_under(app, pic, frame, p)+ {+ if !app.session.state.selection.contains(&clip) {+ actions.push(("timeline.select".into(), json!({"clips": [clip.0]})));+ }+ actions.push(("effects.select".into(), json!({"clip": clip.0, "effect": "motion"})));+ }+ crate::panels::effect_controls::run(app, ui.ctx(), actions);+}diff --git a/crates/ui-egui/tests/audio_fx_editor_ui.rs b/crates/ui-egui/tests/audio_fx_editor_ui.rsindex 1d7d80d74..f15c824a6 100644--- a/crates/ui-egui/tests/audio_fx_editor_ui.rs+++ b/crates/ui-egui/tests/audio_fx_editor_ui.rs@@ -134,7 +134,7 @@ impl Driver {self.frames(3);// fold the fixed effects so the applied one's rows are on screenfor fx in ["volume", "channel_volume", "panner"] {- self.click(&format!("effectControls.effect.{fx}"));+ self.click(&format!("effectControls.effect.{fx}.twirl"));}id}@@ -202,7 +202,7 @@ fn graphic_eq_and_dynamics_editors() {// Dynamics: the transfer curve and section togglesd.exec("effects.apply", json!({"clips": [clip], "effect": "dynamics_rack"}));d.frames(3);- d.click("effectControls.effect.graphic_eq_30");+ d.click("effectControls.effect.graphic_eq_30.twirl");d.click("effectControls.effect.dynamics_rack.edit");d.frames(3);assert!(d.element("fxEditor.dynamics_rack.curve").is_some());diff --git a/crates/ui-egui/tests/clip_audio_ui.rs b/crates/ui-egui/tests/clip_audio_ui.rsindex 3ca87a33b..2b687eafa 100644--- a/crates/ui-egui/tests/clip_audio_ui.rs+++ b/crates/ui-egui/tests/clip_audio_ui.rs@@ -130,7 +130,7 @@ fn effect_controls_show_the_audio_of_a_video_clip() {// the audio rows edit the audio clipfor fx in ["motion", "opacity", "time_remap"] {- d.click(&format!("effectControls.effect.{fx}"));+ d.click(&format!("effectControls.effect.{fx}.twirl"));}d.click("effectControls.volume.level.stopwatch");assert!(d.item(pair.audio).effect("volume").unwrap().param("level").unwrap().is_animated());diff --git a/crates/ui-egui/tests/masks_ui.rs b/crates/ui-egui/tests/masks_ui.rsindex 08934963f..43d06252c 100644--- a/crates/ui-egui/tests/masks_ui.rs+++ b/crates/ui-egui/tests/masks_ui.rs@@ -113,7 +113,7 @@ fn create_and_edit_masks_on_the_monitor() {// ellipse mask from the Effect Controls icon// fold Motion and Time Remapping so the Gaussian Blur rows are on screenfor fx in ["motion", "time_remap"] {- d.ok("ui.click", json!({"id": format!("effectControls.effect.{fx}")}));+ d.ok("ui.click", json!({"id": format!("effectControls.effect.{fx}.twirl")}));d.frames(2);}d.ok("ui.click", json!({"id": "effectControls.gaussian_blur.mask.ellipse"}));@@ -166,13 +166,13 @@ fn create_and_edit_masks_on_the_monitor() {d.shot("mask-edited");// Inverted checkbox (fold Opacity so the row is on screen)- d.ok("ui.click", json!({"id": "effectControls.effect.opacity"}));+ d.ok("ui.click", json!({"id": "effectControls.effect.opacity.twirl"}));d.frames(2);d.ok("ui.click", json!({"id": "effectControls.gaussian_blur.mask0.inverted"}));d.frames(2);assert_eq!(d.masks()[0]["inverted"], true);d.shot("mask-inverted");- d.ok("ui.click", json!({"id": "effectControls.effect.opacity"}));+ d.ok("ui.click", json!({"id": "effectControls.effect.opacity.twirl"}));d.frames(2);// pen mask on Opacity: four clicks, then click the first point to close@@ -285,7 +285,7 @@ fn presets_bin_drag_and_save_dialog() {d.shot("presets-bin");// Save Preset dialog from the effect's context menu (opened through the command-equivalent UI state)for fx in ["motion", "opacity", "time_remap"] {- d.ok("ui.click", json!({"id": format!("effectControls.effect.{fx}")}));+ d.ok("ui.click", json!({"id": format!("effectControls.effect.{fx}.twirl")}));d.frames(2);}d.ok("ui.click", json!({"id": "effectControls.effect.brightness_contrast", "button": "right"}));diff --git a/crates/ui-egui/tests/transform_handles_ui.rs b/crates/ui-egui/tests/transform_handles_ui.rsnew file mode 100644index 000000000..a15cb8d97--- /dev/null+++ b/crates/ui-egui/tests/transform_handles_ui.rs@@ -0,0 +1,364 @@+//! On-screen transform handles on the Program monitor (#639), driven headless through the control+//! channel: selecting Motion (or the Transform effect) in Effect Controls shows a box with handles+//! and the anchor point; dragging moves, scales, rotates and moves the anchor point, one undo+//! step per drag, keying the playhead when the stopwatch is on. Clicking an effect header selects+//! it and only its arrow twirls it; double-clicking a clip's picture selects its Motion.+//!+//! With `FILMCRAFT_UI_SHOTS=<dir>` the tests also render the UI with wgpu and write PNGs there.++use std::sync::mpsc::{Sender, channel};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_project::{ClipId, ParamValue};+use filmcraft_time::Tick;+use filmcraft_ui_egui::FilmcraftApp;+use filmcraft_ui_egui::control::ControlRequest;+use serde_json::{Value, json};++struct Driver {+ harness: Harness<'static, FilmcraftApp>,+ tx: Sender<ControlRequest>,+ shots: Option<std::path::PathBuf>,+}++impl Driver {+ fn demo() -> Self {+ let mut session = Session::default();+ session.execute("file.openDemoProject", json!({})).expect("demo project");+ let (tx, rx) = channel();+ let app = FilmcraftApp::new(session).with_control(rx);+ let shots = std::env::var_os("FILMCRAFT_UI_SHOTS").map(std::path::PathBuf::from);+ // frames 1/60 s apart, so that two clicks make a double-click+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_step_dt(1.0 / 60.0).with_max_steps(10_000);+ if shots.is_some() {+ b = b.wgpu().with_pixels_per_point(1.0);+ }+ let harness = b.build_eframe(move |_cc| app);+ let mut d = Driver { harness, tx, shots };+ d.frames(4);+ d.ok("ui.set", json!({"workspace": "Effects"}));+ d+ }+ fn frames(&mut self, n: usize) {+ for _ in 0..n {+ let ctx = self.harness.ctx.clone();+ let mut raw = std::mem::take(self.harness.input_mut());+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);+ *self.harness.input_mut() = raw;+ self.harness.step();+ }+ }+ fn call(&mut self, method: &str, params: Value) -> Value {+ let (req, reply) = ControlRequest::new(method, params.clone());+ self.tx.send(req).unwrap();+ for _ in 0..600 {+ self.frames(1);+ if let Ok(v) = reply.try_recv() {+ return v;+ }+ }+ panic!("no reply to {method} {params}");+ }+ fn ok(&mut self, method: &str, params: Value) -> Value {+ let r = self.call(method, params.clone());+ assert_eq!(r["ok"], true, "{method} {params}: {r}");+ r["result"].clone()+ }+ fn exec(&mut self, command: &str, params: Value) -> Value {+ self.ok("engine.execute", json!({"command": command, "params": params}))+ }+ fn find(&mut self, id: &str) -> Option<[f64; 4]> {+ let v = self.ok("ui.elements", json!({"prefix": id}));+ let e = v.as_array().unwrap().iter().find(|e| e["id"] == id)?.clone();+ let r: Vec<f64> = e["rect"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();+ Some([r[0], r[1], r[2], r[3]])+ }+ fn rect(&mut self, id: &str) -> [f64; 4] {+ self.find(id).unwrap_or_else(|| panic!("no element {id}"))+ }+ fn center(&mut self, id: &str) -> (f64, f64) {+ let r = self.rect(id);+ (r[0] + r[2] / 2.0, r[1] + r[3] / 2.0)+ }+ fn click(&mut self, id: &str) {+ self.ok("ui.click", json!({"id": id}));+ self.frames(2);+ }+ fn drag_from(&mut self, (x, y): (f64, f64), dx: f64, dy: f64) {+ self.ok("ui.drag", json!({"from": {"x": x, "y": y}, "to": {"x": x + dx, "y": y + dy}, "steps": 6}));+ self.frames(2);+ }+ fn drag(&mut self, id: &str, dx: f64, dy: f64) {+ let at = self.center(id);+ self.drag_from(at, dx, dy);+ }+ fn undo_len(&mut self) -> usize {+ self.exec("history.list", json!({}))["undo"].as_array().unwrap().len()+ }+ fn selected_effect(&mut self) -> Value {+ self.exec("state.inspect", json!({}))["selected_effect"].clone()+ }+ /// The first V1 clip, selected, with the playhead in its middle.+ fn first_clip(&mut self) -> (u64, i64) {+ let seq = self.exec("sequence.inspect", json!({}));+ let clip = &seq["video"][0]["items"][0];+ let (id, start, dur) = (clip["clip"].as_u64().unwrap(), clip["start"].as_i64().unwrap(), clip["duration"].as_i64().unwrap());+ self.exec("playhead.set", json!({"time": start + dur / 2}));+ self.exec("timeline.select", json!({"clips": [id]}));+ self.frames(3);+ (id, start + dur / 2)+ }+ /// A parameter of a clip's effect: its value at the playhead and its keyframe times.+ fn param(&self, clip: u64, effect: &str, param: &str) -> (ParamValue, Vec<Tick>) {+ let app = self.harness.state();+ let it = app.session.active_sequence().unwrap().find_item(ClipId(clip)).unwrap().1;+ let mt = it.source_time_at(app.session.playhead());+ let p = it.effect(effect).unwrap().param(param).unwrap();+ (p.value_at(mt), p.keyframes.iter().map(|k| k.time).collect())+ }+ fn num(&self, clip: u64, effect: &str, param: &str) -> f64 {+ self.param(clip, effect, param).0.as_f64().unwrap()+ }+ fn point(&self, clip: u64, effect: &str, param: &str) -> (f64, f64) {+ match self.param(clip, effect, param).0 {+ ParamValue::Vec2(v) => (v.x, v.y),+ other => panic!("{param} is not a point: {other:?}"),+ }+ }+ fn shot(&mut self, name: &str) {+ let Some(dir) = self.shots.clone() else { return };+ for _ in 0..40 {+ self.frames(1);+ std::thread::sleep(std::time::Duration::from_millis(25));+ }+ let img = self.harness.render().expect("wgpu render");+ std::fs::create_dir_all(&dir).unwrap();+ img.save(dir.join(format!("{name}.png"))).unwrap();+ }+}++fn near(a: (f64, f64), b: (f64, f64)) -> bool {+ (a.0 - b.0).abs() < 1.5 && (a.1 - b.1).abs() < 1.5+}++const HANDLES: [&str; 11] = [+ "program.transform.box",+ "program.transform.anchor",+ "program.transform.handle.0",+ "program.transform.handle.1",+ "program.transform.handle.2",+ "program.transform.handle.3",+ "program.transform.handle.4",+ "program.transform.handle.5",+ "program.transform.handle.6",+ "program.transform.handle.7",+ "program.transform.rotate.1",+];++#[test]+fn motion_handles_move_scale_rotate_and_move_the_anchor() {+ let mut d = Driver::demo();+ let (clip, _) = d.first_clip();+ // half size, so the whole box and the corners' rotate zones are on the monitor+ d.exec("effects.setParam", json!({"clip": clip, "effect": "motion", "param": "scale", "value": 50.0}));+ d.frames(2);+ assert!(d.find("program.transform.box").is_none(), "no handles before Motion is selected");+ d.click("effectControls.effect.motion");+ assert_eq!(d.selected_effect(), json!({"clip": clip, "effect": "motion", "instance": 0}));+ for id in HANDLES {+ d.rect(id);+ }+ d.shot("transform-motion-selected");++ // a drag inside the box (away from the anchor point) moves the picture: one undo step+ let undo = d.undo_len();+ let p0 = d.point(clip, "motion", "position");+ let b = d.rect("program.transform.box");+ let pic = d.rect("program.picture");+ d.drag_from((b[0] + b[2] * 0.3, b[1] + b[3] * 0.3), 40.0, 20.0);+ let p1 = d.point(clip, "motion", "position");+ let k = 1920.0 / pic[2];+ assert!((p1.0 - p0.0 - 40.0 * k).abs() < 2.0 * k && (p1.1 - p0.1 - 20.0 * k).abs() < 2.0 * k, "{p0:?} → {p1:?} (×{k})");+ assert_eq!(d.num(clip, "motion", "scale"), 50.0);+ assert_eq!(d.undo_len(), undo + 1, "one undo step per drag");+ assert!(d.param(clip, "motion", "position").1.is_empty(), "the stopwatch is off: no keyframe");++ // a corner scales both axes about the anchor point (Uniform Scale is on); the drawn square is+ // 5 points wide but a press a few points beside it, outside the box, still takes it+ let undo = d.undo_len();+ let (hx, hy) = d.center("program.transform.handle.2");+ d.drag_from((hx + 4.0, hy + 4.0), 30.0, 30.0);+ let s = d.num(clip, "motion", "scale");+ assert!(s > 55.0, "scale {s}");+ assert_eq!(d.point(clip, "motion", "position"), p1, "scaling keeps the position");+ assert_eq!(d.undo_len(), undo + 1);++ // just outside a corner rotates: down from beside the top-right corner turns clockwise+ d.drag("program.transform.rotate.1", 0.0, 60.0);+ let r = d.num(clip, "motion", "rotation");+ assert!(r > 5.0, "rotation {r}");+ d.shot("transform-motion-rotated");++ // the anchor point moves over the picture, which stays where it is+ let corners: Vec<(f64, f64)> = (0..4).map(|n| d.center(&format!("program.transform.handle.{n}"))).collect();+ let (a0, p2) = (d.point(clip, "motion", "anchor"), d.point(clip, "motion", "position"));+ let at = d.center("program.transform.anchor");+ let undo = d.undo_len();+ d.drag("program.transform.anchor", 30.0, 20.0);+ assert!(near(d.center("program.transform.anchor"), (at.0 + 30.0, at.1 + 20.0)), "the anchor point follows the pointer");+ for (n, c) in corners.iter().enumerate() {+ assert!(near(d.center(&format!("program.transform.handle.{n}")), *c), "corner {n} stays put");+ }+ assert_ne!(d.point(clip, "motion", "anchor"), a0);+ let p3 = d.point(clip, "motion", "position");+ assert!((p3.0 - p2.0 - 30.0 * k).abs() < 2.0 * k && (p3.1 - p2.1 - 20.0 * k).abs() < 2.0 * k, "position {p2:?} → {p3:?}");+ assert_eq!(d.undo_len(), undo + 1, "anchor and position change in one undo step");+ d.exec("edit.undo", json!({}));+ assert_eq!((d.point(clip, "motion", "anchor"), d.point(clip, "motion", "position")), (a0, p2));++ // Uniform Scale off: a side handle changes only the width, the top only the height+ d.exec("effects.setParam", json!({"clip": clip, "effect": "motion", "param": "rotation", "value": 0.0}));+ d.exec("effects.setParam", json!({"clip": clip, "effect": "motion", "param": "uniform_scale", "value": false}));+ d.exec("effects.setParam", json!({"clip": clip, "effect": "motion", "param": "scale_width", "value": 50.0}));+ d.exec("effects.setParam", json!({"clip": clip, "effect": "motion", "param": "scale", "value": 50.0}));+ d.frames(2);+ d.drag("program.transform.handle.5", 30.0, 10.0);+ assert!(d.num(clip, "motion", "scale_width") > 55.0);+ assert_eq!(d.num(clip, "motion", "scale"), 50.0);+ let w = d.num(clip, "motion", "scale_width");+ d.drag("program.transform.handle.4", 10.0, -30.0);+ assert!(d.num(clip, "motion", "scale") > 55.0);+ assert_eq!(d.num(clip, "motion", "scale_width"), w);+ // a corner changes both, each by its own side+ d.drag("program.transform.handle.2", 30.0, 0.0);+ assert!(d.num(clip, "motion", "scale_width") > w + 3.0);+ d.shot("transform-motion-non-uniform");++ // a click beside the box lets go of it+ let b = d.rect("program.transform.box");+ d.ok("ui.click", json!({"x": b[0] - 20.0, "y": b[1] + b[3] / 2.0}));+ d.frames(2);+ assert_eq!(d.selected_effect(), Value::Null);+ assert!(d.find("program.transform.box").is_none());+}++#[test]+fn a_drag_keys_the_playhead_and_headers_select_while_arrows_twirl() {+ let mut d = Driver::demo();+ let (clip, mid) = d.first_clip();+ d.exec("effects.setParam", json!({"clip": clip, "effect": "motion", "param": "scale", "value": 50.0}));+ // stopwatch on at the middle of the clip, then a second further on+ d.exec("effects.toggleAnimation", json!({"clip": clip, "effect": "motion", "param": "position"}));+ let key0 = d.param(clip, "motion", "position").1;+ assert_eq!(key0.len(), 1);+ d.exec("playhead.set", json!({"time": mid + filmcraft_time::TICKS_PER_SECOND}));+ d.frames(2);+ // clicking a property (its name) selects Motion too+ let (sx, sy) = d.center("effectControls.motion.scale.stopwatch");+ d.ok("ui.click", json!({"x": sx + 30.0, "y": sy}));+ d.frames(2);+ assert_eq!(d.selected_effect(), json!({"clip": clip, "effect": "motion", "instance": 0}));+ let p0 = d.point(clip, "motion", "position");+ let undo = d.undo_len();+ let b = d.rect("program.transform.box");+ d.drag_from((b[0] + b[2] * 0.3, b[1] + b[3] * 0.3), -30.0, 15.0);+ let (moved, keys) = d.param(clip, "motion", "position");+ assert_eq!(keys.len(), 2, "a keyframe at the playhead: {keys:?}");+ assert!(keys.contains(&key0[0]));+ assert_ne!(moved, ParamValue::Vec2(filmcraft_geom::Vec2::new(p0.0, p0.1)));+ assert_eq!(d.undo_len(), undo + 1);+ // the first keyframe keeps its value+ d.exec("playhead.set", json!({"time": mid}));+ d.frames(2);+ assert_eq!(d.point(clip, "motion", "position"), p0);++ // the header selects without twirling; the arrow twirls without selecting+ d.exec("effects.select", json!({"none": true}));+ d.click("effectControls.effect.motion");+ assert_eq!(d.selected_effect(), json!({"clip": clip, "effect": "motion", "instance": 0}));+ assert!(d.find("effectControls.motion.position.stopwatch").is_some(), "Motion is still open");+ d.click("effectControls.effect.motion.twirl");+ assert!(d.find("effectControls.motion.position.stopwatch").is_none(), "the arrow folds Motion");+ assert_eq!(d.selected_effect(), json!({"clip": clip, "effect": "motion", "instance": 0}));+ d.click("effectControls.effect.motion.twirl");+ assert!(d.find("effectControls.motion.position.stopwatch").is_some(), "and opens it again");+ // selecting another effect hides the handles: Opacity has none+ d.click("effectControls.effect.opacity");+ assert_eq!(d.selected_effect(), json!({"clip": clip, "effect": "opacity", "instance": 0}));+ assert!(d.find("program.transform.box").is_none());+}++#[test]+fn transform_effect_handles_and_double_click_selection() {+ let mut d = Driver::demo();+ let (clip, _) = d.first_clip();+ d.exec("effects.apply", json!({"clips": [clip], "effect": "transform"}));+ d.exec("effects.setParam", json!({"clip": clip, "effect": "transform", "param": "scale_height", "value": 50.0}));+ d.frames(2);+ // fold the fixed effects so the Transform header is on screen+ for fx in ["motion", "opacity", "time_remap"] {+ d.click(&format!("effectControls.effect.{fx}.twirl"));+ }+ d.click("effectControls.effect.transform");+ assert_eq!(d.selected_effect(), json!({"clip": clip, "effect": "transform", "instance": 0}));+ for id in HANDLES {+ d.rect(id);+ }+ d.shot("transform-effect-selected");+ let motion = d.point(clip, "motion", "position");+ let p0 = d.point(clip, "transform", "position");+ let b = d.rect("program.transform.box");+ d.drag_from((b[0] + b[2] * 0.3, b[1] + b[3] * 0.3), 40.0, 0.0);+ let p1 = d.point(clip, "transform", "position");+ assert!(p1.0 > p0.0 + 20.0 && (p1.1 - p0.1).abs() < 1e-6, "{p0:?} → {p1:?}");+ assert_eq!(d.point(clip, "motion", "position"), motion, "Motion is left alone");+ d.drag("program.transform.handle.2", 30.0, 30.0);+ assert!(d.num(clip, "transform", "scale_height") > 55.0);+ d.drag("program.transform.rotate.1", 0.0, 60.0);+ assert!(d.num(clip, "transform", "rotation") > 5.0);+ d.exec("effects.setParam", json!({"clip": clip, "effect": "transform", "param": "rotation", "value": 0.0}));+ d.exec("effects.setParam", json!({"clip": clip, "effect": "transform", "param": "uniform_scale", "value": false}));+ d.exec("effects.setParam", json!({"clip": clip, "effect": "transform", "param": "scale_width", "value": 50.0}));+ d.exec("effects.setParam", json!({"clip": clip, "effect": "transform", "param": "scale_height", "value": 50.0}));+ d.frames(2);+ d.drag("program.transform.handle.7", -30.0, 0.0);+ assert!(d.num(clip, "transform", "scale_width") > 55.0);+ assert_eq!(d.num(clip, "transform", "scale_height"), 50.0);+ let corners: Vec<(f64, f64)> = (0..4).map(|n| d.center(&format!("program.transform.handle.{n}"))).collect();+ d.drag("program.transform.anchor", -25.0, 15.0);+ for (n, c) in corners.iter().enumerate() {+ assert!(near(d.center(&format!("program.transform.handle.{n}")), *c), "corner {n} stays put");+ }++ // double-clicking a picture selects its clip's Motion: the overlay on V2, then V1 under it+ let seq = d.exec("sequence.inspect", json!({}));+ let overlay = seq["video"][1]["items"][0]["clip"].as_u64().unwrap();+ let start = seq["video"][1]["items"][0]["start"].as_i64().unwrap();+ d.exec("playhead.set", json!({"time": start + filmcraft_time::TICKS_PER_SECOND}));+ d.frames(3);+ let pic = d.rect("program.picture");+ d.ok("ui.click", json!({"x": pic[0] + pic[2] * 0.8, "y": pic[1] + pic[3] * 0.76, "count": 2}));+ d.frames(3);+ assert_eq!(d.selected_effect(), json!({"clip": overlay, "effect": "motion", "instance": 0}));+ let sel = d.exec("state.inspect", json!({}))["selection"].clone();+ assert!(sel.as_array().unwrap().contains(&json!(overlay)), "{sel}");+ d.rect("program.transform.anchor");+ d.shot("transform-double-click-overlay");+ // half a second later, or egui counts the next clicks as a triple click+ d.frames(30);+ d.ok("ui.click", json!({"x": pic[0] + pic[2] * 0.2, "y": pic[1] + pic[3] * 0.2, "count": 2}));+ d.frames(3);+ let under = d.exec("sequence.inspect", json!({}))["video"][0]["items"]+ .as_array()+ .unwrap()+ .iter()+ .find(|it| {+ let (s, l) = (it["start"].as_i64().unwrap(), it["duration"].as_i64().unwrap());+ (s..s + l).contains(&(start + filmcraft_time::TICKS_PER_SECOND))+ })+ .unwrap()["clip"]+ .as_u64()+ .unwrap();+ assert_eq!(d.selected_effect(), json!({"clip": under, "effect": "motion", "instance": 0}));+}