Merge main (engine menu tree) into M9.6; wire text animation menus

Animation ▸ Animate Text (Enable Per-character 3D, every animator property,
Fill/Stroke Color RGB/Hue/Saturation/Brightness/Opacity submenus, Line Anchor,
Character Value), Add Text Selector ▸ Range/Wiggly/Expression (text.addSelector
now supports all kinds) and Text Animation Presets after Browse Presets, in the
engine menu tree. Stubs replaced: text.perCharacter3d, animatorLineAnchor,
animatorCharacterValue, addWigglySelector, addExpressionSelector.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 00:44:20 -04:00
co-authored by Claude Opus 5.5
58 changed files with 8571 additions and 396 deletions
+345
View File
@@ -0,0 +1,345 @@
//! Real-time audio preview.
//!
//! The frontend owns no audio API: the native app supplies an [`AudioDevice`] (cpal) through
//! [`crate::Hooks::audio_device`]. During preview playback an [`AudioPlayback`] runs a feeder
//! thread that mixes the composition ahead of the device with the same mixdown export uses
//! (`effectcraft_render::audio::mix_comp`: Audio switch, solo, Audio Levels, audio effects) and
//! pushes it into an [`AudioFeed`]; the device callback pulls from the feed.
//!
//! **A/V sync:** while audio plays, the audio clock drives playback. The clock is the number of
//! sample frames the device has actually consumed (underruns do not advance it) minus the
//! device's output latency, mapped through the work-area loop ([`clock_sample`]); the viewer
//! shows the comp frame at that sample ([`frame_of_sample`]), dropping video frames rather
//! than drifting.
//!
//! The feed also tracks per-channel peaks for the Audio panel's VU meters ([`Meter`]).
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use effectcraft_engine::project::ItemId;
use effectcraft_engine::time::{FrameRate, Tick};
use crate::frames::RenderSource;
/// An audio output (implemented by the native app with cpal).
pub trait AudioDevice: Send {
/// Device sample rate in Hz.
fn sample_rate(&self) -> u32;
/// Start pulling interleaved stereo frames from `feed` (see [`AudioFeed::pull`]).
fn start(&mut self, feed: Arc<AudioFeed>) -> Result<(), String>;
fn stop(&mut self);
/// Output latency in sample frames (device buffering), for A/V sync.
fn latency_frames(&self) -> u64 {
0
}
}
/// Opens the default output device (`None` when there is none).
pub type AudioDeviceFactory = Box<dyn Fn() -> Option<Box<dyn AudioDevice>>>;
/// Lock-protected sample queue between the feeder thread and the device callback.
#[derive(Default)]
pub struct AudioFeed {
queue: Mutex<VecDeque<f32>>,
/// Sample frames handed to the device (real audio only: underruns do not count).
consumed: AtomicU64,
/// Peak |sample| per channel since the last [`AudioFeed::take_peaks`] (f32 bits).
peak: [AtomicU32; 2],
/// The feeder reached the end of a non-looping span.
finished: AtomicBool,
}
impl AudioFeed {
/// Fill `out` (interleaved stereo) from the queue; silence where the queue runs dry.
pub fn pull(&self, out: &mut [f32]) {
let mut real = 0usize;
let mut pk = [0.0f32; 2];
if let Ok(mut q) = self.queue.lock() {
let n = q.len().min(out.len()) & !1;
for (i, (o, s)) in out.iter_mut().zip(q.drain(..n)).enumerate() {
*o = s;
pk[i & 1] = pk[i & 1].max(s.abs());
}
real = n;
}
out[real..].iter_mut().for_each(|o| *o = 0.0);
self.consumed.fetch_add((real / 2) as u64, Ordering::Relaxed);
for (c, v) in pk.into_iter().enumerate() {
let _ = self.peak[c].fetch_update(Ordering::Relaxed, Ordering::Relaxed, |old| (v > f32::from_bits(old)).then_some(v.to_bits()));
}
}
pub fn push(&self, samples: &[f32]) {
if let Ok(mut q) = self.queue.lock() {
q.extend(samples.iter().copied());
}
}
/// Sample frames waiting in the queue.
pub fn queued_frames(&self) -> usize {
self.queue.lock().map(|q| q.len() / 2).unwrap_or(0)
}
pub fn consumed(&self) -> u64 {
self.consumed.load(Ordering::Relaxed)
}
/// Peak |sample| per channel since the last call (resets them).
pub fn take_peaks(&self) -> [f32; 2] {
[f32::from_bits(self.peak[0].swap(0, Ordering::Relaxed)), f32::from_bits(self.peak[1].swap(0, Ordering::Relaxed))]
}
pub fn finished(&self) -> bool {
self.finished.load(Ordering::Relaxed) && self.queued_frames() == 0
}
}
/// What a preview plays, in comp sample indices at the device rate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlaySpan {
pub start: i64,
/// Work area [wa, wb).
pub wa: i64,
pub wb: i64,
pub looping: bool,
}
impl PlaySpan {
/// Span for comp times: start, work area [wa, wb).
pub fn new(start: Tick, wa: Tick, wb: Tick, looping: bool, rate: u32) -> PlaySpan {
let r = rate as i64;
PlaySpan { start: start.to_units_floor(r), wa: wa.to_units_floor(r), wb: wb.to_units_floor(r).max(wa.to_units_floor(r) + 1), looping }
}
}
/// The comp sample index audible now: `consumed` frames played by the device minus its
/// `latency`, from the span start, wrapped into the work area when looping (clamped at its end
/// otherwise).
pub fn clock_sample(span: &PlaySpan, consumed: u64, latency: u64) -> i64 {
let s = span.start + consumed.saturating_sub(latency) as i64;
if s < span.wb {
return s;
}
if span.looping { span.wa + (s - span.wb).rem_euclid((span.wb - span.wa).max(1)) } else { span.wb - 1 }
}
/// Comp time of sample index `s` at `rate` Hz.
pub fn sample_time(s: i64, rate: u32) -> Tick {
Tick::from_units(s, rate.max(1) as i64)
}
/// The comp frame showing sample `s` (the frame whose interval contains it).
pub fn frame_of_sample(s: i64, rate: u32, fps: FrameRate) -> i64 {
fps.frame_at(sample_time(s, rate))
}
/// Block size the feeder mixes at a time.
const BLOCK: usize = 1024;
/// A running audio preview: device + feeder thread.
pub struct AudioPlayback {
pub feed: Arc<AudioFeed>,
device: Box<dyn AudioDevice>,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
pub rate: u32,
pub span: PlaySpan,
}
impl AudioPlayback {
/// Start mixing `comp` over `span` into `device`.
pub fn start(
mut device: Box<dyn AudioDevice>,
src: RenderSource,
comp: ItemId,
start: Tick,
wa: Tick,
wb: Tick,
looping: bool,
) -> Result<AudioPlayback, String> {
let rate = device.sample_rate().max(8000);
let span = PlaySpan::new(start, wa, wb, looping, rate);
let feed = Arc::new(AudioFeed::default());
let stop = Arc::new(AtomicBool::new(false));
// Prime ~50 ms so the device does not start on an empty queue.
let mut cursor = span.start;
let prime = (rate as usize / 20).div_ceil(BLOCK);
for _ in 0..prime {
cursor = feed_block(&src, comp, &feed, &span, cursor, rate);
}
let thread = {
let (feed, stop) = (feed.clone(), stop.clone());
std::thread::Builder::new()
.name("ec-audio-feed".into())
.spawn(move || {
// Keep ~200 ms queued ahead of the device.
let target = rate as usize / 5;
while !stop.load(Ordering::Relaxed) {
if feed.queued_frames() < target && !feed.finished.load(Ordering::Relaxed) {
cursor = feed_block(&src, comp, &feed, &span, cursor, rate);
} else {
std::thread::sleep(std::time::Duration::from_millis(4));
}
}
})
.map_err(|e| e.to_string())?
};
device.start(feed.clone())?;
Ok(AudioPlayback { feed, device, stop, thread: Some(thread), rate, span })
}
/// The comp sample index audible now.
pub fn clock(&self) -> i64 {
clock_sample(&self.span, self.feed.consumed(), self.device.latency_frames())
}
pub fn finished(&self) -> bool {
self.feed.finished()
}
pub fn stop(&mut self) {
self.device.stop();
self.stop.store(true, Ordering::Relaxed);
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
impl Drop for AudioPlayback {
fn drop(&mut self) {
self.stop();
}
}
/// Mix one block at `cursor` into the feed; returns the next cursor (wrapping or finishing at
/// the work-area end).
fn feed_block(src: &RenderSource, comp: ItemId, feed: &AudioFeed, span: &PlaySpan, cursor: i64, rate: u32) -> i64 {
let mut cursor = cursor;
if cursor >= span.wb {
if !span.looping {
feed.finished.store(true, Ordering::Relaxed);
return cursor;
}
cursor = span.wa;
}
let n = ((span.wb - cursor) as usize).min(BLOCK);
let buf = effectcraft_engine::render::audio::mix_comp(&src.project, src.footage.as_ref(), src.expr.as_deref(), comp, sample_time(cursor, rate), n, rate);
feed.push(&buf);
cursor + n as i64
}
/// VU meter state for the Audio panel: smoothed level with a falling decay and peak hold, in
/// dBFS per channel.
#[derive(Clone, Copy, Debug)]
pub struct Meter {
pub level_db: [f32; 2],
pub peak_db: [f32; 2],
peak_at: [f64; 2],
/// Clip indicators (latched until clicked / playback restarts).
pub clipped: [bool; 2],
last: f64,
}
impl Default for Meter {
fn default() -> Self {
Meter { level_db: [METER_FLOOR; 2], peak_db: [METER_FLOOR; 2], peak_at: [0.0; 2], clipped: [false; 2], last: 0.0 }
}
}
/// Bottom of the meter scale (dB).
pub const METER_FLOOR: f32 = -48.0;
/// How long the peak marker holds (s) and how fast levels fall (dB/s).
const PEAK_HOLD: f64 = 1.5;
const FALL_DB_PER_S: f32 = 30.0;
pub fn to_db(v: f32) -> f32 {
if v <= 1e-6 { METER_FLOOR } else { (20.0 * v.log10()).max(METER_FLOOR) }
}
impl Meter {
/// Feed the peaks measured since the last update at wall time `now` (seconds).
pub fn update(&mut self, peaks: [f32; 2], now: f64) {
let dt = if self.last > 0.0 { (now - self.last).clamp(0.0, 0.5) as f32 } else { 0.0 };
self.last = now;
for c in 0..2 {
let db = to_db(peaks[c]);
self.level_db[c] = db.max(self.level_db[c] - FALL_DB_PER_S * dt);
if db >= self.peak_db[c] || now - self.peak_at[c] > PEAK_HOLD {
self.peak_db[c] = db.max(self.level_db[c]);
self.peak_at[c] = now;
}
if peaks[c] >= 1.0 {
self.clipped[c] = true;
}
}
}
/// Anything to animate (levels still falling)?
pub fn active(&self) -> bool {
self.level_db.iter().chain(self.peak_db.iter()).any(|d| *d > METER_FLOOR)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clock_follows_consumed_frames_and_loops() {
let span = PlaySpan { start: 4800, wa: 0, wb: 48000, looping: true };
assert_eq!(clock_sample(&span, 0, 0), 4800);
// Latency holds the clock back until the device has played through its buffer.
assert_eq!(clock_sample(&span, 512, 1024), 4800);
assert_eq!(clock_sample(&span, 2048, 1024), 4800 + 1024);
// Wrap at the work-area end.
assert_eq!(clock_sample(&span, 48000 - 4800 + 100, 0), 100);
let once = PlaySpan { looping: false, ..span };
assert_eq!(clock_sample(&once, 100_000, 0), 47999);
}
#[test]
fn frame_mapping_matches_comp_frames() {
let fps = FrameRate::new(30, 1);
// 48 kHz at 30 fps: 1600 samples per frame.
assert_eq!(frame_of_sample(0, 48000, fps), 0);
assert_eq!(frame_of_sample(1599, 48000, fps), 0);
assert_eq!(frame_of_sample(1600, 48000, fps), 1);
assert_eq!(frame_of_sample(48000 * 2, 48000, fps), 60);
let span = PlaySpan::new(Tick::from_seconds_f64(1.0), Tick::ZERO, Tick::from_seconds_f64(2.0), true, 48000);
assert_eq!((span.start, span.wa, span.wb), (48000, 0, 96000));
// 29.97: frame boundaries are fractional in samples.
let ntsc = FrameRate::new(30000, 1001);
assert_eq!(frame_of_sample(1601, 48000, ntsc), 0);
assert_eq!(frame_of_sample(1602, 48000, ntsc), 1);
}
#[test]
fn feed_counts_real_frames_and_peaks() {
let f = AudioFeed::default();
f.push(&[0.5, -0.25, 0.1, 0.9]);
let mut out = [1.0f32; 8];
f.pull(&mut out);
assert_eq!(out, [0.5, -0.25, 0.1, 0.9, 0.0, 0.0, 0.0, 0.0]);
assert_eq!(f.consumed(), 2);
assert_eq!(f.take_peaks(), [0.5, 0.9]);
assert_eq!(f.take_peaks(), [0.0, 0.0]);
}
#[test]
fn meter_decays_and_holds_peaks() {
let mut m = Meter::default();
m.update([1.0, 0.5], 1.0);
assert!((m.level_db[0] - 0.0).abs() < 1e-4 && (m.level_db[1] + 6.0206).abs() < 1e-3);
assert!(m.clipped[0] && !m.clipped[1]);
m.update([0.0, 0.0], 1.1);
assert!((m.level_db[0] + 3.0).abs() < 1e-3, "{}", m.level_db[0]);
assert_eq!(m.peak_db[0], 0.0, "peak holds");
// After the hold time the peak marker follows the falling level.
m.update([0.0, 0.0], 3.0);
assert!(m.peak_db[0] < -10.0, "{}", m.peak_db[0]);
}
}
+4 -1
View File
@@ -304,9 +304,12 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
match s("action").unwrap_or("toggle") {
"play" => app.play(now),
"stop" => app.stop(),
"status" => {}
_ => app.toggle_play(now),
}
ok(json!({"playing": app.playback.playing, "time": app.session.time().seconds()}))
ok(
json!({"playing": app.playback.playing, "time": app.session.time().seconds(), "audio": app.audio.is_some(), "levelsDb": app.meter.level_db, "peaksDb": app.meter.peak_db}),
)
}
"ui.screenshot" => {
let crop = s("panel").and_then(PanelKind::from_name).and_then(|pk| app.auto.find(&format!("panel.{}", pk.id())).map(|e| e.rect));
+76
View File
@@ -5,6 +5,7 @@
//! Everything goes through `effectcraft_engine::Session::execute` (or `menus::invoke` for
//! frontend-only commands) so every gesture is also available to agents.
pub mod audio;
pub mod automation;
pub mod control;
pub mod dock;
@@ -41,6 +42,16 @@ pub enum Dialog {
CompSettings,
SolidSettings,
CommandPalette,
/// Settings (Preferences) on `dialog_state.settings_page`.
Settings,
/// Edit ▸ Keyboard Shortcuts.
Shortcuts,
/// A generic parameter form for a command (`dialog_state.form`).
Form,
/// A message (`dialog_state.info`).
Info,
/// View ▸ View Options.
ViewOptions,
CameraSettings,
LightSettings,
KeyVelocity,
@@ -54,6 +65,8 @@ pub struct Hooks {
pub pick_files: Option<Box<dyn Fn(&[&str]) -> Vec<String>>>,
pub pick_save: Option<Box<dyn Fn(&str) -> Option<String>>>,
pub pick_open_project: Option<Box<dyn Fn() -> Option<String>>>,
/// Opens the audio output for preview playback (the desktop app uses cpal).
pub audio_device: Option<audio::AudioDeviceFactory>,
}
#[derive(Default)]
@@ -101,6 +114,14 @@ pub struct EffectcraftApp {
pub(crate) pointer_comp: Option<[f32; 2]>,
pub(crate) dialog_state: panels::dialogs::DialogState,
pub integrated_titlebar: bool,
/// Audio preview while playing (audio clock drives playback).
pub audio: Option<audio::AudioPlayback>,
/// Audio panel VU meters.
pub meter: audio::Meter,
/// Waveform peak summaries per footage item (see `panels::waveform`).
pub(crate) waveforms: panels::waveform::Cache,
/// Last reveal shortcut and when (double-press shortcuts such as LL).
pub(crate) last_reveal: Option<(String, f64)>,
}
impl EffectcraftApp {
@@ -133,6 +154,10 @@ impl EffectcraftApp {
pointer_comp: None,
dialog_state: Default::default(),
integrated_titlebar: false,
audio: None,
meter: Default::default(),
waveforms: Default::default(),
last_reveal: None,
}
}
@@ -244,10 +269,32 @@ impl EffectcraftApp {
waiting: false,
fps: c.frame_rate.as_f64(),
};
self.start_audio(t);
}
/// Start audio preview from comp time `t` when the Preview panel includes audio, the comp
/// has something audible and an output device opens.
fn start_audio(&mut self, t: Tick) {
self.audio = None;
self.meter.clipped = [false; 2];
if !self.ui.preview_audio {
return;
}
let Some(cid) = self.session.active_comp_id() else { return };
let Some(c) = self.session.project.comp(cid).cloned() else { return };
if !effectcraft_engine::render::audio::comp_has_audio(&self.session.project, cid) {
return;
}
let Some(dev) = self.hooks.audio_device.as_ref().and_then(|f| f()) else { return };
match audio::AudioPlayback::start(dev, self.render_source(), cid, t, c.work_area.0, c.work_area.1, self.ui.preview_loop) {
Ok(a) => self.audio = Some(a),
Err(e) => log::warn!("audio preview: {e}"),
}
}
pub fn stop(&mut self) {
self.playback.playing = false;
self.audio = None;
}
pub fn toggle_play(&mut self, now: f64) {
@@ -291,9 +338,32 @@ impl EffectcraftApp {
queued += 1;
}
}
if let Some(a) = &self.audio {
self.meter.update(a.feed.take_peaks(), now);
} else if self.meter.active() {
self.meter.update([0.0; 2], now);
ctx.request_repaint();
}
if !self.playback.playing {
return;
}
// Audio clock drives playback: show the frame under the audible sample (frames that
// are not rendered yet are dropped, never delayed).
if let Some(a) = &self.audio {
if a.finished() {
self.session.set_time(fr.tick_of(wb));
self.stop();
return;
}
let target = audio::frame_of_sample(a.clock(), a.rate, fr).clamp(wa, wb);
self.playback.waiting = !self.frames.is_cached(&self.frame_key(cid, target, scale));
if target != cur {
self.session.set_time(fr.tick_of(target));
self.playback.shown += 1;
}
ctx.request_repaint();
return;
}
let elapsed = now - self.playback.start_wall;
let mut target = self.playback.start_frame + (elapsed * fr.as_f64()).floor() as i64;
if target > wb {
@@ -444,6 +514,12 @@ impl EffectcraftApp {
effectcraft_engine::Event::Toast { message, .. } => self.toast = Some((message, ctx.input(|i| i.time))),
effectcraft_engine::Event::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
effectcraft_engine::Event::ProjectChanged { .. } => {}
effectcraft_engine::Event::Frontend { command, params } => {
if let Err(e) = crate::menus::frontend(self, ctx, &command, params) {
self.ui.status = e;
}
}
effectcraft_engine::Event::PurgeCaches => self.frames.clear(),
}
}
}
+534 -259
View File
@@ -1,13 +1,16 @@
//! Menus, keyboard shortcuts and UI-level commands. The menu bar is generated from the engine
//! registry plus the UI command table (commands that only affect the frontend: tools, playback,
//! viewer zoom, panels, reveal shortcuts). `invoke` is the single entry point used by menus,
//! shortcuts and the control channel.
//! Menus, keyboard shortcuts and UI-level commands. The menu bar is the engine's After Effects
//! menu tree (`effectcraft_engine::menus`): every entry is an engine command, and frontend-only
//! commands (viewer zoom, panels, dialogs…) come back as `Event::Frontend` and are performed by
//! [`frontend`]. [`UI_COMMANDS`] holds the remaining UI-only shortcuts (tools, timeline
//! navigation, reveal keys). `invoke` is the single entry point used by menus, shortcuts and the
//! control channel.
use serde_json::{Value, json};
use crate::EffectcraftApp;
use crate::dock::PanelKind;
use crate::state::{Resolution, Tool};
use effectcraft_engine::menus::{MenuEntry, MenuNode};
pub struct UiCommand {
pub id: &'static str,
@@ -22,32 +25,23 @@ macro_rules! uic {
};
}
/// UI-only commands (not in the AE menus; shortcuts and the command palette).
pub const UI_COMMANDS: &[UiCommand] = &[
uic!("playback.toggle", "Play/Stop", ["Composition", "Preview"], Some("Space")),
uic!("playback.ramPreview", "Play Current Preview", ["Composition", "Preview"], Some("Num0")),
uic!("playback.ramPreview", "Play Current Preview", [], Some("Num0")),
uic!("playback.stop", "Stop", [], None),
uic!("view.zoomIn", "Zoom In", ["View"], Some(".")),
uic!("view.zoomOut", "Zoom Out", ["View"], Some(",")),
uic!("view.fit", "Fit", ["View"], Some("Shift+/")),
uic!("view.actualSize", "100%", ["View"], Some("/")),
uic!("view.res.full", "Full", ["View", "Resolution"], Some("Cmd+J")),
uic!("view.res.half", "Half", ["View", "Resolution"], Some("Cmd+Shift+J")),
uic!("view.res.third", "Third", ["View", "Resolution"], None),
uic!("view.res.quarter", "Quarter", ["View", "Resolution"], Some("Cmd+Alt+Shift+J")),
uic!("view.res.auto", "Auto", ["View", "Resolution"], None),
uic!("view.rulers", "Show Rulers", ["View"], Some("Cmd+R")),
uic!("view.grid", "Show Grid", ["View"], Some("Cmd+'")),
uic!("view.safeMargins", "Title/Action Safe", ["View"], None),
uic!("view.transparencyGrid", "Transparency Grid", ["View"], None),
uic!("view.layerControls", "Show Layer Controls", ["View"], Some("Cmd+Shift+H")),
uic!("view.fastPreviews", "Fast Previews", ["View"], None),
uic!("view.theme.dark", "Dark", ["View", "Appearance"], None),
uic!("view.theme.darker", "Darker", ["View", "Appearance"], None),
uic!("view.theme.light", "Light", ["View", "Appearance"], None),
uic!("view.fit", "Fit", [], Some("Shift+/")),
uic!("view.actualSize", "100%", [], Some("/")),
uic!("view.res.auto", "Resolution: Auto", [], None),
uic!("view.safeMargins", "Title/Action Safe", [], None),
uic!("view.transparencyGrid", "Transparency Grid", [], None),
uic!("view.fastPreviews", "Fast Previews", [], None),
uic!("view.theme.dark", "Theme: Dark", [], None),
uic!("view.theme.darker", "Theme: Darker", [], None),
uic!("view.theme.light", "Theme: Light", [], None),
uic!("timeline.zoomIn", "Zoom In Time", [], Some("=")),
uic!("timeline.zoomOut", "Zoom Out Time", [], Some("-")),
uic!("timeline.zoomFit", "Zoom to Fit Comp", [], Some(";")),
uic!("timeline.graphEditor", "Graph Editor", ["Window"], Some("Shift+F3")),
uic!("timeline.graphEditor", "Graph Editor", [], Some("Shift+F3")),
uic!("timeline.switchesModes", "Toggle Switches / Modes", [], Some("F4")),
uic!("timeline.workAreaBegin", "Set Work Area Begin", [], Some("B")),
uic!("timeline.workAreaEnd", "Set Work Area End", [], Some("N")),
@@ -60,22 +54,12 @@ pub const UI_COMMANDS: &[UiCommand] = &[
uic!("timeline.reveal.rotation", "Reveal Rotation", [], Some("R")),
uic!("timeline.reveal.opacity", "Reveal Opacity", [], Some("T")),
uic!("timeline.reveal.anchor", "Reveal Anchor Point", [], Some("A")),
uic!("timeline.reveal.animated", "Reveal Animated Properties", ["Animation"], Some("U")),
uic!("timeline.reveal.effects", "Reveal Effects", [], Some("E")),
uic!("timeline.reveal.masks", "Reveal Masks", [], Some("M")),
uic!("timeline.reveal.feather", "Reveal Mask Feather", [], Some("F")),
uic!("timeline.reveal.levels", "Reveal Audio Levels (press twice: Waveform)", [], Some("L")),
uic!("timeline.reveal.waveform", "Reveal Audio Waveform", [], None),
uic!("timeline.collapseAll", "Collapse All", [], Some("Cmd+`")),
uic!("window.workspace.default", "Default", ["Window", "Workspace"], Some("Shift+F10")),
uic!("window.workspace.standard", "Standard", ["Window", "Workspace"], Some("Shift+F11")),
uic!("window.workspace.smallscreen", "Small Screen", ["Window", "Workspace"], Some("Shift+F12")),
uic!("window.workspace.animation", "Animation", ["Window", "Workspace"], None),
uic!("window.workspace.effects", "Effects", ["Window", "Workspace"], None),
uic!("window.workspace.motiontracking", "Motion Tracking", ["Window", "Workspace"], None),
uic!("window.workspace.paint", "Paint", ["Window", "Workspace"], None),
uic!("window.workspace.text", "Text", ["Window", "Workspace"], None),
uic!("window.workspace.minimal", "Minimal", ["Window", "Workspace"], None),
uic!("window.workspace.allpanels", "All Panels", ["Window", "Workspace"], None),
uic!("window.workspace.reset", "Reset to Saved Layout", ["Window", "Workspace"], None),
uic!("tool.selection", "Selection Tool", [], Some("V")),
uic!("tool.hand", "Hand Tool", [], Some("H")),
uic!("tool.zoom", "Zoom Tool", [], Some("Z")),
@@ -90,19 +74,23 @@ pub const UI_COMMANDS: &[UiCommand] = &[
uic!("tool.brush", "Brush Tools", [], Some("Cmd+B")),
uic!("tool.rotoBrush", "Roto Brush Tool", [], Some("Alt+W")),
uic!("tool.puppet", "Puppet Tools", [], Some("Cmd+P")),
uic!("app.newComp", "New Composition…", [], None),
uic!("app.compSettings", "Composition Settings…", [], None),
uic!("app.solidSettings", "New Solid…", [], None),
uic!("app.commandPalette", "Command Palette…", ["Window"], Some("Cmd+Shift+P")),
uic!("app.about", "About EffectCraft", ["Help"], None),
uic!("app.home", "Home", ["Window"], None),
uic!("app.newComp", "New Composition...", [], None),
uic!("app.compSettings", "Composition Settings...", [], None),
uic!("app.solidSettings", "New Solid...", [], None),
uic!("app.home", "Home", [], None),
];
pub fn panel_command_id(p: PanelKind) -> String {
format!("window.panel.{}", p.id())
}
fn reveal(app: &mut EffectcraftApp, kind: &str) {
fn reveal(app: &mut EffectcraftApp, kind: &str, now: f64) {
// 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();
@@ -118,6 +106,10 @@ fn reveal(app: &mut EffectcraftApp, kind: &str) {
app.ui.timeline.open_layers = sel.iter().map(|l| l.0).collect();
}
fn no_params(p: &Value) -> bool {
p.as_object().is_none_or(|m| m.is_empty())
}
/// Execute a UI or engine command by id.
pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
let now = ctx.input(|i| i.time);
@@ -125,20 +117,15 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
if crate::panels::dialogs_3d::route(app, id, &params)? {
return Ok(Value::Null);
}
// Legacy per-panel / per-workspace ids (`window.panel.Project`, `window.workspace.default`).
if let Some(rest) = id.strip_prefix("window.panel.") {
let p = PanelKind::from_name(rest).ok_or_else(|| format!("unknown panel `{rest}`"))?;
app.show_panel(p);
return Ok(Value::Null);
return frontend(app, ctx, "window.panel", json!({"panel": rest}));
}
if let Some(ws) = id.strip_prefix("window.workspace.") {
if ws == "reset" {
let name = app.ui.workspace.clone();
app.set_workspace(&name);
return Ok(Value::Null);
return frontend(app, ctx, "window.resetWorkspace", json!({}));
}
let name = crate::dock::WORKSPACES.iter().find(|w| w.to_ascii_lowercase().replace(' ', "") == ws).ok_or_else(|| format!("unknown workspace `{ws}`"))?;
app.set_workspace(name);
return Ok(json!({"workspace": name}));
return frontend(app, ctx, "window.workspace", json!({"name": ws}));
}
if let Some(t) = id.strip_prefix("tool.") {
// Slot shortcuts cycle through the slot's tools.
@@ -169,11 +156,14 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
return Ok(json!({"tool": tool}));
}
if let Some(k) = id.strip_prefix("timeline.reveal.") {
reveal(app, k);
if k == "animated" {
return run_engine(app, ctx, "anim.reveal", json!({"kind": "keyframes"}));
}
reveal(app, k, now);
return Ok(Value::Null);
}
if let Some(r) = id.strip_prefix("view.res.") {
app.ui.viewer.res = Resolution::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r)).ok_or("unknown resolution")?;
if id == "view.res.auto" {
app.ui.viewer.res = Resolution::Auto;
return Ok(Value::Null);
}
if let Some(th) = id.strip_prefix("view.theme.") {
@@ -183,7 +173,7 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
}
let timing = |app: &mut EffectcraftApp, op: &str| app.session.execute("layer.timing", json!({"op": op})).map_err(|e| e.to_string());
match id {
"playback.toggle" | "playback.ramPreview" => {
"playback.ramPreview" => {
app.toggle_play(now);
return Ok(json!({"playing": app.playback.playing}));
}
@@ -191,17 +181,6 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
app.stop();
return Ok(Value::Null);
}
"view.zoomIn" | "view.zoomOut" => {
let cur = app.ui.viewer.zoom.unwrap_or_else(|| crate::panels::viewer::last_fit(ctx));
const STEPS: [f32; 16] = [0.015, 0.03, 0.0625, 0.125, 0.25, 0.333, 0.5, 0.66, 1.0, 1.5, 2.0, 3.0, 4.0, 8.0, 16.0, 32.0];
let next = if id == "view.zoomIn" {
STEPS.iter().copied().find(|s| *s > cur + 1e-3).unwrap_or(32.0)
} else {
STEPS.iter().rev().copied().find(|s| *s < cur - 1e-3).unwrap_or(0.015)
};
app.ui.viewer.zoom = Some(next);
return Ok(json!({"zoom": next}));
}
"view.fit" => {
app.ui.viewer.zoom = None;
app.ui.viewer.pan = [0.0, 0.0];
@@ -212,11 +191,8 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
app.ui.viewer.pan = [0.0, 0.0];
return Ok(Value::Null);
}
"view.rulers" => app.ui.viewer.rulers = !app.ui.viewer.rulers,
"view.grid" => app.ui.viewer.grid = !app.ui.viewer.grid,
"view.safeMargins" => app.ui.viewer.safe_margins = !app.ui.viewer.safe_margins,
"view.transparencyGrid" => app.ui.viewer.transparency_grid = !app.ui.viewer.transparency_grid,
"view.layerControls" => app.ui.viewer.show_layer_controls = !app.ui.viewer.show_layer_controls,
"view.fastPreviews" => app.ui.viewer.fast_preview = !app.ui.viewer.fast_preview,
"timeline.zoomIn" | "timeline.zoomOut" => {
let k = if id == "timeline.zoomIn" { 1.5 } else { 1.0 / 1.5 };
@@ -237,31 +213,38 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
"timeline.moveOutToTime" => return timing(app, "moveOutToTime"),
"timeline.trimInToTime" => return timing(app, "trimInToTime"),
"timeline.trimOutToTime" => return timing(app, "trimOutToTime"),
"app.about" => app.dialog = Some(crate::Dialog::About),
"app.home" => app.ui.start_screen = !app.ui.start_screen,
"app.commandPalette" => {
app.dialog_state.palette_query.clear();
app.dialog = Some(crate::Dialog::CommandPalette);
}
"app.newComp" | "comp.new" if params.as_object().is_none_or(|m| m.is_empty()) => {
crate::panels::dialogs::open_new_comp(app);
}
"app.compSettings" | "comp.settings" if params.as_object().is_none_or(|m| m.is_empty()) => {
crate::panels::dialogs::open_comp_settings(app)?;
}
"keys.velocity" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_velocity(app)?,
"keys.interpolation" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_interpolation(app)?,
"layer.timeStretch" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_time_stretch(app)?,
"app.solidSettings" | "layer.newSolid" if params.as_object().is_none_or(|m| m.is_empty()) => {
crate::panels::dialogs::open_new_solid(app)?;
}
"app.newComp" | "comp.new" if no_params(&params) => crate::panels::dialogs::open_new_comp(app),
"app.compSettings" | "comp.settings" if no_params(&params) => crate::panels::dialogs::open_comp_settings(app)?,
"app.solidSettings" | "layer.newSolid" if no_params(&params) => crate::panels::dialogs::open_new_solid(app)?,
"keys.velocity" if no_params(&params) => crate::panels::key_dialogs::open_velocity(app)?,
"keys.interpolation" if no_params(&params) => crate::panels::key_dialogs::open_interpolation(app)?,
"layer.timeStretch" if no_params(&params) => crate::panels::key_dialogs::open_time_stretch(app)?,
_ => {
if (id == "file.import" && params.get("paths").is_none() && params.get("path").is_none())
|| (id == "file.saveAs" && params.get("path").is_none())
|| (id == "file.open" && params.get("path").is_none())
|| (id == "file.save" && params.get("path").is_none() && app.session.path.is_none())
{
return file_dialog(app, id);
if id == "renderQueue.render" && params.get("wait").is_none() {
// The UI renders in the background; the panel shows progress.
let mut p = params.clone();
if let Some(m) = p.as_object_mut() {
m.insert("wait".into(), json!(false));
} else {
p = json!({"wait": false});
}
app.show_panel(PanelKind::RenderQueue);
return app.session.execute(id, p).map_err(|e| e.to_string());
}
if id == "renderQueue.add" {
let r = app.session.execute(id, params).map_err(|e| e.to_string());
match &r {
Ok(_) => app.show_panel(PanelKind::RenderQueue),
Err(e) => app.ui.status = e.clone(),
}
return r;
}
if let Some(r) = file_dialog(app, id, &params) {
return r;
}
if crate::panels::dialogs::open_form(app, id, &params) {
return Ok(json!({"dialog": id}));
}
if id == "renderQueue.render" && params.get("wait").is_none() {
// The UI renders in the background; the panel shows progress.
@@ -286,44 +269,270 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
crate::panels::timeline::begin_rename(app, ctx);
return Ok(Value::Null);
}
let r = app.session.execute(id, params).map_err(|e| e.to_string());
if let Err(e) = &r {
app.ui.status = e.clone();
}
return r;
return run_engine(app, ctx, id, params);
}
}
Ok(Value::Null)
}
fn file_dialog(app: &mut EffectcraftApp, id: &str) -> Result<Value, String> {
match id {
"file.import" => {
let f = app.hooks.pick_files.as_ref().ok_or("no file dialog available (pass `paths`)")?;
/// Run an engine command and perform the frontend events it emitted right away.
fn run_engine(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
let r = app.session.execute(id, params).map_err(|e| e.to_string());
if let Err(e) = &r {
app.ui.status = e.clone();
}
let events = app.session.drain_events();
for ev in events {
match ev {
effectcraft_engine::Event::Frontend { command, params } => {
if let Err(e) = frontend(app, ctx, &command, params) {
app.ui.status = e;
}
}
other => app.session.events.push(other),
}
}
r
}
fn toggle(slot: &mut bool, p: &Value) -> Value {
*slot = p.get("value").and_then(Value::as_bool).unwrap_or(!*slot);
json!(*slot)
}
/// Perform a frontend command (from `Event::Frontend`).
pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Value) -> Result<Value, String> {
let now = ctx.input(|i| i.time);
let v = &mut app.ui.viewer;
Ok(match id {
"app.about" => {
app.dialog = Some(crate::Dialog::About);
Value::Null
}
"app.settings" => {
app.dialog_state.settings_page = p.get("page").and_then(Value::as_str).unwrap_or("general").to_string();
app.dialog = Some(crate::Dialog::Settings);
Value::Null
}
"app.hide" => {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));
Value::Null
}
"app.quit" => {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
Value::Null
}
"app.commandPalette" => {
app.dialog_state.palette_query = p.get("query").and_then(Value::as_str).unwrap_or_default().to_string();
app.dialog_state.palette_sel = 0;
app.dialog = Some(crate::Dialog::CommandPalette);
Value::Null
}
"app.keyboardShortcuts" => {
app.dialog = Some(crate::Dialog::Shortcuts);
Value::Null
}
"app.templates" => {
let kind = p.get("kind").and_then(Value::as_str).unwrap_or("renderSettings");
let title = if kind == "outputModule" { "Output Module Templates" } else { "Render Settings Templates" };
crate::panels::dialogs::info(app, title, "Render and output templates are managed from the Render Queue panel (Window ▸ Render Queue).");
Value::Null
}
"app.find" => {
if let Some(q) = p.get("query").and_then(Value::as_str) {
app.ui.project_search = q.to_string();
}
app.show_panel(PanelKind::Project);
Value::Null
}
"playback.toggle" => {
app.toggle_play(now);
json!({"playing": app.playback.playing})
}
"playback.cacheWhenIdle" => toggle(&mut app.ui.cache_when_idle, &p),
"playback.audio" => {
let r = toggle(&mut app.ui.preview_audio, &p);
if !app.ui.preview_audio {
app.audio = None;
}
r
}
"view.zoomIn" | "view.zoomOut" => {
let cur = v.zoom.unwrap_or_else(|| crate::panels::viewer::last_fit(ctx));
const STEPS: [f32; 16] = [0.015, 0.03, 0.0625, 0.125, 0.25, 0.333, 0.5, 0.66, 1.0, 1.5, 2.0, 3.0, 4.0, 8.0, 16.0, 32.0];
let next = if id == "view.zoomIn" {
STEPS.iter().copied().find(|s| *s > cur + 1e-3).unwrap_or(32.0)
} else {
STEPS.iter().rev().copied().find(|s| *s < cur - 1e-3).unwrap_or(0.015)
};
v.zoom = Some(next);
json!({"zoom": next})
}
"view.res.full" | "view.res.half" | "view.res.third" | "view.res.quarter" => {
let r = id.trim_start_matches("view.res.");
v.res = Resolution::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r)).ok_or("unknown resolution")?;
Value::Null
}
"view.rulers" => toggle(&mut v.rulers, &p),
"view.guides" => toggle(&mut v.guides, &p),
"view.snapToGuides" => toggle(&mut v.snap_guides, &p),
"view.lockGuides" => toggle(&mut v.lock_guides, &p),
"view.grid" => toggle(&mut v.grid, &p),
"view.snapToGrid" => toggle(&mut v.snap_grid, &p),
"view.layerControls" => toggle(&mut v.show_layer_controls, &p),
"view.options" => {
app.dialog = Some(crate::Dialog::ViewOptions);
Value::Null
}
"view.panelBackground" => {
if p.get("pick").and_then(Value::as_bool) == Some(true) {
let [r, g, b] = v.custom_pasteboard;
crate::panels::dialogs::form(
app,
"Panel Background Color",
"view.panelBackground",
json!({}),
vec![crate::panels::dialogs::Field::text("color", "Color (#rrggbb)", &format!("#{r:02x}{g:02x}{b:02x}"))],
);
return Ok(Value::Null);
}
let c = p.get("color").and_then(Value::as_str).unwrap_or("mediumGray");
v.pasteboard = match c {
"black" => Some([0, 0, 0]),
"darkGray" => Some([0x2a, 0x2a, 0x2a]),
"mediumGray" => None,
"lightGray" => Some([0xb4, 0xb4, 0xb4]),
"white" => Some([0xff, 0xff, 0xff]),
"custom" => Some(v.custom_pasteboard),
hex => {
let c = effectcraft_engine::color::Rgba::from_hex(hex).ok_or_else(|| format!("unknown colour `{hex}`"))?;
let rgb = [(c.r * 255.0).round() as u8, (c.g * 255.0).round() as u8, (c.b * 255.0).round() as u8];
v.custom_pasteboard = rgb;
Some(rgb)
}
};
Value::Null
}
"view.fullScreen" => {
let full = ctx.input(|i| i.viewport().fullscreen.unwrap_or(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(!full));
json!(!full)
}
"window.panel" => {
let name = p.get("panel").and_then(Value::as_str).unwrap_or_default();
if name.eq_ignore_ascii_case("tools") {
app.ui.status = "The Tools panel is the toolbar in the header".into();
return Ok(Value::Null);
}
let panel = PanelKind::from_name(name).ok_or_else(|| format!("unknown panel `{name}`"))?;
app.show_panel(panel);
Value::Null
}
"window.workspace" => {
let want = p.get("name").and_then(Value::as_str).unwrap_or("Default").to_ascii_lowercase().replace(' ', "");
let name = crate::dock::WORKSPACES
.iter()
.find(|w| w.to_ascii_lowercase().replace(' ', "") == want)
.ok_or_else(|| format!("unknown workspace `{want}`"))?;
app.set_workspace(name);
json!({"workspace": name})
}
"window.resetWorkspace" => {
let name = app.ui.workspace.clone();
app.set_workspace(&name);
Value::Null
}
"comp.flowchart" | "comp.miniFlowchart" => {
app.show_panel(PanelKind::Flowchart);
Value::Null
}
"layer.openLayer" => {
app.show_panel(PanelKind::Layer);
Value::Null
}
"effect.manage" | "anim.browsePresets" => {
app.show_panel(PanelKind::EffectsPresets);
Value::Null
}
"timeline.revealProps" => {
let props = p.get("props").and_then(Value::as_array).cloned().unwrap_or_default();
let tl = &mut app.ui.timeline;
tl.reveal_props = props.iter().filter_map(|x| x.get("prop").and_then(Value::as_u64)).collect();
tl.open_layers = props.iter().filter_map(|x| x.get("layer").and_then(Value::as_u64)).collect();
tl.reveal = if tl.reveal_props.is_empty() { vec![] } else { vec!["props".into()] };
json!({"revealed": tl.reveal_props.len()})
}
_ => return Err(format!("`{id}` is not a frontend command")),
})
}
/// Commands that need a file or folder path: ask the host's file dialog when `params` lacks one.
fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
enum Ask {
Import,
OpenProject,
Save(&'static str),
Open(&'static [&'static str]),
}
let (key, ask) = match id {
"file.import" | "file.importMultiple" => ("paths", Ask::Import),
"file.open" => ("path", Ask::OpenProject),
"file.save" if app.session.path.is_none() => ("path", Ask::Save("Untitled Project.ecproj")),
"file.saveAs" | "file.saveCopy" => ("path", Ask::Save("Untitled Project.ecproj")),
"comp.saveFrameAs" => ("path", Ask::Save("Frame.png")),
"anim.savePreset" => ("path", Ask::Save("Preset.ecpreset")),
"anim.applyPreset" => ("path", Ask::Open(&["ecpreset", "json"])),
"view.exportGuides" => ("path", Ask::Save("Guides.json")),
"view.importGuides" => ("path", Ask::Open(&["json"])),
"file.runScript" => ("path", Ask::Open(&["jsonl", "json", "txt"])),
"file.replaceFootage" => ("path", Ask::Import),
"file.collectFiles" => ("folder", Ask::Save("Collected Files")),
_ => return None,
};
if params.get(key).is_some()
|| params.get("path").is_some()
|| params.get("paths").is_some()
|| params.get("steps").is_some()
|| params.get("preset").is_some()
{
return None;
}
let mut p = params.as_object().cloned().unwrap_or_default();
let picked: Option<Value> = match ask {
Ask::Import => {
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",
]);
if paths.is_empty() {
return Ok(Value::Null);
}
app.session.execute("file.import", json!({"paths": paths})).map_err(|e| e.to_string())
}
"file.open" => {
let f = app.hooks.pick_open_project.as_ref().ok_or("no file dialog available (pass `path`)")?;
match f() {
Some(p) => app.session.execute("file.open", json!({"path": p})).map_err(|e| e.to_string()),
None => Ok(Value::Null),
match (paths.is_empty(), key) {
(true, _) => None,
(false, "paths") => Some(json!(paths)),
(false, _) => paths.first().map(|s| json!(s)),
}
}
_ => {
let f = app.hooks.pick_save.as_ref().ok_or("no file dialog available (pass `path`)")?;
match f("Untitled Project.ecproj") {
Some(p) => app.session.execute("file.saveAs", json!({"path": p})).map_err(|e| e.to_string()),
None => Ok(Value::Null),
}
Ask::OpenProject => {
let Some(f) = app.hooks.pick_open_project.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
f().map(|s| json!(s))
}
Ask::Open(exts) => {
let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
f(exts).first().map(|s| json!(s))
}
Ask::Save(default) => {
let Some(f) = app.hooks.pick_save.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
f(default).map(|s| json!(s))
}
};
let Some(v) = picked else { return Some(Ok(Value::Null)) };
p.insert(key.to_string(), v);
// 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());
if let Err(e) = &r {
app.ui.status = e.clone();
}
Some(r)
}
/// A menu entry for display / `ui.menu.list`.
@@ -334,104 +543,90 @@ pub struct MenuItem {
pub path: Vec<String>,
pub shortcut: Option<String>,
pub enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub checked: Option<bool>,
/// Parameters bound to the entry (e.g. the effect for Effect menu items).
#[serde(skip_serializing_if = "Value::is_null")]
pub params: Value,
}
pub const MENUS: [&str; 9] = ["File", "Edit", "Composition", "Layer", "Effect", "Animation", "View", "Window", "Help"];
/// Top-level menus in order.
pub fn menus() -> Vec<&'static str> {
effectcraft_engine::menus::top_level()
}
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()),
_ => e.label.clone(),
}
}
/// Check-mark state of frontend toggles (engine state is answered by the engine).
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() {
"view.rulers" => Some(v.rulers),
"view.guides" => Some(v.guides),
"view.snapToGuides" => Some(v.snap_guides),
"view.lockGuides" => Some(v.lock_guides),
"view.grid" => Some(v.grid),
"view.snapToGrid" => Some(v.snap_grid),
"view.layerControls" => Some(v.show_layer_controls),
"playback.cacheWhenIdle" => Some(app.ui.cache_when_idle),
"playback.audio" => Some(app.ui.preview_audio),
"view.res.full" | "view.res.half" | "view.res.third" | "view.res.quarter" => {
Some(v.res.label().eq_ignore_ascii_case(e.command.trim_start_matches("view.res.")))
}
"window.workspace" => Some(pstr("name").is_some_and(|n| n == app.ui.workspace)),
"view.panelBackground" if e.params.get("pick").is_none() => {
let cur = match v.pasteboard {
None => "mediumGray",
Some([0, 0, 0]) => "black",
Some([0x2a, 0x2a, 0x2a]) => "darkGray",
Some([0xb4, 0xb4, 0xb4]) => "lightGray",
Some([0xff, 0xff, 0xff]) => "white",
Some(_) => "custom",
};
Some(pstr("color") == Some(cur))
}
_ => effectcraft_engine::menus::checked(&app.session, &e.command, &e.params),
}
}
fn entry_enabled(app: &EffectcraftApp, e: &MenuEntry) -> bool {
if e.command == "window.panel" {
return true;
}
app.session.is_enabled(&e.command)
}
/// Every menu entry, flattened with its submenu path.
pub fn menu_items(app: &EffectcraftApp) -> Vec<MenuItem> {
let mut out = Vec::new();
for c in effectcraft_engine::command_specs() {
if c.menu.is_empty() {
continue;
}
out.push(MenuItem {
id: c.id.into(),
label: c.label.into(),
path: c.menu.iter().map(|s| s.to_string()).collect(),
shortcut: c.shortcut.map(str::to_string),
enabled: app.session.is_enabled(c.id),
params: Value::Null,
});
}
for c in UI_COMMANDS {
if c.menu.is_empty() {
continue;
}
out.push(MenuItem {
id: c.id.into(),
label: c.label.into(),
path: c.menu.iter().map(|s| s.to_string()).collect(),
shortcut: c.shortcut.map(str::to_string),
enabled: true,
params: Value::Null,
});
}
for p in PanelKind::ALL {
out.push(MenuItem {
id: panel_command_id(p),
label: p.title().into(),
path: vec!["Window".into()],
shortcut: p.window_shortcut().map(str::to_string),
enabled: true,
params: Value::Null,
});
}
// Animation ▸ Animate Text / Add Text Selector / Text Animation Presets.
let anim_on = app.session.is_enabled("layer.addTextAnimator");
for (k, l) in effectcraft_engine::project::build::TEXT_ANIMATOR_KINDS.iter().filter(|(k, _)| *k != "-") {
out.push(MenuItem {
id: "layer.addTextAnimator".into(),
label: (*l).into(),
path: vec!["Animation".into(), "Animate Text".into()],
shortcut: None,
enabled: anim_on,
params: json!({"property": k}),
});
}
let sel_on = app.session.is_enabled("layer.addTextSelector");
for (k, l) in [("range", "Range"), ("wiggly", "Wiggly"), ("expression", "Expression")] {
out.push(MenuItem {
id: "layer.addTextSelector".into(),
label: l.into(),
path: vec!["Animation".into(), "Add Text Selector".into()],
shortcut: None,
enabled: sel_on,
params: json!({"kind": k}),
});
}
let preset_on = app.session.is_enabled("layer.applyTextPreset");
for (id, name) in effectcraft_engine::text_presets() {
out.push(MenuItem {
id: "layer.applyTextPreset".into(),
label: name,
path: vec!["Animation".into(), "Text Animation Presets".into()],
shortcut: None,
enabled: preset_on,
params: json!({"preset": id}),
});
}
let has_layer = !app.session.state.selected_layers.is_empty();
for e in effectcraft_engine::effects::registry() {
out.push(MenuItem {
id: "effect.apply".into(),
label: e.name.into(),
path: vec!["Effect".into(), e.category.into()],
shortcut: None,
enabled: has_layer,
params: json!({"effect": e.id}),
});
}
out
effectcraft_engine::menus::entries()
.into_iter()
.map(|(path, e)| MenuItem {
id: e.command.clone(),
label: entry_label(app, e),
path,
shortcut: e.shortcut.clone(),
enabled: entry_enabled(app, e),
checked: entry_checked(app, e),
params: e.params.clone(),
})
.collect()
}
/// Shortcut text in this OS's notation (`⇧⌘K` on macOS, `Ctrl+Shift+K` elsewhere).
pub fn shortcut_text(s: &str) -> String {
if cfg!(target_os = "macos") {
let mut out = String::new();
let parts: Vec<&str> = s.split('+').collect();
let parts: Vec<&str> = match s.strip_suffix("++") {
Some(head) => vec![head, "+"],
None => s.split('+').collect(),
};
let (mods, key) = parts.split_at(parts.len().saturating_sub(1));
for m in mods {
out.push_str(match *m {
@@ -442,7 +637,12 @@ pub fn shortcut_text(s: &str) -> String {
x => x,
});
}
out.push_str(key.first().copied().unwrap_or(""));
out.push_str(match key.first().copied().unwrap_or("") {
"Space" => "Space",
"Escape" => "Esc",
"Home" => "↖",
k => k,
});
out
} else {
s.replace("Cmd", "Ctrl")
@@ -489,22 +689,53 @@ pub fn parse_shortcut(s: &str) -> Option<(egui::Modifiers, egui::Key)> {
key.map(|k| (m, k))
}
/// The key some keyboards report for a shifted punctuation key (`Shift+=` arrives as `+`).
fn shifted_alias(k: egui::Key) -> Option<egui::Key> {
use egui::Key::*;
Some(match k {
Equals => Plus,
Semicolon => Colon,
OpenBracket => OpenCurlyBracket,
CloseBracket => CloseCurlyBracket,
Slash => Questionmark,
Backslash => Pipe,
_ => return None,
})
}
/// A key binding: modifiers, key, command id and bound params.
pub type Binding = (egui::Modifiers, egui::Key, String, Value);
/// All active bindings, most modifiers first.
pub fn bindings() -> Vec<(egui::Modifiers, egui::Key, String)> {
let mut v: Vec<(egui::Modifiers, egui::Key, String)> = Vec::new();
pub fn bindings() -> Vec<Binding> {
let mut v: Vec<Binding> = Vec::new();
let mut push = |sc: &str, id: &str, params: Value| {
if let Some((m, k)) = parse_shortcut(sc) {
if m.shift
&& let Some(alias) = shifted_alias(k)
{
v.push((m, alias, id.to_string(), params.clone()));
}
v.push((m, k, id.to_string(), params));
}
};
// Menu entries (their shortcuts may bind params), then command defaults not in the menus.
let entries = effectcraft_engine::menus::entries();
for (_, e) in &entries {
if let Some(sc) = &e.shortcut {
push(sc, &e.command, e.params.clone());
}
}
for c in effectcraft_engine::command_specs() {
if let Some((m, k)) = c.shortcut.and_then(parse_shortcut) {
v.push((m, k, c.id.to_string()));
if let Some(sc) = c.shortcut
&& !entries.iter().any(|(_, e)| e.command == c.id)
{
push(sc, c.id, Value::Null);
}
}
for c in UI_COMMANDS {
if let Some((m, k)) = c.shortcut.and_then(parse_shortcut) {
v.push((m, k, c.id.to_string()));
}
}
for p in PanelKind::ALL {
if let Some((m, k)) = p.window_shortcut().and_then(parse_shortcut) {
v.push((m, k, panel_command_id(p)));
if let Some(sc) = c.shortcut {
push(sc, c.id, Value::Null);
}
}
v.sort_by_key(|(m, ..)| std::cmp::Reverse(m.command as u8 + m.shift as u8 + m.alt as u8 + m.ctrl as u8));
@@ -551,57 +782,30 @@ pub fn handle_shortcuts(app: &mut EffectcraftApp, ctx: &egui::Context) {
let _ = invoke(app, ctx, "edit.clear", json!({}));
continue;
}
if let Some((_, _, id)) = binds.iter().find(|(m, k, _)| *k == key && mods_match(*m, mods)) {
let id = id.clone();
if let Err(e) = invoke(app, ctx, &id, json!({})) {
if let Some((_, _, id, params)) = binds.iter().find(|(m, k, ..)| *k == key && mods_match(*m, mods)) {
let (id, params) = (id.clone(), if params.is_null() { json!({}) } else { params.clone() });
if let Err(e) = invoke(app, ctx, &id, params) {
app.ui.status = e;
}
}
}
}
/// Draw the in-window menu bar.
/// Draw the in-window menu bar (the engine's AE menu tree).
pub fn menu_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
let items = menu_items(app);
let ctx = ui.ctx().clone();
let mut clicked: Option<(String, Value)> = None;
ui.horizontal_centered(|ui| {
ui.add_space(6.0);
egui::MenuBar::new().ui(ui, |ui| {
for top in MENUS {
let mine: Vec<&MenuItem> = items.iter().filter(|i| i.path.first().map(String::as_str) == Some(top)).collect();
ui.menu_button(top, |ui| {
ui.set_min_width(260.0);
let mut subs: Vec<&str> = Vec::new();
let mut last_was_sub = false;
for it in &mine {
if it.path.len() > 1 {
let sub = it.path[1].as_str();
if !subs.contains(&sub) {
subs.push(sub);
ui.menu_button(sub, |ui| {
ui.set_min_width(220.0);
for s in mine.iter().filter(|x| x.path.get(1).map(String::as_str) == Some(sub)) {
if menu_entry(ui, s) {
clicked = Some((s.id.clone(), s.params.clone()));
ui.close();
}
}
});
last_was_sub = true;
}
} else {
if last_was_sub && top != "Effect" {
ui.separator();
last_was_sub = false;
}
if menu_entry(ui, it) {
clicked = Some((it.id.clone(), it.params.clone()));
ui.close();
}
}
}
});
for node in effectcraft_engine::menus::menu_bar() {
if let MenuNode::Submenu { label, children } = node {
let r = ui.menu_button(label, |ui| {
ui.set_min_width(if label == "Effect" { 200.0 } else { 280.0 });
menu_nodes(app, ui, children, &mut clicked);
});
app.auto.add(&format!("menu.{label}"), r.response.rect, label);
}
}
});
});
@@ -612,10 +816,81 @@ pub fn menu_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
}
}
fn menu_entry(ui: &mut egui::Ui, it: &MenuItem) -> bool {
let mut b = egui::Button::new(&it.label);
if let Some(s) = &it.shortcut {
fn menu_nodes(app: &mut EffectcraftApp, ui: &mut egui::Ui, nodes: &[MenuNode], clicked: &mut Option<(String, Value)>) {
for n in nodes {
match n {
MenuNode::Separator => {
ui.separator();
}
MenuNode::Submenu { label, children } => {
ui.menu_button((gutter(false), label.as_str()), |ui| {
ui.set_min_width(if children.len() > 30 { 200.0 } else { 240.0 });
// Long submenus (Blending Mode, effect categories) scroll instead of running
// off the screen.
let max_h = ui.ctx().content_rect().height() - 40.0;
egui::ScrollArea::vertical().max_height(max_h).show(ui, |ui| menu_nodes(app, ui, children, clicked));
});
}
MenuNode::Item(e) => {
if menu_entry(app, ui, e) {
*clicked = Some((e.command.clone(), e.params.clone()));
ui.close();
}
}
}
}
}
/// The check-mark column every menu row reserves (like macOS / After Effects menus).
fn gutter(checked: bool) -> egui::Atom<'static> {
use egui::AtomExt;
(if checked { "✔" } else { "" }).atom_size(egui::vec2(14.0, 14.0))
}
fn menu_entry(app: &EffectcraftApp, ui: &mut egui::Ui, e: &MenuEntry) -> bool {
let label = entry_label(app, e);
let mut b = egui::Button::new((gutter(entry_checked(app, e) == Some(true)), label));
if let Some(s) = &e.shortcut {
b = b.shortcut_text(shortcut_text(s));
}
ui.add_enabled(it.enabled, b).clicked()
ui.add_enabled(entry_enabled(app, e), b).clicked()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_ui_shortcut_parses() {
for c in UI_COMMANDS {
if let Some(sc) = c.shortcut {
assert!(parse_shortcut(sc).is_some() || sc == "Num*", "{sc}");
}
}
for (_, e) in effectcraft_engine::menus::entries() {
if let Some(sc) = &e.shortcut {
assert!(parse_shortcut(sc).is_some() || sc == "Num*", "{} ({sc})", e.label);
}
}
}
#[test]
fn ui_and_menu_shortcuts_do_not_collide() {
let mut seen: std::collections::BTreeMap<(String, String), (String, String)> = Default::default();
for (m, k, id, params) in bindings() {
let key = (format!("{m:?}"), format!("{k:?}"));
let target = (id.clone(), params.to_string());
if let Some(prev) = seen.get(&key) {
assert_eq!(prev, &target, "{key:?} bound to {prev:?} and {target:?}");
} else {
seen.insert(key, target);
}
}
}
#[test]
fn menu_items_cover_the_tree() {
assert_eq!(menus().last(), Some(&"Help"));
assert!(effectcraft_engine::menus::entries().len() > 500);
}
}
+12
View File
@@ -4,6 +4,7 @@
use egui::{Align2, Color32, Rect, Sense, pos2, vec2};
use serde_json::json;
pub use super::forms::{Field, form, info, open_form};
use crate::icons::{self, Icon};
use crate::theme::Tokens;
use crate::{Dialog, EffectcraftApp};
@@ -19,6 +20,12 @@ pub struct DialogState {
pub solid_size: [u32; 2],
pub palette_query: String,
pub palette_sel: usize,
/// Settings dialog page id (`general`, `appearance`…).
pub settings_page: String,
/// The open parameter form.
pub form: super::forms::Form,
/// Message box (title, body).
pub info: (String, String),
pub camera: super::dialogs_3d::CameraDraft,
pub light: super::dialogs_3d::LightDraft,
pub velocity: super::key_dialogs::VelocityDraft,
@@ -91,6 +98,11 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context) {
Dialog::NewComp | Dialog::CompSettings => comp_settings(app, ctx, &t, d == Dialog::CompSettings),
Dialog::SolidSettings => solid(app, ctx, &t),
Dialog::CommandPalette => palette(app, ctx, &t),
Dialog::Settings => super::forms::show_settings(app, ctx, &t),
Dialog::Shortcuts => super::forms::show_shortcuts(app, ctx, &t),
Dialog::Form => super::forms::show_form(app, ctx, &t),
Dialog::Info => super::forms::show_info(app, ctx, &t),
Dialog::ViewOptions => super::forms::show_view_options(app, ctx, &t),
Dialog::CameraSettings => super::dialogs_3d::camera(app, ctx, &t),
Dialog::LightSettings => super::dialogs_3d::light(app, ctx, &t),
Dialog::KeyVelocity => super::key_dialogs::velocity(app, ctx, &t),
+544
View File
@@ -0,0 +1,544 @@
//! Menu dialogs: a generic parameter form (numeric Transform dialogs, Mask Feather/Opacity/
//! Expansion, Auto-Orient, Go to Time, Add Guide, Sequence Layers, Interpret Footage, Project
//! Settings, placeholders…), Settings (Preferences), Keyboard Shortcuts, View Options and simple
//! message boxes. Every form runs an engine command with the collected parameters, so whatever a
//! dialog does an agent can do with one `engine.execute`.
use egui::{Color32, vec2};
use serde_json::{Map, Value, json};
use crate::theme::Tokens;
use crate::{Dialog, EffectcraftApp};
#[derive(Clone, Debug)]
pub enum FieldKind {
Number {
value: f64,
speed: f64,
},
Text(String),
Bool(bool),
/// Options as (label, value); `sel` is the chosen index.
Choice {
options: Vec<(String, Value)>,
sel: usize,
},
}
/// One form field. `key` may index into an array param (`value[1]`).
#[derive(Clone, Debug)]
pub struct Field {
pub key: String,
pub label: String,
pub kind: FieldKind,
}
impl Field {
pub fn num(key: &str, label: &str, value: f64) -> Field {
Field { key: key.into(), label: label.into(), kind: FieldKind::Number { value, speed: 1.0 } }
}
pub fn text(key: &str, label: &str, value: &str) -> Field {
Field { key: key.into(), label: label.into(), kind: FieldKind::Text(value.into()) }
}
pub fn bool(key: &str, label: &str, value: bool) -> Field {
Field { key: key.into(), label: label.into(), kind: FieldKind::Bool(value) }
}
pub fn choice(key: &str, label: &str, options: &[(&str, Value)], sel: usize) -> Field {
Field {
key: key.into(),
label: label.into(),
kind: FieldKind::Choice { options: options.iter().map(|(l, v)| (l.to_string(), v.clone())).collect(), sel },
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Form {
pub title: String,
pub command: String,
pub base: Value,
pub fields: Vec<Field>,
}
impl Form {
/// The command parameters: `base` plus every field.
pub fn params(&self) -> Value {
let mut m: Map<String, Value> = self.base.as_object().cloned().unwrap_or_default();
for f in &self.fields {
let v = match &f.kind {
FieldKind::Number { value, .. } => json!(value),
FieldKind::Text(s) => json!(s),
FieldKind::Bool(b) => json!(b),
FieldKind::Choice { options, sel } => options.get(*sel).map(|o| o.1.clone()).unwrap_or(Value::Null),
};
match f.key.split_once('[') {
Some((name, idx)) => {
let i: usize = idx.trim_end_matches(']').parse().unwrap_or(0);
let arr = m.entry(name.to_string()).or_insert_with(|| json!([]));
if let Value::Array(a) = arr {
while a.len() <= i {
a.push(json!(0));
}
a[i] = v;
}
}
None => {
m.insert(f.key.clone(), v);
}
}
}
Value::Object(m)
}
}
/// Open a form dialog.
pub fn form(app: &mut EffectcraftApp, title: &str, command: &str, base: Value, fields: Vec<Field>) {
app.dialog_state.form = Form { title: title.into(), command: command.into(), base, fields };
app.dialog = Some(Dialog::Form);
}
/// Open a message box.
pub fn info(app: &mut EffectcraftApp, title: &str, body: &str) {
app.dialog_state.info = (title.into(), body.into());
app.dialog = Some(Dialog::Info);
}
fn has(p: &Value, keys: &[&str]) -> bool {
keys.iter().any(|k| p.get(*k).is_some())
}
/// If `id` is a dialog command invoked without its parameters, open its form and return true.
pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
let s = &app.session;
let comp = s.active_comp();
let layer = comp.and_then(|c| s.state.selected_layers.first().and_then(|l| c.layer(*l)));
let t = s.time();
let lt = layer.map(|l| l.layer_time(t)).unwrap_or(t);
let base = p.clone();
let (title, fields): (String, Vec<Field>) = match id {
"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));
let v = cur.map(|c| c.as_vec3()).unwrap_or([0.0; 3]);
let three = layer.is_some_and(|l| l.is_3d());
let title = match prop {
"anchor" => "Anchor Point",
"position" => "Position",
"scale" => "Scale",
"orientation" => "Orientation",
"rotation" => "Rotation",
_ => "Opacity",
};
let fields = match prop {
"rotation" | "opacity" => vec![Field::num("value", if prop == "rotation" { "Degrees" } else { "Opacity (%)" }, v[0])],
"orientation" => vec![Field::num("value[0]", "X", v[0]), Field::num("value[1]", "Y", v[1]), Field::num("value[2]", "Z", v[2])],
_ if three => vec![Field::num("value[0]", "X", v[0]), Field::num("value[1]", "Y", v[1]), Field::num("value[2]", "Z", v[2])],
_ => vec![Field::num("value[0]", "X", v[0]), Field::num("value[1]", "Y", v[1])],
};
(title.into(), fields)
}
"layer.mask.set" if !has(p, &["value"]) => {
let field = p.get("field").and_then(Value::as_str).unwrap_or("feather");
let first = layer.and_then(|l| l.masks()).and_then(|m| m.groups().next()).and_then(|g| g.get(field)).map(|pr| pr.value_at(lt).as_f64());
let (title, label, d) = match field {
"feather" => ("Mask Feather", "Feather (pixels)", 0.0),
"opacity" => ("Mask Opacity", "Opacity (%)", 100.0),
_ => ("Mask Expansion", "Expansion (pixels)", 0.0),
};
(title.into(), vec![Field::num("value", label, first.unwrap_or(d))])
}
"layer.mask.shape" if !has(p, &["rect"]) => {
let (w, h) = layer.map(|l| effectcraft_engine::render::source_size(&s.project, l)).unwrap_or((100, 100));
(
"Mask Shape".into(),
vec![
Field::num("rect[0]", "Left", 0.0),
Field::num("rect[1]", "Top", 0.0),
Field::num("rect[2]", "Width", w as f64),
Field::num("rect[3]", "Height", h as f64),
Field::choice("shape", "Shape", &[("Rectangle", json!("rect")), ("Ellipse", json!("ellipse"))], 0),
],
)
}
"layer.autoOrient" if !has(p, &["mode"]) => {
let cur = layer.map(|l| l.auto_orient as usize).unwrap_or(0);
(
"Auto-Orientation".into(),
vec![Field::choice(
"mode",
"Mode",
&[
("Off", json!("off")),
("Orient Along Path", json!("alongPath")),
("Orient Towards Camera", json!("towardsCamera")),
("Orient Towards Point of Interest", json!("towardsPointOfInterest")),
],
cur.min(3),
)],
)
}
"time.set" if !has(p, &["time", "frame", "timecode"]) => {
let frame = comp.map(|c| c.frame_rate.frame_at(t)).unwrap_or(0);
("Go to Time".into(), vec![Field::num("frame", "Frame", frame as f64)])
}
"view.addGuide" if !has(p, &["position"]) => {
let (w, _) = comp.map(|c| (c.width, c.height)).unwrap_or((1920, 1080));
(
"Add Guide".into(),
vec![
Field::choice("orientation", "Orientation", &[("Vertical", json!("vertical")), ("Horizontal", json!("horizontal"))], 0),
Field::num("position", "Position (pixels)", w as f64 / 2.0),
],
)
}
"layer.sequence" if !has(p, &["overlap"]) => (
"Sequence Layers".into(),
vec![
Field::bool("overlap", "Overlap", false),
Field::num("duration", "Duration (seconds)", 1.0),
Field::choice(
"transition",
"Transition",
&[
("Off", json!("off")),
("Dissolve Front Layer", json!("dissolveFront")),
("Cross Dissolve Front and Back Layers", json!("crossDissolve")),
],
0,
),
],
),
"file.interpretFootage" if !has(p, &["frameRate", "alpha", "loop", "pixelAspect"]) => {
let f = s.state.project_selection.first().and_then(|i| s.project.item(*i)).and_then(|it| match &it.kind {
effectcraft_engine::project::ItemKind::Footage(f) => Some(f.clone()),
_ => None,
});
let Some(f) = f else { return false };
(
"Interpret Footage".into(),
vec![
Field::num("frameRate", "Frame rate", f.frame_rate.as_f64()),
Field::choice(
"alpha",
"Alpha",
&[("Straight", json!("straight")), ("Premultiplied", json!("premultiplied")), ("Ignore", json!("ignore"))],
f.alpha as usize,
),
Field::num("loop", "Loop (times)", f.loop_count as f64),
Field::num("pixelAspect", "Pixel aspect ratio", f.pixel_aspect),
],
)
}
"file.projectSettings" if p.as_object().is_none_or(|m| m.is_empty()) => {
let st = &s.project.settings;
let depth = match st.bit_depth.label() {
l if l.starts_with("16") => 1,
l if l.starts_with("32") => 2,
_ => 0,
};
(
"Project Settings".into(),
vec![
Field::choice(
"bitDepth",
"Depth",
&[("8 bits per channel", json!(8)), ("16 bits per channel", json!(16)), ("32 bits per channel (float)", json!(32))],
depth,
),
Field::choice(
"timeDisplay",
"Time display style",
&[("Timecode", json!("timecode")), ("Frames", json!("frames"))],
usize::from(matches!(st.time_display, effectcraft_engine::project::TimeDisplayStyle::Frames)),
),
Field::bool("linearize", "Linearize working space", st.linearize),
],
)
}
"layer.precompose" if !has(p, &["name"]) => {
let n = s.project.comps().count() + 1;
("Pre-compose".into(), vec![Field::text("name", "New composition name", &format!("Pre-comp {n}"))])
}
"file.importPlaceholder" | "file.replaceWithPlaceholder" if p.as_object().is_none_or(|m| m.is_empty()) => (
"New Placeholder".into(),
vec![
Field::text("name", "Name", "Placeholder"),
Field::num("width", "Width", 1920.0),
Field::num("height", "Height", 1080.0),
Field::num("frameRate", "Frame rate", 29.97),
Field::num("duration", "Duration (seconds)", 30.0),
],
),
"file.importSolid" | "file.replaceWithSolid" if p.as_object().is_none_or(|m| m.is_empty()) => {
let (w, h) = comp.map(|c| (c.width, c.height)).unwrap_or((1920, 1080));
(
"Solid Settings".into(),
vec![
Field::text("name", "Name", "Solid"),
Field::text("color", "Color (#rrggbb)", "#808080"),
Field::num("width", "Width", w as f64),
Field::num("height", "Height", h as f64),
],
)
}
_ => return false,
};
form(app, &title, id, base, fields);
true
}
pub fn show_form(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut f = app.dialog_state.form.clone();
let (mut ok, mut close) = (false, false);
let h = 120.0 + f.fields.len() as f32 * 30.0;
super::dialogs::modal(ctx, &f.title.clone(), vec2(440.0, h), t, |ui| {
egui::Grid::new("form-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
for fl in &mut f.fields {
ui.label(&fl.label);
match &mut fl.kind {
FieldKind::Number { value, speed } => {
ui.add(egui::DragValue::new(value).speed(*speed).max_decimals(3));
}
FieldKind::Text(s) => {
ui.add(egui::TextEdit::singleline(s).desired_width(220.0));
}
FieldKind::Bool(b) => {
ui.checkbox(b, "");
}
FieldKind::Choice { options, sel } => {
let cur = options.get(*sel).map(|o| o.0.clone()).unwrap_or_default();
egui::ComboBox::from_id_salt(("form", fl.key.as_str())).selected_text(cur).width(240.0).show_ui(ui, |ui| {
for (i, (l, _)) in options.iter().enumerate() {
ui.selectable_value(sel, i, l);
}
});
}
}
ui.end_row();
}
});
ui.add_space(14.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
ok = true;
}
if ui.button("Cancel").clicked() {
close = true;
}
});
});
let enter = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Enter));
app.dialog_state.form = f.clone();
if ok || enter {
app.dialog = None;
let params = f.params();
if let Err(e) = app.session.execute(&f.command, params) {
app.ui.status = e.to_string();
}
return;
}
if close {
app.dialog = None;
}
}
pub fn show_info(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let (title, body) = app.dialog_state.info.clone();
let mut close = false;
super::dialogs::modal(ctx, &title, vec2(440.0, 160.0), t, |ui| {
ui.label(body);
ui.add_space(16.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
close = true;
}
});
});
if close {
app.dialog = None;
}
}
pub const SETTINGS_PAGES: [(&str, &str); 17] = [
("general", "General"),
("startup", "Startup & Repair"),
("project", "Project"),
("composition", "Composition"),
("previews", "Previews"),
("appearance", "Appearance"),
("grids", "Grids & Guides"),
("labels", "Labels"),
("type", "Type"),
("import", "Import"),
("export", "Export"),
("audio", "Audio"),
("disk", "Disk"),
("memory", "Memory & CPU"),
("video", "Video"),
("3d", "3D"),
("scripting", "Scripting & Expressions"),
];
pub fn show_settings(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut page = app.dialog_state.settings_page.clone();
let mut close = false;
let mut theme = None;
super::dialogs::modal(ctx, "Settings", vec2(640.0, 440.0), t, |ui| {
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(170.0);
for (id, label) in SETTINGS_PAGES {
if ui.selectable_label(page == id, label).clicked() {
page = id.to_string();
}
}
});
ui.separator();
ui.vertical(|ui| {
let title = SETTINGS_PAGES.iter().find(|p| p.0 == page).map(|p| p.1).unwrap_or("General");
ui.label(egui::RichText::new(title).font(Tokens::semibold(13.0)));
ui.add_space(8.0);
match page.as_str() {
"general" => {
ui.checkbox(&mut app.ui.show_menu_bar, "Show the in-window menu bar");
ui.checkbox(&mut app.ui.snapping, "Snapping");
}
"appearance" => {
for (k, name) in [("dark", "Dark"), ("darker", "Darker"), ("light", "Light")] {
if ui.button(name).clicked() {
theme = crate::theme::ThemeKind::from_name(k);
}
}
}
"previews" => {
ui.checkbox(&mut app.ui.cache_when_idle, "Cache frames when idle");
ui.checkbox(&mut app.ui.viewer.fast_preview, "Fast previews");
}
"grids" => {
ui.checkbox(&mut app.ui.viewer.grid, "Show grid");
ui.checkbox(&mut app.ui.viewer.guides, "Show guides");
ui.checkbox(&mut app.ui.viewer.safe_margins, "Show title/action safe");
}
"labels" => {
for l in effectcraft_engine::color::Label::ALL.into_iter().skip(1) {
ui.horizontal(|ui| {
let [r, g, b] = l.rgb();
let (rect, _) = ui.allocate_exact_size(vec2(26.0, 14.0), egui::Sense::hover());
ui.painter().rect_filled(rect, 2.0, Color32::from_rgb(r, g, b));
ui.label(l.name());
});
}
}
_ => {
ui.label(egui::RichText::new("No options on this page yet.").color(t.text_dim));
}
}
});
});
ui.add_space(10.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
close = true;
}
});
});
app.dialog_state.settings_page = page;
if let Some(k) = theme {
app.set_theme(ctx, k);
}
if close {
app.dialog = None;
}
}
pub fn show_shortcuts(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut q = app.dialog_state.palette_query.clone();
let mut close = false;
// (shortcut, where, label)
let mut rows: Vec<(String, String, String)> = vec![];
for (path, e) in effectcraft_engine::menus::entries() {
if let Some(sc) = &e.shortcut {
rows.push((crate::menus::shortcut_text(sc), path.join(" ▸ "), e.label.clone()));
}
}
for c in effectcraft_engine::command_specs().iter().filter(|c| c.menu.is_empty()) {
if let Some(sc) = c.shortcut
&& !rows.iter().any(|r| r.2 == c.label)
{
rows.push((crate::menus::shortcut_text(sc), "Commands".into(), c.label.to_string()));
}
}
for c in crate::menus::UI_COMMANDS {
if let Some(sc) = c.shortcut {
rows.push((crate::menus::shortcut_text(sc), "Panels & Tools".into(), c.label.to_string()));
}
}
super::dialogs::modal(ctx, "Keyboard Shortcuts", vec2(640.0, 520.0), t, |ui| {
ui.add(egui::TextEdit::singleline(&mut q).hint_text("Search commands or shortcuts").desired_width(f32::INFINITY));
ui.add_space(8.0);
let ql = q.to_lowercase();
egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| {
egui::Grid::new("shortcut-grid").num_columns(3).striped(true).spacing([18.0, 4.0]).show(ui, |ui| {
for (sc, place, label) in rows.iter().filter(|r| ql.is_empty() || format!("{} {} {}", r.0, r.1, r.2).to_lowercase().contains(&ql)) {
ui.label(egui::RichText::new(sc).monospace());
ui.label(label);
ui.label(egui::RichText::new(place).color(t.text_dim));
ui.end_row();
}
});
});
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
close = true;
}
});
});
app.dialog_state.palette_query = q;
if close {
app.dialog = None;
}
}
pub fn show_view_options(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut close = false;
super::dialogs::modal(ctx, "View Options", vec2(360.0, 330.0), t, |ui| {
let v = &mut app.ui.viewer;
ui.checkbox(&mut v.show_layer_controls, "Layer controls");
ui.checkbox(&mut v.show_masks, "Masks");
ui.checkbox(&mut v.rulers, "Rulers");
ui.checkbox(&mut v.guides, "Guides");
ui.checkbox(&mut v.grid, "Grid");
ui.checkbox(&mut v.safe_margins, "Title/action safe");
ui.checkbox(&mut v.transparency_grid, "Transparency grid");
ui.add_space(12.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
close = true;
}
});
});
if close {
app.dialog = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn form_params_build_arrays_and_choices() {
let f = Form {
title: "T".into(),
command: "layer.setTransform".into(),
base: json!({"prop": "position"}),
fields: vec![
Field::num("value[0]", "X", 10.0),
Field::num("value[1]", "Y", 20.0),
Field::choice("mode", "M", &[("A", json!("a")), ("B", json!("b"))], 1),
],
};
assert_eq!(f.params(), json!({"prop": "position", "value": [10.0, 20.0], "mode": "b"}));
}
}
+89 -10
View File
@@ -1,6 +1,6 @@
//! Smaller panels: Preview, Audio, History, Markers, Wiggler, the Home screen and placeholders.
use egui::{Align2, Color32, Rect, Sense, pos2, vec2};
use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};
use serde_json::json;
use crate::dock::PanelKind;
@@ -51,6 +51,12 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
app.auto.add("preview.loop", lr, "Loop");
p.text(pos2(lr.max.x + 6.0, yy), Align2::LEFT_CENTER, "Loop", Tokens::ui(12.0), t.text);
let ar = Rect::from_min_size(pos2(rect.min.x + 90.0, yy - 8.0), vec2(16.0, 16.0));
if widgets::checkbox(ui, ar, app.ui.preview_audio, &t, egui::Id::new("pv-audio")).clicked() {
let _ = crate::menus::invoke(app, &ctx, "playback.audio", json!({}));
}
app.auto.add("preview.audio", ar, "Include Audio");
p.text(pos2(ar.max.x + 6.0, yy), Align2::LEFT_CENTER, "Include Audio", Tokens::ui(12.0), t.text);
yy += 24.0;
row(&p, yy, "Range", "Work Area Extended By Current Time");
yy += 22.0;
@@ -74,19 +80,92 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
/// Audio panel: L/R VU meters (dBFS, 0 to -48) with peak hold and clip indicators, fed by the
/// audio preview; the selected layer's Audio Levels on the right.
pub fn audio(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
use crate::audio::METER_FLOOR;
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
// Level meters (silent until audio playback lands).
for (i, x) in [rect.min.x + 20.0, rect.min.x + 34.0].into_iter().enumerate() {
let r = Rect::from_min_max(pos2(x, rect.min.y + 14.0), pos2(x + 10.0, rect.max.y - 20.0));
p.rect_filled(r, 1.0, t.field_bg);
let _ = i;
let top = rect.min.y + 26.0;
let bottom = rect.max.y - 22.0;
if bottom - top < 40.0 {
return;
}
for (k, db) in [0, -6, -12, -18, -24, -36, -48].iter().enumerate() {
let y = rect.min.y + 14.0 + (rect.height() - 34.0) * (-*db as f32 / 48.0);
p.text(pos2(rect.min.x + 52.0, y), Align2::LEFT_CENTER, format!("{db} dB"), Tokens::ui(10.0), t.text_faint);
let _ = k;
let y_of = |db: f32| top + (bottom - top) * (db.clamp(METER_FLOOR, 0.0) / METER_FLOOR);
let m = app.meter;
let green = Color32::from_rgb(0x3c, 0xc8, 0x5a);
let yellow = Color32::from_rgb(0xe6, 0xc8, 0x3c);
let red = Color32::from_rgb(0xe6, 0x46, 0x3c);
let seg_col = |db: f32| {
if db > -3.0 {
red
} else if db > -12.0 {
yellow
} else {
green
}
};
for c in 0..2 {
let x = rect.min.x + 18.0 + c as f32 * 16.0;
let bar = Rect::from_min_max(pos2(x, top), pos2(x + 12.0, bottom));
p.rect_filled(bar, 1.0, t.field_bg);
// Lit segments, 1.5 dB each, coloured by their level.
let lvl = m.level_db[c];
let mut db = METER_FLOOR;
while db < lvl.min(0.0) {
let hi = (db + 1.5).min(lvl);
p.rect_filled(Rect::from_min_max(pos2(bar.min.x + 1.0, y_of(hi)), pos2(bar.max.x - 1.0, y_of(db) - 0.5)), 0.0, seg_col(db));
db += 1.5;
}
if m.peak_db[c] > METER_FLOOR {
let py = y_of(m.peak_db[c]);
p.line_segment([pos2(bar.min.x, py), pos2(bar.max.x, py)], Stroke::new(2.0, seg_col(m.peak_db[c])));
}
// Clip indicator (click to reset).
let clip = Rect::from_min_max(pos2(bar.min.x, top - 14.0), pos2(bar.max.x, top - 4.0));
p.rect_filled(clip, 1.0, if m.clipped[c] { red } else { t.field_bg });
let id = if c == 0 { "audio.clipLeft" } else { "audio.clipRight" };
if ui.interact(clip, egui::Id::new(id), Sense::click()).clicked() {
app.meter.clipped[c] = false;
}
app.auto.add(id, clip, if c == 0 { "Left clip indicator" } else { "Right clip indicator" });
app.auto.add(if c == 0 { "audio.meterLeft" } else { "audio.meterRight" }, bar, &format!("{:.1} dB", m.level_db[c]));
p.text(pos2(bar.center().x, bottom + 9.0), Align2::CENTER_CENTER, if c == 0 { "L" } else { "R" }, Tokens::ui(10.0), t.text_dim);
}
let sx = rect.min.x + 54.0;
for db in [0, -6, -12, -18, -24, -30, -36, -42, -48] {
let y = y_of(db as f32);
p.line_segment([pos2(sx - 4.0, y), pos2(sx - 1.0, y)], Stroke::new(1.0, t.text_faint));
p.text(pos2(sx + 2.0, y), Align2::LEFT_CENTER, format!("{db:.1}"), Tokens::ui(10.0), t.text_faint);
}
p.text(pos2(sx + 30.0, top - 9.0), Align2::LEFT_CENTER, "dB", Tokens::ui(10.0), t.text_dim);
// Selected layer's Audio Levels.
let lx = rect.min.x + 120.0;
if rect.max.x - lx < 80.0 {
return;
}
let sel = app.session.state.selected_layers.first().copied();
let levels = sel.and_then(|id| {
let c = app.session.active_comp()?;
let l = c.layer(id)?;
let pr = l.props.sub("audio")?.get("levels")?;
Some((l.name.clone(), pr.value.as_vec2()))
});
match levels {
Some((name, [a, b])) => {
p.text(pos2(lx, top - 9.0), Align2::LEFT_CENTER, &name, Tokens::ui(11.0), t.text_dim);
for (i, (k, v)) in [("Left", a), ("Right", b)].into_iter().enumerate() {
let y = top + 12.0 + i as f32 * 20.0;
p.text(pos2(lx, y), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim);
p.text(pos2(lx + 44.0, y), Align2::LEFT_CENTER, format!("{v:+.1} dB"), Tokens::ui(12.0), t.hot_text);
}
}
None => {
p.text(pos2(lx, top + 12.0), Align2::LEFT_CENTER, "No audio layer selected", Tokens::ui(11.0), t.text_faint);
}
}
if app.meter.active() || app.audio.is_some() {
ui.ctx().request_repaint();
}
}
+2
View File
@@ -5,6 +5,7 @@ pub mod dialogs;
pub mod dialogs_3d;
pub mod effect_controls;
pub mod effects_presets;
pub mod forms;
pub mod graph;
pub mod info;
pub mod key_dialogs;
@@ -15,6 +16,7 @@ pub mod render_queue;
pub mod text_panels;
pub mod timeline;
pub mod viewer;
pub mod waveform;
use effectcraft_engine::Session;
use effectcraft_engine::project::{Comp, TimeDisplayStyle};
+80 -1
View File
@@ -38,12 +38,20 @@ enum RowKind {
uid: u64,
lines: usize,
},
/// Audio > Waveform of a footage layer with audio (drawn from the item's peak summary).
Waveform {
item: u64,
},
}
/// Synthetic group uid for a layer's Audio > Waveform twirl (never a real property uid).
const WAVE_BIT: u64 = 1 << 60;
/// Row height (expression editors grow with their text).
fn row_height(row: &Row, rh: f32) -> f32 {
match row.kind {
RowKind::Expr { lines, .. } => rh * lines.clamp(1, 8) as f32 + 6.0,
RowKind::Waveform { .. } => rh * 3.0,
_ => rh,
}
}
@@ -237,9 +245,15 @@ fn build_rows(app: &EffectcraftApp, comp: &Comp) -> Vec<Row> {
"opacity" => ("transform", vec!["opacity"]),
"anchor" => ("transform", vec!["anchor"]),
"feather" => ("masks", vec!["feather"]),
"levels" => ("audio", vec!["levels"]),
_ => ("", vec![]),
};
match kind.as_str() {
"waveform" => {
if let Some(item) = super::waveform::audio_item(&app.session.project, l) {
rows.push(Row { layer: l.id, depth: 1, kind: RowKind::Waveform { item: item.0 } });
}
}
"effects" => {
if let Some(fx) = l.effects() {
for g in fx.groups() {
@@ -282,6 +296,36 @@ fn build_rows(app: &EffectcraftApp, comp: &Comp) -> Vec<Row> {
}
}
}
"props" => {
// Animation ▸ Reveal Properties…: the engine picked the uids.
fn groups_in<'a>(g: &'a PropGroup, set: &std::collections::BTreeSet<u64>, out: &mut Vec<&'a PropGroup>) {
for sg in g.groups() {
if set.contains(&sg.uid) {
out.push(sg);
} else {
groups_in(sg, set, out);
}
}
}
let mut groups = vec![];
groups_in(&l.props, &tl.reveal_props, &mut groups);
for g in groups {
let open = tl.open_groups.contains(&g.uid);
rows.push(Row {
layer: l.id,
depth: 1,
kind: RowKind::Group { uid: g.uid, name: g.name.clone(), open, has_children: !g.children.is_empty(), fx: None, eye: None },
});
if open {
push_group(&mut rows, l, g, 2, &tl.open_groups);
}
}
let mut found = vec![];
collect_props(&l.props, &mut found, &|p| prop_visible(p, l) && tl.reveal_props.contains(&p.uid));
for uid in found {
rows.push(Row { layer: l.id, depth: 1, kind: RowKind::Prop { uid } });
}
}
_ => {
let mut found = vec![];
let root = if group.is_empty() {
@@ -319,6 +363,21 @@ fn build_rows(app: &EffectcraftApp, comp: &Comp) -> Vec<Row> {
});
if open {
push_group(&mut rows, l, g, 2, &tl.open_groups);
// Audio > Waveform > Waveform (footage with audio).
if g.match_id == "audio"
&& let Some(item) = super::waveform::audio_item(&app.session.project, l)
{
let wuid = WAVE_BIT | g.uid;
let wopen = tl.open_groups.contains(&wuid);
rows.push(Row {
layer: l.id,
depth: 2,
kind: RowKind::Group { uid: wuid, name: "Waveform".into(), open: wopen, has_children: true, fx: None, eye: None },
});
if wopen {
rows.push(Row { layer: l.id, depth: 3, kind: RowKind::Waveform { item: item.0 } });
}
}
}
}
Node::Prop(p) if prop_visible(p, l) => rows.push(Row { layer: l.id, depth: 1, kind: RowKind::Prop { uid: p.uid } }),
@@ -995,13 +1054,33 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
lp.text(pos2(ir.max.x + 4.0, cy), Align2::LEFT_CENTER, "Inverted", Tokens::ui(11.0), t.text_dim);
}
let gr = ui.interact(Rect::from_min_max(pos2(indent + 8.0, r.min.y), pos2(cw.switches, r.max.y)), egui::Id::new(("grow", uid)), Sense::click());
if gr.clicked() {
if gr.clicked() && uid & WAVE_BIT == 0 {
actions.push(("prop.select".into(), json!({"layer": layer.id.0, "prop": uid, "selectKeys": false})));
}
if gr.double_clicked() {
ui_actions.push(UiAct::ToggleGroup(*uid));
}
}
RowKind::Waveform { item } => {
lp.rect_filled(left, 0.0, if ri % 2 == 0 { t.row } else { t.row_alt });
let indent = cw.name + 6.0 + 14.0 * row.depth as f32;
lp.text(pos2(indent + 10.0, cy), Align2::LEFT_CENTER, "Waveform", Tokens::ui(12.0), t.text);
let wr = Rect::from_min_max(pos2(graph_x0, r.min.y), r.max);
gp.rect_filled(wr, 0.0, t.tl_bg);
app.auto.add(&format!("timeline.layer.{}.waveform", layer.id.0), wr, "Waveform");
match super::waveform::summary(app, &ctx, effectcraft_engine::project::ItemId(*item)) {
Some(s) => super::waveform::draw(&gp, wr.shrink2(vec2(0.0, 2.0)), &tm, layer, &s, Color32::from_rgb(0x5f, 0xc8, 0x8a)),
None => {
gp.text(
pos2(tm.x(layer.in_point.seconds()).max(wr.min.x) + 6.0, wr.center().y),
Align2::LEFT_CENTER,
"Building waveform…",
Tokens::ui(11.0),
t.text_faint,
);
}
}
}
RowKind::Expr { uid, lines } => {
let Some(prop) = layer.props.find(*uid) else { continue };
let Some(ex) = prop.expr.clone() else { continue };
+30 -2
View File
@@ -263,7 +263,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let bar_h = 30.0;
let bar = Rect::from_min_max(pos2(rect.min.x, rect.max.y - bar_h), rect.max);
let area = Rect::from_min_max(pos2(rect.min.x, nav.max.y), pos2(rect.max.x, bar.min.y));
p.rect_filled(area, 0.0, t.pasteboard);
let pasteboard = app.ui.viewer.pasteboard.map(|[r, g, b]| Color32::from_rgb(r, g, b)).unwrap_or(t.pasteboard);
p.rect_filled(area, 0.0, pasteboard);
let (cw, ch) = (comp.width as f32, comp.height as f32);
let fit = ((area.width() - 40.0) / cw).min((area.height() - 40.0) / ch).max(0.01);
@@ -340,6 +341,24 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
// Comp guides (View ▸ Show Guides) and the region of interest.
if app.ui.viewer.guides {
let stroke = Stroke::new(1.0, Color32::from_rgb(0x3c, 0xc8, 0xf0));
for g in &comp.guides {
if g.vertical {
let x = comp_rect.min.x + g.position as f32 * zoom;
painter.line_segment([pos2(x, area.min.y), pos2(x, area.max.y)], stroke);
} else {
let y = comp_rect.min.y + g.position as f32 * zoom;
painter.line_segment([pos2(area.min.x, y), pos2(area.max.x, y)], stroke);
}
}
}
if let Some([rx, ry, rw, rh]) = app.session.state.region_of_interest {
let r = Rect::from_min_size(comp_rect.min + vec2(rx as f32 * zoom, ry as f32 * zoom), vec2(rw as f32 * zoom, rh as f32 * zoom));
painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::WHITE), StrokeKind::Middle);
}
// Overlays + interaction.
let snap_project = app.session.project.clone();
let snap_expr = app.session.expr.clone();
@@ -1207,7 +1226,16 @@ fn bottom_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, zoom: f32,
app.ui.viewer.res = Resolution::ALL[i];
}
x = r.max.x + 6.0;
let _ = tog(ui, &mut app.auto, &mut x, Icon::Region, false, "roi", "Region of Interest");
let has_roi = app.session.state.region_of_interest.is_some();
if tog(ui, &mut app.auto, &mut x, Icon::Region, has_roi, "roi", "Region of Interest") {
// Toggle a centred region of interest (Composition ▸ Crop Comp to Region of Interest).
let rect = if has_roi {
serde_json::Value::Null
} else {
json!([comp.width as f64 / 4.0, comp.height as f64 / 4.0, comp.width as f64 / 2.0, comp.height as f64 / 2.0])
};
let _ = app.session.execute("view.setRegionOfInterest", json!({"rect": rect}));
}
if tog(ui, &mut app.auto, &mut x, Icon::Checker, app.ui.viewer.transparency_grid, "transparency", "Toggle Transparency Grid") {
app.ui.viewer.transparency_grid = !app.ui.viewer.transparency_grid;
}
+95
View File
@@ -0,0 +1,95 @@
//! Audio waveforms for the Timeline's Audio > Waveform property (revealed with `LL`).
//!
//! Each footage item's audio is summarised once into min/max peaks
//! (`effectcraft_render::audio::footage_peaks`, [`BINS_PER_SEC`] bins per second) on a
//! background thread; the timeline draws from that summary at any zoom.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use effectcraft_engine::project::{ItemId, ItemKind, Layer, LayerSource, Project};
use effectcraft_engine::time::Tick;
use egui::{Color32, Painter, Rect, Stroke, pos2};
use super::timeline::TMap;
use crate::EffectcraftApp;
/// Peak-summary resolution.
pub const BINS_PER_SEC: u32 = 200;
/// A footage item's peak summary: `[min L, max L, min R, max R]` per bin.
pub struct Summary {
pub bins_per_sec: u32,
pub peaks: Vec<[f32; 4]>,
}
/// Summaries by footage item (`None` while computing).
#[derive(Default)]
pub struct Cache {
map: Arc<Mutex<HashMap<u64, Option<Arc<Summary>>>>>,
}
/// The footage item whose audio a layer plays, when it has audio.
pub fn audio_item(project: &Project, l: &Layer) -> Option<ItemId> {
let LayerSource::Footage { item } = &l.source else { return None };
match &project.item(*item)?.kind {
ItemKind::Footage(f) if f.has_audio && !f.missing => Some(*item),
_ => None,
}
}
/// The summary for `item`, starting its computation on first request.
pub fn summary(app: &EffectcraftApp, ctx: &egui::Context, item: ItemId) -> Option<Arc<Summary>> {
let mut m = app.waveforms.map.lock().ok()?;
if let Some(s) = m.get(&item.0) {
return s.clone();
}
let ItemKind::Footage(f) = &app.session.project.item(item)?.kind else { return None };
m.insert(item.0, None);
let (f, footage, map, ctx) = (f.clone(), app.session.footage.clone(), app.waveforms.map.clone(), ctx.clone());
std::thread::Builder::new()
.name("ec-waveform".into())
.spawn(move || {
let peaks = effectcraft_engine::render::audio::footage_peaks(footage.as_ref(), item, &f, f.duration, BINS_PER_SEC);
if let Ok(mut m) = map.lock() {
m.insert(item.0, Some(Arc::new(Summary { bins_per_sec: BINS_PER_SEC, peaks })));
}
ctx.request_repaint();
})
.ok()?;
None
}
/// Draw `layer`'s waveform in `rect` (left channel above right), columns mapped through the
/// timeline's time map and the layer's time mapping, limited to its [in, out) span.
pub(crate) fn draw(p: &Painter, rect: Rect, tm: &TMap, layer: &Layer, s: &Summary, color: Color32) {
let mid = [rect.min.y + rect.height() * 0.25, rect.min.y + rect.height() * 0.75];
let half = rect.height() * 0.25 - 1.0;
let x0 = tm.x(layer.in_point.seconds()).max(rect.min.x).floor() as i32;
let x1 = tm.x(layer.out_point.seconds()).min(rect.max.x).ceil() as i32;
let n = s.peaks.len() as i64;
for c in 0..2 {
p.line_segment([pos2(x0 as f32, mid[c]), pos2(x1 as f32, mid[c])], Stroke::new(1.0, color.gamma_multiply(0.5)));
}
for x in x0..x1 {
let (ta, tb) = (tm.t(x as f32), tm.t(x as f32 + 1.0));
let src = |t: f64| layer.layer_time(Tick::from_seconds_f64(t)).seconds() * s.bins_per_sec as f64;
let (ba, bb) = (src(ta).floor() as i64, src(tb).ceil() as i64);
let (ba, bb) = (ba.min(bb).clamp(0, n), ba.max(bb).max(ba + 1).clamp(0, n));
if ba >= bb {
continue;
}
let mut agg = [0.0f32; 4];
for b in &s.peaks[ba as usize..bb as usize] {
agg[0] = agg[0].min(b[0]);
agg[1] = agg[1].max(b[1]);
agg[2] = agg[2].min(b[2]);
agg[3] = agg[3].max(b[3]);
}
for c in 0..2 {
let (lo, hi) = (agg[c * 2].clamp(-1.0, 1.0), agg[c * 2 + 1].clamp(-1.0, 1.0));
let (ya, yb) = (mid[c] - hi * half, mid[c] - lo * half);
p.line_segment([pos2(x as f32 + 0.5, ya), pos2(x as f32 + 0.5, yb.max(ya + 1.0))], Stroke::new(1.0, color));
}
}
}
+26
View File
@@ -199,6 +199,7 @@ impl Resolution {
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct ViewerState {
/// Magnification (1 = 100%); None = fit.
pub zoom: Option<f32>,
@@ -213,6 +214,14 @@ pub struct ViewerState {
pub channel: String,
pub show_layer_controls: bool,
pub fast_preview: bool,
/// View ▸ Show Guides / Snap to Guides / Lock Guides / Snap to Grid.
pub guides: bool,
pub snap_guides: bool,
pub lock_guides: bool,
pub snap_grid: bool,
/// View ▸ Panel Background Color (`None` = theme default).
pub pasteboard: Option<[u8; 3]>,
pub custom_pasteboard: [u8; 3],
}
impl Default for ViewerState {
@@ -229,6 +238,12 @@ impl Default for ViewerState {
channel: "RGB".into(),
show_layer_controls: true,
fast_preview: false,
guides: true,
snap_guides: false,
lock_guides: false,
snap_grid: false,
pasteboard: None,
custom_pasteboard: [0x80, 0x80, 0x80],
}
}
}
@@ -249,6 +264,9 @@ pub struct TimelineState {
pub open_groups: BTreeSet<u64>,
/// "Reveal" filter: only show these property match ids (P/S/R/T/A…) — empty = normal.
pub reveal: Vec<String>,
/// Properties / groups (uids) shown by the `props` reveal (Animation ▸ Reveal Properties…).
#[serde(default)]
pub reveal_props: BTreeSet<u64>,
/// Graph Editor: `value` or `speed` graph.
#[serde(default = "value_graph")]
pub graph_mode: String,
@@ -286,6 +304,7 @@ impl Default for TimelineState {
open_layers: BTreeSet::new(),
open_groups: BTreeSet::new(),
reveal: vec![],
reveal_props: BTreeSet::new(),
graph_mode: value_graph(),
graph_show_selected: true,
graph_auto_zoom: true,
@@ -338,7 +357,12 @@ pub struct UiState {
/// Preview panel options.
pub preview_loop: bool,
pub preview_cache_first: bool,
/// Preview panel "Include Audio" (Mute Audio off).
#[serde(default = "yes")]
pub preview_audio: bool,
pub start_screen: bool,
/// Composition ▸ Preview ▸ Cache Frames When Idle.
pub cache_when_idle: bool,
}
impl Default for UiState {
@@ -369,7 +393,9 @@ impl Default for UiState {
tool_creates_shape: true,
preview_loop: true,
preview_cache_first: false,
preview_audio: true,
start_screen: false,
cache_when_idle: false,
}
}
}