Merge main into CMP-7/ANM-5/PRJ-8/PRJ-3 work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 23:43:41 -04:00
co-authored by Claude Opus 5.5
154 changed files with 30420 additions and 398 deletions
+127 -3
View File
@@ -34,11 +34,12 @@ pub enum PanelKind {
History,
Markers,
MaskInterpolation,
ScriptConsole,
EssentialGraphics,
}
impl PanelKind {
pub const ALL: [PanelKind; 25] = [
pub const ALL: [PanelKind; 26] = [
PanelKind::Project,
PanelKind::EffectControls,
PanelKind::Composition,
@@ -63,6 +64,7 @@ impl PanelKind {
PanelKind::History,
PanelKind::Markers,
PanelKind::MaskInterpolation,
PanelKind::ScriptConsole,
PanelKind::EssentialGraphics,
];
pub fn title(self) -> &'static str {
@@ -91,6 +93,7 @@ impl PanelKind {
PanelKind::History => "History",
PanelKind::Markers => "Markers",
PanelKind::MaskInterpolation => "Mask Interpolation",
PanelKind::ScriptConsole => "Script Console",
PanelKind::EssentialGraphics => "Essential Graphics",
}
}
@@ -175,7 +178,43 @@ 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 built-in workspaces: After Effects 2026's (Window ▸ Workspace), less Libraries (an Adobe
/// service). Learn shows the Home screen (community links instead of Adobe's tutorials);
/// Essential Graphics uses the Properties panel; Undocked Panels floats the panels over the
/// Composition panel.
pub const WORKSPACES: &[&str] = &[
"Default",
"Standard",
"Small Screen",
"Animation",
"Effects",
"Motion Tracking",
"Paint",
"Text",
"Minimal",
"All Panels",
"Review",
"Learn",
"Essential Graphics",
"Color",
"Undocked Panels",
];
/// The floating panels a workspace starts with (Undocked Panels), in points for a window of
/// about 1680×1020 (they are kept inside the window when drawn).
pub fn workspace_floating(name: &str) -> Vec<Floating> {
use PanelKind::*;
let f = |panels: &[PanelKind], rect: [f32; 4]| Floating { panels: panels.to_vec(), active: 0, rect };
match name {
"Undocked Panels" => vec![
f(&[Project, EffectControls], [24.0, 110.0, 320.0, 420.0]),
f(&[Preview, Info, Audio], [1330.0, 110.0, 320.0, 300.0]),
f(&[EffectsPresets, Properties, Character, Paragraph], [1330.0, 430.0, 320.0, 360.0]),
f(&[Timeline, RenderQueue], [24.0, 640.0, 1280.0, 340.0]),
],
_ => vec![],
}
}
/// The default layout of a named workspace.
pub fn workspace(name: &str) -> DockNode {
@@ -229,6 +268,40 @@ pub fn workspace(name: &str) -> DockNode {
tabs(&[Timeline], 0),
),
"Minimal" => vsplit(Ratio(0.6), tabs(&[Composition], 0), tabs(&[Timeline], 0)),
// Review: a large viewer with the markers and the project beside it.
"Review" => vsplit(
Ratio(0.66),
hsplit(FixedA(280.0), tabs(&[Project, Markers], 0), hsplit(FixedB(260.0), tabs(&[Composition, Layer], 0), right(&[Preview, Info], &[Audio]))),
tabs(&[Timeline, RenderQueue], 0),
),
// Essential Graphics: the Properties panel (After Effects' successor to the Essential
// Graphics panel) full height on the right, type panels beside the viewer.
"Essential Graphics" => hsplit(
FixedB(320.0),
vsplit(
Ratio(0.58),
hsplit(
FixedA(280.0),
tabs(&[Project, EffectControls], 0),
hsplit(FixedB(260.0), tabs(&[Composition, Layer], 0), right(&[Character, Paragraph], &[Align, Preview])),
),
tabs(&[Timeline], 0),
),
stack(&[(Properties, true, None), (EffectsPresets, false, None)]),
),
// Color: wide Effect Controls for grading effects, Info for colour readouts.
"Color" => vsplit(
Ratio(0.6),
hsplit(
FixedA(360.0),
tabs(&[EffectControls, Project], 0),
hsplit(FixedB(300.0), tabs(&[Composition, Layer], 0), right(&[Info, Preview], &[EffectsPresets])),
),
tabs(&[Timeline], 0),
),
// Undocked Panels: the Composition panel docked, the others floating
// ([`workspace_floating`]).
"Undocked Panels" => tabs(&[Composition, Layer, Flowchart], 0),
"Small Screen" => vsplit(
Ratio(0.55),
hsplit(
@@ -817,8 +890,59 @@ mod tests {
fn workspaces_contain_core_panels() {
for w in WORKSPACES {
let d = workspace(w);
assert!(d.contains(PanelKind::Timeline), "{w}");
let floating: Vec<PanelKind> = workspace_floating(w).into_iter().flat_map(|f| f.panels).collect();
assert!(d.contains(PanelKind::Timeline) || floating.contains(&PanelKind::Timeline), "{w}");
assert!(d.contains(PanelKind::Composition) || d.contains(PanelKind::Layer), "{w}");
// A panel is in one place only.
let mut all = vec![];
d.panels(&mut all);
all.extend(floating);
let n = all.len();
all.sort_by_key(|p| p.id());
all.dedup();
assert_eq!(all.len(), n, "{w} has a panel twice");
}
}
#[test]
fn after_effects_workspaces_exist() {
// Window ▸ Workspace in After Effects 2026, less Libraries (an Adobe service).
for w in [
"Default",
"Review",
"Learn",
"Small Screen",
"Standard",
"All Panels",
"Animation",
"Essential Graphics",
"Color",
"Effects",
"Minimal",
"Motion Tracking",
"Paint",
"Text",
"Undocked Panels",
] {
assert!(WORKSPACES.contains(&w), "{w}");
}
assert!(!WORKSPACES.contains(&"Libraries"));
// Layouts differ from Default (except Learn, which is Default plus the Home screen).
let def = workspace("Default");
for w in WORKSPACES.iter().filter(|w| !matches!(**w, "Default" | "Learn")) {
assert_ne!(workspace(w), def, "{w} falls back to Default");
}
assert!(workspace("Essential Graphics").contains(PanelKind::Properties));
assert!(workspace("Color").contains(PanelKind::EffectControls));
assert!(!workspace_floating("Undocked Panels").is_empty());
// Every built-in workspace is in Window ▸ Workspace.
let menu: Vec<String> = effectcraft_engine::menus::entries()
.into_iter()
.filter(|(_, e)| e.command == "window.workspace")
.filter_map(|(_, e)| e.params.get("name").and_then(|v| v.as_str()).map(str::to_string))
.collect();
for w in WORKSPACES {
assert!(menu.iter().any(|m| m == w), "{w} missing from Window > Workspace");
}
}
+93 -15
View File
@@ -7,6 +7,11 @@
//! wasm32 has no threads: jobs wait in the same priority queue and [`Frames::pump`] renders them
//! on the UI thread between egui frames, within a time budget.
//!
//! With the disk cache on (Settings ▸ Media & Disk Cache), every CPU-rendered frame is also
//! written to disk under a content key (the comp's content hash, frame, scale, view and render
//! options), and a job first looks there: frames survive restarts and project reopenings. The
//! timeline shows disk-only frames as a blue cache bar.
//!
//! With Mercury GPU Acceleration (a [`Gpu`] on egui-wgpu's device and the project's renderer set
//! to the GPU) frames stay on the GPU: the compositor writes an RGBA8 texture that the viewer
//! registers with egui-wgpu and draws directly; pixels are read back only when something needs
@@ -16,6 +21,7 @@ use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use effectcraft_engine::project::{ItemId, Project};
use effectcraft_engine::render::disk_cache::{self, DiskCache};
use effectcraft_engine::render::{ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
use effectcraft_engine::time::Tick;
use effectcraft_gpu::{DisplayFrame, Gpu};
@@ -122,6 +128,37 @@ pub struct RenderSource {
/// Show Channel / exposure / region-of-interest drawing read the CPU frame texture, so GPU
/// frames are read back (the compositing still runs on the GPU).
pub gpu_display: bool,
/// The persistent disk cache, when enabled.
pub disk: Option<Arc<DiskCache>>,
}
/// Content keys of (project revision, comp), computed once per revision.
type ContentKeys = Arc<Mutex<HashMap<(u64, u64), u128>>>;
fn content_key(keys: &ContentKeys, project: &Project, revision: u64, comp: u64) -> u128 {
if let Some(k) = keys.lock().ok().and_then(|m| m.get(&(revision, comp)).copied()) {
return k;
}
let k = disk_cache::comp_content_key(project, ItemId(comp));
if let Ok(mut m) = keys.lock() {
if m.len() > 256 {
m.clear();
}
m.insert((revision, comp), k);
}
k
}
fn opts_hash(o: &RenderOpts) -> u64 {
let mut h = disk_cache::Hash128::default();
h.write(format!("{o:?}").as_bytes());
h.finish() as u64
}
/// Disk key of a viewer frame (render options included: region of interest, draft…).
fn frame_disk_key(keys: &ContentKeys, project: &Project, key: &FrameKey, opts_hash: u64) -> u128 {
let content = content_key(keys, project, key.revision, key.comp);
disk_cache::frame_key(content, key.frame, key.scale, key.view ^ opts_hash)
}
pub struct Frames {
@@ -135,6 +172,7 @@ pub struct Frames {
ctx: Option<egui::Context>,
/// Render time of the last viewer (urgent) frame in ms, for the Info panel / perf readout.
pub last_ms: Arc<Mutex<f64>>,
content_keys: ContentKeys,
}
impl Default for Frames {
@@ -149,6 +187,7 @@ impl Default for Frames {
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)),
content_keys: Arc::default(),
}
}
}
@@ -195,6 +234,21 @@ impl Frames {
v
}
/// Frames of (revision, comp, scale) in the disk cache but not in RAM — the blue cache bar.
/// `opts` are the viewer's render options (part of the disk key).
pub fn disk_frames(&self, src: &RenderSource, revision: u64, comp: u64, scale: u32, view: u64, frames: i64, opts: &RenderOpts) -> Vec<i64> {
let Some(dc) = &src.disk else { return vec![] };
let ram: HashSet<i64> = self.cached_frames(revision, comp, scale).into_iter().collect();
let oh = opts_hash(opts);
(0..frames.clamp(0, 100_000))
.filter(|f| !ram.contains(f))
.filter(|f| {
let key = FrameKey { revision, comp, frame: *f, scale, view };
dc.contains(disk_cache::Kind::Frame, frame_disk_key(&self.content_keys, &src.project, &key, oh))
})
.collect()
}
/// Change the RAM preview cache budget (Settings ▸ Memory & CPU), evicting the oldest
/// frames when it shrinks.
pub fn set_budget(&self, bytes: usize) {
@@ -278,7 +332,14 @@ impl Frames {
}
fn worker(&self) -> Worker {
Worker { queue: self.queue.clone(), cache: self.cache.clone(), inflight: self.inflight.clone(), ctx: self.ctx.clone(), last: self.last_ms.clone() }
Worker {
queue: self.queue.clone(),
cache: self.cache.clone(),
inflight: self.inflight.clone(),
ctx: self.ctx.clone(),
last: self.last_ms.clone(),
content_keys: self.content_keys.clone(),
}
}
/// Render queued frames on this thread, most important first, until the queue is empty or
@@ -306,12 +367,13 @@ struct Worker {
inflight: Arc<Mutex<HashSet<FrameKey>>>,
ctx: Option<egui::Context>,
last: Arc<Mutex<f64>>,
content_keys: ContentKeys,
}
impl Worker {
/// Render the queued job that matters most right now. `false` when the queue was empty.
fn run_next(&self) -> bool {
let Worker { queue, cache, inflight, ctx, last } = self;
let Worker { queue, cache, inflight, ctx, last, content_keys } = self;
let job = {
let Ok(mut q) = queue.lock() else { return false };
// Urgent first (newest), then prefetch in request order.
@@ -325,19 +387,18 @@ impl Worker {
job
};
let t0 = web_time::Instant::now();
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
r.expr = job.src.expr.as_deref();
r.cache = Some(&job.src.layer_cache);
r.accel = job.src.gpu.as_ref().map(|g| g as &dyn effectcraft_engine::render::Accelerator);
// The GPU leaves the frame in a texture for the viewer; otherwise (Software Only, no
// adapter, or a frame the GPU cannot finish here) the CPU renders it.
let gpu_frame = match (&job.src.gpu, r.active_accel()) {
(Some(g), Some(_)) if job.src.gpu_display => g.render_display(&r, job.comp, job.t),
_ => None,
};
let ci = match gpu_frame {
Some(f) => FrameImage::Gpu(Arc::new(f)),
None => FrameImage::Cpu(Arc::new(to_color_image(&r.comp_frame(job.comp, job.t)))),
let disk = job.src.disk.as_ref().map(|dc| (dc.clone(), frame_disk_key(content_keys, &job.src.project, &job.key, opts_hash(&job.opts))));
let from_disk = disk.as_ref().and_then(|(dc, k)| dc.get_frame(*k));
let ci = match from_disk {
Some(f) => FrameImage::Cpu(Arc::new(egui::ColorImage::from_rgba_premultiplied([f.width as usize, f.height as usize], &f.rgba))),
None => {
let ci = self.render_job(&job);
if let (Some((dc, k)), FrameImage::Cpu(img)) = (&disk, &ci) {
let rgba: Vec<u8> = img.pixels.iter().flat_map(|c| c.to_array()).collect();
dc.put_frame(*k, img.size[0] as u32, img.size[1] as u32, &rgba);
}
ci
}
};
if job.urgent
&& let Ok(mut l) = last.lock()
@@ -361,6 +422,23 @@ impl Worker {
}
true
}
fn render_job(&self, job: &Job) -> FrameImage {
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
r.expr = job.src.expr.as_deref();
r.cache = Some(&job.src.layer_cache);
r.accel = job.src.gpu.as_ref().map(|g| g as &dyn effectcraft_engine::render::Accelerator);
// The GPU leaves the frame in a texture for the viewer; otherwise (Software Only, no
// adapter, or a frame the GPU cannot finish here) the CPU renders it.
let gpu_frame = match (&job.src.gpu, r.active_accel()) {
(Some(g), Some(_)) if job.src.gpu_display => g.render_display(&r, job.comp, job.t),
_ => None,
};
match gpu_frame {
Some(f) => FrameImage::Gpu(Arc::new(f)),
None => FrameImage::Cpu(Arc::new(to_color_image(&r.comp_frame(job.comp, job.t)))),
}
}
}
struct Job {
+10
View File
@@ -33,6 +33,7 @@ pub enum Icon {
Clone,
Eraser,
RotoBrush,
RefineEdge,
Puppet,
// switches & timeline
Eye,
@@ -282,6 +283,15 @@ pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {
pen.ellipse(6.0, 10.0, 3.6, 3.6);
pen.dot(6.0, 10.0, 1.0);
}
RefineEdge => {
// A brush over a soft (dashed) edge.
pen.line(&[(13.5, 2.5), (9.0, 7.0)]);
pen.ellipse(7.0, 9.0, 2.6, 2.6);
pen.line(&[(2.0, 14.0), (3.5, 12.5)]);
pen.line(&[(5.0, 14.0), (6.5, 12.5)]);
pen.line(&[(8.0, 14.0), (9.5, 12.5)]);
pen.line(&[(11.0, 14.0), (12.5, 12.5)]);
}
Puppet => {
pen.circle(8.0, 3.6, 1.6);
pen.line(&[(8.0, 5.2), (8.0, 10.0)]);
+36 -7
View File
@@ -14,6 +14,7 @@ pub mod frames;
pub mod header;
pub mod icons;
pub mod menus;
pub mod native_menu;
pub mod panels;
pub mod state;
pub mod theme;
@@ -86,6 +87,11 @@ pub struct Hooks {
pub pick_folder: Option<Box<dyn Fn() -> Option<String>>>,
/// Save dialog for other file kinds: (default name, extension).
pub pick_save_file: Option<Box<dyn Fn(&str, &str) -> Option<String>>>,
/// The system clipboard's text (native menu Edit ▸ Paste into a text field).
pub clipboard_text: Option<Box<dyn Fn() -> Option<String>>>,
/// Application actions the OS performs (`app.hide`, `app.hideOthers`, `app.showAll` on
/// macOS). Returns false when the host doesn't handle the id.
pub app_action: Option<Box<dyn Fn(&str) -> bool>>,
}
#[derive(Default)]
@@ -158,6 +164,10 @@ pub struct EffectcraftApp {
/// Docked groups laid out last frame: (active panel, group rect) — `~` maximizes the one
/// under the pointer.
pub(crate) dock_rects: Vec<(PanelKind, egui::Rect)>,
/// Home screen: recent-project thumbnail textures by path (None = no thumbnail).
pub(crate) home_thumbs: std::collections::HashMap<String, Option<egui::TextureHandle>>,
/// The (project path, saved revision) whose thumbnail was stored last.
pub(crate) home_thumb_saved: Option<(String, u64)>,
}
impl EffectcraftApp {
@@ -202,6 +212,8 @@ impl EffectcraftApp {
applied_prefs: None,
recovery: None,
dock_rects: vec![],
home_thumbs: Default::default(),
home_thumb_saved: None,
}
.with_ui_commands()
}
@@ -267,8 +279,12 @@ impl EffectcraftApp {
pub fn set_workspace(&mut self, name: &str) {
self.ui.workspace = name.to_string();
self.ui.dock = self.ui.saved_workspaces.get(name).cloned().unwrap_or_else(|| dock::workspace(name));
self.ui.floating = self.ui.saved_floating.get(name).cloned().unwrap_or_default();
self.ui.floating = self.ui.saved_floating.get(name).cloned().unwrap_or_else(|| dock::workspace_floating(name));
self.ui.maximized = None;
// Learn: the Home screen (community links) in the Composition panel.
if name == "Learn" {
self.ui.start_screen = true;
}
}
/// Built-in workspaces followed by the saved ones (Window ▸ Workspace ▸ Save as New Workspace).
@@ -308,6 +324,7 @@ impl EffectcraftApp {
layer_cache: self.session.layer_cache.clone(),
gpu: self.gpu.clone(),
gpu_display: false,
disk: self.session.disk_cache.clone(),
}
}
@@ -405,13 +422,11 @@ impl EffectcraftApp {
self.request_frame_with(comp, frame, scale, true);
}
fn request_frame_with(&self, comp: ItemId, frame: i64, scale: f64, urgent: bool) {
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);
/// Render options of viewer frames of `comp` at `scale`.
pub fn frame_opts(&self, comp: ItemId, scale: f64) -> RenderOpts {
let (draft, _) = self.session.state.viewer.fast_previews.render(self.ui.viewer.interacting);
let roi = self.session.state.region_of_interest.filter(|_| self.session.active_comp_id() == Some(comp));
let opts = RenderOpts {
RenderOpts {
scale,
motion_blur: true,
guides: true,
@@ -420,7 +435,14 @@ impl EffectcraftApp {
roi,
backend: effectcraft_engine::render::Backend::Auto,
proxy: Default::default(),
};
}
}
fn request_frame_with(&self, comp: ItemId, frame: i64, scale: f64, urgent: bool) {
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 = self.frame_opts(comp, scale);
if urgent {
self.frames.request_urgent(&self.render_source(), key, comp, t, opts);
} else {
@@ -726,6 +748,12 @@ impl EffectcraftApp {
// Warp Stabilizer: finish analyses and start queued (re-)analyses in the background.
if self.session.warp_job.is_some() || !self.session.warp_pending.is_empty() {
self.session.poll_warp(true);
self.session.poll_roto(true);
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
// 3D Camera Tracker: likewise (tracking, then solving).
if self.session.camera_job.is_some() || !self.session.camera_pending.is_empty() {
self.session.poll_camera(true);
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
self.apply_prefs(&ctx);
@@ -757,6 +785,7 @@ impl EffectcraftApp {
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::precomp::mini_flowchart(self, &ctx);
panels::home::capture_thumbnail(self);
panels::dialogs::show(self, &ctx);
self.draw_toast(ui, full);
}
+112 -22
View File
@@ -59,6 +59,21 @@ pub const UI_COMMANDS: &[UiCommand] = &[
uic!("timeline.reveal.feather", "Reveal Mask Feather", [], Some("F")),
uic!("timeline.reveal.levels", "Reveal Audio Levels (press twice: Waveform)", [], Some("L")),
uic!("timeline.reveal.waveform", "Reveal Audio Waveform", [], None),
uic!("timeline.revealAdd.position", "Add Position to Revealed Properties", [], Some("Shift+P")),
uic!("timeline.revealAdd.scale", "Add Scale to Revealed Properties", [], Some("Shift+S")),
uic!("timeline.revealAdd.rotation", "Add Rotation to Revealed Properties", [], Some("Shift+R")),
uic!("timeline.revealAdd.opacity", "Add Opacity to Revealed Properties", [], Some("Shift+T")),
uic!("timeline.revealAdd.anchor", "Add Anchor Point to Revealed Properties", [], Some("Shift+A")),
uic!("timeline.revealAdd.effects", "Add Effects to Revealed Properties", [], Some("Shift+E")),
uic!("timeline.revealAdd.masks", "Add Masks to Revealed Properties", [], Some("Shift+M")),
uic!("timeline.revealAdd.feather", "Add Mask Feather to Revealed Properties", [], Some("Shift+F")),
uic!("timeline.revealAdd.levels", "Add Audio Levels to Revealed Properties", [], Some("Shift+L")),
uic!("timeline.revealAdd.animated", "Add Animated Properties to Revealed Properties", [], Some("Shift+U")),
uic!("timeline.column", "Show/Hide Timeline Column", [], None),
uic!("timeline.sourceName", "Source Name / Layer Name", [], None),
uic!("timeline.search", "Search Timeline", [], None),
uic!("flowchart.options", "Flowchart Options", [], None),
uic!("flowchart.graph", "Flowchart Graph", [], None),
uic!("timeline.collapseAll", "Collapse All", [], Some("Cmd+`")),
uic!("tool.selection", "Selection Tool", [], Some("V")),
uic!("tool.hand", "Hand Tool", [], Some("H")),
@@ -72,7 +87,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[
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.rotoBrush", "Roto Brush & Refine Edge Tools", [], Some("Alt+W")),
uic!("tool.puppet", "Puppet Tools", [], Some("Cmd+P")),
uic!("app.newComp", "New Composition...", [], None),
uic!("app.compSettings", "Composition Settings...", [], None),
@@ -89,26 +104,42 @@ pub fn panel_command_id(p: PanelKind) -> String {
format!("window.panel.{}", p.id())
}
fn reveal(app: &mut EffectcraftApp, kind: &str, now: f64) {
/// The reveal shortcuts (P, S, R, T, A, E, M, F, L…). `add` (Shift+key) adds the property to
/// (or removes it from) those already revealed instead of replacing them.
pub fn reveal(app: &mut EffectcraftApp, kind: &str, now: f64, add: bool) {
// AE's double-press shortcuts: L then L again quickly reveals the Waveform (LL).
let kind = match app.last_reveal.take() {
Some((k, t)) if k == "levels" && kind == "levels" && now - t < 0.6 => "waveform",
_ => kind,
};
app.last_reveal = Some((kind.to_string(), now));
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();
let tl = &mut app.ui.timeline;
let present = tl.reveal.iter().any(|k| k == kind);
let sel: Vec<u64> = if app.session.state.selected_layers.is_empty() {
app.session.active_comp().map(|c| c.layers.iter().map(|l| l.id.0).collect()).unwrap_or_default()
} else {
app.session.state.selected_layers.iter().map(|l| l.0).collect()
};
if add {
if present {
tl.reveal.retain(|k| k != kind);
if tl.reveal.is_empty() {
tl.open_layers.clear();
}
} else {
tl.reveal.retain(|k| k != "props" || !tl.reveal_props.is_empty());
tl.reveal.push(kind.to_string());
tl.open_layers.extend(sel);
}
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();
if present && tl.reveal.len() == 1 {
tl.reveal.clear();
tl.open_layers.clear();
return;
}
tl.reveal = vec![kind.to_string()];
tl.open_layers = sel.into_iter().collect();
}
fn no_params(p: &Value) -> bool {
@@ -139,6 +170,7 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
"pen" => Some(9),
"type" => Some(10),
"brush" => Some(11),
"rotoBrush" => Some(14),
"puppet" => Some(15),
_ => None,
};
@@ -166,9 +198,30 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
if k == "animated" {
return run_engine(app, ctx, "anim.reveal", json!({"kind": "keyframes"}));
}
reveal(app, k, now);
reveal(app, k, now, false);
return Ok(Value::Null);
}
if let Some(k) = id.strip_prefix("timeline.revealAdd.") {
reveal(app, k, now, true);
return Ok(json!({"revealed": app.ui.timeline.reveal}));
}
// U reveals keyframed properties; UU (pressed twice quickly) all modified properties; U
// again later hides them.
if id == "anim.reveal" && params.get("kind").and_then(Value::as_str) == Some("keyframes") {
let last = app.last_reveal.take();
app.last_reveal = Some(("keyframes".into(), now));
match last {
Some((k, t)) if k == "keyframes" && now - t < 0.6 => {
return run_engine(app, ctx, "anim.reveal", json!({"kind": "modified"}));
}
Some((k, _)) if k == "keyframes" && app.ui.timeline.reveal == ["props"] => {
app.ui.timeline.reveal.clear();
app.ui.timeline.open_layers.clear();
return Ok(json!({"revealed": 0}));
}
_ => {}
}
}
// Docking: {panel, anchor, zone: center|left|right|top|bottom}, {panel, rect?}, {panel?}.
if let Some(op) = id.strip_prefix("window.").filter(|o| matches!(*o, "maximizePanel" | "dockPanel" | "floatPanel" | "closePanel")) {
let panel_of = |k: &str| params.get(k).and_then(Value::as_str).map(|s| PanelKind::from_name(s).ok_or(format!("unknown panel `{s}`")));
@@ -268,6 +321,24 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
return Ok(Value::Null);
}
"timeline.zoomFit" => app.ui.timeline.pps = None,
"timeline.column" => {
let col = params.get("column").and_then(Value::as_str).ok_or("timeline.column: need `column`")?;
let on = params.get("visible").and_then(Value::as_bool).unwrap_or(!crate::panels::timeline::column_visible(&app.ui.timeline, col));
crate::panels::timeline::set_column(&mut app.ui.timeline, col, on)?;
let shown: Vec<&str> =
crate::panels::timeline::COLUMNS.iter().map(|c| c.0).filter(|c| crate::panels::timeline::column_visible(&app.ui.timeline, c)).collect();
return Ok(json!({"columns": shown}));
}
"timeline.sourceName" => {
let tl = &mut app.ui.timeline;
tl.source_name = params.get("value").and_then(Value::as_bool).unwrap_or(!tl.source_name);
return Ok(json!({"sourceName": tl.source_name}));
}
"flowchart.options" | "flowchart.graph" => return crate::panels::flowchart::command(app, id, &params),
"timeline.search" => {
app.ui.timeline.search = params.get("query").and_then(Value::as_str).unwrap_or_default().to_string();
app.show_panel(PanelKind::Timeline);
}
"timeline.graphEditor" => app.ui.timeline.graph_editor = !app.ui.timeline.graph_editor,
"timeline.switchesModes" => app.ui.timeline.show_modes = !app.ui.timeline.show_modes,
"timeline.collapseAll" => {
@@ -399,8 +470,16 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
);
Value::Null
}
"app.hide" => {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));
"app.hide" | "app.hideOthers" | "app.showAll" => {
// The desktop app asks macOS (NSApplication hide / hideOtherApplications /
// unhideAllApplications); elsewhere Hide minimizes and the others don't apply.
if app.hooks.app_action.as_ref().is_some_and(|f| f(id)) {
return Ok(Value::Null);
}
match id {
"app.hide" => ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true)),
_ => return Err(format!("`{id}` is only available on macOS")),
}
Value::Null
}
"app.quit" => {
@@ -637,6 +716,13 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
Value::Null
}
"comp.flowchart" => {
// Chart the active comp; Layer ▸ Reveal ▸ Reveal Layer in Project Flowchart shows
// layers and selects the layer's node.
app.ui.flowchart.root = app.session.active_comp_id().map(|c| c.0);
if let (Some(c), Some(l)) = (app.session.active_comp_id(), app.session.state.selected_layers.first()) {
app.ui.flowchart.layers = true;
app.ui.flowchart.selected = Some(format!("layer:{}:{}", c.0, l.0));
}
app.show_panel(PanelKind::Flowchart);
Value::Null
}
@@ -697,7 +783,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
"file.exportLottie" => ("path", Ask::Save("Animation.json")),
"file.importLottie" => ("path", Ask::Open(&["json", "lottie"])),
"render.saveCurrentPreview" => ("path", Ask::Save("Preview.mp4")),
"file.runScript" => ("path", Ask::Open(&["jsonl", "json", "txt"])),
"file.runScript" => ("path", Ask::Open(&["jsx", "js", "jsonl", "json", "txt"])),
"file.replaceFootage" => ("path", Ask::Import),
"file.collectFiles" => ("folder", Ask::Save("Collected Files")),
"essential.exportTemplate" => ("path", Ask::Save("Template.ectemplate")),
@@ -719,7 +805,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `paths`)".into())) };
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", "gltf", "glb", "obj", "json", "csv", "tsv",
"ogg", "opus", "svg", "psd", "psb", "gltf", "glb", "obj", "json", "csv", "tsv",
]);
match (paths.is_empty(), key) {
(true, _) => None,
@@ -742,6 +828,10 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
};
let Some(v) = picked else { return Some(Ok(Value::Null)) };
p.insert(key.to_string(), v);
// Photoshop files ask how to import them first.
if id == "file.import" && crate::panels::dialogs::open_form(app, id, &Value::Object(p.clone())) {
return Some(Ok(json!({"dialog": id})));
}
// Save (untitled) becomes Save As.
let id = if id == "file.save" { "file.saveAs" } else { id };
let r = app.session.execute(id, Value::Object(p)).map_err(|e| e.to_string());
@@ -771,7 +861,7 @@ pub fn menus() -> Vec<&'static str> {
effectcraft_engine::menus::top_level()
}
fn entry_label(app: &EffectcraftApp, e: &MenuEntry) -> String {
pub(crate) fn entry_label(app: &EffectcraftApp, e: &MenuEntry) -> String {
match e.command.as_str() {
"edit.undo" => app.session.history.undo.last().map(|u| format!("Undo {}", u.0)).unwrap_or_else(|| "Can't Undo".into()),
"edit.redo" => app.session.history.redo.last().map(|u| format!("Redo {}", u.0)).unwrap_or_else(|| "Can't Redo".into()),
@@ -780,12 +870,12 @@ fn entry_label(app: &EffectcraftApp, e: &MenuEntry) -> String {
}
/// The entry's shortcut in the active keyboard shortcut preset.
fn entry_shortcut(app: &EffectcraftApp, e: &MenuEntry) -> Option<String> {
pub(crate) fn entry_shortcut(app: &EffectcraftApp, e: &MenuEntry) -> Option<String> {
app.session.shortcuts().shortcut_of(&e.command, &e.params).map(str::to_string)
}
/// Check-mark state of frontend toggles (engine state is answered by the engine).
fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option<bool> {
pub(crate) fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option<bool> {
let v = &app.ui.viewer;
let pstr = |k: &str| e.params.get(k).and_then(Value::as_str);
match e.command.as_str() {
@@ -817,7 +907,7 @@ fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option<bool> {
}
}
fn entry_enabled(app: &EffectcraftApp, e: &MenuEntry) -> bool {
pub(crate) fn entry_enabled(app: &EffectcraftApp, e: &MenuEntry) -> bool {
if e.command == "window.panel" {
return true;
}
+459
View File
@@ -0,0 +1,459 @@
//! The native (macOS) menu bar as a plain, serializable spec. The desktop app turns it into an
//! `NSMenu` with `muda` (`apps/effectcraft/src/native_menu.rs`); everything that decides *what*
//! the menu contains lives here, so it is tested without creating real menus and builds for the
//! web (where the in-window menu bar is used).
//!
//! The spec mirrors the engine's After Effects menu tree ([`effectcraft_engine::menus`]):
//! submenus, separators, labels (Undo/Redo and label names are live), check marks, enabled
//! state, and the active shortcut preset's keys as accelerators. File ▸ Open Recent lists the
//! recent projects. The application menu's Hide / Hide Others / Show All are macOS'
//! predefined items, and a Services submenu is added as on every Mac app.
//!
//! Item ids are positional (`m.3.0.2`), stable while the menu's structure stays the same; the
//! app rebuilds the native menu when [`NativeMenu::structure`] changes and otherwise only pushes
//! label / enabled / checked updates, and only when [`state_key`] changes.
use std::hash::{Hash, Hasher};
use serde::Serialize;
use serde_json::{Value, json};
use crate::EffectcraftApp;
use effectcraft_engine::menus::{MenuNode, menu_bar};
/// What macOS performs itself (no command dispatch).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Role {
Services,
Hide,
HideOthers,
ShowAll,
}
/// One node of the native menu.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum NativeNode {
Item(NativeItem),
Separator,
Submenu {
label: String,
children: Vec<NativeNode>,
},
/// A predefined macOS item; `command` is the engine entry it stands for (empty for Services).
Predefined {
role: Role,
label: String,
command: String,
},
}
/// A clickable item: activating it runs `command` with `params`, exactly like the in-window bar.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct NativeItem {
pub id: String,
pub label: String,
pub command: String,
#[serde(skip_serializing_if = "Value::is_null")]
pub params: Value,
/// The shortcut in EffectCraft notation (`Cmd+Shift+S`).
pub shortcut: Option<String>,
/// The menu key equivalent in `muda` accelerator notation, when the shortcut can be one (see
/// [`accelerator`]).
pub accelerator: Option<String>,
pub enabled: bool,
pub checked: Option<bool>,
}
/// The whole menu bar: top-level menus in order (the application menu first).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct NativeMenu {
pub menus: Vec<NativeNode>,
}
impl NativeMenu {
/// Every clickable item, depth first.
pub fn items(&self) -> Vec<&NativeItem> {
fn rec<'a>(n: &'a [NativeNode], out: &mut Vec<&'a NativeItem>) {
for x in n {
match x {
NativeNode::Item(i) => out.push(i),
NativeNode::Submenu { children, .. } => rec(children, out),
_ => {}
}
}
}
let mut out = vec![];
rec(&self.menus, &mut out);
out
}
pub fn find(&self, id: &str) -> Option<&NativeItem> {
self.items().into_iter().find(|i| i.id == id)
}
/// Fingerprint of everything that needs a rebuild when it changes (tree shape, commands,
/// accelerators, submenu labels); labels, enabled and check state are updated in place.
pub fn structure(&self) -> u64 {
fn rec(n: &[NativeNode], h: &mut std::collections::hash_map::DefaultHasher) {
for x in n {
match x {
NativeNode::Item(i) => {
0u8.hash(h);
i.id.hash(h);
i.command.hash(h);
i.params.to_string().hash(h);
i.accelerator.hash(h);
}
NativeNode::Separator => 1u8.hash(h),
NativeNode::Submenu { label, children } => {
2u8.hash(h);
label.hash(h);
rec(children, h);
3u8.hash(h);
}
NativeNode::Predefined { role, .. } => {
4u8.hash(h);
role.hash(h);
}
}
}
}
let mut h = std::collections::hash_map::DefaultHasher::new();
rec(&self.menus, &mut h);
h.finish()
}
}
/// Build the native menu spec for the app's current state.
pub fn build(app: &EffectcraftApp) -> NativeMenu {
fn rec(app: &EffectcraftApp, nodes: &[MenuNode], path: &str, out: &mut Vec<NativeNode>) {
let mut services_added = false;
for (i, n) in nodes.iter().enumerate() {
let id = format!("{path}.{i}");
match n {
MenuNode::Separator => out.push(NativeNode::Separator),
MenuNode::Submenu { label, children } => {
let mut kids = vec![];
if label == "Open Recent" {
for (k, p) in app.session.prefs.recent_projects.iter().enumerate() {
let name = std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(p.clone());
kids.push(NativeNode::Item(NativeItem {
id: format!("{id}.r{k}"),
label: name,
command: "file.openRecent".into(),
params: json!({"index": k}),
shortcut: None,
accelerator: None,
enabled: true,
checked: None,
}));
}
if !kids.is_empty() {
kids.push(NativeNode::Separator);
}
}
rec(app, children, &id, &mut kids);
out.push(NativeNode::Submenu { label: label.clone(), children: kids });
}
MenuNode::Item(e) => {
let role = match e.command.as_str() {
"app.hide" => Some(Role::Hide),
"app.hideOthers" => Some(Role::HideOthers),
"app.showAll" => Some(Role::ShowAll),
_ => None,
};
if let Some(role) = role {
// Services sits just above Hide, as in every Mac app.
if role == Role::Hide && !services_added {
out.push(NativeNode::Predefined { role: Role::Services, label: "Services".into(), command: String::new() });
out.push(NativeNode::Separator);
services_added = true;
}
out.push(NativeNode::Predefined { role, label: e.label.clone(), command: e.command.clone() });
continue;
}
let shortcut = crate::menus::entry_shortcut(app, e);
out.push(NativeNode::Item(NativeItem {
id,
label: crate::menus::entry_label(app, e),
command: e.command.clone(),
params: e.params.clone(),
accelerator: shortcut.as_deref().and_then(accelerator),
shortcut,
enabled: crate::menus::entry_enabled(app, e),
checked: crate::menus::entry_checked(app, e),
}));
}
}
}
}
let mut menus = vec![];
rec(app, menu_bar(), "m", &mut menus);
NativeMenu { menus }
}
/// The `muda` accelerator for an EffectCraft shortcut, or `None` when it must stay a plain
/// keyboard shortcut. Only shortcuts with Cmd or Ctrl (and function keys) become menu key
/// equivalents: a single-key shortcut (`V`, `Space`, `U`) or an Alt/Shift-only one would be
/// swallowed by the menu while typing into a text field. Those still work through the
/// window's shortcut dispatcher, as on the other platforms.
pub fn accelerator(shortcut: &str) -> Option<String> {
let parts: Vec<&str> = match shortcut.strip_suffix("++") {
Some(head) => head.split('+').chain(std::iter::once("+")).collect(),
None => shortcut.split('+').collect(),
};
let (key, mods) = parts.split_last()?;
let mut out: Vec<String> = vec![];
let mut primary = false;
for m in mods {
out.push(
match *m {
"Cmd" => {
primary = true;
"Cmd"
}
"Ctrl" => {
primary = true;
"Ctrl"
}
"Alt" => "Alt",
"Shift" => "Shift",
_ => return None,
}
.to_string(),
);
}
let function_key = key.len() >= 2 && key.starts_with('F') && key[1..].parse::<u8>().is_ok_and(|n| (1..=24).contains(&n));
if !primary && !function_key {
return None;
}
let k = match *key {
"Num*" => "NumpadMultiply".to_string(),
"+" => "Equal".to_string(),
k if k.starts_with("Num") && k.len() == 4 => format!("Numpad{}", &k[3..]),
"Escape" | "Space" | "Enter" | "Tab" | "Home" | "End" | "PageUp" | "PageDown" | "Delete" | "Backspace" => key.to_string(),
"ArrowLeft" | "ArrowRight" | "ArrowUp" | "ArrowDown" => key.to_string(),
k if k.chars().count() == 1 => {
let c = k.chars().next()?;
if c.is_ascii_alphanumeric() || "`\\[],-=./;'".contains(c) {
c.to_ascii_uppercase().to_string()
} else {
return None;
}
}
k if function_key => k.to_string(),
_ => return None,
};
out.push(k);
Some(out.join("+"))
}
/// Cheap per-frame fingerprint of everything menu labels, check marks and enabled state depend
/// on (project revision, selection, history, settings, executed commands, viewer toggles).
pub fn state_key(app: &EffectcraftApp) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
let s = &app.session;
s.revision.hash(&mut h);
s.prefs_revision.hash(&mut h);
s.path.hash(&mut h);
s.active_comp_id().map(|c| c.0).hash(&mut h);
for l in &s.state.selected_layers {
l.0.hash(&mut h);
}
s.state.selected_keys.len().hash(&mut h);
s.state.selected_props.len().hash(&mut h);
s.state.project_selection.len().hash(&mut h);
s.state.selected_vertices.len().hash(&mut h);
s.state.clipboard.len().hash(&mut h);
s.state.key_clipboard.len().hash(&mut h);
(s.history.undo.len(), s.history.redo.len()).hash(&mut h);
s.journal.len().hash(&mut h);
s.journal.last().map(|j| &j.0).hash(&mut h);
s.prefs.recent_projects.hash(&mut h);
s.keymaps.active.hash(&mut h);
let v = &app.ui.viewer;
(v.rulers, v.guides, v.snap_guides, v.lock_guides, v.grid, v.snap_grid, v.show_layer_controls, v.pasteboard).hash(&mut h);
v.res.label().hash(&mut h);
(app.ui.cache_when_idle, app.ui.preview_audio, &app.ui.workspace, app.dialog.is_some()).hash(&mut h);
h.finish()
}
/// Commands that act on a focused text field instead (Edit menu while typing): the egui event to
/// send in their place.
fn text_field_event(command: &str, clipboard: Option<String>) -> Option<Vec<egui::Event>> {
let key = |k: egui::Key, shift: bool| egui::Event::Key {
key: k,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers { shift, ..egui::Modifiers::COMMAND },
};
Some(match command {
"edit.copy" => vec![egui::Event::Copy],
"edit.cut" => vec![egui::Event::Cut],
"edit.paste" => vec![egui::Event::Paste(clipboard?)],
"edit.selectAll" => vec![key(egui::Key::A, false)],
"edit.undo" => vec![key(egui::Key::Z, false)],
"edit.redo" => vec![key(egui::Key::Z, true)],
_ => return None,
})
}
/// Run a native menu item (by id) the way the in-window menu bar does. While a text field has
/// the keyboard, Edit ▸ Cut/Copy/Paste/Select All/Undo/Redo edit the text instead.
pub fn activate(app: &mut EffectcraftApp, ctx: &egui::Context, menu: &NativeMenu, id: &str) -> Result<Value, String> {
let item = menu.find(id).ok_or_else(|| format!("no native menu item `{id}`"))?;
let (command, params) = (item.command.clone(), item.params.clone());
if ctx.egui_wants_keyboard_input() {
let clip = if command == "edit.paste" { app.hooks.clipboard_text.as_ref().and_then(|f| f()) } else { None };
if let Some(events) = text_field_event(&command, clip) {
app.synthetic.extend(events);
ctx.request_repaint();
return Ok(Value::Null);
}
}
let params = if params.is_null() { json!({}) } else { params };
let r = crate::menus::invoke(app, ctx, &command, params);
if let Err(e) = &r {
app.ui.status = e.clone();
}
ctx.request_repaint();
r
}
#[cfg(test)]
mod tests {
use super::*;
fn app() -> EffectcraftApp {
let mut s = effectcraft_engine::Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
EffectcraftApp::new(s)
}
#[test]
fn every_engine_entry_is_in_the_native_menu() {
let app = app();
let spec = build(&app);
fn commands(n: &[NativeNode], out: &mut Vec<(String, String)>) {
for x in n {
match x {
NativeNode::Item(i) if i.command != "file.openRecent" => out.push((i.command.clone(), i.params.to_string())),
NativeNode::Predefined { command, .. } if !command.is_empty() => out.push((command.clone(), "null".into())),
NativeNode::Submenu { children, .. } => commands(children, out),
_ => {}
}
}
}
let mut got = vec![];
commands(&spec.menus, &mut got);
let want: Vec<(String, String)> = effectcraft_engine::menus::entries().into_iter().map(|(_, e)| (e.command.clone(), e.params.to_string())).collect();
assert_eq!(got, want, "native menu must mirror the engine tree entry for entry");
// Top-level menus in order.
let tops: Vec<&str> = spec
.menus
.iter()
.filter_map(|n| match n {
NativeNode::Submenu { label, .. } => Some(label.as_str()),
_ => None,
})
.collect();
assert_eq!(tops, effectcraft_engine::menus::top_level());
// Ids are unique.
let ids: std::collections::BTreeSet<&str> = spec.items().iter().map(|i| i.id.as_str()).collect();
assert_eq!(ids.len(), spec.items().len());
// The spec serializes (agents can read it).
let v = serde_json::to_value(&spec).unwrap();
assert!(v["menus"].as_array().is_some_and(|a| a.len() >= 9));
}
#[test]
fn hide_items_are_predefined_on_macos() {
let spec = build(&app());
let mut roles = vec![];
fn rec(n: &[NativeNode], out: &mut Vec<Role>) {
for x in n {
match x {
NativeNode::Predefined { role, .. } => out.push(*role),
NativeNode::Submenu { children, .. } => rec(children, out),
_ => {}
}
}
}
rec(&spec.menus, &mut roles);
if cfg!(target_os = "macos") {
assert_eq!(roles, vec![Role::Services, Role::Hide, Role::HideOthers, Role::ShowAll]);
// Quit and About dispatch our commands (clean shutdown, our About dialog).
assert!(spec.items().iter().any(|i| i.command == "app.quit" && i.accelerator.as_deref() == Some("Cmd+Q")));
assert!(spec.items().iter().any(|i| i.command == "app.about"));
} else {
assert!(roles.is_empty());
}
}
#[test]
fn accelerators_convert() {
assert_eq!(accelerator("Cmd+Shift+S").as_deref(), Some("Cmd+Shift+S"));
assert_eq!(accelerator("Cmd+Alt+;").as_deref(), Some("Cmd+Alt+;"));
assert_eq!(accelerator("Cmd+`").as_deref(), Some("Cmd+`"));
assert_eq!(accelerator("Ctrl+Cmd+F").as_deref(), Some("Ctrl+Cmd+F"));
assert_eq!(accelerator("F3").as_deref(), Some("F3"));
assert_eq!(accelerator("Cmd+Alt+0").as_deref(), Some("Cmd+Alt+0"));
// Keys that would swallow typing stay window shortcuts.
assert_eq!(accelerator("V"), None);
assert_eq!(accelerator("Space"), None);
assert_eq!(accelerator("Shift+="), None);
assert_eq!(accelerator("Alt+["), None);
assert_eq!(accelerator("Num*"), None);
// Every menu shortcut either converts or is a single-key/Alt/Shift shortcut.
let app = app();
for i in build(&app).items() {
if let Some(sc) = &i.shortcut {
let primary = sc.contains("Cmd") || sc.contains("Ctrl");
if primary {
assert!(i.accelerator.is_some(), "{} ({sc}) has no accelerator", i.label);
}
}
}
}
#[test]
fn state_changes_flow_into_the_spec() {
let mut app = app();
let k0 = state_key(&app);
let spec0 = build(&app);
let undo = |s: &NativeMenu| s.items().into_iter().find(|i| i.command == "edit.undo").map(|i| (i.label.clone(), i.enabled)).unwrap();
// Select a layer and toggle Lock: the key changes, the Lock entry gets a check mark.
let first = app.session.active_comp().unwrap().layers[0].id.0;
app.session.execute("layer.select", json!({"layers": [first]})).unwrap();
app.session.execute("layer.setSwitch", json!({"switch": "lock"})).unwrap();
assert_ne!(state_key(&app), k0);
let spec1 = build(&app);
assert_eq!(spec0.structure(), spec1.structure(), "state changes don't rebuild the menu");
let lock = spec1.items().into_iter().find(|i| i.command == "layer.setSwitch" && i.params["switch"] == "lock").unwrap().checked;
assert_eq!(lock, Some(true));
assert_ne!(undo(&spec0), undo(&spec1));
// A recent project changes the structure (Open Recent grows).
app.session.prefs.push_recent("/tmp/Recent Test.ecproj");
let spec2 = build(&app);
assert_ne!(spec1.structure(), spec2.structure());
assert!(spec2.items().iter().any(|i| i.command == "file.openRecent" && i.label == "Recent Test.ecproj"));
}
#[test]
fn activation_dispatches_the_menu_command() {
let mut app = app();
let ctx = egui::Context::default();
let spec = build(&app);
let id = spec.items().into_iter().find(|i| i.command == "layer.newNull").unwrap().id.clone();
let n = app.session.active_comp().unwrap().layers.len();
activate(&mut app, &ctx, &spec, &id).unwrap();
assert_eq!(app.session.active_comp().unwrap().layers.len(), n + 1);
assert!(activate(&mut app, &ctx, &spec, "m.999").is_err());
assert!(text_field_event("edit.copy", None).is_some());
assert!(text_field_event("edit.paste", None).is_none());
assert!(text_field_event("layer.newNull", None).is_none());
}
}
@@ -0,0 +1,438 @@
//! 3D Camera Tracker in the Composition viewer and Effect Controls:
//!
//! - while the effect is selected, the solved 3D track points are drawn as coloured targets
//! sized by depth (or the 2D source tracks with Show Track Points ▸ 2D Source);
//! - hovering between three points shows the target plane they span (a disc in perspective);
//! click a point (Shift adds / toggles) or drag a marquee to select points, click inside a
//! triangle to select its three points; the selection's target is drawn;
//! - right-click: Set Ground Plane and Origin, Create Text / Solid / Null / Shadow Catcher …
//! and Camera, Create Multiple …, Delete Selected Points; Delete removes the selection;
//! - the "Analyzing in background (step 1 of 2)" / "Solving camera" banner;
//! - the Effect Controls block with Analyze / Cancel / Create Camera, Method Used and Average
//! Error.
//!
//! Everything is dispatched to the `camera.*` commands.
use std::sync::Arc;
use effectcraft_engine::Session;
use effectcraft_engine::effects::camera_tracker as ct;
use effectcraft_engine::geom::{Mat3, vec2 as gv2};
use effectcraft_engine::keyframe::Value;
use effectcraft_engine::project::{Comp, Layer, LayerId, PropGroup, Uid};
use effectcraft_engine::render::EvalCtx;
use effectcraft_engine::track::camtrack::{CameraSolve, CameraTracks, Target, point_color};
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, pos2, vec2};
use serde_json::json;
use super::viewer::ViewerMap;
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
/// The tracker whose points the viewer shows.
struct Active {
layer: LayerId,
uid: Uid,
solve: Option<Arc<CameraSolve>>,
tracks: Option<Arc<CameraTracks>>,
show_3d: bool,
point_size: f64,
target_size: f64,
/// Layer pixels → comp pixels.
l2c: Mat3,
frame: usize,
}
/// A drawn point: (id, screen position, screen radius).
type Hit = (u32, Pos2, f32);
fn tracker_group(l: &Layer, uid: Uid) -> Option<&PropGroup> {
l.props.find_group(uid).filter(|g| matches!(&g.kind, effectcraft_engine::project::GroupKind::Effect { effect } if effect == ct::ID))
}
/// The selected 3D Camera Tracker effect on an active layer (After Effects shows the points
/// while the effect is selected).
fn active(s: &Session, comp: &Comp, ectx: &EvalCtx, l2c: &dyn Fn(&EvalCtx, &Layer) -> Mat3) -> Option<Active> {
let time = ectx.time;
for (lid, uid) in &s.state.selected_props {
let Some(l) = comp.layer(*lid).filter(|l| l.is_active_at(time)) else { continue };
let Some(g) = tracker_group(l, *uid) else { continue };
let params = effectcraft_engine::camera_track::static_params(g);
let val = |id: &str| effectcraft_engine::effects::warp_stab::param(&params, id).cloned();
let solve = ct::solve(&params);
let tracks = ct::tracks(&params);
let lt = l.layer_time(time).seconds();
let frame = solve.as_ref().and_then(|sv| sv.frame_at(lt)).or_else(|| {
let t = tracks.as_ref()?;
(t.frame_duration > 0.0).then(|| ((lt - t.start) / t.frame_duration).round().clamp(0.0, t.frames.saturating_sub(1) as f64) as usize)
});
return Some(Active {
layer: *lid,
uid: *uid,
solve,
tracks,
show_3d: val("showTrackPoints").map(|v| v.as_enum()).unwrap_or(1) == 1,
point_size: val("trackPointSize").map(|v| v.as_f64()).unwrap_or(100.0),
target_size: val("targetSize").map(|v| v.as_f64()).unwrap_or(100.0),
l2c: l2c(ectx, l),
frame: frame.unwrap_or(0),
});
}
None
}
fn to_screen(a: &Active, map: &ViewerMap, q: [f64; 2]) -> Pos2 {
let c = a.l2c.apply(gv2(q[0], q[1]));
map.to_screen([c.x, c.y])
}
fn col(id: u32) -> Color32 {
let c = point_color(id);
Color32::from_rgb((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8)
}
/// Comp-pixel scale of the layer → comp mapping.
fn l2c_scale(m: &Mat3) -> f32 {
m.0[0][0].hypot(m.0[1][0]) as f32
}
/// Draw the target disc (concentric rings in perspective) of `t` on frame `k`.
fn draw_target(p: &egui::Painter, a: &Active, map: &ViewerMap, sv: &CameraSolve, t: &Target) {
let Some(cam) = sv.frames.get(a.frame) else { return };
let r = t.size * 0.5 * a.target_size / 100.0;
for (i, frac) in [1.0, 0.66, 0.33].into_iter().enumerate() {
let ring = ct::target_circle(t.center, t.normal, r * frac, 48);
let pts: Vec<Pos2> = ring.iter().filter_map(|x| cam.project(sv.size, *x)).map(|q| to_screen(a, map, q)).collect();
if pts.len() < 3 {
return;
}
let fill = if i % 2 == 0 { Color32::from_rgba_unmultiplied(0xd0, 0x30, 0x30, 70) } else { Color32::from_rgba_unmultiplied(0xff, 0xff, 0xff, 50) };
p.add(egui::Shape::convex_polygon(pts.clone(), fill, Stroke::new(1.0, Color32::from_rgb(0xe0, 0x40, 0x40))));
}
if let Some(c) = cam.project(sv.size, t.center) {
let c = to_screen(a, map, c);
p.circle_filled(c, 3.0, Color32::from_rgb(0xff, 0xd0, 0x40));
}
}
/// The three drawn points forming a triangle around `hp` (nearest first).
fn triangle_at(hits: &[Hit], hp: Pos2) -> Option<[u32; 3]> {
let mut near: Vec<&Hit> = hits.iter().collect();
near.sort_by(|x, y| x.1.distance_sq(hp).total_cmp(&y.1.distance_sq(hp)));
let near: Vec<&Hit> = near.into_iter().take(8).collect();
let inside = |a: Pos2, b: Pos2, c: Pos2| {
let s = |p: Pos2, q: Pos2| (q.x - p.x) * (hp.y - p.y) - (q.y - p.y) * (hp.x - p.x);
let (d1, d2, d3) = (s(a, b), s(b, c), s(c, a));
!((d1 < 0.0 || d2 < 0.0 || d3 < 0.0) && (d1 > 0.0 || d2 > 0.0 || d3 > 0.0))
};
for i in 0..near.len() {
for j in i + 1..near.len() {
for k in j + 1..near.len() {
let (a, b, c) = (near[i], near[j], near[k]);
// Skip slivers.
let area = ((b.1 - a.1).x * (c.1 - a.1).y - (b.1 - a.1).y * (c.1 - a.1).x).abs();
if area > 30.0 && inside(a.1, b.1, c.1) {
return Some([a.0, b.0, c.0]);
}
}
}
}
None
}
fn run(app: &mut EffectcraftApp, ctx: &egui::Context, cmd: &str, p: serde_json::Value) {
if let Err(e) = crate::menus::invoke(app, ctx, cmd, p) {
app.ui.status = e;
}
}
/// The viewer overlay and its interaction (call after the viewer's own gestures so it takes
/// the clicks while a 3D Camera Tracker is selected).
pub fn viewer_hook(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
painter: &egui::Painter,
map: &ViewerMap,
ectx: &EvalCtx,
l2c: &dyn Fn(&EvalCtx, &Layer) -> Mat3,
) {
let ctx = ui.ctx().clone();
let comp = ectx.comp;
banner(app, painter, map, ectx, l2c);
if !app.ui.viewer.show_layer_controls {
return;
}
let Some(a) = active(&app.session, comp, ectx, l2c) else { return };
let selected = app.session.state.camera_points.clone();
let lscale = l2c_scale(&a.l2c) * map.zoom;
let mut hits: Vec<Hit> = vec![];
match (&a.solve, a.show_3d) {
(Some(sv), true) => {
let pts = ct::projected(sv, a.frame);
let med = ct::median_depth(&pts);
for (id, q, z) in pts {
let sp = to_screen(&a, map, q);
if !map.area.expand(20.0).contains(sp) {
continue;
}
let r = (ct::target_radius(a.point_size, z, med) as f32 * lscale).clamp(2.0, 30.0);
let c = col(id);
let sel = selected.contains(&id);
if sel {
painter.circle_filled(sp, r, c);
painter.circle_stroke(sp, r + 1.5, Stroke::new(1.5, Color32::WHITE));
} else {
painter.circle_stroke(sp, r, Stroke::new((r * 0.3).clamp(1.0, 3.0), c));
painter.circle_filled(sp, (r * 0.25).max(1.0), c);
}
hits.push((id, sp, r));
}
}
_ => {
// 2D source tracks (also shown before the solve finishes).
if let Some(tr) = &a.tracks {
for t in &tr.tracks {
let Some(q) = t.at(a.frame as u32) else { continue };
let sp = to_screen(&a, map, q);
let c = col(t.id);
let r = (3.0 * a.point_size as f32 / 100.0).clamp(1.5, 12.0);
painter.line_segment([sp - vec2(r, r), sp + vec2(r, r)], Stroke::new(1.2, c));
painter.line_segment([sp - vec2(r, -r), sp + vec2(r, -r)], Stroke::new(1.2, c));
hits.push((t.id, sp, r));
}
}
}
}
let Some(sv) = a.solve.clone() else { return };
if app.ui.tool != crate::state::Tool::Selection {
return;
}
// Interaction over the image.
let resp = ui.interact(map.area, egui::Id::new("viewer-camera-tracker"), Sense::click_and_drag());
app.auto.add("viewer.cameraTracker", map.area, "3D Camera Tracker points");
for (id, sp, r) in hits.iter().take(400) {
app.auto.add(&format!("viewer.cameraTracker.point.{id}"), Rect::from_center_size(*sp, vec2(r * 2.0 + 4.0, r * 2.0 + 4.0)), "track point");
}
let hover = resp.hover_pos();
let point_at = |p: Pos2| hits.iter().filter(|h| h.1.distance(p) <= h.2 + 3.0).min_by(|x, y| x.1.distance(p).total_cmp(&y.1.distance(p))).map(|h| h.0);
let tri = hover.filter(|p| point_at(*p).is_none()).and_then(|p| triangle_at(&hits, p));
let mid = egui::Id::new("viewer-camera-tracker-marquee");
let marquee: Option<Pos2> = ui.data(|d| d.get_temp(mid));
// Hover target / the selection's target.
if marquee.is_none() {
if let Some(t3) = tri
&& let Some(t) = effectcraft_engine::camera_track::target_for(&sv, &t3, a.frame)
{
let ps: Vec<Pos2> = t3.iter().filter_map(|i| hits.iter().find(|h| h.0 == *i)).map(|h| h.1).collect();
if ps.len() == 3 {
painter.add(egui::Shape::closed_line(ps, Stroke::new(1.0, Color32::from_white_alpha(200))));
}
draw_target(painter, &a, map, &sv, &t);
} else if !selected.is_empty()
&& let Some(t) = effectcraft_engine::camera_track::target_for(&sv, &selected, a.frame)
{
draw_target(painter, &a, map, &sv, &t);
}
}
let mods = ui.input(|i| i.modifiers);
if resp.drag_started()
&& let Some(p) = ui.input(|i| i.pointer.press_origin())
{
ui.data_mut(|d| d.insert_temp(mid, p));
}
if let (Some(start), Some(p)) = (marquee, resp.interact_pointer_pos()) {
let r = Rect::from_two_pos(start, p);
let t = app.tokens;
painter.rect_filled(r, 0.0, t.accent.gamma_multiply(0.12));
painter.rect_stroke(r, 0.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Middle);
if resp.drag_stopped() {
let ids: Vec<u32> = hits.iter().filter(|h| r.contains(h.1)).map(|h| h.0).collect();
ui.data_mut(|d| d.remove::<Pos2>(mid));
run(app, &ctx, "camera.selectPoints", json!({"points": ids, "add": mods.shift}));
}
} else if resp.drag_stopped() {
ui.data_mut(|d| d.remove::<Pos2>(mid));
}
if resp.clicked()
&& let Some(p) = resp.interact_pointer_pos()
{
match (point_at(p), triangle_at(&hits, p)) {
(Some(id), _) => run(app, &ctx, "camera.selectPoints", json!({"points": [id], "toggle": mods.shift})),
(None, Some(t3)) => run(app, &ctx, "camera.selectPoints", json!({"points": t3, "add": mods.shift})),
(None, None) => run(app, &ctx, "camera.selectPoints", json!({"points": []})),
}
}
// Right-click: the points under the cursor (selection, else the hovered triangle).
let cid = egui::Id::new("viewer-camera-tracker-menu-points");
if resp.secondary_clicked() {
let pts: Vec<u32> = if !selected.is_empty() {
selected.clone()
} else if let Some(p) = resp.interact_pointer_pos() {
point_at(p).map(|i| vec![i]).or_else(|| triangle_at(&hits, p).map(|t| t.to_vec())).unwrap_or_default()
} else {
vec![]
};
ui.data_mut(|d| d.insert_temp(cid, pts));
}
let base = json!({"layer": a.layer.0, "effect": a.uid});
resp.context_menu(|ui| {
let pts: Vec<u32> = ui.data(|d| d.get_temp(cid)).unwrap_or_default();
let with = |kind: Option<&str>, multiple: bool| {
let mut q = base.clone();
q["points"] = json!(pts);
if let Some(k) = kind {
q["kind"] = json!(k);
}
if multiple {
q["multiple"] = json!(true);
}
q
};
let some = !pts.is_empty();
let many = pts.len() > 1;
let mut pick: Option<(&str, serde_json::Value)> = None;
if ui.add_enabled(some, egui::Button::new("Set Ground Plane and Origin")).clicked() {
pick = Some(("camera.setGroundPlane", with(None, false)));
}
ui.separator();
for (label, kind) in [
("Create Text and Camera", "text"),
("Create Solid and Camera", "solid"),
("Create Null and Camera", "null"),
("Create Shadow Catcher, Camera and Light", "shadowCatcher"),
] {
if ui.add_enabled(some, egui::Button::new(label)).clicked() {
pick = Some(("camera.createFromSolve", with(Some(kind), false)));
}
}
ui.separator();
for (label, kind) in
[("Create Multiple Text Layers and Camera", "text"), ("Create Multiple Solids and Camera", "solid"), ("Create Multiple Nulls and Camera", "null")]
{
if ui.add_enabled(many, egui::Button::new(label)).clicked() {
pick = Some(("camera.createFromSolve", with(Some(kind), true)));
}
}
ui.separator();
if ui.add_enabled(some, egui::Button::new("Delete Selected Points")).clicked() {
pick = Some(("camera.deletePoints", with(None, false)));
}
if let Some((cmd, q)) = pick {
ui.close();
run(app, &ctx, cmd, q);
}
});
if resp.hovered()
&& !selected.is_empty()
&& ui.input(|i| i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace))
&& !ctx.egui_wants_keyboard_input()
{
run(app, &ctx, "camera.deletePoints", json!({"layer": a.layer.0, "effect": a.uid, "points": selected}));
}
}
/// "Analyzing in background (step 1 of 2)" / "Solving camera" over the analysed layer, and a
/// warning when the solve failed (unless Hide Warning Banner).
fn banner(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap, ectx: &EvalCtx, l2c: &dyn Fn(&EvalCtx, &Layer) -> Mat3) {
let comp = ectx.comp;
let time = ectx.time;
let cid = ectx.comp_id;
let draw = |app: &mut EffectcraftApp, layer: &Layer, text: String, color: Color32, id: &str| {
let m = l2c(ectx, layer);
let (w, h) = effectcraft_engine::render::source_size(&app.session.project, layer);
let c = m.apply(gv2(w as f64 / 2.0, h as f64 / 2.0));
let at = map.to_screen([c.x, c.y]);
let galley = painter.layout_no_wrap(text.clone(), Tokens::medium(13.0), Color32::WHITE);
let r = Rect::from_center_size(at, galley.size() + vec2(28.0, 14.0)).intersect(map.area);
painter.rect_filled(r, 3.0, color);
painter.galley(pos2(r.center().x - galley.size().x / 2.0, r.center().y - galley.size().y / 2.0), galley, Color32::WHITE);
app.auto.add(id, r, &text);
};
if let Some((cc, cl, _)) = app.session.camera_target()
&& cc == cid
&& let Some(pr) = app.session.camera_progress()
&& let Some(layer) = comp.layer(cl)
&& layer.is_active_at(time)
{
draw(app, layer, pr.banner(), Color32::from_rgba_unmultiplied(0x1d, 0x4f, 0x9c, 0xe0), "viewer.cameraBanner");
return;
}
// A failed solve: tracks without a solve while nothing is running or queued.
for l in comp.layers.iter().filter(|l| l.is_active_at(time)) {
let Some(fx) = l.effects() else { continue };
for g in fx.groups().filter(|g| matches!(&g.kind, effectcraft_engine::project::GroupKind::Effect { effect } if effect == ct::ID)) {
let params = effectcraft_engine::camera_track::static_params(g);
let hide = effectcraft_engine::effects::warp_stab::param(&params, "advanced/hideWarningBanner").is_some_and(Value::as_bool);
let solve_key = matches!(g.prop(ct::SOLVE_KEY).map(|p| &p.value), Some(Value::Str(s)) if !s.is_empty());
let failed = solve_key && ct::tracks(&params).is_some() && ct::solve(&params).is_none();
if failed && !hide && !app.session.camera_pending.iter().any(|(_, ll, u)| *ll == l.id && *u == g.uid) {
draw(app, l, "Unable to solve camera".into(), Color32::from_rgba_unmultiplied(0x9c, 0x2a, 0x1d, 0xe0), "viewer.cameraWarning");
return;
}
}
}
}
/// Effect Controls: Analyze / Cancel, Create Camera and the solve report.
#[allow(clippy::too_many_arguments)]
pub fn editor(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
g: &PropGroup,
r: Rect,
actions: &mut Vec<(String, serde_json::Value)>,
) {
let t = app.tokens;
let running = app.session.camera_target().is_some_and(|(_, l, u)| l == layer.id && u == g.uid) && app.session.is_camera_analyzing();
let busy = app.session.is_camera_analyzing();
let me = json!({"layer": layer.id.0, "effect": g.uid});
let b1 = Rect::from_min_size(pos2(r.min.x + 24.0, r.min.y + 4.0), vec2(84.0, 22.0));
let b2 = Rect::from_min_size(pos2(b1.max.x + 8.0, b1.min.y), vec2(84.0, 22.0));
let b3 = Rect::from_min_size(pos2(b2.max.x + 8.0, b1.min.y), vec2(110.0, 22.0));
if widgets::text_button(ui, b1, "Analyze", false, &t, egui::Id::new(("ct-analyze", g.uid))).clicked() && !busy {
actions.push(("camera.analyze".into(), me.clone()));
}
app.auto.add(&format!("effectControls.cameraTracker.{}.analyze", g.uid), b1, "Analyze");
if running {
if widgets::text_button(ui, b2, "Cancel", false, &t, egui::Id::new(("ct-cancel", g.uid))).clicked() {
actions.push(("camera.cancel".into(), json!({})));
}
app.auto.add(&format!("effectControls.cameraTracker.{}.cancel", g.uid), b2, "Cancel");
}
let params = effectcraft_engine::camera_track::static_params(g);
let solve = ct::solve(&params);
if solve.is_some() {
if widgets::text_button(ui, b3, "Create Camera", false, &t, egui::Id::new(("ct-camera", g.uid))).clicked() {
actions.push(("camera.create".into(), me.clone()));
}
app.auto.add(&format!("effectControls.cameraTracker.{}.createCamera", g.uid), b3, "Create Camera");
}
let status = match app.session.camera_progress() {
Some(pr) if running => pr.banner(),
_ => match &solve {
Some(sv) => format!("Method Used: {} Average Error: {:.2} pixels", sv.method_used.label(), sv.average_error),
None if ct::tracks(&params).is_some() && app.session.camera_pending.iter().any(|(_, l, u)| *l == layer.id && *u == g.uid) => {
"Waiting to solve".into()
}
None if ct::tracks(&params).is_some() => "Unable to solve camera: try another Solve Method or Shot Type".into(),
None if app.session.camera_pending.iter().any(|(_, l, u)| *l == layer.id && *u == g.uid) => "Waiting to analyze".into(),
None => "Not analyzed: click Analyze".into(),
},
};
p.text(pos2(r.min.x + 24.0, r.min.y + 38.0), Align2::LEFT_CENTER, status, Tokens::ui(11.5), t.text_dim);
if let Some(sv) = &solve {
let f = sv.focal();
p.text(
pos2(r.min.x + 24.0, r.min.y + 56.0),
Align2::LEFT_CENTER,
format!("{} solved points · Horizontal Angle of View {:.1}°", sv.points.len(), sv.hfov(f)),
Tokens::ui(11.5),
t.text_faint,
);
}
}
/// Height of [`editor`].
pub const EDITOR_HEIGHT: f32 = 68.0;
@@ -537,6 +537,35 @@ fn warp_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, l
p.text(pos2(r.min.x + 24.0, r.min.y + 38.0), Align2::LEFT_CENTER, status, Tokens::ui(11.5), t.text_dim);
}
/// Roto Brush & Refine Edge: Freeze / Unfreeze and Propagate buttons and the segmentation status.
fn roto_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, layer: &Layer, g: &PropGroup, r: Rect, actions: &mut Actions) {
use effectcraft_engine::effects::roto as fx;
let t = app.tokens;
let params = effectcraft_engine::effects::flatten_params(g, &mut |pr| pr.value.clone());
let frozen = fx::is_frozen(&params);
let d = fx::data(&params);
let running = app.session.roto_target().is_some_and(|(_, l, u, _)| l == layer.id && u == g.uid) && app.session.is_roto_running();
let b1 = Rect::from_min_size(pos2(r.min.x + 24.0, r.min.y + 4.0), vec2(84.0, 22.0));
let b2 = Rect::from_min_size(pos2(b1.max.x + 8.0, b1.min.y), vec2(84.0, 22.0));
let label = if frozen { "Unfreeze" } else { "Freeze" };
if widgets::text_button(ui, b1, label, frozen, &t, egui::Id::new(("roto-freeze-ec", g.uid))).clicked() && !running {
let id = if frozen { "roto.unfreeze" } else { "roto.freeze" };
actions.push((id.into(), json!({"layer": layer.id.0, "effect": g.uid})));
}
app.auto.add(&format!("effectControls.roto.{}.freeze", g.uid), b1, label);
let (l2, id2) = if running { ("Stop", "roto.cancel") } else { ("Propagate", "roto.propagate") };
if widgets::text_button(ui, b2, l2, false, &t, egui::Id::new(("roto-prop-ec", g.uid))).clicked() && !frozen {
actions.push((id2.into(), json!({"layer": layer.id.0, "effect": g.uid})));
}
app.auto.add(&format!("effectControls.roto.{}.propagate", g.uid), b2, l2);
let status = match (app.session.roto_progress(), d.base) {
(Some(pr), _) if running => pr.banner(),
(_, None) => "No strokes: paint with the Roto Brush tool (Alt+W) in the Layer panel".to_string(),
(_, Some(b)) => format!("Base frame {b}, span {}–{}{}", d.span[0], d.span[1], if frozen { " (frozen)" } else { "" }),
};
p.text(pos2(r.min.x + 24.0, r.min.y + 38.0), Align2::LEFT_CENTER, status, Tokens::ui(11.5), t.text_dim);
}
// ---------------------------------------------------------------------------------------------
// Curves / Levels editors
@@ -545,6 +574,8 @@ fn editor_height(effect: &str, width: f32) -> f32 {
match effect {
"ec.color.curves" => 34.0 + curves_size(width) + 26.0,
effectcraft_engine::effects::warp_stab::ID => 50.0,
effectcraft_engine::effects::camera_tracker::ID => super::camera_tracker_ui::EDITOR_HEIGHT,
effectcraft_engine::effects::roto::ID => 50.0,
"ec.color.levels" | "ec.color.levelsic" => 34.0 + 80.0 + 58.0,
"ec.color.autolevels" | "ec.color.autocontrast" | "ec.color.autocolor" => 24.0 + 80.0 + 12.0,
_ => 0.0,
@@ -920,6 +951,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
match effect.as_str() {
"ec.color.curves" => curves_editor(app, ui, &bp, &layer, g, &ectx, er, &mut actions),
effectcraft_engine::effects::warp_stab::ID => warp_editor(app, ui, &bp, &layer, g, er, &mut actions),
effectcraft_engine::effects::camera_tracker::ID => super::camera_tracker_ui::editor(app, ui, &bp, &layer, g, er, &mut actions),
effectcraft_engine::effects::roto::ID => roto_editor(app, ui, &bp, &layer, g, er, &mut actions),
"ec.color.levels" | "ec.color.levelsic" => levels_editor(app, ui, &bp, &layer, g, effect, &ectx, er, &mut actions),
_ => histogram_only(app, ui, &bp, g, er),
}
+460
View File
@@ -0,0 +1,460 @@
//! The Flowchart panel (Composition ▸ Composition Flowchart): a node graph of a composition and
//! everything it uses — nested comps, footage, solids — optionally with its layers and their
//! effects. Left to right or top to bottom; double-click a comp to open it; Cmd/Ctrl-click a
//! node to reveal it in the Project panel (layers: select the layer); drag to pan.
//!
//! [`build`] is pure and cycle-safe (a comp nested in itself is drawn once, with an edge back),
//! so agents get the same graph through `flowchart.graph`.
use std::collections::{BTreeMap, BTreeSet};
use effectcraft_engine::project::{ItemId, ItemKind, LayerSource, Project};
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::icons::{self, Icon};
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
/// Flowchart panel options (the panel's switches).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct FlowOptions {
/// Show layers between a comp and its sources.
pub layers: bool,
/// Show each layer's effects (with layers shown).
pub effects: bool,
/// Show solids.
pub solids: bool,
/// Top to bottom instead of left to right.
pub vertical: bool,
/// The comp the chart starts from (None = the active comp).
pub root: Option<u64>,
#[serde(skip)]
pub pan: [f32; 2],
/// Selected node id.
#[serde(skip)]
pub selected: Option<String>,
}
impl Default for FlowOptions {
fn default() -> Self {
FlowOptions { layers: false, effects: false, solids: true, vertical: false, root: None, pan: [0.0, 0.0], selected: None }
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct FlowNode {
/// `item:<id>`, `layer:<comp>:<layer>` or `fx:<comp>:<layer>:<uid>`.
pub id: String,
/// `comp`, `footage`, `solid`, `layer` or `effect`.
pub kind: &'static str,
pub label: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub item: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub comp: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub layer: Option<u64>,
/// Distance from the root (column, or row when vertical).
pub depth: usize,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct FlowGraph {
pub nodes: Vec<FlowNode>,
/// (from, to) node ids: from a comp to what it uses.
pub edges: Vec<(String, String)>,
}
/// Build the flowchart of `root` (a comp). Shared items appear once; cycles stop at the comp
/// already on the path.
pub fn build(project: &Project, root: ItemId, opts: &FlowOptions) -> FlowGraph {
struct B<'a> {
p: &'a Project,
o: &'a FlowOptions,
nodes: Vec<FlowNode>,
index: BTreeMap<String, usize>,
edges: Vec<(String, String)>,
stack: BTreeSet<u64>,
}
impl B<'_> {
fn node(&mut self, n: FlowNode) -> String {
let id = n.id.clone();
match self.index.get(&id) {
Some(&i) => self.nodes[i].depth = self.nodes[i].depth.min(n.depth),
None => {
self.index.insert(id.clone(), self.nodes.len());
self.nodes.push(n);
}
}
id
}
fn edge(&mut self, a: &str, b: &str) {
let e = (a.to_string(), b.to_string());
if !self.edges.contains(&e) {
self.edges.push(e);
}
}
fn item(&mut self, id: ItemId, depth: usize) -> Option<String> {
let it = self.p.item(id)?;
let kind = match &it.kind {
ItemKind::Comp(_) => "comp",
ItemKind::Footage(_) => "footage",
ItemKind::Solid(_) => "solid",
ItemKind::Folder => return None,
};
if kind == "solid" && !self.o.solids {
return None;
}
let seen = self.index.contains_key(&format!("item:{}", id.0));
let nid = self.node(FlowNode { id: format!("item:{}", id.0), kind, label: it.name.clone(), item: Some(id.0), comp: None, layer: None, depth });
if kind == "comp" && !seen && !self.stack.contains(&id.0) {
self.comp(id, depth);
}
Some(nid)
}
fn comp(&mut self, cid: ItemId, depth: usize) {
let Some(c) = self.p.comp(cid) else { return };
self.stack.insert(cid.0);
let from = format!("item:{}", cid.0);
for l in &c.layers {
let src_depth = if self.o.layers { depth + 2 } else { depth + 1 };
let mut parent = from.clone();
if self.o.layers {
let lid = self.node(FlowNode {
id: format!("layer:{}:{}", cid.0, l.id.0),
kind: "layer",
label: l.name.clone(),
item: None,
comp: Some(cid.0),
layer: Some(l.id.0),
depth: depth + 1,
});
self.edge(&from, &lid);
if self.o.effects
&& let Some(fx) = l.effects()
{
for g in fx.groups() {
let fid = self.node(FlowNode {
id: format!("fx:{}:{}:{}", cid.0, l.id.0, g.uid),
kind: "effect",
label: g.name.clone(),
item: None,
comp: Some(cid.0),
layer: Some(l.id.0),
depth: depth + 2,
});
self.edge(&lid, &fid);
}
}
parent = lid;
}
let src = match l.source {
LayerSource::Footage { item } | LayerSource::Comp { item } | LayerSource::Solid { item } | LayerSource::Model { item } => Some(item),
_ => None,
};
if let Some(item) = src {
// A comp already on the path: link back to it, don't descend (cycle).
if self.stack.contains(&item.0) {
self.edge(&parent, &format!("item:{}", item.0));
} else if let Some(sid) = self.item(item, src_depth) {
self.edge(&parent, &sid);
}
}
}
self.stack.remove(&cid.0);
}
}
let mut b = B { p: project, o: opts, nodes: vec![], index: BTreeMap::new(), edges: vec![], stack: BTreeSet::new() };
b.item(root, 0);
FlowGraph { nodes: b.nodes, edges: b.edges }
}
const NODE_W: f32 = 168.0;
const NODE_H: f32 = 34.0;
/// Node positions (top-left, before panning): one column (or row) per depth, in discovery order.
pub fn layout(g: &FlowGraph, vertical: bool) -> Vec<[f32; 2]> {
let mut slot: BTreeMap<usize, usize> = BTreeMap::new();
g.nodes
.iter()
.map(|n| {
let k = slot.entry(n.depth).or_insert(0);
let i = *k as f32;
*k += 1;
let d = n.depth as f32;
if vertical { [i * (NODE_W + 24.0), d * (NODE_H + 46.0)] } else { [d * (NODE_W + 60.0), i * (NODE_H + 14.0)] }
})
.collect()
}
/// The comp the panel charts.
pub fn root(app: &EffectcraftApp) -> Option<ItemId> {
app.ui.flowchart.root.map(ItemId).filter(|r| app.session.project.comp(*r).is_some()).or_else(|| app.session.active_comp_id())
}
/// `flowchart.options` / `flowchart.graph` (UI commands).
pub fn command(app: &mut EffectcraftApp, id: &str, p: &Value) -> Result<Value, String> {
let o = &mut app.ui.flowchart;
let b = |k: &str| p.get(k).and_then(Value::as_bool);
if let Some(v) = b("layers") {
o.layers = v;
}
if let Some(v) = b("effects") {
o.effects = v;
}
if let Some(v) = b("solids") {
o.solids = v;
}
if let Some(d) = p.get("direction").and_then(Value::as_str) {
o.vertical = match d {
"lr" | "leftToRight" => false,
"tb" | "topToBottom" => true,
_ => return Err(format!("direction: lr|tb, not `{d}`")),
};
}
if let Some(c) = p.get("comp") {
let cid = match c {
Value::Number(n) => n.as_u64().map(ItemId),
Value::String(s) => app.session.project.find_by_name(s).map(|i| i.id),
_ => None,
};
let cid = cid.filter(|c| app.session.project.comp(*c).is_some()).ok_or("comp: a composition id or name")?;
app.ui.flowchart.root = Some(cid.0);
}
let o = app.ui.flowchart.clone();
if id == "flowchart.graph" {
let r = root(app).ok_or("no composition")?;
return Ok(serde_json::to_value(build(&app.session.project, r, &o)).unwrap_or_default());
}
Ok(json!({"layers": o.layers, "effects": o.effects, "solids": o.solids, "direction": if o.vertical { "tb" } else { "lr" }, "root": o.root}))
}
fn kind_style(kind: &str) -> (Icon, Color32) {
match kind {
"comp" => (Icon::Comp, Color32::from_rgb(0x3d, 0x5a, 0x8c)),
"footage" => (Icon::Footage, Color32::from_rgb(0x3c, 0x6e, 0x58)),
"solid" => (Icon::Solid, Color32::from_rgb(0x6a, 0x58, 0x3a)),
"effect" => (Icon::Fx, Color32::from_rgb(0x6c, 0x44, 0x6e)),
_ => (Icon::Null, Color32::from_rgb(0x44, 0x48, 0x52)),
}
}
/// Draw the Flowchart panel.
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().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.tl_bg);
let Some(rid) = root(app) else {
p.text(rect.center(), Align2::CENTER_CENTER, "(no composition)", Tokens::ui(12.0), t.text_faint);
return;
};
// ---- toolbar: switches and direction.
let bar = Rect::from_min_size(rect.min, vec2(rect.width(), 30.0));
p.rect_filled(bar, 0.0, t.panel_bg);
let root_name = app.session.project.item(rid).map(|i| i.name.clone()).unwrap_or_default();
p.text(pos2(bar.min.x + 10.0, bar.center().y), Align2::LEFT_CENTER, format!("Flowchart: {root_name}"), Tokens::medium(12.0), t.text);
let mut x = bar.max.x - 8.0;
let mut cmds: Vec<(String, Value)> = vec![];
let o = app.ui.flowchart.clone();
for (key, label, on) in [
("direction", if o.vertical { "Top to Bottom" } else { "Left to Right" }, false),
("effects", "Effects", o.effects),
("layers", "Layers", o.layers),
("solids", "Solids", o.solids),
] {
let w = 18.0 + label.len() as f32 * 6.6;
let r = Rect::from_min_size(pos2(x - w, bar.min.y + 5.0), vec2(w, 20.0));
x -= w + 6.0;
if widgets::text_button(ui, r, label, on, &t, egui::Id::new(("flow-opt", key))).clicked() {
let v = if key == "direction" { json!({"direction": if o.vertical { "lr" } else { "tb" }}) } else { json!({key: !on}) };
cmds.push(("flowchart.options".into(), v));
}
app.auto.add(&format!("flowchart.option.{key}"), r, label);
}
// ---- graph.
let body = Rect::from_min_max(pos2(rect.min.x, bar.max.y), rect.max);
let g = build(&app.session.project, rid, &o);
let pos = layout(&g, o.vertical);
let origin = body.min + vec2(24.0 + o.pan[0], 24.0 + o.pan[1]);
let bg = ui.interact(body, egui::Id::new("flow-bg"), Sense::click_and_drag());
if bg.dragged() {
let d = bg.drag_delta();
app.ui.flowchart.pan[0] += d.x;
app.ui.flowchart.pan[1] += d.y;
}
if ui.rect_contains_pointer(body) {
let s = ui.input(|i| i.smooth_scroll_delta);
if s != egui::Vec2::ZERO {
app.ui.flowchart.pan[0] += s.x;
app.ui.flowchart.pan[1] += s.y;
}
}
if bg.clicked() {
app.ui.flowchart.selected = None;
}
let gp = p.with_clip_rect(body);
let rect_of = |i: usize| Rect::from_min_size(origin + vec2(pos[i][0], pos[i][1]), vec2(NODE_W, NODE_H));
let idx: BTreeMap<&str, usize> = g.nodes.iter().enumerate().map(|(i, n)| (n.id.as_str(), i)).collect();
// Edges first (curves with an arrowhead at the target).
for (a, b) in &g.edges {
let (Some(&ia), Some(&ib)) = (idx.get(a.as_str()), idx.get(b.as_str())) else { continue };
let (ra, rb) = (rect_of(ia), rect_of(ib));
let back = g.nodes[ib].depth <= g.nodes[ia].depth;
let (s, e, n) = if o.vertical { (ra.center_bottom(), rb.center_top(), vec2(0.0, 1.0)) } else { (ra.right_center(), rb.left_center(), vec2(1.0, 0.0)) };
let k = if o.vertical { (e.y - s.y).abs() * 0.5 } else { (e.x - s.x).abs() * 0.5 }.max(30.0);
let col = if back { Color32::from_rgb(0xd0, 0x80, 0x40) } else { t.text_faint };
let curve = egui::epaint::CubicBezierShape::from_points_stroke([s, s + n * k, e - n * k, e], false, Color32::TRANSPARENT, Stroke::new(1.2, col));
gp.add(curve);
let (l, r) = if o.vertical { (vec2(-4.0, -7.0), vec2(4.0, -7.0)) } else { (vec2(-7.0, -4.0), vec2(-7.0, 4.0)) };
gp.add(egui::Shape::convex_polygon(vec![e, e + l, e + r], col, Stroke::NONE));
}
let cmd_down = ui.input(|i| i.modifiers.command || i.modifiers.ctrl);
for (i, n) in g.nodes.iter().enumerate() {
let r = rect_of(i);
if !r.intersects(body) {
continue;
}
let (icon, fill) = kind_style(n.kind);
let selected = o.selected.as_deref() == Some(n.id.as_str());
let resp = ui.interact(r.intersect(body), egui::Id::new(("flow-node", &n.id)), Sense::click());
let fill = if resp.hovered() { fill.gamma_multiply(1.25) } else { fill };
gp.rect_filled(r, 5.0, fill);
gp.rect_stroke(
r,
5.0,
Stroke::new(if selected { 2.0 } else { 1.0 }, if selected { t.accent } else { Color32::from_black_alpha(120) }),
StrokeKind::Inside,
);
icons::paint(&gp, Rect::from_center_size(pos2(r.min.x + 16.0, r.center().y), vec2(14.0, 14.0)), icon, Color32::WHITE);
gp.with_clip_rect(r.shrink(2.0).intersect(body)).text(
pos2(r.min.x + 30.0, r.center().y),
Align2::LEFT_CENTER,
&n.label,
Tokens::ui(12.0),
Color32::WHITE,
);
app.auto.add(&format!("flowchart.node.{}", n.id), r, &n.label);
if resp.clicked() {
app.ui.flowchart.selected = Some(n.id.clone());
if cmd_down {
// Reveal: items in the Project panel, layers selected in their comp.
match (n.item, n.comp, n.layer) {
(Some(item), ..) => {
cmds.push(("project.select".into(), json!({"items": [item]})));
cmds.push(("window.panel".into(), json!({"panel": "project"})));
}
(None, Some(c), Some(l)) => {
cmds.push(("comp.open".into(), json!({"comp": c})));
cmds.push(("layer.select".into(), json!({"layers": [l]})));
}
_ => {}
}
}
}
if resp.double_clicked() {
match (n.kind, n.item, n.comp) {
("comp", Some(c), _) => cmds.push(("comp.open".into(), json!({"comp": c}))),
(_, _, Some(c)) => cmds.push(("comp.open".into(), json!({"comp": c}))),
_ => {}
}
}
resp.on_hover_text(format!("{} — double-click to open, {}-click to reveal", n.label, if cfg!(target_os = "macos") { "Cmd" } else { "Ctrl" }));
}
for (id, params) in cmds {
if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) {
app.ui.status = e;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use effectcraft_engine::Session;
/// Main ⊃ Mid ⊃ Inner (with a solid), Main also uses Inner directly.
fn session() -> (Session, ItemId, ItemId, ItemId) {
let mut s = Session::default();
let id = |v: Value| ItemId(v["id"].as_u64().or_else(|| v["comp"].as_u64()).or_else(|| v["item"].as_u64()).unwrap());
let inner = id(s.execute("comp.new", json!({"name": "Inner", "width": 100, "height": 100, "duration": 2})).unwrap());
s.execute("layer.newSolid", json!({"name": "Red", "color": "#ff0000", "width": 100, "height": 100})).unwrap();
s.execute("layer.select", json!({"layers": []})).unwrap();
let mid = id(s.execute("comp.new", json!({"name": "Mid", "width": 100, "height": 100, "duration": 2})).unwrap());
s.execute("layer.addItem", json!({"item": inner.0})).unwrap();
let main = id(s.execute("comp.new", json!({"name": "Main", "width": 100, "height": 100, "duration": 2})).unwrap());
s.execute("layer.addItem", json!({"item": mid.0})).unwrap();
s.execute("layer.addItem", json!({"item": inner.0})).unwrap();
s.execute("layer.newText", json!({"text": "Title"})).unwrap();
(s, main, mid, inner)
}
#[test]
fn nested_comps_make_a_graph() {
let (s, main, mid, inner) = session();
let g = build(&s.project, main, &FlowOptions::default());
let label = |id: &str| g.nodes.iter().find(|n| n.id == id).map(|n| (n.label.clone(), n.depth));
assert_eq!(label(&format!("item:{}", main.0)), Some(("Main".into(), 0)));
assert_eq!(label(&format!("item:{}", mid.0)), Some(("Mid".into(), 1)));
// Inner is reached at depth 1 (directly) and 2 (through Mid): drawn once, at depth 1.
assert_eq!(label(&format!("item:{}", inner.0)), Some(("Inner".into(), 1)));
assert_eq!(g.nodes.iter().filter(|n| n.label == "Inner").count(), 1);
let has = |a: ItemId, b: ItemId| g.edges.contains(&(format!("item:{}", a.0), format!("item:{}", b.0)));
assert!(has(main, mid) && has(mid, inner) && has(main, inner));
// The solid is shown (Solids on) and hidden with Solids off; text layers have no source.
assert!(g.nodes.iter().any(|n| n.kind == "solid"));
let g2 = build(&s.project, main, &FlowOptions { solids: false, ..Default::default() });
assert!(!g2.nodes.iter().any(|n| n.kind == "solid"));
// Layers between comps and sources; effects under layers.
let g3 = build(&s.project, main, &FlowOptions { layers: true, ..Default::default() });
assert!(g3.nodes.iter().any(|n| n.kind == "layer" && n.label == "Title"));
let mid_layer = g3.nodes.iter().find(|n| n.kind == "layer" && n.comp == Some(main.0) && n.label == "Mid").unwrap();
assert!(g3.edges.contains(&(mid_layer.id.clone(), format!("item:{}", mid.0))));
// Layout: one column per depth, no overlaps.
let pos = layout(&g3, false);
for i in 0..pos.len() {
for j in i + 1..pos.len() {
assert!(pos[i] != pos[j], "{} and {} overlap", g3.nodes[i].label, g3.nodes[j].label);
}
}
}
#[test]
fn cycles_are_safe() {
let (mut s, main, mid, _) = session();
// Make Mid contain Main: Main → Mid → Main.
s.execute("comp.open", json!({"comp": mid.0})).unwrap();
// Adding a cyclic layer may be refused by the engine; build a cycle in the model directly.
let mut p = (*s.project).clone();
let mut c = (*p.comp(mid).unwrap()).clone();
let mut l = c.layers[0].clone();
l.id = effectcraft_engine::project::LayerId(9999);
l.source = LayerSource::Comp { item: main };
c.layers.push(l);
if let Some(ItemKind::Comp(arc)) = p.items.get_mut(&mid).map(|i| &mut i.kind) {
*arc = std::sync::Arc::new(c);
}
let g = build(&p, main, &FlowOptions { layers: true, effects: true, ..Default::default() });
assert_eq!(g.nodes.iter().filter(|n| n.kind == "comp" && n.label == "Main").count(), 1);
// The back edge points at the root.
assert!(g.edges.iter().any(|(_, b)| *b == format!("item:{}", main.0)));
assert!(g.nodes.len() < 50);
}
#[test]
fn options_command() {
let (s, main, ..) = session();
let mut app = EffectcraftApp::new(s);
let r = command(&mut app, "flowchart.options", &json!({"layers": true, "direction": "tb"})).unwrap();
assert_eq!(r["direction"], "tb");
assert!(app.ui.flowchart.layers && app.ui.flowchart.vertical);
assert!(command(&mut app, "flowchart.options", &json!({"direction": "diagonal"})).is_err());
let g = command(&mut app, "flowchart.graph", &json!({"comp": "Main"})).unwrap();
assert_eq!(g["nodes"][0]["id"], format!("item:{}", main.0));
assert!(g["edges"].as_array().is_some_and(|e| !e.is_empty()));
}
}
+20
View File
@@ -108,6 +108,16 @@ fn has(p: &Value, keys: &[&str]) -> bool {
}
/// If `id` is a dialog command invoked without its parameters, open its form and return true.
/// The import includes a Photoshop document.
fn is_layered(p: &Value) -> bool {
let psd = |v: &Value| v.as_str().is_some_and(|s| matches!(s.rsplit('.').next().map(str::to_ascii_lowercase).as_deref(), Some("psd" | "psb")));
match p.get("paths").or(p.get("path")) {
Some(Value::Array(a)) => a.iter().any(psd),
Some(v) => psd(v),
None => false,
}
}
pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
let s = &app.session;
let comp = s.active_comp();
@@ -116,6 +126,16 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
let lt = layer.map(|l| l.layer_time(t)).unwrap_or(t);
let base = p.clone();
let (title, fields): (String, Vec<Field>) = match id {
// Photoshop files: Import Kind (Footage / Composition / – Retain Layer Sizes).
"file.import" if !has(p, &["importAs"]) && is_layered(p) => (
"Import Photoshop File".into(),
vec![Field::choice(
"importAs",
"Import Kind",
&[("Footage", json!("footage")), ("Composition", json!("composition")), ("Composition - Retain Layer Sizes", json!("compositionLayerSizes"))],
1,
)],
),
"layer.setTransform" if !has(p, &["value"]) => {
let prop = p.get("prop").and_then(Value::as_str).unwrap_or("position");
let cur = layer.and_then(|l| l.transform()).and_then(|tr| tr.get(if prop == "anchorPoint" { "anchor" } else { prop })).map(|pr| pr.value_at(lt));
+389
View File
@@ -0,0 +1,389 @@
//! The Home screen (shown in the Composition panel at launch, from the header's Home button, and
//! by the Learn workspace): New Project / Open Project / New Composition / Open Demo, the recent
//! projects (File ▸ Open Recent, from Settings) with thumbnails, folders and dates, and where
//! After Effects has its Learn / What's New area, the ArtCraft community links.
//!
//! Thumbnails: when a project is opened or saved and the viewer has its frame, a 96×54 RGB
//! thumbnail is stored in the config store (`thumb-<hash>.txt`, hex) and shown here.
use std::hash::{Hash, Hasher};
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde::Serialize;
use serde_json::json;
use crate::icons::{self, Icon};
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
pub const THUMB_W: usize = 96;
pub const THUMB_H: usize = 54;
/// One row of the recent projects list.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct RecentEntry {
pub index: usize,
pub path: String,
pub name: String,
pub folder: String,
/// Last modified (`2026-10-02 14:05`, UTC), when the file is readable.
pub modified: Option<String>,
pub exists: bool,
}
/// The recent projects, most recent first (Settings ▸ General ▸ recent items).
pub fn recent_entries(prefs: &effectcraft_engine::prefs::Prefs) -> Vec<RecentEntry> {
prefs
.recent_projects
.iter()
.enumerate()
.map(|(index, p)| {
let path = std::path::Path::new(p);
let meta = std::fs::metadata(path).ok();
let modified = meta
.as_ref()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| format_utc(d.as_secs() as i64));
RecentEntry {
index,
path: p.clone(),
name: path.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| p.clone()),
folder: path.parent().map(|d| d.to_string_lossy().to_string()).unwrap_or_default(),
modified,
exists: meta.is_some(),
}
})
.collect()
}
/// `YYYY-MM-DD HH:MM` (UTC) from Unix seconds.
pub fn format_utc(secs: i64) -> String {
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}-{m:02}-{d:02} {:02}:{:02}", rem / 3600, (rem % 3600) / 60)
}
/// The config-store name of a project's thumbnail.
pub fn thumb_name(path: &str) -> String {
let mut h = std::collections::hash_map::DefaultHasher::new();
path.hash(&mut h);
format!("thumb-{:016x}.txt", h.finish())
}
/// Downscale an image to a letterboxed THUMB_W×THUMB_H RGB thumbnail (hex text).
pub fn encode_thumb(img: &egui::ColorImage) -> String {
let [w, h] = img.size;
let mut out = String::with_capacity(THUMB_W * THUMB_H * 6);
let k = (THUMB_W as f32 / w.max(1) as f32).min(THUMB_H as f32 / h.max(1) as f32);
let (dw, dh) = (w as f32 * k, h as f32 * k);
let (ox, oy) = ((THUMB_W as f32 - dw) / 2.0, (THUMB_H as f32 - dh) / 2.0);
for y in 0..THUMB_H {
for x in 0..THUMB_W {
let (fx, fy) = ((x as f32 + 0.5 - ox) / k, (y as f32 + 0.5 - oy) / k);
let c = if fx >= 0.0 && fy >= 0.0 && (fx as usize) < w && (fy as usize) < h {
let p = img.pixels[fy as usize * w + fx as usize];
[p.r(), p.g(), p.b()]
} else {
[0x16, 0x17, 0x1c]
};
for v in c {
out.push_str(&format!("{v:02x}"));
}
}
}
out
}
pub fn decode_thumb(text: &str) -> Option<egui::ColorImage> {
let t = text.trim();
if t.len() != THUMB_W * THUMB_H * 6 {
return None;
}
let b: Vec<u8> = (0..t.len()).step_by(2).map(|i| u8::from_str_radix(&t[i..i + 2], 16)).collect::<Result<_, _>>().ok()?;
let px = b.chunks_exact(3).map(|c| Color32::from_rgb(c[0], c[1], c[2])).collect();
Some(egui::ColorImage::new([THUMB_W, THUMB_H], px))
}
/// Store the viewer's frame as the open project's thumbnail after it is opened or saved (once per
/// saved revision, when the viewer shows that revision).
pub fn capture_thumbnail(app: &mut EffectcraftApp) {
let s = &app.session;
let (Some(path), Some(_)) = (s.path.clone(), s.config.as_ref()) else { return };
if s.is_dirty() {
return;
}
let key = (path.clone(), s.saved_revision);
if app.home_thumb_saved.as_ref() == Some(&key) {
return;
}
if app.viewer_shown.as_ref().map(|(_, k)| k.revision) != Some(s.revision) {
return;
}
let Some(img) = app.viewer_pixels() else { return };
let text = encode_thumb(&img);
if let Some(c) = &app.session.config
&& let Err(e) = c.write(&thumb_name(&path), &text)
{
log::warn!("project thumbnail: {e}");
}
app.home_thumbs.remove(&path);
app.home_thumb_saved = Some(key);
}
fn thumb_texture(app: &mut EffectcraftApp, ctx: &egui::Context, path: &str) -> Option<egui::TextureHandle> {
if let Some(t) = app.home_thumbs.get(path) {
return t.clone();
}
let tex = app
.session
.config
.as_ref()
.and_then(|c| c.read(&thumb_name(path)))
.and_then(|t| decode_thumb(&t))
.map(|img| ctx.load_texture(format!("home-thumb-{path}"), img, egui::TextureOptions::LINEAR));
app.home_thumbs.insert(path.to_string(), tex.clone());
tex
}
/// Draw the Home screen.
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().with_clip_rect(rect);
p.rect_filled(rect, 0.0, Color32::from_rgb(0x1b, 0x1d, 0x24));
let wide = rect.width() >= 820.0;
let pad = 32.0;
let left_w = if wide { 250.0 } else { rect.width() - pad * 2.0 };
let mut actions: Vec<(&str, serde_json::Value)> = vec![];
// ---- left: brand + start actions.
let x0 = rect.min.x + pad;
let mut y = rect.min.y + pad;
crate::header::paint_logo(&p, Rect::from_min_size(pos2(x0, y), vec2(40.0, 40.0)));
p.text(pos2(x0 + 52.0, y + 12.0), Align2::LEFT_CENTER, "EffectCraft", Tokens::semibold(22.0), Color32::WHITE);
p.text(pos2(x0 + 52.0, y + 32.0), Align2::LEFT_CENTER, format!("Version {}", env!("CARGO_PKG_VERSION")), Tokens::ui(11.0), t.text_faint);
y += 64.0;
for (label, id, primary) in [
("New Project", "file.newProject", true),
("Open Project…", "file.open", false),
("New Composition", "app.newComp", false),
("Open Demo Project", "file.openDemoProject", false),
("Import Footage…", "file.import", false),
] {
let r = Rect::from_min_size(pos2(x0, y), vec2(left_w.min(250.0), 32.0));
if widgets::text_button(ui, r, label, primary, &t, egui::Id::new(("home", id))).clicked() {
actions.push((id, json!({})));
}
app.auto.add(&format!("home.{id}"), r, label);
y += 40.0;
}
// ---- community (After Effects' Learn / What's New area).
let (cx, mut cy, cw) = if wide { (x0, y + 18.0, left_w) } else { (x0, y + 10.0, left_w) };
p.text(pos2(cx, cy), Align2::LEFT_CENTER, "Community", Tokens::semibold(13.0), t.text);
cy += 16.0;
p.text(pos2(cx, cy), Align2::LEFT_CENTER, "Tutorials, help and what's new", Tokens::ui(11.0), t.text_faint);
cy += 16.0;
let links = [
(Icon::Chat, "Join the ArtCraft Discord", "help.discord"),
(Icon::Globe, "getartcraft.com", "help.website"),
(Icon::Globe, "EffectCraft home page", "help.appPage"),
(Icon::Code, "EffectCraft on GitHub", "help.github"),
];
for (icon, label, cmd) in links {
let r = Rect::from_min_size(pos2(cx, cy), vec2(cw.min(250.0), 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 + 36.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!({}));
}
cy += 36.0;
}
cy += 8.0;
p.text(pos2(cx, cy), Align2::LEFT_CENTER, "More ArtCraft apps", Tokens::ui(11.0), t.text_faint);
cy += 12.0;
let sib = effectcraft_engine::links::SIBLINGS;
let per_row = 2usize;
let sw = (cw.min(250.0) - 6.0) / per_row as f32;
for (i, (name, slug)) in sib.iter().enumerate() {
let r = Rect::from_min_size(pos2(cx + (i % per_row) as f32 * (sw + 6.0), cy + (i / per_row) as f32 * 28.0), vec2(sw, 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);
app.auto.add(&format!("home.sibling.{slug}"), r, name);
if resp.clicked() {
let _ = app.session.execute("help.sibling", json!({"app": slug}));
}
}
let community_bottom = cy + sib.len().div_ceil(per_row) as f32 * 28.0;
// ---- recent projects.
let (rx, mut ry, rw) = if wide {
let rx = x0 + left_w + 40.0;
(rx, rect.min.y + pad + 6.0, rect.max.x - pad - rx)
} else {
(x0, community_bottom + 24.0, left_w)
};
p.text(pos2(rx, ry + 6.0), Align2::LEFT_CENTER, "Recent", Tokens::semibold(16.0), Color32::WHITE);
let entries = recent_entries(&app.session.prefs);
if !entries.is_empty() {
let cr = Rect::from_min_size(pos2(rx + rw - 100.0, ry - 4.0), vec2(100.0, 20.0));
let resp = ui.interact(cr, egui::Id::new("home-clear-recent"), Sense::click());
p.text(cr.right_center(), Align2::RIGHT_CENTER, "Clear list", Tokens::ui(11.0), if resp.hovered() { t.text } else { t.text_faint });
app.auto.add("home.clearRecent", cr, "Clear Recent Projects");
if resp.clicked() {
actions.push(("file.clearRecent", json!({})));
}
}
ry += 26.0;
// Column headings.
let date_w = 130.0;
p.text(pos2(rx + 112.0, ry), Align2::LEFT_CENTER, "Name", Tokens::ui(11.0), t.text_faint);
p.text(pos2(rx + rw - date_w, ry), Align2::LEFT_CENTER, "Modified", Tokens::ui(11.0), t.text_faint);
ry += 10.0;
p.line_segment([pos2(rx, ry), pos2(rx + rw, ry)], Stroke::new(1.0, t.separator));
ry += 6.0;
if entries.is_empty() {
p.text(pos2(rx, ry + 20.0), Align2::LEFT_CENTER, "No recent projects. Projects you open or save appear here.", Tokens::ui(12.0), t.text_faint);
}
let row_h = 66.0;
for e in &entries {
let r = Rect::from_min_size(pos2(rx, ry), vec2(rw, row_h - 4.0));
if r.min.y > rect.max.y {
break;
}
let resp = ui.interact(r, egui::Id::new(("home-recent", e.index)), Sense::click()).on_hover_text(&e.path);
if resp.hovered() {
p.rect_filled(r, 6.0, t.hover);
}
let tr = Rect::from_min_size(pos2(r.min.x + 6.0, r.min.y + 4.0), vec2(THUMB_W as f32, THUMB_H as f32));
match thumb_texture(app, &ctx, &e.path) {
Some(tex) => {
p.image(tex.id(), tr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
None => {
p.rect_filled(tr, 3.0, Color32::from_rgb(0x24, 0x26, 0x2e));
icons::paint(&p, Rect::from_center_size(tr.center(), vec2(20.0, 20.0)), Icon::Comp, t.text_faint);
}
}
p.rect_stroke(tr, 3.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
let tx = tr.max.x + 12.0;
let text_clip = p.with_clip_rect(Rect::from_min_max(pos2(tx, r.min.y), pos2(r.max.x - date_w - 8.0, r.max.y)));
text_clip.text(pos2(tx, r.min.y + 20.0), Align2::LEFT_CENTER, &e.name, Tokens::semibold(13.0), if e.exists { Color32::WHITE } else { t.text_dim });
let sub = if e.exists { e.folder.clone() } else { format!("{} (missing)", e.folder) };
text_clip.text(pos2(tx, r.min.y + 40.0), Align2::LEFT_CENTER, sub, Tokens::ui(11.0), t.text_faint);
if let Some(d) = &e.modified {
p.text(pos2(r.max.x - date_w, r.min.y + 20.0), Align2::LEFT_CENTER, d, Tokens::ui(11.0), t.text_dim);
}
app.auto.add(&format!("home.recent.{}", e.index), r, &e.path);
if resp.clicked() {
actions.push(("file.openRecent", json!({"index": e.index})));
}
ry += row_h;
}
for (id, params) in actions {
let before = (app.session.path.clone(), app.session.revision);
match crate::menus::invoke(app, &ctx, id, params) {
Err(e) => app.ui.status = e,
// Leave Home unless only the list changed or a file dialog was cancelled.
Ok(_) => {
let cancelled = matches!(id, "file.open" | "file.import") && (app.session.path.clone(), app.session.revision) == before;
if id != "file.clearRecent" && !cancelled {
app.ui.start_screen = false;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recent_list_comes_from_settings() {
let mut prefs = effectcraft_engine::prefs::Prefs::default();
prefs.push_recent("/projects/a/Alpha.ecproj");
prefs.push_recent("/projects/b/Beta.ecproj");
let e = recent_entries(&prefs);
assert_eq!(e.len(), 2);
assert_eq!((e[0].name.as_str(), e[0].folder.as_str(), e[0].index), ("Beta", "/projects/b", 0));
assert_eq!(e[1].name, "Alpha");
assert!(!e[0].exists && e[0].modified.is_none());
// A real file has a date.
let dir = std::env::temp_dir().join(format!("ec-home-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let f = dir.join("Real.ecproj");
std::fs::write(&f, "{}").unwrap();
prefs.push_recent(&f.to_string_lossy());
let e = recent_entries(&prefs);
assert!(e[0].exists && e[0].modified.as_ref().is_some_and(|d| d.len() == 16), "{:?}", e[0]);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn dates_and_thumbnails() {
assert_eq!(format_utc(0), "1970-01-01 00:00");
assert_eq!(format_utc(1_790_000_000), "2026-09-21 14:13");
assert_eq!(format_utc(951_782_400), "2000-02-29 00:00");
let img = egui::ColorImage::new([200, 100], vec![Color32::from_rgb(10, 200, 30); 200 * 100]);
let text = encode_thumb(&img);
let back = decode_thumb(&text).unwrap();
assert_eq!(back.size, [THUMB_W, THUMB_H]);
// Letterboxed: the middle is the image, the top row is the background (2:1 into 16:9).
assert_eq!(back.pixels[THUMB_H / 2 * THUMB_W + THUMB_W / 2], Color32::from_rgb(10, 200, 30));
assert_ne!(back.pixels[THUMB_W / 2], Color32::from_rgb(10, 200, 30));
assert!(decode_thumb("abc").is_none());
assert_ne!(thumb_name("/a.ecproj"), thumb_name("/b.ecproj"));
}
#[test]
fn home_screen_registers_its_controls() {
let mut s = effectcraft_engine::Session::default();
s.prefs.push_recent("/projects/Alpha.ecproj");
let mut app = EffectcraftApp::new(s);
let ctx = egui::Context::default();
crate::theme::install(&ctx, &app.tokens);
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
ctx.run_ui(Default::default(), |ui| {
app.auto.begin_frame();
show(&mut app, ui, Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0)));
})
.textures_delta
.clear();
for id in [
"home.file.newProject",
"home.file.open",
"home.app.newComp",
"home.file.openDemoProject",
"home.help.discord",
"home.help.github",
"home.recent.0",
] {
assert!(app.auto.find(id).is_some(), "{id}");
}
}
}
+33 -6
View File
@@ -3,9 +3,13 @@
//!
//! The image is the layer's source and masks followed by its effects up to the View menu's
//! choice (by default the last Paint effect, as After Effects shows "Paint"). Dragging with a
//! paint tool records the stroke's points in layer space and, on release, runs `paint.stroke`
//! paint tools records the stroke's points in layer space and, on release, runs `paint.stroke`
//! at the current time (the drag's duration feeds Write On). Alt/Option-click with the Clone
//! Stamp sets the clone source.
//!
//! With a Roto Brush & Refine Edge effect the panel shows the effect's input with the matte
//! overlay, the segmentation span bar and the view / Freeze buttons; the Roto Brush and Refine
//! Edge tools paint their strokes here (see [`super::roto_tool`]).
use effectcraft_engine::effects::paint;
use effectcraft_engine::project::{Layer, LayerId};
@@ -46,9 +50,15 @@ pub fn current_layer(app: &EffectcraftApp) -> Option<Layer> {
comp.layer(id).cloned()
}
/// Number of effects shown by default: through the last Paint effect (none when there isn't one).
fn default_view(layer: &Layer) -> usize {
layer.effects().and_then(|fx| fx.groups().enumerate().filter(|(_, g)| paint::is_paint(g)).map(|(i, _)| i + 1).last()).unwrap_or(0)
/// Number of effects shown by default: the Roto Brush's input while a Roto Brush tool is active
/// (or when there is no Paint effect), else through the last Paint effect (none when there
/// isn't one).
fn default_view(layer: &Layer, tool: Tool) -> usize {
let paint = layer.effects().and_then(|fx| fx.groups().enumerate().filter(|(_, g)| paint::is_paint(g)).map(|(i, _)| i + 1).last());
match super::roto_tool::roto_index(layer) {
Some(r) if tool.roto_kind(false).is_some() || paint.is_none() => r,
_ => paint.unwrap_or(0),
}
}
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
@@ -64,7 +74,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let comp = app.session.project.comp(cid).cloned().unwrap_or_else(|| effectcraft_engine::project::Comp::new(1, 1, Default::default(), Default::default()));
let time = app.session.time();
let fx_count = layer.effects().map(|f| f.groups().count()).unwrap_or(0);
let view = app.ui.layer_view.map(|v| v.min(fx_count)).unwrap_or_else(|| default_view(&layer));
let view = app.ui.layer_view.map(|v| v.min(fx_count)).unwrap_or_else(|| default_view(&layer, app.ui.tool));
let roto = super::roto_tool::roto_index(&layer);
// Title strip.
let top = Rect::from_min_size(rect.min, vec2(rect.width(), 24.0));
@@ -90,9 +101,17 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
let tc = super::timecode(&app.session, &comp, time);
p.text(pos2(bar.max.x - 10.0, bar.center().y), Align2::RIGHT_CENTER, tc, Tokens::mono(12.0), t.timecode);
// Roto Brush: view / Freeze buttons and the segmentation span bar.
let mut canvas_bottom = bar.min.y;
if roto.is_some() {
super::roto_tool::bar_buttons(app, ui, &p, bar, vr.max.x + 12.0, &layer);
let sb = Rect::from_min_max(pos2(rect.min.x, bar.min.y - 18.0), pos2(rect.max.x, bar.min.y));
super::roto_tool::span_bar(app, ui, &p, sb, &comp, &layer);
canvas_bottom = sb.min.y;
}
// Canvas.
let area = Rect::from_min_max(pos2(rect.min.x, top.max.y), pos2(rect.max.x, bar.min.y));
let area = Rect::from_min_max(pos2(rect.min.x, top.max.y), pos2(rect.max.x, canvas_bottom));
p.rect_filled(area, 0.0, t.pasteboard);
let (w, h) = effectcraft_engine::render::source_size(&app.session.project, &layer);
let (lw, lh) = if w == 0 { (comp.width as f64, comp.height as f64) } else { (w as f64, h as f64) };
@@ -139,10 +158,18 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let r = Rect::from_min_max(to_screen([tx.rect[0], tx.rect[1]]), to_screen([tx.rect[2], tx.rect[3]]));
painter.image(tx.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
if roto.is_some_and(|r| r == view) {
super::roto_tool::draw_overlay(app, &ctx, &painter, &comp, &layer, scale, &to_screen);
}
painter.rect_stroke(frame, 0.0, Stroke::new(1.0, Color32::from_black_alpha(160)), StrokeKind::Outside);
app.auto.add("layerPanel.canvas", frame, &layer.name);
app.auto.add("layerPanel.area", area, "Layer panel");
// Interaction: Roto Brush / Refine Edge.
if app.ui.tool.roto_kind(false).is_some() {
super::roto_tool::interact(app, ui, &painter, area, &layer, zoom, &to_screen, &to_layer);
return;
}
// Interaction: paint tools.
let resp = ui.interact(area, egui::Id::new("layer-panel-interact"), Sense::click_and_drag());
let kind = app.ui.tool.paint_kind();
+2 -72
View File
@@ -1,10 +1,10 @@
//! Smaller panels: Preview, Audio, History, Markers, the Home screen and placeholders.
//! Smaller panels: Preview, Audio, History, Markers 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::icons::Icon;
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
@@ -223,73 +223,3 @@ pub fn markers(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
/// 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;
}
}
+8 -2
View File
@@ -1,6 +1,7 @@
//! Panel bodies.
pub mod anim_tools;
pub mod camera_tracker_ui;
pub mod comp_settings;
pub mod dialogs;
pub mod dialogs_3d;
@@ -8,10 +9,12 @@ pub mod effect_controls;
pub mod effects_presets;
pub mod essential;
pub mod expr_bar;
pub mod flowchart;
pub mod forms;
pub mod fx_widgets;
pub mod graph;
pub mod graph_tools;
pub mod home;
pub mod info;
pub mod key_dialogs;
pub mod layer_panel;
@@ -23,6 +26,8 @@ pub mod project;
pub mod properties;
pub mod puppet_tool;
pub mod render_queue;
pub mod roto_tool;
pub mod script_console;
pub mod settings;
pub mod shortcut_editor;
pub mod text_panels;
@@ -67,7 +72,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
match p {
PanelKind::Composition => {
if app.ui.start_screen {
misc::start_screen(app, ui, rect);
home::show(app, ui, rect);
} else {
viewer::show(app, ui, rect)
}
@@ -86,6 +91,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
PanelKind::History => misc::history(app, ui, rect),
PanelKind::Markers => misc::markers(app, ui, rect),
PanelKind::MaskInterpolation => anim_tools::mask_interpolation(app, ui, rect),
PanelKind::ScriptConsole => script_console::show(app, ui, rect),
PanelKind::Wiggler => anim_tools::wiggler(app, ui, rect),
PanelKind::Smoother => anim_tools::smoother(app, ui, rect),
PanelKind::MotionSketch => anim_tools::motion_sketch(app, ui, rect),
@@ -95,7 +101,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
PanelKind::Paint => paint_panels::paint(app, ui, rect),
PanelKind::Brushes => paint_panels::brushes(app, ui, rect),
PanelKind::EssentialGraphics => essential::show(app, ui, rect),
other => misc::placeholder(app, ui, rect, other),
PanelKind::Flowchart => flowchart::show(app, ui, rect),
}
}
+4 -10
View File
@@ -548,16 +548,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
dresp.on_hover_text("Project color depth: click to cycle 8/16/32 bpc, Alt-click for Project Settings");
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();
if widgets::icon_button(ui, tr, Icon::Trash, false, &t, egui::Id::new("ptrash")).on_hover_text("Delete selected project items").clicked()
&& !app.session.state.project_selection.is_empty()
{
actions.push(("project.delete".into(), json!({})));
}
app.auto.add("project.delete", tr, "Delete");
for (id, params) in actions {
+1 -1
View File
@@ -112,7 +112,7 @@ fn output_menu(it: &RenderQueueItem, available: &[OutputFormat]) -> Vec<(String,
v.push((mark(o.bitrate_kbps == kbps, &format!("Bitrate: {} Mbps", kbps / 1000)), json!({"bitrate": kbps})));
}
}
OutputFormat::JpegSequence => {
OutputFormat::JpegSequence | OutputFormat::WebM => {
v.push(("-".into(), Value::Null));
for q in [60u8, 80, 90, 100] {
v.push((mark(o.quality == q, &format!("Quality: {q}")), json!({"quality": q})));
+331
View File
@@ -0,0 +1,331 @@
//! Roto Brush and Refine Edge tools in the Layer panel: green foreground strokes, Alt/Option red
//! background strokes, Refine Edge strokes along soft edges; the matte overlay (Alpha Boundary in
//! pink, Alpha, Alpha Overlay), the segmentation span bar and the Freeze button.
use effectcraft_engine::effects::roto as fx;
use effectcraft_engine::project::{Comp, Layer};
use effectcraft_engine::render::{EvalCtx, RenderOpts, Renderer};
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde_json::json;
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
/// Position of the layer's first Roto Brush & Refine Edge effect.
pub fn roto_index(layer: &Layer) -> Option<usize> {
layer.effects()?.groups().position(|g| matches!(&g.kind, effectcraft_engine::project::GroupKind::Effect { effect } if effect == fx::ID))
}
fn roto_group(layer: &Layer) -> Option<&effectcraft_engine::project::PropGroup> {
layer.effects()?.groups().nth(roto_index(layer)?)
}
/// A stroke being drawn.
#[derive(Clone, Debug)]
struct Drag {
layer: u64,
kind: &'static str,
points: Vec<[f64; 2]>,
}
#[derive(Clone)]
struct Overlay {
key: (u64, u64, i64, u32, String),
tex: egui::TextureHandle,
rect: [f64; 4],
}
fn c32(c: [f64; 3], a: u8) -> Color32 {
Color32::from_rgba_unmultiplied((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8, a)
}
/// Draw the matte overlay of the Roto Brush on `layer` (the panel shows the effect's input).
pub fn draw_overlay(
app: &mut EffectcraftApp,
ctx: &egui::Context,
painter: &egui::Painter,
comp: &Comp,
layer: &Layer,
scale: f64,
to_screen: &dyn Fn([f64; 2]) -> Pos2,
) {
let Some(idx) = roto_index(layer) else { return };
let o = app.session.state.roto.clone();
if o.view == "none" {
return;
}
let Some(cid) = app.session.active_comp_id() else { return };
let time = app.session.time();
let key = (
app.session.revision,
layer.id.0,
time.0,
(scale * 1000.0) as u32,
format!("{}{:?}{:?}{}", o.view, o.overlay_color, o.boundary_color, o.overlay_opacity),
);
let id = egui::Id::new("roto-overlay");
let cached: Option<Overlay> = ctx.data(|d| d.get_temp(id));
let ov = match cached {
Some(c) if c.key == key => Some(c),
_ => {
let ectx = EvalCtx { project: &app.session.project, comp_id: cid, comp, time, expr: app.session.expr.as_deref(), footage: None };
let mut r = Renderer::new(&app.session.project, &*app.session.footage, RenderOpts { scale, ..Default::default() });
r.expr = app.session.expr.as_deref();
r.cache = Some(&app.session.layer_cache);
let (Some(inp), Some(out)) = (r.layer_input(&ectx, layer, idx), r.layer_input(&ectx, layer, idx + 1)) else { return };
let (w, h) = (inp.img.width as usize, inp.img.height as usize);
let a_at = |x: i64, y: i64| -> f32 {
// Output pixel at the same layer point.
let lx = (x as f64 + 0.5 - inp.offset[0]) / inp.scale;
let ly = (y as f64 + 0.5 - inp.offset[1]) / inp.scale;
let (ox, oy) = out.to_px([lx, ly]);
out.img.get(ox.floor() as i64, oy.floor() as i64)[3]
};
let alpha: Vec<f32> = (0..w * h).map(|i| a_at((i % w) as i64, (i / w) as i64)).collect();
let inside = |x: i64, y: i64| x >= 0 && y >= 0 && x < w as i64 && y < h as i64 && alpha[y as usize * w + x as usize] >= 0.5;
let mut px = vec![Color32::TRANSPARENT; w * h];
let bc = c32(o.boundary_color, 255);
let oc = c32(o.overlay_color, (o.overlay_opacity / 100.0 * 255.0).clamp(0.0, 255.0) as u8);
// View Search Region: the band around the boundary (yellow).
let search = roto_group(layer).filter(|g| g.prop("rotoBrushMatte/viewSearchRegion").is_some_and(|p| p.value.as_bool())).map(|g| {
let r = g.prop("rotoBrushMatte/searchRadius").map(|p| p.value.as_f64()).unwrap_or(15.0) * scale;
let bin: Vec<u8> = alpha.iter().map(|a| (*a >= 0.5) as u8).collect();
let sd = effectcraft_engine::track::roto::matting::signed_distance(&bin, w, h);
(sd, r as f32)
});
for y in 0..h as i64 {
for x in 0..w as i64 {
let i = y as usize * w + x as usize;
let a = alpha[i];
px[i] = match o.view.as_str() {
"alpha" => {
let v = (a.clamp(0.0, 1.0) * 255.0) as u8;
Color32::from_rgb(v, v, v)
}
"alphaOverlay" if a < 0.5 => oc,
"alphaOverlay" => Color32::TRANSPARENT,
_ => {
let me = a >= 0.5;
let edge = me && [(-1, 0), (1, 0), (0, -1), (0, 1)].iter().any(|(dx, dy)| !inside(x + dx, y + dy));
if edge { bc } else { Color32::TRANSPARENT }
}
};
if let Some((sd, r)) = &search {
let d = sd[i].abs();
if (d - r).abs() < 0.75 {
px[i] = Color32::from_rgb(255, 220, 0);
}
}
}
}
let img = egui::ColorImage { size: [w, h], pixels: px, source_size: egui::Vec2::new(w as f32, h as f32) };
let x0 = -inp.offset[0] / inp.scale;
let y0 = -inp.offset[1] / inp.scale;
let rect = [x0, y0, x0 + w as f64 / inp.scale, y0 + h as f64 / inp.scale];
let tex = ctx.load_texture("roto-overlay", img, egui::TextureOptions::NEAREST);
let c = Overlay { key, tex, rect };
ctx.data_mut(|d| d.insert_temp(id, c.clone()));
Some(c)
}
};
if let Some(ov) = ov {
let r = Rect::from_min_max(to_screen([ov.rect[0], ov.rect[1]]), to_screen([ov.rect[2], ov.rect[3]]));
painter.image(ov.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
}
/// Pointer handling for the Roto Brush / Refine Edge tools. Returns true when it handled input.
pub fn interact(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
painter: &egui::Painter,
area: Rect,
layer: &Layer,
zoom: f64,
to_screen: &dyn Fn([f64; 2]) -> Pos2,
to_layer: &dyn Fn(Pos2) -> [f64; 2],
) -> bool {
let ctx = ui.ctx().clone();
let mods = ui.input(|i| i.modifiers);
let Some(kind) = app.ui.tool.roto_kind(mods.alt) else { return false };
let resp = ui.interact(area, egui::Id::new("layer-panel-roto"), Sense::click_and_drag());
let o = app.session.state.roto.clone();
let refine = kind.starts_with("refine");
let dia = if refine { o.refine_diameter } else { o.diameter };
let col = match kind {
"fg" => Color32::from_rgb(40, 220, 60),
"bg" => Color32::from_rgb(235, 50, 40),
"refine" => Color32::from_rgb(110, 200, 255),
_ => Color32::from_rgb(255, 160, 60),
};
if let Some(hp) = resp.hover_pos() {
let lp = to_layer(hp);
app.pointer_comp = Some([lp[0] as f32, lp[1] as f32]);
ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
let r = (dia * 0.5 * zoom) as f32;
painter.circle_stroke(hp, r, Stroke::new(1.5, col));
let sign = if kind == "bg" || kind == "refineErase" { "−" } else { "+" };
painter.text(hp, Align2::CENTER_CENTER, sign, Tokens::semibold(12.0), col);
}
let did = egui::Id::new("layer-panel-roto-drag");
if resp.drag_started()
&& let Some(pos) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
{
ctx.data_mut(|d| d.insert_temp(did, Drag { layer: layer.id.0, kind, points: vec![to_layer(pos)] }));
}
if let Some(mut d) = ctx.data(|d| d.get_temp::<Drag>(did)) {
if let Some(pos) = resp.interact_pointer_pos() {
let lp = to_layer(pos);
let last = d.points.last().copied().unwrap_or(lp);
if (lp[0] - last[0]).hypot(lp[1] - last[1]) * zoom >= 1.5 {
d.points.push(lp);
ctx.data_mut(|dd| dd.insert_temp(did, d.clone()));
}
}
let width = ((dia * zoom) as f32).max(1.0);
let pts: Vec<Pos2> = d.points.iter().map(|q| to_screen(*q)).collect();
let c = col.gamma_multiply(0.6);
if pts.len() == 1 {
painter.circle_filled(pts[0], width / 2.0, c);
} else {
painter.add(egui::Shape::line(pts, Stroke::new(width, c)));
}
if resp.drag_stopped() {
ctx.data_mut(|dd| dd.remove::<Drag>(did));
run_stroke(app, d.layer, d.kind, &d.points, dia / 2.0);
}
} else if resp.clicked()
&& let Some(pos) = resp.interact_pointer_pos()
{
run_stroke(app, layer.id.0, kind, &[to_layer(pos)], dia / 2.0);
}
true
}
fn run_stroke(app: &mut EffectcraftApp, layer: u64, kind: &str, points: &[[f64; 2]], radius: f64) {
let r = app.session.execute("roto.stroke", json!({"layer": layer, "kind": kind, "points": points, "radius": radius}));
if let Err(e) = r {
app.ui.status = e.to_string();
}
}
/// The segmentation span bar (above the panel's bottom bar): the layer's frames, the span, the
/// base frame (yellow), computed frames (green) and stroke frames. Click to go to a frame; drag
/// the span's ends to change it.
pub fn span_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, r: Rect, comp: &Comp, layer: &Layer) {
let t = app.tokens;
let Some(g) = roto_group(layer) else { return };
let Some(cid) = app.session.active_comp_id() else { return };
let uid = g.uid;
let params = effectcraft_engine::effects::flatten_params(g, &mut |p| p.value.clone());
let d = fx::data(&params);
p.rect_filled(r, 0.0, t.panel_bg);
let lim = effectcraft_engine::roto::frame_limits(comp, layer);
let n = (lim[1] - lim[0] + 1).max(1) as f32;
let track = Rect::from_min_max(pos2(r.min.x + 10.0, r.min.y + 4.0), pos2(r.max.x - 10.0, r.max.y - 4.0));
let x_of = |f: f64| track.min.x + ((f - lim[0] as f64) / n as f64) as f32 * track.width();
let f_of = |x: f32| (lim[0] as f64 + ((x - track.min.x) / track.width()).clamp(0.0, 0.9999) as f64 * n as f64).floor() as i64;
p.rect_filled(track, 2.0, t.pasteboard);
if let Some(base) = d.base {
let sp = Rect::from_min_max(pos2(x_of(d.span[0] as f64), track.min.y), pos2(x_of(d.span[1] as f64 + 1.0), track.max.y));
let frozen = fx::is_frozen(&params);
p.rect_filled(sp, 2.0, if frozen { Color32::from_rgb(60, 110, 190) } else { Color32::from_rgb(90, 90, 96) });
for (f, done) in app.session.roto_computed(cid, layer.id, uid) {
if done {
let cr = Rect::from_min_max(pos2(x_of(f as f64), track.max.y - 4.0), pos2(x_of(f as f64 + 1.0), track.max.y));
p.rect_filled(cr, 0.0, Color32::from_rgb(70, 200, 90));
}
}
for f in d.stroke_frames() {
let x = x_of(f as f64 + 0.5);
p.line_segment([pos2(x, track.min.y), pos2(x, track.min.y + 5.0)], Stroke::new(2.0, Color32::WHITE));
}
let bx = x_of(base as f64 + 0.5);
p.rect_filled(Rect::from_center_size(pos2(bx, track.center().y), vec2(6.0, track.height())), 1.0, Color32::from_rgb(240, 200, 40));
}
// Current time.
let fps = comp.frame_rate.as_f64();
let cur = fx::frame_of(layer.layer_time(app.session.time()).seconds(), fps);
let cx = x_of(cur as f64 + 0.5);
p.line_segment([pos2(cx, r.min.y), pos2(cx, r.max.y)], Stroke::new(1.0, t.timecode));
p.rect_stroke(track, 2.0, Stroke::new(1.0, Color32::from_black_alpha(140)), StrokeKind::Outside);
app.auto.add("layerPanel.rotoSpan", track, "Segmentation span");
let resp = ui.interact(track, egui::Id::new("roto-span-bar"), Sense::click_and_drag());
let hid = egui::Id::new("roto-span-handle");
if resp.drag_started()
&& let (Some(pos), Some(_)) = (resp.interact_pointer_pos(), d.base)
{
let (a, b) = (x_of(d.span[0] as f64), x_of(d.span[1] as f64 + 1.0));
let h = if (pos.x - a).abs() < 6.0 {
1
} else if (pos.x - b).abs() < 6.0 {
2
} else {
0
};
ui.ctx().data_mut(|m| m.insert_temp(hid, h));
}
let handle: i32 = ui.ctx().data(|m| m.get_temp(hid)).unwrap_or(0);
if let Some(pos) = resp.interact_pointer_pos() {
let f = f_of(pos.x);
if handle == 0 && (resp.clicked() || resp.dragged()) {
let t = layer.comp_time(comp.frame_rate.tick_of(f));
let _ = app.session.execute("time.set", json!({"time": t.seconds()}));
}
if handle != 0 && resp.dragged() {
p.line_segment([pos2(pos.x, track.min.y), pos2(pos.x, track.max.y)], Stroke::new(2.0, Color32::from_rgb(240, 200, 40)));
}
if handle != 0 && resp.drag_stopped() {
let k = if handle == 1 { "start" } else { "end" };
if let Err(e) = app.session.execute("roto.span", json!({"layer": layer.id.0, "effect": uid, k: f})) {
app.ui.status = e.to_string();
}
}
}
if resp.drag_stopped() {
ui.ctx().data_mut(|m| m.remove::<i32>(hid));
}
}
/// View-mode toggles and Freeze / Propagate buttons in the Layer panel's bottom bar, from `x`.
pub fn bar_buttons(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, bar: Rect, x: f32, layer: &Layer) {
let t = app.tokens;
let mut x = x;
let view = app.session.state.roto.view.clone();
for (id, label) in [("alpha", "Alpha"), ("alphaBoundary", "Boundary"), ("alphaOverlay", "Overlay")] {
let r = Rect::from_min_size(pos2(x, bar.center().y - 10.0), vec2(66.0, 20.0));
let on = view == id;
if widgets::text_button(ui, r, label, on, &t, egui::Id::new(("roto-view", id))).clicked() {
let v = if on { "none" } else { id };
let _ = app.session.execute("roto.options", json!({"view": v}));
}
app.auto.add(&format!("layerPanel.roto.view.{id}"), r, label);
x += 70.0;
}
let Some(g) = roto_group(layer) else { return };
let uid = g.uid;
let params = effectcraft_engine::effects::flatten_params(g, &mut |p| p.value.clone());
let frozen = fx::is_frozen(&params);
let running = app.session.is_roto_running();
x += 8.0;
let r = Rect::from_min_size(pos2(x, bar.center().y - 10.0), vec2(74.0, 20.0));
let label = if frozen { "Unfreeze" } else { "Freeze" };
if widgets::text_button(ui, r, label, frozen, &t, egui::Id::new(("roto-freeze", uid))).clicked() {
let id = if frozen { "roto.unfreeze" } else { "roto.freeze" };
if let Err(e) = app.session.execute(id, json!({"layer": layer.id.0, "effect": uid})) {
app.ui.status = e.to_string();
}
}
app.auto.add("layerPanel.roto.freeze", r, label);
x += 80.0;
if running {
let r = Rect::from_min_size(pos2(x, bar.center().y - 10.0), vec2(60.0, 20.0));
if widgets::text_button(ui, r, "Stop", false, &t, egui::Id::new("roto-stop")).clicked() {
let _ = app.session.execute("roto.cancel", json!({}));
}
app.auto.add("layerPanel.roto.stop", r, "Stop");
if let Some(pr) = app.session.roto_progress() {
p.text(pos2(r.max.x + 8.0, bar.center().y), Align2::LEFT_CENTER, pr.banner(), Tokens::ui(11.5), t.text_dim);
}
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Window ▸ Script Console: a JavaScript REPL over the After Effects-style scripting object model
//! (`app.project`, comps, layers, properties…). Each run goes through the `script.run` command
//! in the console's persistent context, so variables survive between runs; edits are undoable.
use egui::{Align2, Rect, Sense, pos2, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::EffectcraftApp;
use crate::theme::Tokens;
/// One line of console output.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ConsoleLine {
pub text: String,
/// `input`, `output`, `result` or `error`.
pub kind: String,
}
/// Script Console state (serde, so agents can read it).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ScriptConsole {
pub input: String,
pub log: Vec<ConsoleLine>,
/// Previously run inputs (Up/Down recall).
#[serde(default)]
pub history: Vec<String>,
}
impl ScriptConsole {
fn push(&mut self, kind: &str, text: &str) {
for l in text.lines() {
self.log.push(ConsoleLine { text: l.to_string(), kind: kind.to_string() });
}
if self.log.len() > 2000 {
let extra = self.log.len() - 2000;
self.log.drain(..extra);
}
}
/// Record a `script.run` result.
pub fn record(&mut self, code: &str, r: &Result<Value, String>) {
self.push("input", &format!("> {}", code.trim()));
match r {
Ok(v) => {
if let Some(o) = v["output"].as_str().filter(|o| !o.is_empty()) {
self.push("output", o);
}
if let Some(e) = v.get("error").filter(|e| !e.is_null()) {
let line = e["line"].as_u64().map(|l| format!("line {l}: ")).unwrap_or_default();
self.push("error", &format!("{line}{}", e["message"].as_str().unwrap_or("error")));
} else if !v["result"].is_null() {
self.push("result", &v["result"].to_string());
}
}
Err(e) => self.push("error", e),
}
}
}
/// Run the console input.
pub fn run(app: &mut EffectcraftApp, ctx: &egui::Context) {
let code = app.ui.script_console.input.trim().to_string();
if code.is_empty() {
return;
}
let r = crate::menus::invoke(app, ctx, "script.run", json!({"code": code, "name": "Script Console", "console": true}));
let con = &mut app.ui.script_console;
con.record(&code, &r);
if con.history.last() != Some(&code) {
con.history.push(code);
}
con.input.clear();
}
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let input_h = 86.0;
let bar_h = 26.0;
let out_rect = Rect::from_min_max(rect.min, pos2(rect.max.x, rect.max.y - input_h - bar_h));
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(out_rect, 0.0, t.field_bg);
// Output, newest at the bottom.
let line_h = 16.0;
let visible = ((out_rect.height() - 8.0) / line_h).max(1.0) as usize;
let log = &app.ui.script_console.log;
let start = log.len().saturating_sub(visible);
for (i, l) in log[start..].iter().enumerate() {
let color = match l.kind.as_str() {
"error" => t.danger,
"input" => t.text_faint,
"result" => t.accent,
_ => t.text,
};
p.text(pos2(out_rect.min.x + 8.0, out_rect.min.y + 4.0 + i as f32 * line_h), Align2::LEFT_TOP, &l.text, Tokens::mono(11.5), color);
}
if log.is_empty() {
p.text(
out_rect.center(),
Align2::CENTER_CENTER,
"JavaScript with the After Effects scripting object model — try app.project.numItems",
Tokens::ui(12.0),
t.text_faint,
);
}
app.auto.add("scriptConsole.output", out_rect, "Script Console output");
// Input.
let in_rect = Rect::from_min_size(pos2(rect.min.x + 4.0, out_rect.max.y + 4.0), vec2(rect.width() - 8.0, input_h - 8.0));
let mut run_now = false;
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(in_rect));
let te = egui::TextEdit::multiline(&mut app.ui.script_console.input)
.id(egui::Id::new("script-console-input"))
.font(Tokens::mono(12.0))
.desired_width(in_rect.width())
.desired_rows(4)
.hint_text("Script… (⌘/Ctrl+Enter runs)");
let resp = child.add_sized(in_rect.size(), te);
if resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.command) {
run_now = true;
}
app.auto.add("scriptConsole.input", in_rect, "Script Console input");
// Buttons.
let bar = Rect::from_min_size(pos2(rect.min.x, rect.max.y - bar_h), vec2(rect.width(), bar_h));
let run_r = Rect::from_min_size(pos2(bar.max.x - 64.0, bar.min.y + 2.0), vec2(56.0, 20.0));
let clear_r = Rect::from_min_size(pos2(bar.max.x - 128.0, bar.min.y + 2.0), vec2(56.0, 20.0));
let run_resp = ui.interact(run_r, egui::Id::new("script-console-run"), Sense::click());
p.rect_filled(run_r, 3.0, if run_resp.hovered() { t.accent_hover } else { t.accent });
p.text(run_r.center(), Align2::CENTER_CENTER, "Run", Tokens::ui(12.0), egui::Color32::WHITE);
let clear_resp = ui.interact(clear_r, egui::Id::new("script-console-clear"), Sense::click());
p.rect_stroke(clear_r, 3.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
p.text(clear_r.center(), Align2::CENTER_CENTER, "Clear", Tokens::ui(12.0), t.text);
app.auto.add("scriptConsole.run", run_r, "Run");
app.auto.add("scriptConsole.clear", clear_r, "Clear");
if run_resp.clicked() {
run_now = true;
}
if clear_resp.clicked() {
app.ui.script_console.log.clear();
}
if run_now {
let ctx = ui.ctx().clone();
run(app, &ctx);
}
}
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -130,11 +130,14 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let cur = current(app);
let can_track = has_comp && source.is_some();
// Track Camera / Warp Stabilizer (not available) and Track Motion / Stabilize Motion.
// Track Camera / Warp Stabilizer and Track Motion / Stabilize Motion.
let r1 = Rect::from_min_size(pos2(x0, y), vec2(half, 22.0));
let r2 = Rect::from_min_size(pos2(x0 + half + 6.0, y), vec2(half, 22.0));
let src_p = source.map(|l| json!({"layer": l.0})).unwrap_or_else(|| json!({}));
button(app, ui, r1, "Track Camera", false, "tracker.trackCamera");
let can_camera = app.session.is_enabled("track.camera") && !app.session.is_camera_analyzing();
if button(app, ui, r1, "Track Camera", can_camera, "tracker.trackCamera") {
run(app, &ctx, "track.camera", json!({}));
}
let can_warp = app.session.is_enabled("track.warpStabilizer") && !app.session.is_warp_analyzing();
if button(app, ui, r2, "Warp Stabilizer", can_warp, "tracker.warpStabilizer") {
run(app, &ctx, "track.warpStabilizer", json!({}));
+3
View File
@@ -1148,6 +1148,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.session.open_comp(*item);
}
}
// 3D Camera Tracker points, targets and their menu (on top of the viewer's gestures while
// the effect is selected), and its analysis banner.
super::camera_tracker_ui::viewer_hook(app, ui, &painter, &map, &ectx, &|c, l| l2c(c, l).0);
// Effect point controls and crosshair/eyedropper picks (on top of the viewer's gestures).
crate::panels::effect_controls::viewer_hook(app, ui, &painter, &map, &ectx, &|c, l| l2c(c, l).0);
+40 -3
View File
@@ -34,6 +34,7 @@ pub enum Tool {
Clone,
Eraser,
RotoBrush,
RefineEdge,
Puppet,
PuppetStarch,
PuppetBend,
@@ -58,10 +59,10 @@ impl Tool {
&[Tool::Brush],
&[Tool::Clone],
&[Tool::Eraser],
&[Tool::RotoBrush],
&[Tool::RotoBrush, Tool::RefineEdge],
&[Tool::Puppet, Tool::PuppetStarch, Tool::PuppetBend, Tool::PuppetAdvanced, Tool::PuppetOverlap],
];
pub const ALL: [Tool; 29] = [
pub const ALL: [Tool; 30] = [
Tool::Selection,
Tool::Hand,
Tool::Zoom,
@@ -86,6 +87,7 @@ impl Tool {
Tool::Clone,
Tool::Eraser,
Tool::RotoBrush,
Tool::RefineEdge,
Tool::Puppet,
Tool::PuppetStarch,
Tool::PuppetBend,
@@ -118,6 +120,7 @@ impl Tool {
Tool::Clone => "Clone Stamp Tool",
Tool::Eraser => "Eraser Tool",
Tool::RotoBrush => "Roto Brush Tool",
Tool::RefineEdge => "Refine Edge Tool",
Tool::Puppet => "Puppet Position Pin Tool",
Tool::PuppetStarch => "Puppet Starch Pin Tool",
Tool::PuppetBend => "Puppet Bend Pin Tool",
@@ -139,7 +142,7 @@ impl Tool {
Tool::Pen | Tool::PenAdd | Tool::PenDelete | Tool::PenConvert | Tool::MaskFeather => Some("G"),
Tool::Type | Tool::TypeVertical => Some("Cmd+T"),
Tool::Brush | Tool::Clone | Tool::Eraser => Some("Cmd+B"),
Tool::RotoBrush => Some("Alt+W"),
Tool::RotoBrush | Tool::RefineEdge => Some("Alt+W"),
Tool::Puppet | Tool::PuppetStarch | Tool::PuppetBend | Tool::PuppetAdvanced | Tool::PuppetOverlap => Some("Cmd+P"),
}
}
@@ -169,6 +172,7 @@ impl Tool {
Tool::Clone => Icon::Clone,
Tool::Eraser => Icon::Eraser,
Tool::RotoBrush => Icon::RotoBrush,
Tool::RefineEdge => Icon::RefineEdge,
Tool::Puppet | Tool::PuppetStarch | Tool::PuppetBend | Tool::PuppetAdvanced | Tool::PuppetOverlap => Icon::Puppet,
}
}
@@ -187,6 +191,17 @@ impl Tool {
_ => return None,
})
}
/// Roto Brush / Refine Edge: the stroke kind they paint (`roto.stroke` kind), without and
/// with Alt/Option.
pub fn roto_kind(self, alt: bool) -> Option<&'static str> {
Some(match (self, alt) {
(Tool::RotoBrush, false) => "fg",
(Tool::RotoBrush, true) => "bg",
(Tool::RefineEdge, false) => "refine",
(Tool::RefineEdge, true) => "refineErase",
_ => return None,
})
}
/// Paint tools, with their stroke kind (`paint.stroke` kind).
pub fn paint_kind(self) -> Option<&'static str> {
Some(match self {
@@ -360,6 +375,18 @@ pub struct TimelineState {
/// Properties whose inline expression editor is collapsed.
#[serde(default)]
pub expr_closed: BTreeSet<u64>,
/// Visible optional columns (column header right-click ▸ Columns): `av`, `keys`, `label`,
/// `num`, `comment`, `switches`, `parent`, `in`, `out`, `duration`, `stretch`. The name
/// column is always shown; Modes follows `show_modes` (F4).
#[serde(default = "default_tl_columns")]
pub columns: BTreeSet<String>,
/// The name column shows Source Name instead of Layer Name (click its header).
#[serde(default)]
pub source_name: bool,
}
pub fn default_tl_columns() -> BTreeSet<String> {
["av", "label", "num", "switches", "parent"].map(String::from).into_iter().collect()
}
fn value_graph() -> String {
@@ -391,6 +418,8 @@ impl Default for TimelineState {
graph_reference: false,
graph_transform_box: true,
expr_closed: BTreeSet::new(),
columns: default_tl_columns(),
source_name: false,
}
}
}
@@ -476,6 +505,9 @@ impl Default for AnimToolsState {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UiState {
pub tool: Tool,
/// Window ▸ Script Console input, output and history.
#[serde(default)]
pub script_console: crate::panels::script_console::ScriptConsole,
/// Tool shown in each toolbar slot.
pub slot_tools: Vec<Tool>,
pub workspace: String,
@@ -570,12 +602,16 @@ pub struct UiState {
/// Composition Mini-Flowchart popup position (open when set).
#[serde(default)]
pub mini_flowchart: Option<[f32; 2]>,
/// Flowchart panel options (layers, effects, solids, direction, root comp).
#[serde(default)]
pub flowchart: crate::panels::flowchart::FlowOptions,
}
impl Default for UiState {
fn default() -> Self {
UiState {
tool: Tool::Selection,
script_console: Default::default(),
slot_tools: Tool::SLOTS.iter().map(|s| s[0]).collect(),
workspace: "Default".into(),
dock: crate::dock::workspace("Default"),
@@ -620,6 +656,7 @@ impl Default for UiState {
layer_view: None,
anim_tools: AnimToolsState::default(),
mini_flowchart: None,
flowchart: Default::default(),
}
}
}
+3
View File
@@ -60,6 +60,8 @@ pub struct Tokens {
pub cti: Color32,
pub work_area: Color32,
pub cache_green: Color32,
/// Timeline cache bar for frames held in the disk cache (not in RAM).
pub cache_blue: Color32,
pub keyframe: Color32,
pub keyframe_selected: Color32,
pub pasteboard: Color32,
@@ -108,6 +110,7 @@ impl Tokens {
cti: Color32::from_rgb(0x2d, 0x8c, 0xeb),
work_area: Color32::from_rgb(0x4a, 0x4a, 0x4a),
cache_green: Color32::from_rgb(0x3c, 0xa6, 0x4c),
cache_blue: Color32::from_rgb(0x3a, 0x6f, 0xd8),
keyframe: Color32::from_rgb(0xa8, 0xa8, 0xa8),
keyframe_selected: Color32::from_rgb(0x3d, 0x8f, 0xf5),
pasteboard: Color32::from_rgb(0x1a, 0x1a, 0x1a),