EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Merge main into fix/1284-testing-feedback
Claude152ce37f8d06
diff --cc crates/engine/src/tests/session.rsindex 000000000,b5d1cbb5f..e0f3e9cd8mode 000000,100644..100644--- a/crates/engine/src/tests/session.rs+++ b/crates/engine/src/tests/session.rs@@@ -1,0 -1,760 +1,772 @@@+ use serde_json::json;++ use crate::Session;++ fn demo() -> Session {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ s+ }++ #[test]+ fn demo_opens_and_renders() {+ let s = demo();+ let cid = s.active_comp_id().unwrap();+ let img = s.render(cid, s.time(), effectcraft_render::RenderOpts { scale: 0.25, ..Default::default() });+ assert_eq!((img.width, img.height), (480, 270));+ let lit = img.data.iter().filter(|p| p[3] > 0.99).count();+ assert!(lit > 100_000, "{lit}");+ }++ /// The session's layer cache never changes pixels: scrubbing the demo (including back and+ /// forth, and across an edit made through a command) matches cache-less renders exactly.+ #[test]+ fn demo_layer_cache_is_transparent() {+ let mut s = demo();+ let cid = s.active_comp_id().unwrap();+ let opts = effectcraft_render::RenderOpts { scale: 0.25, ..Default::default() };+ let uncached = |s: &Session, t: f64| {+ let mut r = effectcraft_render::Renderer::new(&s.project, s.footage.as_ref(), opts);+ r.expr = s.expr.as_deref();+ r.comp_frame(cid, effectcraft_time::Tick::from_seconds_f64(t))+ };+ let check = |s: &Session, t: f64| {+ let a = s.render(cid, effectcraft_time::Tick::from_seconds_f64(t), opts);+ let b = uncached(s, t);+ assert!(a.data.iter().zip(&b.data).all(|(p, q)| (0..4).all(|c| (p[c] - q[c]).abs() < 1e-6)), "t={t}");+ };+ for t in [0.5, 1.0, 3.0, 3.0334, 6.0, 3.0, 0.5] {+ check(&s, t);+ }+ assert!(s.layer_cache.stats().hits > 0);+ // Edit the title's glow through the command layer, then scrub again.+ let title = s.project.comp(cid).unwrap().layers.iter().find(|l| l.name == "EFFECTCRAFT").map(|l| l.id.0).unwrap();+ s.execute("prop.set", json!({"layer": title, "path": "effects/#1/radius", "value": 5.0})).unwrap();+ for t in [3.0, 0.5] {+ check(&s, t);+ }+ }++ /// `layer.addItem` puts the layer at `index` (1-based) in the stack and starts it at `time`, as a+ /// drop in the Timeline does (#89).+ #[test]+ fn add_item_at_a_stack_index_and_time() {+ let mut s = Session::default();+ let clip = s.execute("comp.new", json!({"name": "Clip", "width": 16, "height": 16, "frameRate": 30, "duration": 1})).unwrap()["comp"].as_u64().unwrap();+ s.execute("comp.new", json!({"name": "Main", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap();+ for name in ["C", "B", "A"] {+ s.execute("layer.newSolid", json!({"name": name})).unwrap();+ }+ let names = |s: &Session| s.active_comp().unwrap().layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();+ s.execute("layer.addItem", json!({"item": clip, "index": 2, "time": 1.01})).unwrap();+ assert_eq!(names(&s), ["A", "Clip", "B", "C"]);+ let l = &s.active_comp().unwrap().layers[1];+ assert_eq!(l.in_point, effectcraft_time::Tick::from_seconds_f64(1.0), "on the nearest frame");+ // Past the bottom: the bottom.+ s.execute("layer.addItem", json!({"item": clip, "index": 99})).unwrap();+ assert_eq!(names(&s).last().map(String::as_str), Some("Clip 2"));+ assert!(s.execute("layer.addItem", json!({"item": clip, "index": 0})).is_err(), "1-based");+ }++ /// Files dropped on the Timeline or the Composition viewer (`file.import {addToComp}`) become+ /// layers of the comp that was active, one under the other, where they were dropped (#85, #89).+ #[test]+ fn imported_files_go_into_the_comp_where_they_were_dropped() {+ use effectcraft_project::{Footage, FootageKind};+ struct Probe;+ impl crate::Importer for Probe {+ fn probe(&self, path: &str) -> Result<Footage, String> {+ Ok(Footage { path: path.into(), kind: FootageKind::Still, width: 64, height: 32, has_video: true, ..Default::default() })+ }+ }+ let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() };+ s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap();+ s.execute("layer.newSolid", json!({"name": "Bg"})).unwrap();+ let params = json!({"paths": ["/drop/a.png", "/drop/b.png"], "addToComp": true, "position": [40.0, 50.0], "index": 1, "time": 1.0});+ s.execute("file.import", params).unwrap();+ let comp = s.active_comp().unwrap();+ assert_eq!(comp.layers.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["a.png", "b.png", "Bg"]);+ for l in &comp.layers[..2] {+ assert_eq!(l.props.prop("transform/position").map(|p| p.value.clone()), Some(effectcraft_keyframe::Value::Vec3([40.0, 50.0, 0.0])));+ assert_eq!(l.in_point, effectcraft_time::Tick::from_seconds_f64(1.0));+ }+ // Without `addToComp` they only import.+ s.execute("file.import", json!({"paths": ["/drop/c.png"]})).unwrap();+ assert_eq!(s.active_comp().unwrap().layers.len(), 3);+ assert!(s.execute("layer.addItem", json!({"item": "a.png", "position": [1.0]})).is_err(), "position needs x and y");+ }++ /// #270: files dropped or picked in the Import dialog (`file.import {background}`) are probed in+ /// a background job that says which file it is reading and how many are left; then they arrive+ /// in one undo step, all selected, with a count. The same file imported again arrives again.+ #[test]+ fn background_imports_report_progress_and_select_what_arrived() {+ use effectcraft_project::{Footage, FootageKind, ItemId};+ use std::sync::Arc;+ use std::sync::atomic::{AtomicUsize, Ordering};+ /// Probes file k once `allow` > k (a slow video; 5 s at most, so an import that waits for it+ /// fails the test instead of hanging it); `.xyz` files fail.+ struct Gated {+ started: AtomicUsize,+ allow: Arc<AtomicUsize>,+ }+ impl crate::Importer for Gated {+ fn probe(&self, path: &str) -> Result<Footage, String> {+ let k = self.started.fetch_add(1, Ordering::SeqCst);+ let until = std::time::Instant::now() + std::time::Duration::from_secs(5);+ while self.allow.load(Ordering::SeqCst) <= k && std::time::Instant::now() < until {+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ if path.ends_with(".xyz") {+ return Err("unsupported file".into());+ }+ Ok(Footage { path: path.into(), kind: FootageKind::Still, width: 64, height: 32, has_video: true, ..Default::default() })+ }+ }+ let allow = Arc::new(AtomicUsize::new(1));+ let mut s = Session { importer: Some(Arc::new(Gated { started: AtomicUsize::new(0), allow: allow.clone() })), ..Default::default() };+ s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap();+ let undo = s.history.undo.len();+ let r = s.execute("file.import", json!({"paths": ["/drop/a.png", "/drop/b.png", "/drop/a.png"], "background": true})).unwrap();+ let job = r["job"].as_str().unwrap().to_string();+ // The first file is through; the second is being read.+ let running = |s: &mut Session| s.execute("jobs.list", json!({})).unwrap()["running"].as_array().unwrap().clone();+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);+ while running(&mut s)[0]["done"] != json!(1) && std::time::Instant::now() < deadline {+ std::thread::sleep(std::time::Duration::from_millis(2));+ }+ let row = running(&mut s)[0].clone();+ assert_eq!(row["id"], json!(job));+ assert_eq!(row["label"], json!("Importing 3 files"));+ assert_eq!(row["message"], json!("b.png (2 of 3)"));+ assert_eq!((row["done"].as_u64(), row["total"].as_u64()), (Some(1), Some(3)));+ assert!(s.project.items.values().all(|i| i.name != "a.png"), "nothing is added before the import finishes");+ allow.store(usize::MAX, Ordering::SeqCst);+ s.execute("jobs.wait", json!({})).unwrap();+ let names = |s: &Session, ids: &[ItemId]| ids.iter().map(|i| s.project.item(*i).unwrap().name.clone()).collect::<Vec<_>>();+ assert_eq!(names(&s, &s.state.project_selection), ["a.png", "b.png", "a.png"], "everything imported is selected, the same file twice too");+ assert_eq!(s.history.undo.len(), undo + 1, "one undo step");+ let rec = s.job_log.last().unwrap();+ assert_eq!((rec.status.as_str(), rec.message.as_str()), ("done", "Imported 3 items"));+ assert!(s.drain_events().iter().any(|e| matches!(e, crate::Event::Toast { message, .. } if message == "Imported 3 items")));+ // Dropped on the viewer: they become layers too; a file that can't be read is reported.+ s.execute("file.import", json!({"paths": ["/drop/c.png", "/drop/d.xyz"], "background": true, "addToComp": true, "position": [10.0, 20.0]})).unwrap();+ s.execute("jobs.wait", json!({})).unwrap();+ assert_eq!(s.active_comp().unwrap().layers.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["c.png"]);+ assert_eq!(s.job_log.last().unwrap().message, "Imported 1 item. /drop/d.xyz: unsupported file");+ // Agents and scripts import at once by default.+ let r = s.execute("file.import", json!({"paths": ["/drop/e.png"]})).unwrap();+ assert_eq!(r["items"].as_array().map(Vec::len), Some(1));+ }++ /// Audio, Lock and Shy don't change pixels: toggling them keeps the cached layers (#103).+ #[test]+ fn audio_lock_and_shy_keep_cached_layers() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"name": "C", "width": 160, "height": 90, "frameRate": 30, "duration": 1})).unwrap();+ s.execute("layer.newSolid", json!({"color": "#3080ff", "width": 80, "height": 40})).unwrap();+ s.execute("effect.apply", json!({"layer": "#1", "effect": "Gaussian Blur"})).unwrap();+ s.execute("prop.set", json!({"layer": "#1", "path": "effects/#1/blurriness", "value": 12})).unwrap();+ let cid = s.active_comp_id().unwrap();+ let t = s.time();+ s.render(cid, t, Default::default());+ let before = s.layer_cache.stats();+ for sw in ["audio", "lock", "shy"] {+ s.execute("layer.setSwitch", json!({"layers": ["#1"], "switch": sw, "value": sw != "audio"})).unwrap();+ }+ s.render(cid, t, Default::default());+ let after = s.layer_cache.stats();+ assert_eq!(after.misses, before.misses, "no layer rendered again");+ assert!(after.hits > before.hits);+ }++ #[test]+ fn every_command_has_unique_id_and_runs_or_reports() {+ let mut ids = std::collections::HashSet::new();+ for c in crate::command_specs() {+ assert!(ids.insert(c.id), "duplicate {}", c.id);+ }+ assert!(ids.len() >= 90, "{}", ids.len());+ }++ #[test]+ fn layer_workflow_with_undo() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"name": "Test", "width": 640, "height": 360, "frameRate": 30, "duration": 4})).unwrap();+ let r = s.execute("layer.newSolid", json!({"color": "#336699"})).unwrap();+ let lid = r["layer"].as_u64().unwrap();+ s.execute("prop.set", json!({"layer": lid, "path": "transform/opacity", "value": 50})).unwrap();+ let tree = s.execute("layer.tree", json!({"layer": lid})).unwrap();+ assert!(tree.to_string().contains("\"value\":50.0"));+ s.execute("prop.toggleAnimation", json!({"layer": lid, "path": "transform/position"})).unwrap();+ s.execute("time.set", json!({"time": 2.0})).unwrap();+ s.execute("prop.set", json!({"layer": lid, "path": "transform/position", "value": [100, 100]})).unwrap();+ let comp = s.active_comp().unwrap();+ let pos = comp.layers[0].props.prop("transform/position").unwrap();+ assert_eq!(pos.keys.len(), 2);+ s.execute("prop.select", json!({"layer": lid, "path": "transform/position"})).unwrap();+ assert_eq!(s.state.selected_keys.len(), 2);+ s.execute("keys.easyEase", json!({})).unwrap();+ s.execute("keys.move", json!({"delta": 0.5})).unwrap();+ let pos = s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().clone();+ assert!((pos.keys[0].time.seconds() - 0.5).abs() < 0.02);+ assert_eq!(pos.keys[0].out_interp, effectcraft_keyframe::Interp::Bezier);+ // undo back to before the move+ s.execute("edit.undo", json!({})).unwrap();+ let pos = s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().clone();+ assert!(pos.keys[0].time.seconds().abs() < 0.02);+ s.execute("effect.apply", json!({"layer": lid, "effect": "Gaussian Blur"})).unwrap();+ s.execute("prop.set", json!({"layer": lid, "path": "effects/#1/blurriness", "value": 12})).unwrap();+ // Applying selects the new effect (Edit ▸ Duplicate would duplicate it); select the layer.+ s.execute("layer.select", json!({"layers": [lid]})).unwrap();+ s.execute("edit.duplicate", json!({})).unwrap();+ assert_eq!(s.active_comp().unwrap().layers.len(), 2);+ s.execute("layer.precompose", json!({"layers": [1, 2], "name": "Pre"})).unwrap();+ assert_eq!(s.active_comp().unwrap().layers.len(), 1);+ }++ #[test]+ fn text_shape_mask_matte_parent() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"width": 800, "height": 450, "duration": 3})).unwrap();+ let t = s.execute("layer.newText", json!({"text": "Hello", "size": 90})).unwrap()["layer"].as_u64().unwrap();+ s.execute("layer.addTextAnimator", json!({"layer": t, "properties": ["position", "opacity"]})).unwrap();+ let sh = s.execute("layer.newShape", json!({"kind": "star", "fill": "#ffcc00"})).unwrap()["layer"].as_u64().unwrap();+ s.execute("layer.addShapeItem", json!({"layer": sh, "kind": "trim"})).unwrap();+ s.execute("layer.addMask", json!({"layer": sh, "shape": "ellipse"})).unwrap();+ s.execute("layer.setMask", json!({"layer": sh, "mask": 1, "mode": "Subtract", "inverted": true})).unwrap();+ s.execute("layer.setTrackMatte", json!({"layer": sh, "matte": t, "kind": "luma"})).unwrap();+ s.execute("layer.setParent", json!({"layers": [sh], "parent": t})).unwrap();+ assert!(s.execute("layer.setParent", json!({"layers": [t], "parent": sh})).is_err());+ s.execute("layer.setBlendMode", json!({"layers": [sh], "mode": "Screen"})).unwrap();+ s.execute("layer.setSwitch", json!({"layers": [sh], "switch": "threeD"})).unwrap();+ let cid = s.active_comp_id().unwrap();+ let _ = s.render(cid, s.time(), Default::default());+ let info = s.execute("comp.info", json!({})).unwrap();+ assert_eq!(info["layers"].as_array().unwrap().len(), 2);+ }+++/// A shape layer the size of the comp and placed at its default position covers the frame: the++/// Shape Tool's double-click (#1284) makes one this way, for backgrounds, mattes and overlays.++#[test]++fn a_comp_sized_shape_layer_sits_on_the_comp_centre() {++ let mut s = Session::default();++ s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();++ let sh = s.execute("layer.newShape", json!({"kind": "rect", "size": [400, 300], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();++ let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap().clone();++ let pos = l.props.prop("transform/position").unwrap().value.clone();++ assert!(matches!(pos, effectcraft_keyframe::Value::Vec3(p) if (p[0] - 200.0).abs() < 1e-9 && (p[1] - 150.0).abs() < 1e-9), "{pos:?}");++}+++ /// The toolbar's Fill / Stroke change a selected shape layer's paint (#205): a shape drawn+ /// without a stroke gets one, later edits change it, and the Contents "Add:" items (#206) include+ /// an empty Path and a Gradient Stroke that render.+ #[test]+ fn toolbar_fill_and_stroke_paint_selected_shape_layers() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();+ let sh = s.execute("layer.newShape", json!({"kind": "rect", "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();+ let paint = |s: &mut Session| s.execute("shape.fillStroke", json!({})).unwrap();+ assert_eq!(paint(&mut s)["stroke"], serde_json::Value::Null, "drawn without a stroke");+ s.execute("shape.fillStroke", json!({"stroke": "#00ff00", "strokeWidth": 6})).unwrap();+ let p = paint(&mut s);+ assert_eq!((p["stroke"][1].as_f64(), p["strokeWidth"].as_f64()), (Some(1.0), Some(6.0)), "{p}");+ s.execute("shape.fillStroke", json!({"fill": "#0000ff", "strokeWidth": 3})).unwrap();+ let p = paint(&mut s);+ assert_eq!((p["fill"][2].as_f64(), p["strokeWidth"].as_f64()), (Some(1.0), Some(3.0)), "{p}");+ // One stroke, before the fill (paths, stroke, fill), and each change is one undo step.+ let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap().clone();+ let group = l.props.group("contents/group").unwrap();+ let order: Vec<&str> = group.sub("contents").unwrap().groups().map(|g| g.match_id.as_str()).collect();+ assert_eq!(order, ["rect", "stroke", "fill"]);+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(paint(&mut s)["strokeWidth"].as_f64(), Some(6.0));+ // Only shape layers.+ s.execute("layer.newSolid", json!({"color": "#808080"})).unwrap();+ assert!(s.execute("shape.fillStroke", json!({"fill": "#ffffff"})).is_err());+ for kind in ["path", "gstroke"] {+ let r = s.execute("layer.addShapeItem", json!({"layer": sh, "kind": kind})).unwrap();+ assert!(r["path"].as_str().is_some_and(|p| p.starts_with("contents/")), "{r}");+ }+ let cid = s.active_comp_id().unwrap();+ let _ = s.render(cid, s.time(), Default::default());+ }++ /// A Wiggle Paths saved without Spatial Phase gets the property, at 0°, after Temporal Phase when+ /// the project opens.+ #[test]+ fn opening_a_wiggle_paths_without_spatial_phase_adds_it() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();+ let sh = s.execute("layer.newShape", json!({"kind": "rect", "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();+ let uid = s.execute("layer.addShapeItem", json!({"layer": sh, "kind": "wiggle"})).unwrap()["uid"].as_u64().unwrap();+ let cid = s.active_comp_id().unwrap();+ let mut old = effectcraft_project::Project::from_json(&s.project.to_file_json().unwrap()).unwrap();+ let l = old.comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(sh)).unwrap();+ let g = l.props.find_group_mut(uid).unwrap();+ g.children.retain(|c| c.match_id() != "spatialPhase");+ assert_eq!(g.children.len(), 7);+ let next = old.next_id;+ s.replace_project(old, None);+ let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap().clone();+ let g = l.props.find_group(uid).unwrap();+ let ids: Vec<&str> = g.children.iter().map(|c| c.match_id()).collect();+ assert_eq!(ids, ["size", "detail", "points", "speed", "correlation", "phase", "spatialPhase", "seed"]);+ let sp = g.get("spatialPhase").unwrap();+ assert_eq!((sp.name.as_str(), &sp.value), ("Spatial Phase", &effectcraft_keyframe::Value::Scalar(0.0)));+ assert!(sp.uid >= next && s.project.next_id > sp.uid, "a fresh uid: {} (next {next})", sp.uid);+ }++ /// The toolbar's Fill Options / Stroke Options change a selected shape layer's paint kind (#732):+ /// None switches the fill off, a gradient turns the Fill into a Gradient Fill that keeps its+ /// opacity, Solid Color turns it back, and a Stroke kind adds a stroke where there is none.+ #[test]+ fn toolbar_fill_and_stroke_kinds_change_selected_shape_layers() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();+ let sh = s.execute("layer.newShape", json!({"kind": "rect", "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();+ let items = |s: &Session| -> Vec<(String, bool)> {+ let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap();+ l.props.group("contents/group/contents").unwrap().groups().map(|g| (g.match_id.clone(), g.enabled)).collect()+ };+ let kinds = |s: &mut Session| {+ let p = s.execute("shape.fillStroke", json!({})).unwrap();+ (p["fillType"].as_str().unwrap().to_string(), p["strokeType"].as_str().unwrap().to_string())+ };+ assert_eq!(kinds(&mut s), ("solid".into(), "none".into()));+ let cid = s.active_comp_id().unwrap();+ let centre = |s: &Session| s.render(cid, s.time(), Default::default()).get(200, 150);+ let red = centre(&s);+ // None switches the fill off: nothing is drawn, and the item stays.+ s.execute("shape.fillStroke", json!({"fillType": "none"})).unwrap();+ assert_eq!(items(&s), [("rect".into(), true), ("fill".into(), false)]);+ assert_eq!(kinds(&mut s).0, "none");+ assert_ne!(centre(&s), red, "the fill is off");+ // A radial gradient: the Fill becomes a Gradient Fill (switched on) that keeps its opacity.+ s.execute("shape.fillStroke", json!({"fillType": "solid", "fill": "#ff0000"})).unwrap();+ assert_eq!(centre(&s), red);+ let opacity = |s: &Session, m: &str| {+ let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap();+ l.props.group(&format!("contents/group/contents/{m}")).unwrap().get("opacity").unwrap().value.as_f64()+ };+ s.execute("prop.set", json!({"layer": sh, "path": "contents/group/contents/fill/opacity", "value": 40})).unwrap();+ s.execute("shape.fillStroke", json!({"fillType": "radial"})).unwrap();+ assert_eq!(items(&s), [("rect".into(), true), ("gfill".into(), true)]);+ assert_eq!((kinds(&mut s).0.as_str(), opacity(&s, "gfill")), ("radial", 40.0));+ s.execute("shape.fillStroke", json!({"fillType": "linear"})).unwrap();+ assert_eq!(kinds(&mut s).0, "linear");+ s.execute("shape.fillStroke", json!({"fillType": "solid", "fill": "#00ff00"})).unwrap();+ assert_eq!(items(&s), [("rect".into(), true), ("fill".into(), true)]);+ assert_eq!(opacity(&s, "fill"), 40.0);+ // A Stroke kind adds a stroke (before the fill); None switches it off again; undo is per step.+ s.execute("shape.fillStroke", json!({"strokeType": "linear"})).unwrap();+ assert_eq!(items(&s), [("rect".into(), true), ("gstroke".into(), true), ("fill".into(), true)]);+ s.execute("shape.fillStroke", json!({"strokeType": "none"})).unwrap();+ assert_eq!(kinds(&mut s), ("solid".into(), "none".into()));+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(kinds(&mut s), ("solid".into(), "linear".into()));+ assert!(s.execute("shape.fillStroke", json!({"fillType": "plaid"})).is_err());+ }++ /// Selecting a mask in the Timeline (its row or its Mask Path) selects all of its points, so the+ /// viewer drags the whole mask (#203); a shape's Path item works the same way.+ #[test]+ fn selecting_a_mask_selects_its_points() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();+ let l = s.execute("layer.newSolid", json!({"color": "#808080"})).unwrap()["layer"].as_u64().unwrap();+ let m1 = s.execute("layer.addMask", json!({"layer": l, "shape": "rect"})).unwrap()["mask"].as_u64().unwrap();+ let m2 = s.execute("layer.addMask", json!({"layer": l, "shape": "ellipse"})).unwrap()["mask"].as_u64().unwrap();+ let points = |s: &Session, m: u64| s.state.selected_vertices.iter().filter(|v| v.mask == m).count();+ s.execute("prop.select", json!({"layer": l, "prop": m1, "selectKeys": false})).unwrap();+ assert_eq!((points(&s, m1), s.state.selected_vertices.len()), (4, 4));+ // Mask Path selects them too; Shift-adding another mask keeps the first.+ let path = s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().props.find_group(m2).unwrap().get("path").unwrap().uid;+ s.execute("prop.select", json!({"layer": l, "prop": path, "add": true})).unwrap();+ assert_eq!((points(&s, m1), points(&s, m2)), (4, 4));+ // Another mask replaces them; another property deselects them.+ s.execute("prop.select", json!({"layer": l, "prop": m2})).unwrap();+ assert_eq!((points(&s, m1), points(&s, m2)), (0, 4));+ // Delete removes the selected mask (not only its points).+ s.execute("edit.clear", json!({})).unwrap();+ let masks = |s: &Session| s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().masks().unwrap().children.len();+ assert_eq!(masks(&s), 1);+ s.execute("prop.select", json!({"layer": l, "path": "transform/opacity"})).unwrap();+ assert!(s.state.selected_vertices.is_empty());+ let sh = s.execute("layer.newShape", json!({"kind": "star"})).unwrap()["layer"].as_u64().unwrap();+ let star = s.execute("layer.addShapeItem", json!({"layer": sh, "kind": "path"})).unwrap()["uid"].as_u64().unwrap();+ s.execute("prop.select", json!({"layer": sh, "prop": star})).unwrap();+ assert_eq!(s.state.selected_vertices.len(), 0, "an empty Path has no points");+ }++ #[test]+ fn save_and_open_roundtrip() {+ let mut s = demo();+ let dir = std::env::temp_dir().join(format!("ec-test-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("demo.ecproj").to_string_lossy().to_string();+ s.execute("file.saveAs", json!({"path": path})).unwrap();+ let before = s.project.clone();+ let mut s2 = Session::default();+ s2.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!(*before, *s2.project);+ let _ = std::fs::remove_dir_all(dir);+ }++ #[test]+ fn help_links_emit_urls() {+ let mut s = Session::default();+ let r = s.execute("help.discord", json!({})).unwrap();+ assert_eq!(r["url"], "https://discord.gg/artcraft");+ assert!(s.drain_events().iter().any(|e| matches!(e, crate::Event::OpenUrl(u) if u.contains("discord"))));+ assert_eq!(s.execute("help.github", json!({})).unwrap()["url"], "https://github.com/storytold/effectcraft");+ }++ #[test]+ fn time_navigation() {+ let mut s = demo();+ s.execute("time.start", json!({})).unwrap();+ let r = s.execute("time.nextKey", json!({})).unwrap();+ assert!(r["time"].as_f64().unwrap() > 0.0);+ s.execute("time.set", json!({"frame": 45})).unwrap();+ assert_eq!(s.execute("time.step", json!({"frames": 5})).unwrap()["frame"], 50);+ }++ #[test]+ fn time_navigation_per_property() {+ let mut s = demo();+ // An animated property and the comp times of its keys.+ let comp = s.active_comp().unwrap().clone();+ let mut found = None;+ for l in &comp.layers {+ l.props.walk("", &mut |_, pr| {+ if found.is_none() && pr.keys.len() >= 2 {+ found = Some((pr.uid, pr.keys.iter().map(|k| l.comp_time(k.time)).collect::<Vec<_>>()));+ }+ });+ }+ let (uid, times) = found.expect("demo has an animated property");+ s.set_time(effectcraft_time::Tick::ZERO);+ let half = comp.frame_duration().0 / 2;+ let expect = times.iter().copied().filter(|t| t.0 > half).min().unwrap();+ s.execute("time.go", json!({"to": "nextKey", "prop": uid})).unwrap();+ let snap = |t| comp.frame_rate.snap(t);+ assert_eq!(s.time(), snap(expect));+ // Going back from past the last key lands on the last key.+ s.set_time(comp.duration);+ s.execute("time.go", json!({"to": "prevKey", "prop": uid})).unwrap();+ assert_eq!(s.time(), snap(*times.iter().max().unwrap()));+ }++ #[test]+ fn set_text_paragraph_fill_and_leading() {+ use effectcraft_keyframe::{Justify, Value as KValue};+ let mut s = demo();+ let t = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();+ let doc = |s: &Session| {+ let l = s.active_comp().unwrap().layer(crate::project::LayerId(t)).unwrap().clone();+ match &l.props.prop("text/sourceText").unwrap().value {+ KValue::Text(d) => (**d).clone(),+ v => panic!("{v:?}"),+ }+ };+ for (key, j) in [+ ("justifyLeft", Justify::JustifyLastLeft),+ ("justifyCenter", Justify::JustifyLastCenter),+ ("justifyRight", Justify::JustifyLastRight),+ ("justifyAll", Justify::JustifyAll),+ ("center", Justify::Center),+ ] {+ s.execute("layer.setText", json!({"layer": t, "justify": key})).unwrap();+ assert_eq!(doc(&s).justify, j, "{key}");+ }+ s.execute("layer.setText", json!({"layer": t, "leading": 50, "applyFill": false, "applyStroke": true})).unwrap();+ let d = doc(&s);+ assert_eq!((d.leading, d.apply_fill, d.apply_stroke), (Some(50.0), false, true));+ s.execute("layer.setText", json!({"layer": t, "leading": "auto"})).unwrap();+ assert_eq!(doc(&s).leading, None);+ s.execute("layer.setText", json!({"layer": t, "hScale": 120, "vScale": 80, "baselineShift": 4, "smallCaps": true, "strokeOverFill": true})).unwrap();+ let d = doc(&s);+ assert_eq!((d.h_scale, d.v_scale, d.baseline_shift, d.small_caps, d.stroke_over_fill), (120.0, 80.0, 4.0, true, true));+ }++ #[test]+ fn property_groups_report_actionable_errors() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"name": "T"})).unwrap();+ let l = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();+ let uid = s.active_comp().unwrap().layer(crate::project::LayerId(l)).unwrap().props.group("text/pathOptions").unwrap().uid;+ for selector in [json!({"path": "text"}), json!({"path": "text/pathOptions"}), json!({"path": format!("@{uid}")}), json!({"prop": uid})] {+ let mut params = selector;+ params["layer"] = json!(l);+ for cmd in ["prop.get", "prop.set"] {+ let err = s.execute(cmd, params.clone()).unwrap_err().to_string();+ assert!(err.contains("is a property group"), "{cmd}: {err}");+ assert!(err.contains("get_layer"), "{cmd}: {err}");+ }+ }+ assert!(s.execute("prop.get", json!({"layer": l, "path": "text/sourceText"})).is_ok());+ let err = s.execute("prop.get", json!({"layer": l, "path": "missing"})).unwrap_err().to_string();+ assert!(err.contains("no property `missing`"), "{err}");+ }++ #[test]+ fn prop_get_and_render_rgba8() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"name": "T", "width": 320, "height": 180, "duration": 2.0, "frameRate": 30})).unwrap();+ let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();+ s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [0, 0]})).unwrap();+ s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 1.0, "value": [100, 50]})).unwrap();+ let v = s.execute("prop.get", json!({"layer": l, "path": "transform/position", "time": 1.0})).unwrap();+ assert_eq!(v["animated"], true);+ assert_eq!(v["keys"].as_array().unwrap().len(), 2);+ assert_eq!(v["value"][0].as_f64().unwrap(), 100.0);+ let cid = s.resolve_comp(Some(&json!("T"))).unwrap();+ let (w, h, rgba) = s.render_rgba8(cid, effectcraft_time::Tick::ZERO, 160).unwrap();+ assert_eq!((w, h), (160, 90));+ assert_eq!(rgba.len(), (w * h * 4) as usize);+ }++ #[test]+ fn params_docs_parse() {+ use crate::commands::accepted_params;+ let k = |d: &str| accepted_params(d).unwrap();+ assert_eq!(k("{layers: [id|name|#n], add?, toggle?}"), ["layers", "add", "toggle"]);+ assert_eq!(k("{time? (s) | frame? | timecode?}"), ["time", "frame", "timecode"]);+ assert_eq!(k("{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}"), ["interpolation", "in", "out", "autoBezier"]);+ assert_eq!(k("{keys: [{layer, prop, time}], add?}"), ["keys", "add"]);+ assert_eq!(k("{label: Red|Yellow|Aqua|…, layers?}"), ["label", "layers"]);+ assert_eq!(k("{name?, background? [r,g,b]|#hex, open?}"), ["name", "background", "open"]);+ assert!(k("{}").is_empty());+ assert!(accepted_params("free text").is_none());+ // Every registered command documents its params as a parseable key list.+ for c in crate::command_specs() {+ assert!(accepted_params(c.params).is_some(), "{}: {}", c.id, c.params);+ }+ }++ #[test]+ fn execute_checked_rejects_unknown_params() {+ let mut s = demo();+ let e = s.execute_checked("layer.select", json!({"index": 2})).unwrap_err().to_string();+ assert!(e.contains("`index`") && e.contains("layers, add, toggle"), "{e}");+ s.execute_checked("layer.select", json!({"layers": ["#2"]})).unwrap();+ assert_eq!(s.state.selected_layers.len(), 1);+ // Aliases and always-accepted keys.+ s.execute_checked("layer.select", json!({"layer": "#1", "comp": s.active_comp_id().unwrap().0})).unwrap();+ s.execute_checked("time.set", json!({"frame": 3})).unwrap();+ assert!(s.execute_checked("edit.undo", json!({"steps": 2})).is_err());+ // Non-object params are not validated; the unchecked path stays lenient.+ s.execute("layer.select", json!({"layers": ["#1"], "index": 2})).unwrap();+ }++ #[test]+ fn layer_tree_paths_resolve() {+ let mut s = demo();+ s.execute("effect.apply", json!({"layer": 1, "effect": "Gaussian Blur"})).unwrap();+ let comp = s.execute("comp.info", json!({})).unwrap();+ let mut checked = 0;+ for l in comp["layers"].as_array().unwrap() {+ let tree = s.execute("layer.tree", json!({"layer": l["id"]})).unwrap();+ let mut stack = vec![tree["properties"].clone()];+ while let Some(n) = stack.pop() {+ if let Some(ch) = n["children"].as_array() {+ stack.extend(ch.iter().cloned());+ continue;+ }+ let path = n["path"].as_str().unwrap();+ let got = s.execute("prop.get", json!({"layer": l["id"], "path": path})).unwrap();+ assert_eq!(got["uid"], n["uid"], "path {path} on layer {}", l["name"]);+ checked += 1;+ }+ }+ assert!(checked > 20, "{checked}");+ }++ #[test]+ fn comp_settings_anchor_start_timecode_renderer() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"name": "A", "width": 100, "height": 100, "duration": 2.0})).unwrap();+ let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();+ s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [10, 20]})).unwrap();+ let pos = |s: &Session| {+ let pr = s.active_comp().unwrap().layer(crate::project::LayerId(l)).unwrap().props.prop("transform/position").unwrap().clone();+ pr.keys[0].value.components()+ };+ // Center anchor: grow by 100x50 → shift by half.+ s.execute("comp.settings", json!({"width": 200, "height": 150})).unwrap();+ assert_eq!(pos(&s)[..2], [60.0, 45.0]);+ // Top-left anchor: no shift. Bottom-right: full shift.+ s.execute("comp.settings", json!({"width": 300, "anchor": 0})).unwrap();+ assert_eq!(pos(&s)[..2], [60.0, 45.0]);+ s.execute("comp.settings", json!({"width": 200, "height": 100, "anchor": 8})).unwrap();+ assert_eq!(pos(&s)[..2], [-40.0, -5.0]);+ s.execute("comp.settings", json!({"startTimecode": "0:00:01:00", "renderer": "advanced3D"})).unwrap();+ let c = s.active_comp().unwrap();+ assert_eq!(c.display_start, c.frame_rate.tick_of(30));+ assert_eq!(c.renderer, crate::project::Renderer::Advanced3D);+ }++ /// `advanced3D` is a value of `renderer`, not a key: comp.new / comp.settings don't advertise it+ /// in their schemas and reject it as unknown instead of ignoring it (#177).+ #[test]+ fn renderer_values_are_not_parameter_keys() {+ let mut s = Session::default();+ for (id, p) in [("comp.new", json!({"name": "A"})), ("comp.settings", json!({}))] {+ let spec = crate::command_specs().iter().find(|c| c.id == id).unwrap();+ let keys = crate::commands::accepted_params(spec.params).unwrap();+ assert!(keys.contains(&"renderer".to_string()) && !keys.contains(&"advanced3D".to_string()), "{id}: {keys:?}");+ let mut bad = p.clone();+ bad["advanced3D"] = json!(true);+ let e = s.execute_checked(id, bad).unwrap_err().to_string();+ assert!(e.contains("unknown parameter(s) `advanced3D`"), "{id}: {e}");+ let mut good = p;+ good["renderer"] = json!("advanced3D");+ s.execute_checked(id, good).unwrap();+ assert_eq!(s.active_comp().unwrap().renderer, crate::project::Renderer::Advanced3D, "{id}");+ s.execute("comp.renderer", json!({"renderer": "classic3d"})).unwrap();+ }+ }++ #[test]+ fn comp_rejects_zero_and_negative_frame_rates() {+ let mut s = Session::default();+ for fps in [0.0, -30.0, 0.0001] {+ assert!(s.execute("comp.new", json!({"frameRate": fps})).is_err(), "{fps}");+ }+ s.execute("comp.new", json!({"frameRate": 30, "duration": 1})).unwrap();+ assert!(s.execute("comp.settings", json!({"frameRate": 0})).is_err());+ assert_eq!(s.active_comp().unwrap().frame_rate, crate::time::FrameRate::FPS_30);+ }++ #[test]+ fn render_queue_add_accepts_documented_settings_when_checked() {+ let mut s = demo();+ let r = s.execute_checked(+ "renderQueue.add",+ json!({"format": "gif", "output": "/tmp/x.gif", "resolution": "quarter", "timeSpan": "custom", "start": 0.0, "end": 0.5, "quality": "draft", "loop": true}),+ );+ // Without an exporter the add itself still succeeds (rendering is what needs one).+ assert!(r.is_ok(), "{r:?}");+ assert!(s.execute_checked("renderQueue.add", json!({"bogus": 1})).is_err());+ }++ #[test]+ fn new_text_rejects_malformed_positions_without_creating_a_layer() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"name": "C", "width": 64, "height": 64, "duration": 1})).unwrap();+ for position in [json!([]), json!([10]), json!(["x", 20]), json!([null, 20])] {+ let err = s.execute("layer.newText", json!({"text": "Hello", "position": position})).unwrap_err();+ assert!(err.to_string().contains("position: [x, y]"), "{err}");+ assert!(s.active_comp().unwrap().layers.is_empty());+ }+ s.execute("layer.newText", json!({"name": "Valid", "text": "Hello", "position": [10, 20]})).unwrap();+ assert_eq!(s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().value, effectcraft_keyframe::Value::Vec3([10.0, 20.0, 0.0]));+ s.execute("layer.newText", json!({"text": "No explicit position"})).unwrap();+ assert_eq!(s.active_comp().unwrap().layers.len(), 2);+ }++ /// The active comp and the open comp tabs are saved with the project and restored on open (#748).+ #[test]+ fn reopening_a_project_restores_its_active_comp() {+ use effectcraft_project::ItemId;+ let dir = std::env::temp_dir().join(format!("ec-test-748-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("view.ecproj").to_string_lossy().to_string();+ let mut s = Session::default();+ let a = s.execute("comp.new", json!({"name": "CompA"})).unwrap()["comp"].as_u64().unwrap();+ let b = s.execute("comp.new", json!({"name": "CompB"})).unwrap()["comp"].as_u64().unwrap();+ let c = s.execute("comp.new", json!({"name": "CompC"})).unwrap()["comp"].as_u64().unwrap();+ s.execute("comp.open", json!({"comp": "CompB"})).unwrap();+ s.state.open_comps.retain(|id| id.0 != c);+ s.execute("file.saveAs", json!({"path": path})).unwrap();+ let mut s2 = Session::default();+ s2.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!(s2.state.active_comp, Some(ItemId(b)));+ assert_eq!(s2.state.open_comps, vec![ItemId(a), ItemId(b)]);+ assert!(!s2.is_dirty());++ // A file from before the view was saved opens on its first comp, as it always did.+ let text = std::fs::read_to_string(&path).unwrap();+ let mut old: serde_json::Value = serde_json::from_str(&text).unwrap();+ let obj = old.as_object_mut().unwrap();+ obj.remove("activeComp");+ obj.remove("openComps");+ std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();+ let mut s3 = Session::default();+ s3.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!((s3.state.active_comp, s3.state.open_comps.clone()), (Some(ItemId(a)), vec![ItemId(a)]));++ // Ids that no longer name a comp (edited by hand, or written by another tool) fall back.+ obj_set(&mut old, json!(999), json!([999, b, "x"]));+ std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();+ let mut s4 = Session::default();+ s4.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!((s4.state.active_comp, s4.state.open_comps.clone()), (Some(ItemId(b)), vec![ItemId(b)]));+ obj_set(&mut old, json!(999), json!([]));+ std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();+ let mut s5 = Session::default();+ s5.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!((s5.state.active_comp, s5.state.open_comps.clone()), (Some(ItemId(a)), vec![ItemId(a)]));++ // XML copies carry it too.+ let xml = dir.join("view.ecprojx").to_string_lossy().to_string();+ s.execute("file.saveAs", json!({"path": xml})).unwrap();+ let mut s6 = Session::default();+ s6.execute("file.open", json!({"path": xml})).unwrap();+ assert_eq!(s6.state.active_comp, Some(ItemId(b)));+ let _ = std::fs::remove_dir_all(dir);++ fn obj_set(v: &mut serde_json::Value, active: serde_json::Value, open: serde_json::Value) {+ let o = v.as_object_mut().unwrap();+ o.insert("activeComp".into(), active);+ o.insert("openComps".into(), open);+ }+ }++ /// Layer times are saved as exact ticks and read back unchanged, and each comp reopens at the+ /// current time it was saved at, not at 0, where a layer starting later shows nothing (#1714).+ #[test]+ fn reopening_a_project_restores_layer_times_and_current_time() {+ use effectcraft_project::ItemId;+ use effectcraft_time::{FrameRate, Tick};+ let dir = std::env::temp_dir().join(format!("ec-test-1714-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("times.ecproj").to_string_lossy().to_string();+ let mut s = Session::default();+ s.execute("comp.new", json!({"name": "C", "width": 108, "height": 192, "duration": 60})).unwrap();+ s.execute("layer.newSolid", json!({"name": "crown"})).unwrap();+ let cid = s.active_comp_id().unwrap();+ let comp = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap();+ comp.frame_rate = FrameRate::FPS_59_94;+ // The layer from the issue: 34f, 315f and 3033f at 59.94 fps.+ let l = comp.layers.first_mut().unwrap();+ (l.start_time, l.in_point, l.out_point) = (Tick(144_086_342_400), Tick(1_334_917_584_000), Tick(12_853_349_308_800));+ s.execute("time.set", json!({"time": 6.0})).unwrap();+ let t = s.time();+ // A second comp keeps its own time.+ let b = ItemId(s.execute("comp.new", json!({"name": "B"})).unwrap()["comp"].as_u64().unwrap());+ s.execute("time.set", json!({"time": 2.0})).unwrap();+ let tb = s.time();+ s.execute("comp.open", json!({"comp": "C"})).unwrap();+ s.execute("file.saveAs", json!({"path": path})).unwrap();++ let mut s2 = Session::default();+ s2.execute("file.open", json!({"path": path})).unwrap();+ let l = s2.project.comp(cid).unwrap().layers.first().unwrap();+ assert_eq!((l.start_time, l.in_point, l.out_point), (Tick(144_086_342_400), Tick(1_334_917_584_000), Tick(12_853_349_308_800)));+ assert_eq!((s2.time(), s2.state.times.get(&b).copied()), (t, Some(tb)));+ assert!(l.in_point <= s2.time() && s2.time() < l.out_point, "the layer shows at the reopened time");+ assert!(!s2.is_dirty());++ // Hand-edited times past the end or before the start land on the last or first frame.+ let mut file: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();+ file["compTimes"] = json!({cid.0.to_string(): i64::MAX, b.0.to_string(): -5});+ std::fs::write(&path, file.to_string()).unwrap();+ let mut s3 = Session::default();+ s3.execute("file.open", json!({"path": path})).unwrap();+ let c = s3.project.comp(cid).unwrap();+ assert_eq!(s3.time(), c.frame_rate.snap_nearest(c.duration - c.frame_duration()));+ assert_eq!(s3.time(), c.frame_rate.snap_nearest(c.duration - c.frame_duration()));+ assert_eq!(s3.state.times.get(&b).copied(), Some(Tick::ZERO));+ }diff --cc crates/ui-egui/src/header.rsindex c4037120f,3eee89453..45caa86de--- a/crates/ui-egui/src/header.rs+++ b/crates/ui-egui/src/header.rs@@@ -131,12 -74,87 +74,96 @@@ fn tool_slots(app: &mut EffectcraftAppx += 6.0;}}+ x+ }- // Tool options.- x += 10.0;- // Selected shape layers: the options show their paint and edit it (as in After Effects).- let shape_layers: Vec<u64> = app- .session+ /// One tool slot button in `r`: select on click, Ctrl+double-click Pan Behind, and the fly-out.+ fn tool_slot(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, si: usize, slot: &[Tool], r: Rect, held_id: egui::Id) {+ let t = app.tokens;+ let cur = app.ui.slot_tools.get(si).copied().unwrap_or(slot[0]);+ let active = slot.contains(&app.ui.tool);+ let id = egui::Id::unique(("tool-slot", si));+ let resp = widgets::icon_button(ui, r, cur.icon(), active, &t, id);+ if slot.len() > 1 {+ // Flyout corner triangle.+ p.add(egui::Shape::convex_polygon(+ vec![pos2(r.max.x - 2.0, r.max.y - 6.0), pos2(r.max.x - 2.0, r.max.y - 2.0), pos2(r.max.x - 6.0, r.max.y - 2.0)],+ if active { Color32::WHITE } else { t.text_dim },+ Stroke::NONE,+ ));+ }+ app.auto.add_response(&format!("tools.{cur:?}"), &resp, cur.label());+ let tip = match cur.shortcut() {+ Some(s) => format!("{} ({})", cur.label(), crate::menus::shortcut_text(s)),+ None => cur.label().to_string(),+ };+ let resp = resp.on_hover_text(tip);+ let held = ui.data(|d| d.get_temp::<egui::Id>(held_id)) == Some(id);+ if resp.clicked() && !held {+ app.ui.tool = cur;+ }+ // Ctrl+double-click Pan Behind: Center Anchor Point in Layer Content.+ if cur == Tool::PanBehind+ && resp.double_clicked()+ && ui.input(|i| i.modifiers.command)+ && let Err(e) = crate::menus::invoke(app, ui.ctx(), "layer.centerAnchor", json!({}))+ {+ app.ui.status = e;+ }++ // Double-click a shape tool: a shape layer filling the composition, centred, for++ // backgrounds, mattes and overlays (as After Effects does).++ if cur.is_shape()++ && resp.double_clicked()++ && let Some((w, h)) = app.session.active_comp().map(|c| (c.width, c.height))++ && let Err(e) = crate::menus::invoke(app, ui.ctx(), "layer.newShape", json!({"kind": crate::panels::viewer::shape_kind(cur), "size": [w, h]}))++ {++ app.ui.status = e;++ }+ if slot.len() > 1 {+ slot_flyout(app, ui, si, slot, &resp, held_id);+ }+ }++ /// The fly-out menu of a multi-tool slot: right-click or press-and-hold opens it.+ fn slot_flyout(app: &mut EffectcraftApp, ui: &mut egui::Ui, si: usize, slot: &[Tool], resp: &egui::Response, held_id: egui::Id) {+ let id = resp.id;+ let held = ui.data(|d| d.get_temp::<egui::Id>(held_id)) == Some(id);+ let held_for = resp.is_pointer_button_down_on().then(|| ui.input(|i| i.pointer.press_start_time().map(|s| i.time - s))).flatten();+ if let Some(seconds) = held_for+ && seconds < 0.35+ {+ ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds));+ }+ let long_press = held_for.is_some_and(|seconds| seconds >= 0.35) && !held;+ let command = if resp.secondary_clicked() || long_press {+ if long_press {+ ui.data_mut(|d| d.insert_temp(held_id, id));+ }+ Some(egui::SetOpenCommand::Bool(true))+ } else if resp.clicked() && !held {+ Some(egui::SetOpenCommand::Bool(false))+ } else {+ None+ };+ let close_behavior = if held && resp.clicked() { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClickOutside };+ egui::Popup::menu(resp).style(crate::widgets::menu_style).open_memory(command).close_behavior(close_behavior).show(|ui| {+ for tool in slot.iter() {+ let row = ui.selectable_label(app.ui.tool == *tool, tool.label());+ app.auto.add(&format!("tools.select.{tool:?}"), row.rect, tool.label());+ if row.clicked() {+ app.ui.tool = *tool;+ if let Some(saved) = app.ui.slot_tools.get_mut(si) {+ *saved = *tool;+ }+ ui.close();+ }+ }+ });+ }++ /// The ids of the selected shape layers: the options show their paint and edit it.+ fn selected_shape_layers(app: &EffectcraftApp) -> Vec<u64> {+ app.session.active_comp().map(|c| {app.session.state.selected_layers.iter().filter(|id| c.layer(**id).is_some_and(|l| matches!(l.source, LayerSource::Shape))).map(|id| id.0).collect()diff --cc crates/ui-egui/src/menus/invoke.rsindex 000000000,b266623f3..2c99274edmode 000000,100644..100644--- a/crates/ui-egui/src/menus/invoke.rs+++ b/crates/ui-egui/src/menus/invoke.rs@@@ -1,0 -1,692 +1,698 @@@+ use super::frontend::{file_dialog, frontend, run_engine};+ use super::shortcuts::system_paste_id;+ use super::*;++ pub fn panel_command_id(p: PanelKind) -> String {+ format!("window.panel.{}", p.id())+ }++ /// The reveal shortcuts (P, S, R, T, A, E, M, F, L…). `add` (Shift+key) adds the property to+ /// (or removes it from) those already revealed instead of replacing them.+ pub fn reveal(app: &mut EffectcraftApp, kind: &str, now: f64, add: bool) {+ // The double-press shortcuts: the same key again within 0.6 s reveals its second set (LL+ // Waveform, TT Mask Opacity, MM all mask properties, EE Expressions, RR Time Remap, AA+ // Material Options, PP paint / Roto Brush / Puppet, SS selected properties, FF missing+ // effects). A single M shows Mask Path.+ let double = |k: &str| -> Option<&'static str> {+ Some(match k {+ "levels" => "waveform",+ "opacity" => "maskOpacity",+ "masks" => "masks",+ "effects" => "expressions",+ "rotation" => "timeRemap",+ "anchor" => "material",+ "position" => "paint",+ "scale" => "selected",+ "feather" => "missingEffects",+ _ => return None,+ })+ };+ let pressed = kind;+ // (With Shift a second press removes the property again instead.)+ let again = !add && matches!(app.last_reveal.take(), Some((k, t)) if k == pressed && now - t < 0.6);+ app.last_reveal = Some((if again { String::new() } else { pressed.to_string() }, now));+ let kind = match (again, double(pressed)) {+ (true, Some(d)) => {+ // The second press replaces what the first one revealed.+ let first = if pressed == "masks" { "maskPath" } else { pressed };+ app.ui.timeline.reveal.retain(|k| k != first);+ d+ }+ _ if pressed == "masks" => "maskPath",+ _ => pressed,+ };+ let targets = reveal_targets(app);+ let tl = &mut app.ui.timeline;+ let present = tl.reveal.iter().any(|k| k == kind);+ let mut kinds = tl.reveal.clone();+ if add {+ if present {+ kinds.retain(|k| k != kind);+ } else {+ kinds.retain(|k| k != "props" || !tl.reveal_props.is_empty());+ kinds.push(kind.to_string());+ }+ } else if present && kinds.len() == 1 {+ kinds.clear();+ } else {+ kinds = vec![kind.to_string()];+ }+ tl.apply_reveal(&targets, kinds.clone());+ crate::panels::timeline::open_revealed(app, &targets, &kinds);+ }++ /// Show Time Remap on the layers of a `layer.enableTimeRemap` (`layers` by id, else the+ /// selected ones) that have it now.+ fn reveal_time_remap(app: &mut EffectcraftApp, params: &Value) {+ let asked: Vec<u64> = match params.get("layers").and_then(Value::as_array) {+ Some(a) => a.iter().filter_map(Value::as_u64).collect(),+ None => app.session.state.selected_layers.iter().map(|l| l.0).collect(),+ };+ let Some(comp) = app.session.active_comp() else { return };+ let layers: Vec<u64> = comp.layers.iter().filter(|l| asked.contains(&l.id.0) && l.props.get("timeRemap").is_some()).map(|l| l.id.0).collect();+ if !layers.is_empty() {+ app.ui.timeline.apply_reveal(&layers, vec!["timeRemap".into()]);+ }+ }++ /// After Alt+Shift+P (A, S, R, T) the Timeline shows the property on each layer it keyed, as in+ /// After Effects: added to what a reveal shortcut shows, else with the layer's Transform twirled+ /// open, else alone like P.+ fn reveal_keyed(app: &mut EffectcraftApp, keyed: &Value, kind: &str) {+ let layers: std::collections::BTreeSet<u64> = keyed.as_array().into_iter().flatten().filter_map(|k| k.get("layer").and_then(Value::as_u64)).collect();+ let Some(comp) = app.session.active_comp() else { return };+ let tl = &mut app.ui.timeline;+ for id in layers {+ let shown = tl.layer_reveal.get(&id).filter(|k| !k.is_empty()).cloned();+ match shown {+ Some(mut kinds) => {+ if !kinds.iter().any(|k| k == kind) {+ kinds.push(kind.to_string());+ tl.layer_reveal.insert(id, kinds);+ }+ }+ None if tl.open_layers.contains(&id) => {+ if let Some(tr) = comp.layer(effectcraft_engine::project::LayerId(id)).and_then(|l| l.transform()) {+ tl.open_groups.insert(tr.uid);+ }+ }+ None => {+ tl.open_layers.insert(id);+ tl.layer_reveal.insert(id, vec![kind.to_string()]);+ }+ }+ }+ }++ /// The layers a reveal shortcut acts on: the selected ones, else every layer of the active comp.+ fn reveal_targets(app: &EffectcraftApp) -> Vec<u64> {+ if app.session.state.selected_layers.is_empty() {+ app.session.active_comp().map(|c| c.layers.iter().map(|l| l.id.0).collect()).unwrap_or_default()+ } else {+ app.session.state.selected_layers.iter().map(|l| l.0).collect()+ }+ }++ /// The arrow keys nudge the selected layers 1 pixel at the viewer's magnification (`up`,+ /// `down`, `left`, `right`), 10 with Shift (`up10`…), as After Effects does, so zoomed in+ /// they move by fractions of a comp pixel. From any panel except Project (which owns the+ /// arrow keys for its own keyboard navigation, #961); not while typing, with a dialog or+ /// menu open. With mask points selected the arrows move the points instead (#1288).+ fn nudge(app: &mut EffectcraftApp, ctx: &egui::Context, dir: &str) -> Result<Value, String> {+ let (side, n) = match dir.strip_suffix("10") {+ Some(side) => (side, 10.0),+ None => (dir, 1.0),+ };+ let (x, y) = match side {+ "up" => (0.0, -n),+ "down" => (0.0, n),+ "left" => (-n, 0.0),+ "right" => (n, 0.0),+ _ => return Err(format!("unknown nudge `{dir}`")),+ };+ let st = &app.session.state;+ if app.ui.focused == PanelKind::Project || (st.selected_layers.is_empty() && st.selected_vertices.is_empty()) || st.text_edit.is_some() {+ return Ok(Value::Null);+ }+ // Screen pixels per comp pixel.+ let zoom = (app.ui.viewer.zoom.unwrap_or_else(|| crate::panels::viewer::last_fit(ctx)) * ctx.pixels_per_point()) as f64;+ let k = if zoom.is_finite() && zoom > 1e-6 { 1.0 / zoom } else { 1.0 };+ if let Some(layer) = st.selected_vertices.first().map(|v| v.layer) {+ let d = vertex_delta(app, layer, [x * k, y * k]);+ return run_engine(app, ctx, "mask.moveVertices", json!({"delta": d}));+ }+ run_engine(app, ctx, "layer.nudge", json!({"x": x * k, "y": y * k}))+ }++ /// A comp-space step `d` in the layer space of `layer`, where mask points live. Like a drag of+ /// the points in the viewer, every selected point takes the first one's layer space.+ fn vertex_delta(app: &EffectcraftApp, layer: effectcraft_engine::project::LayerId, d: [f64; 2]) -> [f64; 2] {+ use effectcraft_engine::geom::vec2;+ let s = &app.session;+ let (Some(cid), Some(comp)) = (s.active_comp_id(), s.active_comp()) else { return d };+ let Some(l) = comp.layer(layer) else { return d };+ let ectx = effectcraft_engine::render::EvalCtx { project: &s.project, comp_id: cid, comp, time: s.time(), expr: s.expr.as_deref(), footage: None };+ let (l2c, _) = crate::panels::viewer::l2c(&ectx, l);+ l2c.inverse().map_or(d, |inv| {+ let v = inv.apply_vec(vec2(d[0], d[1]));+ [v.x, v.y]+ })+ }++ fn no_params(p: &Value) -> bool {+ p.as_object().is_none_or(|m| m.is_empty())+ }++ /// `{"comp": id}` and nothing else: Composition Settings opens on that comp instead of+ /// applying no settings to it.+ fn only_comp(p: &Value) -> Option<effectcraft_engine::project::ItemId> {+ let m = p.as_object().filter(|m| m.len() == 1)?;+ m.get("comp")?.as_u64().map(effectcraft_engine::project::ItemId)+ }++ /// Execute a UI or engine command by id.+ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {+ if matches!(id, "effects.copyPresetsFolderPath" | "mediaBrowser.copySourcePath") {+ return frontend(app, ctx, id, params);+ }+ // Layer ▸ New ▸ Text (menu, shortcut, context menus) puts an insertion point in the centre of+ // the comp, as After Effects does, so typing goes into Source Text rather than running+ // shortcuts (#866). `engine.execute` keeps the headless default.+ if id == "layer.newText" && no_params(¶ms) {+ return run_engine(app, ctx, id, json!({"text": "", "edit": true}));+ }+ // A new folder (File ▸ New, its shortcut, the Project panel's button and context menu) opens+ // with its name ready to type, as in After Effects (#1658). The command selects it.+ // `engine.execute` keeps the headless default.+ if id == "project.newFolder" && no_params(¶ms) {+ let r = run_engine(app, ctx, id, params);+ if r.is_ok() {+ app.show_panel(PanelKind::Project);+ crate::panels::project::begin_rename(app, ctx);+ }+ return r;+ }+ // The Project-panel focus redirects apply only while no text edit is open: creating a text+ // layer leaves focus on Project while the insertion point lives in the comp, so during an+ // edit these commands address the text context — redirected, Deselect All would clear a+ // project selection the user is not looking at and silently swallow the edit's own end.+ if no_params(¶ms) && app.ui.focused == PanelKind::Project && app.session.state.text_edit.is_none() {+ match id {+ "edit.duplicate" => return run_engine(app, ctx, "project.duplicate", json!({})),+ "edit.selectAll" => {+ let items: Vec<u64> = crate::panels::project::visible_rows(app)+ .into_iter()+ .filter(|(id, _)| app.ui.project_search.is_empty() || app.session.project.item(*id).is_some_and(|it| !it.is_folder()))+ .map(|(id, _)| id.0)+ .collect();+ return run_engine(app, ctx, "project.select", json!({"items":items}));+ }+ "edit.deselectAll" => return run_engine(app, ctx, "project.select", json!({"items":[]})),+ "edit.cut" | "edit.copy" | "edit.paste" | "edit.copyWithPropertyLinks" | "edit.copyWithRelativePropertyLinks" | "edit.copyExpressionOnly" => {+ return Err("Project clipboard actions are not supported yet".into());+ }+ _ => {}+ }+ }++ // Close follows panel focus too: with the Render Queue active, Cmd+W closes that panel and++ // leaves the active composition open (it used to close the composition next to it).++ if id == "file.close" && params.as_object().is_some_and(|p| p.is_empty()) && app.ui.focused == PanelKind::RenderQueue {++ app.close_panel(PanelKind::RenderQueue);++ return Ok(Value::Null);++ }+ // Edit ▸ Paste with SVG markup on the system clipboard pastes it as a shape layer (After+ // Effects 26.3). Copying in the app replaces the system clipboard with a note naming what+ // was copied, so SVG there was copied after anything copied in the app.+ if id == "edit.paste" && no_params(¶ms) && app.session.state.text_edit.is_none() {+ let text = ctx.data_mut(|d| d.remove_temp::<String>(system_paste_id())).or_else(|| app.hooks.clipboard_text.as_ref().and_then(|f| f()));+ if let Some(svg) = text.filter(|t| effectcraft_engine::vector::is_svg_text(t)) {+ return run_engine(app, ctx, "edit.pasteSvg", json!({"svg": svg}));+ }+ }+ // Clear follows panel focus, including the Edit menu and keyboard shortcut.+ if id == "edit.clear" && params.as_object().is_some_and(|p| p.is_empty()) && app.ui.focused == PanelKind::Project {+ // Through `invoke`, so deleting items that compositions use still asks first (M3.16).+ return invoke(app, ctx, "project.delete", json!({}));+ }+ if id == "edit.clear" && params.as_object().is_some_and(|p| p.is_empty()) && app.ui.focused == PanelKind::RenderQueue {+ let selected = ctx.data(|d| d.get_temp::<(Vec<u64>, Option<u64>)>(egui::Id::unique("rq-ui"))).and_then(|(_, id)| id);+ return match selected {+ Some(item) => run_engine(app, ctx, "renderQueue.remove", json!({"item": item})),+ None => Err("select a Render Queue item first".into()),+ };+ }+ // Shift+Delete deletes the Project panel's selection without asking; it does nothing in the+ // other panels.+ if id == "project.deleteWithoutConfirmation" {+ if app.ui.focused != PanelKind::Project {+ return Ok(Value::Null);+ }+ return crate::panels::delete_items::delete_confirmed(app, ctx, json!({}));+ }+ let now = app.now();+ // Closing a modified project asks to save it first; the command runs once answered.+ if crate::panels::unsaved::guard(app, id, ¶ms) {+ return Ok(json!({"dialog": "unsavedChanges"}));+ }+ // Deleting Project items that compositions use asks first, as in After Effects.+ if crate::panels::delete_items::guard(app, id, ¶ms) {+ return Ok(json!({"dialog": "deleteItems"}));+ }+ // J / K and Select All Keyframes act on what the Timeline shows (its revealed properties).+ if matches!(id, "time.nextKey" | "time.previousKey" | "keys.selectAll")+ && ["visible", "layers", "layer", "prop"].iter().all(|k| params.get(*k).is_none())+ && let Some(c) = app.session.active_comp_arc()+ {+ let mut p = if params.is_object() { params.clone() } else { json!({}) };+ p["visible"] = json!(crate::panels::timeline::visible_props(app, &c));+ return run_engine(app, ctx, id, p);+ }+ // New Camera/Light and Camera/Light Settings without parameters open their dialogs.+ if crate::panels::dialogs_3d::route(app, id, ¶ms)? {+ return Ok(Value::Null);+ }+ // New 3D Primitive without parameters opens its dialog.+ if crate::panels::primitive_dialog::route(app, id, ¶ms)? {+ return Ok(Value::Null);+ }+ // Layer Settings on a solid, adjustment layer or null opens its settings dialog.+ if crate::panels::dialogs::route_layer_settings(app, id, ¶ms)? {+ return Ok(Value::Null);+ }+ // Layer ▸ Layer Styles ▸ <style> from the menu adds the style and opens the dialog on it.+ if crate::panels::layer_styles_dialog::route(app, id, ¶ms)? {+ return Ok(Value::Null);+ }+ // Shared docking: `window.dockAction`, craft-ui's `window.panel.*` commands, `ui.dock`,+ // `ui.dock.reset` and `window.panelWindow`.+ if let Some(result) = crate::dock_ui::route(app, ctx, id, ¶ms) {+ return result;+ }+ // Legacy per-panel / per-workspace ids (`window.panel.Project`, `window.workspace.default`).+ if let Some(rest) = id.strip_prefix("window.panel.") {+ return frontend(app, ctx, "window.panel", json!({"panel": rest}));+ }+ if let Some(ws) = id.strip_prefix("window.workspace.") {+ if ws == "reset" {+ return frontend(app, ctx, "window.resetWorkspace", json!({}));+ }+ return frontend(app, ctx, "window.workspace", json!({"name": ws}));+ }+ if let Some(t) = id.strip_prefix("tool.") {+ // C cycles through the camera tools.+ if t == "camera" {+ let tools = [Tool::Orbit, Tool::PanCamera, Tool::Dolly];+ let next = match tools.iter().position(|x| *x == app.ui.tool) {+ Some(i) => tools[(i + 1) % tools.len()],+ None => Tool::Orbit,+ };+ app.ui.tool = next;+ return Ok(json!({"tool": next}));+ }+ // Slot shortcuts cycle through the slot's tools.+ let slot = match t {+ "shape" => Some(8),+ "pen" => Some(9),+ "type" => Some(10),+ "brush" => Some(11),+ "rotoBrush" => Some(14),+ "puppet" => Some(15),+ _ => None,+ };+ if let Some(si) = slot {+ let tools: Vec<Tool> = match si {+ 11 => vec![Tool::Brush, Tool::Clone, Tool::Eraser],+ _ => crate::state::Tool::SLOTS[si].to_vec(),+ };+ let cur = tools.iter().position(|x| *x == app.ui.tool);+ let next = match cur {+ Some(i) => tools[(i + 1) % tools.len()],+ None => app.ui.slot_tools.get(si).copied().filter(|x| tools.contains(x)).unwrap_or(tools[0]),+ };+ app.ui.tool = next;+ if si < app.ui.slot_tools.len() && si != 11 {+ app.ui.slot_tools[si] = next;+ }+ return Ok(json!({"tool": next}));+ }+ let tool = Tool::from_name(t).ok_or_else(|| format!("unknown tool `{t}`"))?;+ app.ui.tool = tool;+ return Ok(json!({"tool": tool}));+ }+ if let Some(dir) = id.strip_prefix("viewer.nudge.") {+ return nudge(app, ctx, dir);+ }+ if let Some(k) = id.strip_prefix("timeline.reveal.") {+ if k == "animated" {+ return run_engine(app, ctx, "anim.reveal", json!({"kind": "keyframes"}));+ }+ reveal(app, k, now, false);+ return Ok(Value::Null);+ }+ if let Some(k) = id.strip_prefix("timeline.keyAt.") {+ let r = run_engine(app, ctx, "keys.toggleTransform", json!({"prop": k}))?;+ reveal_keyed(app, &r, k);+ return Ok(r);+ }+ if let Some(k) = id.strip_prefix("timeline.revealAdd.") {+ reveal(app, k, now, true);+ return Ok(json!({"revealed": app.ui.timeline.reveal}));+ }+ // U reveals keyframed properties; UU (pressed twice quickly) all modified properties; U+ // again later hides them.+ if id == "anim.reveal" && params.get("kind").and_then(Value::as_str) == Some("keyframes") {+ let last = app.last_reveal.take();+ app.last_reveal = Some(("keyframes".into(), now));+ match last {+ Some((k, t)) if k == "keyframes" && now - t < 0.6 => {+ return run_engine(app, ctx, "anim.reveal", json!({"kind": "modified"}));+ }+ Some((k, _)) if k == "keyframes" && app.ui.timeline.reveal == ["props"] => {+ let targets = reveal_targets(app);+ app.ui.timeline.apply_reveal(&targets, vec![]);+ return Ok(json!({"revealed": 0}));+ }+ _ => {}+ }+ }+ // A UI-only command (not in the engine's menus), so `frontend` gets it from here.+ if id == "window.maximizeApp" {+ return frontend(app, ctx, id, params);+ }+ // Docking: {panel, anchor, zone: center|left|right|top|bottom}, {panel, rect?}, {panel?}.+ if let Some(op) = id.strip_prefix("window.").filter(|o| matches!(*o, "maximizePanel" | "dockPanel" | "floatPanel" | "closePanel")) {+ let panel_of = |k: &str| params.get(k).and_then(Value::as_str).map(|s| PanelKind::from_name(s).ok_or(format!("unknown panel `{s}`")));+ match op {+ "maximizePanel" => {+ let p = match panel_of("panel") {+ Some(p) => p?,+ None => app.panel_at(ctx.pointer_hover_pos()),+ };+ app.toggle_maximize(p);+ return Ok(json!({"maximized": app.ui.maximized}));+ }+ "closePanel" => {+ let p = panel_of("panel").ok_or("closePanel: need `panel`")??;+ if app.ui.dock.is_open(p) {+ app.apply_dock(craft_ui::docking::Action::Close { panel: p })?;+ }+ return Ok(Value::Null);+ }+ "floatPanel" => {+ let p = panel_of("panel").ok_or("floatPanel: need `panel`")??;+ let r = match params.get("rect") {+ Some(value) => serde_json::from_value::<[f32; 4]>(value.clone()).map_err(|_| "rect must contain four finite numbers")?,+ None => crate::dock_ui::default_float_rect(ctx.content_rect()),+ };+ app.apply_dock(craft_ui::docking::Action::Float { panel: p, rect: r }).map_err(|e| format!("can't undock {}: {e}", p.title()))?;+ return Ok(Value::Null);+ }+ _ => {+ // craft-ui's `window.panel.dock`: zones center/tab, left/right/top/bottom (a split+ // beside the anchor), above/below; without an anchor a side zone docks along that+ // edge of the whole workspace.+ let p = panel_of("panel").ok_or("dockPanel: need `panel`")??;+ let mut command = json!({"command": "window.panel.dock", "panel": p});+ if let Some(anchor) = panel_of("anchor") {+ command["anchor"] = json!(anchor?);+ command["zone"] = json!("center");+ }+ if let Some(zone) = params.get("zone") {+ let zone = zone.as_str().ok_or("zone: center|tab|left|right|top|bottom|above|below")?.to_ascii_lowercase();+ if command.get("anchor").is_some() || zone != "center" {+ command["zone"] = json!(zone);+ }+ }+ if let Some(before) = panel_of("before") {+ command["before"] = json!(before?);+ }+ let command: craft_ui::docking::DockCommand<PanelKind> =+ serde_json::from_value(command).map_err(|e| format!("dockPanel: zone: center|tab|left|right|top|bottom|above|below ({e})"))?;+ app.run_dock_command(ctx, command).map_err(|e| format!("can't dock {}: {e}", p.title()))?;+ app.show_panel(p);+ return Ok(Value::Null);+ }+ }+ }+ if id == "markers.dialog" {+ // The Composition/Layer Marker dialog (double-click a marker): {layer?, index}.+ let index = params.get("index").and_then(Value::as_u64).ok_or("markers.dialog: need `index`")? as usize;+ let layer = params.get("layer").and_then(Value::as_u64);+ crate::panels::markers_ui::open_dialog(app, crate::panels::markers_ui::MarkerRef { layer, index })?;+ return Ok(json!({"dialog": id}));+ }++ if id == "view.theme.toggle" {+ app.cycle_appearance(ctx);+ return Ok(json!({"appearanceMode": app.session.prefs.appearance.appearance_mode}));+ }+ if let Some(th) = id.strip_prefix("view.theme.") {+ let k = crate::theme::ThemeKind::from_name(th).ok_or("unknown theme")?;+ app.set_theme(ctx, k);+ return Ok(Value::Null);+ }+ let timing = |app: &mut EffectcraftApp, op: &str| app.session.execute("layer.timing", json!({"op": op})).map_err(|e| e.to_string());+ match id {+ "playback.ramPreview" => {+ app.toggle_play_with(now, effectcraft_engine::preview::PreviewShortcut::Numpad0);+ return Ok(json!({"playing": app.playback.playing}));+ }+ "playback.preview.shiftSpacebar" | "playback.preview.shiftNumpad0" | "playback.preview.altNumpad0" => {+ let sc = effectcraft_engine::preview::PreviewShortcut::parse(id.trim_start_matches("playback.preview.")).ok_or("unknown preview shortcut")?;+ app.toggle_play_with(now, sc);+ return Ok(json!({"playing": app.playback.playing}));+ }+ "playback.stop" => {+ app.stop();+ return Ok(Value::Null);+ }+ // The focused Layer panel has its own magnification; otherwise the Composition viewer.+ "view.fit" if app.ui.focused == PanelKind::Layer => {+ app.ui.layer_zoom = None;+ app.ui.layer_pan = [0.0, 0.0];+ return Ok(Value::Null);+ }+ "view.fit" => {+ app.ui.viewer.zoom = None;+ app.ui.viewer.fit_up_to_100 = false;+ app.ui.viewer.pan = [0.0, 0.0];+ return Ok(Value::Null);+ }+ "timeline.scrollToTime" => app.ui.timeline.scroll_to = Some(crate::state::ScrollTo::Time),+ "timeline.scrollToLayer" => app.ui.timeline.scroll_to = Some(crate::state::ScrollTo::Layer),+ "timeline.parentColumn" => {+ let on = !crate::panels::timeline::column_visible(&app.ui.timeline, "parent");+ crate::panels::timeline::set_column(&mut app.ui.timeline, "parent", on)?;+ return Ok(json!({"parent": on}));+ }+ "view.fitUpTo100" => {+ app.ui.viewer.zoom = None;+ app.ui.viewer.fit_up_to_100 = true;+ app.ui.viewer.pan = [0.0, 0.0];+ return Ok(Value::Null);+ }+ // Shift+, / Shift+.: the previous / next open composition (the viewer's tabs).+ "view.nextItem" | "view.previousItem" => {+ let open = app.session.state.open_comps.clone();+ let Some(i) = app.session.state.active_comp.and_then(|c| open.iter().position(|o| *o == c)) else { return Ok(Value::Null) };+ let step = if id == "view.nextItem" { 1 } else { open.len().saturating_sub(1) };+ let Some(next) = open.get((i + step) % open.len().max(1)).copied().filter(|n| Some(*n) != app.session.state.active_comp) else {+ return Ok(Value::Null);+ };+ return run_engine(app, ctx, "comp.open", json!({"comp": next.0}));+ }+ // \\: between the Composition viewer and the Timeline.+ "window.toggleCompTimeline" => {+ let to = if app.ui.focused == PanelKind::Timeline { crate::panels::viewers::active_panel(app) } else { PanelKind::Timeline };+ app.show_panel(to);+ return Ok(json!({"focused": to.id()}));+ }+ // Alt+Shift+, / Alt+Shift+.: the previous / next tab of the focused panel's group.+ "window.nextPanel" | "window.previousPanel" => {+ let focused = app.ui.focused;+ let group = app.ui.dock.group_of(focused);+ let Some(i) = group.iter().position(|p| *p == focused) else { return Ok(Value::Null) };+ let step = if id == "window.nextPanel" { 1 } else { group.len().saturating_sub(1) };+ if let Some(next) = group.get((i + step) % group.len().max(1)).copied() {+ app.show_panel(next);+ }+ return Ok(json!({"focused": app.ui.focused.id()}));+ }+ // Ctrl+Shift+W: with a viewer or the Timeline active, every open composition closes;+ // any other panel closes itself.+ "window.closeAll" => {+ let focused = app.ui.focused;+ if matches!(focused, PanelKind::Composition | PanelKind::Timeline | PanelKind::Viewer(_)) {+ for c in app.session.state.open_comps.clone() {+ run_engine(app, ctx, "comp.close", json!({"comp": c.0}))?;+ }+ } else {+ app.close_panel(focused);+ }+ return Ok(Value::Null);+ }+ "view.actualSize" if app.ui.focused == PanelKind::Layer => {+ app.ui.layer_zoom = Some(1.0 / ctx.pixels_per_point());+ app.ui.layer_pan = [0.0, 0.0];+ return Ok(Value::Null);+ }+ "view.actualSize" => {+ app.ui.viewer.zoom = Some(1.0 / ctx.pixels_per_point());+ app.ui.viewer.pan = [0.0, 0.0];+ return Ok(Value::Null);+ }+ "view.safeMargins" => app.ui.viewer.safe_margins = !app.ui.viewer.safe_margins,+ "view.transparencyGrid" => app.ui.viewer.transparency_grid = !app.ui.viewer.transparency_grid,+ "view.fastPreviews" => {+ // With a mode: Fast Previews ▸ Off / Adaptive Resolution / Draft / Fast Draft /+ // Wireframe; without: toggle Draft quality (Settings ▸ Previews).+ if params.get("mode").is_some() {+ return run_engine(app, ctx, "view.fastPreviewMode", params);+ }+ let on = !app.ui.viewer.fast_preview;+ app.set_pref("previews.fastPreviews", json!(on))?;+ app.ui.viewer.fast_preview = on;+ }+ "timeline.zoomIn" | "timeline.zoomOut" => {+ let k = if id == "timeline.zoomIn" { crate::panels::timeline::ZOOM_STEP } else { 1.0 / crate::panels::timeline::ZOOM_STEP };+ crate::panels::timeline::zoom(app, ctx, k);+ return Ok(Value::Null);+ }+ "timeline.zoomFit" => crate::panels::timeline::toggle_fit_zoom(app, ctx),+ "timeline.zoomFrameToggle" => crate::panels::timeline::toggle_frame_zoom(app, ctx),+ "timeline.column" => {+ let col = params.get("column").and_then(Value::as_str).ok_or("timeline.column: need `column`")?;+ let on = params.get("visible").and_then(Value::as_bool).unwrap_or(!crate::panels::timeline::column_visible(&app.ui.timeline, col));+ crate::panels::timeline::set_column(&mut app.ui.timeline, col, on)?;+ let shown: Vec<&str> =+ crate::panels::timeline::COLUMNS.iter().map(|c| c.0).filter(|c| crate::panels::timeline::column_visible(&app.ui.timeline, c)).collect();+ return Ok(json!({"columns": shown}));+ }+ "timeline.sourceName" => {+ let tl = &mut app.ui.timeline;+ tl.source_name = params.get("value").and_then(Value::as_bool).unwrap_or(!tl.source_name);+ return Ok(json!({"sourceName": tl.source_name}));+ }+ "flowchart.options" | "flowchart.graph" => return crate::panels::flowchart::command(app, id, ¶ms),+ "timeline.search" => {+ app.ui.timeline.search = params.get("query").and_then(Value::as_str).unwrap_or_default().to_string();+ app.show_panel(PanelKind::Timeline);+ }+ "timeline.graphEditor" => app.ui.timeline.graph_editor = !app.ui.timeline.graph_editor,+ "timeline.switchesModes" => app.ui.timeline.show_modes = !app.ui.timeline.show_modes,+ "timeline.collapseAll" => {+ app.ui.timeline.open_layers.clear();+ app.ui.timeline.open_groups.clear();+ app.ui.timeline.reveal.clear();+ app.ui.timeline.layer_reveal.clear();+ }+ // Ctrl+`: twirl the selected layers open (all closed ones) or closed (all open). From a+ // reveal shortcut's view it opens their full property trees.+ "timeline.twirlSelected" => {+ let sel: Vec<u64> = app.session.state.selected_layers.iter().map(|l| l.0).collect();+ let tl = &mut app.ui.timeline;+ let revealing = sel.iter().any(|l| tl.layer_reveal.contains_key(l));+ tl.reveal.clear();+ for l in &sel {+ tl.layer_reveal.remove(l);+ }+ if !revealing && sel.iter().all(|l| tl.open_layers.contains(l)) {+ for l in &sel {+ tl.open_layers.remove(l);+ }+ } else {+ tl.open_layers.extend(sel);+ }+ }+ "timeline.workAreaBegin" => return app.session.execute("comp.workArea", json!({"set": "begin"})).map_err(|e| e.to_string()),+ "timeline.workAreaEnd" => return app.session.execute("comp.workArea", json!({"set": "end"})).map_err(|e| e.to_string()),+ "timeline.moveInToTime" => return timing(app, "moveInToTime"),+ "timeline.moveOutToTime" => return timing(app, "moveOutToTime"),+ "timeline.trimInToTime" => return timing(app, "trimInToTime"),+ "timeline.trimOutToTime" => return timing(app, "trimOutToTime"),+ "app.home" => app.ui.start_screen = !app.ui.start_screen,+ "app.newComp" | "comp.new" if no_params(¶ms) => crate::panels::dialogs::open_new_comp(app),+ "app.compSettings" | "comp.settings" if no_params(¶ms) => crate::panels::dialogs::open_comp_settings(app)?,+ "app.compSettings" | "comp.settings" if only_comp(¶ms).is_some() => {+ crate::panels::dialogs::open_comp_settings_for(app, only_comp(¶ms).ok_or("missing `comp`")?)?+ }+ "app.solidSettings" | "layer.newSolid" if no_params(¶ms) => crate::panels::dialogs::open_new_solid(app)?,+ "keys.velocity" if no_params(¶ms) => crate::panels::key_dialogs::open_velocity(app)?,+ "keys.interpolation" if no_params(¶ms) => crate::panels::key_dialogs::open_interpolation(app)?,+ "layer.timeStretch" if no_params(¶ms) => crate::panels::key_dialogs::open_time_stretch(app)?,+ _ => {+ if id == "renderQueue.render" && params.get("wait").is_none() {+ // The UI renders in the background; the panel shows progress.+ let mut p = params.clone();+ if let Some(m) = p.as_object_mut() {+ m.insert("wait".into(), json!(false));+ } else {+ p = json!({"wait": false});+ }+ app.show_panel(PanelKind::RenderQueue);+ return app.session.execute(id, p).map_err(|e| e.to_string());+ }+ if id == "renderQueue.add" {+ let r = app.session.execute(id, params).map_err(|e| e.to_string());+ match &r {+ Ok(_) => app.show_panel(PanelKind::RenderQueue),+ Err(e) => app.ui.status = e.clone(),+ }+ return r;+ }+ if let Some(r) = file_dialog(app, id, ¶ms) {+ return r;+ }+ if id == "layer.precompose" && params.get("name").is_none() {+ crate::panels::precomp::open(app, ¶ms)?;+ return Ok(json!({"dialog": id}));+ }+ if crate::panels::dialogs::open_form(app, id, ¶ms) {+ return Ok(json!({"dialog": id}));+ }+ if id == "renderQueue.render" && params.get("wait").is_none() {+ // The UI renders in the background; the panel shows progress.+ let mut p = params.clone();+ if let Some(m) = p.as_object_mut() {+ m.insert("wait".into(), json!(false));+ } else {+ p = json!({"wait": false});+ }+ app.show_panel(PanelKind::RenderQueue);+ return app.session.execute(id, p).map_err(|e| e.to_string());+ }+ if id == "renderQueue.add" {+ let r = app.session.execute(id, params).map_err(|e| e.to_string());+ match &r {+ Ok(_) => app.show_panel(PanelKind::RenderQueue),+ Err(e) => app.ui.status = e.clone(),+ }+ return r;+ }+ // An effect added to a layer (Effect menu, Last Effect, dropped on a layer) brings+ // up Effect Controls on that layer, as in After Effects.+ if matches!(id, "effect.apply" | "effect.applyLast") {+ let r = run_engine(app, ctx, id, params.clone());+ if let Ok(applied) = &r {+ crate::panels::effect_controls::reveal_applied(app, ¶ms);+ crate::panels::effect_controls::choose_files_after_apply(app, applied);+ }+ return r;+ }+ // Enabling time remapping twirls its layers open on Time Remap and its two keys.+ if id == "layer.enableTimeRemap" {+ let r = run_engine(app, ctx, id, params.clone());+ if r.as_ref().is_ok_and(|on| on.as_bool() == Some(true)) {+ reveal_time_remap(app, ¶ms);+ }+ return r;+ }+ if id == "layer.rename" && params.get("name").is_none() {+ crate::panels::timeline::begin_rename(app, ctx);+ return Ok(Value::Null);+ }+ return run_engine(app, ctx, id, params);+ }+ }+ Ok(Value::Null)+ }diff --cc crates/ui-egui/src/menus/tests.rsindex 000000000,ed2fcf6ca..ed35e727fmode 000000,100644..100644--- a/crates/ui-egui/src/menus/tests.rs+++ b/crates/ui-egui/src/menus/tests.rs@@@ -1,0 -1,425 +1,440 @@@+ use super::*;++ /// #882: at 125 % / 150 % display scaling Zoom In reaches 100 % (one comp pixel per screen+ /// pixel), not 100 % in points (125 % / 150 % on screen).+ #[test]+ fn zoom_steps_land_on_whole_screen_magnifications() {+ for ppp in [1.0f32, 1.25, 1.5, 2.0] {+ let at_100 = zoom_step(0.7 / ppp, ppp, true);+ assert!((at_100 * ppp - 1.0).abs() < 1e-6, "ppp {ppp}: {}", at_100 * ppp);+ assert!((zoom_step(at_100, ppp, true) * ppp - 1.5).abs() < 1e-6);+ assert!((zoom_step(at_100, ppp, false) * ppp - 0.66).abs() < 1e-6);+ }+ assert!(zoom_step(1.0, 0.0, true).is_finite());+ }++ #[test]+ fn shortcut_passes_share_frame_start_modifiers() {+ let ctx = egui::Context::default();+ let mut starts = Vec::new();+ let mut output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT)], ..Default::default() }, |ui| {+ let ctx = ui.ctx();+ starts.push(modifiers_at_start(ctx));+ starts.push(modifiers_at_start(ctx));+ });+ output.textures_delta.clear();+ assert_eq!(starts, vec![None, None]);+ starts.clear();+ let mut output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)], ..Default::default() }, |ui| {+ let ctx = ui.ctx();+ starts.push(modifiers_at_start(ctx));+ starts.push(modifiers_at_start(ctx));+ });+ output.textures_delta.clear();+ assert_eq!(starts, vec![Some(egui::Modifiers::SHIFT), Some(egui::Modifiers::SHIFT)]);+ }++ #[test]+ fn every_ui_shortcut_parses() {+ for c in UI_COMMANDS {+ if let Some(sc) = c.shortcut {+ assert!(parse_shortcut(sc).is_some() || sc == "Num*", "{sc}");+ }+ }+ for (_, e) in effectcraft_engine::menus::entries() {+ if let Some(sc) = &e.shortcut {+ assert!(parse_shortcut(sc).is_some() || sc == "Num*", "{} ({sc})", e.label);+ }+ }+ }++ #[test]+ fn full_screen_default_is_platform_specific() {+ let app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let full_screen = app.session.shortcuts().shortcut_of("view.fullScreen", &Value::Null);+ if cfg!(target_os = "macos") {+ assert_eq!(full_screen, Some("Ctrl+Cmd+F"));+ } else {+ assert_eq!(full_screen, None);+ assert_eq!(app.session.shortcuts().shortcut_of("window.maximizeApp", &Value::Null), Some("Cmd+\\"));+ }+ }++ #[test]+ fn ui_and_menu_shortcuts_do_not_collide() {+ let app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let mut seen: std::collections::BTreeMap<(String, String), (String, String)> = Default::default();+ for (m, k, id, params) in bindings(&app.session) {+ let key = (format!("{m:?}"), format!("{k:?}"));+ let target = (id.clone(), params.to_string());+ if let Some(prev) = seen.get(&key) {+ assert_eq!(prev, &target, "{key:?} bound to {prev:?} and {target:?}");+ } else {+ seen.insert(key, target);+ }+ }+ }++ /// #336: Ctrl+\ (Cmd+\ on macOS) maximizes the application window, and again restores+ /// it, as in After Effects.+ #[test]+ fn ctrl_backslash_maximizes_or_restores_the_window() {+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let (m, k) = parse_shortcut("Cmd+\\").unwrap();+ assert!(m.command && k == egui::Key::Backslash, "{m:?} {k:?}");+ assert!(bindings(&app.session).iter().any(|b| (b.0, b.1) == (m, k) && b.2 == "window.maximizeApp"));+ let ctx = egui::Context::default();+ let run = |app: &mut EffectcraftApp, maximized: bool| {+ let input = egui::RawInput {+ viewports: std::iter::once((egui::ViewportId::ROOT, egui::ViewportInfo { maximized: Some(maximized), ..Default::default() })).collect(),+ ..Default::default()+ };+ let mut r = Value::Null;+ let mut out = ctx.run_ui(input, |ui| r = invoke(app, ui.ctx(), "window.maximizeApp", json!({})).unwrap());+ out.textures_delta.clear();+ let cmds = out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default();+ (r, cmds)+ };+ let (r, cmds) = run(&mut app, false);+ assert_eq!(r, json!({"maximized": true}));+ assert!(cmds.contains(&egui::ViewportCommand::Maximized(true)), "{cmds:?}");+ let (r, cmds) = run(&mut app, true);+ assert_eq!(r, json!({"maximized": false}));+ assert!(cmds.contains(&egui::ViewportCommand::Maximized(false)), "{cmds:?}");+ }++ /// The default keys of the keyboard-only commands parse and reach them.+ #[test]+ fn keyboard_only_commands_are_bound() {+ let app = EffectcraftApp::new(effectcraft_engine::Session::default());+ for (id, keys) in [+ ("time.workAreaStart", "Shift+Home"),+ ("time.workAreaEnd", "Shift+End"),+ ("time.previousInOut", "Cmd+Alt+Shift+ArrowLeft"),+ ("time.nextInOut", "Cmd+Alt+Shift+ArrowRight"),+ ("comp.workAreaToSelection", "Cmd+Alt+B"),+ ("comp.activateRecent", "Shift+Escape"),+ ("keys.deselectAll", "Shift+F2"),+ ("keys.deselectAll", "Cmd+Alt+Shift+A"),+ ("layer.extendSelectionNext", "Cmd+Shift+ArrowDown"),+ ("layer.moveInToStart", "Alt+Home"),+ ("layer.moveEarlier", "Alt+PageUp"),+ ("layer.moveLater10", "Alt+Shift+PageDown"),+ ("layer.stretchInToTime", "Cmd+Shift+,"),+ ("layer.stretchOutToTime", "Cmd+Alt+,"),+ ("layer.mask.selectNext", "Alt+`"),+ ("layer.mask.selectPrevious", "Alt+Shift+`"),+ ("layer.castsShadows", "Alt+Shift+C"),+ ("timeline.scrollToTime", "D"),+ ("timeline.scrollToLayer", "X"),+ ("timeline.parentColumn", "Shift+F4"),+ ("view.fitUpTo100", "Alt+/"),+ ("view.nextItem", "Shift+."),+ ("view.previousItem", "Shift+,"),+ ("window.toggleCompTimeline", "\\"),+ ("window.nextPanel", "Alt+Shift+."),+ ("window.previousPanel", "Alt+Shift+,"),+ ("window.closeAll", "Cmd+Shift+W"),+ ("tool.camera", "C"),+ ] {+ assert!(bindings(&app.session).into_iter().any(|x| x.2 == id && Some((x.0, x.1)) == parse_shortcut(keys)), "{id} on {keys}");+ }+ }++ #[test]+ fn timeline_keys_scroll_and_toggle_the_parent_column() {+ let ctx = egui::Context::default();+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let run = |app: &mut EffectcraftApp, id: &str| invoke(app, &ctx, id, json!({})).unwrap();+ // D and X leave a scroll for the Timeline to do when it is drawn.+ run(&mut app, "timeline.scrollToTime");+ assert_eq!(app.ui.timeline.scroll_to, Some(crate::state::ScrollTo::Time));+ run(&mut app, "timeline.scrollToLayer");+ assert_eq!(app.ui.timeline.scroll_to, Some(crate::state::ScrollTo::Layer));+ // Shift+F4 shows and hides the Parent column.+ let parent = crate::panels::timeline::column_visible(&app.ui.timeline, "parent");+ run(&mut app, "timeline.parentColumn");+ assert_eq!(crate::panels::timeline::column_visible(&app.ui.timeline, "parent"), !parent);+ run(&mut app, "timeline.parentColumn");+ assert_eq!(crate::panels::timeline::column_visible(&app.ui.timeline, "parent"), parent);+ }++ #[test]+ fn viewer_keys_fit_and_step_through_open_comps() {+ let ctx = egui::Context::default();+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let run = |app: &mut EffectcraftApp, id: &str| invoke(app, &ctx, id, json!({})).unwrap();+ let new = |app: &mut EffectcraftApp, name: &str| app.session.execute("comp.new", json!({"name": name, "duration": 4})).unwrap()["comp"].as_u64();+ let active = |app: &EffectcraftApp| app.session.state.active_comp.map(|c| c.0);+ // With one composition open there is nothing to step to.+ let a = new(&mut app, "A");+ run(&mut app, "view.nextItem");+ assert_eq!(active(&app), a);+ // Shift+, / Shift+.: through the open compositions, wrapping.+ let b = new(&mut app, "B");+ assert_eq!(active(&app), b);+ run(&mut app, "view.nextItem");+ assert_eq!(active(&app), a);+ run(&mut app, "view.previousItem");+ assert_eq!(active(&app), b);+ // Alt+/ fits the viewer without magnifying past 100 %; Shift+/ fits fully again.+ app.ui.viewer.zoom = Some(3.0);+ run(&mut app, "view.fitUpTo100");+ assert!(app.ui.viewer.zoom.is_none() && app.ui.viewer.fit_up_to_100);+ run(&mut app, "view.fit");+ assert!(!app.ui.viewer.fit_up_to_100);+ }++ #[test]+ fn panel_keys_switch_cycle_and_close() {+ let ctx = egui::Context::default();+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let run = |app: &mut EffectcraftApp, id: &str| invoke(app, &ctx, id, json!({})).unwrap();+ for name in ["A", "B"] {+ app.session.execute("comp.new", json!({"name": name, "duration": 4})).unwrap();+ }+ // \\ switches between the Timeline and the Composition viewer.+ app.ui.focused = PanelKind::Timeline;+ run(&mut app, "window.toggleCompTimeline");+ assert_eq!(app.ui.focused, PanelKind::Composition);+ run(&mut app, "window.toggleCompTimeline");+ assert_eq!(app.ui.focused, PanelKind::Timeline);+ // Alt+Shift+. / Alt+Shift+,: the tabs of the focused panel's group, wrapping.+ let group = app.ui.dock.group_of(PanelKind::Timeline);+ assert!(group.len() > 1, "{group:?}");+ run(&mut app, "window.nextPanel");+ assert_eq!(app.ui.focused, group[(group.iter().position(|p| *p == PanelKind::Timeline).unwrap() + 1) % group.len()]);+ run(&mut app, "window.previousPanel");+ assert_eq!(app.ui.focused, PanelKind::Timeline);+ // Ctrl+Shift+W with the Timeline active closes every composition.+ run(&mut app, "window.closeAll");+ assert!(app.session.state.open_comps.is_empty());+ // With another panel active it closes that panel.+ app.show_panel(PanelKind::Project);+ run(&mut app, "window.closeAll");+ assert!(!app.ui.dock.is_open(PanelKind::Project));+ }++ #[test]+ fn c_cycles_the_camera_tools() {+ let ctx = egui::Context::default();+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ app.ui.tool = Tool::Selection;+ let mut seen = vec![];+ for _ in 0..4 {+ invoke(&mut app, &ctx, "tool.camera", json!({})).unwrap();+ seen.push(app.ui.tool);+ }+ assert_eq!(seen, [Tool::Orbit, Tool::PanCamera, Tool::Dolly, Tool::Orbit]);+ }++ #[test]+ fn dispatch_uses_the_active_custom_preset() {+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let find = |app: &EffectcraftApp, id: &str| bindings(&app.session).into_iter().filter(|b| b.2 == id).map(|b| (b.0, b.1)).collect::<Vec<_>>();+ let (m, k) = parse_shortcut("Cmd+Alt+Shift+Y").unwrap();+ assert!(find(&app, "layer.newNull").contains(&(m, k)));+ // A UI command rebound in a custom preset.+ app.session.execute("shortcuts.set", json!({"command": "tool.hand", "keys": "Ctrl+Alt+H"})).unwrap();+ assert_eq!(app.session.keymaps.active, "Custom");+ let (m2, k2) = parse_shortcut("Ctrl+Alt+H").unwrap();+ assert_eq!(find(&app, "tool.hand"), vec![(m2, k2)]);+ app.session.execute("shortcuts.set", json!({"command": "layer.newNull", "keys": "F6"})).unwrap();+ assert_eq!(find(&app, "layer.newNull"), vec![(egui::Modifiers::NONE, egui::Key::F6)]);+ // The menus show the preset's shortcut.+ let item = menu_items(&app).into_iter().find(|i| i.id == "layer.newNull").unwrap();+ assert_eq!(item.shortcut.as_deref(), Some("F6"));+ // Back to the default preset.+ app.session.execute("shortcuts.preset", json!({"op": "select", "name": effectcraft_engine::shortcuts::DEFAULT_PRESET})).unwrap();+ assert!(find(&app, "layer.newNull").contains(&(m, k)));+ }++ #[test]+ fn renamed_label_shows_in_the_label_menu() {+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ app.set_pref("labels.1.name", json!("Sunflower")).unwrap();+ let labels: Vec<String> = menu_items(&app).into_iter().filter(|i| i.id == "edit.label").map(|i| i.label).collect();+ assert!(labels.contains(&"Sunflower".to_string()), "{labels:?}");+ assert!(!labels.contains(&"Yellow".to_string()));+ }++ /// Saving anything but a project asks the save dialog for that file's extension (#293): the+ /// project dialog, filtered to `.ecproj`, made macOS append `.ecproj` (`Frame.png.ecproj`).+ /// Hosts with only the project dialog (the web) still get it, given the file name.+ #[test]+ fn save_dialogs_offer_the_file_extension() {+ use std::cell::RefCell;+ use std::rc::Rc;+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ app.session.execute("comp.new", json!({"name": "A", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();+ let ctx = egui::Context::default();+ let asked: Rc<RefCell<Vec<String>>> = Rc::default();+ let (a, b) = (asked.clone(), asked.clone());+ app.hooks.pick_save = Some(Box::new(move |name: &str| {+ a.borrow_mut().push(format!("project {name}"));+ None+ }));+ app.hooks.pick_save_file = Some(Box::new(move |name: &str, ext: &str| {+ b.borrow_mut().push(format!("file {name} [{ext}]"));+ None+ }));+ for id in ["comp.saveFrameAs", "render.saveCurrentPreview", "file.exportLottie", "file.saveCopyAsXml", "file.collectFiles", "file.saveAs"] {+ invoke(&mut app, &ctx, id, json!({})).unwrap();+ }+ assert_eq!(+ *asked.borrow(),+ [+ "file Frame.png [png]",+ "file Preview.mp4 [mp4]",+ "file Animation.json [json]",+ "file Untitled Project.ecprojx [ecprojx]",+ "file Collected Files []",+ "project Untitled Project.ecproj",+ ]+ );+ // Without the other dialog, the project one names any file.+ app.hooks.pick_save_file = None;+ asked.borrow_mut().clear();+ invoke(&mut app, &ctx, "comp.saveFrameAs", json!({})).unwrap();+ assert_eq!(*asked.borrow(), ["project Frame.png"]);+ }++ /// File ▸ Scripts ▸ Recent Script Files and its key run a script again without a file dialog.+ #[test]+ fn recent_script_files_run_without_a_dialog() {+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let ctx = egui::Context::default();+ let dir = std::env::temp_dir().join(format!("ec-recent-script-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let script = dir.join("New Comp.jsonl");+ std::fs::write(&script, r#"{"command": "comp.new", "params": {"name": "From Script", "width": 64, "height": 36, "frameRate": 30, "duration": 1}}"#)+ .unwrap();+ app.session.execute("file.runScript", json!({"path": script.to_string_lossy()})).unwrap();+ let (m, k, id, params) =+ bindings(&app.session).into_iter().find(|b| b.2 == "file.runScript" && b.3 == json!({"recent": 0})).expect("the most recent script has a key");+ assert_eq!((m, k), parse_shortcut("Cmd+Alt+Shift+D").unwrap());+ assert_eq!(invoke(&mut app, &ctx, &id, params).unwrap()["steps"], 1);+ assert_eq!(app.session.project.items.values().filter(|i| i.name.starts_with("From Script")).count(), 2);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// #511: with a host's non-blocking dialogs, a command's file dialog opens without running+ /// a nested event loop inside the frame (a drag over the window then aborted the app on+ /// macOS); the command runs on a later frame with the answer, and a cancelled one not at all.+ #[test]+ fn file_dialogs_can_answer_on_a_later_frame() {+ use std::sync::{Arc, Mutex};+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ app.session.execute("comp.new", json!({"name": "A", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();+ let ctx = egui::Context::default();+ app.hooks.pick_save = Some(Box::new(|_: &str| panic!("the blocking dialog is not used")));+ let pending: Arc<Mutex<Vec<(crate::FileDialog, crate::DialogDone)>>> = Arc::default();+ let queue = pending.clone();+ app.hooks.file_dialog_async = Some(Box::new(move |dialog, done| queue.lock().unwrap().push((dialog, done))));+ assert_eq!(invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap(), json!({"dialog": "file.saveAs"}));+ let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");+ assert_eq!(dialog, crate::FileDialog::Save { default: "Untitled Project.ecproj".into(), ext: "ecproj".into(), project: true });+ assert!(app.session.path.is_none(), "nothing saved until the dialog answers");+ let dir = std::env::temp_dir().join(format!("ec-dialog-answer-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("Answered.ecproj");+ // Answered from another thread, as the host's dialog does.+ std::thread::spawn(move || done(vec![path.to_string_lossy().to_string()])).join().unwrap();+ app.run_dialog_answers();+ assert_eq!(app.session.path.as_deref(), Some(dir.join("Answered.ecproj").to_string_lossy().as_ref()));+ assert!(dir.join("Answered.ecproj").is_file());+ // Cancelled: nothing runs.+ invoke(&mut app, &ctx, "comp.saveFrameAs", json!({})).unwrap();+ let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");+ assert_eq!(dialog, crate::FileDialog::Save { default: "Frame.png".into(), ext: "png".into(), project: false });+ done(Vec::new());+ app.run_dialog_answers();+ assert!(!dir.join("Frame.png").exists());+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// While a command's OS file dialog is up, floating panels' OS windows are blocked, as for+ /// a modal dialog; a dialog that ends, answered or not, unblocks them, and Save As opens a+ /// dialog again. A macOS sheet can end without answering (its window went away): once one of+ /// the app's windows has the keyboard again, or keeps it as if no dialog showed, floating+ /// windows are not left blocked.+ #[test]+ fn file_dialogs_block_floating_windows_only_while_up() {+ use std::sync::{Arc, Mutex};+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let ctx = egui::Context::default();+ let pending: Arc<Mutex<Vec<crate::DialogDone>>> = Arc::default();+ let queue = pending.clone();+ app.hooks.file_dialog_async = Some(Box::new(move |_dialog, done| queue.lock().unwrap().push(done)));+ let blocked = |app: &mut EffectcraftApp, focused: bool, time: f64| {+ let input = egui::RawInput { focused, time: Some(time), ..Default::default() };+ let mut out = false;+ ctx.run_ui(input, |ui| out = app.floats_blocked(ui.ctx())).textures_delta.clear();+ out+ };+ assert!(!blocked(&mut app, true, 0.0));+ // Cancelled.+ invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();+ assert!(blocked(&mut app, true, 0.1), "blocked while the dialog takes the keyboard");+ assert!(blocked(&mut app, false, 0.2));+ let done = pending.lock().unwrap().pop().expect("a dialog was shown");+ done(Vec::new());+ app.run_dialog_answers();+ assert!(!blocked(&mut app, false, 0.3));+ // Save As asks again; the sheet ends without answering.+ invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();+ assert_eq!(pending.lock().unwrap().len(), 1, "Save As opens a dialog again");+ assert!(blocked(&mut app, true, 1.0));+ assert!(blocked(&mut app, false, 1.1));+ assert!(blocked(&mut app, false, 9.0), "a dialog may stay up for long");+ assert!(!blocked(&mut app, true, 9.1), "an app window has the keyboard again");+ // A dialog that never takes the keyboard.+ invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();+ assert!(blocked(&mut app, true, 10.0));+ assert!(blocked(&mut app, true, 11.0));+ assert!(!blocked(&mut app, true, 12.5));+ // Answers of dialogs taken for gone arrive late: nothing stays blocked.+ for done in pending.lock().unwrap().drain(..) {+ done(Vec::new());+ }+ app.run_dialog_answers();+ assert!(!blocked(&mut app, false, 13.0));+ invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();+ assert!(blocked(&mut app, false, 13.1), "a later dialog blocks again");+ }++ #[test]+ fn tga_is_available_in_import_replace_and_proxy_dialogs() {+ use std::sync::{Arc, Mutex};+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let ctx = egui::Context::default();+ let pending = Arc::new(Mutex::new(Vec::new()));+ let queue = pending.clone();+ app.hooks.file_dialog_async = Some(Box::new(move |dialog, _done| queue.lock().unwrap().push(dialog)));+ for command in ["file.import", "file.importMultiple", "file.replaceFootage", "file.setProxy"] {+ assert_eq!(invoke(&mut app, &ctx, command, json!({})).unwrap(), json!({"dialog": command}));+ let crate::FileDialog::Open { exts, .. } = pending.lock().unwrap().pop().unwrap() else { panic!("not an open dialog") };+ assert!(exts.iter().any(|ext| ext == "tga"), "{command}: {exts:?}");+ }+ }+++/// Cmd+W with the Render Queue focused closes the queue; the composition next to it stays++/// open (it used to be closed, and the queue stayed).++#[test]++fn cmd_w_in_the_render_queue_closes_the_queue_not_the_comp() {++ let ctx = egui::Context::default();++ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());++ let a = app.session.execute("comp.new", json!({"name": "A", "duration": 4})).unwrap()["comp"].as_u64();++ app.show_panel(PanelKind::RenderQueue);++ assert_eq!(app.ui.focused, PanelKind::RenderQueue);++ invoke(&mut app, &ctx, "file.close", json!({})).unwrap();++ assert!(!app.ui.dock.is_visible(PanelKind::RenderQueue));++ assert_eq!(app.session.state.active_comp.map(|c| c.0), a);++ assert_eq!(app.session.state.open_comps.len(), 1);++}+++ #[test]+ fn menu_items_cover_the_tree() {+ assert_eq!(menus().last(), Some(&"Help"));+ assert!(effectcraft_engine::menus::entries().len() > 500);+ }diff --cc crates/ui-egui/src/panels/viewer.rsindex cc1f2196e,bcae99bc5..9efa9d940--- a/crates/ui-egui/src/panels/viewer.rs+++ b/crates/ui-egui/src/panels/viewer.rs@@@ -2032,773 -1788,32 +1788,32 @@@ fn phase_tail(app: &mut EffectcraftAppsuper::expr_bar::draw(app, ui, err_bar, cid);}}-- /// Parent-space position change per comp pixel of drag (x and y) for a layer: 2D layers map- /// through the parent transform; 3D layers move in the view plane at their depth.- fn drag_axes(ctx: &EvalCtx, l: &Layer) -> ([f64; 3], [f64; 3]) {- if !l.is_3d() {- let inv = parent_inverse(ctx, l);- let a = inv.apply_vec(gv2(1.0, 0.0));- let b = inv.apply_vec(gv2(0.0, 1.0));- return ([a.x, a.y, 0.0], [b.x, b.y, 0.0]);- }- let cam = cam_state(ctx);- let anchor = l.transform().map(|tr| ctx.v3(l, tr, "anchor", [0.0; 3])).unwrap_or([0.0; 3]);- let wp = ctx.world_matrix(l).apply(anchor.into());- let k = if cam.ortho { 1.0 / cam.zoom.max(1e-9) } else { cam.depth(wp).max(1.0) / cam.zoom.max(1e-9) };- let pinv = match l.parent.and_then(|p| ctx.comp.layer(p)) {- Some(p) => ctx.world_matrix(p).inverse().unwrap_or_default(),- None => effectcraft_engine::geom::Mat4::IDENTITY,- };- let a = pinv.apply_vec(cam.right() * k);- let b = pinv.apply_vec(cam.down() * k);- ([a.x, a.y, a.z], [b.x, b.y, b.z])- }-- /// Wireframes of cameras (frustum, point of interest) and lights (position, direction) as seen- /// through the current 3D view.- /// Camera and light wireframes seen through `cam` (`through_active`: `cam` is the active camera,- /// which is then not drawn). `pane` names the automation ids: `None` for the main view- /// (`viewer.camera.<id>`), `Some(view)` for a view of a 2- or 4-view layout- /// (`viewer.view.<view>.camera.<id>`).- #[allow(clippy::too_many_arguments)]- fn draw_rigs(- app: &mut EffectcraftApp,- painter: &egui::Painter,- map: &ViewerMap,- ectx: &EvalCtx,- selected: &[LayerId],- cam: CameraState,- through_active: bool,- pane: Option<&str>,- ) {- use effectcraft_engine::geom::Vec3;- use effectcraft_engine::project::{LayerSource, LightKind};- let (w, h) = (ectx.comp.width as f64, ectx.comp.height as f64);- let active = ectx.comp.active_camera(ectx.time).map(|c| c.id);- let prefix = pane.map(|v| format!("viewer.view.{v}.")).unwrap_or_else(|| "viewer.".to_string());- let proj = |p: Vec3| cam.project(w, h, p).map(|v| map.to_screen([v.x, v.y]));- let seg = |a: Vec3, b: Vec3, stroke: Stroke| {- if let (Some(x), Some(y)) = (proj(a), proj(b)) {- painter.line_segment([x, y], stroke);- }- };- for l in ectx.comp.layers.iter().filter(|l| (l.is_camera() || l.is_light()) && l.is_active_at(ectx.time)) {- let sel = selected.contains(&l.id);- let col = app.tokens.label(l.label).gamma_multiply(if sel { 1.0 } else { 0.6 });- let stroke = Stroke::new(if sel { 1.5 } else { 1.0 }, col);- let (eye, fwd, down) = three_d::camera::layer_frame(ectx, l);- let poi = |l: &Layer| -> Option<Vec3> {- let pr = l.transform()?.get("poi").filter(|_| three_d::camera::is_two_node(l))?;- Some(three_d::camera::parent_world(ectx, l).apply(ectx.value(l, pr).as_vec3().into()))- };- if l.is_camera() {- if through_active && Some(l.id) == active {- continue;- }- let zoom = l.props.prop("cameraOptions/zoom").map(|p| ectx.value(l, p).as_f64()).unwrap_or(1000.0);- let right = down.cross(fwd);- // Frustum to a plane at a quarter of the zoom distance.- let k = 0.25;- let c = eye + fwd * (zoom * k);- let corners = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].map(|(sx, sy)| c + right * (sx * w * 0.5 * k) + down * (sy * h * 0.5 * k));- for i in 0..4 {- seg(eye, corners[i], stroke);- seg(corners[i], corners[(i + 1) % 4], stroke);- }- if let Some(poi) = poi(l) {- seg(eye, poi, Stroke::new(1.0, col.gamma_multiply(0.6)));- if let Some(s) = proj(poi) {- painter.circle_stroke(s, 4.0, stroke);- }- }- if let Some(s) = proj(eye) {- app.auto.add(&format!("{prefix}camera.{}", l.id.0), Rect::from_center_size(s, vec2(14.0, 14.0)), &l.name);- }- } else {- let LayerSource::Light { kind } = l.source else { continue };- if kind == LightKind::Ambient {- continue;- }- let Some(s) = proj(eye) else { continue };- painter.circle_stroke(s, 6.0, stroke);- for i in 0..8 {- let a = i as f32 * std::f32::consts::FRAC_PI_4;- let d = vec2(a.cos(), a.sin());- painter.line_segment([s + d * 8.0, s + d * 12.0], stroke);- }- if matches!(kind, LightKind::Spot | LightKind::Parallel) {- let target = poi(l).unwrap_or(eye + fwd * 300.0);- seg(eye, target, Stroke::new(1.0, col.gamma_multiply(0.7)));- if let Some(q) = proj(target) {- painter.circle_stroke(q, 3.0, stroke);- }- }- app.auto.add(&format!("{prefix}light.{}", l.id.0), Rect::from_center_size(s, vec2(16.0, 16.0)), &l.name);- }- }- }-- /// Pen tool press at `pos`: continue the path in progress (pressing its first vertex closes it),- /// resume an open path whose last vertex is pressed, add a vertex on a visible path's segment, or- /// start a new path: a mask on the selected footage/solid layer (or shape layer, with Tool Creates- /// Mask), a shape path (Shape n group with the Tools bar's Fill and Stroke) on the selected shape- /// layer, or a new shape layer when nothing is selected. The placed point snaps.- /// Add a Position keyframe at a motion path's frame, keeping the path where it is.- fn add_motion_key(app: &mut EffectcraftApp, f: ov::PathFrame) {- if let Err(e) = app.session.execute("prop.addKey", json!({"layer": f.layer.0, "prop": f.prop, "time": f.time.seconds()})) {- app.ui.status = e.to_string();- }- }-- /// Select only the motion path's keyframe `k` (what the vertex tools act on).- fn select_motion_key(app: &mut EffectcraftApp, k: &ov::KeyHit) -> bool {- app.session.execute("keys.select", json!({"keys": [{"layer": k.layer.0, "prop": k.prop, "time": k.time.seconds()}]})).is_ok()- }-- /// The pointer for a Pen slot tool: the tool's own pen, the Pen showing Add Vertex's over a path- /// it would add a point to (After Effects).- fn pen_cursor_icon(tool: Tool, over_path: bool) -> crate::icons::Icon {- use crate::icons::Icon;- match tool {- Tool::Pen if over_path => Icon::PenAdd,- Tool::PenAdd => Icon::PenAdd,- Tool::PenDelete => Icon::PenDelete,- Tool::PenConvert => Icon::PenConvert,- Tool::MaskFeather => Icon::MaskFeather,- _ => Icon::Pen,- }- }-- /// Paint pen pointer `icon` with its tip at `at`, outlined for any background.- fn pen_cursor(ctx: &egui::Context, at: Pos2, icon: crate::icons::Icon) {- use crate::icons::Icon;- // Where each glyph's tip sits in its 16 × 16 box.- let tip = match icon {- Icon::PenAdd | Icon::PenDelete | Icon::MaskFeather => vec2(6.0, 2.5),- Icon::PenConvert => vec2(8.0, 3.5),- _ => vec2(8.0, 1.8),- };- let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("viewer-pen-cursor")));- let rect = Rect::from_min_size(at - tip, vec2(16.0, 16.0));- for d in [vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, -1.0), vec2(0.0, 1.0)] {- crate::icons::paint(&painter, rect.translate(d), icon, Color32::BLACK);- }- crate::icons::paint(&painter, rect, icon, Color32::WHITE);- }-- #[allow(clippy::too_many_arguments)]- fn pen_press(- app: &mut EffectcraftApp,- ui: &mut egui::Ui,- ectx: &EvalCtx,- map: &ViewerMap,- paths: &[ov::PathInfo],- motion_frame: Option<ov::PathFrame>,- pos: Pos2,- mods: egui::Modifiers,- ) {- use effectcraft_engine::project::LayerSource;- let gid = egui::Id::new("viewer-gesture");- let current: Option<(LayerId, u64)> = ui.data(|d| d.get_temp(pen_id()));- let c0 = map.to_comp(pos);- let corr = vt::snap(app, ui.ctx(), ectx, map, &[], &[c0], mods);- let c = [c0[0] + corr[0], c0[1] + corr[1]];- if let Some((lid, uid)) = current- && let Some(p) = ov::path_of(ectx, lid, uid)- && let Some(inv) = p.m.inverse()- {- let n = p.sp.vertices.len();- let first = p.sp.vertices.first().map(|v| {- let q = p.m.apply(gv2(v[0], v[1]));- map.to_screen([q.x, q.y])- });- if n >= 2 && first.is_some_and(|f| f.distance(pos) < 8.0) {- let _ = app.session.execute("mask.setClosed", json!({"layer": lid.0, "mask": uid, "closed": true}));- ui.data_mut(|d| {- d.remove::<(LayerId, u64)>(pen_id());- d.remove::<Gesture>(gid);- });- return;- }- let lp = inv.apply(gv2(c[0], c[1]));- let lp = [lp.x, lp.y];- if let Ok(v) = app.session.execute("mask.addVertex", json!({"layer": lid.0, "mask": uid, "point": lp})) {- let index = v.as_u64().unwrap_or(0) as usize;- ui.data_mut(|d| d.insert_temp(gid, Gesture::Pen { layer: lid, mask: uid, index, vertex: lp, inv, press: pos }));- }- return;- }- // Clicking the last vertex of an open path (e.g. after Esc ended it) resumes drawing it.- if let Some(cur) = ov::open_end_at(paths, map, pos, 8.0) {- ui.data_mut(|d| d.insert_temp(pen_id(), cur));- return;- }- // On a visible path's segment the Pen adds a vertex there; on a motion path, a keyframe.- if let Some(f) = motion_frame {- add_motion_key(app, f);- return;- }- if let Some((l, m, seg, t)) = ov::segment_at(paths, map, pos, 5.0) {- let _ = app.session.execute("mask.insertVertex", json!({"layer": l.0, "mask": m, "segment": seg, "t": t}));- return;- }- let target = app- .session- .state- .selected_layers- .iter()- .copied()- .find(|id| ectx.comp.layer(*id).is_some_and(|l| !l.switches.locked && (l.masks().is_some() || matches!(l.source, LayerSource::Shape))));- let layer = target.and_then(|id| ectx.comp.layer(id));- let (lid, uid, inv) = match layer {- Some(l) if !matches!(l.source, LayerSource::Shape) || app.session.state.shape_tool.creates_mask => {- let Some(inv) = l2c(ectx, l).0.inverse() else { return };- let lp = inv.apply(gv2(c[0], c[1]));- let Ok(v) = app.session.execute("mask.new", json!({"layer": l.id.0, "vertices": [[lp.x, lp.y]]})) else { return };- let Some(mask) = v["mask"].as_u64() else { return };- (l.id, mask, inv)- }- Some(l) => {- let Some(inv) = l2c(ectx, l).0.inverse() else { return };- let lp = inv.apply(gv2(c[0], c[1]));- let r = app.session.execute("shape.newPath", json!({"layer": l.id.0, "vertices": [[lp.x, lp.y]], "space": "layer"}));- let Some(path) = r.ok().and_then(|v| v["path"].as_u64()) else { return };- (l.id, path, inv)- }- None => {- // A new shape layer at the comp centre (unrotated: comp → layer is a translation).- let r = app.session.execute("shape.newPath", json!({"vertices": [c], "space": "comp"}));- let Some(v) = r.ok() else { return };- let (Some(l), Some(path)) = (v["layer"].as_u64(), v["path"].as_u64()) else { return };- let inv = Mat3::translate(gv2(-(ectx.comp.width as f64) / 2.0, -(ectx.comp.height as f64) / 2.0));- (LayerId(l), path, inv)- }- };- let lp = inv.apply(gv2(c[0], c[1]));- ui.data_mut(|d| {- d.insert_temp(pen_id(), (lid, uid));- d.insert_temp(gid, Gesture::Pen { layer: lid, mask: uid, index: 0, vertex: [lp.x, lp.y], inv, press: pos });- });- }-- /// Visible, unlocked layers eligible for viewer hit tests, in front-to-back order.- /// Solo scope matches the renderer: only active AV layers activate it, even when hidden or locked.- pub(crate) fn selectable_layers(comp: &Comp, time: Tick) -> impl Iterator<Item = &Layer> {- let any_solo = comp.layers.iter().any(|l| l.switches.solo && l.source.is_av() && l.is_active_at(time));- comp.layers- .iter()- .filter(move |l| l.is_active_at(time) && l.switches.video && !l.switches.locked && !l.is_camera() && !l.is_light() && (!any_solo || l.switches.solo))- }-- /// Selectable layers under a comp point, front to back.- pub(crate) fn layers_at<'a, 'b>(ectx: &'b EvalCtx<'a>, cpt: [f64; 2]) -> impl Iterator<Item = &'a Layer> + 'b {- selectable_layers(ectx.comp, ectx.time).filter(move |l| layer_quad(ectx, l).is_some_and(|(_, q, _)| point_in_quad(cpt, &q)))- }-- /// Topmost selectable layer under a comp point.- pub(crate) fn layer_at<'a>(ectx: &EvalCtx<'a>, cpt: [f64; 2]) -> Option<&'a Layer> {- layers_at(ectx, cpt).next()- }-- /// The layer a press at a comp point acts on, selected (Shift toggles the topmost layer). As in- /// After Effects, a selected layer under the point comes before the layers in front of it, so it- /// can be dragged where they cover it; otherwise the topmost layer (#230).- pub(crate) fn pick(app: &mut EffectcraftApp, ectx: &EvalCtx, cpt: [f64; 2], toggle: bool) -> Option<LayerId> {- if toggle {- let hit = layer_at(ectx, cpt)?.id;- let _ = app.session.execute("layer.select", json!({"layers": [hit.0], "toggle": true}));- return Some(hit);- }- let selected = &app.session.state.selected_layers;- let hits: Vec<LayerId> = layers_at(ectx, cpt).map(|l| l.id).collect();- let hit = *hits.iter().find(|id| selected.contains(id)).or(hits.first())?;- if !selected.contains(&hit) {- let _ = app.session.execute("layer.select", json!({"layers": [hit.0]}));- }- Some(hit)- }-- /// Where a shape drag is going to land: a mask on the selected layer, a group inside it, or a new- /// shape layer.- #[derive(Clone, Copy, PartialEq, Eq)]- enum ShapeTarget {- Mask,- IntoLayer,- NewLayer,- }-- impl ShapeTarget {- /// What the drag will make and where, named the way the ghost captions it.- fn label(self, layer_name: &str) -> String {- match self {- ShapeTarget::Mask => format!("Mask on “{layer_name}”"),- ShapeTarget::IntoLayer => format!("Into “{layer_name}”"),- ShapeTarget::NewLayer => "New shape layer".to_string(),- }- }- }-- /// A shape drag as it stands, after the Tools' normalisations: the path it will make and where it- /// will land.- struct ShapeDrag {- /// The `shape.newShape` / `layer.addMask` kind for the tool.- kind: &'static str,- /// Comp-space centre and size, what the drag will make.- centre: [f64; 2],- size: [f64; 2],- target: ShapeTarget,- /// The selected layer's name and the index its next mask would take, for the ghost's caption- /// and colour.- layer_name: String,- mask_index: usize,- }-- /// The kind `tool` draws, as `shape.newShape` / `layer.addMask` name it.- pub(crate) fn shape_kind(tool: Tool) -> &'static str {- match tool {- Tool::Rectangle => "rect",- Tool::RoundedRect => "rounded",- Tool::Ellipse => "ellipse",- Tool::Polygon => "polygon",- _ => "star",- }- }-- /// What a shape tool drag from `start` to `end` makes, or `None` while it is too small to make- /// anything. Alt (Option) draws from the press point and Shift squares the box; the live ghost and- /// [`create_shape`] both go through this, so the drag always shows what it will commit.- fn shape_drag(app: &EffectcraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option<ShapeDrag> {- let comp = app.session.active_comp()?;- let selected = app.session.state.selected_layers.first().copied();- let sel = selected.and_then(|id| comp.layer(id));- // A footage, solid or other non-shape layer selected, or a shape layer with Tool Creates- // Mask: a mask on that layer. Otherwise the engine's own target: the first selected unlocked- // shape layer, else a new one.- let target = match sel {- Some(l) if l.source.is_av() && (app.session.state.shape_tool.creates_mask || !matches!(l.source, LayerSource::Shape)) => (ShapeTarget::Mask, Some(l)),- _ => match effectcraft_engine::commands::shape_tool::selected_shape_target(&app.session, comp).and_then(|id| comp.layer(id)) {- Some(l) => (ShapeTarget::IntoLayer, Some(l)),- None => (ShapeTarget::NewLayer, None),- },- };- let (target, layer) = target;- let mask_index = if target == ShapeTarget::Mask { layer.and_then(|l| l.masks()).map_or(0, |m| m.groups().count()) } else { 0 };- let (mut w, mut h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs());- // Ctrl/Cmd draws from the press point as the centre, as in After Effects.- if mods.command {- w *= 2.0;- h *= 2.0;- }- if w < 2.0 && h < 2.0 {- return None;- }- if mods.shift {- let m = w.max(h);- w = m;- h = m;- }- Some(ShapeDrag {- kind: shape_kind(tool),- centre: if mods.command { start } else { [start[0].min(end[0]) + w / 2.0, start[1].min(end[1]) + h / 2.0] },- size: [w, h],- target,- layer_name: layer.map_or_else(String::new, |l| l.name.clone()),- mask_index,- })- }-- /// The Tools bar's paint colour as bytes, dimmed by `alpha` so the comp shows through the ghost.- fn paint_rgb(c: [f32; 3], opacity: f64, alpha: f32) -> Color32 {- let f = |k: f32| (k.clamp(0.0, 1.0) * 255.0).round() as u8;- Color32::from_rgb(f(c[0]), f(c[1]), f(c[2])).gamma_multiply((opacity.clamp(0.0, 100.0) / 100.0) as f32 * alpha)- }-- /// Draw a shape drag as it will land: the tool's own path, filled with the Tools bar's Fill and- /// outlined in its Stroke (or the mask colour, for a mask), captioned with where it goes.- fn draw_shape_ghost(painter: &egui::Painter, map: &ViewerMap, app: &EffectcraftApp, d: &ShapeDrag, t: &Tokens) {- // The engine's own geometry for the kind, so the ghost is the shape and not a stand-in for it.- let Some(sp) = effectcraft_engine::commands::shape_tool::mask_path(d.kind, d.centre, d.size) else { return };- let mut pts = ov::flatten(&sp, &Mat3::IDENTITY, map);- if pts.first() == pts.last() {- pts.pop();- }- if pts.len() < 3 {- return;- }- let tool = &app.session.state.shape_tool;- let (fill, line) = match d.target {- ShapeTarget::Mask => {- let [r, g, b] = effectcraft_engine::prefs::mask_color(app.session.prefs.appearance.cycle_mask_colors, d.mask_index);- (Color32::from_rgb(r, g, b).gamma_multiply(0.25), Color32::from_rgb(r, g, b))- }- _ => {- let stroke_on = tool.stroke.kind != PaintKind::None && tool.stroke_width > 0.0;- (- if tool.fill.kind == PaintKind::None { Color32::TRANSPARENT } else { paint_rgb(tool.fill.color, tool.fill.opacity, 0.45) },- if stroke_on { paint_rgb(tool.stroke.color, tool.stroke.opacity, 1.0) } else { t.accent },- )- }- };- let Some(bounds) = bounds_of(&pts) else { return };- // A screen-width outline reads at every zoom, where a comp-pixel hairline does not.- painter.add(egui::Shape::Path(egui::epaint::PathShape { points: pts, closed: true, fill, stroke: Stroke::new(1.5, line).into() }));- // Caption it with where the shape lands: a mask, a group in the selected shape layer or a- // new layer.- let font = Tokens::ui(11.0);- let galley = painter.layout_no_wrap(d.target.label(&d.layer_name), font, line);- let caption = Rect::from_min_size(pos2(bounds.left(), bounds.top() - 5.0 - galley.size().y), galley.size());- painter.rect_filled(caption.expand(3.0), 2.0, Color32::from_black_alpha(150));- painter.galley(caption.min, galley, line);- }-- /// The bounds of points on screen, or `None` for an empty set.- fn bounds_of(pts: &[Pos2]) -> Option<Rect> {- let first = *pts.first()?;- let mut r = Rect::from_min_max(first, first);- for p in pts.iter().skip(1) {- r.extend_with(*p);- }- Some(r)- }-- fn create_shape(app: &mut EffectcraftApp, tool: Tool, a: [f64; 2], b: [f64; 2], mods: egui::Modifiers) {- let Some(d) = shape_drag(app, tool, a, b, mods) else { return };- let (kind, (w, h), (cx, cy)) = (d.kind, (d.size[0], d.size[1]), (d.centre[0], d.centre[1]));- // A mask on the selected layer, as the ghost showed.- if d.target == ShapeTarget::Mask {- // In layer space: invert the layer transform.- let sel_layer = app.session.state.selected_layers.first().copied().and_then(|id| app.session.active_comp().and_then(|c| c.layer(id)).cloned());- if let Some(l) = sel_layer- && let Some(comp) = app.session.active_comp_arc()- {- let ectx = EvalCtx {- project: &app.session.project,- comp_id: app.session.active_comp_id().unwrap_or_default(),- comp: &comp,- time: app.session.time(),- expr: None,- footage: None,- };- let inv = l2c(&ectx, &l).0.inverse().unwrap_or(Mat3::IDENTITY);- let p0 = inv.apply(gv2(cx - w / 2.0, cy - h / 2.0));- let p1 = inv.apply(gv2(cx + w / 2.0, cy + h / 2.0));- let rect = [p0.x.min(p1.x), p0.y.min(p1.y), (p1.x - p0.x).abs(), (p1.y - p0.y).abs()];- if let Err(e) = app.session.execute("layer.addMask", json!({"layer": l.id.0, "shape": kind, "rect": rect})) {- app.ui.status = e.to_string();- }- }- return;- }- // Into the selected shape layer's Contents as a new group (as in After Effects), else a new- // shape layer; painted with the Tools bar's Fill and Stroke.- if let Err(e) = app.session.execute("shape.newShape", json!({"kind": kind, "size": [w, h], "position": [cx, cy]})) {- app.ui.status = e.to_string();- }- }-- fn empty_state(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {- let t = app.tokens;- let p = ui.painter().clone();- p.rect_filled(rect, 0.0, t.pasteboard);- let c = rect.center();- p.text(c - vec2(0.0, 40.0), Align2::CENTER_CENTER, crate::i18n::tr("Composition"), Tokens::semibold(16.0), t.text);- let b1 = Rect::from_center_size(c + vec2(0.0, 0.0), vec2(220.0, 30.0));- if widgets::text_button(ui, b1, "New Composition", true, &t, egui::Id::new("empty-newcomp")).clicked() {- crate::panels::dialogs::open_new_comp(app);- }- app.auto.add("viewer.empty.newComp", b1, "New Composition");- let b2 = Rect::from_center_size(c + vec2(0.0, 40.0), vec2(220.0, 30.0));- if widgets::text_button(ui, b2, "New Composition From Footage", false, &t, egui::Id::new("empty-fromfootage")).clicked() {- let _ = crate::menus::invoke(app, &ui.ctx().clone(), "file.import", json!({}));- }- app.auto.add("viewer.empty.import", b2, "New Composition From Footage");- // A Project item dropped on the empty viewer creates the first composition,- // just like dropping it onto an empty Timeline (#684). Multiple selected- // items use the existing New Comp from Selection dialog.- let ctx = ui.ctx().clone();- if let Some(crate::panels::DragPayload::Item(dragged)) = egui::DragAndDrop::payload::<crate::panels::DragPayload>(&ctx).as_deref()- && ui.rect_contains_pointer(rect)- {- let items: Vec<effectcraft_engine::project::ItemId> = crate::panels::project_drop_items(app, *dragged)- .into_iter()- .map(effectcraft_engine::project::ItemId)- .filter(|id| {- app.session.project.item(*id).is_some_and(|item| match &item.kind {- effectcraft_engine::project::ItemKind::Footage(f) => f.kind != effectcraft_engine::project::FootageKind::Data,- effectcraft_engine::project::ItemKind::Solid(_) | effectcraft_engine::project::ItemKind::Comp(_) => true,- _ => false,- })- })- .collect();- if !items.is_empty() {- p.rect_stroke(rect.shrink(2.0), 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);- app.auto.add("viewer.newCompDrop", rect, "Drop footage to create a composition");- if ctx.input(|i| i.pointer.any_released()) {- app.session.state.project_selection = items;- if let Err(e) = crate::menus::invoke(app, &ctx, "file.newCompFromSelection", json!({})) {- app.ui.status = e;- }- egui::DragAndDrop::clear_payload(&ctx);- }- }- }- }-- /// `#rrggbb` → sRGB bytes.- /// A grid or guide line in the Grids & Guides style: `lines`, `dashed` or `dots`.- pub(crate) fn styled_line(painter: &egui::Painter, pts: [Pos2; 2], stroke: Stroke, style: &str) {- match style {- "dashed" => {- painter.add(egui::Shape::dashed_line(&pts, stroke, 6.0, 4.0));- }- "dots" => {- painter.add(egui::Shape::dotted_line(&pts, stroke.color, 4.0, stroke.width.max(1.0) * 0.75));- }- _ => {- painter.line_segment(pts, stroke);- }- }- }-- /// `p` (points) moved to the nearest physical pixel corner at `ppp` pixels per point.- pub(crate) fn snap_to_pixels(p: Pos2, ppp: f32) -> Pos2 {- if !(ppp.is_finite() && ppp > 0.0 && p.x.is_finite() && p.y.is_finite()) {- return p;- }- pos2((p.x * ppp).round() / ppp, (p.y * ppp).round() / ppp)- }-- /// Texture filtering for Viewer Zoom Quality: More Accurate = bilinear, Faster = nearest. As in- /// After Effects, a magnified frame (above 100 %, or a lower Resolution) always shows its pixels- /// as blocks, never smoothed, in either mode (#882).- pub(crate) fn zoom_texture_options(smooth: bool) -> egui::TextureOptions {- if smooth { egui::TextureOptions { magnification: egui::TextureFilter::Nearest, ..egui::TextureOptions::LINEAR } } else { egui::TextureOptions::NEAREST }- }-- /// The sampler GPU frames (mipmapped display textures) are drawn with: More Accurate filters- /// bilinearly within and between mip levels, so a frame shown below 100 % is averaged instead of- /// skipping pixels (#417); Faster takes the nearest pixel of the full-size frame. Magnified, both- /// show the nearest pixel (#882).- pub(crate) fn zoom_sampler(smooth: bool) -> eframe::wgpu::SamplerDescriptor<'static> {- use eframe::wgpu::{FilterMode, MipmapFilterMode, SamplerDescriptor};- let label = Some("viewer frame");- if smooth {- SamplerDescriptor {- label,- mag_filter: FilterMode::Nearest,- min_filter: FilterMode::Linear,- mipmap_filter: MipmapFilterMode::Linear,- ..Default::default()- }- } else {- SamplerDescriptor { label, lod_max_clamp: 0.0, ..Default::default() }- }- }-- /// The whole factor a CPU frame is averaged down by for its texture when `pixels` of it are drawn- /// over `screen` screen pixels: about one texel per screen pixel, so bilinear filtering never- /// skips frame pixels — the CPU frames' counterpart of the GPU frames' mip levels (#417). Faster- /// keeps every pixel.- pub(crate) fn minify_factor(smooth: bool, pixels: f64, screen: f64) -> usize {- let k = (pixels / screen + 1e-3).floor();- if smooth && k >= 1.0 { k.min(256.0) as usize } else { 1 }- }-pub(crate) use crate::widgets::hex_rgb;- /// The Extended Viewer's render region for this frame (see [`ViewerState::extended`]):- /// Settings ▸ 3D ▸ Extended Viewer on, the comp has 3D layers and the view is a custom 3D view- /// (or Draft 3D is on), and part of the visible viewer lies outside the comp frame.- ///- /// [`ViewerState::extended`]: crate::state::ViewerState::extended- pub(crate) fn extended_region(- app: &EffectcraftApp,- comp: &effectcraft_engine::project::Comp,- cid: effectcraft_engine::project::ItemId,- map: ViewerMap,- ) -> Option<[f64; 4]> {- if !app.session.prefs.three_d.extended_viewer || !comp.has_3d() || app.session.state.region_of_interest.is_some() {- return None;- }- let view = app.session.state.views3d.get(&cid).map(|v| v.current).unwrap_or_default();- if view == View3D::ActiveCamera && !comp.draft_3d {- return None;- }- let a = map.to_comp(map.area.min);- let b = map.to_comp(map.area.max);- effectcraft_engine::render::extended_region(comp.width, comp.height, [a[0], a[1], b[0], b[1]], 1.0)- }-- fn rect_of(map: &ViewerMap, r: Option<[f64; 4]>) -> Rect {- let [x, y, w, h] = r.unwrap_or_default();- Rect::from_min_max(map.to_screen([x, y]), map.to_screen([x + w, y + h]))- }-- /// Put a rendered frame on screen: CPU pixels go into an egui texture, averaged down by `minify`- /// (see [`minify_factor`]); GPU frames are drawn straight from their wgpu texture (registered with- /// egui-wgpu, no readback).- fn show_frame(app: &mut EffectcraftApp, ctx: &egui::Context, key: crate::frames::FrameKey, img: crate::frames::FrameImage, minify: usize) {- use crate::frames::FrameImage;- // Settings ▸ Previews ▸ Viewer Zoom Quality.- let smooth = app.session.prefs.viewer_zoom_smooth();- let opts = zoom_texture_options(smooth);- match img {- FrameImage::Cpu(img) => {- // Frames wider or taller than the GPU's texture limit go up averaged down too (#201).- let max = crate::frames::max_texture_side(ctx);- let fitted = crate::frames::fit_shared_texture_by(&img, max, minify);- match &mut app.viewer_tex {- Some((tex, k, m)) if tex.size() == fitted.size() => {- tex.set(fitted, opts);- (*k, *m) = (key, minify);- }- _ => app.viewer_tex = Some((ctx.load_texture("viewer-frame", fitted, opts), key, minify)),- }- app.viewer_shown = app.viewer_tex.as_ref().map(|(t, k, _)| (t.id(), *k));- app.viewer_image = Some(img);- vt::set_texture_roi(ctx, app.session.state.region_of_interest.or(app.ui.viewer.extended));- }- FrameImage::Gpu(f) => {- let Some(rs) = &app.wgpu else { return };- let view = f.texture.create_view(&Default::default());- let mut ren = rs.renderer.write();- let id = match &app.viewer_native {- Some((id, _, _)) => {- ren.update_egui_texture_from_wgpu_texture_with_sampler_options(&rs.device, &view, zoom_sampler(smooth), *id);- *id- }- None => ren.register_native_texture_with_sampler_options(&rs.device, &view, zoom_sampler(smooth)),- };- drop(ren);- app.viewer_native = Some((id, key, f));- app.viewer_shown = Some((id, key));- // Pixels are read back on demand (viewer_pixels).- app.viewer_image = None;- }- }- }+ mod frame;+ mod geometry;+ mod gesture;+ mod shapes;+ mod tools;+ mod view;+ use frame::{empty_state, rect_of, show_frame};+ pub(crate) use frame::{extended_region, minify_factor, snap_to_pixels, styled_line, zoom_sampler, zoom_texture_options};#[cfg(test)]- mod tests {- use super::*;- use effectcraft_engine::geom::{Mat4, vec3};-- /// The Rotation tool counts past a full turn in both directions, as in After Effects: the- /// pointer going round the anchor 1.5 turns clockwise gives 540°, then back 2 turns gives- /// −180°, with no jump where atan2 wraps from 180° to −180°.- #[test]- fn rotate_tool_accumulates_revolutions() {- // Screen y points down, so a growing atan2 angle is clockwise on screen.- let drag = |start: f64, steps: &[f64]| {- let (mut last, mut turned, mut out) = (start, 0.0, vec![]);- for &a in steps {- // atan2's range: (−180°, 180°].- let a = (a + 180.0).rem_euclid(360.0) - 180.0;- turned += turn_delta(last, a);- last = a;- out.push(turned);- }- (last, turned, out)- };- let cw: Vec<f64> = (1..=54).map(|i| i as f64 * 10.0).collect();- let (last, turned, seq) = drag(0.0, &cw);- assert!((turned - 540.0).abs() < 1e-9, "{turned}");- assert!(seq.windows(2).all(|w| (w[1] - w[0] - 10.0).abs() < 1e-9), "no jump: {seq:?}");- assert!((rotate_value(0.0, turned, false) - 540.0).abs() < 1e-9);- let ccw: Vec<f64> = (1..=72).map(|i| 540.0 - i as f64 * 10.0).collect();- let (_, back, seq) = drag(last, &ccw);- assert!(seq.windows(2).all(|w| (w[1] - w[0] + 10.0).abs() < 1e-9), "no jump: {seq:?}");- let total = turned + back;- assert!((total + 180.0).abs() < 1e-9, "{total}");- assert!((rotate_value(30.0, total, false) + 150.0).abs() < 1e-9);- // Shift snaps the accumulated value, not a wrapped one.- assert_eq!(rotate_value(0.0, 400.0, true), 405.0);- assert_eq!(rotate_value(0.0, -400.0, true), -405.0);- // Across the seam: 170° → −170° is +20°, and back is −20°; exactly half a turn is +180°.- assert!((turn_delta(170.0, -170.0) - 20.0).abs() < 1e-9);- assert!((turn_delta(-170.0, 170.0) + 20.0).abs() < 1e-9);- assert_eq!(turn_delta(0.0, 180.0), 180.0);- assert_eq!(turn_delta(0.0, -180.0), 180.0);- // Never crash or poison the value on non-finite input.- assert_eq!(turn_delta(f64::NAN, 10.0), 0.0);- assert_eq!(turn_delta(0.0, f64::INFINITY), 0.0);- assert_eq!(rotate_value(15.0, f64::NAN, false), 15.0);- }-- /// #1042: a path vertex lying under, or just beside, a bounding-box handle is grabbed- /// instead of the handle; away from every handle the reach is unchanged.- #[test]- fn vertex_reaches_as_far_as_a_box_handle_over_it() {- let handle = pos2(100.0, 100.0);- let vertex = pos2(100.0, 100.0);- // The press lands 8 points off the vertex, still on the handle's square.- let press = pos2(108.0, 100.0);- let pick = |p: Pos2, handles: &[Pos2]| vertex.distance(p) < vertex_grab_radius(p, handles.iter().copied());- assert!(handle.distance(press) < HANDLE + 2.0, "the handle would take this press");- assert!(pick(press, &[handle]), "the vertex wins over the handle");- assert!(!pick(press, &[]), "no handle there: the usual reach");- assert!(pick(pos2(105.0, 100.0), &[]));- assert!(!pick(pos2(120.0, 100.0), &[handle]), "past the handle: nothing");- }-- /// #882: the frame's corner sits on a physical pixel at any display scaling, so 100 % maps- /// comp pixels 1:1 onto screen pixels.- #[test]- fn frame_origin_snaps_to_physical_pixels() {- for ppp in [1.0f32, 1.25, 1.5, 1.75, 2.0] {- for p in [pos2(-201.12, 72.4), pos2(689.8, 239.75), pos2(0.3, -0.37)] {- let s = snap_to_pixels(p, ppp);- for v in [s.x * ppp, s.y * ppp] {- assert!((v - v.round()).abs() < 1e-3, "ppp {ppp}: {p:?} → {s:?}");- }- assert!((s - p).length() <= 0.71 / ppp, "moved by at most half a pixel: {p:?} → {s:?}");- }- }- assert_eq!(snap_to_pixels(pos2(1.3, 2.0), 0.0), pos2(1.3, 2.0));- }-- /// #882: a magnified frame shows its pixels as blocks in both Zoom Quality modes; More- /// Accurate only smooths when the frame is shown smaller.- #[test]- fn magnified_frames_are_never_smoothed() {- use eframe::wgpu::FilterMode;- for smooth in [true, false] {- assert_eq!(zoom_texture_options(smooth).magnification, egui::TextureFilter::Nearest);- assert_eq!(zoom_sampler(smooth).mag_filter, FilterMode::Nearest);- }- assert_eq!(zoom_texture_options(true).minification, egui::TextureFilter::Linear);- assert_eq!(zoom_sampler(true).min_filter, FilterMode::Linear);- }-- /// A perspective-like homography: w = 100 + y (the plane crosses the camera at y = −100).- fn tilted() -> Mat3 {- Mat3([[100.0, 0.0, 0.0], [0.0, 100.0, 0.0], [0.0, 1.0, 100.0]])- }-- /// #572: a box reaching behind the camera is clipped at the near plane instead of flipping- /// through infinity into long lines.- #[test]- fn outlines_clip_at_the_near_plane() {- let m = tilted();- let front = project_clipped(&m, &box_corners([-50.0, -50.0, 50.0, 50.0]));- assert_eq!(front.len(), 4);- let crossing = project_clipped(&m, &box_corners([-50.0, -150.0, 50.0, 50.0]));- assert_eq!(crossing.len(), 4, "{crossing:?}");- // Nothing flipped through infinity: a corner behind the camera (y = −150, w = −50) would- // land at y = +300 if it were projected as is; clipped at the near plane it runs off far- // above (negative y) instead, and the front corners stay where they were.- assert!(crossing.iter().all(|p| p[0].is_finite() && p[1].is_finite() && p[1] < 34.0), "{crossing:?}");- assert!(project_clipped(&m, &box_corners([-50.0, -400.0, 50.0, -200.0])).is_empty(), "wholly behind");- }+ use geometry::{box_corners, project_clipped};+ use geometry::{+ cam_state, drag_ratio, handle_axes, handle_cursor, handle_point, one_axis, project_segment, quad_intersects_box, rotate_value, selected_others,+ snap_handle, turn_delta,+ };+ pub(crate) use geometry::{from_effect_space, fx2c, l2c, layer_outline, layer_quad};+ use gesture::{Gesture, HANDLE, ROTO_HINT, pen_id, roi_drag, roi_handles, vertex_grab_radius};+ use shapes::{create_shape, draw_shape_ghost, shape_drag};-pub(crate) use shapes::{layer_at, layers_at, pick, selectable_layers};++pub(crate) use shapes::{layer_at, layers_at, pick, selectable_layers, shape_kind};+ #[cfg(test)]+ use tools::constrain_45;+ use tools::{add_motion_key, axis_at, axis_drag, drag_axes, draw_rigs, parent_world_inverse, pen_cursor, pen_cursor_icon, pen_press, select_motion_key};+ pub(crate) use view::checker;+ use view::{aux_views, locked_pane};- #[test]- fn gizmo_segments_clip_at_the_near_plane() {- // w = 100 + z.- let pc = Mat4([[100.0, 0.0, 0.0, 0.0], [0.0, 100.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 1.0, 100.0]]);- let s = project_segment(&pc, vec3(10.0, 0.0, 0.0), vec3(10.0, 0.0, -300.0)).unwrap();- assert_eq!(s[0], [10.0, 0.0]);- assert!(s[1][0] > 10.0 && s[1][0].is_finite(), "toward the camera it grows, never flips: {s:?}");- assert!(project_segment(&pc, vec3(0.0, 0.0, -200.0), vec3(0.0, 0.0, -300.0)).is_none());- }- }+ #[cfg(test)]+ mod tests;diff --cc crates/ui-egui/src/panels/viewer/shapes.rsindex 000000000,395219a05..1de85e46amode 000000,100644..100644--- a/crates/ui-egui/src/panels/viewer/shapes.rs+++ b/crates/ui-egui/src/panels/viewer/shapes.rs@@@ -1,0 -1,221 +1,221 @@@+ use super::geometry::{l2c, layer_quad, point_in_quad};+ use super::{+ Color32, Comp, EffectcraftApp, EvalCtx, Layer, LayerId, LayerSource, Mat3, PaintKind, Pos2, Rect, Stroke, Tick, Tokens, Tool, ViewerMap, gv2, json, ov,+ pos2,+ };++ /// Visible, unlocked layers eligible for viewer hit tests, in front-to-back order.+ /// Solo scope matches the renderer: any soloed AV layer activates it at every time (as in After+ /// Effects), even when hidden, locked or outside its in-out range.+ pub(crate) fn selectable_layers(comp: &Comp, time: Tick) -> impl Iterator<Item = &Layer> {+ let any_solo = comp.layers.iter().any(|l| l.switches.solo && l.source.is_av());+ comp.layers+ .iter()+ .filter(move |l| l.is_active_at(time) && l.switches.video && !l.switches.locked && !l.is_camera() && !l.is_light() && (!any_solo || l.switches.solo))+ }++ /// Selectable layers under a comp point, front to back.+ pub(crate) fn layers_at<'a, 'b>(ectx: &'b EvalCtx<'a>, cpt: [f64; 2]) -> impl Iterator<Item = &'a Layer> + 'b {+ selectable_layers(ectx.comp, ectx.time).filter(move |l| layer_quad(ectx, l).is_some_and(|(_, q, _)| point_in_quad(cpt, &q)))+ }++ /// Topmost selectable layer under a comp point.+ pub(crate) fn layer_at<'a>(ectx: &EvalCtx<'a>, cpt: [f64; 2]) -> Option<&'a Layer> {+ layers_at(ectx, cpt).next()+ }++ /// The layer a press at a comp point acts on, selected (Shift toggles the topmost layer). As in+ /// After Effects, a selected layer under the point comes before the layers in front of it, so it+ /// can be dragged where they cover it; otherwise the topmost layer (#230).+ pub(crate) fn pick(app: &mut EffectcraftApp, ectx: &EvalCtx, cpt: [f64; 2], toggle: bool) -> Option<LayerId> {+ if toggle {+ let hit = layer_at(ectx, cpt)?.id;+ let _ = app.session.execute("layer.select", json!({"layers": [hit.0], "toggle": true}));+ return Some(hit);+ }+ let selected = &app.session.state.selected_layers;+ let hits: Vec<LayerId> = layers_at(ectx, cpt).map(|l| l.id).collect();+ let hit = *hits.iter().find(|id| selected.contains(id)).or(hits.first())?;+ if !selected.contains(&hit) {+ let _ = app.session.execute("layer.select", json!({"layers": [hit.0]}));+ }+ Some(hit)+ }++ /// Where a shape drag is going to land: a mask on the selected layer, a group inside it, or a new+ /// shape layer.+ #[derive(Clone, Copy, PartialEq, Eq)]+ enum ShapeTarget {+ Mask,+ IntoLayer,+ NewLayer,+ }++ impl ShapeTarget {+ /// What the drag will make and where, named the way the ghost captions it.+ fn label(self, layer_name: &str) -> String {+ match self {+ ShapeTarget::Mask => format!("Mask on “{layer_name}”"),+ ShapeTarget::IntoLayer => format!("Into “{layer_name}”"),+ ShapeTarget::NewLayer => "New shape layer".to_string(),+ }+ }+ }++ /// A shape drag as it stands, after the Tools' normalisations: the path it will make and where it+ /// will land.+ pub(super) struct ShapeDrag {+ /// The `shape.newShape` / `layer.addMask` kind for the tool.+ kind: &'static str,+ /// Comp-space centre and size, what the drag will make.+ centre: [f64; 2],+ size: [f64; 2],+ target: ShapeTarget,+ /// The selected layer's name and the index its next mask would take, for the ghost's caption+ /// and colour.+ layer_name: String,+ mask_index: usize,+ }++ /// The kind `tool` draws, as `shape.newShape` / `layer.addMask` name it.-fn shape_kind(tool: Tool) -> &'static str {++pub(crate) fn shape_kind(tool: Tool) -> &'static str {+ match tool {+ Tool::Rectangle => "rect",+ Tool::RoundedRect => "rounded",+ Tool::Ellipse => "ellipse",+ Tool::Polygon => "polygon",+ _ => "star",+ }+ }++ /// What a shape tool drag from `start` to `end` makes, or `None` while it is too small to make+ /// anything. Alt (Option) draws from the press point and Shift squares the box; the live ghost and+ /// [`create_shape`] both go through this, so the drag always shows what it will commit.+ pub(super) fn shape_drag(app: &EffectcraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option<ShapeDrag> {+ let comp = app.session.active_comp()?;+ let selected = app.session.state.selected_layers.first().copied();+ let sel = selected.and_then(|id| comp.layer(id));+ // A footage, solid or other non-shape layer selected, or a shape layer with Tool Creates+ // Mask: a mask on that layer. Otherwise the engine's own target: the first selected unlocked+ // shape layer, else a new one.+ let target = match sel {+ Some(l) if l.source.is_av() && (app.session.state.shape_tool.creates_mask || !matches!(l.source, LayerSource::Shape)) => (ShapeTarget::Mask, Some(l)),+ _ => match effectcraft_engine::commands::shape_tool::selected_shape_target(&app.session, comp).and_then(|id| comp.layer(id)) {+ Some(l) => (ShapeTarget::IntoLayer, Some(l)),+ None => (ShapeTarget::NewLayer, None),+ },+ };+ let (target, layer) = target;+ let mask_index = if target == ShapeTarget::Mask { layer.and_then(|l| l.masks()).map_or(0, |m| m.groups().count()) } else { 0 };+ let (mut w, mut h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs());+ // Ctrl/Cmd draws from the press point as the centre, as in After Effects.+ if mods.command {+ w *= 2.0;+ h *= 2.0;+ }+ if w < 2.0 && h < 2.0 {+ return None;+ }+ if mods.shift {+ let m = w.max(h);+ w = m;+ h = m;+ }+ Some(ShapeDrag {+ kind: shape_kind(tool),+ centre: if mods.command { start } else { [start[0].min(end[0]) + w / 2.0, start[1].min(end[1]) + h / 2.0] },+ size: [w, h],+ target,+ layer_name: layer.map_or_else(String::new, |l| l.name.clone()),+ mask_index,+ })+ }++ /// The Tools bar's paint colour as bytes, dimmed by `alpha` so the comp shows through the ghost.+ fn paint_rgb(c: [f32; 3], opacity: f64, alpha: f32) -> Color32 {+ let f = |k: f32| (k.clamp(0.0, 1.0) * 255.0).round() as u8;+ Color32::from_rgb(f(c[0]), f(c[1]), f(c[2])).gamma_multiply((opacity.clamp(0.0, 100.0) / 100.0) as f32 * alpha)+ }++ /// Draw a shape drag as it will land: the tool's own path, filled with the Tools bar's Fill and+ /// outlined in its Stroke (or the mask colour, for a mask), captioned with where it goes.+ pub(super) fn draw_shape_ghost(painter: &egui::Painter, map: &ViewerMap, app: &EffectcraftApp, d: &ShapeDrag, t: &Tokens) {+ // The engine's own geometry for the kind, so the ghost is the shape and not a stand-in for it.+ let Some(sp) = effectcraft_engine::commands::shape_tool::mask_path(d.kind, d.centre, d.size) else { return };+ let mut pts = ov::flatten(&sp, &Mat3::IDENTITY, map);+ if pts.first() == pts.last() {+ pts.pop();+ }+ if pts.len() < 3 {+ return;+ }+ let tool = &app.session.state.shape_tool;+ let (fill, line) = match d.target {+ ShapeTarget::Mask => {+ let [r, g, b] = effectcraft_engine::prefs::mask_color(app.session.prefs.appearance.cycle_mask_colors, d.mask_index);+ (Color32::from_rgb(r, g, b).gamma_multiply(0.25), Color32::from_rgb(r, g, b))+ }+ _ => {+ let stroke_on = tool.stroke.kind != PaintKind::None && tool.stroke_width > 0.0;+ (+ if tool.fill.kind == PaintKind::None { Color32::TRANSPARENT } else { paint_rgb(tool.fill.color, tool.fill.opacity, 0.45) },+ if stroke_on { paint_rgb(tool.stroke.color, tool.stroke.opacity, 1.0) } else { t.accent },+ )+ }+ };+ let Some(bounds) = bounds_of(&pts) else { return };+ // A screen-width outline reads at every zoom, where a comp-pixel hairline does not.+ painter.add(egui::Shape::Path(egui::epaint::PathShape { points: pts, closed: true, fill, stroke: Stroke::new(1.5, line).into() }));+ // Caption it with where the shape lands: a mask, a group in the selected shape layer or a+ // new layer.+ let font = Tokens::ui(11.0);+ let galley = painter.layout_no_wrap(d.target.label(&d.layer_name), font, line);+ let caption = Rect::from_min_size(pos2(bounds.left(), bounds.top() - 5.0 - galley.size().y), galley.size());+ painter.rect_filled(caption.expand(3.0), 2.0, Color32::from_black_alpha(150));+ painter.galley(caption.min, galley, line);+ }++ /// The bounds of points on screen, or `None` for an empty set.+ fn bounds_of(pts: &[Pos2]) -> Option<Rect> {+ let first = *pts.first()?;+ let mut r = Rect::from_min_max(first, first);+ for p in pts.iter().skip(1) {+ r.extend_with(*p);+ }+ Some(r)+ }++ pub(super) fn create_shape(app: &mut EffectcraftApp, tool: Tool, a: [f64; 2], b: [f64; 2], mods: egui::Modifiers) {+ let Some(d) = shape_drag(app, tool, a, b, mods) else { return };+ let (kind, (w, h), (cx, cy)) = (d.kind, (d.size[0], d.size[1]), (d.centre[0], d.centre[1]));+ // A mask on the selected layer, as the ghost showed.+ if d.target == ShapeTarget::Mask {+ // In layer space: invert the layer transform.+ let sel_layer = app.session.state.selected_layers.first().copied().and_then(|id| app.session.active_comp().and_then(|c| c.layer(id)).cloned());+ if let Some(l) = sel_layer+ && let Some(comp) = app.session.active_comp_arc()+ {+ let ectx = EvalCtx {+ project: &app.session.project,+ comp_id: app.session.active_comp_id().unwrap_or_default(),+ comp: &comp,+ time: app.session.time(),+ expr: None,+ footage: None,+ };+ let inv = l2c(&ectx, &l).0.inverse().unwrap_or(Mat3::IDENTITY);+ let p0 = inv.apply(gv2(cx - w / 2.0, cy - h / 2.0));+ let p1 = inv.apply(gv2(cx + w / 2.0, cy + h / 2.0));+ let rect = [p0.x.min(p1.x), p0.y.min(p1.y), (p1.x - p0.x).abs(), (p1.y - p0.y).abs()];+ if let Err(e) = app.session.execute("layer.addMask", json!({"layer": l.id.0, "shape": kind, "rect": rect})) {+ app.ui.status = e.to_string();+ }+ }+ return;+ }+ // Into the selected shape layer's Contents as a new group (as in After Effects), else a new+ // shape layer; painted with the Tools bar's Fill and Stroke.+ if let Err(e) = app.session.execute("shape.newShape", json!({"kind": kind, "size": [w, h], "position": [cx, cy]})) {+ app.ui.status = e.to_string();+ }+ }