diff --git a/Cargo.lock b/Cargo.lock index 95fc3df8..b29b9181 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -749,6 +749,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + [[package]] name = "chacha20" version = "0.10.2" @@ -954,6 +963,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", + "libc", "objc2 0.6.4", ] @@ -1028,6 +1039,20 @@ dependencies = [ "emath", ] +[[package]] +name = "effectcraft" +version = "0.1.0" +dependencies = [ + "effectcraft-engine", + "effectcraft-host", + "effectcraft-ui-egui", + "eframe", + "egui", + "rfd", + "serde_json", + "winit", +] + [[package]] name = "effectcraft-cli" version = "0.1.0" @@ -1102,6 +1127,17 @@ dependencies = [ "serde", ] +[[package]] +name = "effectcraft-host" +version = "0.1.0" +dependencies = [ + "effectcraft-engine", + "effectcraft-expr", + "effectcraft-media", + "effectcraft-project", + "serde_json", +] + [[package]] name = "effectcraft-keyframe" version = "0.1.0" @@ -1242,6 +1278,9 @@ dependencies = [ "egui", "egui-wgpu", "egui-winit", + "egui_glow", + "glutin", + "glutin-winit", "image", "js-sys", "log", @@ -1323,6 +1362,20 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_glow" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "606ed4167daf341e5753d703285c4c1d562324b2c07aa8f405cd7d066fe58f3b" +dependencies = [ + "bytemuck", + "egui", + "glow", + "log", + "profiling", + "winit", +] + [[package]] name = "egui_kittest" version = "0.36.2" @@ -1938,6 +1991,63 @@ dependencies = [ "web-sys", ] +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + [[package]] name = "glutin_wgl_sys" version = "0.6.1" @@ -2668,7 +2778,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "objc2 0.6.4", + "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", ] @@ -3544,6 +3656,33 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "pollster 0.4.0", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "web-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustc-hash" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 4c5def65..4165cfef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,7 @@ effectcraft-render = { path = "crates/render" } effectcraft-media = { path = "crates/media" } effectcraft-expr = { path = "crates/expr" } effectcraft-engine = { path = "crates/engine" } +effectcraft-host = { path = "crates/host" } effectcraft-ui-egui = { path = "crates/ui-egui" } effectcraft-automation = { path = "crates/automation" } diff --git a/apps/effectcraft/Cargo.toml b/apps/effectcraft/Cargo.toml new file mode 100644 index 00000000..1759d4c0 --- /dev/null +++ b/apps/effectcraft/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "effectcraft" +description = "EffectCraft desktop app" +version.workspace = true +edition.workspace = true +license.workspace = true +default-run = "effectcraft" + +[lints] +workspace = true + +[dependencies] +effectcraft-engine = { workspace = true } +effectcraft-host = { workspace = true } +effectcraft-ui-egui = { workspace = true } +egui = { workspace = true } +eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] } +serde_json = { workspace = true } +rfd = { workspace = true } + +[target.'cfg(target_os = "macos")'.dependencies] +# Same winit as eframe: macOS event-loop options (no app activation when driven by an agent). +winit = { version = "0.30", default-features = false } diff --git a/apps/effectcraft/src/control_server.rs b/apps/effectcraft/src/control_server.rs new file mode 100644 index 00000000..a7aa0631 --- /dev/null +++ b/apps/effectcraft/src/control_server.rs @@ -0,0 +1,61 @@ +//! Localhost JSON-lines control server (one request per line, one reply per line). Loopback only. + +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::Duration; + +use effectcraft_ui_egui::ControlRequest; +use serde_json::{Value, json}; + +pub fn start(port: u16, ctx: egui::Context) -> Receiver { + let (tx, rx) = channel::(); + let listener = match TcpListener::bind(("127.0.0.1", port)) { + Ok(l) => l, + Err(e) => { + eprintln!("effectcraft: control server failed to bind 127.0.0.1:{port}: {e}"); + return rx; + } + }; + eprintln!("effectcraft: control server listening on 127.0.0.1:{port}"); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let tx = tx.clone(); + let ctx = ctx.clone(); + std::thread::spawn(move || serve(stream, tx, ctx)); + } + }); + rx +} + +fn serve(stream: TcpStream, tx: Sender, ctx: egui::Context) { + let Ok(read) = stream.try_clone() else { return }; + let mut out = stream; + for line in BufReader::new(read).lines() { + let Ok(line) = line else { break }; + if line.trim().is_empty() { + continue; + } + let reply = match serde_json::from_str::(&line) { + Ok(msg) => { + let id = msg.get("id").cloned().unwrap_or(Value::Null); + let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); + let params = msg.get("params").cloned().unwrap_or(json!({})); + let (req, rrx) = ControlRequest::new(method, params); + if tx.send(req).is_err() { + break; + } + ctx.request_repaint(); + let mut r = rrx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})); + if let Some(o) = r.as_object_mut() { + o.insert("id".into(), id); + } + r + } + Err(e) => json!({"ok": false, "error": format!("bad JSON: {e}")}), + }; + if writeln!(out, "{reply}").is_err() { + break; + } + } +} diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs new file mode 100644 index 00000000..6ee51c56 --- /dev/null +++ b/apps/effectcraft/src/main.rs @@ -0,0 +1,93 @@ +//! EffectCraft desktop app. +//! +//! Usage: `effectcraft [--control ] [--demo|--empty|--home] [project.ecproj | media files…]` +//! +//! `--control ` (or `EFFECTCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server; +//! see `effectcraft_ui_egui::control` for the methods. + +mod control_server; + +use effectcraft_ui_egui::EffectcraftApp; +use serde_json::json; + +fn main() -> eframe::Result { + let mut control_port: Option = std::env::var("EFFECTCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()); + let mut files = Vec::new(); + let mut demo = true; + let mut home = false; + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + match a.as_str() { + "--control" => control_port = args.next().and_then(|p| p.parse().ok()), + "--demo" => demo = true, + "--empty" => demo = false, + "--home" => home = true, + "--version" => { + println!("effectcraft {}", env!("CARGO_PKG_VERSION")); + return Ok(()); + } + _ => files.push(a), + } + } + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("EffectCraft") + .with_inner_size([1680.0, 1020.0]) + .with_min_inner_size([960.0, 600.0]) + .with_drag_and_drop(true) + // Started for an agent (`--control`): open without taking the user's keyboard focus. + .with_active(control_port.is_none()), + event_loop_builder: agent_event_loop(control_port.is_some()), + ..Default::default() + }; + eframe::run_native( + "EffectCraft", + options, + Box::new(move |cc| { + let mut session = effectcraft_host::session(); + let project = files.iter().find(|f| f.ends_with(".ecproj")).cloned(); + if let Some(p) = project { + if let Err(e) = session.execute("file.open", json!({"path": p})) { + eprintln!("effectcraft: {e}"); + } + } else if demo { + let _ = session.execute("file.openDemoProject", json!({})); + } + let media: Vec = files.iter().filter(|f| !f.ends_with(".ecproj")).cloned().collect(); + if !media.is_empty() { + if let Err(e) = session.execute("file.import", json!({"paths": media})) { + eprintln!("effectcraft: {e}"); + } + } + let mut app = EffectcraftApp::new(session); + app.ui.start_screen = home; + app.hooks.pick_files = Some(Box::new(|exts: &[&str]| { + rfd::FileDialog::new().add_filter("Media", exts).pick_files().unwrap_or_default().into_iter().map(|p| p.to_string_lossy().to_string()).collect() + })); + app.hooks.pick_save = Some(Box::new(|name: &str| { + rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"]).set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()) + })); + app.hooks.pick_open_project = + Some(Box::new(|| rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"]).pick_file().map(|p| p.to_string_lossy().to_string()))); + if let Some(port) = control_port { + let rx = control_server::start(port, cc.egui_ctx.clone()); + app = app.with_control(rx); + } + Ok(Box::new(app)) + }), + ) +} + +/// Driven by an agent (`--control`): don't activate the app on launch, so the user's keyboard +/// focus stays where it is (macOS; winit activates ignoring other apps by default). +fn agent_event_loop(agent: bool) -> Option { + #[cfg(target_os = "macos")] + if agent { + return Some(Box::new(|b| { + use winit::platform::macos::EventLoopBuilderExtMacOS; + b.with_activate_ignoring_other_apps(false); + })); + } + let _ = agent; + None +} diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 2145bbff..ee239c3c 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -186,7 +186,12 @@ fn dodge(cb: f32, cs: f32) -> f32 { } } fn hard_light(cb: f32, cs: f32) -> f32 { - if cs <= 0.5 { cb * 2.0 * cs } else { let s = 2.0 * cs - 1.0; cb + s - cb * s } + if cs <= 0.5 { + cb * 2.0 * cs + } else { + let s = 2.0 * cs - 1.0; + cb + s - cb * s + } } fn soft_light(cb: f32, cs: f32) -> f32 { if cs <= 0.5 { diff --git a/crates/effects/src/color_fx.rs b/crates/effects/src/color_fx.rs index fa6fca5d..3a8650e8 100644 --- a/crates/effects/src/color_fx.rs +++ b/crates/effects/src/color_fx.rs @@ -33,7 +33,11 @@ fn tritone(ctx: &EffectCtx, mut b: Buf) -> Buf { let blend = 1.0 - ctx.params.f("blend") as f32 / 100.0; b.img.map_straight(|c| { let l = luminance(c[0], c[1], c[2]).clamp(0.0, 1.0); - let t = if l < 0.5 { mix([sh[0], sh[1], sh[2]], [mid[0], mid[1], mid[2]], l * 2.0) } else { mix([mid[0], mid[1], mid[2]], [hi[0], hi[1], hi[2]], (l - 0.5) * 2.0) }; + let t = if l < 0.5 { + mix([sh[0], sh[1], sh[2]], [mid[0], mid[1], mid[2]], l * 2.0) + } else { + mix([mid[0], mid[1], mid[2]], [hi[0], hi[1], hi[2]], (l - 0.5) * 2.0) + }; mix(c, t, blend) }); b @@ -105,7 +109,8 @@ fn exposure(ctx: &EffectCtx, mut b: Buf) -> Buf { } fn black_white(ctx: &EffectCtx, mut b: Buf) -> Buf { - let w = [ctx.params.f("reds"), ctx.params.f("yellows"), ctx.params.f("greens"), ctx.params.f("cyans"), ctx.params.f("blues"), ctx.params.f("magentas")].map(|v| v as f32 / 100.0); + let w = [ctx.params.f("reds"), ctx.params.f("yellows"), ctx.params.f("greens"), ctx.params.f("cyans"), ctx.params.f("blues"), ctx.params.f("magentas")] + .map(|v| v as f32 / 100.0); let tint_on = ctx.params.b("tint"); let tc = ctx.params.color("tintColor"); b.img.map_straight(|c| { @@ -243,7 +248,8 @@ fn channel_mixer(ctx: &EffectCtx, mut b: Buf) -> Buf { } fn gamma_pg(ctx: &EffectCtx, mut b: Buf) -> Buf { - let ch = |n: &str| (ctx.params.f(&format!("{n}Gamma")).max(0.01) as f32, ctx.params.f(&format!("{n}Pedestal")) as f32, ctx.params.f(&format!("{n}Gain")) as f32); + let ch = + |n: &str| (ctx.params.f(&format!("{n}Gamma")).max(0.01) as f32, ctx.params.f(&format!("{n}Pedestal")) as f32, ctx.params.f(&format!("{n}Gain")) as f32); let r = ch("red"); let g = ch("green"); let bl = ch("blue"); @@ -426,7 +432,17 @@ pub fn specs() -> Vec { { let ids = ["rr", "rg", "rb", "rc", "gr", "gg", "gb", "gc", "br", "bg", "bb", "bc"]; let names = [ - "Red-Red", "Red-Green", "Red-Blue", "Red-Const", "Green-Red", "Green-Green", "Green-Blue", "Green-Const", "Blue-Red", "Blue-Green", "Blue-Blue", + "Red-Red", + "Red-Green", + "Red-Blue", + "Red-Const", + "Green-Red", + "Green-Green", + "Green-Blue", + "Green-Const", + "Blue-Red", + "Blue-Green", + "Blue-Blue", "Blue-Const", ]; let mut v: Vec<_> = ids diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index c3fd4209..11a50632 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -1,10 +1,10 @@ //! Distort effects: inverse-mapped warps (each output pixel samples the source). use effectcraft_geom::{Mat3, vec2}; -use rayon::prelude::*; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; use effectcraft_raster::Image; +use rayon::prelude::*; use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider}; @@ -89,7 +89,13 @@ fn wave_warp(ctx: &EffectCtx, mut b: Buf) -> Buf { let wave = move |t: f64| -> f64 { let ph = t.rem_euclid(std::f64::consts::TAU) / std::f64::consts::TAU; match kind { - 1 => if ph < 0.5 { 1.0 } else { -1.0 }, + 1 => { + if ph < 0.5 { + 1.0 + } else { + -1.0 + } + } 2 => 1.0 - 4.0 * (ph - 0.5).abs(), 3 => 2.0 * ph - 1.0, _ => t.sin(), @@ -278,7 +284,12 @@ pub fn specs() -> Vec { ], ripple, ), - spec("ec.distort.mirror", "Mirror", vec![p("center", "Reflection Center", pt(0.5, 0.5), ParamUi::Point), p("angle", "Reflection Angle", num(0.0), ParamUi::Angle)], mirror), + spec( + "ec.distort.mirror", + "Mirror", + vec![p("center", "Reflection Center", pt(0.5, 0.5), ParamUi::Point), p("angle", "Reflection Angle", num(0.0), ParamUi::Angle)], + mirror, + ), spec( "ec.distort.offset", "Offset", diff --git a/crates/effects/src/generate.rs b/crates/effects/src/generate.rs index 8bd47023..4790e3a4 100644 --- a/crates/effects/src/generate.rs +++ b/crates/effects/src/generate.rs @@ -1,9 +1,9 @@ //! Generate and Noise effects that synthesise images. -use rayon::prelude::*; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; use effectcraft_raster::Px; +use rayon::prelude::*; use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider}; @@ -142,7 +142,8 @@ fn circle(ctx: &EffectCtx, mut b: Buf) -> Buf { #[inline] fn lattice(ix: i32, iy: i32, iz: i32, seed: u32) -> f32 { - let mut h = (ix as u32).wrapping_mul(0x27d4_eb2d) ^ (iy as u32).wrapping_mul(0x1656_67b1) ^ (iz as u32).wrapping_mul(0x9e37_79b9) ^ seed.wrapping_mul(0x85eb_ca6b); + let mut h = + (ix as u32).wrapping_mul(0x27d4_eb2d) ^ (iy as u32).wrapping_mul(0x1656_67b1) ^ (iz as u32).wrapping_mul(0x9e37_79b9) ^ seed.wrapping_mul(0x85eb_ca6b); h ^= h >> 15; h = h.wrapping_mul(0x2c1b_3c6d); h ^= h >> 12; diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 4523b591..72ac2676 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -300,7 +300,12 @@ fn noise(ctx: &EffectCtx, mut b: Buf) -> Buf { continue; } let n = |k: u32| (hash_noise(x as u32 + k * w, y as u32, frame_seed) - 0.5) * amt; - let (r, g, bl) = if color { (n(0), n(1), n(2)) } else { let v = n(0); (v, v, v) }; + let (r, g, bl) = if color { + (n(0), n(1), n(2)) + } else { + let v = n(0); + (v, v, v) + }; px[0] = (px[0] + r * a).clamp(0.0, a); px[1] = (px[1] + g * a).clamp(0.0, a); px[2] = (px[2] + bl * a).clamp(0.0, a); @@ -494,7 +499,10 @@ pub fn specs() -> Vec { "ec.noise.noise", "Noise", "Noise & Grain", - vec![p("amount", "Amount of Noise", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)), p("color", "Use Color Noise", Value::Bool(true), ParamUi::Checkbox)], + vec![ + p("amount", "Amount of Noise", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)), + p("color", "Use Color Noise", Value::Bool(true), ParamUi::Checkbox), + ], noise, ), spec( diff --git a/crates/engine/src/commands/file.rs b/crates/engine/src/commands/file.rs index e26ea03c..aa9b8fb2 100644 --- a/crates/engine/src/commands/file.rs +++ b/crates/engine/src/commands/file.rs @@ -148,7 +148,15 @@ pub fn specs() -> Vec { cmd!("file.incrementAndSave", "Increment and Save", ["File"], Some("Cmd+Alt+Shift+S"), "{}", has_path, increment_save), cmd!("file.revert", "Revert", ["File"], None, "{}", has_path, revert), cmd!("file.import", "File…", ["File", "Import"], Some("Cmd+I"), "{paths: [string]}", always, import), - cmd!("file.projectSettings", "Project Settings…", ["File"], Some("Cmd+Alt+Shift+K"), "{bitDepth?: 8|16|32, linearize?, timeDisplay?: timecode|frames}", always, project_settings), + cmd!( + "file.projectSettings", + "Project Settings…", + ["File"], + Some("Cmd+Alt+Shift+K"), + "{bitDepth?: 8|16|32, linearize?, timeDisplay?: timecode|frames}", + always, + project_settings + ), cmd!("file.cycleBitDepth", "Cycle Project Bit Depth", [], None, "{}", always, cycle_depth), ] } diff --git a/crates/engine/src/commands/help.rs b/crates/engine/src/commands/help.rs index 7b536051..4cd9a799 100644 --- a/crates/engine/src/commands/help.rs +++ b/crates/engine/src/commands/help.rs @@ -23,6 +23,14 @@ pub fn specs() -> Vec { cmd!("help.appPage", "EffectCraft Home Page", ["Help"], None, "{}", always, |s, _| open(s, links::APP_PAGE.into())), cmd!("help.github", "EffectCraft on GitHub", ["Help"], None, "{}", always, |s, _| open(s, links::GITHUB.into())), cmd!("help.reportIssue", "Report an Issue…", ["Help"], None, "{}", always, |s, _| open(s, links::ISSUES.into())), - cmd!("help.sibling", "Other ArtCraft Apps", [], None, "{app: photocraft|drawcraft|filmcraft|lightcraft|printcraft|designcraft, kind?: page|github}", always, sibling), + cmd!( + "help.sibling", + "Other ArtCraft Apps", + [], + None, + "{app: photocraft|drawcraft|filmcraft|lightcraft|printcraft|designcraft, kind?: page|github}", + always, + sibling + ), ] } diff --git a/crates/engine/src/commands/layer.rs b/crates/engine/src/commands/layer.rs index 7c97a359..f329dfaa 100644 --- a/crates/engine/src/commands/layer.rs +++ b/crates/engine/src/commands/layer.rs @@ -167,7 +167,11 @@ fn new_shape(s: &mut Session, p: &Value) -> Result { let cid = comp_id(s, p)?; let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); let kind = str_p(p, "kind").unwrap_or("none").to_string(); - let size = p.get("size").and_then(Value::as_array).map(|a| [a[0].as_f64().unwrap_or(200.0), a.get(1).and_then(Value::as_f64).unwrap_or(200.0)]).unwrap_or([300.0, 300.0]); + let size = p + .get("size") + .and_then(Value::as_array) + .map(|a| [a[0].as_f64().unwrap_or(200.0), a.get(1).and_then(Value::as_f64).unwrap_or(200.0)]) + .unwrap_or([300.0, 300.0]); let fill = Some(c4(color_p(p, "fill"), [0.25, 0.55, 1.0, 1.0])); let stroke = (f_p(p, "strokeWidth").unwrap_or(0.0) > 0.0).then(|| (c4(color_p(p, "stroke"), [1.0, 1.0, 1.0, 1.0]), f_p(p, "strokeWidth").unwrap_or(2.0))); let pos = p.get("position").and_then(|v| v.as_array()).map(|a| [a[0].as_f64().unwrap_or(0.0), a.get(1).and_then(Value::as_f64).unwrap_or(0.0)]); @@ -669,7 +673,10 @@ fn add_shape_item(s: &mut Session, p: &Value) -> Result { let l = layer_mut(proj, cid, lid)?; let contents = l.props.sub_mut("contents").ok_or_else(|| bad("layer.addShapeItem", "not a shape layer"))?; let target = match group_uid { - Some(u) => contents.find_group_mut(u).and_then(|g| if g.match_id == "contents" { Some(g) } else { g.sub_mut("contents") }).ok_or_else(|| bad("layer.addShapeItem", "no such group"))?, + Some(u) => contents + .find_group_mut(u) + .and_then(|g| if g.match_id == "contents" { Some(g) } else { g.sub_mut("contents") }) + .ok_or_else(|| bad("layer.addShapeItem", "no such group"))?, None => contents, }; target.children.push(g.into()); @@ -734,7 +741,8 @@ fn transform_op(s: &mut Session, p: &Value) -> Result { let op = str_p(p, "op").unwrap_or("reset").to_string(); let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); let t = s.time(); - let sizes: Vec<(LayerId, (u32, u32))> = comp.layers.iter().filter(|l| ids.contains(&l.id)).map(|l| (l.id, effectcraft_render::source_size(&s.project, l))).collect(); + let sizes: Vec<(LayerId, (u32, u32))> = + comp.layers.iter().filter(|l| ids.contains(&l.id)).map(|l| (l.id, effectcraft_render::source_size(&s.project, l))).collect(); s.edit("Transform", None, |proj, _| { for (lid, (w, h)) in &sizes { let l = layer_mut(proj, cid, *lid)?; @@ -848,7 +856,15 @@ pub fn specs() -> Vec { cmd!("layer.newLight", "Light…", ["Layer", "New"], Some("Cmd+Alt+Shift+L"), "{kind?: Parallel|Spot|Point|Ambient}", has_comp, new_light), cmd!("layer.newCamera", "Camera…", ["Layer", "New"], Some("Cmd+Alt+Shift+C"), "{name?}", has_comp, new_camera), cmd!("layer.newNull", "Null Object", ["Layer", "New"], Some("Cmd+Alt+Shift+Y"), "{name?}", has_comp, new_null), - cmd!("layer.newShape", "Shape Layer", ["Layer", "New"], None, "{kind?: rect|rounded|ellipse|star|polygon|none, size?, fill?, stroke?, strokeWidth?, position?}", has_comp, new_shape), + cmd!( + "layer.newShape", + "Shape Layer", + ["Layer", "New"], + None, + "{kind?: rect|rounded|ellipse|star|polygon|none, size?, fill?, stroke?, strokeWidth?, position?}", + has_comp, + new_shape + ), cmd!("layer.newAdjustment", "Adjustment Layer", ["Layer", "New"], Some("Cmd+Alt+Y"), "{name?}", has_comp, new_adjustment), cmd!("layer.settings", "Layer Settings…", ["Layer"], Some("Cmd+Shift+Y"), "{layer?, name?, color?, width?, height?}", has_layers, layer_settings), cmd!("layer.addItem", "Add Footage to Comp", ["File"], Some("Cmd+/"), "{item: id|name, time?}", has_comp, add_item), @@ -866,12 +882,36 @@ pub fn specs() -> Vec { ), cmd!("layer.rename", "Rename", [], Some("Enter"), "{layer?, name}", has_layers, rename), cmd!("layer.setBlendMode", "Blending Mode", [], None, "{layers?, mode?: Normal|Multiply|Screen|…, step?: ±1}", has_layers, blend), - cmd!("layer.setTrackMatte", "Track Matte", [], None, "{layer?, matte: layer|null, kind?: alpha|alphaInverted|luma|lumaInverted}", has_layers, track_matte), + cmd!( + "layer.setTrackMatte", + "Track Matte", + [], + None, + "{layer?, matte: layer|null, kind?: alpha|alphaInverted|luma|lumaInverted}", + has_layers, + track_matte + ), cmd!("layer.setParent", "Parent", [], None, "{layers?, parent: layer|null}", has_layers, set_parent), - cmd!("layer.timing", "Layer Timing", [], None, "{layers?, op?: moveInToTime|moveOutToTime|trimInToTime|trimOutToTime, delta?, start?, in?, out?, merge?}", has_layers, timing), + cmd!( + "layer.timing", + "Layer Timing", + [], + None, + "{layers?, op?: moveInToTime|moveOutToTime|trimInToTime|trimOutToTime, delta?, start?, in?, out?, merge?}", + has_layers, + timing + ), cmd!("layer.arrange", "Arrange", ["Layer", "Arrange"], None, "{layers?, to: front|forward|backward|back, index?}", has_layers, arrange), cmd!("layer.precompose", "Pre-compose…", ["Layer"], Some("Cmd+Shift+C"), "{layers?, name?}", has_layers, precompose), - cmd!("layer.addMask", "New Mask", ["Layer", "Mask"], Some("Cmd+Shift+N"), "{layer?, shape?: rect|ellipse, rect? [x,y,w,h], mode?}", has_layers, add_mask), + cmd!( + "layer.addMask", + "New Mask", + ["Layer", "Mask"], + Some("Cmd+Shift+N"), + "{layer?, shape?: rect|ellipse, rect? [x,y,w,h], mode?}", + has_layers, + add_mask + ), cmd!("layer.setMask", "Mask Mode", [], None, "{layer?, mask: index|uid|name, mode?, inverted?}", has_layers, mask_props), cmd!( "layer.addShapeItem", @@ -891,8 +931,24 @@ pub fn specs() -> Vec { has_layers, set_text ), - cmd!("layer.addTextAnimator", "Animate Text", ["Animation"], None, "{layer?, properties: [position|scale|rotation|opacity|fillColor|tracking|…]}", has_layers, add_animator), - cmd!("layer.transform", "Transform", ["Layer", "Transform"], None, "{layers?, op: reset|center|fit|fitWidth|fitHeight|flipH|flipV}", has_layers, transform_op), + cmd!( + "layer.addTextAnimator", + "Animate Text", + ["Animation"], + None, + "{layer?, properties: [position|scale|rotation|opacity|fillColor|tracking|…]}", + has_layers, + add_animator + ), + cmd!( + "layer.transform", + "Transform", + ["Layer", "Transform"], + None, + "{layers?, op: reset|center|fit|fitWidth|fitHeight|flipH|flipV}", + has_layers, + transform_op + ), cmd!("layer.timeStretch", "Time Stretch…", ["Layer", "Time"], None, "{layers?, percent?, op?: reverse}", has_layers, time_stretch), ] } diff --git a/crates/engine/src/commands/mod.rs b/crates/engine/src/commands/mod.rs index a775eba1..1a7b41a8 100644 --- a/crates/engine/src/commands/mod.rs +++ b/crates/engine/src/commands/mod.rs @@ -47,7 +47,16 @@ macro_rules! cmd { #[macro_export] macro_rules! query { ($id:literal, $label:literal, $params:literal, $run:expr) => { - $crate::commands::CommandSpec { id: $id, label: $label, menu: &[], shortcut: None, params: $params, enabled: $crate::commands::always, run: $run, journal: false } + $crate::commands::CommandSpec { + id: $id, + label: $label, + menu: &[], + shortcut: None, + params: $params, + enabled: $crate::commands::always, + run: $run, + journal: false, + } }; } @@ -140,7 +149,13 @@ pub(crate) fn layer_p(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, Laye if let Some(v) = p.get("layer") { return resolve_layer(comp, v).map(|l| (cid, l)).ok_or_else(|| bad(cmd, format!("no layer {v}"))); } - s.state.selected_layers.first().copied().filter(|l| comp.layer(*l).is_some()).map(|l| (cid, l)).ok_or_else(|| bad(cmd, "no `layer` given and no layer selected")) + s.state + .selected_layers + .first() + .copied() + .filter(|l| comp.layer(*l).is_some()) + .map(|l| (cid, l)) + .ok_or_else(|| bad(cmd, "no `layer` given and no layer selected")) } /// `layers` param (array) or the selection. diff --git a/crates/engine/src/commands/prop.rs b/crates/engine/src/commands/prop.rs index 685321de..43bd88e6 100644 --- a/crates/engine/src/commands/prop.rs +++ b/crates/engine/src/commands/prop.rs @@ -20,7 +20,15 @@ fn prop_ref(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> Ok((cid, lid, pr.uid)) } -fn with_prop(s: &mut Session, label: &str, merge: Option<&str>, cid: ItemId, lid: LayerId, uid: Uid, f: impl FnOnce(&mut Property, Tick) -> Result) -> Result { +fn with_prop( + s: &mut Session, + label: &str, + merge: Option<&str>, + cid: ItemId, + lid: LayerId, + uid: Uid, + f: impl FnOnce(&mut Property, Tick) -> Result, +) -> Result { let t = s.time(); s.edit(label, merge, |proj, _| { let l = layer_mut(proj, cid, lid)?; @@ -403,15 +411,42 @@ pub fn specs() -> Vec { cmd!("prop.setExpression", "Add Expression", ["Animation"], Some("Alt+Shift+="), "{layer?, path|prop, expression?, enabled?}", has_layers, set_expr), cmd!("prop.reset", "Reset Property", [], None, "{layer?, path|prop, default?}", has_layers, reset), cmd!("prop.select", "Select Property", [], None, "{layer?, path|prop, add?, selectKeys?}", has_layers, select_prop), - cmd!("prop.convertExpressionToKeyframes", "Convert Expression to Keyframes", ["Animation", "Keyframe Assistant"], None, "{layer?, path|prop}", has_layers, convert_expr_to_keys), + cmd!( + "prop.convertExpressionToKeyframes", + "Convert Expression to Keyframes", + ["Animation", "Keyframe Assistant"], + None, + "{layer?, path|prop}", + has_layers, + convert_expr_to_keys + ), cmd!("keys.select", "Select Keyframes", [], None, "{keys: [{layer, prop, time}], add?}", has_comp, select_keys), cmd!("keys.move", "Move Keyframes", [], None, "{delta (s), merge?}", has_keys, move_keys), cmd!("keys.delete", "Delete Keyframes", [], None, "{}", has_keys, delete_keys), cmd!("keys.easyEase", "Easy Ease", ["Animation", "Keyframe Assistant"], Some("F9"), "{which?: both|in|out}", has_keys, ease), cmd!("keys.easyEaseIn", "Easy Ease In", ["Animation", "Keyframe Assistant"], Some("Shift+F9"), "{}", has_keys, |s, _| ease(s, &json!({"which": "in"}))), - cmd!("keys.easyEaseOut", "Easy Ease Out", ["Animation", "Keyframe Assistant"], Some("Cmd+Shift+F9"), "{}", has_keys, |s, _| ease(s, &json!({"which": "out"}))), + cmd!("keys.easyEaseOut", "Easy Ease Out", ["Animation", "Keyframe Assistant"], Some("Cmd+Shift+F9"), "{}", has_keys, |s, _| ease( + s, + &json!({"which": "out"}) + )), cmd!("keys.toggleHold", "Toggle Hold Keyframe", ["Animation"], Some("Cmd+Alt+H"), "{}", has_keys, toggle_hold), - cmd!("keys.interpolation", "Keyframe Interpolation…", ["Animation"], Some("Cmd+Alt+K"), "{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}", has_keys, interpolation), - cmd!("keys.velocity", "Keyframe Velocity…", ["Animation"], Some("Cmd+Shift+K"), "{inSpeed?, inInfluence? %, outSpeed?, outInfluence? %}", has_keys, velocity), + cmd!( + "keys.interpolation", + "Keyframe Interpolation…", + ["Animation"], + Some("Cmd+Alt+K"), + "{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}", + has_keys, + interpolation + ), + cmd!( + "keys.velocity", + "Keyframe Velocity…", + ["Animation"], + Some("Cmd+Shift+K"), + "{inSpeed?, inInfluence? %, outSpeed?, outInfluence? %}", + has_keys, + velocity + ), ] } diff --git a/crates/engine/src/commands/query.rs b/crates/engine/src/commands/query.rs index 298f9d25..1804eaaf 100644 --- a/crates/engine/src/commands/query.rs +++ b/crates/engine/src/commands/query.rs @@ -86,7 +86,12 @@ fn group_json(g: &PropGroup, l: &Layer, t: effectcraft_time::Tick, depth: usize, Node::Prop(p) => { let mut o = json!({"uid": p.uid, "match": p.match_id, "name": p.name, "value": p.value_at(l.layer_time(t)).to_json()}); if !p.keys.is_empty() { - o["keys"] = json!(p.keys.iter().map(|k| json!({"time": k.time.seconds(), "value": k.value.to_json(), "in": k.in_interp.label(), "out": k.out_interp.label()})).collect::>()); + o["keys"] = json!( + p.keys + .iter() + .map(|k| json!({"time": k.time.seconds(), "value": k.value.to_json(), "in": k.in_interp.label(), "out": k.out_interp.label()})) + .collect::>() + ); } if let Some(e) = &p.expr { o["expression"] = json!(e.text); diff --git a/crates/engine/src/commands/time.rs b/crates/engine/src/commands/time.rs index 2f6fb870..0b4e20ff 100644 --- a/crates/engine/src/commands/time.rs +++ b/crates/engine/src/commands/time.rs @@ -51,7 +51,11 @@ fn go(s: &mut Session, p: &Value) -> Result { "nextKey" | "prevKey" => { // Keyframes (of visible/selected layers) and markers, in comp time. let mut times: Vec = comp.markers.iter().map(|m| m.time).collect(); - let layers: Vec<_> = if s.state.selected_layers.is_empty() { comp.layers.iter().collect() } else { comp.layers.iter().filter(|l| s.state.selected_layers.contains(&l.id)).collect() }; + let layers: Vec<_> = if s.state.selected_layers.is_empty() { + comp.layers.iter().collect() + } else { + comp.layers.iter().filter(|l| s.state.selected_layers.contains(&l.id)).collect() + }; for l in layers { l.props.walk("", &mut |_, pr| { for k in &pr.keys { diff --git a/crates/engine/src/demo.rs b/crates/engine/src/demo.rs index 8bcf76a6..eca58e6d 100644 --- a/crates/engine/src/demo.rs +++ b/crates/engine/src/demo.rs @@ -2,10 +2,10 @@ //! work, MIT OR Apache-2.0): gradient background, orbiting shape rings with trim paths and a //! repeater burst, an animated title with a text animator and glow, a lower-third precomp. +use effectcraft_color::BlendMode; use effectcraft_color::Label; use effectcraft_keyframe::{Ease, Gradient, Interp, Justify, Keyframe, TextDoc, Value}; use effectcraft_project::build::{self, Ids}; -use effectcraft_color::BlendMode; use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, Project, PropGroup, Solid}; use effectcraft_time::{FrameRate, Tick}; @@ -227,7 +227,10 @@ pub fn demo_project() -> Project { false, [-320.0, 0.0], [320.0, 0.0], - Gradient { colors: vec![(0.0, [0.24, 0.56, 0.96, 1.0]), (1.0, [0.56, 0.42, 1.0, 1.0])], opacities: vec![(0.0, 0.0), (0.2, 1.0), (0.8, 1.0), (1.0, 0.0)] }, + Gradient { + colors: vec![(0.0, [0.24, 0.56, 0.96, 1.0]), (1.0, [0.56, 0.42, 1.0, 1.0])], + opacities: vec![(0.0, 0.0), (0.2, 1.0), (0.8, 1.0), (1.0, 0.0)], + }, ); let g = build::shape_group(&mut ids, "Line", vec![r, gf]); contents(&mut line, vec![g]); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7f851c02..89bfe04f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -22,8 +22,8 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; pub use commands::{CommandSpec, command_specs, find as find_command}; -pub use effectcraft_effects as effects; pub use effectcraft_color as color; +pub use effectcraft_effects as effects; pub use effectcraft_geom as geom; pub use effectcraft_keyframe as keyframe; pub use effectcraft_project as project; @@ -320,3 +320,8 @@ impl Session { #[cfg(test)] mod tests; + +/// Font families available to text layers (bundled + scanned system fonts). +pub fn text_families() -> Vec { + effectcraft_text::families().into_iter().map(|(f, _)| f).collect() +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 66382153..ef095c52 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -114,4 +114,3 @@ fn time_navigation() { s.execute("time.set", json!({"frame": 45})).unwrap(); assert_eq!(s.execute("time.step", json!({"frames": 5})).unwrap()["frame"], 50); } - diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 09f5df45..fda0ac01 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -228,21 +228,9 @@ impl Mat3 { } let m = &self.0; let inv = [ - [ - (m[1][1] * m[2][2] - m[1][2] * m[2][1]) / d, - (m[0][2] * m[2][1] - m[0][1] * m[2][2]) / d, - (m[0][1] * m[1][2] - m[0][2] * m[1][1]) / d, - ], - [ - (m[1][2] * m[2][0] - m[1][0] * m[2][2]) / d, - (m[0][0] * m[2][2] - m[0][2] * m[2][0]) / d, - (m[0][2] * m[1][0] - m[0][0] * m[1][2]) / d, - ], - [ - (m[1][0] * m[2][1] - m[1][1] * m[2][0]) / d, - (m[0][1] * m[2][0] - m[0][0] * m[2][1]) / d, - (m[0][0] * m[1][1] - m[0][1] * m[1][0]) / d, - ], + [(m[1][1] * m[2][2] - m[1][2] * m[2][1]) / d, (m[0][2] * m[2][1] - m[0][1] * m[2][2]) / d, (m[0][1] * m[1][2] - m[0][2] * m[1][1]) / d], + [(m[1][2] * m[2][0] - m[1][0] * m[2][2]) / d, (m[0][0] * m[2][2] - m[0][2] * m[2][0]) / d, (m[0][2] * m[1][0] - m[0][0] * m[1][2]) / d], + [(m[1][0] * m[2][1] - m[1][1] * m[2][0]) / d, (m[0][1] * m[2][0] - m[0][0] * m[2][1]) / d, (m[0][0] * m[1][1] - m[0][1] * m[1][0]) / d], ]; Some(Mat3(inv)) } @@ -357,11 +345,7 @@ impl Mat4 { } pub fn apply_vec(&self, v: Vec3) -> Vec3 { let m = &self.0; - vec3( - m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z, - m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z, - m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z, - ) + vec3(m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z, m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z, m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z) } pub fn transpose(&self) -> Mat4 { let mut r = [[0.0; 4]; 4]; diff --git a/crates/host/Cargo.toml b/crates/host/Cargo.toml new file mode 100644 index 00000000..642fab7a --- /dev/null +++ b/crates/host/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "effectcraft-host" +description = "Builds a fully wired EffectCraft session: media decoding (FilmCraft codecs), importer and the expression engine" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +effectcraft-engine = { workspace = true } +effectcraft-project = { workspace = true } +effectcraft-media = { workspace = true } +effectcraft-expr = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs new file mode 100644 index 00000000..15ef3f54 --- /dev/null +++ b/crates/host/src/lib.rs @@ -0,0 +1,40 @@ +//! A fully wired [`Session`]: footage decoding through `effectcraft-media` (FilmCraft's codecs), +//! the media importer and the expression engine. Frontends (desktop, CLI, MCP, web) start here. + +use std::sync::Arc; + +use effectcraft_engine::{Importer, Session}; +use effectcraft_project::Footage; + +struct MediaImporter; + +impl Importer for MediaImporter { + fn probe(&self, path: &str) -> Result { + effectcraft_media::probe(path).map_err(|e| e.to_string()) + } +} + +/// A new session with media, import and expressions enabled. +pub fn session() -> Session { + let mut s = Session::default(); + s.footage = Arc::new(effectcraft_media::MediaPool::new()); + s.importer = Some(Arc::new(MediaImporter)); + s.expr = Some(Arc::new(effectcraft_expr::Expressions)); + s +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + #[test] + fn wired_session_renders_demo_with_expressions() { + let mut s = super::session(); + s.execute("file.openDemoProject", json!({})).unwrap(); + let cid = s.active_comp_id().unwrap(); + let lid = s.active_comp().unwrap().layers[1].id.0; + s.execute("prop.setExpression", json!({"layer": lid, "path": "transform/rotation", "expression": "time * 90"})).unwrap(); + let img = s.render(cid, s.time(), effectcraft_engine::render::RenderOpts { scale: 0.25, ..Default::default() }); + assert!(img.data.iter().any(|p| p[3] > 0.5)); + } +} diff --git a/crates/keyframe/src/lib.rs b/crates/keyframe/src/lib.rs index 62956424..bb737d1c 100644 --- a/crates/keyframe/src/lib.rs +++ b/crates/keyframe/src/lib.rs @@ -334,12 +334,7 @@ pub fn segment_value(keys: &[Keyframe], i: usize, t: Tick, spatial: bool) -> Val let p3 = v3(&b.value); let (_, out_t) = spatial_tangents(keys, i); let (in_t, _) = spatial_tangents(keys, i + 1); - let seg = SpatialSeg::new([ - p0, - [p0[0] + out_t[0], p0[1] + out_t[1], p0[2] + out_t[2]], - [p3[0] + in_t[0], p3[1] + in_t[1], p3[2] + in_t[2]], - p3, - ]); + let seg = SpatialSeg::new([p0, [p0[0] + out_t[0], p0[1] + out_t[1], p0[2] + out_t[2]], [p3[0] + in_t[0], p3[1] + in_t[1], p3[2] + in_t[2]], p3]); let len = seg.length(); let f = if lin_out && lin_in || len <= 1e-12 { x diff --git a/crates/project/src/build.rs b/crates/project/src/build.rs index 629e600d..a6fcdf1f 100644 --- a/crates/project/src/build.rs +++ b/crates/project/src/build.rs @@ -58,8 +58,16 @@ pub fn effects(ids: &mut Ids) -> PropGroup { } /// Mask colours cycle like AE's default mask colours. -pub const MASK_COLORS: [[u8; 3]; 8] = - [[0xb1, 0xb4, 0x4f], [0x4f, 0x8c, 0xc9], [0xc9, 0x4f, 0x8c], [0x4f, 0xc9, 0x7a], [0xc9, 0x8c, 0x4f], [0x8c, 0x4f, 0xc9], [0x4f, 0xc9, 0xc9], [0xc9, 0x4f, 0x4f]]; +pub const MASK_COLORS: [[u8; 3]; 8] = [ + [0xb1, 0xb4, 0x4f], + [0x4f, 0x8c, 0xc9], + [0xc9, 0x4f, 0x8c], + [0x4f, 0xc9, 0x7a], + [0xc9, 0x8c, 0x4f], + [0x8c, 0x4f, 0xc9], + [0x4f, 0xc9, 0xc9], + [0xc9, 0x4f, 0x4f], +]; pub fn mask(ids: &mut Ids, name: &str, path: ShapePath, mode: MaskMode, color: [u8; 3]) -> PropGroup { let mut g = ids.group("mask", name); @@ -78,7 +86,11 @@ pub fn text(ids: &mut Ids, doc: TextDoc) -> PropGroup { .group("moreOptions", "More Options") .with(ids.prop("anchorGrouping", "Anchor Point Grouping", Value::Enum(0)).with_ui(popup(&["Character", "Word", "Line", "All"]))) .with(ids.prop("groupingAlignment", "Grouping Alignment", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Percent)) - .with(ids.prop("fillStroke", "Fill & Stroke", Value::Enum(0)).with_ui(popup(&["Per Character Palette", "All Fills Over All Strokes", "All Strokes Over All Fills"]))) + .with(ids.prop("fillStroke", "Fill & Stroke", Value::Enum(0)).with_ui(popup(&[ + "Per Character Palette", + "All Fills Over All Strokes", + "All Strokes Over All Fills", + ]))) .with(ids.prop("interCharBlend", "Inter-Character Blending", Value::Enum(0)).with_ui(popup(&["Normal", "Multiply", "Screen", "Overlay"]))); ids.group("text", "Text").with(st).with(path_opts).with(more).with(ids.group("animators", "Animators")) } @@ -306,7 +318,8 @@ pub fn shape_simple_op(ids: &mut Ids, kind: &str) -> Option { .with(ids.prop("miter", "Miter Limit", Value::Scalar(4.0))) .with(ids.prop("copies", "Copies", Value::Scalar(1.0))) .with(ids.prop("copyOffset", "Copy Offset", Value::Scalar(0.0))), - "pucker" => indexed(ids.group("pucker", "Pucker & Bloat 1")).with(ids.prop("amount", "Amount", Value::Scalar(0.0)).with_ui(slider(-100.0, 100.0, -100.0, 100.0, 1))), + "pucker" => indexed(ids.group("pucker", "Pucker & Bloat 1")) + .with(ids.prop("amount", "Amount", Value::Scalar(0.0)).with_ui(slider(-100.0, 100.0, -100.0, 100.0, 1))), "twist" => indexed(ids.group("twist", "Twist 1")) .with(ids.prop("angle", "Angle", Value::Scalar(0.0)).with_ui(ParamUi::Angle)) .with(ids.prop("center", "Center", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Point)), @@ -322,8 +335,13 @@ pub fn shape_simple_op(ids: &mut Ids, kind: &str) -> Option { .with(ids.prop("correlation", "Correlation", Value::Scalar(50.0)).with_ui(ParamUi::Percent)) .with(ids.prop("phase", "Temporal Phase", Value::Scalar(0.0)).with_ui(ParamUi::Angle)) .with(ids.prop("seed", "Random Seed", Value::Scalar(0.0))), - "merge" => indexed(ids.group("merge", "Merge Paths 1")) - .with(ids.prop("mode", "Mode", Value::Enum(0)).with_ui(popup(&["Merge", "Add", "Subtract", "Intersect", "Exclude Intersections"]))), + "merge" => indexed(ids.group("merge", "Merge Paths 1")).with(ids.prop("mode", "Mode", Value::Enum(0)).with_ui(popup(&[ + "Merge", + "Add", + "Subtract", + "Intersect", + "Exclude Intersections", + ]))), _ => return None, }; Some(g) @@ -446,7 +464,8 @@ pub fn layer(project: &mut Project, comp: &Comp, name: &str, source: LayerSource g.children.push(ids.prop("poi", "Point of Interest", Value::Vec3([cw / 2.0, ch / 2.0, 0.0])).with_ui(ParamUi::Point3).spatial().into()); } if kind != LightKind::Ambient { - g.children.push(ids.prop("position", "Position", Value::Vec3([cw / 2.0 - 260.0, ch / 2.0 - 260.0, -440.0])).with_ui(ParamUi::Point3).spatial().into()); + g.children + .push(ids.prop("position", "Position", Value::Vec3([cw / 2.0 - 260.0, ch / 2.0 - 260.0, -440.0])).with_ui(ParamUi::Point3).spatial().into()); } root.children.push(g.into()); root.children.push(light_options(&mut ids, kind).into()); diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index bdb11ae0..0575e7b4 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -241,16 +241,24 @@ impl LightKind { #[serde(tag = "type")] pub enum LayerSource { /// Footage item (video, still, sequence, audio). - Footage { item: ItemId }, + Footage { + item: ItemId, + }, /// Nested composition (precomp). - Comp { item: ItemId }, + Comp { + item: ItemId, + }, /// Solid item (solids also back adjustment layers). - Solid { item: ItemId }, + Solid { + item: ItemId, + }, Text, Shape, Null, Camera, - Light { kind: LightKind }, + Light { + kind: LightKind, + }, } impl LayerSource { @@ -415,19 +423,11 @@ impl Layer { /// Layer time for a comp time (stretch-aware). pub fn layer_time(&self, comp_t: Tick) -> Tick { let d = comp_t - self.start_time; - if (self.stretch - 100.0).abs() < 1e-9 { - d - } else { - Tick((d.0 as f64 * 100.0 / self.stretch) as i64) - } + if (self.stretch - 100.0).abs() < 1e-9 { d } else { Tick((d.0 as f64 * 100.0 / self.stretch) as i64) } } /// Comp time for a layer time. pub fn comp_time(&self, layer_t: Tick) -> Tick { - if (self.stretch - 100.0).abs() < 1e-9 { - self.start_time + layer_t - } else { - self.start_time + Tick((layer_t.0 as f64 * self.stretch / 100.0) as i64) - } + if (self.stretch - 100.0).abs() < 1e-9 { self.start_time + layer_t } else { self.start_time + Tick((layer_t.0 as f64 * self.stretch / 100.0) as i64) } } pub fn transform(&self) -> Option<&PropGroup> { self.props.sub("transform") diff --git a/crates/project/src/props.rs b/crates/project/src/props.rs index 96e55961..df7f997d 100644 --- a/crates/project/src/props.rs +++ b/crates/project/src/props.rs @@ -182,7 +182,8 @@ pub enum MaskMode { } impl MaskMode { - pub const ALL: [MaskMode; 7] = [MaskMode::None, MaskMode::Add, MaskMode::Subtract, MaskMode::Intersect, MaskMode::Lighten, MaskMode::Darken, MaskMode::Difference]; + pub const ALL: [MaskMode; 7] = + [MaskMode::None, MaskMode::Add, MaskMode::Subtract, MaskMode::Intersect, MaskMode::Lighten, MaskMode::Darken, MaskMode::Difference]; pub fn label(self) -> &'static str { match self { MaskMode::None => "None", @@ -299,13 +300,9 @@ impl PropGroup { match seg { Seg::Uid(u) => self.children.iter().position(|c| c.uid() == *u), Seg::Index(i) => (*i >= 1 && *i <= self.children.len()).then(|| i - 1), - Seg::Match(m, n) => self - .children - .iter() - .enumerate() - .filter(|(_, c)| c.match_id() == m || c.name().eq_ignore_ascii_case(m)) - .nth(n.saturating_sub(1)) - .map(|(i, _)| i), + Seg::Match(m, n) => { + self.children.iter().enumerate().filter(|(_, c)| c.match_id() == m || c.name().eq_ignore_ascii_case(m)).nth(n.saturating_sub(1)).map(|(i, _)| i) + } } } @@ -492,10 +489,13 @@ impl PropGroup { } } pub fn max_uid(&self) -> Uid { - self.children.iter().map(|c| match c { - Node::Prop(p) => p.uid, - Node::Group(g) => g.max_uid(), - }).fold(self.uid, Uid::max) + self.children + .iter() + .map(|c| match c { + Node::Prop(p) => p.uid, + Node::Group(g) => g.max_uid(), + }) + .fold(self.uid, Uid::max) } } diff --git a/crates/project/src/tests.rs b/crates/project/src/tests.rs index 39c30407..290e7e50 100644 --- a/crates/project/src/tests.rs +++ b/crates/project/src/tests.rs @@ -8,7 +8,12 @@ fn project_with_layer() -> (Project, crate::ItemId) { let mut p = Project::default(); let comp = Comp::new(1920, 1080, FrameRate::FPS_29_97, Tick::from_seconds_f64(10.0)); let cid = p.add_item("Main", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); - let sid = p.add_item("Red Solid", effectcraft_color::Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 1920, height: 1080, pixel_aspect: 1.0 })); + let sid = p.add_item( + "Red Solid", + effectcraft_color::Label::Red, + None, + ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 1920, height: 1080, pixel_aspect: 1.0 }), + ); let layer = build::layer(&mut p, &comp, "Red Solid 1", LayerSource::Solid { item: sid }, (1920, 1080), None); p.comp_mut(cid).unwrap().layers.push(layer); (p, cid) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index fb052528..ed9dd898 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -37,11 +37,7 @@ impl Image { } #[inline] pub fn get(&self, x: i64, y: i64) -> Px { - if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 { - [0.0; 4] - } else { - self.data[y as usize * self.width as usize + x as usize] - } + if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 { [0.0; 4] } else { self.data[y as usize * self.width as usize + x as usize] } } #[inline] pub fn get_clamped(&self, x: i64, y: i64) -> Px { @@ -113,12 +109,7 @@ impl Image { let w = |t: f64| -> [f32; 4] { let t2 = t * t; let t3 = t2 * t; - [ - (-0.5 * t3 + t2 - 0.5 * t) as f32, - (1.5 * t3 - 2.5 * t2 + 1.0) as f32, - (-1.5 * t3 + 2.0 * t2 + 0.5 * t) as f32, - (0.5 * t3 - 0.5 * t2) as f32, - ] + [(-0.5 * t3 + t2 - 0.5 * t) as f32, (1.5 * t3 - 2.5 * t2 + 1.0) as f32, (-1.5 * t3 + 2.0 * t2 + 0.5 * t) as f32, (0.5 * t3 - 0.5 * t2) as f32] }; let wx = w(tx); let wy = w(ty); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 0e2380c9..83acd335 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -16,11 +16,11 @@ use std::sync::Arc; use effectcraft_color::BlendMode; use effectcraft_effects::{Buf, EffectCtx, Params}; use effectcraft_geom::{Mat3, vec2}; -pub use eval::{EvalCtx, ExprHost, source_size}; use effectcraft_project::{Comp, Footage, GroupKind, ItemId, ItemKind, Layer, LayerSource, MatteKind, Node, Project, Quality, Sampling}; pub use effectcraft_raster::Image; use effectcraft_raster::{WarpOpts, composite_warp}; use effectcraft_time::Tick; +pub use eval::{EvalCtx, ExprHost, source_size}; use rayon::prelude::*; /// Supplies decoded footage frames (implemented by the media layer). diff --git a/crates/render/src/masks.rs b/crates/render/src/masks.rs index 5595688c..30eea2b3 100644 --- a/crates/render/src/masks.rs +++ b/crates/render/src/masks.rs @@ -19,7 +19,13 @@ fn coverage(ctx: &EvalCtx, layer: &Layer, g: &effectcraft_project::PropGroup, bu let mut cov = effectcraft_path::fill_coverage(std::slice::from_ref(&path), &m, w, h, FillRule::NonZero); let exp = ctx.f(layer, g, "expansion", 0.0); if exp.abs() > 0.01 { - let ring = effectcraft_path::stroke_coverage(std::slice::from_ref(&path), &StrokeStyle { width: exp.abs() * 2.0, join: effectcraft_path::Join::Round, ..Default::default() }, &m, w, h); + let ring = effectcraft_path::stroke_coverage( + std::slice::from_ref(&path), + &StrokeStyle { width: exp.abs() * 2.0, join: effectcraft_path::Join::Round, ..Default::default() }, + &m, + w, + h, + ); cov.data.par_iter_mut().zip(ring.data.par_iter()).for_each(|(c, r)| { *c = if exp > 0.0 { (*c + r - *c * r).min(1.0) } else { (*c * (1.0 - r)).max(0.0) }; }); diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index c147f71d..09735733 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -29,17 +29,30 @@ pub struct CharXf { impl Default for CharXf { fn default() -> Self { - CharXf { offset: [0.0; 2], anchor: [0.0; 2], scale: [100.0; 2], rotation: 0.0, skew: 0.0, opacity: 100.0, fill: None, fill_k: 0.0, stroke: None, stroke_k: 0.0, stroke_width: 0.0, tracking: 0.0 } + CharXf { + offset: [0.0; 2], + anchor: [0.0; 2], + scale: [100.0; 2], + rotation: 0.0, + skew: 0.0, + opacity: 100.0, + fill: None, + fill_k: 0.0, + stroke: None, + stroke_k: 0.0, + stroke_width: 0.0, + tracking: 0.0, + } } } fn shape_value(shape: u32, f: f64) -> f64 { let f = f.clamp(0.0, 1.0); match shape { - 1 => f, // ramp up - 2 => 1.0 - f, // ramp down - 3 => 1.0 - (2.0 * f - 1.0).abs(), // triangle - 4 => (1.0 - (2.0 * f - 1.0).powi(2)).sqrt(), // round + 1 => f, // ramp up + 2 => 1.0 - f, // ramp down + 3 => 1.0 - (2.0 * f - 1.0).abs(), // triangle + 4 => (1.0 - (2.0 * f - 1.0).powi(2)).sqrt(), // round 5 => { let t = 1.0 - (2.0 * f - 1.0).abs(); t * t * (3.0 - 2.0 * t) diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml new file mode 100644 index 00000000..512b9b14 --- /dev/null +++ b/crates/ui-egui/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "effectcraft-ui-egui" +description = "The EffectCraft egui frontend (swappable): docking panels, composition viewer, timeline, effect controls, control channel" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +effectcraft-time = { workspace = true } +effectcraft-geom = { workspace = true } +effectcraft-color = { workspace = true } +effectcraft-keyframe = { workspace = true } +effectcraft-project = { workspace = true } +effectcraft-path = { workspace = true } +effectcraft-text = { workspace = true } +effectcraft-render = { workspace = true } +effectcraft-engine = { workspace = true } +egui = { workspace = true } +eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } +serde = { workspace = true } +serde_json = { workspace = true } +log = { workspace = true } +rayon = { workspace = true } +kurbo = { workspace = true } + +[dev-dependencies] +egui_kittest = { workspace = true, features = ["eframe", "wgpu"] } +image = { workspace = true } +pollster = "0.4" diff --git a/crates/ui-egui/src/automation.rs b/crates/ui-egui/src/automation.rs new file mode 100644 index 00000000..9b9ae3bb --- /dev/null +++ b/crates/ui-egui/src/automation.rs @@ -0,0 +1,36 @@ +//! Automation registry: every interactive element registers a stable id and its screen rect each +//! frame, so agents can click/drag by id (`ui.click {id:"timeline.track.V1.lock"}`) and +//! `ui.inspect` can report the full on-screen widget tree. + +use egui::Rect; +use serde::Serialize; + +#[derive(Clone, Debug, Serialize)] +pub struct Element { + pub id: String, + pub label: String, + pub rect: [f32; 4], +} + +#[derive(Default)] +pub struct Registry { + pub elements: Vec, + /// Last frame's elements (for lookups from control handlers between frames). + pub previous: Vec, +} + +impl Registry { + pub fn add(&mut self, id: &str, rect: Rect, label: &str) { + self.elements.push(Element { id: id.to_string(), label: label.to_string(), rect: [rect.min.x, rect.min.y, rect.width(), rect.height()] }); + } + pub fn begin_frame(&mut self) { + self.previous = std::mem::take(&mut self.elements); + } + pub fn find(&self, id: &str) -> Option<&Element> { + self.previous.iter().chain(self.elements.iter()).find(|e| e.id == id) + } + /// Elements whose id starts with a prefix. + pub fn query(&self, prefix: &str) -> Vec<&Element> { + self.previous.iter().filter(|e| e.id.starts_with(prefix)).collect() + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs new file mode 100644 index 00000000..eaf6ba93 --- /dev/null +++ b/crates/ui-egui/src/control.rs @@ -0,0 +1,419 @@ +//! Programmatic control of the running app (agents, tests, MCP bridge). +//! +//! Transport-agnostic: a transport thread (TCP in the desktop app) sends [`ControlRequest`]s; the +//! UI thread handles them between frames and replies with `{"ok":…, "result"|"error":…}`. +//! +//! Methods: +//! - `engine.execute {command, params}` / `ui.menu.invoke {id, params}`: run any engine or UI command +//! - `engine.commands`: list engine commands; `ui.menu.list`: menu tree with enablement +//! - `ui.inspect`: UI state + summary; `ui.elements {prefix?}`: registered widgets (id, label, rect) +//! - `ui.set {tool?, workspace?, theme?, focused?, viewer?: {zoom, res, pan, grid, …}, timeline?: {pps, start, graphEditor, showModes}}` +//! - `ui.panel.show {panel}` / `ui.panel.close {panel}` +//! - `ui.click {id | x,y, button?, count?, modifiers?}` / `ui.move {x,y}` / `ui.scroll {x,y,dx,dy}` +//! - `ui.drag {from:{id|x,y}, to:{id|x,y}, steps?, modifiers?}`: synthetic press-move-release +//! - `ui.key {key, command?, shift?, alt?, ctrl?}` / `ui.type {text}` +//! - `ui.viewer.locate {x, y}`: screen point of a comp pixel; `ui.viewer.hit {x, y}`: comp pixel at a screen point +//! - `ui.timeline.locate {layer, time?}`: screen point of a layer bar (at a comp time) +//! - `ui.playback {action: play|stop|toggle}` +//! - `ui.screenshot {path?, panel?, id?}`: PNG of the window (or one panel / element) +//! - `ui.resize {width, height}` / `ui.focus` / `app.quit` + +use std::sync::mpsc::Sender; + +use serde_json::{Value, json}; + +use crate::EffectcraftApp; +use crate::dock::PanelKind; +use crate::state::{Resolution, Tool}; + +/// Prefix marking errors that may resolve after another frame. +pub const RETRY: &str = "\u{1}"; + +pub struct ControlRequest { + pub method: String, + pub params: Value, + pub reply: Sender, +} + +impl ControlRequest { + pub fn new(method: impl Into, params: Value) -> (Self, std::sync::mpsc::Receiver) { + let (tx, rx) = std::sync::mpsc::channel(); + (Self { method: method.into(), params, reply: tx }, rx) + } +} + +pub enum Outcome { + Done(Value), + /// Try again on a later frame (e.g. the element is not on screen yet). + Retry(String), + /// Reply once queued synthetic input has been processed. + AfterInput, + Screenshot { + path: Option, + crop: Option<[f32; 4]>, + }, +} + +fn ok(v: Value) -> Outcome { + Outcome::Done(json!({"ok": true, "result": v})) +} +fn err(e: impl std::fmt::Display) -> Outcome { + Outcome::Done(json!({"ok": false, "error": e.to_string()})) +} + +fn modifiers(p: &Value) -> egui::Modifiers { + let m = p.get("modifiers").unwrap_or(p); + let b = |k: &str| m.get(k).and_then(Value::as_bool).unwrap_or(false); + egui::Modifiers { alt: b("alt"), ctrl: b("ctrl"), shift: b("shift"), mac_cmd: cfg!(target_os = "macos") && b("command"), command: b("command") } +} + +/// Resolve a point from `{id}` (element centre) or `{x, y}`. +fn point(app: &EffectcraftApp, p: &Value) -> Result { + if let Some(id) = p.get("id").and_then(Value::as_str) { + let e = app.auto.find(id).ok_or_else(|| format!("{RETRY}no element `{id}` (see ui.elements)"))?; + let fx = p.get("fx").and_then(Value::as_f64).unwrap_or(0.5) as f32; + let fy = p.get("fy").and_then(Value::as_f64).unwrap_or(0.5) as f32; + return Ok(egui::pos2(e.rect[0] + e.rect[2] * fx, e.rect[1] + e.rect[3] * fy)); + } + let x = p.get("x").and_then(Value::as_f64).ok_or("need `id` or `x`,`y`")?; + let y = p.get("y").and_then(Value::as_f64).ok_or("need `y`")?; + Ok(egui::pos2(x as f32, y as f32)) +} + +pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + let p = &req.params; + let s = |k: &str| p.get(k).and_then(Value::as_str); + match req.method.as_str() { + "engine.execute" | "ui.menu.invoke" => { + let Some(id) = s("command").or(s("id")) else { return err("missing `command`") }; + let params = p.get("params").cloned().unwrap_or(json!({})); + match crate::menus::invoke(app, ctx, id, params) { + Ok(v) => ok(v), + Err(e) => err(e), + } + } + "engine.commands" => match app.session.execute("command.list", json!({})) { + Ok(v) => ok(v), + Err(e) => err(e), + }, + "ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_items(app)).unwrap_or_default()), + "ui.inspect" => ok(inspect(app, ctx)), + "ui.elements" => { + let prefix = s("prefix").unwrap_or(""); + ok(serde_json::to_value(app.auto.query(prefix)).unwrap_or_default()) + } + "ui.set" => { + if let Some(t) = s("tool") { + match Tool::from_name(t) { + Some(t) => app.ui.tool = t, + None => return err(format!("unknown tool `{t}`")), + } + } + if let Some(w) = s("workspace") { + match crate::dock::WORKSPACES.iter().find(|x| x.eq_ignore_ascii_case(w)) { + Some(w) => app.set_workspace(w), + None => return err(format!("unknown workspace `{w}`")), + } + } + if let Some(th) = s("theme") { + match crate::theme::ThemeKind::from_name(th) { + Some(k) => app.set_theme(ctx, k), + None => return err("unknown theme (dark, darker, light)"), + } + } + if let Some(f) = s("focused").and_then(PanelKind::from_name) { + app.ui.focused = f; + } + if let Some(v) = p.get("viewer") { + if let Some(z) = v.get("zoom") { + app.ui.viewer.zoom = z.as_f64().map(|z| z as f32); + } + if let Some(r) = v.get("res").and_then(Value::as_str) { + app.ui.viewer.res = Resolution::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r)).unwrap_or(app.ui.viewer.res); + } + if let Some(Value::Array(a)) = v.get("pan") { + app.ui.viewer.pan = [a.first().and_then(Value::as_f64).unwrap_or(0.0) as f32, a.get(1).and_then(Value::as_f64).unwrap_or(0.0) as f32]; + } + for (k, slot) in [ + ("grid", &mut app.ui.viewer.grid), + ("rulers", &mut app.ui.viewer.rulers), + ("safeMargins", &mut app.ui.viewer.safe_margins), + ("transparencyGrid", &mut app.ui.viewer.transparency_grid), + ] { + if let Some(b) = v.get(k).and_then(Value::as_bool) { + *slot = b; + } + } + } + if let Some(tl) = p.get("timeline") { + if let Some(v) = tl.get("pps") { + app.ui.timeline.pps = v.as_f64(); + } + if let Some(v) = tl.get("start").and_then(Value::as_f64) { + app.ui.timeline.start = v; + } + if let Some(v) = tl.get("graphEditor").and_then(Value::as_bool) { + app.ui.timeline.graph_editor = v; + } + if let Some(v) = tl.get("showModes").and_then(Value::as_bool) { + app.ui.timeline.show_modes = v; + } + if let Some(Value::Array(a)) = tl.get("openLayers") { + app.ui.timeline.open_layers = a.iter().filter_map(Value::as_u64).collect(); + } + if let Some(Value::Array(a)) = tl.get("openGroups") { + app.ui.timeline.open_groups = a.iter().filter_map(Value::as_u64).collect(); + } + } + if let Some(b) = p.get("menuBar").and_then(Value::as_bool) { + app.ui.show_menu_bar = b; + } + if let Some(b) = p.get("home").and_then(Value::as_bool) { + app.ui.start_screen = b; + } + ok(Value::Null) + } + "ui.panel.show" | "ui.panel.close" => { + let Some(panel) = s("panel").and_then(PanelKind::from_name) else { return err("unknown `panel`") }; + if req.method == "ui.panel.show" { + app.show_panel(panel); + } else { + app.ui.dock.close(panel); + } + ok(Value::Null) + } + "ui.click" | "ui.move" => { + let pos = match point(app, p) { + Ok(p) => p, + Err(e) if e.starts_with(RETRY) => return Outcome::Retry(e.trim_start_matches(RETRY).to_string()), + Err(e) => return err(e), + }; + let m = modifiers(p); + app.synthetic.push(egui::Event::PointerMoved(pos)); + if req.method == "ui.click" { + let button = match s("button") { + Some("right") => egui::PointerButton::Secondary, + Some("middle") => egui::PointerButton::Middle, + _ => egui::PointerButton::Primary, + }; + let count = p.get("count").and_then(Value::as_u64).unwrap_or(1); + for _ in 0..count { + app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: true, modifiers: m }); + app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: m }); + } + } + Outcome::AfterInput + } + "ui.drag" => { + let (Some(from), Some(to)) = (p.get("from"), p.get("to")) else { return err("need `from` and `to`") }; + let (a, b) = match (point(app, from), point(app, to)) { + (Ok(a), Ok(b)) => (a, b), + (Err(e), _) | (_, Err(e)) if e.starts_with(RETRY) => return Outcome::Retry(e.trim_start_matches(RETRY).to_string()), + (Err(e), _) | (_, Err(e)) => return err(e), + }; + let steps = p.get("steps").and_then(Value::as_u64).unwrap_or(12).max(2); + let m = modifiers(p); + app.synthetic.push(egui::Event::PointerMoved(a)); + app.synthetic.push(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: m }); + for i in 1..=steps { + let f = i as f32 / steps as f32; + app.synthetic.push(egui::Event::PointerMoved(a + (b - a) * f)); + } + app.synthetic.push(egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: m }); + Outcome::AfterInput + } + "ui.scroll" => { + let pos = match point(app, p) { + Ok(p) => p, + Err(e) => return err(e), + }; + let dx = p.get("dx").and_then(Value::as_f64).unwrap_or(0.0) as f32; + let dy = p.get("dy").and_then(Value::as_f64).unwrap_or(0.0) as f32; + app.synthetic.push(egui::Event::PointerMoved(pos)); + app.synthetic.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(dx, dy), + modifiers: modifiers(p), + phase: egui::TouchPhase::Move, + }); + app.synthetic.push(egui::Event::PointerButton { + pos: egui::pos2(-100.0, -100.0), + button: egui::PointerButton::Extra1, + pressed: false, + modifiers: Default::default(), + }); + Outcome::AfterInput + } + "ui.key" => { + let Some(name) = s("key") else { return err("missing `key`") }; + let Some((mut m, key)) = crate::menus::parse_shortcut(name) else { return err(format!("unknown key `{name}`")) }; + let extra = modifiers(p); + m |= extra; + app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m }); + app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: m }); + Outcome::AfterInput + } + "ui.type" => { + let Some(text) = s("text") else { return err("missing `text`") }; + app.synthetic.push(egui::Event::Text(text.to_string())); + app.synthetic.push(egui::Event::Key { key: egui::Key::F35, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }); + Outcome::AfterInput + } + "ui.viewer.locate" => { + let (Some(x), Some(y)) = (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) else { + return err("need `x`, `y` (comp pixels)"); + }; + match crate::panels::viewer::comp_to_screen(ctx, [x as f32, y as f32]) { + Some(pt) => ok(json!({"x": pt.x, "y": pt.y})), + None => Outcome::Retry("the composition viewer is not visible".into()), + } + } + "ui.viewer.hit" => { + let pos = match point(app, p) { + Ok(p) => p, + Err(e) => return err(e), + }; + match crate::panels::viewer::screen_to_comp(ctx, pos) { + Some(c) => ok(json!({"x": c[0], "y": c[1]})), + None => err("the composition viewer is not visible"), + } + } + "ui.timeline.locate" => { + let Some(l) = p.get("layer").and_then(Value::as_u64) else { return err("need `layer` (id)") }; + match crate::panels::timeline::locate(app, l, p.get("time").and_then(Value::as_f64)) { + Some((x, y)) => ok(json!({"x": x, "y": y})), + None => Outcome::Retry("layer not visible in the timeline".into()), + } + } + "ui.playback" => { + let now = ctx.input(|i| i.time); + match s("action").unwrap_or("toggle") { + "play" => app.play(now), + "stop" => app.stop(), + _ => app.toggle_play(now), + } + ok(json!({"playing": app.playback.playing, "time": app.session.time().seconds()})) + } + "ui.screenshot" => { + let crop = s("panel").and_then(PanelKind::from_name).and_then(|pk| app.auto.find(&format!("panel.{}", pk.id())).map(|e| e.rect)); + let crop = crop.or_else(|| s("id").and_then(|id| app.auto.find(id).map(|e| e.rect))); + // Bring the window on screen so a frame is presented, without taking keyboard focus. + app.raise_for_control(ctx); + Outcome::Screenshot { path: s("path").map(str::to_string), crop } + } + "ui.resize" => { + let w = p.get("width").and_then(Value::as_f64).unwrap_or(1600.0) as f32; + let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0) as f32; + ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w, h))); + ok(Value::Null) + } + "ui.focus" => { + // Explicit request: activate the app and take keyboard focus. + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + ok(Value::Null) + } + "app.quit" => { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + ok(Value::Null) + } + m => err(format!("unknown method `{m}`")), + } +} + +pub fn inspect(app: &EffectcraftApp, ctx: &egui::Context) -> Value { + let size = ctx.content_rect().size(); + json!({ + "window": [size.x, size.y], + "pixelsPerPoint": ctx.pixels_per_point(), + "fps": app.fps, + "ui": app.ui, + "playing": app.playback.playing, + "time": app.session.time().seconds(), + "activeComp": app.session.state.active_comp.map(|i| i.0), + "selectedLayers": app.session.state.selected_layers.iter().map(|c| c.0).collect::>(), + "selectedKeys": app.session.state.selected_keys.len(), + "elements": app.auto.previous.len(), + "dialog": app.dialog.map(|d| format!("{d:?}")), + "renderMs": app.frames.last_ms.lock().map(|v| *v).unwrap_or(0.0), + }) +} + +/// Save a screenshot (optionally cropped to a rect in points) as PNG; returns the reply JSON. +pub fn save_screenshot(ctx: &egui::Context, image: &egui::ColorImage, path: Option<&str>, crop: Option<[f32; 4]>) -> Value { + let ppp = ctx.pixels_per_point(); + let [w, h] = image.size; + let (x0, y0, cw, ch) = match crop { + Some([x, y, cw, ch]) => { + let x0 = ((x * ppp) as usize).min(w); + let y0 = ((y * ppp) as usize).min(h); + (x0, y0, ((cw * ppp) as usize).min(w - x0), ((ch * ppp) as usize).min(h - y0)) + } + None => (0, 0, w, h), + }; + let mut rgba = Vec::with_capacity(cw * ch * 4); + for y in y0..y0 + ch { + for x in x0..x0 + cw { + let c = image.pixels[y * w + x]; + rgba.extend_from_slice(&[c.r(), c.g(), c.b(), 255]); + } + } + let path = path.map(str::to_string).unwrap_or_else(|| std::env::temp_dir().join("effectcraft-screenshot.png").to_string_lossy().to_string()); + match encode_png(&rgba, cw as u32, ch as u32) { + Ok(png) => match std::fs::write(&path, png) { + Ok(()) => json!({"ok": true, "result": {"path": path, "width": cw, "height": ch}}), + Err(e) => json!({"ok": false, "error": e.to_string()}), + }, + Err(e) => json!({"ok": false, "error": e}), + } +} + +/// Minimal PNG encoder (stored deflate blocks, no compression dependency). +pub fn encode_png(rgba: &[u8], w: u32, h: u32) -> Result, String> { + fn chunk(out: &mut Vec, ty: &[u8], data: &[u8]) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + let mut c = Vec::with_capacity(4 + data.len()); + c.extend_from_slice(ty); + c.extend_from_slice(data); + out.extend_from_slice(&c); + out.extend_from_slice(&crc(&c).to_be_bytes()); + } + fn crc(d: &[u8]) -> u32 { + let mut c = 0xFFFF_FFFFu32; + for &b in d { + c ^= b as u32; + for _ in 0..8 { + c = if c & 1 != 0 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 }; + } + } + !c + } + let mut raw = Vec::with_capacity((w as usize * 4 + 1) * h as usize); + for y in 0..h as usize { + raw.push(0); + raw.extend_from_slice(&rgba[y * w as usize * 4..(y + 1) * w as usize * 4]); + } + // zlib stream with stored blocks + let mut z = vec![0x78, 0x01]; + for (i, block) in raw.chunks(65535).enumerate() { + let last = (i + 1) * 65535 >= raw.len(); + z.push(last as u8); + z.extend_from_slice(&(block.len() as u16).to_le_bytes()); + z.extend_from_slice(&(!(block.len() as u16)).to_le_bytes()); + z.extend_from_slice(block); + } + let (mut a, mut b) = (1u32, 0u32); + for &x in &raw { + a = (a + x as u32) % 65521; + b = (b + a) % 65521; + } + z.extend_from_slice(&((b << 16) | a).to_be_bytes()); + let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&w.to_be_bytes()); + ihdr.extend_from_slice(&h.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); + chunk(&mut out, b"IHDR", &ihdr); + chunk(&mut out, b"IDAT", &z); + chunk(&mut out, b"IEND", &[]); + Ok(out) +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs new file mode 100644 index 00000000..7a523c89 --- /dev/null +++ b/crates/ui-egui/src/dock.rs @@ -0,0 +1,521 @@ +//! Docking: a tree of splits and tab groups. Panels are rounded frames separated by +//! thin gutters; each group has a tab strip (active tab bright, with a panel menu "≡"); the focused +//! panel gets a blue outline. Gutters drag to resize; workspaces are serialized trees. + +use egui::{Align2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use serde::{Deserialize, Serialize}; + +use crate::icons::{self, Icon}; +use crate::theme::Tokens; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum PanelKind { + Project, + EffectControls, + Composition, + Layer, + Timeline, + Info, + Audio, + Preview, + EffectsPresets, + Properties, + Character, + Paragraph, + Align, + Tracker, + Wiggler, + Smoother, + MotionSketch, + Paint, + Brushes, + RenderQueue, + Flowchart, + History, + Markers, +} + +impl PanelKind { + pub const ALL: [PanelKind; 23] = [ + PanelKind::Project, + PanelKind::EffectControls, + PanelKind::Composition, + PanelKind::Layer, + PanelKind::Timeline, + PanelKind::Info, + PanelKind::Audio, + PanelKind::Preview, + PanelKind::EffectsPresets, + PanelKind::Properties, + PanelKind::Character, + PanelKind::Paragraph, + PanelKind::Align, + PanelKind::Tracker, + PanelKind::Wiggler, + PanelKind::Smoother, + PanelKind::MotionSketch, + PanelKind::Paint, + PanelKind::Brushes, + PanelKind::RenderQueue, + PanelKind::Flowchart, + PanelKind::History, + PanelKind::Markers, + ]; + pub fn title(self) -> &'static str { + match self { + PanelKind::Project => "Project", + PanelKind::EffectControls => "Effect Controls", + PanelKind::Composition => "Composition", + PanelKind::Layer => "Layer", + PanelKind::Timeline => "Timeline", + PanelKind::Info => "Info", + PanelKind::Audio => "Audio", + PanelKind::Preview => "Preview", + PanelKind::EffectsPresets => "Effects & Presets", + PanelKind::Properties => "Properties", + PanelKind::Character => "Character", + PanelKind::Paragraph => "Paragraph", + PanelKind::Align => "Align", + PanelKind::Tracker => "Tracker", + PanelKind::Wiggler => "Wiggler", + PanelKind::Smoother => "Smoother", + PanelKind::MotionSketch => "Motion Sketch", + PanelKind::Paint => "Paint", + PanelKind::Brushes => "Brushes", + PanelKind::RenderQueue => "Render Queue", + PanelKind::Flowchart => "Flowchart", + PanelKind::History => "History", + PanelKind::Markers => "Markers", + } + } + pub fn id(self) -> String { + format!("{self:?}") + } + pub fn from_name(s: &str) -> Option { + let n = s.to_ascii_lowercase().replace([' ', '_', '-', '&'], ""); + Self::ALL.iter().copied().find(|p| format!("{p:?}").to_ascii_lowercase() == n || p.title().to_ascii_lowercase().replace([' ', '&'], "") == n) + } + /// Window-menu shortcut. + pub fn window_shortcut(self) -> Option<&'static str> { + match self { + PanelKind::Project => Some("Cmd+0"), + PanelKind::Info => Some("Cmd+2"), + PanelKind::Preview => Some("Cmd+3"), + PanelKind::Audio => Some("Cmd+4"), + PanelKind::EffectsPresets => Some("Cmd+5"), + PanelKind::Character => Some("Cmd+6"), + PanelKind::Paragraph => Some("Cmd+7"), + PanelKind::Paint => Some("Cmd+8"), + PanelKind::Brushes => Some("Cmd+9"), + PanelKind::RenderQueue => Some("Cmd+Alt+0"), + PanelKind::EffectControls => Some("F3"), + _ => None, + } + } + /// Chrome-less panels (none in the AE layout; kept for parity with the docking code). + pub fn compact(self) -> bool { + false + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub enum SplitSize { + Ratio(f32), + /// First child has a fixed size in points. + FixedA(f32), + /// Second child has a fixed size in points. + FixedB(f32), +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum DockNode { + /// `vertical`: children stacked top/bottom; else side by side. + Split { + vertical: bool, + size: SplitSize, + a: Box, + b: Box, + }, + Tabs { + panels: Vec, + active: usize, + }, +} + +fn tabs(p: &[PanelKind], active: usize) -> DockNode { + DockNode::Tabs { panels: p.to_vec(), active } +} +fn hsplit(size: SplitSize, a: DockNode, b: DockNode) -> DockNode { + DockNode::Split { vertical: false, size, a: Box::new(a), b: Box::new(b) } +} +fn vsplit(size: SplitSize, a: DockNode, b: DockNode) -> DockNode { + DockNode::Split { vertical: true, size, a: Box::new(a), b: Box::new(b) } +} + +pub const WORKSPACES: [&str; 10] = ["Default", "Standard", "Small Screen", "Animation", "Effects", "Motion Tracking", "Paint", "Text", "Minimal", "All Panels"]; + +/// The default layout of a named workspace. +pub fn workspace(name: &str) -> DockNode { + use PanelKind::*; + use SplitSize::*; + let right = |p: &[PanelKind], q: &[PanelKind]| vsplit(Ratio(0.45), tabs(p, 0), tabs(q, 0)); + match name { + "Animation" => vsplit( + Ratio(0.55), + hsplit( + FixedA(300.0), + tabs(&[Project, EffectControls], 1), + hsplit(FixedB(300.0), tabs(&[Composition, Layer], 0), right(&[Info, Preview, Audio], &[EffectsPresets, Smoother, Wiggler, MotionSketch])), + ), + tabs(&[Timeline, RenderQueue], 0), + ), + "Effects" => vsplit( + Ratio(0.58), + hsplit( + FixedA(340.0), + tabs(&[EffectControls, Project], 0), + hsplit(FixedB(300.0), tabs(&[Composition, Layer], 0), right(&[Info, Preview], &[EffectsPresets])), + ), + tabs(&[Timeline, RenderQueue], 0), + ), + "Motion Tracking" => vsplit( + Ratio(0.6), + hsplit( + FixedA(300.0), + tabs(&[Project, EffectControls], 0), + hsplit(FixedB(300.0), tabs(&[Layer, Composition], 0), right(&[Info, Preview], &[Tracker])), + ), + tabs(&[Timeline], 0), + ), + "Paint" => vsplit( + Ratio(0.6), + hsplit( + FixedA(300.0), + tabs(&[Project, EffectControls], 0), + hsplit(FixedB(300.0), tabs(&[Layer, Composition], 0), right(&[Paint, Info], &[Brushes, Preview])), + ), + tabs(&[Timeline], 0), + ), + "Text" => vsplit( + Ratio(0.58), + hsplit( + FixedA(300.0), + tabs(&[Project, EffectControls], 0), + hsplit(FixedB(300.0), tabs(&[Composition], 0), right(&[Character, Paragraph], &[Align, Preview, EffectsPresets])), + ), + tabs(&[Timeline], 0), + ), + "Minimal" => vsplit(Ratio(0.6), tabs(&[Composition], 0), tabs(&[Timeline], 0)), + "Small Screen" => vsplit( + Ratio(0.55), + hsplit( + FixedA(240.0), + tabs(&[Project, EffectControls], 0), + hsplit(FixedB(240.0), tabs(&[Composition], 0), tabs(&[Info, Preview, EffectsPresets], 1)), + ), + tabs(&[Timeline], 0), + ), + "All Panels" => vsplit( + Ratio(0.55), + hsplit( + FixedA(300.0), + tabs(&[Project, EffectControls, Flowchart, History], 0), + hsplit( + FixedB(300.0), + tabs(&[Composition, Layer], 0), + right( + &[Info, Preview, Audio, Align, Character, Paragraph], + &[EffectsPresets, Properties, Tracker, Wiggler, Smoother, MotionSketch, Paint, Brushes, Markers], + ), + ), + ), + tabs(&[Timeline, RenderQueue], 0), + ), + "Standard" => vsplit( + Ratio(0.56), + hsplit( + FixedA(300.0), + tabs(&[Project, EffectControls], 0), + hsplit(FixedB(290.0), tabs(&[Composition, Layer], 0), right(&[Info, Audio], &[Preview, EffectsPresets])), + ), + tabs(&[Timeline, RenderQueue], 0), + ), + // Default: Project/Effect Controls | Composition | Info, Audio, Preview, Effects & Presets… + _ => vsplit( + Ratio(0.56), + hsplit( + FixedA(300.0), + tabs(&[Project, EffectControls], 0), + hsplit( + FixedB(290.0), + tabs(&[Composition, Layer], 0), + vsplit(Ratio(0.42), tabs(&[Info, Audio, Preview], 2), tabs(&[EffectsPresets, Properties, Character, Paragraph, Align], 0)), + ), + ), + tabs(&[Timeline, RenderQueue], 0), + ), + } +} + +impl DockNode { + /// Every panel in the tree. + pub fn panels(&self, out: &mut Vec) { + match self { + DockNode::Split { a, b, .. } => { + a.panels(out); + b.panels(out); + } + DockNode::Tabs { panels, .. } => out.extend(panels.iter().copied()), + } + } + pub fn contains(&self, p: PanelKind) -> bool { + let mut v = Vec::new(); + self.panels(&mut v); + v.contains(&p) + } + /// Make `p` the active tab of its group. Returns false if not present. + pub fn activate(&mut self, p: PanelKind) -> bool { + match self { + DockNode::Split { a, b, .. } => a.activate(p) || b.activate(p), + DockNode::Tabs { panels, active } => { + if let Some(i) = panels.iter().position(|x| *x == p) { + *active = i; + true + } else { + false + } + } + } + } + pub fn is_visible(&self, p: PanelKind) -> bool { + match self { + DockNode::Split { a, b, .. } => a.is_visible(p) || b.is_visible(p), + DockNode::Tabs { panels, active } => panels.get(*active) == Some(&p), + } + } + /// Close a panel (remove its tab; empty groups collapse their split). + pub fn close(&mut self, p: PanelKind) { + if let DockNode::Split { a, b, .. } = self { + a.close(p); + b.close(p); + let empty = |n: &DockNode| matches!(n, DockNode::Tabs { panels, .. } if panels.is_empty()); + if empty(a) { + *self = (**b).clone(); + } else if empty(b) { + *self = (**a).clone(); + } + } else if let DockNode::Tabs { panels, active } = self { + panels.retain(|x| *x != p); + *active = (*active).min(panels.len().saturating_sub(1)); + } + } + /// Add a panel as a tab next to `near` (or into the first group). + pub fn open_near(&mut self, p: PanelKind, near: PanelKind) { + if self.contains(p) { + self.activate(p); + return; + } + fn add(n: &mut DockNode, p: PanelKind, near: PanelKind) -> bool { + match n { + DockNode::Split { a, b, .. } => add(a, p, near) || add(b, p, near), + DockNode::Tabs { panels, active } => { + if panels.contains(&near) { + panels.push(p); + *active = panels.len() - 1; + true + } else { + false + } + } + } + } + if !add(self, p, near) && !add(self, p, PanelKind::EffectsPresets) { + add(self, p, PanelKind::Project); + } + } +} + +/// One laid-out tab group. +pub struct Group { + pub path: String, + pub rect: Rect, + pub content: Rect, + pub panels: Vec, + pub active: usize, +} + +/// Actions produced by interacting with the dock chrome. +#[derive(Debug, Clone, PartialEq)] +pub enum DockAction { + Activate(PanelKind), + Focus(PanelKind), + Close(PanelKind), + PanelMenu(PanelKind, egui::Pos2), +} + +/// Lay out the tree into group rects (with `gap` gutters) and handle gutter dragging. +pub fn layout(ui: &mut egui::Ui, node: &mut DockNode, rect: Rect, t: &Tokens, path: &str, out: &mut Vec, reg: &mut crate::automation::Registry) { + match node { + DockNode::Tabs { panels, active } => { + let tab_h = if panels.len() == 1 && panels[0].compact() { 8.0 } else { t.tab_h }; + let content = Rect::from_min_max(pos2(rect.min.x, rect.min.y + tab_h), rect.max); + out.push(Group { path: path.to_string(), rect, content, panels: panels.clone(), active: *active }); + } + DockNode::Split { vertical, size, a, b } => { + let g = t.gap; + let total = if *vertical { rect.height() } else { rect.width() }; + let avail = (total - g).max(0.0); + let first = match *size { + SplitSize::Ratio(r) => avail * r, + SplitSize::FixedA(px) => px.min(avail - 20.0), + SplitSize::FixedB(px) => avail - px.min(avail - 20.0), + } + .clamp(20.0_f32.min(avail), (avail - 20.0).max(0.0)); + let (ra, gutter, rb) = if *vertical { + ( + Rect::from_min_max(rect.min, pos2(rect.max.x, rect.min.y + first)), + Rect::from_min_max(pos2(rect.min.x, rect.min.y + first), pos2(rect.max.x, rect.min.y + first + g)), + Rect::from_min_max(pos2(rect.min.x, rect.min.y + first + g), rect.max), + ) + } else { + ( + Rect::from_min_max(rect.min, pos2(rect.min.x + first, rect.max.y)), + Rect::from_min_max(pos2(rect.min.x + first, rect.min.y), pos2(rect.min.x + first + g, rect.max.y)), + Rect::from_min_max(pos2(rect.min.x + first + g, rect.min.y), rect.max), + ) + }; + // gutter drag (a slightly larger hit area than the visible gap) + let hit = gutter.expand2(if *vertical { vec2(0.0, 3.0) } else { vec2(3.0, 0.0) }); + let id = egui::Id::new(("dock-gutter", path.to_string())); + let resp = ui.interact(hit, id, Sense::drag()); + reg.add(&format!("dock.gutter.{path}"), hit, "gutter"); + if resp.hovered() || resp.dragged() { + ui.ctx().set_cursor_icon(if *vertical { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }); + } + if resp.dragged() { + let d = if *vertical { resp.drag_delta().y } else { resp.drag_delta().x }; + let nf = (first + d).clamp(40.0, (avail - 40.0).max(40.0)); + *size = match *size { + SplitSize::Ratio(_) => SplitSize::Ratio(nf / avail.max(1.0)), + SplitSize::FixedA(_) => SplitSize::FixedA(nf), + SplitSize::FixedB(_) => SplitSize::FixedB(avail - nf), + }; + } + if resp.dragged() || resp.hovered() { + ui.painter().rect_filled(gutter, 0.0, t.focus.gamma_multiply(if resp.dragged() { 0.9 } else { 0.4 })); + } + layout(ui, a, ra, t, &format!("{path}a"), out, reg); + layout(ui, b, rb, t, &format!("{path}b"), out, reg); + } + } +} + +/// Draw a group's frame + tab strip. Returns actions (tab clicks, panel menu, focus). +pub fn draw_group_chrome(ui: &mut egui::Ui, g: &Group, focused: PanelKind, t: &Tokens, reg: &mut crate::automation::Registry) -> Vec { + let mut actions = Vec::new(); + let painter = ui.painter().clone(); + painter.rect_filled(g.rect, t.radius, t.panel_bg); + let active_panel = g.panels.get(g.active).copied(); + let compact = g.panels.len() == 1 && g.panels[0].compact(); + if compact { + // grip dots + let c = pos2(g.rect.center().x, g.rect.min.y + 4.0); + for dx in [-4.0, 0.0, 4.0] { + painter.circle_filled(c + vec2(dx, 0.0), 1.0, t.text_faint); + } + } else { + let strip = Rect::from_min_size(g.rect.min, vec2(g.rect.width(), t.tab_h)); + let mut x = strip.min.x + 12.0; + let text_y = strip.min.y + 16.0; + for (i, p) in g.panels.iter().enumerate() { + let is_active = i == g.active; + let galley = painter.layout_no_wrap(p.title().to_string(), Tokens::ui(12.0), if is_active { t.tab_text_active } else { t.tab_text }); + let menu_w = if is_active { 20.0 } else { 0.0 }; + let w = galley.size().x + 16.0 + menu_w; + if x + w > strip.max.x - 20.0 && i > g.active { + let r = Rect::from_min_size(pos2(strip.max.x - 22.0, strip.min.y + 6.0), vec2(18.0, 20.0)); + let resp = ui.interact(r, egui::Id::new(("tab-overflow", g.path.clone())), Sense::click()); + icons::paint(&painter, r.shrink(4.0).translate(vec2(-2.0, 0.0)), Icon::ChevronRight, t.tab_text); + icons::paint(&painter, r.shrink(4.0).translate(vec2(2.0, 0.0)), Icon::ChevronRight, t.tab_text); + if resp.clicked() { + let next = g.panels[(g.active + 1) % g.panels.len()]; + actions.push(DockAction::Activate(next)); + } + break; + } + let tab = Rect::from_min_size(pos2(x, strip.min.y), vec2(w, t.tab_h)); + let resp = ui.interact(tab, egui::Id::new(("tab", g.path.clone(), i)), Sense::click()); + reg.add(&format!("panel.tab.{}", p.id()), tab, p.title()); + let label_x = tab.min.x + 8.0; + let label_w = galley.size().x; + let col = if is_active || resp.hovered() { t.tab_text_active } else { t.tab_text }; + painter.galley_with_override_text_color(pos2(label_x, text_y - galley.size().y / 2.0), galley, col); + if is_active { + let mr = Rect::from_center_size(pos2(label_x + label_w + 12.0, text_y), vec2(12.0, 10.0)); + let mresp = ui.interact(mr.expand(3.0), egui::Id::new(("tab-menu", g.path.clone())), Sense::click()); + reg.add(&format!("panel.menu.{}", p.id()), mr, "panel menu"); + let mc = if mresp.hovered() { t.tab_text_active } else { t.tab_text }; + for dy in [-3.5, 0.0, 3.5] { + painter.line_segment([pos2(mr.min.x, mr.center().y + dy), pos2(mr.max.x, mr.center().y + dy)], Stroke::new(1.5, mc)); + } + let uy = strip.min.y + 23.0; + painter.line_segment([pos2(label_x, uy), pos2(mr.max.x, uy)], Stroke::new(1.0, t.tab_text_active)); + if mresp.clicked() { + actions.push(DockAction::PanelMenu(*p, mr.left_bottom())); + } + } + if resp.clicked() { + actions.push(DockAction::Activate(*p)); + actions.push(DockAction::Focus(*p)); + } + if resp.middle_clicked() { + actions.push(DockAction::Close(*p)); + } + x += w + 8.0; + } + } + // focus outline + if active_panel == Some(focused) { + painter.rect_stroke(g.rect, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside); + } + // clicking anywhere in the panel focuses it + if let Some(p) = active_panel + && ui.rect_contains_pointer(g.rect) + && ui.input(|i| i.pointer.any_pressed()) + { + actions.push(DockAction::Focus(p)); + } + actions +} + +/// Placeholder body for panels that are not implemented yet. +pub fn placeholder(ui: &mut egui::Ui, rect: Rect, t: &Tokens, text: &str) { + ui.painter().text(rect.center(), Align2::CENTER_CENTER, text, Tokens::ui(12.0), t.text_faint); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn workspaces_contain_core_panels() { + for w in WORKSPACES { + let d = workspace(w); + assert!(d.contains(PanelKind::Timeline), "{w}"); + assert!(d.contains(PanelKind::Composition) || d.contains(PanelKind::Layer), "{w}"); + } + } + + #[test] + fn close_and_open() { + let mut d = workspace("Default"); + d.close(PanelKind::Paragraph); + assert!(!d.contains(PanelKind::Paragraph)); + d.open_near(PanelKind::Tracker, PanelKind::EffectsPresets); + assert!(d.is_visible(PanelKind::Tracker)); + let s = serde_json::to_string(&d).unwrap(); + let back: DockNode = serde_json::from_str(&s).unwrap(); + assert_eq!(back, d); + assert_eq!(PanelKind::from_name("effects & presets"), Some(PanelKind::EffectsPresets)); + } +} diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs new file mode 100644 index 00000000..3f20b2ec --- /dev/null +++ b/crates/ui-egui/src/frames.rs @@ -0,0 +1,162 @@ +//! Background frame rendering and the RAM preview cache. +//! +//! Frames render on a dedicated thread pool from immutable `Arc` snapshots, so the UI +//! never waits for the compositor. Results land in a memory-budgeted cache keyed by (project +//! revision, comp, frame, scale); the timeline draws the cached range as the green cache bar. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::{Arc, Mutex}; + +use effectcraft_engine::project::{ItemId, Project}; +use effectcraft_engine::render::{ExprHost, FootageSource, RenderOpts, Renderer}; +use effectcraft_engine::time::Tick; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FrameKey { + pub revision: u64, + pub comp: u64, + pub frame: i64, + /// Render scale × 1000. + pub scale: u32, +} + +struct Cache { + map: HashMap>, + order: VecDeque, + bytes: usize, + budget: usize, +} + +impl Cache { + fn insert(&mut self, k: FrameKey, img: Arc) { + let sz = img.pixels.len() * 4; + if self.map.insert(k, img).is_none() { + self.order.push_back(k); + self.bytes += sz; + } + while self.bytes > self.budget { + let Some(old) = self.order.pop_front() else { break }; + if let Some(i) = self.map.remove(&old) { + self.bytes -= i.pixels.len() * 4; + } + } + } +} + +/// What a render job needs (all cheap clones). +#[derive(Clone)] +pub struct RenderSource { + pub project: Arc, + pub footage: Arc, + pub expr: Option>, +} + +pub struct Frames { + cache: Arc>, + inflight: Arc>>, + pool: rayon::ThreadPool, + ctx: Option, + /// Last render time per frame (ms), for the Info panel / perf readout. + pub last_ms: Arc>, +} + +impl Default for Frames { + fn default() -> Self { + let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(2, 16); + Frames { + cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, budget: 3 << 30 })), + inflight: Arc::new(Mutex::new(HashSet::new())), + pool: rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("ec-frame-{i}")).build().expect("frame pool"), + ctx: None, + last_ms: Arc::new(Mutex::new(0.0)), + } + } +} + +/// Premultiplied f32 → egui premultiplied Color32 (alpha kept, so the viewer can show the +/// transparency grid or the comp background colour underneath). +pub fn to_color_image(img: &effectcraft_engine::render::Image) -> egui::ColorImage { + let px: Vec = img + .data + .iter() + .map(|p| { + let a = p[3].clamp(0.0, 1.0); + let c = |v: f32| (v.clamp(0.0, a) * 255.0 + 0.5) as u8; + egui::Color32::from_rgba_premultiplied(c(p[0]), c(p[1]), c(p[2]), (a * 255.0 + 0.5) as u8) + }) + .collect(); + egui::ColorImage::new([img.width as usize, img.height as usize], px) +} + +impl Frames { + pub fn set_context(&mut self, ctx: &egui::Context) { + if self.ctx.is_none() { + self.ctx = Some(ctx.clone()); + } + } + + pub fn get(&self, k: &FrameKey) -> Option> { + self.cache.lock().ok()?.map.get(k).cloned() + } + + pub fn is_cached(&self, k: &FrameKey) -> bool { + self.cache.lock().map(|c| c.map.contains_key(k)).unwrap_or(false) + } + + pub fn inflight(&self) -> usize { + self.inflight.lock().map(|s| s.len()).unwrap_or(0) + } + + /// Cached frame numbers for (revision, comp, scale) — for the cache bar. + pub fn cached_frames(&self, revision: u64, comp: u64, scale: u32) -> Vec { + let Ok(c) = self.cache.lock() else { return vec![] }; + let mut v: Vec = c.map.keys().filter(|k| k.revision == revision && k.comp == comp && k.scale == scale).map(|k| k.frame).collect(); + v.sort_unstable(); + v + } + + pub fn clear(&self) { + if let Ok(mut c) = self.cache.lock() { + c.map.clear(); + c.order.clear(); + c.bytes = 0; + } + } + + /// Queue a frame (no-op if cached or already rendering). + pub fn request(&self, src: &RenderSource, key: FrameKey, comp: ItemId, t: Tick, opts: RenderOpts) { + if self.is_cached(&key) { + return; + } + { + let Ok(mut inf) = self.inflight.lock() else { return }; + if !inf.insert(key) { + return; + } + } + let src = src.clone(); + let cache = self.cache.clone(); + let inflight = self.inflight.clone(); + let ctx = self.ctx.clone(); + let last = self.last_ms.clone(); + self.pool.spawn(move || { + let t0 = std::time::Instant::now(); + let mut r = Renderer::new(&src.project, src.footage.as_ref(), opts); + r.expr = src.expr.as_deref(); + let img = r.comp_frame(comp, t); + let ci = Arc::new(to_color_image(&img)); + if let Ok(mut l) = last.lock() { + *l = t0.elapsed().as_secs_f64() * 1000.0; + } + if let Ok(mut c) = cache.lock() { + c.insert(key, ci); + } + if let Ok(mut inf) = inflight.lock() { + inf.remove(&key); + } + if let Some(ctx) = ctx { + ctx.request_repaint(); + } + }); + } +} diff --git a/crates/ui-egui/src/header.rs b/crates/ui-egui/src/header.rs new file mode 100644 index 00000000..6ed55cb6 --- /dev/null +++ b/crates/ui-egui/src/header.rs @@ -0,0 +1,250 @@ +//! The Tools bar: home, the tool slots, tool options, snapping, workspaces and the community +//! buttons (Discord is always one click away). + +use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2}; +use serde_json::json; + +use crate::icons::{self, Icon}; +use crate::state::Tool; +use crate::theme::Tokens; +use crate::widgets; +use crate::{Dialog, EffectcraftApp}; + +pub fn show(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.header_bg); + p.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.app_bg)); + let cy = rect.center().y; + let mut x = rect.min.x + if app.integrated_titlebar && !app.ui.show_menu_bar { 80.0 } else { 10.0 }; + + // Brand mark. + let brand = Rect::from_min_size(pos2(x, cy - 12.0), vec2(24.0, 24.0)); + paint_logo(&p, brand); + let bresp = ui.interact(brand, egui::Id::new("brand"), Sense::click()); + app.auto.add("header.about", brand, "About EffectCraft"); + if bresp.on_hover_text("About EffectCraft").clicked() { + app.dialog = Some(Dialog::About); + } + x += 32.0; + + // Home. + let home = Rect::from_min_size(pos2(x, cy - 13.0), vec2(26.0, 26.0)); + if widgets::icon_button(ui, home, Icon::Home, app.ui.start_screen, &t, egui::Id::new("tool-home")).on_hover_text("Home").clicked() { + app.ui.start_screen = !app.ui.start_screen; + } + app.auto.add("header.home", home, "Home"); + x += 30.0; + p.line_segment([pos2(x, cy - 10.0), pos2(x, cy + 10.0)], Stroke::new(1.0, t.separator)); + x += 6.0; + + // Tool slots (with group separators after camera tools and pan-behind). + for (si, slot) in Tool::SLOTS.iter().enumerate() { + let cur = app.ui.slot_tools.get(si).copied().unwrap_or(slot[0]); + let r = Rect::from_min_size(pos2(x, cy - 13.0), vec2(26.0, 26.0)); + let active = slot.contains(&app.ui.tool); + let id = egui::Id::new(("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(&format!("tools.{cur:?}"), r, 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); + if resp.clicked() { + app.ui.tool = cur; + } + if slot.len() > 1 { + resp.context_menu(|ui| { + for tool in slot.iter() { + if ui.selectable_label(app.ui.tool == *tool, tool.label()).clicked() { + app.ui.tool = *tool; + app.ui.slot_tools[si] = *tool; + ui.close(); + } + } + }); + } + x += 28.0; + if matches!(si, 2 | 5 | 7 | 10 | 13) { + x += 4.0; + p.line_segment([pos2(x, cy - 10.0), pos2(x, cy + 10.0)], Stroke::new(1.0, t.separator)); + x += 6.0; + } + } + + // Tool options. + x += 10.0; + if app.ui.tool.is_shape() || app.ui.tool == Tool::Pen { + p.text(pos2(x, cy), Align2::LEFT_CENTER, "Fill:", Tokens::ui(12.0), t.text_dim); + x += 28.0; + let fr = Rect::from_center_size(pos2(x + 10.0, cy), vec2(20.0, 16.0)); + let c = app.ui.fill_color; + if widgets::swatch(ui, fr, [c[0], c[1], c[2], 1.0], egui::Id::new("tool-fill"), &t).clicked() { + widgets::open_popup(ui, egui::Id::new("tool-fill-pop")); + } + color_popup(ui, egui::Id::new("tool-fill-pop"), fr.left_bottom(), &mut app.ui.fill_color); + x += 32.0; + p.text(pos2(x, cy), Align2::LEFT_CENTER, "Stroke:", Tokens::ui(12.0), t.text_dim); + x += 44.0; + let sr = Rect::from_center_size(pos2(x + 10.0, cy), vec2(20.0, 16.0)); + let c = app.ui.stroke_color; + if widgets::swatch(ui, sr, [c[0], c[1], c[2], 1.0], egui::Id::new("tool-stroke"), &t).clicked() { + widgets::open_popup(ui, egui::Id::new("tool-stroke-pop")); + } + color_popup(ui, egui::Id::new("tool-stroke-pop"), sr.left_bottom(), &mut app.ui.stroke_color); + x += 26.0; + let (r, v, _) = + widgets::hot_number_at(ui, pos2(x, cy - 9.0), egui::Id::new("tool-stroke-w"), app.ui.stroke_width as f64, 0.2, (0.0, 1000.0), 0, " px", &t); + if let Some(v) = v { + app.ui.stroke_width = v as f32; + } + x = r.max.x + 14.0; + } + let snap = Rect::from_min_size(pos2(x, cy - 10.0), vec2(20.0, 20.0)); + if widgets::checkbox(ui, snap, app.ui.snapping, &t, egui::Id::new("snapping")).clicked() { + app.ui.snapping = !app.ui.snapping; + app.session.state.snapping = app.ui.snapping; + } + app.auto.add("header.snapping", snap, "Snapping"); + p.text(pos2(snap.max.x + 4.0, cy), Align2::LEFT_CENTER, "Snapping", Tokens::ui(12.0), t.text_dim); + + // Right side: community buttons, workspaces. + let mut rx = rect.max.x - 10.0; + let discord = Rect::from_min_max(pos2(rx - 104.0, cy - 13.0), pos2(rx, cy + 13.0)); + let dresp = ui.interact(discord, egui::Id::new("hdr-discord"), Sense::click()); + let dc = Color32::from_rgb(0x58, 0x65, 0xf2); + p.rect_filled(discord, 13.0, if dresp.hovered() { dc.gamma_multiply(1.2) } else { dc }); + icons::paint(&p, Rect::from_center_size(pos2(discord.min.x + 16.0, cy), vec2(14.0, 14.0)), Icon::Chat, Color32::WHITE); + p.text(pos2(discord.min.x + 28.0, cy), Align2::LEFT_CENTER, "Discord", Tokens::semibold(12.0), Color32::WHITE); + app.auto.add("header.discord", discord, "Join the ArtCraft Discord"); + if dresp.on_hover_text("Join the ArtCraft community on Discord").clicked() { + let _ = app.session.execute("help.discord", json!({})); + } + rx = discord.min.x - 6.0; + for (id, icon, tip, cmd) in + [("hdr-github", Icon::Code, "EffectCraft on GitHub", "help.github"), ("hdr-web", Icon::Globe, "EffectCraft on getartcraft.com", "help.appPage")] + { + let r = Rect::from_min_max(pos2(rx - 26.0, cy - 13.0), pos2(rx, cy + 13.0)); + if widgets::icon_button(ui, r, icon, false, &t, egui::Id::new(id)).on_hover_text(tip).clicked() { + let _ = app.session.execute(cmd, json!({})); + } + app.auto.add(&format!("header.{}", &id[4..]), r, tip); + rx = r.min.x - 4.0; + } + rx -= 10.0; + p.line_segment([pos2(rx, cy - 10.0), pos2(rx, cy + 10.0)], Stroke::new(1.0, t.separator)); + rx -= 10.0; + // Workspace tabs (right to left), with a » menu of all. + let more = Rect::from_min_max(pos2(rx - 20.0, cy - 11.0), pos2(rx, cy + 11.0)); + let mresp = ui.interact(more, egui::Id::new("ws-more"), Sense::click()); + p.text(more.center(), Align2::CENTER_CENTER, "»", Tokens::ui(15.0), if mresp.hovered() { t.text } else { t.text_dim }); + app.auto.add("header.workspaces", more, "Workspaces"); + mresp.context_menu(|ui| ws_menu(app, ui)); + if mresp.clicked() { + widgets::open_popup(ui, egui::Id::new("ws-pop")); + } + let names: Vec = crate::dock::WORKSPACES.iter().map(|s| s.to_string()).collect(); + if let Some(i) = widgets::popup_menu( + ui, + egui::Id::new("ws-pop"), + more.left_bottom() - vec2(140.0, 0.0), + &names, + crate::dock::WORKSPACES.iter().position(|w| *w == app.ui.workspace), + ) { + app.set_workspace(crate::dock::WORKSPACES[i]); + } + rx = more.min.x - 6.0; + let shown = ["Small Screen", "Standard", "Animation", "Default"]; + for name in shown { + let g = p.layout_no_wrap(name.to_string(), Tokens::ui(12.0), t.text); + let w = g.size().x + 16.0; + let r = Rect::from_min_max(pos2(rx - w, cy - 13.0), pos2(rx, cy + 13.0)); + if r.min.x < x + 120.0 { + break; + } + let active = app.ui.workspace == name; + let resp = ui.interact(r, egui::Id::new(("ws", name)), Sense::click()); + let col = if active { + t.hot_text + } else if resp.hovered() { + t.text + } else { + t.text_dim + }; + p.galley_with_override_text_color(pos2(r.min.x + 8.0, cy - g.size().y / 2.0), g, col); + if active { + p.line_segment([pos2(r.min.x + 8.0, r.max.y - 3.0), pos2(r.max.x - 8.0, r.max.y - 3.0)], Stroke::new(2.0, t.hot_text)); + } + app.auto.add(&format!("header.workspace.{name}"), r, name); + if resp.clicked() { + app.set_workspace(name); + } + rx = r.min.x - 2.0; + } +} + +fn ws_menu(app: &mut EffectcraftApp, ui: &mut egui::Ui) { + for w in crate::dock::WORKSPACES { + if ui.selectable_label(app.ui.workspace == w, w).clicked() { + app.set_workspace(w); + ui.close(); + } + } + ui.separator(); + if ui.button("Reset to Saved Layout").clicked() { + let n = app.ui.workspace.clone(); + app.set_workspace(&n); + ui.close(); + } +} + +/// A small colour picker popup bound to an RGB value. +pub fn color_popup(ui: &mut egui::Ui, id: egui::Id, pos: egui::Pos2, c: &mut [f32; 3]) -> bool { + let open_id = id.with("open"); + if !ui.data(|d| d.get_temp::(open_id).unwrap_or(false)) { + return false; + } + let mut changed = false; + let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos + vec2(0.0, 4.0)).show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + let mut col = + egui::Color32::from_rgb((c[0].clamp(0.0, 1.0) * 255.0) as u8, (c[1].clamp(0.0, 1.0) * 255.0) as u8, (c[2].clamp(0.0, 1.0) * 255.0) as u8); + if egui::color_picker::color_picker_color32(ui, &mut col, egui::color_picker::Alpha::Opaque) { + *c = [col.r() as f32 / 255.0, col.g() as f32 / 255.0, col.b() as f32 / 255.0]; + changed = true; + } + }); + }); + if ui.input(|i| i.pointer.any_pressed()) && !area.response.contains_pointer() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + ui.data_mut(|d| d.insert_temp(open_id, false)); + } + changed +} + +/// The EffectCraft mark: a rounded square with a gradient-like split and a keyframe diamond. +pub fn paint_logo(p: &egui::Painter, r: Rect) { + p.rect_filled(r, 6.0, Color32::from_rgb(0x1d, 0x2b, 0x5e)); + let inner = r.shrink(2.0); + p.rect_filled( + Rect::from_min_max(inner.min, pos2(inner.center().x, inner.max.y)), + egui::CornerRadius { nw: 5, sw: 5, ne: 0, se: 0 }, + Color32::from_rgb(0x2d, 0x8c, 0xeb), + ); + p.rect_filled( + Rect::from_min_max(pos2(inner.center().x, inner.min.y), inner.max), + egui::CornerRadius { nw: 0, sw: 0, ne: 5, se: 5 }, + Color32::from_rgb(0x8e, 0x6b, 0xff), + ); + let c = r.center(); + let s = r.width() * 0.26; + p.add(egui::Shape::convex_polygon(vec![c + vec2(0.0, -s), c + vec2(s, 0.0), c + vec2(0.0, s), c + vec2(-s, 0.0)], Color32::WHITE, Stroke::NONE)); +} diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs new file mode 100644 index 00000000..816da289 --- /dev/null +++ b/crates/ui-egui/src/icons.rs @@ -0,0 +1,609 @@ +//! Vector icons drawn in code on a 16×16 design grid (crisp at any DPI, recolourable). Original +//! drawings following generic motion-graphics conventions; no third-party or Adobe artwork. + +use egui::epaint::{PathShape, PathStroke}; +use egui::{Color32, Painter, Pos2, Rect, Stroke, pos2, vec2}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Icon { + // tools + Home, + Selection, + Hand, + Zoom, + Orbit, + PanCamera, + Dolly, + Rotate, + PanBehind, + Rectangle, + RoundedRect, + Ellipse, + Polygon, + Star, + Pen, + Type, + TypeVertical, + Brush, + Clone, + Eraser, + RotoBrush, + Puppet, + // switches & timeline + Eye, + Speaker, + Solo, + Lock, + Shy, + Collapse, + Quality, + Fx, + FrameBlend, + MotionBlur, + Adjustment, + Cube, + Draft3D, + Graph, + Stopwatch, + Keyframe, + PickWhip, + Flowchart, + // project items + Folder, + Comp, + Footage, + Image, + Audio, + Solid, + TextLayer, + ShapeLayer, + Null, + Camera, + Light, + // ui + Search, + Trash, + NewFolder, + NewComp, + Gear, + Hamburger, + ChevronDown, + ChevronRight, + ChevronLeft, + Play, + Pause, + StepBack, + StepFwd, + First, + Last, + Loop, + Snapshot, + ShowSnapshot, + Grid, + MaskVis, + Checker, + Region, + Plus, + Minus, + Close, + Link, + MountainSmall, + MountainLarge, + Fullscreen, + Channel, + Exposure, + // links + Chat, + Globe, + Code, + Sparkle, +} + +pub struct Pen16<'a> { + painter: &'a Painter, + rect: Rect, + color: Color32, + width: f32, +} + +impl Pen16<'_> { + fn s(&self) -> f32 { + self.rect.width().min(self.rect.height()) / 16.0 + } + fn p(&self, x: f32, y: f32) -> Pos2 { + let s = self.s(); + let o = self.rect.center() - vec2(8.0 * s, 8.0 * s); + pos2(o.x + x * s, o.y + y * s) + } + fn line(&self, pts: &[(f32, f32)]) { + let v: Vec = pts.iter().map(|(x, y)| self.p(*x, *y)).collect(); + self.painter.add(PathShape::line(v, PathStroke::new(self.width * self.s(), self.color))); + } + fn closed(&self, pts: &[(f32, f32)]) { + let v: Vec = pts.iter().map(|(x, y)| self.p(*x, *y)).collect(); + self.painter.add(PathShape::closed_line(v, PathStroke::new(self.width * self.s(), self.color))); + } + fn fill(&self, pts: &[(f32, f32)]) { + let v: Vec = pts.iter().map(|(x, y)| self.p(*x, *y)).collect(); + self.painter.add(PathShape::convex_polygon(v, self.color, Stroke::NONE)); + } + fn circle(&self, x: f32, y: f32, r: f32) { + self.painter.circle_stroke(self.p(x, y), r * self.s(), Stroke::new(self.width * self.s(), self.color)); + } + fn dot(&self, x: f32, y: f32, r: f32) { + self.painter.circle_filled(self.p(x, y), r * self.s(), self.color); + } + fn rect(&self, x0: f32, y0: f32, x1: f32, y1: f32) { + let r = Rect::from_min_max(self.p(x0, y0), self.p(x1, y1)); + self.painter.rect_stroke(r, 1.0 * self.s(), Stroke::new(self.width * self.s(), self.color), egui::StrokeKind::Middle); + } + fn rrect(&self, x0: f32, y0: f32, x1: f32, y1: f32, rad: f32) { + let r = Rect::from_min_max(self.p(x0, y0), self.p(x1, y1)); + self.painter.rect_stroke(r, rad * self.s(), Stroke::new(self.width * self.s(), self.color), egui::StrokeKind::Middle); + } + fn rect_fill(&self, x0: f32, y0: f32, x1: f32, y1: f32) { + let r = Rect::from_min_max(self.p(x0, y0), self.p(x1, y1)); + self.painter.rect_filled(r, 0.8 * self.s(), self.color); + } + fn arc(&self, cx: f32, cy: f32, r: f32, a0: f32, a1: f32) { + let n = 24; + let pts: Vec<(f32, f32)> = (0..=n) + .map(|i| { + let a = (a0 + (a1 - a0) * i as f32 / n as f32).to_radians(); + (cx + r * a.cos(), cy + r * a.sin()) + }) + .collect(); + self.line(&pts); + } + fn ellipse(&self, cx: f32, cy: f32, rx: f32, ry: f32) { + let n = 32; + let pts: Vec<(f32, f32)> = (0..n) + .map(|i| { + let a = std::f32::consts::TAU * i as f32 / n as f32; + (cx + rx * a.cos(), cy + ry * a.sin()) + }) + .collect(); + self.closed(&pts); + } + fn star(&self, cx: f32, cy: f32, ro: f32, ri: f32, n: usize) -> Vec<(f32, f32)> { + (0..n * 2) + .map(|i| { + let a = std::f32::consts::PI * i as f32 / n as f32 - std::f32::consts::FRAC_PI_2; + let r = if i % 2 == 0 { ro } else { ri }; + (cx + r * a.cos(), cy + r * a.sin()) + }) + .collect() + } +} + +/// Paint `icon` centred in `rect`. +pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) { + let pen = Pen16 { painter, rect, color, width: 1.25 }; + use Icon::*; + match icon { + Home => { + pen.closed(&[(2.5, 7.5), (8.0, 2.5), (13.5, 7.5), (13.5, 13.5), (2.5, 13.5)]); + pen.rect(6.5, 9.5, 9.5, 13.5); + } + Selection => pen.fill(&[(4.5, 2.0), (4.5, 13.0), (7.2, 10.5), (9.2, 14.6), (10.8, 13.9), (8.9, 9.9), (12.5, 9.7)]), + Hand => { + pen.line(&[(5.0, 9.0), (5.0, 4.0)]); + pen.line(&[(7.3, 8.0), (7.3, 2.6)]); + pen.line(&[(9.6, 8.0), (9.6, 3.2)]); + pen.line(&[(11.8, 8.8), (11.8, 5.0)]); + pen.line(&[(5.0, 9.0), (3.2, 7.4), (2.4, 8.4), (5.6, 13.4), (11.0, 14.0), (12.4, 11.0), (11.8, 8.8)]); + } + Zoom => { + pen.circle(6.8, 6.8, 4.3); + pen.line(&[(10.0, 10.0), (14.0, 14.0)]); + } + Orbit => { + pen.ellipse(8.0, 8.0, 6.0, 2.8); + pen.dot(8.0, 8.0, 1.6); + pen.fill(&[(12.0, 3.0), (14.5, 5.2), (11.4, 6.0)]); + } + PanCamera => { + pen.line(&[(8.0, 1.8), (8.0, 14.2)]); + pen.line(&[(1.8, 8.0), (14.2, 8.0)]); + pen.fill(&[(8.0, 1.0), (6.2, 3.5), (9.8, 3.5)]); + pen.fill(&[(8.0, 15.0), (6.2, 12.5), (9.8, 12.5)]); + pen.fill(&[(1.0, 8.0), (3.5, 6.2), (3.5, 9.8)]); + pen.fill(&[(15.0, 8.0), (12.5, 6.2), (12.5, 9.8)]); + } + Dolly => { + pen.line(&[(8.0, 1.8), (8.0, 14.2)]); + pen.fill(&[(8.0, 1.0), (5.5, 4.5), (10.5, 4.5)]); + pen.fill(&[(8.0, 15.0), (5.5, 11.5), (10.5, 11.5)]); + pen.rect(5.0, 6.5, 11.0, 9.5); + } + Rotate => { + pen.arc(8.0, 8.0, 5.0, -60.0, 220.0); + pen.fill(&[(10.2, 1.8), (13.6, 4.6), (9.6, 5.8)]); + } + PanBehind => { + pen.circle(8.0, 8.0, 3.0); + pen.line(&[(8.0, 1.5), (8.0, 5.0)]); + pen.line(&[(8.0, 11.0), (8.0, 14.5)]); + pen.line(&[(1.5, 8.0), (5.0, 8.0)]); + pen.line(&[(11.0, 8.0), (14.5, 8.0)]); + } + Rectangle => pen.rect(2.5, 3.5, 13.5, 12.5), + RoundedRect => pen.rrect(2.5, 3.5, 13.5, 12.5, 3.0), + Ellipse => pen.ellipse(8.0, 8.0, 5.8, 4.8), + Polygon => { + let pts: Vec<(f32, f32)> = (0..6) + .map(|i| { + let a = std::f32::consts::TAU * i as f32 / 6.0 - std::f32::consts::FRAC_PI_2; + (8.0 + 6.0 * a.cos(), 8.4 + 6.0 * a.sin()) + }) + .collect(); + pen.closed(&pts); + } + Star => { + let pts = pen.star(8.0, 8.6, 6.4, 2.7, 5); + pen.closed(&pts); + } + Pen => { + pen.closed(&[(8.0, 1.8), (12.0, 9.0), (8.0, 14.0), (4.0, 9.0)]); + pen.dot(8.0, 8.6, 1.1); + pen.line(&[(8.0, 1.8), (8.0, 7.6)]); + } + Type => { + pen.line(&[(3.0, 3.5), (13.0, 3.5)]); + pen.line(&[(8.0, 3.5), (8.0, 13.5)]); + pen.line(&[(6.0, 13.5), (10.0, 13.5)]); + } + TypeVertical => { + pen.line(&[(12.5, 3.0), (12.5, 13.0)]); + pen.line(&[(12.5, 8.0), (3.0, 8.0)]); + pen.line(&[(3.0, 6.0), (3.0, 10.0)]); + } + Brush => { + pen.line(&[(13.5, 2.5), (7.0, 9.0)]); + pen.fill(&[(7.6, 8.4), (4.4, 9.4), (2.6, 13.6), (6.8, 12.0), (7.8, 9.0)]); + } + Clone => { + pen.rect(6.0, 8.0, 10.0, 14.0); + pen.line(&[(8.0, 8.0), (8.0, 5.5)]); + pen.ellipse(8.0, 3.8, 3.0, 1.8); + } + Eraser => { + pen.closed(&[(9.0, 2.5), (14.0, 7.5), (8.0, 13.5), (3.0, 8.5)]); + pen.line(&[(5.5, 6.0), (11.5, 11.0)]); + pen.line(&[(6.0, 14.0), (14.0, 14.0)]); + } + RotoBrush => { + pen.line(&[(13.0, 2.5), (8.0, 7.5)]); + pen.ellipse(6.0, 10.0, 3.6, 3.6); + pen.dot(6.0, 10.0, 1.0); + } + Puppet => { + pen.circle(8.0, 3.6, 1.6); + pen.line(&[(8.0, 5.2), (8.0, 10.0)]); + pen.line(&[(3.5, 7.0), (8.0, 6.5), (12.5, 7.0)]); + pen.line(&[(5.5, 14.0), (8.0, 10.0), (10.5, 14.0)]); + } + Eye => { + pen.line(&[(1.5, 8.0), (4.0, 5.0), (8.0, 3.8), (12.0, 5.0), (14.5, 8.0), (12.0, 11.0), (8.0, 12.2), (4.0, 11.0), (1.5, 8.0)]); + pen.dot(8.0, 8.0, 2.2); + } + Speaker => { + pen.fill(&[(2.0, 6.0), (5.0, 6.0), (9.0, 2.5), (9.0, 13.5), (5.0, 10.0), (2.0, 10.0)]); + pen.arc(9.0, 8.0, 3.0, -50.0, 50.0); + pen.arc(9.0, 8.0, 5.5, -50.0, 50.0); + } + Solo => { + pen.circle(8.0, 8.0, 4.5); + pen.dot(8.0, 8.0, 2.4); + } + Lock => { + pen.rect(3.5, 7.0, 12.5, 14.0); + pen.arc(8.0, 7.0, 3.0, 180.0, 360.0); + pen.dot(8.0, 10.5, 1.0); + } + Shy => { + pen.circle(8.0, 8.0, 5.8); + pen.dot(6.0, 7.0, 0.8); + pen.dot(10.0, 7.0, 0.8); + pen.arc(8.0, 8.5, 2.6, 30.0, 150.0); + } + Collapse => { + pen.circle(8.0, 8.0, 2.8); + for i in 0..8 { + let a = std::f32::consts::TAU * i as f32 / 8.0; + pen.line(&[(8.0 + 4.3 * a.cos(), 8.0 + 4.3 * a.sin()), (8.0 + 6.3 * a.cos(), 8.0 + 6.3 * a.sin())]); + } + } + Quality => pen.line(&[(4.0, 2.5), (12.0, 13.5)]), + Fx => { + pen.line(&[(7.0, 3.0), (5.6, 3.0), (4.6, 4.2), (4.6, 13.0)]); + pen.line(&[(3.0, 7.0), (7.0, 7.0)]); + pen.line(&[(8.5, 7.0), (13.0, 13.0)]); + pen.line(&[(13.0, 7.0), (8.5, 13.0)]); + } + FrameBlend => { + pen.rect(2.0, 4.0, 9.0, 11.0); + pen.rect(7.0, 5.0, 14.0, 12.0); + } + MotionBlur => { + pen.circle(10.5, 8.0, 3.5); + pen.circle(7.0, 8.0, 3.5); + pen.circle(4.0, 8.0, 3.0); + } + Adjustment => { + pen.circle(8.0, 8.0, 5.5); + pen.fill(&[(8.0, 2.5), (8.0, 13.5), (5.2, 12.7), (3.2, 10.6), (2.5, 8.0), (3.2, 5.4), (5.2, 3.3)]); + } + Cube => { + pen.closed(&[(8.0, 2.0), (13.5, 5.0), (13.5, 11.0), (8.0, 14.0), (2.5, 11.0), (2.5, 5.0)]); + pen.line(&[(2.5, 5.0), (8.0, 8.0), (13.5, 5.0)]); + pen.line(&[(8.0, 8.0), (8.0, 14.0)]); + } + Draft3D => { + pen.closed(&[(8.0, 2.0), (13.5, 5.0), (13.5, 11.0), (8.0, 14.0), (2.5, 11.0), (2.5, 5.0)]); + pen.line(&[(5.0, 9.0), (11.0, 9.0)]); + } + Graph => { + pen.line(&[(2.0, 13.0), (5.0, 12.0), (7.0, 8.0), (9.0, 4.5), (11.5, 3.2), (14.0, 3.0)]); + pen.line(&[(2.0, 2.0), (2.0, 14.0), (14.0, 14.0)]); + } + Stopwatch => { + pen.circle(8.0, 9.0, 5.2); + pen.line(&[(8.0, 9.0), (8.0, 5.8)]); + pen.line(&[(6.5, 2.0), (9.5, 2.0)]); + pen.line(&[(8.0, 2.0), (8.0, 3.8)]); + } + Keyframe => pen.fill(&[(8.0, 2.5), (13.5, 8.0), (8.0, 13.5), (2.5, 8.0)]), + PickWhip => { + pen.arc(8.0, 8.0, 5.5, 0.0, 300.0); + pen.arc(8.0, 8.0, 3.0, 40.0, 340.0); + pen.dot(8.0, 8.0, 1.0); + } + Flowchart => { + pen.rect(1.5, 2.5, 6.0, 6.5); + pen.rect(10.0, 9.5, 14.5, 13.5); + pen.line(&[(6.0, 4.5), (12.25, 4.5), (12.25, 9.5)]); + } + Folder => pen.closed(&[(1.5, 4.0), (6.0, 4.0), (7.5, 5.5), (14.5, 5.5), (14.5, 13.0), (1.5, 13.0)]), + Comp => { + pen.rect(2.0, 3.0, 14.0, 13.0); + pen.rect_fill(4.0, 5.0, 8.0, 9.0); + pen.rect(7.0, 7.5, 12.0, 11.0); + } + Footage => { + pen.rect(2.0, 3.0, 14.0, 13.0); + for y in [5.0, 8.0, 11.0] { + pen.dot(3.8, y, 0.6); + pen.dot(12.2, y, 0.6); + } + pen.line(&[(5.5, 3.0), (5.5, 13.0)]); + pen.line(&[(10.5, 3.0), (10.5, 13.0)]); + } + Image => { + pen.rect(2.0, 3.0, 14.0, 13.0); + pen.line(&[(2.5, 11.5), (6.0, 8.0), (9.0, 10.5), (11.0, 9.0), (13.5, 11.5)]); + pen.dot(10.5, 5.8, 1.1); + } + Audio => { + pen.line(&[(6.0, 12.0), (6.0, 3.5), (13.0, 2.5), (13.0, 10.5)]); + pen.dot(4.4, 12.0, 1.8); + pen.dot(11.4, 10.5, 1.8); + } + Solid => pen.rect_fill(3.0, 3.0, 13.0, 13.0), + TextLayer => { + pen.line(&[(3.5, 3.5), (12.5, 3.5)]); + pen.line(&[(8.0, 3.5), (8.0, 13.0)]); + } + ShapeLayer => { + let pts = pen.star(8.0, 8.6, 6.4, 2.7, 5); + pen.closed(&pts); + } + Null => pen.rect(3.0, 3.0, 13.0, 13.0), + Camera => { + pen.rect(1.5, 5.0, 10.5, 12.0); + pen.closed(&[(10.5, 7.5), (14.5, 5.5), (14.5, 11.5), (10.5, 9.5)]); + } + Light => { + pen.circle(8.0, 6.5, 3.8); + pen.line(&[(6.3, 10.0), (6.3, 12.5), (9.7, 12.5), (9.7, 10.0)]); + pen.line(&[(6.8, 14.2), (9.2, 14.2)]); + } + Search => { + pen.circle(6.8, 6.8, 4.0); + pen.line(&[(9.8, 9.8), (13.5, 13.5)]); + } + Trash => { + pen.line(&[(2.5, 4.0), (13.5, 4.0)]); + pen.closed(&[(4.0, 4.0), (5.0, 14.0), (11.0, 14.0), (12.0, 4.0)]); + pen.line(&[(6.0, 4.0), (6.5, 2.0), (9.5, 2.0), (10.0, 4.0)]); + } + NewFolder => { + pen.closed(&[(1.5, 4.0), (6.0, 4.0), (7.5, 5.5), (14.5, 5.5), (14.5, 13.0), (1.5, 13.0)]); + pen.line(&[(8.0, 7.5), (8.0, 11.5)]); + pen.line(&[(6.0, 9.5), (10.0, 9.5)]); + } + NewComp => { + pen.rect(2.0, 3.0, 14.0, 13.0); + pen.line(&[(8.0, 5.5), (8.0, 10.5)]); + pen.line(&[(5.5, 8.0), (10.5, 8.0)]); + } + Gear => { + pen.circle(8.0, 8.0, 2.2); + for i in 0..8 { + let a = std::f32::consts::TAU * i as f32 / 8.0; + pen.line(&[(8.0 + 4.0 * a.cos(), 8.0 + 4.0 * a.sin()), (8.0 + 6.0 * a.cos(), 8.0 + 6.0 * a.sin())]); + } + pen.circle(8.0, 8.0, 4.2); + } + Hamburger => { + for y in [4.5, 8.0, 11.5] { + pen.line(&[(3.0, y), (13.0, y)]); + } + } + ChevronDown => pen.fill(&[(4.0, 6.0), (12.0, 6.0), (8.0, 11.0)]), + ChevronRight => pen.fill(&[(6.0, 4.0), (11.0, 8.0), (6.0, 12.0)]), + ChevronLeft => pen.fill(&[(10.0, 4.0), (5.0, 8.0), (10.0, 12.0)]), + Play => pen.fill(&[(4.5, 2.5), (13.0, 8.0), (4.5, 13.5)]), + Pause => { + pen.rect_fill(4.0, 3.0, 6.8, 13.0); + pen.rect_fill(9.2, 3.0, 12.0, 13.0); + } + StepBack => { + pen.fill(&[(12.5, 3.5), (6.0, 8.0), (12.5, 12.5)]); + pen.rect_fill(3.5, 3.5, 5.0, 12.5); + } + StepFwd => { + pen.fill(&[(3.5, 3.5), (10.0, 8.0), (3.5, 12.5)]); + pen.rect_fill(11.0, 3.5, 12.5, 12.5); + } + First => { + pen.fill(&[(13.5, 3.5), (8.0, 8.0), (13.5, 12.5)]); + pen.fill(&[(8.5, 3.5), (3.0, 8.0), (8.5, 12.5)]); + pen.rect_fill(1.8, 3.5, 3.0, 12.5); + } + Last => { + pen.fill(&[(2.5, 3.5), (8.0, 8.0), (2.5, 12.5)]); + pen.fill(&[(7.5, 3.5), (13.0, 8.0), (7.5, 12.5)]); + pen.rect_fill(13.0, 3.5, 14.2, 12.5); + } + Loop => { + pen.arc(8.0, 8.0, 5.0, 200.0, 520.0); + pen.fill(&[(1.8, 5.5), (5.2, 5.5), (3.2, 8.5)]); + } + Snapshot => { + pen.closed(&[(2.0, 5.0), (5.0, 5.0), (6.0, 3.5), (10.0, 3.5), (11.0, 5.0), (14.0, 5.0), (14.0, 12.5), (2.0, 12.5)]); + pen.circle(8.0, 8.7, 2.3); + } + ShowSnapshot => { + pen.line(&[(1.5, 8.0), (4.0, 5.0), (8.0, 3.8), (12.0, 5.0), (14.5, 8.0), (12.0, 11.0), (8.0, 12.2), (4.0, 11.0), (1.5, 8.0)]); + pen.rect(6.0, 6.5, 10.0, 9.5); + } + Grid => { + pen.rect(2.0, 2.0, 14.0, 14.0); + pen.line(&[(6.0, 2.0), (6.0, 14.0)]); + pen.line(&[(10.0, 2.0), (10.0, 14.0)]); + pen.line(&[(2.0, 6.0), (14.0, 6.0)]); + pen.line(&[(2.0, 10.0), (14.0, 10.0)]); + } + MaskVis => { + pen.rect(2.0, 2.0, 14.0, 14.0); + pen.ellipse(8.0, 8.0, 3.8, 3.8); + } + Checker => { + pen.rect(2.0, 2.0, 14.0, 14.0); + pen.rect_fill(2.0, 2.0, 8.0, 8.0); + pen.rect_fill(8.0, 8.0, 14.0, 14.0); + } + Region => { + pen.rect(2.5, 2.5, 13.5, 13.5); + pen.rect(5.5, 5.5, 10.5, 10.5); + } + Plus => { + pen.line(&[(8.0, 3.0), (8.0, 13.0)]); + pen.line(&[(3.0, 8.0), (13.0, 8.0)]); + } + Minus => pen.line(&[(3.0, 8.0), (13.0, 8.0)]), + Close => { + pen.line(&[(4.0, 4.0), (12.0, 12.0)]); + pen.line(&[(12.0, 4.0), (4.0, 12.0)]); + } + Link => { + pen.arc(5.5, 8.0, 3.0, 90.0, 270.0); + pen.arc(10.5, 8.0, 3.0, -90.0, 90.0); + pen.line(&[(5.5, 5.0), (8.0, 5.0)]); + pen.line(&[(5.5, 11.0), (8.0, 11.0)]); + pen.line(&[(8.0, 5.0), (10.5, 5.0)]); + pen.line(&[(8.0, 11.0), (10.5, 11.0)]); + } + MountainSmall => pen.fill(&[(4.0, 12.0), (8.0, 7.0), (12.0, 12.0)]), + MountainLarge => { + pen.fill(&[(1.0, 13.0), (7.0, 4.0), (13.0, 13.0)]); + pen.fill(&[(8.0, 13.0), (11.5, 8.0), (15.0, 13.0)]); + } + Fullscreen => { + pen.line(&[(2.0, 6.0), (2.0, 2.0), (6.0, 2.0)]); + pen.line(&[(10.0, 2.0), (14.0, 2.0), (14.0, 6.0)]); + pen.line(&[(14.0, 10.0), (14.0, 14.0), (10.0, 14.0)]); + pen.line(&[(6.0, 14.0), (2.0, 14.0), (2.0, 10.0)]); + } + Channel => { + pen.circle(6.0, 6.5, 3.6); + pen.circle(10.0, 6.5, 3.6); + pen.circle(8.0, 10.0, 3.6); + } + Exposure => { + pen.circle(8.0, 8.0, 5.5); + pen.fill(&[(8.0, 2.5), (13.5, 8.0), (8.0, 13.5)]); + } + Chat => { + pen.closed(&[(2.0, 3.0), (14.0, 3.0), (14.0, 11.0), (7.0, 11.0), (4.0, 14.0), (4.5, 11.0), (2.0, 11.0)]); + pen.dot(5.3, 7.0, 0.95); + pen.dot(8.0, 7.0, 0.95); + pen.dot(10.7, 7.0, 0.95); + } + Globe => { + pen.circle(8.0, 8.0, 6.0); + pen.ellipse(8.0, 8.0, 2.6, 6.0); + pen.line(&[(2.0, 8.0), (14.0, 8.0)]); + pen.line(&[(3.2, 4.8), (12.8, 4.8)]); + pen.line(&[(3.2, 11.2), (12.8, 11.2)]); + } + Code => { + pen.line(&[(5.0, 4.0), (1.8, 8.0), (5.0, 12.0)]); + pen.line(&[(11.0, 4.0), (14.2, 8.0), (11.0, 12.0)]); + pen.line(&[(9.4, 2.8), (6.6, 13.2)]); + } + Sparkle => { + pen.fill(&[(8.0, 1.5), (9.4, 6.6), (14.5, 8.0), (9.4, 9.4), (8.0, 14.5), (6.6, 9.4), (1.5, 8.0), (6.6, 6.6)]); + } + } +} + +/// Keyframe glyph by interpolation (diamond = linear, hourglass = bezier/ease, circle = auto, +/// square = hold), split into in/out halves. +pub fn keyframe( + painter: &Painter, + center: Pos2, + size: f32, + left: effectcraft_engine::keyframe::KeyHalf, + right: effectcraft_engine::keyframe::KeyHalf, + fill: Color32, + outline: Color32, +) { + use effectcraft_engine::keyframe::KeyHalf as H; + let r = size / 2.0; + let half = |pts: Vec| { + painter.add(PathShape::convex_polygon(pts, fill, Stroke::new(1.0, outline))); + }; + let c = center; + for (side, h) in [(-1.0f32, left), (1.0, right)] { + match h { + H::Linear => half(if side < 0.0 { + vec![c + vec2(0.0, -r), c, c + vec2(0.0, r), c + vec2(-r, 0.0)] + } else { + vec![c + vec2(0.0, -r), c + vec2(r, 0.0), c + vec2(0.0, r), c] + }), + H::Hold => half(if side < 0.0 { + vec![c + vec2(-r * 0.8, -r * 0.8), c + vec2(0.0, -r * 0.8), c + vec2(0.0, r * 0.8), c + vec2(-r * 0.8, r * 0.8)] + } else { + vec![c + vec2(0.0, -r * 0.8), c + vec2(r * 0.8, -r * 0.8), c + vec2(r * 0.8, r * 0.8), c + vec2(0.0, r * 0.8)] + }), + H::Bezier => half(if side < 0.0 { + vec![c + vec2(-r * 0.75, -r), c + vec2(0.0, -r * 0.35), c + vec2(0.0, r * 0.35), c + vec2(-r * 0.75, r)] + } else { + vec![c + vec2(0.0, -r * 0.35), c + vec2(r * 0.75, -r), c + vec2(r * 0.75, r), c + vec2(0.0, r * 0.35)] + }), + H::Auto => { + let n = 10; + // Simple half-disc. + let mut hp = vec![c + vec2(0.0, -r * 0.8), c + vec2(0.0, r * 0.8)]; + for i in 1..n { + let t = std::f32::consts::PI * i as f32 / n as f32; + hp.push(c + vec2(side * r * 0.8 * t.sin(), r * 0.8 * t.cos())); + } + half(hp); + } + } + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs new file mode 100644 index 00000000..e809e8d2 --- /dev/null +++ b/crates/ui-egui/src/lib.rs @@ -0,0 +1,565 @@ +//! The EffectCraft egui frontend (swappable): docking panels, the Composition viewer, the +//! Timeline with property twirl-downs and keyframes, Effect Controls, Effects & Presets, Preview, +//! Info, Character/Paragraph/Align, menus, dialogs and the control channel. +//! +//! Everything goes through `effectcraft_engine::Session::execute` (or `menus::invoke` for +//! frontend-only commands) so every gesture is also available to agents. + +pub mod automation; +pub mod control; +pub mod dock; +pub mod frames; +pub mod header; +pub mod icons; +pub mod menus; +pub mod panels; +pub mod state; +pub mod theme; +pub mod widgets; + +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender}; + +pub use control::ControlRequest; +use dock::PanelKind; +use effectcraft_engine::Session; +use effectcraft_engine::project::ItemId; +use effectcraft_engine::render::RenderOpts; +use effectcraft_engine::time::Tick; +use frames::{FrameKey, Frames, RenderSource}; +use serde_json::json; +use state::UiState; +use theme::Tokens; + +const SCREENSHOT_TIMEOUT_S: f64 = 4.0; + +/// Modal dialogs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Dialog { + About, + NewComp, + CompSettings, + SolidSettings, + CommandPalette, +} + +/// Host hooks provided by the native app (file pickers etc.). +#[derive(Default)] +pub struct Hooks { + pub pick_files: Option Vec>>, + pub pick_save: Option Option>>, + pub pick_open_project: Option Option>>, +} + +#[derive(Default)] +pub struct Playback { + pub playing: bool, + /// Wall-clock start and the comp time it corresponds to. + pub start_wall: f64, + pub start_time: Tick, + pub start_frame: i64, + /// Frames shown / dropped (for the Info/Preview readout). + pub shown: u64, + pub waiting: bool, + pub fps: f64, +} + +pub struct EffectcraftApp { + pub session: Session, + pub ui: UiState, + pub tokens: Tokens, + pub auto: automation::Registry, + pub frames: Frames, + pub playback: Playback, + pub dialog: Option, + pub hooks: Hooks, + pub fps: f32, + last_time: f64, + styled: bool, + fonts_ready: bool, + pub(crate) control_rx: Option>, + pub(crate) deferred: Vec<(ControlRequest, f64)>, + pub(crate) synthetic: Vec, + pub(crate) input_waiters: Vec>, + queued_screenshots: Vec<(u64, f64, u32)>, + pending_screenshots: Vec<(u64, Option, Option<[f32; 4]>, Sender, f64)>, + next_token: u64, + pub(crate) last_ui_time: f64, + pub(crate) toast: Option<(String, f64)>, + /// Texture of the frame shown in the viewer and the key it came from. + pub(crate) viewer_tex: Option<(egui::TextureHandle, FrameKey)>, + /// Last displayed image (for the Info panel colour picker). + pub(crate) viewer_image: Option>, + /// Commands from the native menu bar. + pub command_inbox: Option>, + /// Pointer position in comp pixels (Info panel). + pub(crate) pointer_comp: Option<[f32; 2]>, + pub(crate) dialog_state: panels::dialogs::DialogState, + pub integrated_titlebar: bool, +} + +impl EffectcraftApp { + pub fn new(session: Session) -> Self { + EffectcraftApp { + session, + ui: UiState::default(), + tokens: Tokens::for_kind(Default::default()), + auto: Default::default(), + frames: Frames::default(), + playback: Playback::default(), + dialog: None, + hooks: Hooks::default(), + fps: 60.0, + last_time: 0.0, + styled: false, + fonts_ready: false, + control_rx: None, + deferred: vec![], + synthetic: vec![], + input_waiters: vec![], + queued_screenshots: vec![], + pending_screenshots: vec![], + next_token: 1, + last_ui_time: 0.0, + toast: None, + viewer_tex: None, + viewer_image: None, + command_inbox: None, + pointer_comp: None, + dialog_state: Default::default(), + integrated_titlebar: false, + } + } + + pub fn with_control(mut self, rx: Receiver) -> Self { + self.control_rx = Some(rx); + self + } + + pub fn set_theme(&mut self, ctx: &egui::Context, k: theme::ThemeKind) { + self.ui.theme = k; + self.tokens = Tokens::for_kind(k); + theme::apply_visuals(ctx, &self.tokens); + } + + pub fn set_workspace(&mut self, name: &str) { + self.ui.workspace = name.to_string(); + self.ui.dock = dock::workspace(name); + } + + pub fn show_panel(&mut self, p: PanelKind) { + if !self.ui.dock.contains(p) { + let near = match p { + PanelKind::Layer | PanelKind::Flowchart => PanelKind::Composition, + PanelKind::RenderQueue => PanelKind::Timeline, + PanelKind::EffectControls | PanelKind::History => PanelKind::Project, + _ => PanelKind::EffectsPresets, + }; + self.ui.dock.open_near(p, near); + } + self.ui.dock.activate(p); + self.ui.focused = p; + } + + pub fn render_source(&self) -> RenderSource { + RenderSource { project: self.session.project.clone(), footage: self.session.footage.clone(), expr: self.session.expr.clone() } + } + + /// The render scale used by the viewer right now. + pub fn viewer_scale(&self, zoom: f32, ppp: f32) -> f64 { + if self.playback.playing && self.ui.viewer.res == state::Resolution::Auto { + // Keep previews snappy: never more than the displayed size. + return self.ui.viewer.res.scale(zoom, ppp).min(0.5); + } + self.ui.viewer.res.scale(zoom, ppp) + } + + pub fn frame_key(&self, comp: ItemId, frame: i64, scale: f64) -> FrameKey { + FrameKey { revision: self.session.revision, comp: comp.0, frame, scale: (scale * 1000.0).round() as u32 } + } + + /// Request a frame render (no-op if cached/in flight). + pub fn request_frame(&self, comp: ItemId, frame: i64, scale: f64) { + let Some(c) = self.session.project.comp(comp) else { return }; + let key = self.frame_key(comp, frame, scale); + let t = c.frame_rate.tick_of(frame); + let opts = RenderOpts { scale, motion_blur: true, guides: true, draft: self.ui.viewer.fast_preview }; + self.frames.request(&self.render_source(), key, comp, t, opts); + } + + // ---------------------------------------------------------------- playback + + pub fn play(&mut self, now: f64) { + let Some(c) = self.session.active_comp().cloned() else { return }; + let mut t = self.session.time(); + let (wa, wb) = c.work_area; + if t >= wb - c.frame_duration() || t < wa { + t = wa; + } + self.session.set_time(t); + self.playback = Playback { + playing: true, + start_wall: now, + start_time: t, + start_frame: c.frame_rate.frame_at(t), + shown: 0, + waiting: false, + fps: c.frame_rate.as_f64(), + }; + } + + pub fn stop(&mut self) { + self.playback.playing = false; + } + + pub fn toggle_play(&mut self, now: f64) { + if self.playback.playing { self.stop() } else { self.play(now) } + } + + /// RAM preview: advance at the comp frame rate when frames are cached; otherwise hold and + /// keep rendering ahead (the green cache bar fills, then playback runs in real time). + fn advance_playback(&mut self, ctx: &egui::Context, scale: f64) { + let Some(cid) = self.session.active_comp_id() else { return }; + let Some(c) = self.session.project.comp(cid).cloned() else { return }; + let now = ctx.input(|i| i.time); + let fr = c.frame_rate; + let (wa, wb) = (fr.frame_at(c.work_area.0), fr.frame_at(c.work_area.1 - c.frame_duration())); + // Prefetch ahead. + let cur = fr.frame_at(self.session.time()); + let ahead = (self.frames_parallelism() * 2).max(4) as i64; + let mut queued = self.frames.inflight(); + for k in 0..ahead * 3 { + if queued >= ahead as usize { + break; + } + let mut f = cur + k; + if f > wb { + if !self.ui.preview_loop { + break; + } + f = wa + (f - wb - 1).rem_euclid((wb - wa + 1).max(1)); + } + let key = self.frame_key(cid, f, scale); + if !self.frames.is_cached(&key) { + self.request_frame(cid, f, scale); + queued += 1; + } + } + if !self.playback.playing { + return; + } + let elapsed = now - self.playback.start_wall; + let mut target = self.playback.start_frame + (elapsed * fr.as_f64()).floor() as i64; + if target > wb { + if self.ui.preview_loop { + target = wa + (target - wa).rem_euclid((wb - wa + 1).max(1)); + } else { + self.session.set_time(fr.tick_of(wb)); + self.stop(); + return; + } + } + let key = self.frame_key(cid, target, scale); + if self.frames.is_cached(&key) { + self.playback.waiting = false; + if target != cur { + self.session.set_time(fr.tick_of(target)); + self.playback.shown += 1; + } + } else { + // Not cached yet: hold the clock at the current frame (cache first, then play). + self.playback.waiting = true; + let next = cur + 1; + let next = if next > wb { wa } else { next }; + if self.frames.is_cached(&self.frame_key(cid, next, scale)) { + self.session.set_time(fr.tick_of(next)); + } + self.playback.start_wall = now; + self.playback.start_frame = fr.frame_at(self.session.time()); + } + ctx.request_repaint(); + } + + fn frames_parallelism(&self) -> usize { + std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4) + } + + // ---------------------------------------------------------------- control channel + + pub(crate) fn raise_for_control(&mut self, ctx: &egui::Context) { + ctx.request_repaint(); + } + + fn drain_control(&mut self, ctx: &egui::Context) { + let Some(rx) = self.control_rx.take() else { return }; + let now = ctx.input(|i| i.time); + let mut reqs: Vec<(ControlRequest, f64)> = std::mem::take(&mut self.deferred); + while let Ok(req) = rx.try_recv() { + reqs.push((req, now + 3.0)); + } + for (req, deadline) in reqs { + let reply = req.reply.clone(); + match control::handle(self, ctx, &req) { + control::Outcome::Done(v) => { + let _ = reply.send(v); + } + control::Outcome::Retry(msg) => { + if now < deadline { + self.deferred.push((req, deadline)); + ctx.request_repaint(); + } else { + let _ = reply.send(json!({"ok": false, "error": msg})); + } + } + control::Outcome::AfterInput => self.input_waiters.push(reply), + control::Outcome::Screenshot { path, crop } => { + let token = self.next_token; + self.next_token += 1; + let settle = now + 0.35; + self.queued_screenshots.push((token, settle, 0)); + self.pending_screenshots.push((token, path, crop, reply, settle + SCREENSHOT_TIMEOUT_S)); + } + } + } + self.control_rx = Some(rx); + } + + fn issue_screenshots(&mut self, ctx: &egui::Context) { + let now = ctx.input(|i| i.time); + let mut any = false; + let busy = self.frames.inflight() > 0; + self.queued_screenshots.retain_mut(|(token, at, frames)| { + *frames += 1; + any = true; + // Wait for the viewer's frame to finish rendering (bounded by the timeout below). + if now >= *at && *frames >= 3 && (!busy || now > *at + 2.5) { + ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(*token))); + false + } else { + true + } + }); + self.pending_screenshots.retain(|(.., reply, deadline)| { + if now > *deadline { + let _ = reply.send(json!({"ok": false, "error": "no frame was presented (window hidden or display asleep)"})); + false + } else { + true + } + }); + if any { + ctx.request_repaint(); + } else if !self.pending_screenshots.is_empty() { + ctx.request_repaint_after(std::time::Duration::from_millis(16)); + } + } + + fn collect_screenshots(&mut self, ctx: &egui::Context) { + if self.pending_screenshots.is_empty() { + return; + } + let events: Vec<_> = ctx.input(|i| { + i.raw + .events + .iter() + .filter_map(|e| match e { + egui::Event::Screenshot { user_data, image, .. } => { + let token = user_data.data.as_ref().and_then(|d| d.downcast_ref::()).copied()?; + Some((token, image.clone())) + } + _ => None, + }) + .collect() + }); + for (token, image) in events { + if let Some(i) = self.pending_screenshots.iter().position(|(t, ..)| *t == token) { + let (_, path, crop, reply, _) = self.pending_screenshots.remove(i); + let r = control::save_screenshot(ctx, &image, path.as_deref(), crop); + let _ = reply.send(r); + } + } + } + + // ---------------------------------------------------------------- frame + + fn handle_events(&mut self, ctx: &egui::Context) { + for ev in self.session.drain_events() { + match ev { + effectcraft_engine::Event::OpenComp(_) => { + self.ui.dock.activate(PanelKind::Composition); + self.ui.timeline.pps = None; + } + effectcraft_engine::Event::Toast { message, .. } => self.toast = Some((message, ctx.input(|i| i.time))), + effectcraft_engine::Event::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), + effectcraft_engine::Event::ProjectChanged { .. } => {} + } + } + } + + fn frame(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + self.auto.begin_frame(); + self.frames.set_context(&ctx); + self.handle_events(&ctx); + if let Some(rx) = self.command_inbox.take() { + while let Ok(id) = rx.try_recv() { + if let Err(e) = menus::invoke(self, &ctx, &id, json!({})) { + self.ui.status = e; + } + } + self.command_inbox = Some(rx); + } + menus::handle_shortcuts(self, &ctx); + let t = self.tokens; + let full = ui.max_rect(); + ui.painter().rect_filled(full, 0.0, t.app_bg); + let mut top = full.min.y; + if self.ui.show_menu_bar { + let mb = egui::Rect::from_min_size(full.min, egui::vec2(full.width(), 24.0)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(mb)); + child.painter().rect_filled(mb, 0.0, t.header_bg); + menus::menu_bar(self, &mut child); + top = mb.max.y; + } + let header_h = 40.0; + let header = egui::Rect::from_min_size(egui::pos2(full.min.x, top), egui::vec2(full.width(), header_h)); + header::show(self, ui, header); + let body = egui::Rect::from_min_max(egui::pos2(full.min.x + 4.0, header.max.y + 2.0), egui::pos2(full.max.x - 4.0, full.max.y - 4.0)); + self.dock_area(ui, body); + panels::dialogs::show(self, &ctx); + self.draw_toast(ui, full); + } + + fn draw_toast(&mut self, ui: &mut egui::Ui, full: egui::Rect) { + let now = ui.input(|i| i.time); + let msg = if !self.ui.status.is_empty() { + Some(self.ui.status.clone()) + } else { + self.toast.as_ref().filter(|(_, at)| now - at < 4.0).map(|(m, _)| m.clone()) + }; + if let Some(m) = msg { + let t = &self.tokens; + let galley = ui.painter().layout_no_wrap(m, Tokens::ui(12.0), t.text); + let r = egui::Rect::from_min_size(egui::pos2(full.min.x + 16.0, full.max.y - 44.0), galley.size() + egui::vec2(24.0, 14.0)); + ui.painter().rect_filled(r, 6.0, egui::Color32::from_rgba_premultiplied(30, 30, 30, 235)); + ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + ui.painter().galley(r.min + egui::vec2(12.0, 7.0), galley, t.text); + let resp = ui.interact(r, egui::Id::new("toast"), egui::Sense::click()); + if resp.clicked() { + self.ui.status.clear(); + self.toast = None; + } + ui.ctx().request_repaint_after(std::time::Duration::from_millis(500)); + if !self.ui.status.is_empty() { + let since: f64 = ui.data(|d| d.get_temp(egui::Id::new("status-since")).unwrap_or(now)); + ui.data_mut(|d| d.insert_temp(egui::Id::new("status-since"), since)); + if now - since > 5.0 { + self.ui.status.clear(); + ui.data_mut(|d| d.remove::(egui::Id::new("status-since"))); + } + } + } + } + + fn dock_area(&mut self, ui: &mut egui::Ui, body: egui::Rect) { + let t = self.tokens; + let mut dock = std::mem::replace(&mut self.ui.dock, dock::DockNode::Tabs { panels: vec![], active: 0 }); + let mut groups = Vec::new(); + dock::layout(ui, &mut dock, body, &t, "", &mut groups, &mut self.auto); + let mut actions = Vec::new(); + for g in &groups { + actions.extend(dock::draw_group_chrome(ui, g, self.ui.focused, &t, &mut self.auto)); + } + self.ui.dock = dock; + for g in &groups { + let Some(p) = g.panels.get(g.active).copied() else { continue }; + self.auto.add(&format!("panel.{}", p.id()), g.content, p.title()); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(g.content).id_salt(("panel", p.id()))); + child.set_clip_rect(g.content.intersect(ui.clip_rect())); + panels::show(self, &mut child, p, g.content); + } + for a in actions { + match a { + dock::DockAction::Activate(p) => { + self.ui.dock.activate(p); + } + dock::DockAction::Focus(p) => self.ui.focused = p, + dock::DockAction::Close(p) => self.ui.dock.close(p), + dock::DockAction::PanelMenu(p, pos) => { + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("panel-menu"), (p, pos))); + } + } + } + panels::panel_menu_popup(self, ui); + } +} + +impl eframe::App for EffectcraftApp { + fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) { + if !self.synthetic.is_empty() { + // Pointer events go one per frame so egui sees press → moves → release as a real drag. + let pointer = |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. }); + let n = if pointer(&self.synthetic[0]) { + 1 + } else { + self.synthetic + .iter() + .position(|e| pointer(e) || matches!(e, egui::Event::Key { pressed: false, .. })) + .map_or(self.synthetic.len(), |i| if pointer(&self.synthetic[i]) { i.max(1) } else { i + 1 }) + }; + raw_input.events.extend(self.synthetic.drain(..n)); + } + } + + fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + if !self.styled { + theme::install(ctx, &self.tokens); + self.styled = true; + ctx.request_repaint(); + } else { + self.fonts_ready = true; + } + let now = ctx.input(|i| i.time); + let dt = (now - self.last_time) as f32; + if dt > 0.0 { + self.fps = self.fps * 0.9 + (1.0 / dt).min(480.0) * 0.1; + } + self.last_time = now; + self.drain_control(ctx); + if !self.synthetic.is_empty() { + ctx.request_repaint(); + } else if !self.input_waiters.is_empty() { + for w in self.input_waiters.drain(..) { + let _ = w.send(json!({"ok": true, "result": null})); + } + } + self.issue_screenshots(ctx); + self.collect_screenshots(ctx); + } + + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + if !self.fonts_ready { + ui.ctx().request_repaint(); + return; + } + self.frame(ui); + let ctx = ui.ctx().clone(); + self.last_ui_time = ctx.input(|i| i.time); + if !self.synthetic.is_empty() { + ctx.request_repaint(); + } else if !self.input_waiters.is_empty() { + ctx.request_repaint(); + for w in self.input_waiters.drain(..) { + let _ = w.send(json!({"ok": true, "result": null})); + } + } + if self.frames.inflight() > 0 { + ctx.request_repaint_after(std::time::Duration::from_millis(30)); + } + } +} + +/// Advance playback with the viewer's scale (called by the viewer panel each frame). +pub(crate) fn tick_playback(app: &mut EffectcraftApp, ctx: &egui::Context, scale: f64) { + app.advance_playback(ctx, scale); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs new file mode 100644 index 00000000..321cee16 --- /dev/null +++ b/crates/ui-egui/src/menus.rs @@ -0,0 +1,561 @@ +//! Menus, keyboard shortcuts and UI-level commands. The menu bar is generated from the engine +//! registry plus the UI command table (commands that only affect the frontend: tools, playback, +//! viewer zoom, panels, reveal shortcuts). `invoke` is the single entry point used by menus, +//! shortcuts and the control channel. + +use serde_json::{Value, json}; + +use crate::EffectcraftApp; +use crate::dock::PanelKind; +use crate::state::{Resolution, Tool}; + +pub struct UiCommand { + pub id: &'static str, + pub label: &'static str, + pub menu: &'static [&'static str], + pub shortcut: Option<&'static str>, +} + +macro_rules! uic { + ($id:literal, $label:literal, [$($m:literal),*], $sc:expr) => { + UiCommand { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc } + }; +} + +pub const UI_COMMANDS: &[UiCommand] = &[ + uic!("playback.toggle", "Play/Stop", ["Composition", "Preview"], Some("Space")), + uic!("playback.ramPreview", "Play Current Preview", ["Composition", "Preview"], Some("Num0")), + uic!("playback.stop", "Stop", [], None), + uic!("view.zoomIn", "Zoom In", ["View"], Some(".")), + uic!("view.zoomOut", "Zoom Out", ["View"], Some(",")), + uic!("view.fit", "Fit", ["View"], Some("Shift+/")), + uic!("view.actualSize", "100%", ["View"], Some("/")), + uic!("view.res.full", "Full", ["View", "Resolution"], Some("Cmd+J")), + uic!("view.res.half", "Half", ["View", "Resolution"], Some("Cmd+Shift+J")), + uic!("view.res.third", "Third", ["View", "Resolution"], None), + uic!("view.res.quarter", "Quarter", ["View", "Resolution"], Some("Cmd+Alt+Shift+J")), + uic!("view.res.auto", "Auto", ["View", "Resolution"], None), + uic!("view.rulers", "Show Rulers", ["View"], Some("Cmd+R")), + uic!("view.grid", "Show Grid", ["View"], Some("Cmd+'")), + uic!("view.safeMargins", "Title/Action Safe", ["View"], None), + uic!("view.transparencyGrid", "Transparency Grid", ["View"], None), + uic!("view.layerControls", "Show Layer Controls", ["View"], Some("Cmd+Shift+H")), + uic!("view.fastPreviews", "Fast Previews", ["View"], None), + uic!("view.theme.dark", "Dark", ["View", "Appearance"], None), + uic!("view.theme.darker", "Darker", ["View", "Appearance"], None), + uic!("view.theme.light", "Light", ["View", "Appearance"], None), + uic!("timeline.zoomIn", "Zoom In Time", [], Some("=")), + uic!("timeline.zoomOut", "Zoom Out Time", [], Some("-")), + uic!("timeline.zoomFit", "Zoom to Fit Comp", [], Some(";")), + uic!("timeline.graphEditor", "Graph Editor", ["Window"], Some("Shift+F3")), + uic!("timeline.switchesModes", "Toggle Switches / Modes", [], Some("F4")), + uic!("timeline.workAreaBegin", "Set Work Area Begin", [], Some("B")), + uic!("timeline.workAreaEnd", "Set Work Area End", [], Some("N")), + uic!("timeline.moveInToTime", "Move Layer In Point to Current Time", [], Some("[")), + uic!("timeline.moveOutToTime", "Move Layer Out Point to Current Time", [], Some("]")), + uic!("timeline.trimInToTime", "Trim Layer In Point to Current Time", [], Some("Alt+[")), + uic!("timeline.trimOutToTime", "Trim Layer Out Point to Current Time", [], Some("Alt+]")), + uic!("timeline.reveal.position", "Reveal Position", [], Some("P")), + uic!("timeline.reveal.scale", "Reveal Scale", [], Some("S")), + uic!("timeline.reveal.rotation", "Reveal Rotation", [], Some("R")), + uic!("timeline.reveal.opacity", "Reveal Opacity", [], Some("T")), + uic!("timeline.reveal.anchor", "Reveal Anchor Point", [], Some("A")), + uic!("timeline.reveal.animated", "Reveal Animated Properties", ["Animation"], Some("U")), + uic!("timeline.reveal.effects", "Reveal Effects", [], Some("E")), + uic!("timeline.reveal.masks", "Reveal Masks", [], Some("M")), + uic!("timeline.reveal.feather", "Reveal Mask Feather", [], Some("F")), + uic!("timeline.collapseAll", "Collapse All", [], Some("Cmd+`")), + uic!("window.workspace.default", "Default", ["Window", "Workspace"], Some("Shift+F10")), + uic!("window.workspace.standard", "Standard", ["Window", "Workspace"], Some("Shift+F11")), + uic!("window.workspace.smallscreen", "Small Screen", ["Window", "Workspace"], Some("Shift+F12")), + uic!("window.workspace.animation", "Animation", ["Window", "Workspace"], None), + uic!("window.workspace.effects", "Effects", ["Window", "Workspace"], None), + uic!("window.workspace.motiontracking", "Motion Tracking", ["Window", "Workspace"], None), + uic!("window.workspace.paint", "Paint", ["Window", "Workspace"], None), + uic!("window.workspace.text", "Text", ["Window", "Workspace"], None), + uic!("window.workspace.minimal", "Minimal", ["Window", "Workspace"], None), + uic!("window.workspace.allpanels", "All Panels", ["Window", "Workspace"], None), + uic!("window.workspace.reset", "Reset to Saved Layout", ["Window", "Workspace"], None), + uic!("tool.selection", "Selection Tool", [], Some("V")), + uic!("tool.hand", "Hand Tool", [], Some("H")), + uic!("tool.zoom", "Zoom Tool", [], Some("Z")), + uic!("tool.orbit", "Orbit Tool", [], Some("1")), + uic!("tool.panCamera", "Pan Camera Tool", [], Some("2")), + uic!("tool.dolly", "Dolly Tool", [], Some("3")), + uic!("tool.rotate", "Rotation Tool", [], Some("W")), + uic!("tool.panBehind", "Pan Behind Tool", [], Some("Y")), + uic!("tool.shape", "Shape Tools", [], Some("Q")), + uic!("tool.pen", "Pen Tool", [], Some("G")), + uic!("tool.type", "Type Tools", [], Some("Cmd+T")), + uic!("tool.brush", "Brush Tools", [], Some("Cmd+B")), + uic!("tool.rotoBrush", "Roto Brush Tool", [], Some("Alt+W")), + uic!("tool.puppet", "Puppet Tools", [], Some("Cmd+P")), + uic!("app.newComp", "New Composition…", [], None), + uic!("app.compSettings", "Composition Settings…", [], None), + uic!("app.solidSettings", "New Solid…", [], None), + uic!("app.commandPalette", "Command Palette…", ["Window"], Some("Cmd+Shift+P")), + uic!("app.about", "About EffectCraft", ["Help"], None), + uic!("app.home", "Home", ["Window"], None), +]; + +pub fn panel_command_id(p: PanelKind) -> String { + format!("window.panel.{}", p.id()) +} + +fn reveal(app: &mut EffectcraftApp, kind: &str) { + let add = app.ui.timeline.reveal.contains(&kind.to_string()); + if add && app.ui.timeline.reveal.len() == 1 { + app.ui.timeline.reveal.clear(); + app.ui.timeline.open_layers.clear(); + return; + } + app.ui.timeline.reveal = vec![kind.to_string()]; + let sel = if app.session.state.selected_layers.is_empty() { + app.session.active_comp().map(|c| c.layers.iter().map(|l| l.id).collect()).unwrap_or_default() + } else { + app.session.state.selected_layers.clone() + }; + app.ui.timeline.open_layers = sel.iter().map(|l| l.0).collect(); +} + +/// Execute a UI or engine command by id. +pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { + let now = ctx.input(|i| i.time); + if let Some(rest) = id.strip_prefix("window.panel.") { + let p = PanelKind::from_name(rest).ok_or_else(|| format!("unknown panel `{rest}`"))?; + app.show_panel(p); + return Ok(Value::Null); + } + if let Some(ws) = id.strip_prefix("window.workspace.") { + if ws == "reset" { + let name = app.ui.workspace.clone(); + app.set_workspace(&name); + return Ok(Value::Null); + } + let name = crate::dock::WORKSPACES.iter().find(|w| w.to_ascii_lowercase().replace(' ', "") == ws).ok_or_else(|| format!("unknown workspace `{ws}`"))?; + app.set_workspace(name); + return Ok(json!({"workspace": name})); + } + if let Some(t) = id.strip_prefix("tool.") { + // Slot shortcuts cycle through the slot's tools. + let slot = match t { + "shape" => Some(8), + "type" => Some(10), + "brush" => Some(11), + _ => None, + }; + if let Some(si) = slot { + let tools: Vec = 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(k) = id.strip_prefix("timeline.reveal.") { + reveal(app, k); + return Ok(Value::Null); + } + if let Some(r) = id.strip_prefix("view.res.") { + app.ui.viewer.res = Resolution::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r)).ok_or("unknown resolution")?; + return Ok(Value::Null); + } + 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.toggle" | "playback.ramPreview" => { + app.toggle_play(now); + return Ok(json!({"playing": app.playback.playing})); + } + "playback.stop" => { + app.stop(); + return Ok(Value::Null); + } + "view.zoomIn" | "view.zoomOut" => { + let cur = app.ui.viewer.zoom.unwrap_or_else(|| crate::panels::viewer::last_fit(ctx)); + const STEPS: [f32; 16] = [0.015, 0.03, 0.0625, 0.125, 0.25, 0.333, 0.5, 0.66, 1.0, 1.5, 2.0, 3.0, 4.0, 8.0, 16.0, 32.0]; + let next = if id == "view.zoomIn" { + STEPS.iter().copied().find(|s| *s > cur + 1e-3).unwrap_or(32.0) + } else { + STEPS.iter().rev().copied().find(|s| *s < cur - 1e-3).unwrap_or(0.015) + }; + app.ui.viewer.zoom = Some(next); + return Ok(json!({"zoom": next})); + } + "view.fit" => { + app.ui.viewer.zoom = None; + app.ui.viewer.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.rulers" => app.ui.viewer.rulers = !app.ui.viewer.rulers, + "view.grid" => app.ui.viewer.grid = !app.ui.viewer.grid, + "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.layerControls" => app.ui.viewer.show_layer_controls = !app.ui.viewer.show_layer_controls, + "view.fastPreviews" => app.ui.viewer.fast_preview = !app.ui.viewer.fast_preview, + "timeline.zoomIn" | "timeline.zoomOut" => { + let k = if id == "timeline.zoomIn" { 1.5 } else { 1.0 / 1.5 }; + crate::panels::timeline::zoom(app, ctx, k); + return Ok(Value::Null); + } + "timeline.zoomFit" => app.ui.timeline.pps = None, + "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(); + } + "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.about" => app.dialog = Some(crate::Dialog::About), + "app.home" => app.ui.start_screen = !app.ui.start_screen, + "app.commandPalette" => { + app.dialog_state.palette_query.clear(); + app.dialog = Some(crate::Dialog::CommandPalette); + } + "app.newComp" | "comp.new" if params.as_object().is_none_or(|m| m.is_empty()) => { + crate::panels::dialogs::open_new_comp(app); + } + "app.compSettings" | "comp.settings" if params.as_object().is_none_or(|m| m.is_empty()) => { + crate::panels::dialogs::open_comp_settings(app)?; + } + "app.solidSettings" | "layer.newSolid" if params.as_object().is_none_or(|m| m.is_empty()) => { + crate::panels::dialogs::open_new_solid(app)?; + } + _ => { + if (id == "file.import" && params.get("paths").is_none() && params.get("path").is_none()) + || (id == "file.saveAs" && params.get("path").is_none()) + || (id == "file.open" && params.get("path").is_none()) + || (id == "file.save" && params.get("path").is_none() && app.session.path.is_none()) + { + return file_dialog(app, id); + } + if id == "layer.rename" && params.get("name").is_none() { + crate::panels::timeline::begin_rename(app, ctx); + return Ok(Value::Null); + } + let r = app.session.execute(id, params).map_err(|e| e.to_string()); + if let Err(e) = &r { + app.ui.status = e.clone(); + } + return r; + } + } + Ok(Value::Null) +} + +fn file_dialog(app: &mut EffectcraftApp, id: &str) -> Result { + match id { + "file.import" => { + let f = app.hooks.pick_files.as_ref().ok_or("no file dialog available (pass `paths`)")?; + let paths = f(&[ + "mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "wav", "aif", "aiff", "mp3", "flac", + "ogg", "opus", "svg", + ]); + if paths.is_empty() { + return Ok(Value::Null); + } + app.session.execute("file.import", json!({"paths": paths})).map_err(|e| e.to_string()) + } + "file.open" => { + let f = app.hooks.pick_open_project.as_ref().ok_or("no file dialog available (pass `path`)")?; + match f() { + Some(p) => app.session.execute("file.open", json!({"path": p})).map_err(|e| e.to_string()), + None => Ok(Value::Null), + } + } + _ => { + let f = app.hooks.pick_save.as_ref().ok_or("no file dialog available (pass `path`)")?; + match f("Untitled Project.ecproj") { + Some(p) => app.session.execute("file.saveAs", json!({"path": p})).map_err(|e| e.to_string()), + None => Ok(Value::Null), + } + } + } +} + +/// A menu entry for display / `ui.menu.list`. +#[derive(Clone, Debug, serde::Serialize)] +pub struct MenuItem { + pub id: String, + pub label: String, + pub path: Vec, + pub shortcut: Option, + pub enabled: bool, + /// Parameters bound to the entry (e.g. the effect for Effect menu items). + #[serde(skip_serializing_if = "Value::is_null")] + pub params: Value, +} + +pub const MENUS: [&str; 9] = ["File", "Edit", "Composition", "Layer", "Effect", "Animation", "View", "Window", "Help"]; + +pub fn menu_items(app: &EffectcraftApp) -> Vec { + let mut out = Vec::new(); + for c in effectcraft_engine::command_specs() { + if c.menu.is_empty() { + continue; + } + out.push(MenuItem { + id: c.id.into(), + label: c.label.into(), + path: c.menu.iter().map(|s| s.to_string()).collect(), + shortcut: c.shortcut.map(str::to_string), + enabled: app.session.is_enabled(c.id), + params: Value::Null, + }); + } + for c in UI_COMMANDS { + if c.menu.is_empty() { + continue; + } + out.push(MenuItem { + id: c.id.into(), + label: c.label.into(), + path: c.menu.iter().map(|s| s.to_string()).collect(), + shortcut: c.shortcut.map(str::to_string), + enabled: true, + params: Value::Null, + }); + } + for p in PanelKind::ALL { + out.push(MenuItem { + id: panel_command_id(p), + label: p.title().into(), + path: vec!["Window".into()], + shortcut: p.window_shortcut().map(str::to_string), + enabled: true, + params: Value::Null, + }); + } + let has_layer = !app.session.state.selected_layers.is_empty(); + for e in effectcraft_engine::effects::registry() { + out.push(MenuItem { + id: "effect.apply".into(), + label: e.name.into(), + path: vec!["Effect".into(), e.category.into()], + shortcut: None, + enabled: has_layer, + params: json!({"effect": e.id}), + }); + } + out +} + +/// Shortcut text in this OS's notation (`⇧⌘K` on macOS, `Ctrl+Shift+K` elsewhere). +pub fn shortcut_text(s: &str) -> String { + if cfg!(target_os = "macos") { + let mut out = String::new(); + let parts: Vec<&str> = s.split('+').collect(); + let (mods, key) = parts.split_at(parts.len().saturating_sub(1)); + for m in mods { + out.push_str(match *m { + "Ctrl" => "⌃", + "Alt" => "⌥", + "Shift" => "⇧", + "Cmd" => "⌘", + x => x, + }); + } + out.push_str(key.first().copied().unwrap_or("")); + out + } else { + s.replace("Cmd", "Ctrl") + } +} + +/// Parse "Cmd+Shift+K" into modifiers + key. +pub fn parse_shortcut(s: &str) -> Option<(egui::Modifiers, egui::Key)> { + let mut m = egui::Modifiers::NONE; + let mut key = None; + let parts: Vec<&str> = if s == "+" { vec!["+"] } else { s.split('+').collect() }; + for p in parts { + match p { + "Cmd" => { + m.command = true; + m.mac_cmd = cfg!(target_os = "macos"); + if !cfg!(target_os = "macos") { + m.ctrl = true; + } + } + "Shift" => m.shift = true, + "Alt" => m.alt = true, + "Ctrl" => m.ctrl = true, + k => { + key = match k { + ";" => Some(egui::Key::Semicolon), + "'" => Some(egui::Key::Quote), + "," => Some(egui::Key::Comma), + "." => Some(egui::Key::Period), + "/" => Some(egui::Key::Slash), + "\\" => Some(egui::Key::Backslash), + "=" => Some(egui::Key::Equals), + "-" => Some(egui::Key::Minus), + "`" => Some(egui::Key::Backtick), + "[" => Some(egui::Key::OpenBracket), + "]" => Some(egui::Key::CloseBracket), + "Num0" => Some(egui::Key::Num0), + "Num*" => None, + _ => egui::Key::from_name(k), + } + } + } + } + key.map(|k| (m, k)) +} + +/// All active bindings, most modifiers first. +pub fn bindings() -> Vec<(egui::Modifiers, egui::Key, String)> { + let mut v: Vec<(egui::Modifiers, egui::Key, String)> = Vec::new(); + for c in effectcraft_engine::command_specs() { + if let Some((m, k)) = c.shortcut.and_then(parse_shortcut) { + v.push((m, k, c.id.to_string())); + } + } + for c in UI_COMMANDS { + if let Some((m, k)) = c.shortcut.and_then(parse_shortcut) { + v.push((m, k, c.id.to_string())); + } + } + for p in PanelKind::ALL { + if let Some((m, k)) = p.window_shortcut().and_then(parse_shortcut) { + v.push((m, k, panel_command_id(p))); + } + } + v.sort_by_key(|(m, ..)| std::cmp::Reverse(m.command as u8 + m.shift as u8 + m.alt as u8 + m.ctrl as u8)); + v +} + +fn mods_match(want: egui::Modifiers, got: egui::Modifiers) -> bool { + want.command == got.command && want.shift == got.shift && want.alt == got.alt && (want.ctrl == got.ctrl || got.command && cfg!(not(target_os = "macos"))) +} + +/// Dispatch keyboard shortcuts (skipped while typing in a text field). +pub fn handle_shortcuts(app: &mut EffectcraftApp, ctx: &egui::Context) { + if ctx.egui_wants_keyboard_input() { + return; + } + let events: Vec<(egui::Key, egui::Modifiers)> = ctx.input(|i| { + i.events + .iter() + .filter_map(|e| match e { + egui::Event::Key { key, pressed: true, modifiers, repeat, .. } + if !*repeat || matches!(key, egui::Key::PageUp | egui::Key::PageDown | egui::Key::ArrowLeft | egui::Key::ArrowRight) => + { + Some((*key, *modifiers)) + } + _ => None, + }) + .collect() + }); + if events.is_empty() { + return; + } + let binds = bindings(); + for (key, mods) in events { + // Escape closes dialogs. + if key == egui::Key::Escape && app.dialog.is_some() { + app.dialog = None; + continue; + } + if app.dialog.is_some() { + continue; + } + // Delete/Backspace clears selection. + if matches!(key, egui::Key::Delete | egui::Key::Backspace) && !mods.any() { + let _ = invoke(app, ctx, "edit.clear", json!({})); + continue; + } + if let Some((_, _, id)) = binds.iter().find(|(m, k, _)| *k == key && mods_match(*m, mods)) { + let id = id.clone(); + if let Err(e) = invoke(app, ctx, &id, json!({})) { + app.ui.status = e; + } + } + } +} + +/// Draw the in-window menu bar. +pub fn menu_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui) { + let items = menu_items(app); + let ctx = ui.ctx().clone(); + let mut clicked: Option<(String, Value)> = None; + ui.horizontal_centered(|ui| { + ui.add_space(6.0); + egui::MenuBar::new().ui(ui, |ui| { + for top in MENUS { + let mine: Vec<&MenuItem> = items.iter().filter(|i| i.path.first().map(String::as_str) == Some(top)).collect(); + ui.menu_button(top, |ui| { + ui.set_min_width(260.0); + let mut subs: Vec<&str> = Vec::new(); + let mut last_was_sub = false; + for it in &mine { + if it.path.len() > 1 { + let sub = it.path[1].as_str(); + if !subs.contains(&sub) { + subs.push(sub); + ui.menu_button(sub, |ui| { + ui.set_min_width(220.0); + for s in mine.iter().filter(|x| x.path.get(1).map(String::as_str) == Some(sub)) { + if menu_entry(ui, s) { + clicked = Some((s.id.clone(), s.params.clone())); + ui.close(); + } + } + }); + last_was_sub = true; + } + } else { + if last_was_sub && top != "Effect" { + ui.separator(); + last_was_sub = false; + } + if menu_entry(ui, it) { + clicked = Some((it.id.clone(), it.params.clone())); + ui.close(); + } + } + } + }); + } + }); + }); + if let Some((id, params)) = clicked + && let Err(e) = invoke(app, &ctx, &id, if params.is_null() { json!({}) } else { params }) + { + app.ui.status = e; + } +} + +fn menu_entry(ui: &mut egui::Ui, it: &MenuItem) -> bool { + let mut b = egui::Button::new(&it.label); + if let Some(s) = &it.shortcut { + b = b.shortcut_text(shortcut_text(s)); + } + ui.add_enabled(it.enabled, b).clicked() +} diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs new file mode 100644 index 00000000..87a2a2cf --- /dev/null +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -0,0 +1,387 @@ +//! Modal dialogs: About (with community links), New Composition / Composition Settings, Solid +//! Settings and the command palette. + +use egui::{Align2, Color32, Rect, Sense, pos2, vec2}; +use serde_json::json; + +use crate::icons::{self, Icon}; +use crate::theme::Tokens; +use crate::{Dialog, EffectcraftApp, widgets}; + +#[derive(Clone, Debug)] +pub struct CompDraft { + pub name: String, + pub width: u32, + pub height: u32, + pub fps: f64, + pub duration: f64, + pub bg: [f32; 3], + pub lock_aspect: bool, +} + +impl Default for CompDraft { + fn default() -> Self { + CompDraft { name: "Comp 1".into(), width: 1920, height: 1080, fps: 29.97, duration: 10.0, bg: [0.0, 0.0, 0.0], lock_aspect: true } + } +} + +#[derive(Clone, Debug, Default)] +pub struct DialogState { + pub comp: CompDraft, + pub editing_existing: bool, + pub solid_name: String, + pub solid_color: [f32; 3], + pub solid_size: [u32; 2], + pub palette_query: String, + pub palette_sel: usize, +} + +pub fn open_new_comp(app: &mut EffectcraftApp) { + let n = app.session.project.comps().count() + 1; + app.dialog_state.comp = CompDraft { name: format!("Comp {n}"), ..Default::default() }; + app.dialog_state.editing_existing = false; + app.dialog = Some(Dialog::NewComp); +} + +pub fn open_comp_settings(app: &mut EffectcraftApp) -> Result<(), String> { + let cid = app.session.active_comp_id().ok_or("no composition is open")?; + let c = app.session.project.comp(cid).ok_or("no composition")?; + app.dialog_state.comp = CompDraft { + name: app.session.project.item(cid).map(|i| i.name.clone()).unwrap_or_default(), + width: c.width, + height: c.height, + fps: c.frame_rate.as_f64(), + duration: c.duration.seconds(), + bg: c.background, + lock_aspect: true, + }; + app.dialog_state.editing_existing = true; + app.dialog = Some(Dialog::CompSettings); + Ok(()) +} + +pub fn open_new_solid(app: &mut EffectcraftApp) -> Result<(), String> { + let c = app.session.active_comp().ok_or("no composition is open")?; + let n = app.session.project.items.values().filter(|i| matches!(i.kind, effectcraft_engine::project::ItemKind::Solid(_))).count() + 1; + app.dialog_state.solid_name = format!("Solid {n}"); + app.dialog_state.solid_size = [c.width, c.height]; + if app.dialog_state.solid_color == [0.0; 3] { + app.dialog_state.solid_color = [0.2, 0.45, 0.85]; + } + app.dialog = Some(Dialog::SolidSettings); + Ok(()) +} + +fn modal(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui)) { + // Dim the app. + let screen = ctx.content_rect(); + ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("modal-dim"))).rect_filled(screen, 0.0, Color32::from_black_alpha(120)); + egui::Area::new(egui::Id::new(("modal", title))).order(egui::Order::Foreground).fixed_pos(screen.center() - size / 2.0).show(ctx, |ui| { + egui::Frame::window(ui.style()).fill(t.panel_bg).inner_margin(egui::Margin::same(18)).show(ui, |ui| { + ui.set_width(size.x - 36.0); + ui.set_min_height(size.y - 36.0); + ui.label(egui::RichText::new(title).font(Tokens::semibold(15.0)).color(t.tab_text_active)); + ui.add_space(10.0); + body(ui); + }); + }); +} + +pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context) { + let Some(d) = app.dialog else { return }; + let t = app.tokens; + match d { + Dialog::About => about(app, ctx, &t), + Dialog::NewComp | Dialog::CompSettings => comp_settings(app, ctx, &t, d == Dialog::CompSettings), + Dialog::SolidSettings => solid(app, ctx, &t), + Dialog::CommandPalette => palette(app, ctx, &t), + } +} + +fn about(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) { + let mut close = false; + let mut cmd: Option<&str> = None; + modal(ctx, "About EffectCraft", vec2(520.0, 400.0), t, |ui| { + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 96.0), Sense::hover()); + let p = ui.painter(); + p.rect_filled(r, 10.0, Color32::from_rgb(0x1b, 0x22, 0x3c)); + crate::header::paint_logo(p, Rect::from_min_size(r.min + vec2(18.0, 20.0), vec2(56.0, 56.0))); + p.text(r.min + vec2(90.0, 34.0), Align2::LEFT_CENTER, "EffectCraft", Tokens::semibold(24.0), Color32::WHITE); + p.text( + r.min + vec2(90.0, 62.0), + Align2::LEFT_CENTER, + format!("Version {} • Motion graphics & VFX in pure Rust", env!("CARGO_PKG_VERSION")), + Tokens::ui(12.0), + t.text_dim, + ); + ui.add_space(12.0); + ui.label("A clean-room, open-source compositor for motion graphics and visual effects: native on macOS, Windows and Linux, and in the browser. Part of the ArtCraft family of creative apps."); + ui.add_space(14.0); + let links: [(Icon, &str, &str, &str); 4] = [ + (Icon::Chat, "Join the ArtCraft Discord", effectcraft_engine::links::DISCORD, "help.discord"), + (Icon::Globe, "ArtCraft website", effectcraft_engine::links::WEBSITE, "help.website"), + (Icon::Sparkle, "EffectCraft home page", effectcraft_engine::links::APP_PAGE, "help.appPage"), + (Icon::Code, "Source code on GitHub", effectcraft_engine::links::GITHUB, "help.github"), + ]; + for (icon, label, url, c) in links { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click()); + let p = ui.painter(); + let discord = c == "help.discord"; + p.rect_filled( + r, + 6.0, + if discord { + Color32::from_rgb(0x58, 0x65, 0xf2) + } else if resp.hovered() { + t.hover + } else { + Color32::from_rgb(0x2b, 0x2b, 0x2b) + }, + ); + icons::paint(p, Rect::from_center_size(pos2(r.min.x + 18.0, r.center().y), vec2(15.0, 15.0)), icon, Color32::WHITE); + p.text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::medium(12.5), Color32::WHITE); + p.text( + pos2(r.max.x - 12.0, r.center().y), + Align2::RIGHT_CENTER, + url, + Tokens::ui(11.0), + if discord { Color32::from_white_alpha(200) } else { t.text_dim }, + ); + app.auto.add(&format!("about.{c}"), r, label); + if resp.clicked() { + cmd = Some(c); + } + ui.add_space(4.0); + } + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.label(egui::RichText::new("MIT OR Apache-2.0 • Fonts: Inter, JetBrains Mono (OFL)").small().color(t.text_faint)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Close").clicked() { + close = true; + } + }); + }); + }); + if let Some(c) = cmd { + let _ = app.session.execute(c, json!({})); + } + if close { + app.dialog = None; + } +} + +fn comp_settings(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens, existing: bool) { + let mut close = false; + let mut ok = false; + let mut d = app.dialog_state.comp.clone(); + modal(ctx, if existing { "Composition Settings" } else { "Composition Settings — New" }, vec2(520.0, 420.0), t, |ui| { + egui::Grid::new("comp-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| { + ui.label("Composition Name"); + ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(260.0)); + ui.end_row(); + ui.label("Preset"); + egui::ComboBox::from_id_salt("comp-preset").selected_text(format!("{}x{} {:.2}", d.width, d.height, d.fps)).show_ui(ui, |ui| { + for (label, w, h, f) in [ + ("HD · 1920x1080 · 29.97 fps", 1920, 1080, 29.97), + ("HD · 1920x1080 · 25 fps", 1920, 1080, 25.0), + ("HD · 1920x1080 · 23.976 fps", 1920, 1080, 23.976), + ("HD · 1280x720 · 29.97 fps", 1280, 720, 29.97), + ("UHD 4K · 3840x2160 · 29.97 fps", 3840, 2160, 29.97), + ("Social 9:16 · 1080x1920 · 30 fps", 1080, 1920, 30.0), + ("Social 1:1 · 1080x1080 · 30 fps", 1080, 1080, 30.0), + ("Social 4:5 · 1080x1350 · 30 fps", 1080, 1350, 30.0), + ("Cinema 4K · 4096x2160 · 24 fps", 4096, 2160, 24.0), + ] { + if ui.selectable_label(false, label).clicked() { + d.width = w; + d.height = h; + d.fps = f; + } + } + }); + ui.end_row(); + ui.label("Width / Height"); + ui.horizontal(|ui| { + let ow = d.width; + ui.add(egui::DragValue::new(&mut d.width).range(4..=30000).suffix(" px")); + ui.label("×"); + let oh = d.height; + ui.add(egui::DragValue::new(&mut d.height).range(4..=30000).suffix(" px")); + ui.checkbox(&mut d.lock_aspect, "Lock aspect"); + if d.lock_aspect && ow != d.width && ow > 0 { + d.height = ((d.width as f64) * oh as f64 / ow as f64).round().max(4.0) as u32; + } + }); + ui.end_row(); + ui.label("Frame Rate"); + egui::ComboBox::from_id_salt("comp-fps").selected_text(format!("{:.3}", d.fps).trim_end_matches('0').trim_end_matches('.').to_string()).show_ui( + ui, + |ui| { + for f in [23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 120.0] { + if ui.selectable_label((d.fps - f).abs() < 1e-3, format!("{f}")).clicked() { + d.fps = f; + } + } + }, + ); + ui.end_row(); + ui.label("Duration"); + ui.add(egui::DragValue::new(&mut d.duration).range(0.04..=86400.0).speed(0.1).suffix(" s")); + ui.end_row(); + ui.label("Background Color"); + ui.color_edit_button_rgb(&mut d.bg); + ui.end_row(); + }); + ui.add_space(18.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() { + ok = true; + } + if ui.button("Cancel").clicked() { + close = true; + } + }); + }); + }); + if ui_enter(ctx) { + ok = true; + } + app.dialog_state.comp = d.clone(); + if ok { + let params = json!({"name": d.name, "width": d.width, "height": d.height, "frameRate": d.fps, "duration": d.duration, "background": [d.bg[0], d.bg[1], d.bg[2]]}); + let r = if existing { app.session.execute("comp.settings", params) } else { app.session.execute("comp.new", params) }; + if let Err(e) = r { + app.ui.status = e.to_string(); + } + close = true; + } + if close { + app.dialog = None; + } +} + +fn ui_enter(ctx: &egui::Context) -> bool { + !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Enter)) +} + +fn solid(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) { + let mut close = false; + let mut ok = false; + let mut name = app.dialog_state.solid_name.clone(); + let mut col = app.dialog_state.solid_color; + let mut size = app.dialog_state.solid_size; + modal(ctx, "Solid Settings", vec2(420.0, 300.0), t, |ui| { + egui::Grid::new("solid-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| { + ui.label("Name"); + ui.add(egui::TextEdit::singleline(&mut name).desired_width(220.0)); + ui.end_row(); + ui.label("Size"); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut size[0]).range(1..=30000)); + ui.label("×"); + ui.add(egui::DragValue::new(&mut size[1]).range(1..=30000)); + }); + ui.end_row(); + ui.label("Color"); + ui.color_edit_button_rgb(&mut col); + ui.end_row(); + }); + ui.add_space(18.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() { + ok = true; + } + if ui.button("Cancel").clicked() { + close = true; + } + }); + }); + app.dialog_state.solid_name = name.clone(); + app.dialog_state.solid_color = col; + app.dialog_state.solid_size = size; + if ok || ui_enter(ctx) { + let _ = app.session.execute("layer.newSolid", json!({"name": name, "color": [col[0], col[1], col[2]], "width": size[0], "height": size[1]})); + close = true; + } + if close { + app.dialog = None; + } +} + +/// ⌘⇧P: fuzzy search over every command (engine + UI) and effect. +fn palette(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) { + let mut q = app.dialog_state.palette_query.clone(); + let mut run: Option<(String, serde_json::Value)> = None; + let mut close = false; + let items: Vec<(String, String, serde_json::Value, String)> = { + let mut v: Vec<(String, String, serde_json::Value, String)> = crate::menus::menu_items(app) + .into_iter() + .filter(|m| m.enabled) + .map(|m| (m.path.join(" ▸ ") + " ▸ " + &m.label, m.id, if m.params.is_null() { json!({}) } else { m.params }, m.shortcut.unwrap_or_default())) + .collect(); + for c in effectcraft_engine::command_specs().iter().filter(|c| c.menu.is_empty() && c.journal && c.params == "{}") { + if app.session.is_enabled(c.id) { + v.push((c.label.to_string(), c.id.to_string(), json!({}), c.shortcut.unwrap_or("").to_string())); + } + } + v + }; + let ql = q.to_lowercase(); + let matches: Vec<&(String, String, serde_json::Value, String)> = items + .iter() + .filter(|(label, id, ..)| { + let hay = format!("{} {}", label.to_lowercase(), id.to_lowercase()); + ql.split_whitespace().all(|w| hay.contains(w)) + }) + .take(14) + .collect(); + modal(ctx, "Command Palette", vec2(560.0, 470.0), t, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut q).hint_text("Type a command or effect…").desired_width(f32::INFINITY).font(Tokens::ui(14.0))); + r.request_focus(); + ui.add_space(8.0); + let sel = app.dialog_state.palette_sel.min(matches.len().saturating_sub(1)); + for (i, (label, id, params, sc)) in matches.iter().enumerate() { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click()); + let p = ui.painter(); + if i == sel || resp.hovered() { + p.rect_filled(r, 4.0, if i == sel { t.row_selected } else { t.hover }); + } + p.text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::ui(12.5), t.text); + if !sc.is_empty() { + p.text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, crate::menus::shortcut_text(sc), Tokens::ui(11.0), t.text_dim); + } + if resp.clicked() { + run = Some((id.clone(), (*params).clone())); + } + } + }); + let (down, up, enter) = ctx.input(|i| (i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::Enter))); + if down { + app.dialog_state.palette_sel = (app.dialog_state.palette_sel + 1).min(matches.len().saturating_sub(1)); + } + if up { + app.dialog_state.palette_sel = app.dialog_state.palette_sel.saturating_sub(1); + } + if enter && let Some((_, id, params, _)) = matches.get(app.dialog_state.palette_sel) { + run = Some((id.clone(), (*params).clone())); + } + if q != app.dialog_state.palette_query { + app.dialog_state.palette_sel = 0; + } + app.dialog_state.palette_query = q; + if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + close = true; + } + if let Some((id, params)) = run { + app.dialog = None; + if let Err(e) = crate::menus::invoke(app, ctx, &id, params) { + app.ui.status = e; + } + return; + } + if close { + app.dialog = None; + } +} diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs new file mode 100644 index 00000000..bb418ccd --- /dev/null +++ b/crates/ui-egui/src/panels/effect_controls.rs @@ -0,0 +1,416 @@ +//! Effect Controls (the selected layer's effects with all parameters) and the Properties panel +//! (essential properties: transform + text/shape basics). + +use effectcraft_engine::keyframe::Value; +use effectcraft_engine::project::{GroupKind, Layer, Node, ParamUi, PropGroup, Property}; +use effectcraft_engine::render::EvalCtx; +use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2}; +use serde_json::json; + +use crate::icons::{self, Icon}; +use crate::theme::Tokens; +use crate::{EffectcraftApp, widgets}; + +type Actions = Vec<(String, serde_json::Value)>; + +fn selected_layer(app: &EffectcraftApp) -> Option { + let comp = app.session.active_comp()?; + let id = app.session.state.selected_layers.first()?; + comp.layer(*id).cloned() +} + +/// One property row: stopwatch, name, value control. +fn prop_row( + app: &mut EffectcraftApp, + ui: &mut egui::Ui, + p: &egui::Painter, + layer: &Layer, + prop: &Property, + ectx: &EvalCtx, + r: Rect, + indent: f32, + actions: &mut Actions, +) { + let t = app.tokens; + let cy = r.center().y; + let uid = prop.uid; + let swr = Rect::from_center_size(pos2(r.min.x + indent, cy), vec2(14.0, 14.0)); + if !prop.static_only && !matches!(prop.ui, ParamUi::Hidden) { + let resp = ui.interact(swr, egui::Id::new(("ec-sw", uid)), Sense::click()); + icons::paint( + p, + swr, + Icon::Stopwatch, + if prop.is_animated() { + t.hot_text + } else if resp.hovered() { + t.text + } else { + t.text_dim + }, + ); + app.auto.add(&format!("effectControls.prop.{uid}.stopwatch"), swr, &prop.name); + if resp.clicked() { + actions.push(("prop.toggleAnimation".into(), json!({"layer": layer.id.0, "prop": uid}))); + } + } + p.text(pos2(swr.max.x + 6.0, cy), Align2::LEFT_CENTER, &prop.name, Tokens::ui(12.0), t.text); + let vx = (r.min.x + r.width() * 0.48).max(swr.max.x + 130.0); + let value = ectx.value(layer, prop); + let merge = format!("ec-{uid}"); + let set = + |actions: &mut Actions, v: serde_json::Value| actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": v, "merge": merge}))); + match &value { + Value::Scalar(v) => { + let (min, max, dec) = match &prop.ui { + ParamUi::Slider { min, max, decimals, .. } => (*min, *max, *decimals as usize), + _ => (-1e9, 1e9, 1), + }; + let suffix = match prop.ui { + ParamUi::Angle => "°", + ParamUi::Percent => "%", + _ => "", + }; + let speed = match &prop.ui { + ParamUi::Slider { slider_min, slider_max, .. } => ((slider_max - slider_min) / 300.0).clamp(0.001, 50.0), + _ => 0.5, + }; + let (vr, nv, _) = widgets::hot_number_at( + ui, + pos2(vx, cy - 9.0), + egui::Id::new(("ec-v", uid)), + *v, + speed, + (min, max), + dec.max(if dec == 0 { 0 } else { 1 }), + suffix, + &t, + ); + app.auto.add(&format!("effectControls.prop.{uid}.value"), vr, &prop.name); + if let Some(nv) = nv { + set(actions, json!(nv)); + } + // Slider track for slider params. + if let ParamUi::Slider { slider_min, slider_max, .. } = prop.ui { + let tr = Rect::from_min_max(pos2(vr.max.x + 10.0, cy - 2.0), pos2(r.max.x - 12.0, cy + 2.0)); + if tr.width() > 40.0 { + p.rect_filled(tr, 2.0, t.field_bg); + let f = ((v - slider_min) / (slider_max - slider_min)).clamp(0.0, 1.0) as f32; + p.rect_filled(Rect::from_min_max(tr.min, pos2(tr.min.x + tr.width() * f, tr.max.y)), 2.0, t.accent.gamma_multiply(0.7)); + let knob = pos2(tr.min.x + tr.width() * f, cy); + p.circle_filled(knob, 5.0, t.text); + let sresp = ui.interact(tr.expand2(vec2(4.0, 6.0)), egui::Id::new(("ec-slider", uid)), Sense::click_and_drag()); + app.auto.add(&format!("effectControls.prop.{uid}.slider"), tr, &prop.name); + if (sresp.dragged() || sresp.clicked()) + && let Some(pt) = sresp.interact_pointer_pos() + { + let f = ((pt.x - tr.min.x) / tr.width()).clamp(0.0, 1.0) as f64; + set(actions, json!(slider_min + (slider_max - slider_min) * f)); + } + } + } + } + Value::Vec2(_) | Value::Vec3(_) => { + let c = value.components(); + let n = if prop.shown_dims > 0 && !(layer.is_3d() && c.len() == 3) { prop.shown_dims as usize } else { c.len() }; + let mut x = vx; + if matches!(prop.ui, ParamUi::Point | ParamUi::Point3) { + icons::paint(p, Rect::from_center_size(pos2(x + 6.0, cy), vec2(12.0, 12.0)), Icon::PanBehind, t.text_dim); + x += 18.0; + } + for d in 0..n.min(c.len()) { + let (vr, nv, _) = widgets::hot_number_at(ui, pos2(x, cy - 9.0), egui::Id::new(("ec-v", uid, d)), c[d], 1.0, (-1e9, 1e9), 1, "", &t); + app.auto.add(&format!("effectControls.prop.{uid}.value.{d}"), vr, &prop.name); + if let Some(nv) = nv { + let mut nc = c.clone(); + nc[d] = nv; + set(actions, json!(nc)); + } + x = vr.max.x + 8.0; + } + } + Value::Color(c) => { + let sr = Rect::from_min_size(pos2(vx, cy - 8.0), vec2(30.0, 16.0)); + let pop = egui::Id::new(("ec-cpop", uid)); + if widgets::swatch(ui, sr, [c[0] as f32, c[1] as f32, c[2] as f32, 1.0], egui::Id::new(("ec-c", uid)), &t).clicked() { + widgets::open_popup(ui, pop); + } + app.auto.add(&format!("effectControls.prop.{uid}.value"), sr, &prop.name); + let mut rgb = [c[0] as f32, c[1] as f32, c[2] as f32]; + if crate::header::color_popup(ui, pop, sr.left_bottom(), &mut rgb) { + set(actions, json!([rgb[0], rgb[1], rgb[2], 1.0])); + } + p.text( + pos2(sr.max.x + 8.0, cy), + Align2::LEFT_CENTER, + effectcraft_engine::color::Rgba::from_array([c[0] as f32, c[1] as f32, c[2] as f32, 1.0]).to_hex(), + Tokens::mono(11.0), + t.text_dim, + ); + } + Value::Bool(b) => { + let cr = Rect::from_min_size(pos2(vx, cy - 8.0), vec2(16.0, 16.0)); + if widgets::checkbox(ui, cr, *b, &t, egui::Id::new(("ec-b", uid))).clicked() { + set(actions, json!(!b)); + } + app.auto.add(&format!("effectControls.prop.{uid}.value"), cr, &prop.name); + } + Value::Enum(i) => { + if let ParamUi::Popup { options } = &prop.ui { + let dr = Rect::from_min_size(pos2(vx, cy - 9.0), vec2((r.max.x - vx - 12.0).clamp(80.0, 220.0), 18.0)); + let pop = egui::Id::new(("ec-epop", uid)); + if widgets::dropdown(ui, dr, options.get(*i as usize).map(String::as_str).unwrap_or(""), &t, egui::Id::new(("ec-e", uid))).clicked() { + widgets::open_popup(ui, pop); + } + app.auto.add(&format!("effectControls.prop.{uid}.value"), dr, &prop.name); + if let Some(ni) = widgets::popup_menu(ui, pop, dr.left_bottom(), options, Some(*i as usize)) { + set(actions, json!(ni)); + } + } + } + Value::Layer(l) => { + let comp = app.session.active_comp().cloned(); + if let Some(comp) = comp { + let dr = Rect::from_min_size(pos2(vx, cy - 9.0), vec2(160.0, 18.0)); + let name = l.and_then(|id| comp.layer(effectcraft_engine::project::LayerId(id))).map(|l| l.name.clone()).unwrap_or_else(|| "None".into()); + let pop = egui::Id::new(("ec-lpop", uid)); + if widgets::dropdown(ui, dr, &name, &t, egui::Id::new(("ec-l", uid))).clicked() { + widgets::open_popup(ui, pop); + } + let mut opts = vec!["None".to_string()]; + opts.extend(comp.layers.iter().map(|l| l.name.clone())); + if let Some(i) = widgets::popup_menu(ui, pop, dr.left_bottom(), &opts, None) { + set(actions, if i == 0 { serde_json::Value::Null } else { json!(comp.layers[i - 1].id.0) }); + } + } + } + _ => {} + } +} + +fn group_rows( + app: &mut EffectcraftApp, + ui: &mut egui::Ui, + p: &egui::Painter, + layer: &Layer, + g: &PropGroup, + ectx: &EvalCtx, + rect: Rect, + y: &mut f32, + depth: usize, + actions: &mut Actions, +) { + let t = app.tokens; + for c in &g.children { + let r = Rect::from_min_size(pos2(rect.min.x, *y), vec2(rect.width(), 24.0)); + match c { + Node::Prop(pr) => { + if matches!(pr.ui, ParamUi::Hidden) || pr.three_d_only && !layer.is_3d() { + continue; + } + *y += 24.0; + if r.max.y < rect.min.y || r.min.y > rect.max.y { + continue; + } + prop_row(app, ui, p, layer, pr, ectx, r, 24.0 + 14.0 * depth as f32, actions); + } + Node::Group(sg) => { + *y += 24.0; + let open = !app.ui.fx_closed.contains(&sg.uid); + let tw = Rect::from_center_size(pos2(r.min.x + 12.0 + 14.0 * depth as f32, r.center().y), vec2(12.0, 12.0)); + if r.max.y >= rect.min.y && r.min.y <= rect.max.y { + if widgets::twirl(ui, tw, open, egui::Id::new(("ec-g", sg.uid)), &t).clicked() { + if open { + app.ui.fx_closed.insert(sg.uid); + } else { + app.ui.fx_closed.remove(&sg.uid); + } + } + p.text(pos2(tw.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, &sg.name, Tokens::ui(12.0), t.text); + } + if open { + group_rows(app, ui, p, layer, sg, ectx, rect, y, depth + 1, actions); + } + } + } + } +} + +pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let ctx = ui.ctx().clone(); + let Some(layer) = selected_layer(app) else { + p.text(rect.center(), Align2::CENTER_CENTER, "Select a layer to see its effects", Tokens::ui(12.0), t.text_faint); + return; + }; + let Some(cid) = app.session.active_comp_id() else { return }; + let comp = app.session.project.comp(cid).cloned().unwrap_or_else(|| effectcraft_engine::project::Comp::new(1, 1, Default::default(), Default::default())); + let comp_name = app.session.project.item(cid).map(|i| i.name.clone()).unwrap_or_default(); + let snap_project = app.session.project.clone(); + let snap_expr = app.session.expr.clone(); + let ectx = EvalCtx { project: &snap_project, comp_id: cid, comp: &comp, time: app.session.time(), expr: snap_expr.as_deref() }; + let hdr = Rect::from_min_size(rect.min, vec2(rect.width(), 24.0)); + p.text(pos2(hdr.min.x + 10.0, hdr.center().y), Align2::LEFT_CENTER, format!("{} • {}", comp_name, layer.name), Tokens::ui(11.5), t.text_dim); + p.line_segment([hdr.left_bottom(), hdr.right_bottom()], Stroke::new(1.0, t.separator)); + let body = Rect::from_min_max(pos2(rect.min.x, hdr.max.y), rect.max); + let scroll_id = egui::Id::new("ec-scroll"); + let mut scroll: f32 = ctx.data(|d| d.get_temp(scroll_id).unwrap_or(0.0)); + if ui.rect_contains_pointer(body) { + scroll = (scroll - ui.input(|i| i.smooth_scroll_delta.y)).max(0.0); + } + let mut y = body.min.y + 4.0 - scroll; + let mut actions: Actions = vec![]; + let bp = p.with_clip_rect(body); + let fx: Vec = layer.effects().map(|f| f.groups().cloned().collect()).unwrap_or_default(); + if fx.is_empty() { + bp.text( + pos2(body.center().x, body.min.y + 40.0), + Align2::CENTER_CENTER, + "No effects. Drag one from Effects & Presets.", + Tokens::ui(12.0), + t.text_faint, + ); + } + for g in &fx { + let GroupKind::Effect { .. } = g.kind else { continue }; + let r = Rect::from_min_size(pos2(body.min.x, y), vec2(body.width(), 26.0)); + y += 26.0; + let open = !app.ui.fx_closed.contains(&g.uid); + bp.rect_filled(r, 0.0, Color32::from_rgb(0x2a, 0x2a, 0x2a)); + let fxr = Rect::from_center_size(pos2(r.min.x + 14.0, r.center().y), vec2(16.0, 16.0)); + if widgets::icon_toggle(ui, fxr, Icon::Fx, g.enabled, &t, egui::Id::new(("ec-fx", g.uid)), None).clicked() { + actions.push(("effect.toggle".into(), json!({"layer": layer.id.0, "effect": g.uid}))); + } + app.auto.add(&format!("effectControls.effect.{}.fx", g.uid), fxr, &g.name); + let tw = Rect::from_center_size(pos2(r.min.x + 32.0, r.center().y), vec2(12.0, 12.0)); + if widgets::twirl(ui, tw, open, egui::Id::new(("ec-tw", g.uid)), &t).clicked() { + if open { + app.ui.fx_closed.insert(g.uid); + } else { + app.ui.fx_closed.remove(&g.uid); + } + } + bp.text(pos2(tw.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, &g.name, Tokens::semibold(12.0), t.text); + let reset = Rect::from_min_size(pos2(r.max.x - 92.0, r.min.y + 4.0), vec2(40.0, 18.0)); + let rresp = ui.interact(reset, egui::Id::new(("ec-reset", g.uid)), Sense::click()); + bp.text(reset.center(), Align2::CENTER_CENTER, "Reset", Tokens::ui(11.5), if rresp.hovered() { t.hot_text } else { t.text_dim }); + app.auto.add(&format!("effectControls.effect.{}.reset", g.uid), reset, "Reset"); + if rresp.clicked() + && let Some(spec) = g.kind_effect().and_then(effectcraft_engine::effects::find) + { + for ps in &spec.params { + if let Some(pr) = g.get(ps.id) { + let size = effectcraft_engine::render::source_size(&app.session.project, &layer); + let def = match (&ps.ui, &ps.default) { + (ParamUi::Point, Value::Vec2(f)) => Value::Vec2([f[0] * size.0.max(comp.width) as f64, f[1] * size.1.max(comp.height) as f64]), + _ => ps.default.clone(), + }; + actions.push(("prop.reset".into(), json!({"layer": layer.id.0, "prop": pr.uid, "default": def.to_json()}))); + } + } + } + let rm = Rect::from_min_size(pos2(r.max.x - 28.0, r.min.y + 4.0), vec2(18.0, 18.0)); + if widgets::icon_button(ui, rm, Icon::Close, false, &t, egui::Id::new(("ec-rm", g.uid))).on_hover_text("Remove effect").clicked() { + actions.push(("effect.remove".into(), json!({"layer": layer.id.0, "effect": g.uid}))); + } + app.auto.add(&format!("effectControls.effect.{}.remove", g.uid), rm, "Remove"); + let hresp = + ui.interact(Rect::from_min_max(pos2(tw.max.x, r.min.y), pos2(reset.min.x - 4.0, r.max.y)), egui::Id::new(("ec-hdr", g.uid)), Sense::click()); + app.auto.add(&format!("effectControls.effect.{}", g.uid), r, &g.name); + if hresp.clicked() { + app.session.state.selected_props = vec![(layer.id, g.uid)]; + } + hresp.context_menu(|ui| { + for (label, cmd) in [("Duplicate", "effect.duplicate"), ("Remove", "effect.remove")] { + if ui.button(label).clicked() { + actions.push((cmd.into(), json!({"layer": layer.id.0, "effect": g.uid}))); + ui.close(); + } + } + if ui.button("Move Up").clicked() { + let idx = fx.iter().position(|x| x.uid == g.uid).unwrap_or(0); + actions.push(("effect.reorder".into(), json!({"layer": layer.id.0, "effect": g.uid, "index": idx.max(1)}))); + ui.close(); + } + if ui.button("Move Down").clicked() { + let idx = fx.iter().position(|x| x.uid == g.uid).unwrap_or(0); + actions.push(("effect.reorder".into(), json!({"layer": layer.id.0, "effect": g.uid, "index": idx + 2}))); + ui.close(); + } + }); + if open { + group_rows(app, ui, &bp, &layer, g, &ectx, body, &mut y, 0, &mut actions); + } + y += 4.0; + } + let content_h = y + scroll - body.min.y; + scroll = scroll.min((content_h - body.height()).max(0.0)); + ctx.data_mut(|d| d.insert_temp(scroll_id, scroll)); + // Drop effects here. + if let Some(payload) = egui::DragAndDrop::payload::(&ctx) + && ui.rect_contains_pointer(rect) + && let crate::panels::DragPayload::Effect(e) = payload.as_ref() + { + p.rect_stroke(rect, 0.0, Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); + if ctx.input(|i| i.pointer.any_released()) { + actions.push(("effect.apply".into(), json!({"effect": e, "layers": [layer.id.0]}))); + egui::DragAndDrop::clear_payload(&ctx); + } + } + for (id, params) in actions { + if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) { + app.ui.status = e; + } + } +} + +trait EffectKind { + fn kind_effect(&self) -> Option<&str>; +} +impl EffectKind for PropGroup { + fn kind_effect(&self) -> Option<&str> { + match &self.kind { + GroupKind::Effect { effect } => Some(effect.as_str()), + _ => None, + } + } +} + +/// Properties panel: the selected layer's transform (and text basics), always visible. +pub fn properties(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let ctx = ui.ctx().clone(); + let Some(layer) = selected_layer(app) else { + p.text(rect.center(), Align2::CENTER_CENTER, "Select a layer", Tokens::ui(12.0), t.text_faint); + return; + }; + let Some(cid) = app.session.active_comp_id() else { return }; + let comp = app.session.project.comp(cid).cloned().unwrap_or_else(|| effectcraft_engine::project::Comp::new(1, 1, Default::default(), Default::default())); + let snap_project = app.session.project.clone(); + let snap_expr = app.session.expr.clone(); + let ectx = EvalCtx { project: &snap_project, comp_id: cid, comp: &comp, time: app.session.time(), expr: snap_expr.as_deref() }; + let mut y = rect.min.y + 8.0; + p.text(pos2(rect.min.x + 10.0, y + 8.0), Align2::LEFT_CENTER, &layer.name, Tokens::semibold(13.0), t.text); + p.text(pos2(rect.min.x + 10.0, y + 24.0), Align2::LEFT_CENTER, layer.source.type_name(), Tokens::ui(11.0), t.text_dim); + y += 40.0; + let mut actions: Actions = vec![]; + if let Some(tr) = layer.transform().cloned() { + p.text(pos2(rect.min.x + 10.0, y + 10.0), Align2::LEFT_CENTER, "Layer Transform", Tokens::semibold(12.0), t.text); + y += 24.0; + for pr in tr.props() { + if pr.three_d_only && !layer.is_3d() { + continue; + } + let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), 24.0)); + prop_row(app, ui, &p, &layer, pr, &ectx, r, 16.0, &mut actions); + y += 24.0; + } + } + for (id, params) in actions { + if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) { + app.ui.status = e; + } + } +} diff --git a/crates/ui-egui/src/panels/effects_presets.rs b/crates/ui-egui/src/panels/effects_presets.rs new file mode 100644 index 00000000..db24c83f --- /dev/null +++ b/crates/ui-egui/src/panels/effects_presets.rs @@ -0,0 +1,113 @@ +//! Effects & Presets: search + category tree; double-click applies to the selected layers, drag +//! onto a layer (timeline, viewer, Effect Controls) applies there. + +use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2}; +use serde_json::json; + +use crate::icons::{self, Icon}; +use crate::panels::DragPayload; +use crate::theme::Tokens; +use crate::{EffectcraftApp, widgets}; + +pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let ctx = ui.ctx().clone(); + let p = ui.painter().clone(); + let sr = Rect::from_min_size(rect.min + vec2(8.0, 8.0), vec2(rect.width() - 16.0, 24.0)); + let mut q = app.ui.effects_search.clone(); + widgets::search_field(ui, sr, &mut q, "Search effects", &t); + app.ui.effects_search = q.clone(); + app.auto.add("effects.search", sr, "Search"); + let list = Rect::from_min_max(pos2(rect.min.x, sr.max.y + 6.0), rect.max); + let lp = p.with_clip_rect(list); + let scroll_id = egui::Id::new("fx-scroll"); + let mut scroll: f32 = ctx.data(|d| d.get_temp(scroll_id).unwrap_or(0.0)); + if ui.rect_contains_pointer(list) { + scroll = (scroll - ui.input(|i| i.smooth_scroll_delta.y)).max(0.0); + } + let query = q.to_lowercase(); + let mut y = list.min.y - scroll; + let mut apply: Option = None; + let row_h = 21.0; + // "* Animation Presets" (our own, original presets come later) then categories. + let mut cats: Vec<&str> = effectcraft_engine::effects::CATEGORIES.to_vec(); + cats.retain(|c| effectcraft_engine::effects::registry().iter().any(|e| e.category == *c)); + for cat in cats { + let items: Vec<_> = effectcraft_engine::effects::registry() + .iter() + .filter(|e| e.category == cat && (query.is_empty() || e.name.to_lowercase().contains(&query))) + .collect(); + if items.is_empty() { + continue; + } + let open = !query.is_empty() || app.ui.effects_open.contains(cat); + let r = Rect::from_min_size(pos2(list.min.x, y), vec2(list.width(), row_h)); + y += row_h; + let tw = Rect::from_center_size(pos2(r.min.x + 12.0, r.center().y), vec2(12.0, 12.0)); + let resp = ui.interact(r.intersect(list), egui::Id::new(("fxcat", cat)), Sense::click()); + if resp.hovered() { + lp.rect_filled(r, 0.0, t.hover); + } + icons::paint(&lp, tw, if open { Icon::ChevronDown } else { Icon::ChevronRight }, t.text_dim); + icons::paint(&lp, Rect::from_center_size(pos2(r.min.x + 28.0, r.center().y), vec2(13.0, 13.0)), Icon::Folder, Color32::from_rgb(0xc8, 0xb0, 0x58)); + lp.text(pos2(r.min.x + 40.0, r.center().y), Align2::LEFT_CENTER, cat, Tokens::ui(12.0), t.text); + app.auto.add(&format!("effects.category.{cat}"), r, cat); + if resp.clicked() && query.is_empty() { + if open { + app.ui.effects_open.remove(cat); + } else { + app.ui.effects_open.insert(cat.to_string()); + } + } + if !open { + continue; + } + for e in items { + let r = Rect::from_min_size(pos2(list.min.x, y), vec2(list.width(), row_h)); + y += row_h; + if r.max.y < list.min.y || r.min.y > list.max.y { + continue; + } + let resp = ui.interact(r.intersect(list), egui::Id::new(("fx", e.id)), Sense::click_and_drag()); + if resp.hovered() { + lp.rect_filled(r, 0.0, t.hover); + } + icons::paint(&lp, Rect::from_center_size(pos2(r.min.x + 44.0, r.center().y), vec2(12.0, 12.0)), Icon::Fx, t.text_dim); + lp.text(pos2(r.min.x + 56.0, r.center().y), Align2::LEFT_CENTER, e.name, Tokens::ui(12.0), t.text); + if e.float { + lp.text(pos2(r.max.x - 10.0, r.center().y), Align2::RIGHT_CENTER, "32", Tokens::ui(9.5), t.text_faint); + } + app.auto.add(&format!("effects.item.{}", e.id), r, e.name); + if resp.double_clicked() { + apply = Some(e.id.to_string()); + } + if resp.drag_started() { + egui::DragAndDrop::set_payload(&ctx, DragPayload::Effect(e.id.to_string())); + } + } + } + let content = y + scroll - list.min.y; + scroll = scroll.min((content - list.height()).max(0.0)); + ctx.data_mut(|d| d.insert_temp(scroll_id, scroll)); + if let Some(DragPayload::Effect(id)) = egui::DragAndDrop::payload::(&ctx).as_deref() + && let Some(pos) = ctx.pointer_hover_pos() + { + let name = effectcraft_engine::effects::find(id).map(|e| e.name).unwrap_or(""); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("dnd-fx"))); + let g = painter.layout_no_wrap(name.to_string(), Tokens::ui(12.0), t.text); + let r = Rect::from_min_size(pos + vec2(12.0, 8.0), g.size() + vec2(16.0, 8.0)); + painter.rect_filled(r, 4.0, Color32::from_rgba_premultiplied(40, 40, 40, 230)); + painter.rect_stroke(r, 4.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + painter.galley(r.min + vec2(8.0, 4.0), g, t.text); + } + if let Some(id) = apply { + if app.session.state.selected_layers.is_empty() { + app.ui.status = "Select a layer to apply the effect to".into(); + } else if let Err(e) = app.session.execute("effect.apply", json!({"effect": id})) { + app.ui.status = e.to_string(); + } else { + app.show_panel(crate::dock::PanelKind::EffectControls); + app.ui.focused = crate::dock::PanelKind::EffectsPresets; + } + } +} diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs new file mode 100644 index 00000000..eb370ecd --- /dev/null +++ b/crates/ui-egui/src/panels/info.rs @@ -0,0 +1,77 @@ +//! Info panel: colour and position under the pointer, plus the current selection. + +use egui::{Align2, Color32, Rect, pos2, vec2}; + +use crate::EffectcraftApp; +use crate::theme::Tokens; + +pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let x0 = rect.min.x + 12.0; + let mut y = rect.min.y + 14.0; + let (rgba, xy) = match (app.pointer_comp, &app.viewer_image) { + (Some([cx, cy]), Some(img)) => { + let comp = app.session.active_comp(); + let (cw, ch) = comp.map(|c| (c.width as f32, c.height as f32)).unwrap_or((1.0, 1.0)); + let sx = (cx / cw * img.size[0] as f32) as i64; + let sy = (cy / ch * img.size[1] as f32) as i64; + let px = if sx >= 0 && sy >= 0 && (sx as usize) < img.size[0] && (sy as usize) < img.size[1] { + Some(img.pixels[sy as usize * img.size[0] + sx as usize]) + } else { + None + }; + (px, Some((cx, cy))) + } + _ => (None, None), + }; + let row = |p: &egui::Painter, y: f32, k: &str, v: String, col: Color32| { + p.text(pos2(x0, y), Align2::LEFT_CENTER, k, Tokens::ui(12.0), col); + p.text(pos2(x0 + 22.0, y), Align2::LEFT_CENTER, v, Tokens::mono(12.0), t.text); + }; + let unpre = |c: Color32| -> [u8; 4] { + let a = c.a(); + if a == 0 { + [0, 0, 0, 0] + } else { + let f = |v: u8| ((v as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8; + [f(c.r()), f(c.g()), f(c.b()), a] + } + }; + let px = rgba.map(unpre).unwrap_or([0, 0, 0, 0]); + row(&p, y, "R :", format!("{}", px[0]), Color32::from_rgb(0xe0, 0x60, 0x60)); + row(&p, y + 18.0, "G :", format!("{}", px[1]), Color32::from_rgb(0x60, 0xd0, 0x60)); + row(&p, y + 36.0, "B :", format!("{}", px[2]), Color32::from_rgb(0x60, 0x90, 0xf0)); + row(&p, y + 54.0, "A :", format!("{}", px[3]), t.text_dim); + let cx = rect.min.x + rect.width() * 0.5; + if let Some((x, yy)) = xy { + p.text(pos2(cx, y), Align2::LEFT_CENTER, format!("X : {x:.0}"), Tokens::mono(12.0), t.text); + p.text(pos2(cx, y + 18.0), Align2::LEFT_CENTER, format!("Y : {yy:.0}"), Tokens::mono(12.0), t.text); + } + if let Some(c) = rgba { + let sw = egui::Rect::from_min_size(pos2(cx, y + 34.0), vec2(36.0, 30.0)); + p.rect_filled(sw, 3.0, Color32::from_rgb(px[0], px[1], px[2])); + let _ = c; + } + y += 82.0; + p.line_segment([pos2(rect.min.x + 8.0, y), pos2(rect.max.x - 8.0, y)], egui::Stroke::new(1.0, t.separator)); + y += 14.0; + let comp = app.session.active_comp().cloned(); + if let Some(c) = comp { + let sel: Vec = app.session.state.selected_layers.iter().filter_map(|id| c.layer(*id)).map(|l| l.name.clone()).collect(); + let tc = crate::panels::timecode(&app.session, &c, app.session.time()); + p.text(pos2(x0, y), Align2::LEFT_CENTER, if sel.is_empty() { "No layer selected".to_string() } else { sel.join(", ") }, Tokens::semibold(12.0), t.text); + p.text(pos2(x0, y + 18.0), Align2::LEFT_CENTER, format!("Time: {tc}"), Tokens::ui(12.0), t.text_dim); + let ms = app.frames.last_ms.lock().map(|v| *v).unwrap_or(0.0); + p.text(pos2(x0, y + 36.0), Align2::LEFT_CENTER, format!("Render: {ms:.0} ms • UI {:.0} fps", app.fps), Tokens::ui(11.5), t.text_faint); + if !app.session.state.selected_keys.is_empty() { + p.text( + pos2(x0, y + 54.0), + Align2::LEFT_CENTER, + format!("{} keyframes selected", app.session.state.selected_keys.len()), + Tokens::ui(11.5), + t.text_dim, + ); + } + } +} diff --git a/crates/ui-egui/src/panels/misc.rs b/crates/ui-egui/src/panels/misc.rs new file mode 100644 index 00000000..60205270 --- /dev/null +++ b/crates/ui-egui/src/panels/misc.rs @@ -0,0 +1,275 @@ +//! Smaller panels: Preview, Audio, History, Markers, Wiggler, Render Queue, the Home screen and +//! placeholders. + +use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2}; +use serde_json::json; + +use crate::dock::PanelKind; +use crate::icons::{self, Icon}; +use crate::theme::Tokens; +use crate::{EffectcraftApp, widgets}; + +pub fn placeholder(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, p: PanelKind) { + let t = app.tokens; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, format!("{} — coming soon", p.title()), Tokens::ui(12.0), t.text_faint); +} + +/// Preview panel: transport controls and RAM preview options. +pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let ctx = ui.ctx().clone(); + let p = ui.painter().with_clip_rect(rect); + let y = rect.min.y + 12.0; + let bw = 30.0; + let total = bw * 5.0 + 16.0; + let mut x = rect.center().x - total / 2.0; + let buttons: [(Icon, &str, &str); 5] = [ + (Icon::First, "time.start", "First Frame"), + (Icon::StepBack, "time.previousFrame", "Previous Frame"), + (Icon::Play, "playback.toggle", "Play/Stop"), + (Icon::StepFwd, "time.nextFrame", "Next Frame"), + (Icon::Last, "time.end", "Last Frame"), + ]; + for (icon, cmd, tip) in buttons { + let r = Rect::from_min_size(pos2(x, y), vec2(bw, 28.0)); + let icon = if cmd == "playback.toggle" && app.playback.playing { Icon::Pause } else { icon }; + if widgets::icon_button(ui, r, icon, cmd == "playback.toggle" && app.playback.playing, &t, egui::Id::new(("pv", cmd))).on_hover_text(tip).clicked() { + let _ = crate::menus::invoke(app, &ctx, cmd, json!({})); + } + app.auto.add(&format!("preview.{}", tip.replace([' ', '/'], "")), r, tip); + x += bw + 4.0; + } + let mut yy = y + 44.0; + let row = |p: &egui::Painter, yy: f32, k: &str, v: &str| { + p.text(pos2(rect.min.x + 12.0, yy), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim); + p.text(pos2(rect.min.x + 130.0, yy), Align2::LEFT_CENTER, v, Tokens::ui(12.0), t.text); + }; + row(&p, yy, "Shortcut", "Spacebar"); + yy += 22.0; + let lr = Rect::from_min_size(pos2(rect.min.x + 10.0, yy - 8.0), vec2(16.0, 16.0)); + if widgets::checkbox(ui, lr, app.ui.preview_loop, &t, egui::Id::new("pv-loop")).clicked() { + app.ui.preview_loop = !app.ui.preview_loop; + } + app.auto.add("preview.loop", lr, "Loop"); + p.text(pos2(lr.max.x + 6.0, yy), Align2::LEFT_CENTER, "Loop", Tokens::ui(12.0), t.text); + yy += 24.0; + row(&p, yy, "Range", "Work Area Extended By Current Time"); + yy += 22.0; + row(&p, yy, "Play From", "Current Time"); + yy += 22.0; + let comp = app.session.active_comp().cloned(); + row(&p, yy, "Frame Rate", &comp.as_ref().map(|c| format!("({:.2})", c.frame_rate.as_f64())).unwrap_or_default()); + yy += 22.0; + row(&p, yy, "Resolution", app.ui.viewer.res.label()); + yy += 26.0; + if let Some(c) = comp { + let cid = app.session.active_comp_id().map(|i| i.0).unwrap_or(0); + let scale = app.viewer_tex.as_ref().map(|(_, k)| k.scale).unwrap_or(1000); + let cached = app.frames.cached_frames(app.session.revision, cid, scale).len(); + let total = c.frame_rate.frame_at(c.work_area.1) - c.frame_rate.frame_at(c.work_area.0); + let bar = Rect::from_min_size(pos2(rect.min.x + 12.0, yy), vec2(rect.width() - 24.0, 6.0)); + p.rect_filled(bar, 3.0, t.field_bg); + let f = (cached as f32 / total.max(1) as f32).min(1.0); + p.rect_filled(Rect::from_min_size(bar.min, vec2(bar.width() * f, bar.height())), 3.0, t.cache_green); + p.text(pos2(bar.min.x, bar.max.y + 12.0), Align2::LEFT_CENTER, format!("{cached} / {total} frames cached"), Tokens::ui(11.0), t.text_faint); + } +} + +pub fn audio(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + // Level meters (silent until audio playback lands). + for (i, x) in [rect.min.x + 20.0, rect.min.x + 34.0].into_iter().enumerate() { + let r = Rect::from_min_max(pos2(x, rect.min.y + 14.0), pos2(x + 10.0, rect.max.y - 20.0)); + p.rect_filled(r, 1.0, t.field_bg); + let _ = i; + } + for (k, db) in [0, -6, -12, -18, -24, -36, -48].iter().enumerate() { + let y = rect.min.y + 14.0 + (rect.height() - 34.0) * (-*db as f32 / 48.0); + p.text(pos2(rect.min.x + 52.0, y), Align2::LEFT_CENTER, format!("{db} dB"), Tokens::ui(10.0), t.text_faint); + let _ = k; + } +} + +pub fn history(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let mut y = rect.min.y + 6.0; + let undo: Vec = app.session.history.undo.iter().map(|u| u.0.clone()).collect(); + let redo: Vec = app.session.history.redo.iter().rev().map(|u| u.0.clone()).collect(); + let n = undo.len(); + let mut jump: Option = None; + for (i, label) in undo.iter().chain(redo.iter()).enumerate() { + let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), 22.0)); + y += 22.0; + let current = i + 1 == n; + let future = i >= n; + let resp = ui.interact(r, egui::Id::new(("hist", i)), Sense::click()); + if current { + p.rect_filled(r, 0.0, t.row_selected); + } else if resp.hovered() { + p.rect_filled(r, 0.0, t.hover); + } + p.text(pos2(r.min.x + 12.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::ui(12.0), if future { t.text_faint } else { t.text }); + if resp.clicked() { + jump = Some(i as i64 + 1 - n as i64); + } + } + if let Some(d) = jump { + for _ in 0..d.unsigned_abs() { + if d < 0 { + app.session.undo(); + } else { + app.session.redo(); + } + } + } +} + +pub fn markers(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let Some(c) = app.session.active_comp().cloned() else { return }; + let mut y = rect.min.y + 8.0; + if c.markers.is_empty() { + p.text(rect.center(), Align2::CENTER_CENTER, "No composition markers", Tokens::ui(12.0), t.text_faint); + } + for m in &c.markers { + let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), 22.0)); + y += 22.0; + let tc = crate::panels::timecode(&app.session, &c, m.time); + p.text(pos2(r.min.x + 12.0, r.center().y), Align2::LEFT_CENTER, tc, Tokens::mono(11.5), t.timecode); + p.text(pos2(r.min.x + 120.0, r.center().y), Align2::LEFT_CENTER, &m.comment, Tokens::ui(12.0), t.text); + if ui.interact(r, egui::Id::new(("mk", m.time.0)), Sense::click()).clicked() { + app.session.set_time(m.time); + } + } +} + +/// Wiggler: add random keyframes between two selected keys (applied as a wiggle expression). +pub fn wiggler(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let freq_id = egui::Id::new("wiggler-freq"); + let mag_id = egui::Id::new("wiggler-mag"); + let mut freq: f64 = ui.data(|d| d.get_temp(freq_id).unwrap_or(5.0)); + let mut mag: f64 = ui.data(|d| d.get_temp(mag_id).unwrap_or(30.0)); + let x0 = rect.min.x + 12.0; + let mut y = rect.min.y + 14.0; + p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Frequency:", Tokens::ui(12.0), t.text_dim); + let (_, nv, _) = widgets::hot_number_at(ui, pos2(x0 + 110.0, y), egui::Id::new("wg-f"), freq, 0.1, (0.1, 100.0), 1, " per second", &t); + if let Some(v) = nv { + freq = v; + } + y += 26.0; + p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Magnitude:", Tokens::ui(12.0), t.text_dim); + let (_, nv, _) = widgets::hot_number_at(ui, pos2(x0 + 110.0, y), egui::Id::new("wg-m"), mag, 0.5, (0.0, 10000.0), 1, "", &t); + if let Some(v) = nv { + mag = v; + } + ui.data_mut(|d| { + d.insert_temp(freq_id, freq); + d.insert_temp(mag_id, mag); + }); + y += 34.0; + let b = Rect::from_min_size(pos2(rect.max.x - 92.0, y), vec2(80.0, 24.0)); + if widgets::text_button(ui, b, "Apply", true, &t, egui::Id::new("wg-apply")).clicked() { + let props = app.session.state.selected_props.clone(); + if props.is_empty() { + app.ui.status = "Select a property in the Timeline first".into(); + } + for (l, u) in props { + let _ = app.session.execute("prop.setExpression", json!({"layer": l.0, "prop": u, "expression": format!("wiggle({freq}, {mag})")})); + } + } + app.auto.add("wiggler.apply", b, "Apply"); +} + +/// Render Queue: comps queued for export with output settings. +pub fn render_queue(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let hdr = Rect::from_min_size(rect.min, vec2(rect.width(), 40.0)); + p.text(pos2(hdr.min.x + 14.0, hdr.center().y), Align2::LEFT_CENTER, "Render Queue", Tokens::semibold(13.0), t.text); + let b = Rect::from_min_size(pos2(hdr.max.x - 100.0, hdr.min.y + 8.0), vec2(84.0, 24.0)); + let _ = widgets::text_button(ui, b, "Render", true, &t, egui::Id::new("rq-render")); + app.auto.add("renderQueue.render", b, "Render"); + p.line_segment([hdr.left_bottom(), hdr.right_bottom()], Stroke::new(1.0, t.separator)); + p.text( + pos2(rect.min.x + 14.0, hdr.max.y + 20.0), + Align2::LEFT_CENTER, + "Composition ▸ Add to Render Queue (⌃⌘M) to queue a render.", + Tokens::ui(12.0), + t.text_faint, + ); +} + +/// Home screen: new/open, recent, and community links. +pub fn start_screen(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let ctx = ui.ctx().clone(); + let p = ui.painter().with_clip_rect(rect); + p.rect_filled(rect, 0.0, Color32::from_rgb(0x1b, 0x1d, 0x24)); + let c = rect.center(); + let logo = Rect::from_center_size(c + vec2(0.0, -150.0), vec2(64.0, 64.0)); + crate::header::paint_logo(&p, logo); + p.text(c + vec2(0.0, -96.0), Align2::CENTER_CENTER, "EffectCraft", Tokens::semibold(28.0), Color32::WHITE); + p.text(c + vec2(0.0, -66.0), Align2::CENTER_CENTER, "Motion graphics and visual effects, in pure Rust.", Tokens::ui(13.0), t.text_dim); + let mut y = c.y - 30.0; + for (label, id, primary) in [ + ("New Composition", "app.newComp", true), + ("Open Demo Project", "file.openDemoProject", false), + ("Open Project…", "file.open", false), + ("Import Footage…", "file.import", false), + ] { + let r = Rect::from_center_size(pos2(c.x, y + 16.0), vec2(240.0, 32.0)); + if widgets::text_button(ui, r, label, primary, &t, egui::Id::new(("home", id))).clicked() { + let _ = crate::menus::invoke(app, &ctx, id, json!({})); + app.ui.start_screen = false; + } + app.auto.add(&format!("home.{id}"), r, label); + y += 40.0; + } + // Community. + y += 14.0; + let links = [(Icon::Chat, "Join the Discord", "help.discord"), (Icon::Globe, "getartcraft.com", "help.website"), (Icon::Code, "GitHub", "help.github")]; + let w = 170.0; + let mut x = c.x - w * 1.5 - 8.0; + for (icon, label, cmd) in links { + let r = Rect::from_min_size(pos2(x, y), vec2(w, 30.0)); + let resp = ui.interact(r, egui::Id::new(("home-link", cmd)), Sense::click()); + let discord = cmd == "help.discord"; + let bg = if discord { + Color32::from_rgb(0x58, 0x65, 0xf2) + } else if resp.hovered() { + t.hover + } else { + Color32::from_rgb(0x2a, 0x2c, 0x34) + }; + p.rect_filled(r, 15.0, bg); + icons::paint(&p, Rect::from_center_size(pos2(r.min.x + 20.0, r.center().y), vec2(14.0, 14.0)), icon, Color32::WHITE); + p.text(pos2(r.min.x + 34.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::medium(12.0), Color32::WHITE); + app.auto.add(&format!("home.{cmd}"), r, label); + if resp.clicked() { + let _ = app.session.execute(cmd, json!({})); + } + x += w + 8.0; + } + // Siblings. + y += 52.0; + p.text(pos2(c.x, y), Align2::CENTER_CENTER, "More ArtCraft apps", Tokens::ui(11.5), t.text_faint); + y += 18.0; + let sib = effectcraft_engine::links::SIBLINGS; + let sw = 104.0; + let mut x = c.x - sw * sib.len() as f32 / 2.0; + for (name, slug) in sib { + let r = Rect::from_min_size(pos2(x + 2.0, y), vec2(sw - 4.0, 24.0)); + let resp = ui.interact(r, egui::Id::new(("sib", *slug)), Sense::click()); + p.rect_filled(r, 12.0, if resp.hovered() { t.hover } else { Color32::from_rgb(0x24, 0x26, 0x2e) }); + p.text(r.center(), Align2::CENTER_CENTER, *name, Tokens::ui(11.5), t.text); + if resp.clicked() { + let _ = app.session.execute("help.sibling", json!({"app": slug})); + } + x += sw; + } +} diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs new file mode 100644 index 00000000..9d4e3848 --- /dev/null +++ b/crates/ui-egui/src/panels/mod.rs @@ -0,0 +1,128 @@ +//! Panel bodies. + +pub mod dialogs; +pub mod effect_controls; +pub mod effects_presets; +pub mod info; +pub mod misc; +pub mod project; +pub mod text_panels; +pub mod timeline; +pub mod viewer; + +use effectcraft_engine::Session; +use effectcraft_engine::project::{Comp, TimeDisplayStyle}; +use effectcraft_engine::time::Tick; +use egui::Rect; + +use crate::EffectcraftApp; +use crate::dock::PanelKind; + +/// Drag-and-drop payloads between panels. +#[derive(Clone, Debug)] +pub enum DragPayload { + /// A project item (footage, comp, solid). + Item(u64), + /// An effect id from Effects & Presets. + Effect(String), +} + +/// The current time formatted per project settings (timecode with `;` for drop-frame, or frames). +pub fn timecode(session: &Session, comp: &Comp, t: Tick) -> String { + let fr = comp.frame_rate; + match session.project.settings.time_display { + TimeDisplayStyle::Frames => format!("{:05}", fr.frame_at(t) + session.project.settings.frame_start), + TimeDisplayStyle::Timecode => { + let df = fr.supports_drop_frame(); + let s = effectcraft_engine::time::format_timecode_frames(fr.frame_at(t + comp.display_start), fr, df); + if df { s } else { s.replace(';', ":") } + } + } +} + +pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rect) { + match p { + PanelKind::Composition => { + if app.ui.start_screen { + misc::start_screen(app, ui, rect); + } else { + viewer::show(app, ui, rect) + } + } + PanelKind::Timeline => timeline::show(app, ui, rect), + PanelKind::Project => project::show(app, ui, rect), + PanelKind::EffectControls => effect_controls::show(app, ui, rect), + PanelKind::EffectsPresets => effects_presets::show(app, ui, rect), + PanelKind::Info => info::show(app, ui, rect), + PanelKind::Preview => misc::preview(app, ui, rect), + PanelKind::Character => text_panels::character(app, ui, rect), + PanelKind::Paragraph => text_panels::paragraph(app, ui, rect), + PanelKind::Align => text_panels::align(app, ui, rect), + PanelKind::Properties => effect_controls::properties(app, ui, rect), + PanelKind::Audio => misc::audio(app, ui, rect), + PanelKind::History => misc::history(app, ui, rect), + PanelKind::Markers => misc::markers(app, ui, rect), + PanelKind::Wiggler => misc::wiggler(app, ui, rect), + PanelKind::RenderQueue => misc::render_queue(app, ui, rect), + other => misc::placeholder(app, ui, rect, other), + } +} + +/// The ≡ panel menu (opened from a tab). +pub fn panel_menu_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui) { + let id = egui::Id::new("panel-menu"); + let Some((panel, pos)) = ui.ctx().data(|d| d.get_temp::<(PanelKind, egui::Pos2)>(id)) else { return }; + let mut close = false; + let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos).show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_min_width(200.0); + if ui.button("Close Panel").clicked() { + app.ui.dock.close(panel); + close = true; + } + if ui.button("Maximize Panel").clicked() { + app.ui.dock = crate::dock::DockNode::Tabs { panels: vec![panel], active: 0 }; + close = true; + } + ui.separator(); + match panel { + PanelKind::Timeline => { + for (label, id) in [ + ("Hide Shy Layers", "hideShy"), + ("Enable Frame Blending", "frameBlending"), + ("Enable Motion Blur", "motionBlur"), + ("Draft 3D", "draft3d"), + ] { + if ui.button(label).clicked() { + let _ = app.session.execute("comp.setSwitch", serde_json::json!({"switch": id})); + close = true; + } + } + if ui.button("Composition Settings…").clicked() { + let _ = dialogs::open_comp_settings(app); + close = true; + } + } + PanelKind::Composition => { + for (label, cmd) in [ + ("Composition Settings…", "app.compSettings"), + ("View Options…", "view.layerControls"), + ("Show Grid", "view.grid"), + ("Title/Action Safe", "view.safeMargins"), + ] { + if ui.button(label).clicked() { + let _ = crate::menus::invoke(app, &ui.ctx().clone(), cmd, serde_json::json!({})); + close = true; + } + } + } + _ => { + ui.label(egui::RichText::new(panel.title()).weak()); + } + } + }); + }); + if close || (ui.input(|i| i.pointer.any_pressed()) && !area.response.contains_pointer() && !area.response.hovered()) { + ui.ctx().data_mut(|d| d.remove::<(PanelKind, egui::Pos2)>(id)); + } +} diff --git a/crates/ui-egui/src/panels/project.rs b/crates/ui-egui/src/panels/project.rs new file mode 100644 index 00000000..bba588ad --- /dev/null +++ b/crates/ui-egui/src/panels/project.rs @@ -0,0 +1,264 @@ +//! The Project panel: item preview header, search, item list with columns, folders, and the +//! bottom bar (new folder, new comp, bit depth, delete). + +use effectcraft_engine::project::{Item, ItemId, ItemKind}; +use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2}; +use serde_json::json; + +use crate::icons::{self, Icon}; +use crate::panels::DragPayload; +use crate::theme::Tokens; +use crate::{EffectcraftApp, widgets}; + +fn item_icon(it: &Item) -> Icon { + match &it.kind { + ItemKind::Folder => Icon::Folder, + ItemKind::Comp(_) => Icon::Comp, + ItemKind::Solid(_) => Icon::Solid, + ItemKind::Footage(f) => match f.kind { + effectcraft_engine::project::FootageKind::Still | effectcraft_engine::project::FootageKind::Sequence => Icon::Image, + effectcraft_engine::project::FootageKind::Audio => Icon::Audio, + _ => Icon::Footage, + }, + } +} + +fn fmt_dur(secs: f64, fps: f64) -> String { + let f = (secs * fps).round() as i64; + let fpsi = fps.round().max(1.0) as i64; + format!("0;{:02};{:02};{:02}", f / fpsi / 60, (f / fpsi) % 60, f % fpsi) +} + +pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().clone(); + let ctx = ui.ctx().clone(); + // Preview header. + let head = Rect::from_min_size(rect.min, vec2(rect.width(), 74.0)); + let sel = app.session.state.project_selection.first().copied(); + if let Some(it) = sel.and_then(|i| app.session.project.item(i)).cloned() { + let thumb = Rect::from_min_size(head.min + vec2(10.0, 10.0), vec2(96.0, 54.0)); + p.rect_filled(thumb, 3.0, Color32::from_rgb(0x15, 0x15, 0x15)); + match &it.kind { + ItemKind::Solid(s) => { + p.rect_filled(thumb.shrink(4.0), 2.0, Color32::from_rgb((s.color[0] * 255.0) as u8, (s.color[1] * 255.0) as u8, (s.color[2] * 255.0) as u8)); + } + ItemKind::Comp(_) => { + if let Some((tex, k)) = &app.viewer_tex + && k.comp == it.id.0 + { + p.image(tex.id(), thumb, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } else { + icons::paint(&p, Rect::from_center_size(thumb.center(), vec2(24.0, 24.0)), Icon::Comp, t.text_dim); + } + } + _ => icons::paint(&p, Rect::from_center_size(thumb.center(), vec2(24.0, 24.0)), item_icon(&it), t.text_dim), + } + let tx = thumb.max.x + 10.0; + p.text(pos2(tx, thumb.min.y + 6.0), Align2::LEFT_CENTER, &it.name, Tokens::semibold(12.0), t.text); + let mut lines = vec![]; + if let Some((w, h)) = it.dimensions() { + lines.push(format!("{w} x {h} (1.00)")); + } + if let Some(d) = it.duration() { + let fps = it.frame_rate().map(|r| r.as_f64()).unwrap_or(30.0); + lines.push(format!("Δ {}, {:.2} fps", fmt_dur(d.seconds(), fps), fps)); + } + if let ItemKind::Footage(f) = &it.kind { + lines.push(f.codec.clone()); + } + for (i, l) in lines.iter().enumerate() { + p.text(pos2(tx, thumb.min.y + 22.0 + 13.0 * i as f32), Align2::LEFT_CENTER, l, Tokens::ui(11.0), t.text_dim); + } + } else { + p.text(head.center(), Align2::CENTER_CENTER, "Select an item to see its details", Tokens::ui(11.0), t.text_faint); + } + // Search. + let sr = Rect::from_min_size(pos2(rect.min.x + 8.0, head.max.y + 2.0), vec2(rect.width() - 16.0, 22.0)); + let mut q = app.ui.project_search.clone(); + widgets::search_field(ui, sr, &mut q, "Search project", &t); + app.ui.project_search = q; + app.auto.add("project.search", sr, "Search"); + // Column header. + let hdr = Rect::from_min_size(pos2(rect.min.x, sr.max.y + 6.0), vec2(rect.width(), 20.0)); + p.line_segment([hdr.left_bottom(), hdr.right_bottom()], Stroke::new(1.0, t.separator)); + let name_w = (rect.width() * 0.48).max(140.0); + let col_type = rect.min.x + name_w + 30.0; + let col_size = col_type + 76.0; + p.text(pos2(rect.min.x + 26.0, hdr.center().y), Align2::LEFT_CENTER, "Name", Tokens::ui(11.0), t.text_dim); + icons::paint(&p, Rect::from_center_size(pos2(rect.min.x + name_w + 14.0, hdr.center().y), vec2(10.0, 10.0)), Icon::Keyframe, t.text_dim); + p.text(pos2(col_type, hdr.center().y), Align2::LEFT_CENTER, "Type", Tokens::ui(11.0), t.text_dim); + p.text(pos2(col_size, hdr.center().y), Align2::LEFT_CENTER, "Size", Tokens::ui(11.0), t.text_dim); + // Rows. + let footer_h = 28.0; + let list = Rect::from_min_max(pos2(rect.min.x, hdr.max.y), pos2(rect.max.x, rect.max.y - footer_h)); + let lp = p.with_clip_rect(list); + let mut y = list.min.y; + let query = app.ui.project_search.to_lowercase(); + let mut rows: Vec<(ItemId, usize)> = vec![]; + fn walk(app: &EffectcraftApp, folder: Option, depth: usize, q: &str, out: &mut Vec<(ItemId, usize)>) { + for it in app.session.project.children(folder) { + if !q.is_empty() && !it.is_folder() && !it.name.to_lowercase().contains(q) { + continue; + } + out.push((it.id, depth)); + if it.is_folder() && (app.ui.project_open_folders.contains(&it.id.0) || !q.is_empty()) { + walk(app, Some(it.id), depth + 1, q, out); + } + } + } + walk(app, None, 0, &query, &mut rows); + let mut actions: Vec<(String, serde_json::Value)> = vec![]; + for (i, (id, depth)) in rows.iter().enumerate() { + let Some(it) = app.session.project.item(*id).cloned() else { continue }; + let r = Rect::from_min_size(pos2(list.min.x, y), vec2(list.width(), 22.0)); + y += 22.0; + if r.min.y > list.max.y { + break; + } + let selected = app.session.state.project_selection.contains(id); + lp.rect_filled( + r, + 0.0, + if selected { + t.row_selected + } else if i % 2 == 0 { + t.row + } else { + t.row_alt + }, + ); + let x0 = r.min.x + 8.0 + 14.0 * *depth as f32; + if it.is_folder() { + let open = app.ui.project_open_folders.contains(&id.0); + let tw = Rect::from_center_size(pos2(x0 + 4.0, r.center().y), vec2(12.0, 12.0)); + if widgets::twirl(ui, tw, open, egui::Id::new(("pf", id.0)), &t).clicked() { + if open { + app.ui.project_open_folders.remove(&id.0); + } else { + app.ui.project_open_folders.insert(id.0); + } + } + } + icons::paint( + &lp, + Rect::from_center_size(pos2(x0 + 18.0, r.center().y), vec2(14.0, 14.0)), + item_icon(&it), + if it.is_folder() { Color32::from_rgb(0xd8, 0xc0, 0x60) } else { t.text_dim }, + ); + lp.text(pos2(x0 + 30.0, r.center().y), Align2::LEFT_CENTER, &it.name, Tokens::ui(12.0), if selected { Color32::WHITE } else { t.text }); + lp.rect_filled(Rect::from_center_size(pos2(r.min.x + name_w + 14.0, r.center().y), vec2(10.0, 10.0)), 2.0, Tokens::label(it.label)); + lp.text(pos2(col_type, r.center().y), Align2::LEFT_CENTER, it.type_name(), Tokens::ui(11.5), t.text_dim); + if let Some((w, h)) = it.dimensions() { + lp.text(pos2(col_size, r.center().y), Align2::LEFT_CENTER, format!("{w} x {h}"), Tokens::ui(11.5), t.text_dim); + } + let resp = ui.interact(r.intersect(list), egui::Id::new(("pitem", id.0)), Sense::click_and_drag()); + app.auto.add(&format!("project.item.{}", id.0), r, &it.name); + if resp.clicked() { + let add = ui.input(|i| i.modifiers.command || i.modifiers.shift); + if add { + if !app.session.state.project_selection.contains(id) { + app.session.state.project_selection.push(*id); + } + } else { + app.session.state.project_selection = vec![*id]; + } + } + if resp.double_clicked() { + match &it.kind { + ItemKind::Comp(_) => actions.push(("comp.open".into(), json!({"comp": id.0}))), + ItemKind::Folder => { + if !app.ui.project_open_folders.remove(&id.0) { + app.ui.project_open_folders.insert(id.0); + } + } + _ => {} + } + } + if resp.drag_started() && !it.is_folder() { + egui::DragAndDrop::set_payload(&ctx, DragPayload::Item(id.0)); + } + resp.context_menu(|ui| { + if matches!(it.kind, ItemKind::Comp(_)) && ui.button("Open Composition").clicked() { + actions.push(("comp.open".into(), json!({"comp": id.0}))); + ui.close(); + } + if !it.is_folder() && ui.button("Add to Composition").clicked() { + actions.push(("layer.addItem".into(), json!({"item": id.0}))); + ui.close(); + } + if ui.button("New Comp from Selection").clicked() { + if let Some((w, h)) = it.dimensions() { + let d = it.duration().map(|d| d.seconds()).unwrap_or(10.0); + actions.push(("comp.new".into(), json!({"name": format!("{} Comp", it.name), "width": w, "height": h, "duration": d}))); + actions.push(("layer.addItem".into(), json!({"item": id.0}))); + } + ui.close(); + } + }); + } + // Drag ghost. + if let Some(DragPayload::Item(iid)) = egui::DragAndDrop::payload::(&ctx).as_deref() + && let Some(pos) = ctx.pointer_hover_pos() + && let Some(it) = app.session.project.item(ItemId(*iid)) + { + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("dnd-ghost"))); + let g = painter.layout_no_wrap(it.name.clone(), Tokens::ui(12.0), t.text); + let r = Rect::from_min_size(pos + vec2(12.0, 8.0), g.size() + vec2(16.0, 8.0)); + painter.rect_filled(r, 4.0, Color32::from_rgba_premultiplied(40, 40, 40, 230)); + painter.galley(r.min + vec2(8.0, 4.0), g, t.text); + } + // Footer. + let foot = Rect::from_min_max(pos2(rect.min.x, rect.max.y - footer_h), rect.max); + p.line_segment([foot.left_top(), foot.right_top()], Stroke::new(1.0, t.separator)); + let mut x = foot.min.x + 8.0; + for (icon, id, tip) in [ + (Icon::Gear, "interpret", "Interpret Footage"), + (Icon::NewFolder, "newFolder", "Create a new Folder"), + (Icon::NewComp, "newComp", "Create a new Composition"), + ] { + let r = Rect::from_min_size(pos2(x, foot.min.y + 3.0), vec2(22.0, 22.0)); + let resp = widgets::icon_button(ui, r, icon, false, &t, egui::Id::new(("pfoot", id))).on_hover_text(tip); + app.auto.add(&format!("project.{id}"), r, tip); + if resp.clicked() { + match id { + "newComp" => crate::panels::dialogs::open_new_comp(app), + "newFolder" => { + let _ = app.session.edit("New Folder", None, |proj, st| { + let id = proj.add_item("Untitled Folder", effectcraft_engine::color::Label::Yellow, None, ItemKind::Folder); + st.project_selection = vec![id]; + Ok(()) + }); + } + _ => app.ui.status = "Interpret Footage: select a footage item".into(), + } + } + x += 26.0; + } + let depth = app.session.project.settings.bit_depth.label(); + let dr = Rect::from_min_size(pos2(x + 4.0, foot.min.y + 5.0), vec2(48.0, 18.0)); + let dresp = ui.interact(dr, egui::Id::new("bpc"), Sense::click()); + p.text(dr.center(), Align2::CENTER_CENTER, depth, Tokens::ui(11.5), if dresp.hovered() { t.text } else { t.text_dim }); + app.auto.add("project.bitDepth", dr, depth); + if dresp.clicked() { + actions.push(("file.cycleBitDepth".into(), json!({}))); + } + let tr = Rect::from_min_size(pos2(foot.max.x - 30.0, foot.min.y + 3.0), vec2(22.0, 22.0)); + if widgets::icon_button(ui, tr, Icon::Trash, false, &t, egui::Id::new("ptrash")).on_hover_text("Delete selected project items").clicked() { + let sel = app.session.state.project_selection.clone(); + let _ = app.session.edit("Delete Items", None, |proj, st| { + for id in &sel { + proj.items.remove(id); + } + st.project_selection.clear(); + Ok(()) + }); + app.session.sanitize_state(); + } + app.auto.add("project.delete", tr, "Delete"); + for (id, params) in actions { + if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) { + app.ui.status = e; + } + } +} diff --git a/crates/ui-egui/src/panels/text_panels.rs b/crates/ui-egui/src/panels/text_panels.rs new file mode 100644 index 00000000..62f02fd5 --- /dev/null +++ b/crates/ui-egui/src/panels/text_panels.rs @@ -0,0 +1,280 @@ +//! Character, Paragraph and Align panels. + +use effectcraft_engine::keyframe::{Justify, TextDoc}; +use effectcraft_engine::render::EvalCtx; +use egui::{Align2, Rect, Sense, pos2, vec2}; +use serde_json::json; + +use crate::icons::{self, Icon}; +use crate::theme::Tokens; +use crate::{EffectcraftApp, widgets}; + +/// The selected text layer's Source Text at the CTI. +fn text_doc(app: &EffectcraftApp) -> Option<(u64, TextDoc)> { + let comp = app.session.active_comp()?; + let cid = app.session.active_comp_id()?; + let layer = app + .session + .state + .selected_layers + .iter() + .filter_map(|id| comp.layer(*id)) + .find(|l| matches!(l.source, effectcraft_engine::project::LayerSource::Text))?; + let ectx = EvalCtx { project: &app.session.project, comp_id: cid, comp, time: app.session.time(), expr: app.session.expr.as_deref() }; + effectcraft_engine::render::text::source_text(&ectx, layer).map(|d| (layer.id.0, d)) +} + +pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let ctx = ui.ctx().clone(); + let (lid, doc) = text_doc(app).unwrap_or((0, TextDoc::default())); + let enabled = lid != 0; + let mut y = rect.min.y + 10.0; + let x0 = rect.min.x + 10.0; + let w = rect.width() - 20.0; + let mut actions: Vec = vec![]; + // Font family + style. + let fr = Rect::from_min_size(pos2(x0, y), vec2(w, 22.0)); + let pop = egui::Id::new("char-font-pop"); + if widgets::dropdown(ui, fr, &doc.font, &t, egui::Id::new("char-font")).clicked() && enabled { + widgets::open_popup(ui, pop); + } + app.auto.add("character.font", fr, "Font family"); + let fams: Vec = effectcraft_engine::text_families(); + if let Some(i) = widgets::popup_menu(ui, pop, fr.left_bottom(), &fams, fams.iter().position(|f| *f == doc.font)) { + actions.push(json!({"font": fams[i]})); + } + y += 28.0; + let sr = Rect::from_min_size(pos2(x0, y), vec2(w, 22.0)); + let spop = egui::Id::new("char-style-pop"); + if widgets::dropdown(ui, sr, &doc.style, &t, egui::Id::new("char-style")).clicked() && enabled { + widgets::open_popup(ui, spop); + } + app.auto.add("character.style", sr, "Font style"); + let styles: Vec = ["Regular", "Medium", "SemiBold", "Bold", "Italic"].iter().map(|s| s.to_string()).collect(); + if let Some(i) = widgets::popup_menu(ui, spop, sr.left_bottom(), &styles, styles.iter().position(|s| *s == doc.style)) { + actions.push(json!({"style": styles[i]})); + } + y += 34.0; + // Numeric fields in a 2-column grid. + let fields: [(&str, &str, f64, (f64, f64), &str); 6] = [ + ("size", "T", doc.size, (1.0, 2000.0), " px"), + ("leading", "A", doc.leading.unwrap_or(doc.size * 1.2), (0.0, 5000.0), " px"), + ("tracking", "VA", doc.tracking, (-1000.0, 10000.0), ""), + ("strokeWidth", "≡", doc.stroke_width, (0.0, 500.0), " px"), + ("baselineShift", "A↑", doc.baseline_shift, (-1000.0, 1000.0), " px"), + ("hScale", "↔", doc.h_scale, (1.0, 1000.0), "%"), + ]; + for (i, (key, glyph, v, range, suffix)) in fields.into_iter().enumerate() { + let col = i % 2; + let row = i / 2; + let fx = x0 + col as f32 * (w / 2.0); + let fy = y + row as f32 * 28.0; + p.text(pos2(fx, fy + 9.0), Align2::LEFT_CENTER, glyph, Tokens::semibold(11.0), t.text_dim); + let (r, nv, _) = widgets::hot_number_at(ui, pos2(fx + 26.0, fy), egui::Id::new(("char", key)), v, 0.5, range, 0, suffix, &t); + app.auto.add(&format!("character.{key}"), r, key); + if let Some(nv) = nv + && enabled + { + let k = if key == "baselineShift" || key == "hScale" { "tracking" } else { key }; + if k == key { + actions.push(json!({key: nv, "merge": format!("char-{key}")})); + } + } + } + y += 3.0 * 28.0 + 8.0; + // Fill / stroke swatches. + p.text(pos2(x0, y + 10.0), Align2::LEFT_CENTER, "Fill", Tokens::ui(11.5), t.text_dim); + let fs = Rect::from_min_size(pos2(x0 + 34.0, y), vec2(26.0, 20.0)); + if widgets::swatch(ui, fs, doc.fill, egui::Id::new("char-fill"), &t).clicked() && enabled { + widgets::open_popup(ui, egui::Id::new("char-fill-pop")); + } + app.auto.add("character.fill", fs, "Fill color"); + let mut fc = [doc.fill[0], doc.fill[1], doc.fill[2]]; + if crate::header::color_popup(ui, egui::Id::new("char-fill-pop"), fs.left_bottom(), &mut fc) { + actions.push(json!({"fill": [fc[0], fc[1], fc[2]], "merge": "char-fill"})); + } + p.text(pos2(x0 + 80.0, y + 10.0), Align2::LEFT_CENTER, "Stroke", Tokens::ui(11.5), t.text_dim); + let ss = Rect::from_min_size(pos2(x0 + 126.0, y), vec2(26.0, 20.0)); + if widgets::swatch(ui, ss, doc.stroke, egui::Id::new("char-stroke"), &t).clicked() && enabled { + widgets::open_popup(ui, egui::Id::new("char-stroke-pop")); + } + app.auto.add("character.stroke", ss, "Stroke color"); + let mut sc = [doc.stroke[0], doc.stroke[1], doc.stroke[2]]; + if crate::header::color_popup(ui, egui::Id::new("char-stroke-pop"), ss.left_bottom(), &mut sc) { + actions.push(json!({"stroke": [sc[0], sc[1], sc[2]], "merge": "char-stroke"})); + } + y += 32.0; + // Style toggles. + let toggles = [("fauxBold", "T", doc.faux_bold), ("fauxItalic", "T", doc.faux_italic), ("allCaps", "TT", doc.all_caps)]; + for (i, (key, label, on)) in toggles.into_iter().enumerate() { + let r = Rect::from_min_size(pos2(x0 + i as f32 * 34.0, y), vec2(30.0, 24.0)); + let resp = ui.interact(r, egui::Id::new(("char-t", key)), Sense::click()); + p.rect_filled( + r, + 3.0, + if on { + t.accent + } else if resp.hovered() { + t.hover + } else { + t.field_bg + }, + ); + let font = if key == "fauxBold" { Tokens::semibold(13.0) } else { Tokens::ui(12.0) }; + p.text(r.center(), Align2::CENTER_CENTER, label, font, if on { egui::Color32::WHITE } else { t.text }); + app.auto.add(&format!("character.{key}"), r, key); + if resp.clicked() && enabled { + actions.push(json!({key: !on})); + } + } + if !enabled { + p.text(pos2(rect.center().x, rect.max.y - 20.0), Align2::CENTER_CENTER, "Select a text layer", Tokens::ui(11.0), t.text_faint); + } + for mut a in actions { + a["layer"] = json!(lid); + if let Err(e) = crate::menus::invoke(app, &ctx, "layer.setText", a) { + app.ui.status = e; + } + } +} + +pub fn paragraph(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let ctx = ui.ctx().clone(); + let (lid, doc) = text_doc(app).unwrap_or((0, TextDoc::default())); + let x0 = rect.min.x + 10.0; + let y = rect.min.y + 10.0; + let opts = [ + (Justify::Left, "left"), + (Justify::Center, "center"), + (Justify::Right, "right"), + (Justify::JustifyLastLeft, "justify"), + (Justify::JustifyAll, "justifyAll"), + ]; + for (i, (j, key)) in opts.into_iter().enumerate() { + let r = Rect::from_min_size(pos2(x0 + i as f32 * 32.0, y), vec2(28.0, 26.0)); + let on = doc.justify == j; + let resp = ui.interact(r, egui::Id::new(("para", key)), Sense::click()); + p.rect_filled( + r, + 3.0, + if on { + t.accent + } else if resp.hovered() { + t.hover + } else { + t.field_bg + }, + ); + let c = if on { egui::Color32::WHITE } else { t.text }; + for k in 0..4 { + let ly = r.min.y + 7.0 + k as f32 * 4.0; + let full = r.width() - 12.0; + let lw = if k % 2 == 1 && !matches!(j, Justify::JustifyAll) { full * 0.65 } else { full }; + let lx = match j { + Justify::Center => r.center().x - lw / 2.0, + Justify::Right => r.max.x - 6.0 - lw, + _ => r.min.x + 6.0, + }; + p.line_segment([pos2(lx, ly), pos2(lx + lw, ly)], egui::Stroke::new(1.4, c)); + } + app.auto.add(&format!("paragraph.{key}"), r, key); + if resp.clicked() && lid != 0 { + let _ = crate::menus::invoke(app, &ctx, "layer.setText", json!({"layer": lid, "justify": key})); + } + } + if lid == 0 { + p.text(pos2(rect.center().x, rect.max.y - 20.0), Align2::CENTER_CENTER, "Select a text layer", Tokens::ui(11.0), t.text_faint); + } +} + +/// Align panel: align selected layers to the composition (or to the selection). +pub fn align(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter().with_clip_rect(rect); + let x0 = rect.min.x + 10.0; + let y = rect.min.y + 10.0; + p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Align Layers to: Composition", Tokens::ui(11.5), t.text_dim); + let ops = ["left", "hcenter", "right", "top", "vcenter", "bottom"]; + for (i, op) in ops.iter().enumerate() { + let r = Rect::from_min_size(pos2(x0 + i as f32 * 34.0 + if i >= 3 { 12.0 } else { 0.0 }, y + 24.0), vec2(30.0, 28.0)); + let resp = ui.interact(r, egui::Id::new(("align", *op)), Sense::click()); + p.rect_filled(r, 3.0, if resp.hovered() { t.hover } else { t.field_bg }); + // Glyph: a bar (alignment edge) and two boxes. + let c = r.center(); + let st = egui::Stroke::new(1.3, t.text); + match *op { + "left" | "hcenter" | "right" => { + let ex = match *op { + "left" => r.min.x + 7.0, + "right" => r.max.x - 7.0, + _ => c.x, + }; + p.line_segment([pos2(ex, r.min.y + 5.0), pos2(ex, r.max.y - 5.0)], st); + let off = |w: f32| match *op { + "left" => ex, + "right" => ex - w, + _ => ex - w / 2.0, + }; + p.rect_filled(Rect::from_min_size(pos2(off(14.0), c.y - 7.0), vec2(14.0, 5.0)), 1.0, t.text_dim); + p.rect_filled(Rect::from_min_size(pos2(off(9.0), c.y + 2.0), vec2(9.0, 5.0)), 1.0, t.text_dim); + } + _ => { + let ey = match *op { + "top" => r.min.y + 6.0, + "bottom" => r.max.y - 6.0, + _ => c.y, + }; + p.line_segment([pos2(r.min.x + 5.0, ey), pos2(r.max.x - 5.0, ey)], st); + let off = |h: f32| match *op { + "top" => ey, + "bottom" => ey - h, + _ => ey - h / 2.0, + }; + p.rect_filled(Rect::from_min_size(pos2(c.x - 8.0, off(14.0)), vec2(5.0, 14.0)), 1.0, t.text_dim); + p.rect_filled(Rect::from_min_size(pos2(c.x + 3.0, off(9.0)), vec2(5.0, 9.0)), 1.0, t.text_dim); + } + } + app.auto.add(&format!("align.{op}"), r, op); + if resp.clicked() { + align_layers(app, op); + } + } + let _ = icons::paint; + let _ = Icon::Grid; +} + +/// Move selected layers so their content bounds align to the comp. +pub fn align_layers(app: &mut EffectcraftApp, op: &str) { + let Some(cid) = app.session.active_comp_id() else { return }; + let Some(comp) = app.session.project.comp(cid).cloned() else { return }; + let time = app.session.time(); + let mut moves = vec![]; + { + let ectx = EvalCtx { project: &app.session.project, comp_id: cid, comp: &comp, time, expr: app.session.expr.as_deref() }; + for l in comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id)) { + let Some(b) = effectcraft_engine::render::content_bounds(&ectx, l) else { continue }; + let (m, _) = ectx.layer_to_comp(l); + let pts = [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]].map(|p| m.apply(effectcraft_engine::geom::vec2(p[0], p[1]))); + let (x0, x1) = (pts.iter().map(|p| p.x).fold(f64::INFINITY, f64::min), pts.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max)); + let (y0, y1) = (pts.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), pts.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max)); + let (cw, ch) = (comp.width as f64, comp.height as f64); + let (dx, dy) = match op { + "left" => (-x0, 0.0), + "right" => (cw - x1, 0.0), + "hcenter" => (cw / 2.0 - (x0 + x1) / 2.0, 0.0), + "top" => (0.0, -y0), + "bottom" => (0.0, ch - y1), + _ => (0.0, ch / 2.0 - (y0 + y1) / 2.0), + }; + let pos = l.transform().map(|tr| ectx.v3(l, tr, "position", [0.0; 3])).unwrap_or([0.0; 3]); + moves.push((l.id.0, [pos[0] + dx, pos[1] + dy, pos[2]])); + } + } + for (id, v) in moves { + let _ = app.session.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": v})); + } +} diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs new file mode 100644 index 00000000..53b0cdc8 --- /dev/null +++ b/crates/ui-egui/src/panels/timeline.rs @@ -0,0 +1,1497 @@ +//! The Timeline panel. +//! +//! Left: current-time display, search, comp switches, then per layer A/V features (video, audio, +//! solo, lock), label, number, name, switches (shy, collapse, quality, fx, frame blend, motion +//! blur, adjustment, 3D), mode, track matte and parent, with twirl-down property trees (stopwatch, +//! keyframe navigator, scrubbable values). Right: time navigator, ruler with work area and cache +//! bar, layer duration bars, keyframes, the CTI, and the value graph editor. + +use effectcraft_engine::color::BlendMode; +use effectcraft_engine::keyframe::Value; +use effectcraft_engine::project::{Comp, GroupKind, Layer, LayerId, LayerSource, MatteKind, Node, ParamUi, PropGroup, Property}; +use effectcraft_engine::render::EvalCtx; +use effectcraft_engine::time::Tick; +use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use serde_json::json; + +use crate::icons::{self, Icon}; +use crate::theme::Tokens; +use crate::{EffectcraftApp, widgets}; + +#[derive(Clone, Debug)] +enum RowKind { + Layer, + Group { uid: u64, name: String, open: bool, has_children: bool, fx: Option }, + Prop { uid: u64 }, +} + +#[derive(Clone, Debug)] +struct Row { + layer: LayerId, + depth: usize, + kind: RowKind, +} + +const AV_W: f32 = 76.0; +const LABEL_W: f32 = 20.0; +const NUM_W: f32 = 26.0; +const SW: f32 = 19.0; + +struct Cols { + av: f32, + label: f32, + num: f32, + name: f32, + name_w: f32, + switches: f32, + mode: f32, + trkmat: f32, + parent: f32, + end: f32, +} + +fn cols(x0: f32, width: f32, show_modes: bool) -> Cols { + let fixed = AV_W + LABEL_W + NUM_W + SW * 8.0 + if show_modes { 92.0 + 112.0 } else { 0.0 } + 116.0; + let name_w = (width - fixed).max(120.0); + let av = x0; + let label = av + AV_W; + let num = label + LABEL_W; + let name = num + NUM_W; + let switches = name + name_w; + let mode = switches + SW * 8.0 + 6.0; + let trkmat = mode + if show_modes { 92.0 } else { 0.0 }; + let parent = trkmat + if show_modes { 112.0 } else { 0.0 }; + Cols { av, label, num, name, name_w, switches, mode, trkmat, parent, end: parent + 116.0 } +} + +/// Timeline horizontal mapping. +#[derive(Clone, Copy, Debug)] +struct TMap { + x0: f32, + start: f64, + pps: f64, +} + +impl TMap { + fn x(&self, secs: f64) -> f32 { + self.x0 + ((secs - self.start) * self.pps) as f32 + } + fn t(&self, x: f32) -> f64 { + self.start + (x - self.x0) as f64 / self.pps + } +} + +fn tl_map_id() -> egui::Id { + egui::Id::new("timeline-map") +} + +/// Zoom the time ruler around the CTI. +pub fn zoom(app: &mut EffectcraftApp, ctx: &egui::Context, k: f64) { + let Some((x0, w)) = ctx.data(|d| d.get_temp::<(f32, f32)>(egui::Id::new("timeline-graph-area"))) else { return }; + let comp = app.session.active_comp().cloned(); + let Some(comp) = comp else { return }; + let fit = (w as f64 - 20.0) / comp.duration.seconds().max(0.01); + let pps = app.ui.timeline.pps.unwrap_or(fit); + let npps = (pps * k).clamp(fit.min(1.0), 4000.0); + let cti = app.session.time().seconds(); + let rel = (cti - app.ui.timeline.start) * pps; + app.ui.timeline.start = (cti - rel / npps).max(0.0); + app.ui.timeline.pps = Some(npps); + let _ = x0; +} + +/// Screen point of a layer bar (centre, or at a comp time). +pub fn locate(app: &EffectcraftApp, layer: u64, time: Option) -> Option<(f32, f32)> { + let e = app.auto.find(&format!("timeline.layer.{layer}.bar"))?; + let y = e.rect[1] + e.rect[3] / 2.0; + match time { + Some(t) => { + // The ruler element's label carries "start,pps". + let tm = app.auto.find("timeline.ruler")?; + let (start, pps) = tm.label.split_once(',').and_then(|(a, b)| Some((a.parse::().ok()?, b.parse::().ok()?)))?; + Some((tm.rect[0] + 6.0 + ((t - start) * pps) as f32, y)) + } + None => Some((e.rect[0] + e.rect[2] / 2.0, y)), + } +} + +/// Start renaming the first selected layer. +pub fn begin_rename(app: &mut EffectcraftApp, ctx: &egui::Context) { + if let Some(l) = app.session.state.selected_layers.first().and_then(|id| app.session.active_comp().and_then(|c| c.layer(*id))) { + ctx.data_mut(|d| d.insert_temp(egui::Id::new("tl-rename"), (l.id.0, l.name.clone()))); + } +} + +fn group_visible(g: &PropGroup, layer: &Layer) -> bool { + match g.match_id.as_str() { + "masks" | "effects" => !g.children.is_empty(), + "materialOptions" | "geometryOptions" => layer.is_3d(), + "audio" => true, + _ => true, + } +} + +fn prop_visible(p: &Property, layer: &Layer) -> bool { + if matches!(p.ui, ParamUi::Hidden) { + return false; + } + if p.three_d_only && !layer.is_3d() { + return false; + } + if p.two_d_only && layer.is_3d() { + return false; + } + true +} + +fn reveal_matches(p: &Property, path_matches: &[&str], kind: &str) -> bool { + match kind { + "animated" => p.is_animated() || p.has_expression(), + _ => path_matches.contains(&p.match_id.as_str()), + } +} + +fn build_rows(app: &EffectcraftApp, comp: &Comp) -> Vec { + let tl = &app.ui.timeline; + let search = tl.search.to_lowercase(); + let mut rows = Vec::new(); + for l in &comp.layers { + if comp.hide_shy && l.switches.shy { + continue; + } + if !search.is_empty() && !l.name.to_lowercase().contains(&search) { + continue; + } + rows.push(Row { layer: l.id, depth: 0, kind: RowKind::Layer }); + if !tl.open_layers.contains(&l.id.0) { + continue; + } + if let Some(kind) = tl.reveal.first() { + let (group, props): (&str, Vec<&str>) = match kind.as_str() { + "position" => ("transform", vec!["position"]), + "scale" => ("transform", vec!["scale"]), + "rotation" => ("transform", vec!["rotation", "rotationX", "rotationY", "orientation"]), + "opacity" => ("transform", vec!["opacity"]), + "anchor" => ("transform", vec!["anchor"]), + "feather" => ("masks", vec!["feather"]), + _ => ("", vec![]), + }; + match kind.as_str() { + "effects" => { + if let Some(fx) = l.effects() { + for g in fx.groups() { + rows.push(Row { + layer: l.id, + depth: 1, + kind: RowKind::Group { + uid: g.uid, + name: g.name.clone(), + open: tl.open_groups.contains(&g.uid), + has_children: true, + fx: Some(g.enabled), + }, + }); + if tl.open_groups.contains(&g.uid) { + push_group(&mut rows, l, g, 2, &tl.open_groups); + } + } + } + } + "masks" => { + if let Some(m) = l.masks() { + for g in m.groups() { + rows.push(Row { + layer: l.id, + depth: 1, + kind: RowKind::Group { uid: g.uid, name: g.name.clone(), open: tl.open_groups.contains(&g.uid), has_children: true, fx: None }, + }); + if tl.open_groups.contains(&g.uid) { + push_group(&mut rows, l, g, 2, &tl.open_groups); + } + } + } + } + _ => { + let mut found = vec![]; + let root = if group.is_empty() { + Some(&l.props) + } else if group == "masks" { + l.masks() + } else { + l.props.sub(group) + }; + if let Some(g) = root { + collect_props(g, &mut found, &|p| prop_visible(p, l) && reveal_matches(p, &props, kind)); + } + for uid in found { + rows.push(Row { layer: l.id, depth: 1, kind: RowKind::Prop { uid } }); + } + } + } + continue; + } + for c in &l.props.children { + match c { + Node::Group(g) if group_visible(g, l) => { + let open = tl.open_groups.contains(&g.uid); + rows.push(Row { + layer: l.id, + depth: 1, + kind: RowKind::Group { uid: g.uid, name: g.name.clone(), open, has_children: !g.children.is_empty(), fx: None }, + }); + if open { + push_group(&mut rows, l, g, 2, &tl.open_groups); + } + } + Node::Prop(p) if prop_visible(p, l) => rows.push(Row { layer: l.id, depth: 1, kind: RowKind::Prop { uid: p.uid } }), + _ => {} + } + } + } + rows +} + +fn collect_props(g: &PropGroup, out: &mut Vec, f: &dyn Fn(&Property) -> bool) { + for c in &g.children { + match c { + Node::Prop(p) if f(p) => out.push(p.uid), + Node::Group(g) => collect_props(g, out, f), + _ => {} + } + } +} + +fn push_group(rows: &mut Vec, l: &Layer, g: &PropGroup, depth: usize, open: &std::collections::BTreeSet) { + for c in &g.children { + match c { + Node::Group(sg) => { + let o = open.contains(&sg.uid); + let fx = matches!(sg.kind, GroupKind::Effect { .. }).then_some(sg.enabled); + rows.push(Row { + layer: l.id, + depth, + kind: RowKind::Group { uid: sg.uid, name: sg.name.clone(), open: o, has_children: !sg.children.is_empty(), fx }, + }); + if o { + push_group(rows, l, sg, depth + 1, open); + } + } + Node::Prop(p) if prop_visible(p, l) => rows.push(Row { layer: l.id, depth, kind: RowKind::Prop { uid: p.uid } }), + _ => {} + } + } +} + +fn layer_icon(l: &Layer, project: &effectcraft_engine::project::Project) -> Icon { + match &l.source { + LayerSource::Text => Icon::TextLayer, + LayerSource::Shape => Icon::ShapeLayer, + LayerSource::Null => Icon::Null, + LayerSource::Camera => Icon::Camera, + LayerSource::Light { .. } => Icon::Light, + LayerSource::Comp { .. } => Icon::Comp, + LayerSource::Solid { .. } => { + if l.switches.adjustment { + Icon::Adjustment + } else { + Icon::Solid + } + } + LayerSource::Footage { item } => match project.item(*item).map(|i| i.type_name()) { + Some("Image") | Some("Image Sequence") => Icon::Image, + Some("Audio") => Icon::Audio, + _ => Icon::Footage, + }, + } +} + +pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let ctx = ui.ctx().clone(); + let Some(cid) = app.session.active_comp_id() else { + ui.painter().text(rect.center(), Align2::CENTER_CENTER, "(no composition)", Tokens::ui(12.0), t.text_faint); + return; + }; + let Some(comp) = app.session.project.comp(cid).cloned() else { return }; + let p = ui.painter().clone(); + let time = app.session.time(); + let fr = comp.frame_rate; + + // Geometry. + let header_h = 48.0; + let ruler_h = 34.0; + let colhdr_h = 22.0; + let footer_h = 24.0; + let left_w = (rect.width() * 0.5).clamp(420.0, 860.0); + let cw = cols(rect.min.x, left_w, app.ui.timeline.show_modes); + let graph_x0 = rect.min.x + left_w + 1.0; + let graph_x1 = rect.max.x - 10.0; + ctx.data_mut(|d| d.insert_temp(egui::Id::new("timeline-graph-area"), (graph_x0, graph_x1 - graph_x0))); + let fit_pps = (graph_x1 - graph_x0 - 10.0) as f64 / comp.duration.seconds().max(0.01); + let pps = app.ui.timeline.pps.unwrap_or(fit_pps); + if app.ui.timeline.pps.is_none() { + app.ui.timeline.start = 0.0; + } + let tm = TMap { x0: graph_x0 + 6.0, start: app.ui.timeline.start, pps }; + ctx.data_mut(|d| d.insert_temp(tl_map_id(), (tm.x0, tm.start, tm.pps))); + let top = rect.min.y; + let rows_top = top + header_h + colhdr_h; + let rows_rect = Rect::from_min_max(pos2(rect.min.x, rows_top), pos2(rect.max.x, rect.max.y - footer_h)); + let graph_rect = Rect::from_min_max(pos2(graph_x0, top + header_h - ruler_h + colhdr_h), pos2(graph_x1 + 10.0, rect.max.y - footer_h)); + p.rect_filled(Rect::from_min_max(pos2(graph_x0, top), rect.max), 0.0, t.tl_bg); + p.line_segment([pos2(graph_x0 - 1.0, top), pos2(graph_x0 - 1.0, rect.max.y)], Stroke::new(1.0, t.app_bg)); + + // ---- header (left): time display, search, switches. + let tc = crate::panels::timecode(&app.session, &comp, time); + let tc_rect = Rect::from_min_size(pos2(rect.min.x + 12.0, top + 6.0), vec2(150.0, 24.0)); + let tc_resp = ui.interact(tc_rect, egui::Id::new("tl-timecode"), Sense::click_and_drag()); + p.text(tc_rect.left_center(), Align2::LEFT_CENTER, &tc, Tokens::semibold(20.0), t.timecode); + let sub = format!("{} ({:.2} fps)", fr.frame_at(time), fr.as_f64()); + p.text(pos2(tc_rect.min.x, tc_rect.max.y + 8.0), Align2::LEFT_CENTER, sub, Tokens::ui(10.5), t.text_faint); + app.auto.add("timeline.timecode", tc_rect, &tc); + if tc_resp.dragged() { + let d = tc_resp.drag_delta().x as f64; + let f = fr.frame_at(time) + (d * 0.5).round() as i64; + let _ = app.session.execute("time.set", json!({"frame": f.max(0)})); + } + if tc_resp.double_clicked() { + ctx.data_mut(|d| d.insert_temp(egui::Id::new("tl-tc-edit"), tc.clone())); + } + if let Some(mut buf) = ctx.data(|d| d.get_temp::(egui::Id::new("tl-tc-edit"))) { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(tc_rect)); + let r = child.add(egui::TextEdit::singleline(&mut buf).font(Tokens::semibold(18.0)).desired_width(150.0)); + r.request_focus(); + if r.lost_focus() { + let _ = app.session.execute("time.set", json!({"timecode": buf})); + ctx.data_mut(|d| d.remove::(egui::Id::new("tl-tc-edit"))); + } else { + ctx.data_mut(|d| d.insert_temp(egui::Id::new("tl-tc-edit"), buf)); + } + } + let sr = Rect::from_min_size(pos2(tc_rect.max.x + 14.0, top + 12.0), vec2((left_w - 420.0).clamp(120.0, 220.0), 22.0)); + let mut search = app.ui.timeline.search.clone(); + widgets::search_field(ui, sr, &mut search, "Search", &t); + app.ui.timeline.search = search; + app.auto.add("timeline.search", sr, "Search"); + let mut bx = rect.min.x + left_w - 10.0; + for (icon, on, id, tip) in [ + (Icon::Graph, app.ui.timeline.graph_editor, "graph", "Graph Editor"), + (Icon::MotionBlur, comp.enable_motion_blur, "motionBlur", "Enables Motion Blur for all layers with the Motion Blur switch set"), + (Icon::FrameBlend, comp.enable_frame_blending, "frameBlending", "Enables Frame Blending for all layers with the Frame Blend switch set"), + (Icon::Shy, comp.hide_shy, "hideShy", "Hides all layers for which the Shy switch is set"), + (Icon::Draft3D, comp.draft_3d, "draft3d", "Draft 3D"), + (Icon::Flowchart, false, "flowchart", "Composition Mini-Flowchart"), + ] { + let r = Rect::from_min_size(pos2(bx - 24.0, top + 11.0), vec2(24.0, 24.0)); + let resp = widgets::icon_button(ui, r, icon, on, &t, egui::Id::new(("tl-sw", id))).on_hover_text(tip); + app.auto.add(&format!("timeline.switch.{id}"), r, tip); + if resp.clicked() { + match id { + "graph" => app.ui.timeline.graph_editor = !app.ui.timeline.graph_editor, + "flowchart" => app.show_panel(crate::dock::PanelKind::Flowchart), + _ => { + let _ = app.session.execute("comp.setSwitch", json!({"switch": id})); + } + } + } + bx -= 28.0; + } + + // ---- ruler (right). + let ruler = Rect::from_min_max(pos2(graph_x0, top + header_h - ruler_h), pos2(rect.max.x, top + header_h)); + let nav = Rect::from_min_max(pos2(graph_x0 + 6.0, top + 6.0), pos2(graph_x1, top + 12.0)); + // Time navigator. + p.rect_filled(nav, 3.0, t.field_bg); + let vis0 = (tm.start / comp.duration.seconds()) as f32; + let vis1 = (tm.t(graph_x1) / comp.duration.seconds()) as f32; + let nav_vis = + Rect::from_min_max(pos2(nav.min.x + nav.width() * vis0.clamp(0.0, 1.0), nav.min.y), pos2(nav.min.x + nav.width() * vis1.clamp(0.0, 1.0), nav.max.y)); + p.rect_filled(nav_vis, 3.0, t.work_area); + let nresp = ui.interact(nav, egui::Id::new("tl-nav"), Sense::drag()); + if nresp.dragged() { + let d = nresp.drag_delta().x as f64 / nav.width() as f64 * comp.duration.seconds(); + app.ui.timeline.start = (app.ui.timeline.start + d).clamp(0.0, comp.duration.seconds()); + if app.ui.timeline.pps.is_none() { + app.ui.timeline.pps = Some(pps); + } + } + p.rect_filled(ruler, 0.0, t.tl_ruler_bg); + app.auto.add("timeline.ruler", ruler, &format!("{},{}", tm.start, tm.pps)); + // Work area bar. + let wa = Rect::from_min_max(pos2(tm.x(comp.work_area.0.seconds()), ruler.min.y + 2.0), pos2(tm.x(comp.work_area.1.seconds()), ruler.min.y + 10.0)); + p.rect_filled(wa, 2.0, t.work_area); + for (hx, set) in [(wa.min.x, "begin"), (wa.max.x, "end")] { + let hr = Rect::from_center_size(pos2(hx, wa.center().y), vec2(8.0, 12.0)); + p.rect_filled(Rect::from_center_size(pos2(hx, wa.center().y), vec2(3.0, 10.0)), 1.0, t.text_dim); + let resp = ui.interact(hr, egui::Id::new(("wa", set)), Sense::drag()); + app.auto.add(&format!("timeline.workArea.{set}"), hr, set); + if resp.dragged() + && let Some(pt) = resp.interact_pointer_pos() + { + let secs = fr.snap_nearest(Tick::from_seconds_f64(tm.t(pt.x).max(0.0))).seconds(); + let key = if set == "begin" { "start" } else { "end" }; + let _ = app.session.execute("comp.workArea", json!({key: secs, "merge": "wa-drag"})); + } + } + // Cache bar (green: cached frames at the viewer's resolution). + let scale_key = app.viewer_tex.as_ref().map(|(_, k)| k.scale).unwrap_or(1000); + let cached = app.frames.cached_frames(app.session.revision, cid.0, scale_key); + let fd = comp.frame_duration().seconds(); + let cy0 = ruler.min.y + 11.0; + let mut run: Option<(i64, i64)> = None; + let mut draw_run = |a: i64, b: i64| { + let x0 = tm.x(a as f64 * fd); + let x1 = tm.x((b + 1) as f64 * fd); + p.rect_filled(Rect::from_min_max(pos2(x0, cy0), pos2(x1, cy0 + 2.5)), 0.0, t.cache_green); + }; + for f in cached { + run = match run { + Some((a, b)) if f == b + 1 => Some((a, f)), + Some((a, b)) => { + draw_run(a, b); + Some((f, f)) + } + None => Some((f, f)), + }; + } + if let Some((a, b)) = run { + draw_run(a, b); + } + // Ticks + labels. + let secs_per_label = [0.0333, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0].into_iter().find(|s| s * pps >= 70.0).unwrap_or(60.0); + let first = (tm.start / secs_per_label).floor() * secs_per_label; + let mut s = first; + let pr = p.with_clip_rect(Rect::from_min_max(pos2(graph_x0, ruler.min.y), ruler.max)); + while s <= tm.t(graph_x1) + secs_per_label { + let x = tm.x(s); + pr.line_segment([pos2(x, ruler.max.y - 10.0), pos2(x, ruler.max.y)], Stroke::new(1.0, t.tl_ruler_tick)); + let label = if secs_per_label < 1.0 { format!("{:02}f", fr.frame_at(Tick::from_seconds_f64(s + 1e-9))) } else { format!("{:02}s", s.round() as i64) }; + pr.text(pos2(x + 3.0, ruler.max.y - 16.0), Align2::LEFT_CENTER, label, Tokens::ui(10.0), t.tl_ruler_text); + for k in 1..5 { + let xx = tm.x(s + secs_per_label * k as f64 / 5.0); + pr.line_segment([pos2(xx, ruler.max.y - 4.0), pos2(xx, ruler.max.y)], Stroke::new(1.0, t.tl_ruler_tick.gamma_multiply(0.6))); + } + s += secs_per_label; + } + // Comp markers. + for m in &comp.markers { + let x = tm.x(m.time.seconds()); + pr.add(egui::Shape::convex_polygon( + vec![pos2(x - 4.0, ruler.max.y - 10.0), pos2(x + 4.0, ruler.max.y - 10.0), pos2(x, ruler.max.y - 4.0)], + Tokens::label(m.label), + Stroke::NONE, + )); + } + // Scrub in the ruler. + let rresp = ui.interact(Rect::from_min_max(pos2(graph_x0, ruler.min.y + 12.0), ruler.max), egui::Id::new("tl-ruler"), Sense::click_and_drag()); + if (rresp.dragged() || rresp.clicked()) + && let Some(pt) = rresp.interact_pointer_pos() + { + let tt = Tick::from_seconds_f64(tm.t(pt.x).max(0.0)); + app.session.set_time(tt); + app.stop(); + } + + // ---- column headers. + let ch = Rect::from_min_max(pos2(rect.min.x, top + header_h), pos2(rect.max.x, top + header_h + colhdr_h)); + p.rect_filled(Rect::from_min_max(ch.min, pos2(graph_x0 - 1.0, ch.max.y)), 0.0, t.panel_bg); + p.line_segment([pos2(rect.min.x, ch.max.y), pos2(rect.max.x, ch.max.y)], Stroke::new(1.0, t.separator)); + let hy = ch.center().y; + let hic = |icon: Icon, x: f32| icons::paint(&p, Rect::from_center_size(pos2(x, hy), vec2(12.0, 12.0)), icon, t.text_dim); + hic(Icon::Eye, cw.av + 10.0); + hic(Icon::Speaker, cw.av + 28.0); + hic(Icon::Solo, cw.av + 46.0); + hic(Icon::Lock, cw.av + 64.0); + icons::paint(&p, Rect::from_center_size(pos2(cw.label + 10.0, hy), vec2(10.0, 10.0)), Icon::Keyframe, t.text_dim); + p.text(pos2(cw.num + 6.0, hy), Align2::LEFT_CENTER, "#", Tokens::ui(11.0), t.text_dim); + p.text(pos2(cw.name + 22.0, hy), Align2::LEFT_CENTER, "Layer Name", Tokens::ui(11.0), t.text_dim); + for (i, icon) in + [Icon::Shy, Icon::Collapse, Icon::Quality, Icon::Fx, Icon::FrameBlend, Icon::MotionBlur, Icon::Adjustment, Icon::Cube].into_iter().enumerate() + { + hic(icon, cw.switches + SW * i as f32 + SW / 2.0); + } + if app.ui.timeline.show_modes { + p.text(pos2(cw.mode + 4.0, hy), Align2::LEFT_CENTER, "Mode", Tokens::ui(11.0), t.text_dim); + p.text(pos2(cw.mode + 74.0, hy), Align2::LEFT_CENTER, "T", Tokens::ui(11.0), t.text_dim); + p.text(pos2(cw.trkmat + 4.0, hy), Align2::LEFT_CENTER, "Track Matte", Tokens::ui(11.0), t.text_dim); + } + icons::paint(&p, Rect::from_center_size(pos2(cw.parent + 10.0, hy), vec2(12.0, 12.0)), Icon::PickWhip, t.text_dim); + p.text(pos2(cw.parent + 20.0, hy), Align2::LEFT_CENTER, "Parent & Link", Tokens::ui(11.0), t.text_dim); + let _ = cw.end; + + // ---- rows. + let rows = build_rows(app, &comp); + let rh = t.row_h; + let total_h = rows.len() as f32 * rh; + let max_scroll = (total_h - rows_rect.height() + rh).max(0.0); + if ui.rect_contains_pointer(rows_rect) { + let (dy, dx, zoom) = ui.input(|i| (i.smooth_scroll_delta.y, i.smooth_scroll_delta.x, i.modifiers.alt)); + if zoom && dy.abs() > 0.0 { + zoom_at(app, &comp, tm, (dy as f64 / 200.0).exp(), ui.input(|i| i.pointer.hover_pos()).map(|p| p.x).unwrap_or(graph_x0)); + } else { + app.ui.timeline.scroll_y = (app.ui.timeline.scroll_y - dy).clamp(0.0, max_scroll); + if dx.abs() > 0.0 && app.ui.timeline.pps.is_some() { + app.ui.timeline.start = (app.ui.timeline.start - dx as f64 / pps).max(0.0); + } + } + } + app.ui.timeline.scroll_y = app.ui.timeline.scroll_y.min(max_scroll); + let snap_project = app.session.project.clone(); + let snap_expr = app.session.expr.clone(); + let ectx = EvalCtx { project: &snap_project, comp_id: cid, comp: &comp, time, expr: snap_expr.as_deref() }; + let lp = p.with_clip_rect(rows_rect.intersect(Rect::from_min_max(rows_rect.min, pos2(graph_x0 - 1.0, rows_rect.max.y)))); + let gp = p.with_clip_rect(rows_rect.intersect(Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max))); + let mut y = rows_rect.min.y - app.ui.timeline.scroll_y; + let selected = app.session.state.selected_layers.clone(); + let sel_keys = app.session.state.selected_keys.clone(); + let mut actions: Vec<(String, serde_json::Value)> = Vec::new(); + let mut ui_actions: Vec = Vec::new(); + let idx_of = |id: LayerId| comp.index_of(id).unwrap_or(0); + let graph_on = app.ui.timeline.graph_editor; + for (ri, row) in rows.iter().enumerate() { + let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), rh)); + y += rh; + if r.max.y < rows_rect.min.y || r.min.y > rows_rect.max.y { + continue; + } + let Some(layer) = comp.layer(row.layer) else { continue }; + let is_sel = selected.contains(&layer.id); + let left = Rect::from_min_max(r.min, pos2(graph_x0 - 1.0, r.max.y)); + let cy = r.center().y; + match &row.kind { + RowKind::Layer => { + lp.rect_filled( + left, + 0.0, + if is_sel { + t.row_selected + } else if ri % 2 == 0 { + t.row + } else { + t.row_alt + }, + ); + gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, if is_sel { Color32::from_rgb(0x26, 0x26, 0x26) } else { t.tl_bg }); + lp.line_segment([pos2(rect.min.x, r.max.y), pos2(graph_x0, r.max.y)], Stroke::new(1.0, Color32::from_black_alpha(80))); + // A/V features. + let sw = &layer.switches; + let av_items: [(Icon, bool, &str, bool); 4] = [ + (Icon::Eye, sw.video, "video", layer.source.is_av()), + (Icon::Speaker, sw.audio, "audio", layer.props.sub("audio").is_some()), + (Icon::Solo, sw.solo, "solo", layer.source.is_av()), + (Icon::Lock, sw.locked, "lock", true), + ]; + for (i, (icon, on, name, applicable)) in av_items.into_iter().enumerate() { + let br = Rect::from_center_size(pos2(cw.av + 10.0 + 18.0 * i as f32, cy), vec2(17.0, 17.0)); + if !applicable { + continue; + } + lp.rect_stroke(br.shrink(1.5), 2.0, Stroke::new(1.0, t.separator), StrokeKind::Inside); + let resp = widgets::icon_toggle(ui, br, icon, on, &t, egui::Id::new(("av", layer.id.0, i)), None); + app.auto.add(&format!("timeline.layer.{}.{name}", layer.id.0), br, name); + if resp.clicked() { + actions.push(("layer.setSwitch".into(), json!({"layers": [layer.id.0], "switch": name}))); + } + } + // Label swatch. + let lr = Rect::from_center_size(pos2(cw.label + 10.0, cy), vec2(12.0, 12.0)); + lp.rect_filled(lr, 2.0, Tokens::label(layer.label)); + let lresp = ui.interact(lr, egui::Id::new(("label", layer.id.0)), Sense::click()); + lresp.context_menu(|ui| { + for lab in effectcraft_engine::color::Label::ALL { + if ui.button(lab.name()).clicked() { + actions.push(("edit.label".into(), json!({"layers": [layer.id.0], "label": lab.name()}))); + ui.close(); + } + } + }); + lp.text(pos2(cw.num + 13.0, cy), Align2::CENTER_CENTER, format!("{}", idx_of(layer.id)), Tokens::ui(11.5), t.text_dim); + // Twirl + icon + name. + let tw = Rect::from_center_size(pos2(cw.name + 8.0, cy), vec2(14.0, 14.0)); + let open = app.ui.timeline.open_layers.contains(&layer.id.0); + if widgets::twirl(ui, tw, open, egui::Id::new(("twirl", layer.id.0)), &t).clicked() { + ui_actions.push(UiAct::ToggleLayer(layer.id.0, ui.input(|i| i.modifiers.alt))); + } + app.auto.add(&format!("timeline.layer.{}.twirl", layer.id.0), tw, "twirl"); + icons::paint(&lp, Rect::from_center_size(pos2(cw.name + 24.0, cy), vec2(13.0, 13.0)), layer_icon(layer, &app.session.project), t.text_dim); + let name_rect = Rect::from_min_max(pos2(cw.name + 34.0, r.min.y), pos2(cw.switches - 4.0, r.max.y)); + let rename_id = egui::Id::new("tl-rename"); + let renaming: Option<(u64, String)> = ctx.data(|d| d.get_temp(rename_id)); + if let Some((rl, mut buf)) = renaming.filter(|(rl, _)| *rl == layer.id.0) { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect.shrink2(vec2(0.0, 2.0)))); + let er = child.add(egui::TextEdit::singleline(&mut buf).font(Tokens::ui(12.0)).desired_width(name_rect.width())); + er.request_focus(); + if er.lost_focus() { + if !ui.input(|i| i.key_pressed(egui::Key::Escape)) { + actions.push(("layer.rename".into(), json!({"layer": rl, "name": buf}))); + } + ctx.data_mut(|d| d.remove::<(u64, String)>(rename_id)); + } else { + ctx.data_mut(|d| d.insert_temp(rename_id, (rl, buf))); + } + } else { + let name_col = if is_sel { Color32::WHITE } else { t.text }; + let lpn = lp.with_clip_rect(name_rect.intersect(lp.clip_rect())); + lpn.text(pos2(name_rect.min.x, cy), Align2::LEFT_CENTER, &layer.name, Tokens::ui(12.0), name_col); + } + // Row click → select; double-click → rename; drag → reorder (later). + let row_resp = + ui.interact(Rect::from_min_max(pos2(cw.num, r.min.y), pos2(cw.switches, r.max.y)), egui::Id::new(("row", layer.id.0)), Sense::click()); + app.auto.add(&format!("timeline.layer.{}.row", layer.id.0), left, &layer.name); + if row_resp.clicked() { + let m = ui.input(|i| i.modifiers); + actions.push(("layer.select".into(), json!({"layers": [layer.id.0], "toggle": m.command, "add": m.shift}))); + } + if row_resp.double_clicked() { + match &layer.source { + LayerSource::Comp { item } => actions.push(("comp.open".into(), json!({"comp": item.0}))), + _ => { + ctx.data_mut(|d| d.insert_temp(rename_id, (layer.id.0, layer.name.clone()))); + } + } + } + layer_context_menu(&row_resp, layer, &mut actions); + // Switches. + let sws: [(Icon, bool, &str, bool); 8] = [ + (Icon::Shy, sw.shy, "shy", true), + (Icon::Collapse, sw.collapse, "collapse", matches!(layer.source, LayerSource::Comp { .. } | LayerSource::Shape | LayerSource::Text)), + (Icon::Quality, sw.quality == effectcraft_engine::project::Quality::Best, "quality", layer.source.is_av()), + (Icon::Fx, sw.effects, "fx", layer.effects().is_some_and(|f| !f.children.is_empty())), + ( + Icon::FrameBlend, + sw.frame_blend != effectcraft_engine::project::FrameBlend::Off, + "frameBlend", + matches!(layer.source, LayerSource::Footage { .. } | LayerSource::Comp { .. }), + ), + (Icon::MotionBlur, sw.motion_blur, "motionBlur", layer.source.is_av()), + (Icon::Adjustment, sw.adjustment, "adjustment", layer.source.is_av()), + (Icon::Cube, layer.is_3d(), "threeD", layer.source.is_av() || matches!(layer.source, LayerSource::Null)), + ]; + for (i, (icon, on, name, applicable)) in sws.into_iter().enumerate() { + if !applicable { + continue; + } + let br = Rect::from_center_size(pos2(cw.switches + SW * i as f32 + SW / 2.0, cy), vec2(16.0, 16.0)); + lp.rect_stroke(br.shrink(1.5), 2.0, Stroke::new(1.0, t.separator), StrokeKind::Inside); + let resp = widgets::icon_toggle(ui, br, icon, on, &t, egui::Id::new(("sw", layer.id.0, i)), None); + app.auto.add(&format!("timeline.layer.{}.switch.{name}", layer.id.0), br, name); + if resp.clicked() { + actions.push(("layer.setSwitch".into(), json!({"layers": [layer.id.0], "switch": name}))); + } + } + // Modes. + if app.ui.timeline.show_modes && layer.source.is_av() { + let mr = Rect::from_min_size(pos2(cw.mode + 2.0, cy - 9.0), vec2(80.0, 18.0)); + let mresp = widgets::dropdown(ui, mr, layer.blend_mode.label(), &t, egui::Id::new(("mode", layer.id.0))); + app.auto.add(&format!("timeline.layer.{}.mode", layer.id.0), mr, "Mode"); + let pop = egui::Id::new(("mode-pop", layer.id.0)); + if mresp.clicked() { + widgets::open_popup(ui, pop); + } + let opts: Vec = BlendMode::ALL + .iter() + .flat_map(|m| if m.ends_group() { vec![m.label().to_string(), "-".to_string()] } else { vec![m.label().to_string()] }) + .collect(); + if let Some(i) = widgets::popup_menu(ui, pop, mr.left_bottom(), &opts, opts.iter().position(|o| o == layer.blend_mode.label())) { + actions.push(("layer.setBlendMode".into(), json!({"layers": [layer.id.0], "mode": opts[i]}))); + } + let tr = Rect::from_center_size(pos2(cw.mode + 76.0 + 6.0, cy), vec2(14.0, 14.0)); + if widgets::checkbox(ui, tr, layer.preserve_transparency, &t, egui::Id::new(("pt", layer.id.0))).clicked() { + actions.push(("layer.setSwitch".into(), json!({"layers": [layer.id.0], "switch": "preserveTransparency"}))); + } + // Track matte: layer picker + kind. + let mr = Rect::from_min_size(pos2(cw.trkmat + 2.0, cy - 9.0), vec2(104.0, 18.0)); + let label = match layer.track_matte { + Some(m) => comp.layer(m.layer).map(|l| format!("{} {}", idx_of(l.id), l.name)).unwrap_or("None".into()), + None => "No Track Matte".into(), + }; + let tresp = widgets::dropdown(ui, mr, &label, &t, egui::Id::new(("trkmat", layer.id.0))); + app.auto.add(&format!("timeline.layer.{}.trackMatte", layer.id.0), mr, "Track Matte"); + let pop = egui::Id::new(("trk-pop", layer.id.0)); + if tresp.clicked() { + widgets::open_popup(ui, pop); + } + let mut opts = vec!["No Track Matte".to_string(), "-".to_string()]; + let candidates: Vec<&Layer> = comp.layers.iter().filter(|l| l.id != layer.id && l.source.is_av()).collect(); + for l in &candidates { + opts.push(format!("{}. {}", idx_of(l.id), l.name)); + } + opts.push("-".into()); + for k in MatteKind::ALL { + opts.push(k.label().into()); + } + if let Some(i) = widgets::popup_menu(ui, pop, mr.left_bottom(), &opts, None) { + if i == 0 { + actions.push(("layer.setTrackMatte".into(), json!({"layer": layer.id.0, "matte": null}))); + } else if i >= 2 && i < 2 + candidates.len() { + let kind = layer.track_matte.map(|m| m.kind).unwrap_or_default(); + actions + .push(("layer.setTrackMatte".into(), json!({"layer": layer.id.0, "matte": candidates[i - 2].id.0, "kind": kind_name(kind)}))); + } else if let Some(k) = MatteKind::ALL.into_iter().find(|k| k.label() == opts[i]) + && let Some(m) = layer.track_matte + { + actions.push(("layer.setTrackMatte".into(), json!({"layer": layer.id.0, "matte": m.layer.0, "kind": kind_name(k)}))); + } + } + if layer.track_matte.is_some() { + let kr = Rect::from_center_size(pos2(mr.max.x - 26.0, cy), vec2(10.0, 10.0)); + let _ = kr; + } + } + // Parent. + let pr_rect = Rect::from_min_size(pos2(cw.parent + 2.0, cy - 9.0), vec2(110.0, 18.0)); + let plabel = layer.parent.and_then(|p| comp.layer(p)).map(|l| format!("{}. {}", idx_of(l.id), l.name)).unwrap_or_else(|| "None".into()); + let presp = widgets::dropdown(ui, pr_rect, &plabel, &t, egui::Id::new(("parent", layer.id.0))); + app.auto.add(&format!("timeline.layer.{}.parent", layer.id.0), pr_rect, "Parent"); + let pop = egui::Id::new(("par-pop", layer.id.0)); + if presp.clicked() { + widgets::open_popup(ui, pop); + } + let cands: Vec<&Layer> = comp.layers.iter().filter(|l| l.id != layer.id).collect(); + let mut popts = vec!["None".to_string(), "-".to_string()]; + popts.extend(cands.iter().map(|l| format!("{}. {}", idx_of(l.id), l.name))); + if let Some(i) = widgets::popup_menu(ui, pop, pr_rect.left_bottom(), &popts, None) { + let par = if i == 0 { serde_json::Value::Null } else { json!(cands[i - 2].id.0) }; + actions.push(("layer.setParent".into(), json!({"layers": [layer.id.0], "parent": par}))); + } + // Layer bar. + if !graph_on { + let x_in = tm.x(layer.in_point.seconds()); + let x_out = tm.x(layer.out_point.seconds()); + let bar = Rect::from_min_max(pos2(x_in, r.min.y + 3.0), pos2(x_out, r.max.y - 3.0)); + let lc = Tokens::label(layer.label); + let fill = if is_sel { lc.gamma_multiply(0.85) } else { lc.gamma_multiply(0.55) }; + gp.rect_filled(bar, 2.0, fill); + if is_sel { + gp.rect_stroke(bar, 2.0, Stroke::new(1.0, Color32::from_white_alpha(120)), StrokeKind::Inside); + } + // Source extent (e.g. trimmed footage) shown faint. + if let LayerSource::Footage { .. } | LayerSource::Comp { .. } = layer.source + && let Some(d) = layer.source.item().and_then(|i| app.session.project.item(i)).and_then(|i| i.duration()) + { + let xs = tm.x(layer.start_time.seconds()); + let xe = tm.x(layer.comp_time(d).seconds()); + let ghost = Rect::from_min_max(pos2(xs, r.min.y + 9.0), pos2(xe, r.max.y - 9.0)); + gp.rect_filled(ghost, 1.0, lc.gamma_multiply(0.18)); + } + app.auto.add(&format!("timeline.layer.{}.bar", layer.id.0), bar, &layer.name); + // Interactions: move body, trim edges. + let edge_w = 6.0; + let body = ui.interact(bar.shrink2(vec2(edge_w, 0.0)), egui::Id::new(("bar", layer.id.0)), Sense::click_and_drag()); + let lin = + ui.interact(Rect::from_min_max(bar.min, pos2(bar.min.x + edge_w, bar.max.y)), egui::Id::new(("bar-in", layer.id.0)), Sense::drag()); + let lout = + ui.interact(Rect::from_min_max(pos2(bar.max.x - edge_w, bar.min.y), bar.max), egui::Id::new(("bar-out", layer.id.0)), Sense::drag()); + if lin.hovered() || lout.hovered() || lin.dragged() || lout.dragged() { + ctx.set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + if body.clicked() || body.drag_started() { + if !is_sel { + actions.push(("layer.select".into(), json!({"layers": [layer.id.0], "add": ui.input(|i| i.modifiers.shift)}))); + } + } + layer_context_menu(&body, layer, &mut actions); + let drag_key = format!("bar-{}", layer.id.0); + for (resp, kind) in [(&body, "move"), (&lin, "in"), (&lout, "out")] { + if resp.dragged() { + let acc_id = egui::Id::new(("bar-acc", layer.id.0, kind)); + let mut acc: f32 = ctx.data(|d| d.get_temp(acc_id).unwrap_or(0.0)); + acc += resp.drag_delta().x; + let frames = ((acc as f64 / pps) / fd).trunc() as i64; + if frames != 0 { + acc -= (frames as f64 * fd * pps) as f32; + let d = frames as f64 * fd; + let params = match kind { + "move" => { + json!({"layers": if is_sel { json!(selected.iter().map(|l| l.0).collect::>()) } else { json!([layer.id.0]) }, "delta": d, "merge": drag_key}) + } + "in" => json!({"layers": [layer.id.0], "in": (layer.in_point.seconds() + d).max(0.0), "merge": drag_key}), + _ => { + json!({"layers": [layer.id.0], "out": (layer.out_point.seconds() + d).min(comp.duration.seconds()), "merge": drag_key}) + } + }; + actions.push(("layer.timing".into(), params)); + } + ctx.data_mut(|d| d.insert_temp(acc_id, acc)); + } + if resp.drag_stopped() { + ctx.data_mut(|d| d.remove::(egui::Id::new(("bar-acc", layer.id.0, kind)))); + ui_actions.push(UiAct::EndMerge); + } + } + // Markers on the layer. + for m in &layer.markers { + let x = tm.x(layer.comp_time(m.time).seconds()); + gp.add(egui::Shape::convex_polygon( + vec![pos2(x - 3.5, r.min.y + 3.0), pos2(x + 3.5, r.min.y + 3.0), pos2(x, r.min.y + 9.0)], + Color32::from_rgb(0xd8, 0xd8, 0x60), + Stroke::NONE, + )); + } + } + } + RowKind::Group { uid, name, open, has_children, fx } => { + lp.rect_filled(left, 0.0, if ri % 2 == 0 { t.row } else { t.row_alt }); + gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, t.tl_bg); + let indent = cw.name + 6.0 + 14.0 * row.depth as f32; + if *has_children { + let tw = Rect::from_center_size(pos2(indent, cy), vec2(13.0, 13.0)); + if widgets::twirl(ui, tw, *open, egui::Id::new(("gtw", uid)), &t).clicked() { + ui_actions.push(UiAct::ToggleGroup(*uid)); + } + app.auto.add(&format!("timeline.group.{uid}.twirl"), tw, name); + } + if let Some(en) = fx { + let fr_ = Rect::from_center_size(pos2(cw.switches + SW * 3.0 + SW / 2.0, cy), vec2(16.0, 16.0)); + if widgets::icon_toggle(ui, fr_, Icon::Fx, *en, &t, egui::Id::new(("gfx", uid)), None).clicked() { + actions.push(("effect.toggle".into(), json!({"layer": layer.id.0, "effect": uid}))); + } + } + lp.text(pos2(indent + 10.0, cy), Align2::LEFT_CENTER, name, Tokens::ui(12.0), t.text); + // Mask mode + inverted inline. + if let Some(g) = layer.props.find_group(*uid) + && let GroupKind::Mask { mode, inverted, .. } = g.kind + { + let mr = Rect::from_min_size(pos2(cw.switches + 4.0, cy - 9.0), vec2(80.0, 18.0)); + let pop = egui::Id::new(("maskmode", uid)); + if widgets::dropdown(ui, mr, mode.label(), &t, egui::Id::new(("mm", uid))).clicked() { + widgets::open_popup(ui, pop); + } + let opts: Vec = effectcraft_engine::project::MaskMode::ALL.iter().map(|m| m.label().to_string()).collect(); + if let Some(i) = widgets::popup_menu(ui, pop, mr.left_bottom(), &opts, None) { + actions.push(("layer.setMask".into(), json!({"layer": layer.id.0, "mask": uid, "mode": opts[i]}))); + } + let ir = Rect::from_min_size(pos2(mr.max.x + 8.0, cy - 8.0), vec2(16.0, 16.0)); + if widgets::checkbox(ui, ir, inverted, &t, egui::Id::new(("minv", uid))).clicked() { + actions.push(("layer.setMask".into(), json!({"layer": layer.id.0, "mask": uid, "inverted": !inverted}))); + } + lp.text(pos2(ir.max.x + 4.0, cy), Align2::LEFT_CENTER, "Inverted", Tokens::ui(11.0), t.text_dim); + } + let gr = ui.interact(Rect::from_min_max(pos2(indent + 8.0, r.min.y), pos2(cw.switches, r.max.y)), egui::Id::new(("grow", uid)), Sense::click()); + if gr.clicked() { + actions.push(("prop.select".into(), json!({"layer": layer.id.0, "prop": uid, "selectKeys": false}))); + } + if gr.double_clicked() { + ui_actions.push(UiAct::ToggleGroup(*uid)); + } + } + RowKind::Prop { uid } => { + let Some(prop) = layer.props.find(*uid) else { continue }; + let sel_prop = app.session.state.selected_props.contains(&(layer.id, *uid)); + lp.rect_filled( + left, + 0.0, + if sel_prop { + t.row_selected + } else if ri % 2 == 0 { + t.row + } else { + t.row_alt + }, + ); + gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, t.tl_bg); + let indent = cw.name + 6.0 + 14.0 * row.depth as f32; + // Keyframe navigator (in the A/V column, like AE). + if prop.is_animated() { + let lt = layer.layer_time(time); + let at_key = effectcraft_engine::keyframe::key_at(&prop.keys, lt).is_some(); + let nav_x = cw.av + 18.0; + let prev = Rect::from_center_size(pos2(nav_x, cy), vec2(12.0, 14.0)); + let mid = Rect::from_center_size(pos2(nav_x + 16.0, cy), vec2(14.0, 14.0)); + let next = Rect::from_center_size(pos2(nav_x + 32.0, cy), vec2(12.0, 14.0)); + icons::paint(&lp, prev.shrink(2.0), Icon::ChevronLeft, t.text_dim); + icons::paint(&lp, next.shrink(2.0), Icon::ChevronRight, t.text_dim); + let kc = if at_key { t.keyframe_selected } else { Color32::TRANSPARENT }; + lp.add(egui::Shape::convex_polygon( + vec![mid.center() + vec2(0.0, -5.0), mid.center() + vec2(5.0, 0.0), mid.center() + vec2(0.0, 5.0), mid.center() + vec2(-5.0, 0.0)], + kc, + Stroke::new(1.0, t.text_dim), + )); + if ui.interact(prev, egui::Id::new(("kprev", uid)), Sense::click()).clicked() + && let Some(k) = prop.keys.iter().rev().find(|k| layer.comp_time(k.time).0 < time.0 - fr.frame_duration().0 / 2) + { + ui_actions.push(UiAct::SetTime(layer.comp_time(k.time))); + } + if ui.interact(next, egui::Id::new(("knext", uid)), Sense::click()).clicked() + && let Some(k) = prop.keys.iter().find(|k| layer.comp_time(k.time).0 > time.0 + fr.frame_duration().0 / 2) + { + ui_actions.push(UiAct::SetTime(layer.comp_time(k.time))); + } + if ui.interact(mid, egui::Id::new(("kmid", uid)), Sense::click()).clicked() { + actions.push(("prop.toggleKey".into(), json!({"layer": layer.id.0, "prop": uid}))); + } + app.auto.add(&format!("timeline.prop.{uid}.addKey"), mid, "Add or remove keyframe"); + } + // Stopwatch. + if !prop.static_only { + let swr = Rect::from_center_size(pos2(indent, cy), vec2(15.0, 15.0)); + let resp = ui.interact(swr, egui::Id::new(("stopwatch", uid)), Sense::click()); + let col = if prop.is_animated() { + t.hot_text + } else if resp.hovered() { + t.text + } else { + t.text_dim + }; + icons::paint(&lp, swr, Icon::Stopwatch, col); + app.auto.add(&format!("timeline.prop.{uid}.stopwatch"), swr, &prop.name); + if resp.clicked() { + if ui.input(|i| i.modifiers.alt) { + actions.push(("prop.setExpression".into(), json!({"layer": layer.id.0, "prop": uid}))); + } else { + actions.push(("prop.toggleAnimation".into(), json!({"layer": layer.id.0, "prop": uid}))); + } + } + } + let name_x = indent + 12.0; + let pname = if prop.has_expression() { format!("{} =", prop.name) } else { prop.name.clone() }; + lp.text( + pos2(name_x, cy), + Align2::LEFT_CENTER, + &pname, + Tokens::ui(12.0), + if prop.has_expression() { Color32::from_rgb(0xe8, 0x7c, 0x5c) } else { t.text }, + ); + let name_resp = + ui.interact(Rect::from_min_max(pos2(name_x, r.min.y), pos2(cw.switches - 2.0, r.max.y)), egui::Id::new(("pname", uid)), Sense::click()); + if name_resp.clicked() { + actions.push(("prop.select".into(), json!({"layer": layer.id.0, "prop": uid, "add": ui.input(|i| i.modifiers.shift)}))); + } + // Value editors. + let value = ectx.value(layer, prop); + let vx = (cw.switches + 4.0).max(name_x + 120.0); + value_editor(app, ui, &lp, layer, prop, &value, pos2(vx, cy), &mut actions); + // Expression text row hint. + if let Some(e) = prop.expr.as_ref().filter(|e| e.enabled) { + gp.text( + pos2(graph_x0 + 8.0, cy), + Align2::LEFT_CENTER, + format!("= {}", e.text.lines().next().unwrap_or("")), + Tokens::mono(11.0), + Color32::from_rgb(0xe8, 0x7c, 0x5c), + ); + } + // Keyframes. + if !graph_on { + for k in &prop.keys { + let ct = layer.comp_time(k.time); + let x = tm.x(ct.seconds()); + if x < graph_x0 - 8.0 || x > rect.max.x + 8.0 { + continue; + } + let kref = effectcraft_engine::KeyRef { layer: layer.id, prop: *uid, time: k.time }; + let ks = sel_keys.contains(&kref); + let icon = k.icon(); + let c = pos2(x, cy); + icons::keyframe(&gp, c, 11.0, icon.left, icon.right, if ks { t.keyframe_selected } else { t.keyframe }, Color32::from_black_alpha(200)); + let kr = Rect::from_center_size(c, vec2(12.0, 14.0)); + let kresp = ui.interact(kr, egui::Id::new(("key", uid, k.time.0)), Sense::click_and_drag()); + app.auto.add(&format!("timeline.key.{uid}.{}", fr.frame_at(ct)), kr, &format!("{} key", prop.name)); + if kresp.clicked() || kresp.drag_started() { + let shift = ui.input(|i| i.modifiers.shift); + if !ks || shift { + actions.push(( + "keys.select".into(), + json!({"keys": [{"layer": layer.id.0, "prop": uid, "time": k.time.seconds()}], "add": shift}), + )); + } + } + if kresp.double_clicked() { + ui_actions.push(UiAct::SetTime(ct)); + } + kresp.context_menu(|ui| { + for (lbl, cmd, params) in [ + ("Easy Ease", "keys.easyEase", json!({})), + ("Easy Ease In", "keys.easyEaseIn", json!({})), + ("Easy Ease Out", "keys.easyEaseOut", json!({})), + ("Toggle Hold Keyframe", "keys.toggleHold", json!({})), + ("Linear", "keys.interpolation", json!({"interpolation": "linear"})), + ("Bezier", "keys.interpolation", json!({"interpolation": "bezier"})), + ("Auto Bezier", "keys.interpolation", json!({"autoBezier": true})), + ("Delete", "keys.delete", json!({})), + ] { + if ui.button(lbl).clicked() { + if !ks { + actions.push(("keys.select".into(), json!({"keys": [{"layer": layer.id.0, "prop": uid, "time": k.time.seconds()}]}))); + } + actions.push((cmd.into(), params)); + ui.close(); + } + } + }); + if kresp.dragged() { + let acc_id = egui::Id::new("key-drag-acc"); + let mut acc: f32 = ctx.data(|d| d.get_temp(acc_id).unwrap_or(0.0)); + acc += kresp.drag_delta().x; + let frames = ((acc as f64 / pps) / fd).trunc() as i64; + if frames != 0 { + acc -= (frames as f64 * fd * pps) as f32; + actions.push(("keys.move".into(), json!({"delta": frames as f64 * fd, "merge": "key-drag"}))); + } + ctx.data_mut(|d| d.insert_temp(acc_id, acc)); + } + if kresp.drag_stopped() { + ctx.data_mut(|d| d.remove::(egui::Id::new("key-drag-acc"))); + ui_actions.push(UiAct::EndMerge); + } + } + } + } + } + } + // Graph editor. + if graph_on { + graph_editor(app, ui, &gp, &comp, &ectx, tm, Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max)); + } + // Empty-area click in the graph: deselect keys; drag: box-select keys. + let empty = ui.interact(Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max), egui::Id::new("tl-graph-bg"), Sense::click_and_drag()); + if empty.clicked() { + actions.push(("keys.select".into(), json!({"keys": []}))); + } + if let (true, Some(origin), Some(cur)) = + (empty.dragged(), empty.interact_pointer_pos().map(|_| ctx.input(|i| i.pointer.press_origin())).flatten(), empty.interact_pointer_pos()) + { + let br = Rect::from_two_pos(origin, cur); + gp.rect_filled(br, 0.0, t.accent.gamma_multiply(0.12)); + gp.rect_stroke(br, 0.0, Stroke::new(1.0, t.accent), StrokeKind::Middle); + ctx.data_mut(|d| d.insert_temp(egui::Id::new("tl-box"), br)); + } + if empty.drag_stopped() + && let Some(br) = ctx.data(|d| d.get_temp::(egui::Id::new("tl-box"))) + { + ctx.data_mut(|d| d.remove::(egui::Id::new("tl-box"))); + let mut keys = vec![]; + let mut yy = rows_rect.min.y - app.ui.timeline.scroll_y; + for row in &rows { + let cy = yy + rh / 2.0; + yy += rh; + if let RowKind::Prop { uid } = row.kind + && cy >= br.min.y + && cy <= br.max.y + && let Some(l) = comp.layer(row.layer) + && let Some(pr) = l.props.find(uid) + { + for k in &pr.keys { + let x = tm.x(l.comp_time(k.time).seconds()); + if x >= br.min.x && x <= br.max.x { + keys.push(json!({"layer": l.id.0, "prop": uid, "time": k.time.seconds()})); + } + } + } + } + actions.push(("keys.select".into(), json!({"keys": keys, "add": ui.input(|i| i.modifiers.shift)}))); + } + + // CTI. + let cx = tm.x(time.seconds()); + if cx >= graph_x0 && cx <= rect.max.x { + p.line_segment([pos2(cx, ruler.min.y + 12.0), pos2(cx, rows_rect.max.y)], Stroke::new(1.0, t.cti)); + let head = vec![ + pos2(cx - 6.0, ruler.min.y + 12.0), + pos2(cx + 6.0, ruler.min.y + 12.0), + pos2(cx + 6.0, ruler.max.y - 8.0), + pos2(cx, ruler.max.y - 2.0), + pos2(cx - 6.0, ruler.max.y - 8.0), + ]; + p.add(egui::Shape::convex_polygon(head, t.cti, Stroke::NONE)); + app.auto.add("timeline.cti", Rect::from_center_size(pos2(cx, ruler.center().y), vec2(12.0, 20.0)), "Current time indicator"); + } + let _ = graph_rect; + + // Footer. + let footer = Rect::from_min_max(pos2(rect.min.x, rect.max.y - footer_h), rect.max); + p.rect_filled(footer, 0.0, t.panel_bg); + p.line_segment([footer.left_top(), footer.right_top()], Stroke::new(1.0, t.separator)); + let tgl = Rect::from_min_size(pos2(footer.min.x + 10.0, footer.min.y + 3.0), vec2(150.0, 18.0)); + let tresp = ui.interact(tgl, egui::Id::new("tl-toggle-modes"), Sense::click()); + p.text(tgl.left_center(), Align2::LEFT_CENTER, "Toggle Switches / Modes", Tokens::ui(11.0), if tresp.hovered() { t.text } else { t.text_dim }); + app.auto.add("timeline.toggleSwitchesModes", tgl, "Toggle Switches / Modes"); + if tresp.clicked() { + app.ui.timeline.show_modes = !app.ui.timeline.show_modes; + } + let ms = app.frames.last_ms.lock().map(|v| *v).unwrap_or(0.0); + p.text(pos2(graph_x0 - 12.0, footer.center().y), Align2::RIGHT_CENTER, format!("Frame Render Time {ms:.0}ms"), Tokens::ui(11.0), t.text_faint); + // Zoom slider. + let zs = Rect::from_min_max(pos2(graph_x0 + 30.0, footer.center().y - 2.0), pos2((graph_x0 + 230.0).min(rect.max.x - 30.0), footer.center().y + 2.0)); + icons::paint(&p, Rect::from_center_size(pos2(zs.min.x - 14.0, footer.center().y), vec2(14.0, 14.0)), Icon::MountainSmall, t.text_dim); + icons::paint(&p, Rect::from_center_size(pos2(zs.max.x + 14.0, footer.center().y), vec2(16.0, 16.0)), Icon::MountainLarge, t.text_dim); + p.rect_filled(zs, 2.0, t.field_bg); + let maxpps = 4000.0f64; + let frac = ((pps / fit_pps).ln() / (maxpps / fit_pps).ln()).clamp(0.0, 1.0) as f32; + let knob = pos2(zs.min.x + zs.width() * frac, zs.center().y); + p.circle_filled(knob, 6.0, t.text); + let zresp = ui.interact(zs.expand2(vec2(6.0, 8.0)), egui::Id::new("tl-zoom"), Sense::drag()); + app.auto.add("timeline.zoomSlider", zs, "Zoom"); + if zresp.dragged() + && let Some(pt) = zresp.interact_pointer_pos() + { + let f = ((pt.x - zs.min.x) / zs.width()).clamp(0.0, 1.0) as f64; + let npps = fit_pps * (maxpps / fit_pps).powf(f); + let cti = time.seconds(); + let rel = (cti - tm.start) * pps; + app.ui.timeline.start = (cti - rel / npps).max(0.0); + app.ui.timeline.pps = Some(npps); + } + + // Drop targets: footage/comps from the Project panel, effects from Effects & Presets. + if let Some(payload) = egui::DragAndDrop::payload::(&ctx) + && ui.rect_contains_pointer(rows_rect) + { + p.rect_stroke(rows_rect, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside); + if ctx.input(|i| i.pointer.any_released()) { + let hover_y = ctx.input(|i| i.pointer.hover_pos()).map(|p| p.y).unwrap_or(0.0); + let row_i = ((hover_y - rows_rect.min.y + app.ui.timeline.scroll_y) / rh).floor() as usize; + let target = rows.get(row_i).map(|r| r.layer); + match payload.as_ref() { + crate::panels::DragPayload::Item(id) => actions.push(("layer.addItem".into(), json!({"item": id}))), + crate::panels::DragPayload::Effect(e) => { + if let Some(l) = target { + actions.push(("effect.apply".into(), json!({"effect": e, "layers": [l.0]}))); + } + } + } + egui::DragAndDrop::clear_payload(&ctx); + } + } + + // Apply. + for a in ui_actions { + match a { + UiAct::ToggleLayer(id, all) => { + let tl = &mut app.ui.timeline; + tl.reveal.clear(); + let open = !tl.open_layers.contains(&id); + if open { + tl.open_layers.insert(id); + } else { + tl.open_layers.remove(&id); + } + if all && let Some(l) = comp.layer(LayerId(id)) { + let mut uids = vec![]; + walk_groups(&l.props, &mut uids); + for u in uids { + if open { + tl.open_groups.insert(u); + } else { + tl.open_groups.remove(&u); + } + } + } + } + UiAct::ToggleGroup(uid) => { + if !app.ui.timeline.open_groups.remove(&uid) { + app.ui.timeline.open_groups.insert(uid); + } + } + UiAct::SetTime(tt) => app.session.set_time(tt), + UiAct::EndMerge => app.session.history.merge_key = None, + } + } + for (id, params) in actions { + if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) { + app.ui.status = e; + } + } +} + +enum UiAct { + ToggleLayer(u64, bool), + ToggleGroup(u64), + SetTime(Tick), + EndMerge, +} + +fn walk_groups(g: &PropGroup, out: &mut Vec) { + for sg in g.groups() { + out.push(sg.uid); + walk_groups(sg, out); + } +} + +fn kind_name(k: MatteKind) -> &'static str { + match k { + MatteKind::Alpha => "alpha", + MatteKind::AlphaInverted => "alphaInverted", + MatteKind::Luma => "luma", + MatteKind::LumaInverted => "lumaInverted", + } +} + +fn zoom_at(app: &mut EffectcraftApp, comp: &Comp, tm: TMap, k: f64, at_x: f32) { + let fit = tm.pps / app.ui.timeline.pps.map(|p| p / tm.pps).unwrap_or(1.0); + let npps = (tm.pps * k).clamp(fit.min(5.0), 4000.0); + let at_t = tm.t(at_x); + app.ui.timeline.start = (at_t - (at_x - tm.x0) as f64 / npps).clamp(0.0, comp.duration.seconds()); + app.ui.timeline.pps = Some(npps); +} + +fn layer_context_menu(resp: &egui::Response, layer: &Layer, actions: &mut Vec<(String, serde_json::Value)>) { + resp.context_menu(|ui| { + let id = layer.id.0; + let mut item = |ui: &mut egui::Ui, label: &str, cmd: &str, params: serde_json::Value| { + if ui.button(label).clicked() { + actions.push(("layer.select".into(), json!({"layers": [id]}))); + actions.push((cmd.into(), params)); + ui.close(); + } + }; + ui.menu_button("New", |ui| { + item(ui, "Text", "layer.newText", json!({"text": "Text"})); + item(ui, "Solid…", "app.solidSettings", json!({})); + item(ui, "Light…", "layer.newLight", json!({})); + item(ui, "Camera…", "layer.newCamera", json!({})); + item(ui, "Null Object", "layer.newNull", json!({})); + item(ui, "Shape Layer", "layer.newShape", json!({"kind": "none"})); + item(ui, "Adjustment Layer", "layer.newAdjustment", json!({})); + }); + item(ui, "Layer Settings…", "layer.settings", json!({})); + ui.separator(); + ui.menu_button("Masks", |ui| { + item(ui, "New Mask", "layer.addMask", json!({"layer": id})); + }); + ui.menu_button("Transform", |ui| { + item(ui, "Reset", "layer.transform", json!({"layers": [id], "op": "reset"})); + item(ui, "Center In View", "layer.transform", json!({"layers": [id], "op": "center"})); + item(ui, "Fit to Comp", "layer.transform", json!({"layers": [id], "op": "fit"})); + item(ui, "Flip Horizontal", "layer.transform", json!({"layers": [id], "op": "flipH"})); + item(ui, "Flip Vertical", "layer.transform", json!({"layers": [id], "op": "flipV"})); + }); + ui.menu_button("Time", |ui| { + item(ui, "Time-Reverse Layer", "layer.timeStretch", json!({"layers": [id], "op": "reverse"})); + }); + ui.menu_button("Blending Mode", |ui| { + for m in BlendMode::ALL { + item(ui, m.label(), "layer.setBlendMode", json!({"layers": [id], "mode": m.label()})); + if m.ends_group() { + ui.separator(); + } + } + }); + ui.menu_button("Arrange", |ui| { + item(ui, "Bring Layer to Front", "layer.arrange", json!({"layers": [id], "to": "front"})); + item(ui, "Bring Layer Forward", "layer.arrange", json!({"layers": [id], "to": "forward"})); + item(ui, "Send Layer Backward", "layer.arrange", json!({"layers": [id], "to": "backward"})); + item(ui, "Send Layer to Back", "layer.arrange", json!({"layers": [id], "to": "back"})); + }); + ui.separator(); + item(ui, "Pre-compose…", "layer.precompose", json!({"layers": [id], "name": format!("{} Comp 1", layer.name)})); + item(ui, "Duplicate", "edit.duplicate", json!({"layers": [id]})); + item(ui, "Split Layer", "edit.splitLayer", json!({"layers": [id]})); + item(ui, "Delete", "edit.clear", json!({"layers": [id]})); + }); +} + +fn fmt_num(v: f64, d: usize) -> String { + format!("{v:.d$}") +} + +/// Inline value editor for a property row; pushes `prop.set` actions. +fn value_editor( + app: &mut EffectcraftApp, + ui: &mut egui::Ui, + p: &egui::Painter, + layer: &Layer, + prop: &Property, + value: &Value, + at: Pos2, + actions: &mut Vec<(String, serde_json::Value)>, +) { + let t = app.tokens; + let uid = prop.uid; + let merge = format!("scrub-{uid}"); + let set = |actions: &mut Vec<(String, serde_json::Value)>, v: serde_json::Value| { + actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": v, "merge": merge}))) + }; + let is_3d = layer.is_3d(); + let mut x = at.x; + let y = at.y - 9.0; + match value { + Value::Scalar(v) => { + let (min, max, dec, speed) = match &prop.ui { + ParamUi::Slider { min, max, decimals, .. } => (*min, *max, *decimals as usize, ((max - min) / 400.0).clamp(0.01, 10.0)), + ParamUi::Angle => (-1e9, 1e9, 1, 0.5), + ParamUi::Percent => (-1e6, 1e6, 1, 0.5), + _ => (-1e9, 1e9, 1, 1.0), + }; + if matches!(prop.ui, ParamUi::Angle) { + let rev = (v / 360.0).trunc(); + let deg = v - rev * 360.0; + p.text(pos2(x, at.y), Align2::LEFT_CENTER, format!("{}x", rev as i64), Tokens::ui(12.0), t.hot_text); + x += 22.0; + let (r, nv, _) = widgets::hot_number_at(ui, pos2(x, y), egui::Id::new(("v", uid, 0)), deg, speed, (-1e9, 1e9), 1, "°", &t); + app.auto.add(&format!("timeline.prop.{uid}.value"), r, &prop.name); + if let Some(nv) = nv { + set(actions, json!(rev * 360.0 + nv)); + } + } else { + let suffix = if matches!(prop.ui, ParamUi::Percent) || prop.match_id == "opacity" { "%" } else { "" }; + let (r, nv, _) = widgets::hot_number_at(ui, pos2(x, y), egui::Id::new(("v", uid, 0)), *v, speed, (min, max), dec.max(1), suffix, &t); + app.auto.add(&format!("timeline.prop.{uid}.value"), r, &prop.name); + if let Some(nv) = nv { + set(actions, json!(nv)); + } + } + } + Value::Vec2(_) | Value::Vec3(_) => { + let c = value.components(); + let n = if prop.shown_dims > 0 && !(is_3d && c.len() == 3) { prop.shown_dims as usize } else { c.len() }; + let pct = matches!(prop.ui, ParamUi::Percent); + for d in 0..n.min(c.len()) { + let suffix = if pct && d + 1 == n { "%" } else { "" }; + let (r, nv, _) = + widgets::hot_number_at(ui, pos2(x, y), egui::Id::new(("v", uid, d)), c[d], if pct { 0.5 } else { 1.0 }, (-1e9, 1e9), 1, suffix, &t); + app.auto.add(&format!("timeline.prop.{uid}.value.{d}"), r, &prop.name); + if let Some(nv) = nv { + let mut nc = c.clone(); + if pct && prop.match_id == "scale" && !ui.input(|i| i.modifiers.alt) { + // Constrain proportions (AE's chain link, on by default). + let k = if c[d].abs() > 1e-9 { nv / c[d] } else { 1.0 }; + for e in 0..n { + nc[e] = if e == d { nv } else { c[e] * k }; + } + } else { + nc[d] = nv; + } + set(actions, json!(nc)); + } + x = r.max.x + if d + 1 < n { 2.0 } else { 0.0 }; + if d + 1 < n { + p.text(pos2(x, at.y), Align2::LEFT_CENTER, ",", Tokens::ui(12.0), t.hot_text); + x += 6.0; + } + } + } + Value::Color(c) => { + let r = Rect::from_min_size(pos2(x, at.y - 7.0), vec2(26.0, 14.0)); + let resp = widgets::swatch(ui, r, [c[0] as f32, c[1] as f32, c[2] as f32, 1.0], egui::Id::new(("sw", uid)), &t); + app.auto.add(&format!("timeline.prop.{uid}.value"), r, &prop.name); + let pop = egui::Id::new(("cpop", uid)); + if resp.clicked() { + widgets::open_popup(ui, pop); + } + let mut rgb = [c[0] as f32, c[1] as f32, c[2] as f32]; + if crate::header::color_popup(ui, pop, r.left_bottom(), &mut rgb) { + set(actions, json!([rgb[0], rgb[1], rgb[2], 1.0])); + } + } + Value::Bool(b) => { + let r = Rect::from_min_size(pos2(x, at.y - 8.0), vec2(16.0, 16.0)); + if widgets::checkbox(ui, r, *b, &t, egui::Id::new(("cb", uid))).clicked() { + set(actions, json!(!b)); + } + app.auto.add(&format!("timeline.prop.{uid}.value"), r, &prop.name); + } + Value::Enum(i) => { + if let ParamUi::Popup { options } = &prop.ui { + let r = Rect::from_min_size(pos2(x, at.y - 9.0), vec2(150.0, 18.0)); + let label = options.get(*i as usize).cloned().unwrap_or_default(); + let pop = egui::Id::new(("epop", uid)); + if widgets::dropdown(ui, r, &label, &t, egui::Id::new(("en", uid))).clicked() { + widgets::open_popup(ui, pop); + } + app.auto.add(&format!("timeline.prop.{uid}.value"), r, &prop.name); + if let Some(ni) = widgets::popup_menu(ui, pop, r.left_bottom(), options, Some(*i as usize)) { + set(actions, json!(ni)); + } + } else { + p.text(pos2(x, at.y), Align2::LEFT_CENTER, fmt_num(*i as f64, 0), Tokens::ui(12.0), t.hot_text); + } + } + Value::Path(_) => { + p.text(pos2(x, at.y), Align2::LEFT_CENTER, "Shape…", Tokens::ui(12.0), t.hot_text); + } + Value::Text(_) => {} + Value::Layer(l) => { + p.text(pos2(x, at.y), Align2::LEFT_CENTER, l.map(|l| format!("Layer {l}")).unwrap_or("None".into()), Tokens::ui(12.0), t.hot_text); + } + Value::Gradient(_) => { + p.text(pos2(x, at.y), Align2::LEFT_CENTER, "Edit Gradient…", Tokens::ui(12.0), t.hot_text); + } + Value::Str(s) => { + p.text(pos2(x, at.y), Align2::LEFT_CENTER, s.chars().take(30).collect::(), Tokens::ui(12.0), t.text_dim); + } + } +} + +/// Value graph of the selected properties (numeric dimensions over time) with key markers. +fn graph_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, comp: &Comp, ectx: &EvalCtx, tm: TMap, area: Rect) { + let t = app.tokens; + let props: Vec<(LayerId, u64)> = if app.session.state.selected_props.is_empty() { + // Default: animated properties of selected layers. + let mut v = vec![]; + for l in comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id)) { + l.props.walk("", &mut |_, pr| { + if pr.is_animated() && !pr.value.components().is_empty() { + v.push((l.id, pr.uid)); + } + }); + } + v + } else { + app.session.state.selected_props.clone() + }; + p.rect_filled(area, 0.0, Color32::from_rgb(0x1e, 0x1e, 0x1e)); + // Grid. + for i in 1..8 { + let y = area.min.y + area.height() * i as f32 / 8.0; + p.line_segment([pos2(area.min.x, y), pos2(area.max.x, y)], Stroke::new(1.0, Color32::from_white_alpha(10))); + } + if props.is_empty() { + p.text(area.center(), Align2::CENTER_CENTER, "Select animated properties to show them in the Graph Editor", Tokens::ui(12.0), t.text_faint); + return; + } + let colors = + [Color32::from_rgb(0xe0, 0x50, 0x50), Color32::from_rgb(0x60, 0xd0, 0x60), Color32::from_rgb(0x50, 0x8c, 0xf0), Color32::from_rgb(0xe8, 0xc8, 0x40)]; + // Sample all curves over the visible span; normalise to a common range. + let n = ((area.width() / 2.0) as usize).max(2); + let mut curves: Vec<(Vec>, &Layer, &Property)> = vec![]; + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for (lid, uid) in &props { + let Some(l) = comp.layer(*lid) else { continue }; + let Some(pr) = l.props.find(*uid) else { continue }; + let mut dims: Vec> = vec![]; + for i in 0..n { + let x = area.min.x + area.width() * i as f32 / (n - 1) as f32; + let tt = Tick::from_seconds_f64(tm.t(x)); + let v = ectx.at(tt).value(l, pr).components(); + if dims.is_empty() { + dims = vec![Vec::with_capacity(n); v.len().min(3)]; + } + for (d, c) in v.iter().take(dims.len()).enumerate() { + dims[d].push(*c); + lo = lo.min(*c); + hi = hi.max(*c); + } + } + curves.push((dims, l, pr)); + } + if !lo.is_finite() || !hi.is_finite() { + return; + } + if (hi - lo).abs() < 1e-9 { + hi = lo + 1.0; + } + let pad = (hi - lo) * 0.1; + let (lo, hi) = (lo - pad, hi + pad); + let ymap = |v: f64| area.max.y - ((v - lo) / (hi - lo)) as f32 * area.height(); + for (dims, l, pr) in &curves { + for (d, vals) in dims.iter().enumerate() { + let pts: Vec = vals.iter().enumerate().map(|(i, v)| pos2(area.min.x + area.width() * i as f32 / (n - 1) as f32, ymap(*v))).collect(); + p.add(egui::Shape::line(pts, Stroke::new(1.5, colors[d % colors.len()]))); + } + for k in &pr.keys { + let x = tm.x(l.comp_time(k.time).seconds()); + for (d, v) in k.value.components().iter().take(dims.len()).enumerate() { + let c = pos2(x, ymap(*v)); + p.rect_filled(Rect::from_center_size(c, vec2(6.0, 6.0)), 0.0, Color32::WHITE); + p.rect_stroke(Rect::from_center_size(c, vec2(6.0, 6.0)), 0.0, Stroke::new(1.0, colors[d % colors.len()]), StrokeKind::Outside); + } + } + } + // Value labels. + for i in 0..=4 { + let v = lo + (hi - lo) * i as f64 / 4.0; + p.text(pos2(area.min.x + 4.0, ymap(v)), Align2::LEFT_BOTTOM, format!("{v:.1}"), Tokens::ui(10.0), t.text_faint); + } + let _ = ui; +} diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs new file mode 100644 index 00000000..b1ae92af --- /dev/null +++ b/crates/ui-egui/src/panels/viewer.rs @@ -0,0 +1,886 @@ +//! The Composition viewer: pasteboard + comp frame, magnification and resolution, transparency +//! grid, guides, layer bounding boxes with handles, anchor points, motion paths and masks, and +//! direct manipulation (move, scale, rotate, pan behind, shape/type creation, hand and zoom). + +use effectcraft_engine::geom::{Mat3, vec2 as gv2}; +use effectcraft_engine::project::{GroupKind, Layer, LayerId}; +use effectcraft_engine::render::EvalCtx; +use effectcraft_engine::time::Tick; +use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use serde_json::json; + +use crate::icons::Icon; +use crate::state::{Resolution, Tool}; +use crate::theme::Tokens; +use crate::{EffectcraftApp, widgets}; + +/// Viewer mapping published each frame (for the control channel and other panels). +#[derive(Clone, Copy, Debug)] +pub struct ViewerMap { + pub origin: Pos2, + /// Points per comp pixel. + pub zoom: f32, + pub comp: [f32; 2], + pub area: Rect, +} + +impl ViewerMap { + pub fn to_screen(&self, p: [f64; 2]) -> Pos2 { + pos2(self.origin.x + p[0] as f32 * self.zoom, self.origin.y + p[1] as f32 * self.zoom) + } + pub fn to_comp(&self, p: Pos2) -> [f64; 2] { + [((p.x - self.origin.x) / self.zoom) as f64, ((p.y - self.origin.y) / self.zoom) as f64] + } +} + +fn map_id() -> egui::Id { + egui::Id::new("viewer-map") +} + +pub fn comp_to_screen(ctx: &egui::Context, p: [f32; 2]) -> Option { + let m: ViewerMap = ctx.data(|d| d.get_temp(map_id()))?; + Some(m.to_screen([p[0] as f64, p[1] as f64])) +} + +pub fn screen_to_comp(ctx: &egui::Context, p: Pos2) -> Option<[f64; 2]> { + let m: ViewerMap = ctx.data(|d| d.get_temp(map_id()))?; + Some(m.to_comp(p)) +} + +/// The fit magnification from the last frame. +pub fn last_fit(ctx: &egui::Context) -> f32 { + ctx.data(|d| d.get_temp::(egui::Id::new("viewer-fit"))).unwrap_or(0.5) +} + +/// What a drag in the viewer is doing. +#[derive(Clone, Debug)] +enum Gesture { + Move { layers: Vec<(LayerId, [f64; 3], Mat3)>, start: [f64; 2] }, + Scale { layer: LayerId, anchor_screen: Pos2, start_scale: [f64; 3], start_local: [f64; 2], inv: Mat3, uniform: bool }, + Rotate { layer: LayerId, center: Pos2, start_angle: f64, start_rot: f64 }, + Anchor { layer: LayerId, start_anchor: [f64; 3], start_pos: [f64; 3], start: [f64; 2], inv: Mat3, l2p: Mat3 }, + Pan { start_pan: [f32; 2] }, + Create { tool: Tool, start: [f64; 2] }, + Marquee { start: Pos2 }, +} + +const HANDLE: f32 = 7.0; + +/// Layer → comp matrix and its bounds quad (in comp pixels). +fn layer_quad(ctx: &EvalCtx, layer: &Layer) -> Option<(Mat3, [[f64; 2]; 4], [f64; 4])> { + let b = effectcraft_engine::render::content_bounds(ctx, layer)?; + let (m, _) = ctx.layer_to_comp(layer); + let pts = [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]].map(|p| { + let q = m.apply(gv2(p[0], p[1])); + [q.x, q.y] + }); + Some((m, pts, b)) +} + +fn point_in_quad(p: [f64; 2], q: &[[f64; 2]; 4]) -> bool { + let mut sign = 0.0; + for i in 0..4 { + let a = q[i]; + let b = q[(i + 1) % 4]; + let c = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]); + if c.abs() < 1e-9 { + continue; + } + if sign == 0.0 { + sign = c.signum(); + } else if c.signum() != sign { + return false; + } + } + true +} + +/// Parent-space linear inverse (to convert a comp-space drag delta into a position delta). +fn parent_inverse(ctx: &EvalCtx, layer: &Layer) -> Mat3 { + match layer.parent.and_then(|p| ctx.comp.layer(p)) { + Some(p) => { + let w = ctx.world_matrix(p); + let m = Mat3([[w.0[0][0], w.0[0][1], 0.0], [w.0[1][0], w.0[1][1], 0.0], [0.0, 0.0, 1.0]]); + m.inverse().unwrap_or(Mat3::IDENTITY) + } + None => Mat3::IDENTITY, + } +} + +fn checker(p: &egui::Painter, r: Rect) { + let s = 10.0; + p.rect_filled(r, 0.0, Color32::from_gray(0xcc)); + let mut y = r.min.y; + let mut row = 0; + while y < r.max.y { + let mut x = r.min.x + if row % 2 == 0 { 0.0 } else { s }; + while x < r.max.x { + p.rect_filled(Rect::from_min_max(pos2(x, y), pos2((x + s).min(r.max.x), (y + s).min(r.max.y))), 0.0, Color32::from_gray(0x99)); + x += 2.0 * s; + } + y += s; + row += 1; + } +} + +pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let ctx = ui.ctx().clone(); + let Some(cid) = app.session.active_comp_id() else { + empty_state(app, ui, rect); + return; + }; + let comp = app.session.project.comp(cid).cloned().unwrap_or_else(|| effectcraft_engine::project::Comp::new(1920, 1080, Default::default(), Tick::ZERO)); + let comp_name = app.session.project.item(cid).map(|i| i.name.clone()).unwrap_or_default(); + let p = ui.painter().clone(); + + // Navigator bar (open comps as breadcrumbs). + let nav = Rect::from_min_size(rect.min, vec2(rect.width(), 24.0)); + p.rect_filled(nav, 0.0, t.panel_bg); + let mut x = nav.min.x + 10.0; + let open = app.session.state.open_comps.clone(); + for oc in open { + let name = app.session.project.item(oc).map(|i| i.name.clone()).unwrap_or_default(); + let g = p.layout_no_wrap(name.clone(), Tokens::ui(11.5), t.text); + let r = Rect::from_min_size(pos2(x, nav.min.y + 3.0), vec2(g.size().x + 16.0, 18.0)); + let resp = ui.interact(r, egui::Id::new(("nav", oc.0)), Sense::click()); + let active = oc == cid; + p.rect_filled( + r, + 9.0, + if active { + Color32::from_rgb(0x34, 0x3c, 0x4e) + } else if resp.hovered() { + t.hover + } else { + Color32::TRANSPARENT + }, + ); + p.galley_with_override_text_color(pos2(r.min.x + 8.0, r.center().y - g.size().y / 2.0), g, if active { t.tab_text_active } else { t.text_dim }); + app.auto.add(&format!("viewer.nav.{}", oc.0), r, &name); + if resp.clicked() { + app.session.open_comp(oc); + } + x = r.max.x + 4.0; + } + + // Bottom control bar. + let bar_h = 30.0; + let bar = Rect::from_min_max(pos2(rect.min.x, rect.max.y - bar_h), rect.max); + let area = Rect::from_min_max(pos2(rect.min.x, nav.max.y), pos2(rect.max.x, bar.min.y)); + p.rect_filled(area, 0.0, t.pasteboard); + + let (cw, ch) = (comp.width as f32, comp.height as f32); + let fit = ((area.width() - 40.0) / cw).min((area.height() - 40.0) / ch).max(0.01); + ctx.data_mut(|d| d.insert_temp(egui::Id::new("viewer-fit"), fit)); + let zoom = app.ui.viewer.zoom.unwrap_or(fit); + let center = area.center() + vec2(app.ui.viewer.pan[0], app.ui.viewer.pan[1]); + let origin = center - vec2(cw * zoom / 2.0, ch * zoom / 2.0); + let map = ViewerMap { origin, zoom, comp: [cw, ch], area }; + ctx.data_mut(|d| d.insert_temp(map_id(), map)); + let comp_rect = Rect::from_min_size(origin, vec2(cw * zoom, ch * zoom)); + let painter = p.with_clip_rect(area); + + // Frame. + let ppp = ctx.pixels_per_point(); + let scale = app.viewer_scale(zoom, ppp); + crate::tick_playback(app, &ctx, scale); + let time = app.session.time(); + let frame = comp.frame_rate.frame_at(time); + let key = app.frame_key(cid, frame, scale); + app.request_frame(cid, frame, scale); + if let Some(img) = app.frames.get(&key) { + let stale = app.viewer_tex.as_ref().is_none_or(|(_, k)| *k != key); + if stale { + match &mut app.viewer_tex { + Some((tex, k)) if tex.size() == img.size => { + tex.set((*img).clone(), egui::TextureOptions::LINEAR); + *k = key; + } + _ => app.viewer_tex = Some((ctx.load_texture("viewer-frame", (*img).clone(), egui::TextureOptions::LINEAR), key)), + } + app.viewer_image = Some(img); + } + } + if app.ui.viewer.transparency_grid { + checker(&painter, comp_rect); + } else { + let bg = comp.background; + painter.rect_filled(comp_rect, 0.0, Color32::from_rgb((bg[0] * 255.0) as u8, (bg[1] * 255.0) as u8, (bg[2] * 255.0) as u8)); + } + if let Some((tex, k)) = &app.viewer_tex + && k.comp == cid.0 + { + painter.image(tex.id(), comp_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + painter.rect_stroke(comp_rect, 0.0, Stroke::new(1.0, Color32::from_black_alpha(160)), StrokeKind::Outside); + app.auto.add("viewer.comp", comp_rect, &comp_name); + app.auto.add("viewer.area", area, "Composition viewer"); + + // Guides. + if app.ui.viewer.safe_margins { + for (k, a) in [(0.9, 120u8), (0.8, 160)] { + let r = Rect::from_center_size(comp_rect.center(), comp_rect.size() * k); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_white_alpha(a)), StrokeKind::Middle); + } + let c = comp_rect.center(); + painter.line_segment([c - vec2(10.0, 0.0), c + vec2(10.0, 0.0)], Stroke::new(1.0, Color32::from_white_alpha(140))); + painter.line_segment([c - vec2(0.0, 10.0), c + vec2(0.0, 10.0)], Stroke::new(1.0, Color32::from_white_alpha(140))); + } + if app.ui.viewer.grid { + let step = 100.0 * zoom; + let mut gx = comp_rect.min.x; + while gx <= comp_rect.max.x { + painter.line_segment([pos2(gx, comp_rect.min.y), pos2(gx, comp_rect.max.y)], Stroke::new(1.0, Color32::from_rgba_unmultiplied(120, 160, 255, 50))); + gx += step; + } + let mut gy = comp_rect.min.y; + while gy <= comp_rect.max.y { + painter.line_segment([pos2(comp_rect.min.x, gy), pos2(comp_rect.max.x, gy)], Stroke::new(1.0, Color32::from_rgba_unmultiplied(120, 160, 255, 50))); + gy += step; + } + } + + // Overlays + interaction. + let snap_project = app.session.project.clone(); + let snap_expr = app.session.expr.clone(); + let ectx = EvalCtx { project: &snap_project, comp_id: cid, comp: &comp, time, expr: snap_expr.as_deref() }; + let selected = app.session.state.selected_layers.clone(); + let mut handle_hits: Vec<(LayerId, usize, Pos2)> = Vec::new(); + if app.ui.viewer.show_layer_controls { + for l in comp.layers.iter().filter(|l| selected.contains(&l.id) && l.is_active_at(time)) { + let col = Tokens::label(l.label); + // Motion path of animated position. + if let Some(pos) = l.transform().and_then(|tr| tr.get("position")) + && pos.keys.len() > 1 + && l.parent.is_none() + { + let lt0 = pos.keys.first().map(|k| k.time).unwrap_or(Tick::ZERO); + let lt1 = pos.keys.last().map(|k| k.time).unwrap_or(Tick::ZERO); + let fd = comp.frame_duration(); + let mut pts = vec![]; + let mut lt = lt0; + while lt <= lt1 { + let v = pos.value_at(lt).as_vec2(); + pts.push(map.to_screen(v)); + lt += fd; + } + painter.add(egui::Shape::line(pts.clone(), Stroke::new(1.0, col.gamma_multiply(0.8)))); + for q in pts.iter().step_by(1) { + painter.circle_filled(*q, 1.2, col.gamma_multiply(0.8)); + } + for k in &pos.keys { + let v = k.value.as_vec2(); + let s = map.to_screen(v); + painter.rect_filled(Rect::from_center_size(s, vec2(6.0, 6.0)), 0.0, col); + } + } + // Masks. + if app.ui.viewer.show_masks + && let Some(masks) = l.masks() + { + let (m, _) = ectx.layer_to_comp(l); + for g in masks.groups() { + let GroupKind::Mask { color, .. } = g.kind else { continue }; + let Some(path) = g.get("path").map(|pr| ectx.value(l, pr)) else { continue }; + let Some(sp) = path.as_path() else { continue }; + let k = effectcraft_engine::render::kurbo_path(sp); + let mut pts: Vec = vec![]; + kurbo::flatten(k.iter(), 0.5, |el| match el { + kurbo::PathEl::MoveTo(q) | kurbo::PathEl::LineTo(q) => { + let c = m.apply(gv2(q.x, q.y)); + pts.push(map.to_screen([c.x, c.y])); + } + _ => {} + }); + if sp.closed && !pts.is_empty() { + pts.push(pts[0]); + } + painter.add(egui::Shape::line(pts, Stroke::new(1.0, Color32::from_rgb(color[0], color[1], color[2])))); + for v in &sp.vertices { + let c = m.apply(gv2(v[0], v[1])); + painter.rect_filled( + Rect::from_center_size(map.to_screen([c.x, c.y]), vec2(5.0, 5.0)), + 0.0, + Color32::from_rgb(color[0], color[1], color[2]), + ); + } + } + } + let Some((m, q, _)) = layer_quad(&ectx, l) else { + // Cameras, lights, empty layers: just the anchor. + if let Some(tr) = l.transform() { + let pos = ectx.v3(l, tr, "position", [0.0; 3]); + let s = map.to_screen([pos[0], pos[1]]); + painter.circle_stroke(s, 6.0, Stroke::new(1.0, col)); + } + continue; + }; + let sq: Vec = q.iter().map(|p| map.to_screen(*p)).collect(); + painter.add(egui::Shape::closed_line(sq.clone(), Stroke::new(1.0, col))); + for i in 0..8 { + let hp = if i < 4 { sq[i] } else { sq[i - 4] + (sq[(i - 3) % 4] - sq[i - 4]) * 0.5 }; + let hr = Rect::from_center_size(hp, vec2(HANDLE, HANDLE)); + painter.rect_filled(hr, 0.0, col); + painter.rect_stroke(hr, 0.0, Stroke::new(1.0, Color32::from_black_alpha(120)), StrokeKind::Outside); + handle_hits.push((l.id, i, hp)); + app.auto.add(&format!("viewer.handle.{}.{i}", l.id.0), hr, "handle"); + } + // Anchor point. + if let Some(tr) = l.transform() { + let a = ectx.v3(l, tr, "anchor", [0.0; 3]); + let c = m.apply(gv2(a[0], a[1])); + let s = map.to_screen([c.x, c.y]); + painter.circle_stroke(s, 5.0, Stroke::new(1.0, Color32::WHITE)); + painter.line_segment([s - vec2(9.0, 0.0), s + vec2(9.0, 0.0)], Stroke::new(1.0, Color32::WHITE)); + painter.line_segment([s - vec2(0.0, 9.0), s + vec2(0.0, 9.0)], Stroke::new(1.0, Color32::WHITE)); + app.auto.add(&format!("viewer.anchor.{}", l.id.0), Rect::from_center_size(s, vec2(12.0, 12.0)), "anchor point"); + // 3D axis gizmo. + if l.is_3d() { + let w = ectx.world_matrix(l); + let (cam, _, _) = ectx.camera(); + let pc = cam * w; + let a3 = effectcraft_engine::geom::vec3(a[0], a[1], a[2]); + let o = pc.apply(a3); + let len = 60.0 / zoom as f64; + for (axis, col) in [ + (effectcraft_engine::geom::vec3(len, 0.0, 0.0), Color32::from_rgb(0xe0, 0x50, 0x50)), + (effectcraft_engine::geom::vec3(0.0, len, 0.0), Color32::from_rgb(0x60, 0xd0, 0x60)), + (effectcraft_engine::geom::vec3(0.0, 0.0, len), Color32::from_rgb(0x50, 0x8c, 0xf0)), + ] { + let e = pc.apply(a3 + axis); + painter.arrow(map.to_screen([o.x, o.y]), map.to_screen([e.x, e.y]) - map.to_screen([o.x, o.y]), Stroke::new(2.0, col)); + } + } + } + } + } + + // Interaction. + let resp = ui.interact(area, egui::Id::new("viewer-interact"), Sense::click_and_drag()); + let gid = egui::Id::new("viewer-gesture"); + if let Some(hp) = resp.hover_pos() { + app.pointer_comp = Some({ + let c = map.to_comp(hp); + [c[0] as f32, c[1] as f32] + }); + let cursor = match app.ui.tool { + Tool::Hand => egui::CursorIcon::Grab, + Tool::Zoom => egui::CursorIcon::ZoomIn, + Tool::Type | Tool::TypeVertical => egui::CursorIcon::Text, + t if t.is_shape() || t == Tool::Pen => egui::CursorIcon::Crosshair, + _ => { + if handle_hits.iter().any(|(_, _, h)| h.distance(hp) < HANDLE) { + egui::CursorIcon::ResizeNwSe + } else { + egui::CursorIcon::Default + } + } + }; + ctx.set_cursor_icon(cursor); + // Scroll wheel zooms around the pointer. + let scroll = ui.input(|i| i.smooth_scroll_delta.y + i.zoom_delta().ln() * 300.0); + if scroll.abs() > 0.1 && area.contains(hp) { + let k = (scroll / 300.0).exp(); + let nz = (zoom * k).clamp(0.01, 32.0); + let before = map.to_comp(hp); + let new_origin = hp - vec2(before[0] as f32 * nz, before[1] as f32 * nz); + let new_center = new_origin + vec2(cw * nz / 2.0, ch * nz / 2.0); + let pan = new_center - area.center(); + app.ui.viewer.zoom = Some(nz); + app.ui.viewer.pan = [pan.x, pan.y]; + } + } else { + app.pointer_comp = None; + } + let mods = ui.input(|i| i.modifiers); + let space_pan = ui.input(|i| i.key_down(egui::Key::Space)) && !ctx.egui_wants_keyboard_input(); + if resp.drag_started() + && let Some(pos) = resp.interact_pointer_pos() + { + let cpt = map.to_comp(pos); + let tool = if space_pan || resp.dragged_by(egui::PointerButton::Middle) { Tool::Hand } else { app.ui.tool }; + let g = match tool { + Tool::Hand => Some(Gesture::Pan { start_pan: app.ui.viewer.pan }), + Tool::Rotate => pick(app, &ectx, cpt, mods.shift).map(|l| { + let layer = comp.layer(l).cloned(); + let center = layer + .as_ref() + .and_then(|l| l.transform().map(|tr| ectx.v3(l, tr, "position", [0.0; 3]))) + .map(|p| map.to_screen([p[0], p[1]])) + .unwrap_or(pos); + let rot = layer.as_ref().and_then(|l| l.transform().map(|tr| ectx.f(l, tr, "rotation", 0.0))).unwrap_or(0.0); + Gesture::Rotate { layer: l, center, start_angle: ((pos.y - center.y) as f64).atan2((pos.x - center.x) as f64).to_degrees(), start_rot: rot } + }), + Tool::PanBehind => pick(app, &ectx, cpt, false).and_then(|l| { + let layer = comp.layer(l)?; + let tr = layer.transform()?; + let (l2c, _) = ectx.layer_to_comp(layer); + let l2p = ectx.local_matrix(layer); + let l2p = Mat3([[l2p.0[0][0], l2p.0[0][1], 0.0], [l2p.0[1][0], l2p.0[1][1], 0.0], [0.0, 0.0, 1.0]]); + Some(Gesture::Anchor { + layer: l, + start_anchor: ectx.v3(layer, tr, "anchor", [0.0; 3]), + start_pos: ectx.v3(layer, tr, "position", [0.0; 3]), + start: cpt, + inv: l2c.inverse().unwrap_or(Mat3::IDENTITY), + l2p, + }) + }), + t if t.is_shape() => Some(Gesture::Create { tool: t, start: cpt }), + Tool::Selection => { + if let Some((lid, hi, _)) = handle_hits.iter().find(|(_, _, h)| h.distance(pos) < HANDLE + 2.0).cloned() { + let layer = comp.layer(lid).cloned(); + layer.and_then(|layer| { + let tr = layer.transform()?; + let (l2c, _) = ectx.layer_to_comp(&layer); + let inv = l2c.inverse()?; + let a = ectx.v3(&layer, tr, "anchor", [0.0; 3]); + let ac = l2c.apply(gv2(a[0], a[1])); + let lp = inv.apply(gv2(cpt[0], cpt[1])); + let _ = hi; + Some(Gesture::Scale { + layer: lid, + anchor_screen: map.to_screen([ac.x, ac.y]), + start_scale: ectx.v3(&layer, tr, "scale", [100.0; 3]), + start_local: [lp.x - a[0], lp.y - a[1]], + inv, + uniform: hi < 4, + }) + }) + } else if let Some(l) = pick(app, &ectx, cpt, mods.shift) { + let layers: Vec<(LayerId, [f64; 3], Mat3)> = app + .session + .state + .selected_layers + .iter() + .filter_map(|id| comp.layer(*id)) + .filter(|l| !l.switches.locked) + .filter_map(|l| Some((l.id, ectx.v3(l, l.transform()?, "position", [0.0; 3]), parent_inverse(&ectx, l)))) + .collect(); + let _ = l; + (!layers.is_empty()).then_some(Gesture::Move { layers, start: cpt }) + } else { + let _ = app.session.execute("edit.deselectAll", json!({})); + Some(Gesture::Marquee { start: pos }) + } + } + _ => None, + }; + if let Some(g) = g { + ui.data_mut(|d| d.insert_temp(gid, g)); + } + } + let gesture: Option = ui.data(|d| d.get_temp(gid)); + if let (Some(g), Some(pos)) = (gesture.clone(), resp.interact_pointer_pos()) { + let cpt = map.to_comp(pos); + let merge = format!("viewer-drag-{}", ui.data(|d| d.get_temp::(egui::Id::new("viewer-drag-n")).unwrap_or(0))); + match g { + Gesture::Pan { start_pan } => { + let d = resp.total_drag_delta().unwrap_or_default(); + app.ui.viewer.pan = [start_pan[0] + d.x, start_pan[1] + d.y]; + } + Gesture::Move { layers, start } => { + let mut d = [cpt[0] - start[0], cpt[1] - start[1]]; + if mods.shift { + if d[0].abs() > d[1].abs() { d[1] = 0.0 } else { d[0] = 0.0 } + } + for (lid, p0, inv) in layers { + let dd = inv.apply_vec(gv2(d[0], d[1])); + let v = json!([p0[0] + dd.x, p0[1] + dd.y, p0[2]]); + let _ = app.session.execute("prop.set", json!({"layer": lid.0, "path": "transform/position", "value": v, "merge": merge})); + } + } + Gesture::Scale { layer, start_scale, start_local, inv, uniform, .. } => { + let lp = inv.apply(gv2(cpt[0], cpt[1])); + // Local point relative to the anchor in *unscaled* layer space. + let a = comp.layer(layer).and_then(|l| l.transform().map(|tr| ectx.v3(l, tr, "anchor", [0.0; 3]))).unwrap_or([0.0; 3]); + let cur = [lp.x - a[0], lp.y - a[1]]; + let fx = if start_local[0].abs() > 1e-6 { cur[0] / start_local[0] } else { 1.0 }; + let fy = if start_local[1].abs() > 1e-6 { cur[1] / start_local[1] } else { 1.0 }; + let (fx, fy) = if mods.shift || uniform && start_local[0].abs() > 1e-6 && start_local[1].abs() > 1e-6 && mods.shift { + let f = (fx + fy) / 2.0; + (f, f) + } else { + (if start_local[0].abs() > 1e-3 { fx } else { 1.0 }, if start_local[1].abs() > 1e-3 { fy } else { 1.0 }) + }; + // The local point moved within the *current* scale; compose with the start scale. + let cs = comp.layer(layer).and_then(|l| l.transform().map(|tr| ectx.v3(l, tr, "scale", [100.0; 3]))).unwrap_or([100.0; 3]); + let nx = cs[0] * fx; + let ny = cs[1] * fy; + let _ = start_scale; + let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/scale", "value": [nx, ny, cs[2]], "merge": merge})); + ui.data_mut(|d| { + if let Some(Gesture::Scale { start_local, .. }) = d.get_temp_mut_or_default::>(egui::Id::new("unused")).as_mut() { + let _ = start_local; + } + }); + // Re-baseline so the next frame's ratios are relative to the new scale. + let lp_unscaled = [cur[0] / fx.max(1e-9) * fx, cur[1] / fy.max(1e-9) * fy]; + let mut g2 = gesture.clone(); + if let Some(Gesture::Scale { start_local, inv: i2, .. }) = g2.as_mut() { + *start_local = lp_unscaled; + if let Some(l) = app.session.active_comp().and_then(|c| c.layer(layer)).cloned() { + let e2 = EvalCtx { + project: &app.session.project, + comp_id: cid, + comp: app.session.project.comp(cid).unwrap_or(&comp), + time, + expr: app.session.expr.as_deref(), + }; + if let Some(m) = e2.layer_to_comp(&l).0.inverse() { + *i2 = m; + } + } + } + if let Some(g2) = g2 { + ui.data_mut(|d| d.insert_temp(gid, g2)); + } + } + Gesture::Rotate { layer, center, start_angle, start_rot } => { + let ang = ((pos.y - center.y) as f64).atan2((pos.x - center.x) as f64).to_degrees(); + let mut r = start_rot + (ang - start_angle); + if mods.shift { + r = (r / 45.0).round() * 45.0; + } + let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/rotation", "value": r, "merge": merge})); + } + Gesture::Anchor { layer, start_anchor, start_pos, start, inv, l2p } => { + let a = inv.apply(gv2(start[0], start[1])); + let b = inv.apply(gv2(cpt[0], cpt[1])); + let dl = gv2(b.x - a.x, b.y - a.y); + let na = [start_anchor[0] + dl.x, start_anchor[1] + dl.y, start_anchor[2]]; + let dp = l2p.apply_vec(dl); + let np = [start_pos[0] + dp.x, start_pos[1] + dp.y, start_pos[2]]; + let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/anchor", "value": na, "merge": merge})); + let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/position", "value": np, "merge": merge})); + } + Gesture::Create { start, .. } => { + let a = map.to_screen(start); + let r = Rect::from_two_pos(a, pos); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, t.accent), StrokeKind::Middle); + } + Gesture::Marquee { start } => { + let r = Rect::from_two_pos(start, pos); + painter.rect_filled(r, 0.0, t.accent.gamma_multiply(0.12)); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, t.accent), StrokeKind::Middle); + } + } + } + if resp.drag_stopped() { + if let (Some(g), Some(pos)) = (gesture, resp.interact_pointer_pos()) { + match g { + Gesture::Create { tool, start } => { + let end = map.to_comp(pos); + create_shape(app, tool, start, end, mods.shift); + } + Gesture::Marquee { start } => { + let a = map.to_comp(start); + let b = map.to_comp(pos); + let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0])); + let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1])); + let hits: Vec = comp + .layers + .iter() + .filter(|l| l.is_active_at(time) && !l.switches.locked) + .filter(|l| layer_quad(&ectx, l).is_some_and(|(_, q, _)| q.iter().any(|p| p[0] >= x0 && p[0] <= x1 && p[1] >= y0 && p[1] <= y1))) + .map(|l| l.id.0) + .collect(); + let _ = app.session.execute("layer.select", json!({"layers": hits})); + } + _ => {} + } + } + ui.data_mut(|d| { + d.remove::(gid); + let n: u64 = d.get_temp(egui::Id::new("viewer-drag-n")).unwrap_or(0); + d.insert_temp(egui::Id::new("viewer-drag-n"), n + 1); + }); + } + if resp.clicked() + && let Some(pos) = resp.interact_pointer_pos() + { + let cpt = map.to_comp(pos); + match app.ui.tool { + Tool::Zoom => { + let k = if mods.alt { 0.5 } else { 2.0 }; + let nz = (zoom * k).clamp(0.01, 32.0); + let new_origin = pos - vec2(cpt[0] as f32 * nz, cpt[1] as f32 * nz); + let pan = new_origin + vec2(cw * nz / 2.0, ch * nz / 2.0) - area.center(); + app.ui.viewer.zoom = Some(nz); + app.ui.viewer.pan = [pan.x, pan.y]; + } + Tool::Type | Tool::TypeVertical => { + let r = app.session.execute("layer.newText", json!({"text": "Text", "size": 96, "position": [cpt[0], cpt[1]], "justify": "left"})); + if let Ok(v) = r { + ui.data_mut(|d| d.insert_temp(egui::Id::new("viewer-text-edit"), (v["layer"].as_u64().unwrap_or(0), "Text".to_string()))); + } + } + _ => { + if pick(app, &ectx, cpt, mods.shift).is_none() { + let _ = app.session.execute("edit.deselectAll", json!({})); + } + } + } + } + if resp.double_clicked() + && let Some(pos) = resp.interact_pointer_pos() + { + let cpt = map.to_comp(pos); + if let Some(l) = pick(app, &ectx, cpt, false).and_then(|l| comp.layer(l)) { + match &l.source { + effectcraft_engine::project::LayerSource::Comp { item } => app.session.open_comp(*item), + effectcraft_engine::project::LayerSource::Text => { + let doc = effectcraft_engine::render::text::source_text(&ectx, l).map(|d| d.text).unwrap_or_default(); + ui.data_mut(|d| d.insert_temp(egui::Id::new("viewer-text-edit"), (l.id.0, doc))); + } + _ => {} + } + } + } + text_edit_overlay(app, ui, &map); + + // Status chips (render time / caching). + if app.playback.playing && app.playback.waiting { + let r = Rect::from_min_size(area.min + vec2(10.0, 10.0), vec2(150.0, 22.0)); + painter.rect_filled(r, 11.0, Color32::from_black_alpha(170)); + painter.text(r.center(), Align2::CENTER_CENTER, "Caching frames…", Tokens::ui(11.5), t.cache_green); + } + + bottom_bar(app, ui, bar, zoom, fit, time, &comp); +} + +/// Topmost layer under a comp point (selects it; shift toggles). Returns the hit layer. +fn pick(app: &mut EffectcraftApp, ectx: &EvalCtx, cpt: [f64; 2], toggle: bool) -> Option { + let hit = ectx + .comp + .layers + .iter() + .filter(|l| l.is_active_at(ectx.time) && l.switches.video && !l.switches.locked && !l.is_camera() && !l.is_light()) + .find(|l| layer_quad(ectx, l).is_some_and(|(_, q, _)| point_in_quad(cpt, &q))) + .map(|l| l.id)?; + if toggle { + let _ = app.session.execute("layer.select", json!({"layers": [hit.0], "toggle": true})); + } else if !app.session.state.selected_layers.contains(&hit) { + let _ = app.session.execute("layer.select", json!({"layers": [hit.0]})); + } + Some(hit) +} + +fn create_shape(app: &mut EffectcraftApp, tool: Tool, a: [f64; 2], b: [f64; 2], square: bool) { + let mut w = (b[0] - a[0]).abs(); + let mut h = (b[1] - a[1]).abs(); + if w < 2.0 && h < 2.0 { + return; + } + if square { + let m = w.max(h); + w = m; + h = m; + } + let cx = a[0].min(b[0]) + w / 2.0; + let cy = a[1].min(b[1]) + h / 2.0; + let kind = match tool { + Tool::Rectangle => "rect", + Tool::RoundedRect => "rounded", + Tool::Ellipse => "ellipse", + Tool::Polygon => "polygon", + _ => "star", + }; + // A non-shape layer selected and "creates mask": add a mask instead. + let sel = app.session.state.selected_layers.first().copied(); + let sel_layer = sel.and_then(|id| app.session.active_comp().and_then(|c| c.layer(id)).cloned()); + if let Some(l) = sel_layer + && !matches!(l.source, effectcraft_engine::project::LayerSource::Shape) + && l.source.is_av() + && matches!(kind, "rect" | "ellipse") + { + // Mask in layer space: invert the layer transform. + let comp = app.session.active_comp().cloned(); + if let Some(comp) = comp { + 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, + }; + let inv = ectx.layer_to_comp(&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 _ = app.session.execute( + "layer.addMask", + json!({"layer": l.id.0, "shape": if kind == "ellipse" { "ellipse" } else { "rect" }, "rect": [p0.x.min(p1.x), p0.y.min(p1.y), (p1.x - p0.x).abs(), (p1.y - p0.y).abs()]}), + ); + return; + } + } + let fill = app.ui.fill_color; + let stroke = app.ui.stroke_color; + let _ = app.session.execute( + "layer.newShape", + json!({"kind": kind, "size": [w, h], "position": [cx, cy], "fill": [fill[0], fill[1], fill[2]], "stroke": [stroke[0], stroke[1], stroke[2]], "strokeWidth": app.ui.stroke_width}), + ); +} + +/// Inline text editing for a text layer (double-click or Type tool click). +fn text_edit_overlay(app: &mut EffectcraftApp, ui: &mut egui::Ui, map: &ViewerMap) { + let id = egui::Id::new("viewer-text-edit"); + let Some((lid, mut text)) = ui.data(|d| d.get_temp::<(u64, String)>(id)) else { return }; + let comp = app.session.active_comp().cloned(); + let Some(comp) = comp else { return }; + let Some(layer) = comp.layer(LayerId(lid)).cloned() else { + ui.data_mut(|d| d.remove::<(u64, String)>(id)); + return; + }; + let pos = layer.transform().and_then(|tr| tr.get("position")).map(|p| p.value_at(layer.layer_time(app.session.time())).as_vec2()).unwrap_or([0.0, 0.0]); + let at = map.to_screen(pos) + vec2(-20.0, 10.0); + let mut done = false; + egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(at).show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.label(egui::RichText::new("Edit text — Enter to commit, Esc to cancel").small()); + let r = ui.add(egui::TextEdit::multiline(&mut text).desired_width(320.0).desired_rows(2).font(Tokens::ui(16.0))); + r.request_focus(); + if ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift) { + let _ = app.session.execute("layer.setText", json!({"layer": lid, "text": text.trim_end_matches('\n')})); + done = true; + } + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + done = true; + } + }); + }); + if done { + ui.data_mut(|d| d.remove::<(u64, String)>(id)); + } else { + ui.data_mut(|d| d.insert_temp(id, (lid, text))); + } +} + +fn bottom_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, zoom: f32, fit: f32, time: Tick, comp: &effectcraft_engine::project::Comp) { + let t = app.tokens; + let p = ui.painter().clone(); + p.rect_filled(bar, 0.0, t.panel_bg); + p.line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, t.separator)); + let cy = bar.center().y; + let mut x = bar.min.x + 8.0; + // Magnification. + let ppp = ui.ctx().pixels_per_point(); + let mag = if app.ui.viewer.zoom.is_none() { format!("Fit ({:.0}%)", fit * ppp * 100.0) } else { format!("{:.1}%", zoom * ppp * 100.0).replace(".0%", "%") }; + let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(92.0, 20.0)); + if widgets::dropdown(ui, r, &mag, &t, egui::Id::new("vw-mag")).clicked() { + widgets::open_popup(ui, egui::Id::new("vw-mag-pop")); + } + app.auto.add("viewer.magnification", r, "Magnification"); + let opts: Vec = ["Fit", "Fit up to 100%", "-", "1.5%", "3.1%", "6.25%", "12.5%", "25%", "33.3%", "50%", "100%", "200%", "400%", "800%", "1600%"] + .iter() + .map(|s| s.to_string()) + .collect(); + if let Some(i) = widgets::popup_menu(ui, egui::Id::new("vw-mag-pop"), r.left_top() - vec2(0.0, 380.0), &opts, None) { + let o = &opts[i]; + app.ui.viewer.pan = [0.0, 0.0]; + app.ui.viewer.zoom = match o.as_str() { + "Fit" => None, + "Fit up to 100%" => Some(fit.min(1.0 / ppp)), + s => s.trim_end_matches('%').parse::().ok().map(|v| v / 100.0 / ppp), + }; + } + x = r.max.x + 6.0; + // Toggles. + let tog = |ui: &mut egui::Ui, auto: &mut crate::automation::Registry, x: &mut f32, icon: Icon, on: bool, id: &str, tip: &str| -> bool { + let r = Rect::from_min_size(pos2(*x, cy - 11.0), vec2(22.0, 22.0)); + let resp = widgets::icon_button(ui, r, icon, on, &t, egui::Id::new(id)).on_hover_text(tip); + auto.add(&format!("viewer.{id}"), r, tip); + *x += 24.0; + resp.clicked() + }; + if tog(ui, &mut app.auto, &mut x, Icon::Grid, app.ui.viewer.grid || app.ui.viewer.safe_margins, "grid", "Choose grid and guide options") { + if app.ui.viewer.safe_margins { + app.ui.viewer.safe_margins = false; + app.ui.viewer.grid = !app.ui.viewer.grid; + } else { + app.ui.viewer.safe_margins = true; + } + } + if tog(ui, &mut app.auto, &mut x, Icon::MaskVis, app.ui.viewer.show_masks, "masks", "Toggle Mask and Shape Path Visibility") { + app.ui.viewer.show_masks = !app.ui.viewer.show_masks; + } + // Timecode. + let tc = crate::panels::timecode(&app.session, comp, time); + let g = p.layout_no_wrap(tc, Tokens::mono(12.0), t.timecode); + let tr = Rect::from_min_size(pos2(x + 4.0, cy - 9.0), g.size() + vec2(8.0, 4.0)); + p.galley(pos2(tr.min.x + 4.0, tr.min.y + 2.0), g, t.timecode); + app.auto.add("viewer.timecode", tr, "Current time"); + x = tr.max.x + 6.0; + if tog(ui, &mut app.auto, &mut x, Icon::Snapshot, false, "snapshot", "Take Snapshot") { + app.ui.status = "Snapshot taken".into(); + } + let _ = tog(ui, &mut app.auto, &mut x, Icon::ShowSnapshot, false, "showSnapshot", "Show Snapshot"); + let _ = tog(ui, &mut app.auto, &mut x, Icon::Channel, app.ui.viewer.channel != "RGB", "channel", "Show Channel and Color Management Settings"); + // Resolution. + let r = Rect::from_min_size(pos2(x + 2.0, cy - 10.0), vec2(78.0, 20.0)); + let rl = if app.ui.viewer.res == Resolution::Auto { + let s = app.viewer_scale(zoom, ppp); + format!( + "Auto ({})", + if s >= 1.0 { + "Full" + } else if s >= 0.5 { + "Half" + } else if s >= 0.33 { + "Third" + } else { + "Quarter" + } + ) + } else { + app.ui.viewer.res.label().to_string() + }; + if widgets::dropdown(ui, r, &rl, &t, egui::Id::new("vw-res")).clicked() { + widgets::open_popup(ui, egui::Id::new("vw-res-pop")); + } + app.auto.add("viewer.resolution", r, "Resolution/Down Sample Factor"); + let ro: Vec = Resolution::ALL.iter().map(|r| r.label().to_string()).collect(); + if let Some(i) = + widgets::popup_menu(ui, egui::Id::new("vw-res-pop"), r.left_top() - vec2(0.0, 140.0), &ro, Resolution::ALL.iter().position(|x| *x == app.ui.viewer.res)) + { + app.ui.viewer.res = Resolution::ALL[i]; + } + x = r.max.x + 6.0; + if tog(ui, &mut app.auto, &mut x, Icon::Region, false, "roi", "Region of Interest") {} + if tog(ui, &mut app.auto, &mut x, Icon::Checker, app.ui.viewer.transparency_grid, "transparency", "Toggle Transparency Grid") { + app.ui.viewer.transparency_grid = !app.ui.viewer.transparency_grid; + } + if tog(ui, &mut app.auto, &mut x, Icon::Sparkle, app.ui.viewer.fast_preview, "fastPreviews", "Fast Previews") { + app.ui.viewer.fast_preview = !app.ui.viewer.fast_preview; + } + // 3D renderer + view. + if comp.has_3d() { + let r = Rect::from_min_size(pos2(x + 2.0, cy - 10.0), vec2(96.0, 20.0)); + let _ = widgets::dropdown(ui, r, "Classic 3D", &t, egui::Id::new("vw-3d")); + x = r.max.x + 4.0; + let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(110.0, 20.0)); + let _ = widgets::dropdown(ui, r, "Active Camera", &t, egui::Id::new("vw-cam")); + } + // Right: render time. + let ms = app.frames.last_ms.lock().map(|v| *v).unwrap_or(0.0); + p.text(pos2(bar.max.x - 10.0, cy), Align2::RIGHT_CENTER, format!("{ms:.0} ms"), Tokens::ui(11.0), t.text_faint); +} + +fn empty_state(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { + let t = app.tokens; + let p = ui.painter(); + p.rect_filled(rect, 0.0, t.pasteboard); + let c = rect.center(); + p.text(c - vec2(0.0, 40.0), Align2::CENTER_CENTER, "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"); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs new file mode 100644 index 00000000..05a85121 --- /dev/null +++ b/crates/ui-egui/src/state.rs @@ -0,0 +1,332 @@ +//! Frontend view state (not project data). Serde so the control channel can read and set it. + +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; + +use crate::dock::{DockNode, PanelKind}; +use crate::icons::Icon; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Tool { + #[default] + Selection, + Hand, + Zoom, + Orbit, + PanCamera, + Dolly, + Rotate, + PanBehind, + Rectangle, + RoundedRect, + Ellipse, + Polygon, + Star, + Pen, + Type, + TypeVertical, + Brush, + Clone, + Eraser, + RotoBrush, + Puppet, +} + +impl Tool { + /// Toolbar slots: each slot shows its current tool; the slot cycles with its shortcut. + pub const SLOTS: &'static [&'static [Tool]] = &[ + &[Tool::Selection], + &[Tool::Hand], + &[Tool::Zoom], + &[Tool::Orbit], + &[Tool::PanCamera], + &[Tool::Dolly], + &[Tool::Rotate], + &[Tool::PanBehind], + &[Tool::Rectangle, Tool::RoundedRect, Tool::Ellipse, Tool::Polygon, Tool::Star], + &[Tool::Pen], + &[Tool::Type, Tool::TypeVertical], + &[Tool::Brush], + &[Tool::Clone], + &[Tool::Eraser], + &[Tool::RotoBrush], + &[Tool::Puppet], + ]; + pub const ALL: [Tool; 21] = [ + Tool::Selection, + Tool::Hand, + Tool::Zoom, + Tool::Orbit, + Tool::PanCamera, + Tool::Dolly, + Tool::Rotate, + Tool::PanBehind, + Tool::Rectangle, + Tool::RoundedRect, + Tool::Ellipse, + Tool::Polygon, + Tool::Star, + Tool::Pen, + Tool::Type, + Tool::TypeVertical, + Tool::Brush, + Tool::Clone, + Tool::Eraser, + Tool::RotoBrush, + Tool::Puppet, + ]; + pub fn label(self) -> &'static str { + match self { + Tool::Selection => "Selection Tool", + Tool::Hand => "Hand Tool", + Tool::Zoom => "Zoom Tool", + Tool::Orbit => "Orbit Around Cursor Tool", + Tool::PanCamera => "Pan Under Cursor Tool", + Tool::Dolly => "Dolly Towards Cursor Tool", + Tool::Rotate => "Rotation Tool", + Tool::PanBehind => "Pan Behind (Anchor Point) Tool", + Tool::Rectangle => "Rectangle Tool", + Tool::RoundedRect => "Rounded Rectangle Tool", + Tool::Ellipse => "Ellipse Tool", + Tool::Polygon => "Polygon Tool", + Tool::Star => "Star Tool", + Tool::Pen => "Pen Tool", + Tool::Type => "Horizontal Type Tool", + Tool::TypeVertical => "Vertical Type Tool", + Tool::Brush => "Brush Tool", + Tool::Clone => "Clone Stamp Tool", + Tool::Eraser => "Eraser Tool", + Tool::RotoBrush => "Roto Brush Tool", + Tool::Puppet => "Puppet Position Pin Tool", + } + } + pub fn shortcut(self) -> Option<&'static str> { + match self { + Tool::Selection => Some("V"), + Tool::Hand => Some("H"), + Tool::Zoom => Some("Z"), + Tool::Orbit => Some("1"), + Tool::PanCamera => Some("2"), + Tool::Dolly => Some("3"), + Tool::Rotate => Some("W"), + Tool::PanBehind => Some("Y"), + Tool::Rectangle | Tool::RoundedRect | Tool::Ellipse | Tool::Polygon | Tool::Star => Some("Q"), + Tool::Pen => Some("G"), + Tool::Type | Tool::TypeVertical => Some("Cmd+T"), + Tool::Brush | Tool::Clone | Tool::Eraser => Some("Cmd+B"), + Tool::RotoBrush => Some("Alt+W"), + Tool::Puppet => Some("Cmd+P"), + } + } + pub fn icon(self) -> Icon { + match self { + Tool::Selection => Icon::Selection, + Tool::Hand => Icon::Hand, + Tool::Zoom => Icon::Zoom, + Tool::Orbit => Icon::Orbit, + Tool::PanCamera => Icon::PanCamera, + Tool::Dolly => Icon::Dolly, + Tool::Rotate => Icon::Rotate, + Tool::PanBehind => Icon::PanBehind, + Tool::Rectangle => Icon::Rectangle, + Tool::RoundedRect => Icon::RoundedRect, + Tool::Ellipse => Icon::Ellipse, + Tool::Polygon => Icon::Polygon, + Tool::Star => Icon::Star, + Tool::Pen => Icon::Pen, + Tool::Type => Icon::Type, + Tool::TypeVertical => Icon::TypeVertical, + Tool::Brush => Icon::Brush, + Tool::Clone => Icon::Clone, + Tool::Eraser => Icon::Eraser, + Tool::RotoBrush => Icon::RotoBrush, + Tool::Puppet => Icon::Puppet, + } + } + pub fn from_name(s: &str) -> Option { + let n = s.to_ascii_lowercase().replace([' ', '_', '-'], ""); + Tool::ALL.into_iter().find(|t| format!("{t:?}").to_ascii_lowercase() == n || t.label().to_ascii_lowercase().replace(' ', "").starts_with(&n)) + } + pub fn is_shape(self) -> bool { + matches!(self, Tool::Rectangle | Tool::RoundedRect | Tool::Ellipse | Tool::Polygon | Tool::Star) + } +} + +/// Viewer resolution (Auto follows the magnification). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Resolution { + #[default] + Auto, + Full, + Half, + Third, + Quarter, +} + +impl Resolution { + pub const ALL: [Resolution; 5] = [Resolution::Auto, Resolution::Full, Resolution::Half, Resolution::Third, Resolution::Quarter]; + pub fn label(self) -> &'static str { + match self { + Resolution::Auto => "Auto", + Resolution::Full => "Full", + Resolution::Half => "Half", + Resolution::Third => "Third", + Resolution::Quarter => "Quarter", + } + } + /// Render scale for a viewer magnification (and display pixel density). + pub fn scale(self, zoom: f32, ppp: f32) -> f64 { + match self { + Resolution::Auto => { + let z = (zoom * ppp) as f64; + if z >= 0.75 { + 1.0 + } else if z >= 0.45 { + 0.5 + } else if z >= 0.3 { + 1.0 / 3.0 + } else { + 0.25 + } + } + Resolution::Full => 1.0, + Resolution::Half => 0.5, + Resolution::Third => 1.0 / 3.0, + Resolution::Quarter => 0.25, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ViewerState { + /// Magnification (1 = 100%); None = fit. + pub zoom: Option, + /// Pan offset in points from the centred position. + pub pan: [f32; 2], + pub res: Resolution, + pub transparency_grid: bool, + pub show_masks: bool, + pub safe_margins: bool, + pub grid: bool, + pub rulers: bool, + pub channel: String, + pub show_layer_controls: bool, + pub fast_preview: bool, +} + +impl Default for ViewerState { + fn default() -> Self { + ViewerState { + zoom: None, + pan: [0.0, 0.0], + res: Resolution::Auto, + transparency_grid: false, + show_masks: true, + safe_margins: false, + grid: false, + rulers: false, + channel: "RGB".into(), + show_layer_controls: true, + fast_preview: false, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TimelineState { + /// Visible span start (seconds) and pixels per second; None = fit comp. + pub start: f64, + pub pps: Option, + pub scroll_y: f32, + /// Left column area width. + pub columns_w: f32, + pub show_modes: bool, + pub graph_editor: bool, + pub search: String, + /// Twirled-open layers and groups (by layer id / group uid). + pub open_layers: BTreeSet, + pub open_groups: BTreeSet, + /// "Reveal" filter: only show these property match ids (P/S/R/T/A…) — empty = normal. + pub reveal: Vec, +} + +impl Default for TimelineState { + fn default() -> Self { + TimelineState { + start: 0.0, + pps: None, + scroll_y: 0.0, + columns_w: 560.0, + show_modes: true, + graph_editor: false, + search: String::new(), + open_layers: BTreeSet::new(), + open_groups: BTreeSet::new(), + reveal: vec![], + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct UiState { + pub tool: Tool, + /// Tool shown in each toolbar slot. + pub slot_tools: Vec, + pub workspace: String, + pub dock: DockNode, + pub focused: PanelKind, + pub viewer: ViewerState, + pub timeline: TimelineState, + pub theme: crate::theme::ThemeKind, + pub show_menu_bar: bool, + pub status: String, + /// Effects & Presets search text. + pub effects_search: String, + pub effects_open: BTreeSet, + pub project_search: String, + pub project_open_folders: BTreeSet, + /// Effect Controls twirl state (group uids that are collapsed). + pub fx_closed: BTreeSet, + /// Shape tool options. + pub fill_color: [f32; 3], + pub stroke_color: [f32; 3], + pub stroke_width: f32, + pub snapping: bool, + /// Tool creates shape (true) or mask (false) when a layer is selected. + pub tool_creates_shape: bool, + /// Preview panel options. + pub preview_loop: bool, + pub preview_cache_first: bool, + pub start_screen: bool, +} + +impl Default for UiState { + fn default() -> Self { + UiState { + tool: Tool::Selection, + slot_tools: Tool::SLOTS.iter().map(|s| s[0]).collect(), + workspace: "Default".into(), + dock: crate::dock::workspace("Default"), + focused: PanelKind::Composition, + viewer: ViewerState::default(), + timeline: TimelineState::default(), + theme: Default::default(), + show_menu_bar: true, + status: String::new(), + effects_search: String::new(), + effects_open: BTreeSet::new(), + project_search: String::new(), + project_open_folders: BTreeSet::new(), + fx_closed: BTreeSet::new(), + fill_color: [0.24, 0.55, 0.96], + stroke_color: [1.0, 1.0, 1.0], + stroke_width: 0.0, + snapping: true, + tool_creates_shape: true, + preview_loop: true, + preview_cache_first: false, + start_screen: false, + } + } +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs new file mode 100644 index 00000000..72bbfffb --- /dev/null +++ b/crates/ui-egui/src/theme.rs @@ -0,0 +1,250 @@ +//! Design tokens. Every widget reads colours/sizes from [`Tokens`] so themes apply everywhere. +//! +//! The default theme follows the look of After Effects' dark UI (values estimated from public +//! documentation and product knowledge, tuned by eye; see `plan/aftereffects/README.md` §2). Fonts +//! are Inter + JetBrains Mono (OFL). + +use std::sync::Arc; + +use egui::{Color32, FontData, FontDefinitions, FontFamily, FontId, Stroke, TextStyle, Visuals}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ThemeKind { + #[default] + Dark, + Darker, + Light, +} + +impl ThemeKind { + pub fn from_name(s: &str) -> Option { + match s.to_ascii_lowercase().as_str() { + "dark" | "default" => Some(ThemeKind::Dark), + "darker" | "darkest" => Some(ThemeKind::Darker), + "light" => Some(ThemeKind::Light), + _ => None, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tokens { + pub kind: ThemeKind, + pub app_bg: Color32, + pub header_bg: Color32, + pub panel_bg: Color32, + pub tab_text: Color32, + pub tab_text_active: Color32, + pub focus: Color32, + pub accent: Color32, + pub accent_hover: Color32, + pub text: Color32, + pub text_dim: Color32, + pub text_faint: Color32, + pub icon: Color32, + pub icon_active: Color32, + pub hover: Color32, + pub pressed: Color32, + pub field_bg: Color32, + pub field_border: Color32, + pub separator: Color32, + pub row: Color32, + pub row_alt: Color32, + pub row_selected: Color32, + pub hot_text: Color32, + pub tl_bg: Color32, + pub tl_ruler_bg: Color32, + pub tl_ruler_tick: Color32, + pub tl_ruler_text: Color32, + pub cti: Color32, + pub work_area: Color32, + pub cache_green: Color32, + pub keyframe: Color32, + pub keyframe_selected: Color32, + pub pasteboard: Color32, + pub timecode: Color32, + pub danger: Color32, + pub warning: Color32, + pub radius: f32, + pub radius_sm: f32, + pub gap: f32, + pub tab_h: f32, + pub row_h: f32, +} + +impl Tokens { + pub fn for_kind(kind: ThemeKind) -> Self { + let dark = Tokens { + kind, + app_bg: Color32::from_rgb(0x12, 0x12, 0x12), + header_bg: Color32::from_rgb(0x1f, 0x1f, 0x1f), + panel_bg: Color32::from_rgb(0x23, 0x23, 0x23), + tab_text: Color32::from_rgb(0x9a, 0x9a, 0x9a), + tab_text_active: Color32::from_rgb(0xe3, 0xe3, 0xe3), + focus: Color32::from_rgb(0x2d, 0x8c, 0xeb), + accent: Color32::from_rgb(0x2d, 0x8c, 0xeb), + accent_hover: Color32::from_rgb(0x4a, 0xa0, 0xf5), + text: Color32::from_rgb(0xc8, 0xc8, 0xc8), + text_dim: Color32::from_rgb(0x9a, 0x9a, 0x9a), + text_faint: Color32::from_rgb(0x66, 0x66, 0x66), + icon: Color32::from_rgb(0xb4, 0xb4, 0xb4), + icon_active: Color32::from_rgb(0xf0, 0xf0, 0xf0), + hover: Color32::from_rgb(0x30, 0x30, 0x30), + pressed: Color32::from_rgb(0x45, 0x45, 0x45), + field_bg: Color32::from_rgb(0x17, 0x17, 0x17), + field_border: Color32::from_rgb(0x3a, 0x3a, 0x3a), + separator: Color32::from_rgb(0x34, 0x34, 0x34), + row: Color32::from_rgb(0x23, 0x23, 0x23), + row_alt: Color32::from_rgb(0x27, 0x27, 0x27), + row_selected: Color32::from_rgb(0x3a, 0x3a, 0x3a), + hot_text: Color32::from_rgb(0x3d, 0x8f, 0xf5), + tl_bg: Color32::from_rgb(0x1b, 0x1b, 0x1b), + tl_ruler_bg: Color32::from_rgb(0x23, 0x23, 0x23), + tl_ruler_tick: Color32::from_rgb(0x70, 0x70, 0x70), + tl_ruler_text: Color32::from_rgb(0x9a, 0x9a, 0x9a), + cti: Color32::from_rgb(0x2d, 0x8c, 0xeb), + work_area: Color32::from_rgb(0x4a, 0x4a, 0x4a), + cache_green: Color32::from_rgb(0x3c, 0xa6, 0x4c), + keyframe: Color32::from_rgb(0xa8, 0xa8, 0xa8), + keyframe_selected: Color32::from_rgb(0x3d, 0x8f, 0xf5), + pasteboard: Color32::from_rgb(0x1a, 0x1a, 0x1a), + timecode: Color32::from_rgb(0x3d, 0x8f, 0xf5), + danger: Color32::from_rgb(0xe0, 0x4a, 0x3c), + warning: Color32::from_rgb(0xe8, 0x9a, 0x2c), + radius: 6.0, + radius_sm: 3.0, + gap: 4.0, + tab_h: 30.0, + row_h: 22.0, + }; + match kind { + ThemeKind::Dark => dark, + ThemeKind::Darker => Tokens { + app_bg: Color32::from_rgb(0x08, 0x08, 0x08), + header_bg: Color32::from_rgb(0x16, 0x16, 0x16), + panel_bg: Color32::from_rgb(0x19, 0x19, 0x19), + row: Color32::from_rgb(0x19, 0x19, 0x19), + row_alt: Color32::from_rgb(0x1d, 0x1d, 0x1d), + tl_bg: Color32::from_rgb(0x12, 0x12, 0x12), + tl_ruler_bg: Color32::from_rgb(0x19, 0x19, 0x19), + field_bg: Color32::from_rgb(0x0e, 0x0e, 0x0e), + pasteboard: Color32::from_rgb(0x11, 0x11, 0x11), + ..dark + }, + ThemeKind::Light => Tokens { + app_bg: Color32::from_rgb(0xb4, 0xb4, 0xb4), + header_bg: Color32::from_rgb(0xd6, 0xd6, 0xd6), + panel_bg: Color32::from_rgb(0xe6, 0xe6, 0xe6), + tab_text: Color32::from_rgb(0x5a, 0x5a, 0x5a), + tab_text_active: Color32::from_rgb(0x14, 0x14, 0x14), + text: Color32::from_rgb(0x22, 0x22, 0x22), + text_dim: Color32::from_rgb(0x5a, 0x5a, 0x5a), + text_faint: Color32::from_rgb(0x8c, 0x8c, 0x8c), + icon: Color32::from_rgb(0x3c, 0x3c, 0x3c), + icon_active: Color32::from_rgb(0x10, 0x10, 0x10), + hover: Color32::from_rgb(0xd0, 0xd0, 0xd0), + pressed: Color32::from_rgb(0xc0, 0xc0, 0xc0), + field_bg: Color32::from_rgb(0xfa, 0xfa, 0xfa), + field_border: Color32::from_rgb(0xaa, 0xaa, 0xaa), + separator: Color32::from_rgb(0xc8, 0xc8, 0xc8), + row: Color32::from_rgb(0xe6, 0xe6, 0xe6), + row_alt: Color32::from_rgb(0xde, 0xde, 0xde), + row_selected: Color32::from_rgb(0xaa, 0xc8, 0xf0), + tl_bg: Color32::from_rgb(0xd2, 0xd2, 0xd2), + tl_ruler_bg: Color32::from_rgb(0xe2, 0xe2, 0xe2), + tl_ruler_text: Color32::from_rgb(0x50, 0x50, 0x50), + pasteboard: Color32::from_rgb(0xa8, 0xa8, 0xa8), + ..dark + }, + } + } + + pub fn mono(size: f32) -> FontId { + FontId::new(size, FontFamily::Monospace) + } + pub fn ui(size: f32) -> FontId { + FontId::new(size, FontFamily::Proportional) + } + pub fn semibold(size: f32) -> FontId { + FontId::new(size, FontFamily::Name("semibold".into())) + } + pub fn medium(size: f32) -> FontId { + FontId::new(size, FontFamily::Name("medium".into())) + } + /// sRGB colour of an item/layer label. + pub fn label(l: effectcraft_color::Label) -> Color32 { + let [r, g, b] = l.rgb(); + Color32::from_rgb(r, g, b) + } +} + +static INTER_REGULAR: &[u8] = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); +static INTER_MEDIUM: &[u8] = include_bytes!("../../../assets/fonts/Inter-Medium.ttf"); +static INTER_SEMIBOLD: &[u8] = include_bytes!("../../../assets/fonts/Inter-SemiBold.ttf"); +static JETBRAINS_MONO: &[u8] = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"); + +/// Install fonts (Inter, Inter Medium/SemiBold, JetBrains Mono) and egui visuals. +pub fn install(ctx: &egui::Context, t: &Tokens) { + let mut fonts = FontDefinitions::default(); + fonts.font_data.insert("inter".into(), Arc::new(FontData::from_static(INTER_REGULAR))); + fonts.font_data.insert("inter-medium".into(), Arc::new(FontData::from_static(INTER_MEDIUM))); + fonts.font_data.insert("inter-semibold".into(), Arc::new(FontData::from_static(INTER_SEMIBOLD))); + fonts.font_data.insert("jbmono".into(), Arc::new(FontData::from_static(JETBRAINS_MONO))); + fonts.families.entry(FontFamily::Proportional).or_default().insert(0, "inter".into()); + fonts.families.entry(FontFamily::Monospace).or_default().insert(0, "jbmono".into()); + fonts.families.insert(FontFamily::Name("semibold".into()), vec!["inter-semibold".into(), "inter".into()]); + fonts.families.insert(FontFamily::Name("medium".into()), vec!["inter-medium".into(), "inter".into()]); + ctx.set_fonts(fonts); + apply_visuals(ctx, t); +} + +pub fn apply_visuals(ctx: &egui::Context, t: &Tokens) { + let mut v = if t.kind == ThemeKind::Light { Visuals::light() } else { Visuals::dark() }; + v.panel_fill = t.panel_bg; + v.window_fill = t.panel_bg; + v.extreme_bg_color = t.field_bg; + v.faint_bg_color = t.row_alt; + v.override_text_color = Some(t.text); + v.selection.bg_fill = t.accent; + v.selection.stroke = Stroke::new(1.0, Color32::WHITE); + v.hyperlink_color = t.accent; + v.window_stroke = Stroke::new(1.0, t.field_border); + v.window_corner_radius = egui::CornerRadius::same(8); + v.menu_corner_radius = egui::CornerRadius::same(6); + v.popup_shadow = egui::epaint::Shadow { offset: [0, 6], blur: 20, spread: 0, color: Color32::from_black_alpha(150) }; + v.window_shadow = egui::epaint::Shadow { offset: [0, 10], blur: 36, spread: 0, color: Color32::from_black_alpha(170) }; + for w in [&mut v.widgets.noninteractive, &mut v.widgets.inactive, &mut v.widgets.hovered, &mut v.widgets.active, &mut v.widgets.open] { + w.corner_radius = egui::CornerRadius::same(t.radius_sm as u8); + } + v.widgets.noninteractive.bg_fill = t.panel_bg; + v.widgets.noninteractive.weak_bg_fill = t.panel_bg; + v.widgets.noninteractive.bg_stroke = Stroke::new(1.0, t.separator); + v.widgets.noninteractive.fg_stroke = Stroke::new(1.0, t.text); + v.widgets.inactive.bg_fill = t.field_bg; + v.widgets.inactive.weak_bg_fill = Color32::from_rgb(0x2e, 0x2e, 0x2e); + v.widgets.inactive.bg_stroke = Stroke::new(1.0, t.field_border); + v.widgets.inactive.fg_stroke = Stroke::new(1.0, t.text); + v.widgets.hovered.bg_fill = t.hover; + v.widgets.hovered.weak_bg_fill = Color32::from_rgb(0x3a, 0x3a, 0x3a); + v.widgets.hovered.bg_stroke = Stroke::new(1.0, t.field_border); + v.widgets.hovered.fg_stroke = Stroke::new(1.0, t.tab_text_active); + v.widgets.active.bg_fill = t.pressed; + v.widgets.active.weak_bg_fill = t.pressed; + v.widgets.active.fg_stroke = Stroke::new(1.0, t.tab_text_active); + v.widgets.open.bg_fill = t.hover; + v.widgets.open.weak_bg_fill = t.hover; + ctx.set_visuals(v); + ctx.global_style_mut(|s| { + s.spacing.item_spacing = egui::vec2(6.0, 4.0); + s.spacing.button_padding = egui::vec2(8.0, 3.0); + s.spacing.interact_size.y = 22.0; + s.spacing.menu_margin = egui::Margin::same(5); + s.text_styles.insert(TextStyle::Body, FontId::new(12.0, FontFamily::Proportional)); + s.text_styles.insert(TextStyle::Button, FontId::new(12.0, FontFamily::Proportional)); + s.text_styles.insert(TextStyle::Small, FontId::new(11.0, FontFamily::Proportional)); + s.text_styles.insert(TextStyle::Heading, FontId::new(15.0, FontFamily::Name("semibold".into()))); + s.text_styles.insert(TextStyle::Monospace, FontId::new(12.0, FontFamily::Monospace)); + s.animation_time = 0.1; + }); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs new file mode 100644 index 00000000..2af57f21 --- /dev/null +++ b/crates/ui-egui/src/widgets.rs @@ -0,0 +1,216 @@ +//! Small custom widgets in the motion-graphics app visual language. + +use egui::{Align2, Color32, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; + +use crate::icons::{self, Icon}; +use crate::theme::Tokens; + +/// "Hot text": a blue number you drag horizontally to scrub, click to type. +/// Returns (response, Some(new value) when changed, drag finished). +pub fn hot_number_at( + ui: &mut Ui, + rect_min: egui::Pos2, + id: egui::Id, + value: f64, + speed: f64, + range: (f64, f64), + decimals: usize, + suffix: &str, + t: &Tokens, +) -> (Rect, Option, bool) { + let editing_id = id.with("editing"); + let editing: Option = ui.data(|d| d.get_temp(editing_id)); + let text = format!("{value:.decimals$}{suffix}"); + let galley = ui.painter().layout_no_wrap(text, Tokens::ui(12.0), t.hot_text); + let rect = Rect::from_min_size(rect_min, galley.size() + vec2(4.0, 4.0)); + if let Some(mut buf) = editing { + let er = Rect::from_min_size(rect_min - vec2(2.0, 1.0), vec2((galley.size().x + 24.0).max(54.0), 18.0)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(er)); + let r = child.add(egui::TextEdit::singleline(&mut buf).desired_width(er.width()).font(Tokens::ui(12.0)).margin(egui::Margin::symmetric(2, 1))); + let mut out = None; + if r.lost_focus() { + let txt = buf.trim().trim_end_matches(suffix).trim().replace(',', "."); + if let Ok(v) = txt.parse::() { + out = Some(v.clamp(range.0, range.1)); + } + ui.data_mut(|d| d.remove::(editing_id)); + } else { + ui.data_mut(|d| d.insert_temp(editing_id, buf)); + r.request_focus(); + } + return (er, out, out.is_some()); + } + let resp = ui.interact(rect, id, Sense::click_and_drag()); + let col = if resp.hovered() || resp.dragged() { t.accent_hover } else { t.hot_text }; + ui.painter().galley_with_override_text_color(rect.min + vec2(2.0, 2.0), galley, col); + if resp.hovered() || resp.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + let y = rect.max.y - 2.0; + ui.painter().line_segment( + [pos2(rect.min.x + 2.0, y), pos2(rect.max.x - 2.0, y)], + egui::Stroke::new(1.0, col.gamma_multiply(if resp.hovered() { 0.8 } else { 0.35 })), + ); + let mut out = None; + if resp.dragged() { + let dx = resp.drag_delta().x as f64; + let mult = ui.input(|i| { + if i.modifiers.shift { + 10.0 + } else if i.modifiers.command { + 0.1 + } else { + 1.0 + } + }); + let nv = (value + dx * speed * mult).clamp(range.0, range.1); + if (nv - value).abs() > f64::EPSILON { + out = Some(nv); + } + } + if resp.clicked() { + ui.data_mut(|d| d.insert_temp(editing_id, format!("{value:.decimals$}"))); + } + (rect, out, resp.drag_stopped()) +} + +/// A colour swatch; returns the response (click opens the picker in the caller). +pub fn swatch(ui: &mut Ui, rect: Rect, c: [f32; 4], id: egui::Id, t: &Tokens) -> Response { + let resp = ui.interact(rect, id, Sense::click()); + let col = Color32::from_rgb((c[0].clamp(0.0, 1.0) * 255.0) as u8, (c[1].clamp(0.0, 1.0) * 255.0) as u8, (c[2].clamp(0.0, 1.0) * 255.0) as u8); + ui.painter().rect_filled(rect, 2.0, col); + ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, if resp.hovered() { t.text } else { t.field_border }), StrokeKind::Inside); + resp +} + +/// A twirl-down triangle; returns clicked. +pub fn twirl(ui: &mut Ui, rect: Rect, open: bool, id: egui::Id, t: &Tokens) -> Response { + let resp = ui.interact(rect, id, Sense::click()); + let col = if resp.hovered() { t.tab_text_active } else { t.text_dim }; + icons::paint(ui.painter(), rect.shrink(rect.width() * 0.22), if open { Icon::ChevronDown } else { Icon::ChevronRight }, col); + resp +} + +/// A flat icon toggle inside a rect. +pub fn icon_toggle(ui: &mut Ui, rect: Rect, icon: Icon, on: bool, t: &Tokens, id: egui::Id, on_color: Option) -> Response { + let resp = ui.interact(rect, id, Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, 2.0, t.hover); + } + let col = if on { on_color.unwrap_or(t.icon) } else { t.text_faint.gamma_multiply(0.7) }; + if on || resp.hovered() { + icons::paint(ui.painter(), rect.shrink(rect.width() * 0.18), icon, if !on { t.text_faint } else { col }); + } + resp +} + +/// Icon button (toolbar style) with optional active state. +pub fn icon_button(ui: &mut Ui, rect: Rect, icon: Icon, active: bool, t: &Tokens, id: egui::Id) -> Response { + let resp = ui.interact(rect, id, Sense::click()); + if active { + ui.painter().rect_filled(rect, 4.0, t.accent); + } else if resp.hovered() { + ui.painter().rect_filled(rect, 4.0, t.hover); + } + let col = if active { + Color32::WHITE + } else if resp.hovered() { + t.icon_active + } else { + t.icon + }; + icons::paint(ui.painter(), rect.shrink(rect.width() * 0.22), icon, col); + resp +} + +/// Rounded search field with a magnifier icon. +pub fn search_field(ui: &mut Ui, rect: Rect, text: &mut String, hint: &str, t: &Tokens) -> Response { + let h = rect.height(); + ui.painter().rect_filled(rect, h / 2.0, t.field_bg); + ui.painter().rect_stroke(rect, h / 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + icons::paint(ui.painter(), Rect::from_center_size(pos2(rect.min.x + 12.0, rect.center().y), vec2(12.0, 12.0)), Icon::Search, t.text_dim); + let inner = Rect::from_min_max(pos2(rect.min.x + 22.0, rect.min.y + 1.0), pos2(rect.max.x - 8.0, rect.max.y - 1.0)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner)); + child.add( + egui::TextEdit::singleline(text) + .hint_text(hint) + .frame(egui::Frame::NONE) + .desired_width(inner.width()) + .font(Tokens::ui(12.0)) + .vertical_align(egui::Align::Center), + ) +} + +/// Dropdown-looking control ("Full ▾"). +pub fn dropdown(ui: &mut Ui, rect: Rect, text: &str, t: &Tokens, id: egui::Id) -> Response { + let resp = ui.interact(rect, id, Sense::click()); + ui.painter().rect_filled(rect, 3.0, if resp.hovered() { t.hover } else { t.field_bg }); + ui.painter().rect_stroke(rect, 3.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + ui.painter().text(pos2(rect.min.x + 7.0, rect.center().y), Align2::LEFT_CENTER, text, Tokens::ui(11.5), t.text); + icons::paint(ui.painter(), Rect::from_center_size(pos2(rect.max.x - 9.0, rect.center().y), vec2(8.0, 8.0)), Icon::ChevronDown, t.text_dim); + resp +} + +/// Text button with a subtle fill. +pub fn text_button(ui: &mut Ui, rect: Rect, text: &str, primary: bool, t: &Tokens, id: egui::Id) -> Response { + let resp = ui.interact(rect, id, Sense::click()); + let bg = if primary { + if resp.hovered() { t.accent_hover } else { t.accent } + } else if resp.hovered() { + t.pressed + } else { + Color32::from_rgb(0x33, 0x33, 0x33) + }; + ui.painter().rect_filled(rect, rect.height() / 2.0, bg); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, text, Tokens::medium(12.0), if primary { Color32::WHITE } else { t.text }); + resp +} + +/// Checkbox in the AE look (small square). +pub fn checkbox(ui: &mut Ui, rect: Rect, on: bool, t: &Tokens, id: egui::Id) -> Response { + let resp = ui.interact(rect, id, Sense::click()); + let b = Rect::from_center_size(rect.center(), vec2(12.0, 12.0)); + ui.painter().rect_filled(b, 2.0, if on { t.accent } else { t.field_bg }); + ui.painter().rect_stroke(b, 2.0, Stroke::new(1.0, if on { t.accent } else { t.field_border }), StrokeKind::Inside); + if on { + let p = |x: f32, y: f32| pos2(b.min.x + x * b.width(), b.min.y + y * b.height()); + ui.painter().line(vec![p(0.2, 0.52), p(0.42, 0.74), p(0.8, 0.28)], Stroke::new(1.6, Color32::WHITE)); + } + resp +} + +/// Show a popup menu anchored at `pos` with string options; returns the chosen index. +pub fn popup_menu(ui: &mut Ui, id: egui::Id, pos: egui::Pos2, options: &[String], current: Option) -> Option { + let mut chosen = None; + let open_id = id.with("open"); + let open: bool = ui.data(|d| d.get_temp(open_id).unwrap_or(false)); + if !open { + return None; + } + let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos).show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_min_width(160.0); + egui::ScrollArea::vertical().max_height(420.0).show(ui, |ui| { + for (i, o) in options.iter().enumerate() { + if o == "-" { + ui.separator(); + continue; + } + let sel = current == Some(i); + if ui.selectable_label(sel, o).clicked() { + chosen = Some(i); + } + } + }); + }); + }); + let clicked_outside = ui.input(|i| i.pointer.any_pressed()) && !area.response.contains_pointer() && !area.response.hovered(); + if chosen.is_some() || clicked_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + ui.data_mut(|d| d.insert_temp(open_id, false)); + } + chosen +} + +pub fn open_popup(ui: &Ui, id: egui::Id) { + ui.data_mut(|d| d.insert_temp(id.with("open"), true)); +}