Merge upstream/main into gap-object-matte

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76
2026-10-12 19:03:42 +02:00
co-authored by Claude Sonnet 5.5
275 changed files with 24783 additions and 1912 deletions
+21 -1
View File
@@ -41,7 +41,8 @@ pub fn color_popup(ui: &mut Ui, id: egui::Id, pos: egui::Pos2, c: &mut [f32; 3])
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos + vec2(0.0, 4.0)).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| out = color_picker(ui, id, c, original));
});
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
// Escape is the picker's: consume it, so nothing later this pass takes it too.
if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
out.close = Some(false);
}
if pressed_outside(ui.ctx(), &area.response) {
@@ -55,11 +56,30 @@ pub fn color_popup(ui: &mut Ui, id: egui::Id, pos: egui::Pos2, c: &mut [f32; 3])
ui.data_mut(|d| {
d.insert_temp(id.with("open"), false);
d.remove::<[f32; 3]>(orig_id);
// Closed: the next Escape is the dialog's again.
d.remove::<u64>(open_pass_id());
});
} else {
// Still open after this pass: dialogs leave Escape to the picker (see `open_recently`).
let pass = ui.ctx().cumulative_pass_nr();
ui.data_mut(|d| d.insert_temp(open_pass_id(), pass));
}
out.changed
}
fn open_pass_id() -> egui::Id {
egui::Id::new("color-picker-open-pass")
}
/// A colour picker is open: it was drawn, and stayed open, in this pass or the last one (so one
/// that stops being drawn without closing, its dialog gone, doesn't count for long). Escape then
/// belongs to the picker (it goes back to the original colour and closes), not to the dialog it
/// was opened from. Closing clears this at once, so the next Escape reaches the dialog.
pub fn open_recently(ctx: &egui::Context) -> bool {
let pass: Option<u64> = ctx.data(|d| d.get_temp(open_pass_id()));
pass.is_some_and(|p| p.saturating_add(1) >= ctx.cumulative_pass_nr())
}
/// What the picker did this frame.
#[derive(Default)]
struct Outcome {
+21 -2
View File
@@ -223,8 +223,16 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
if let Some(z) = v.get("zoom") {
app.ui.viewer.zoom = z.as_f64().map(|z| z as f32);
}
// The active comp's Resolution (`view.res.*`), saved with the project.
if let Some(r) = v.get("res").and_then(Value::as_str) {
app.ui.viewer.res = Resolution::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r)).unwrap_or(app.ui.viewer.res);
let Some(res) = Resolution::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r)) else {
return err(format!("unknown resolution `{r}` (auto, full, half, third, quarter)"));
};
if let Some(cid) = app.session.active_comp_id()
&& let Err(e) = app.session.set_resolution(cid, res)
{
return err(e);
}
}
if let Some(Value::Array(a)) = v.get("pan") {
app.ui.viewer.pan = [a.first().and_then(Value::as_f64).unwrap_or(0.0) as f32, a.get(1).and_then(Value::as_f64).unwrap_or(0.0) as f32];
@@ -308,6 +316,9 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
Err(e) => return err(e),
};
let m = modifiers(p);
// egui keeps the modifiers from `ModifiersChanged` (not the ones on a pointer event)
// and the synthetic events arrive one per frame: hold them for the whole gesture.
app.synthetic.push(egui::Event::ModifiersChanged(m));
app.synthetic.push(egui::Event::PointerMoved(pos));
if req.method == "ui.click" {
let button = match s("button") {
@@ -321,6 +332,7 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: m });
}
}
app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
Outcome::AfterInput
}
"ui.drag" => {
@@ -332,6 +344,7 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
};
let steps = p.get("steps").and_then(Value::as_u64).unwrap_or(12).max(2);
let m = modifiers(p);
app.synthetic.push(egui::Event::ModifiersChanged(m));
app.synthetic.push(egui::Event::PointerMoved(a));
app.synthetic.push(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: m });
for i in 1..=steps {
@@ -339,6 +352,7 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
app.synthetic.push(egui::Event::PointerMoved(a + (b - a) * f));
}
app.synthetic.push(egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: m });
app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
Outcome::AfterInput
}
"ui.scroll" => {
@@ -522,11 +536,16 @@ pub fn inspect(app: &EffectcraftApp, ctx: &egui::Context) -> Value {
let automation_id = app.auto.elements.iter().chain(app.auto.previous.iter()).find(|e| e.response_id == Some(id)).map(|e| e.id.as_str());
json!({"id": format!("{:016x}", id.value()), "rect": rect, "automationId": automation_id, "registryCandidates": candidates})
});
let mut ui = json!(app.ui);
// The viewer's Resolution is the active comp's (kept in the project).
if let Some(v) = ui.get_mut("viewer").and_then(Value::as_object_mut) {
v.insert("res".into(), json!(app.viewer_res()));
}
json!({
"window": [size.x, size.y],
"pixelsPerPoint": ctx.pixels_per_point(),
"fps": app.fps,
"ui": app.ui,
"ui": ui,
"playing": app.playback.playing,
"time": app.session.time().seconds(),
"activeComp": app.session.state.active_comp.map(|i| i.0),
+35 -1
View File
@@ -670,6 +670,37 @@ pub struct Floating {
pub rect: [f32; 4],
}
/// A floating group moved out of the main window into its own native window (which can sit on
/// another monitor): the group holding `panel` shows there.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct PanelWindow {
pub panel: PanelKind,
/// The window's [x, y] outer position and [w, h] inner size, in desktop points.
pub rect: [f32; 4],
}
/// The smallest and largest native panel window, in points.
pub const PANEL_WINDOW_MIN: [f32; 2] = [160.0, 100.0];
pub const PANEL_WINDOW_MAX: f32 = 16_384.0;
/// The farthest a native panel window may sit from the desktop origin, in points.
pub const PANEL_WINDOW_MAX_POS: f32 = 100_000.0;
impl PanelWindow {
/// The rect made safe to hand to the windowing system: finite, with a size within
/// [`PANEL_WINDOW_MIN`]..=[`PANEL_WINDOW_MAX`] and a position within
/// ±[`PANEL_WINDOW_MAX_POS`] (hostile workspace files and bad monitor reports included).
pub fn sanitized(rect: [f32; 4]) -> [f32; 4] {
let finite = |v: f32, fallback: f32| if v.is_finite() { v } else { fallback };
let [x, y, w, h] = rect;
[
finite(x, 0.0).clamp(-PANEL_WINDOW_MAX_POS, PANEL_WINDOW_MAX_POS),
finite(y, 0.0).clamp(-PANEL_WINDOW_MAX_POS, PANEL_WINDOW_MAX_POS),
finite(w, 420.0).clamp(PANEL_WINDOW_MIN[0], PANEL_WINDOW_MAX),
finite(h, 320.0).clamp(PANEL_WINDOW_MIN[1], PANEL_WINDOW_MAX),
]
}
}
impl DockNode {
/// Insert panel `p` relative to the group that holds `anchor`: as a tab next to it
/// (Center) or in a new group split off to one side. In a stack, the group is `anchor`'s
@@ -1305,10 +1336,13 @@ pub fn draw_group_chrome(ui: &mut egui::Ui, g: &Group, t: &Tokens, reg: &mut cra
}
}
}
// clicking anywhere in the panel focuses it
// clicking anywhere in the panel focuses it; a press on another of its tabs waits for that
// tab's click, which focuses the panel actually chosen (a text edit stays open in Character)
let at = ui.input(|i| i.pointer.interact_pos());
if let Some(p) = active_panel
&& ui.rect_contains_pointer(g.rect)
&& ui.input(|i| i.pointer.any_pressed())
&& !out.tabs.iter().any(|(q, r)| *q != p && at.is_some_and(|a| r.contains(a)))
{
out.actions.push(DockAction::Focus(p));
}
+152 -2
View File
@@ -2,11 +2,13 @@
//! and body, floating (undocked) panel groups over it, and tab drag-and-drop: drag a tab onto a
//! group to tab it there (center) or split it off to a side (After Effects' drop zones, with a
//! highlight of where it will land); hold Cmd/Ctrl when releasing, or drop outside every group,
//! to float it. `` ` `` maximizes the panel under the pointer.
//! to float it. `` ` `` maximizes the panel under the pointer. A floating group can also move
//! out of the main window into its own native window ([`EffectcraftApp::set_panel_window`]),
//! which can sit on another monitor.
use egui::{Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use crate::dock::{self, DockAction, DockNode, Group, Layout, PanelKind};
use crate::dock::{self, DockAction, DockNode, Group, Layout, PanelKind, PanelWindow};
use crate::{EffectcraftApp, panels};
use craft_ui::docking::{Action, DropTarget, resolve_drop};
@@ -245,7 +247,15 @@ impl EffectcraftApp {
})
.unwrap_or(usize::MAX)
});
// A native window is kept only for a panel that still floats.
let ui_state = &mut self.ui;
ui_state.panel_windows.retain(|w| ui_state.floating.iter().any(|group| group.panels.contains(&w.panel)));
for i in floating_order {
// Groups in their own native window take no tab drops from the main window.
if let Some(window) = self.ui.floating.get(i).and_then(|group| self.panel_window_of(&group.panels)) {
self.panel_window(&ctx, i, window, &info, &mut actions);
continue;
}
if let Some((g, tabs)) = self.floating_window(&ctx, i, &info, &mut actions) {
tab_rects.push((g.path.clone(), tabs));
float_groups.push(g);
@@ -264,6 +274,7 @@ impl EffectcraftApp {
}
DockAction::Focus(p) => {
self.ui.focused = p;
panels::viewer_text::panel_clicked(self, &ctx, p);
// A click in (or on the tab of) another Composition viewer makes it active.
if let Some(id) = panels::viewers::id_of(p) {
panels::viewers::activate(self, &ctx, id);
@@ -376,6 +387,135 @@ impl EffectcraftApp {
group
}
/// The native window a floating group (its `panels`) shows in, if any.
pub(crate) fn panel_window_of(&self, panels: &[PanelKind]) -> Option<PanelWindow> {
self.ui.panel_windows.iter().find(|w| panels.contains(&w.panel)).copied()
}
/// Whether panel `p` shows in its own native window.
pub fn in_panel_window(&self, p: PanelKind) -> bool {
self.ui.floating.iter().any(|group| group.panels.contains(&p) && self.panel_window_of(&group.panels).is_some())
}
/// The viewport panel `p` is drawn in: its native window's, or the main window's (also when
/// the platform embeds viewports, as the browser build does).
pub(crate) fn panel_viewport(&self, ctx: &egui::Context, p: PanelKind) -> egui::ViewportId {
if ctx.embed_viewports() {
return egui::ViewportId::ROOT;
}
self.ui
.floating
.iter()
.find(|group| group.panels.contains(&p))
.and_then(|group| self.panel_window_of(&group.panels))
.map_or(egui::ViewportId::ROOT, |w| panel_window_id(w.panel))
}
/// Move panel `p` (and the floating group it is in) into its own native window, which can be
/// placed on another monitor, or back into the main window (`window` false; it floats there
/// where it was before). `None` toggles. A docked panel is undocked first. The window opens
/// over the place the panel had in the main window. Returns whether `p` is now in a window.
pub fn set_panel_window(&mut self, ctx: &egui::Context, p: PanelKind, window: Option<bool>) -> Result<bool, String> {
let group_of = |app: &Self| app.ui.floating.iter().find(|group| group.panels.contains(&p)).map(|group| (group.panels.clone(), group.rect));
let current = self.in_panel_window(p);
let window = window.unwrap_or(!current);
if window == current {
return Ok(current);
}
if !window {
if let Some((panels, _)) = group_of(self) {
self.ui.panel_windows.retain(|w| !panels.contains(&w.panel));
}
return Ok(false);
}
if group_of(self).is_none() {
if !self.ui.dock.contains(p) {
return Err(format!("{} is not open", p.title()));
}
let rect = default_float_rect(ctx.input_for(egui::ViewportId::ROOT, |i| i.content_rect()));
if !self.edit_layout(|layout| layout.float(p, rect)) {
return Err(format!("can't undock {}", p.title()));
}
}
let Some((_, [x, y, w, h])) = group_of(self) else { return Err(format!("can't undock {}", p.title())) };
// Over the panel's place in the main window (its content's position on the desktop).
let origin = ctx.input_for(egui::ViewportId::ROOT, |i| i.viewport().inner_rect.map(|r| r.min)).unwrap_or(pos2(0.0, 0.0));
let rect = PanelWindow::sanitized([origin.x + x, origin.y + y, w, h]);
ctx.data_mut(|d| d.remove::<[f32; 4]>(panel_window_spawn_id(p)));
self.ui.panel_windows.push(PanelWindow { panel: p, rect });
if self.ui.maximized == Some(p) {
self.ui.maximized = None;
}
Ok(true)
}
/// One floating group in its own native window: the group's tab strip and active panel fill
/// the window. Closing the window brings the group back into the main window.
fn panel_window(&mut self, ctx: &egui::Context, i: usize, window: PanelWindow, info: &dock::TabInfo, actions: &mut Vec<DockAction>) {
let t = self.tokens;
let Some(f) = self.ui.floating.get(i).cloned() else { return };
let active = f.active.min(f.panels.len().saturating_sub(1));
let Some(shown) = f.panels.get(active).copied() else { return };
// The window opens at its saved place; after that the window system owns its position and
// size (handing them back every frame would fight the user dragging it).
let spawn_id = panel_window_spawn_id(window.panel);
let spawn = ctx.data_mut(|d| *d.get_temp_mut_or_insert_with(spawn_id, || PanelWindow::sanitized(window.rect)));
let builder = egui::ViewportBuilder::default()
.with_title((info.title)(shown))
.with_position([spawn[0], spawn[1]])
.with_inner_size([spawn[2], spawn[3]])
.with_min_inner_size(dock::PANEL_WINDOW_MIN);
let mut closed = false;
let mut placed = None;
ctx.show_viewport_immediate(panel_window_id(window.panel), builder, |ui, class| {
let native = matches!(class, egui::ViewportClass::Immediate | egui::ViewportClass::Deferred);
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.panel_bg)).show(ui, |ui| {
let r = ui.max_rect();
let g = Group {
path: format!("w{i}"),
rect: r,
content: Rect::from_min_max(pos2(r.min.x, (r.min.y + t.tab_h).min(r.max.y)), r.max),
panels: f.panels.clone(),
active,
stacked: None,
};
let c = dock::draw_group_chrome(ui, &g, &t, &mut self.auto, info);
// Tabs can't be dragged between native windows yet.
actions.extend(c.actions.into_iter().filter(|a| !matches!(a, DockAction::BeginDrag(_))));
self.panel_body(ui, shown, g.content);
if shown == self.ui.focused {
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside);
}
if native {
panels::panel_menu_popup(self, ui);
}
});
// An embedded window (no native windows on this platform) reads the main window's
// input: its close request and place aren't this window's.
if native {
closed = ui.input(|i| i.viewport().close_requested());
placed = ui.input(|i| {
let v = i.viewport();
let inner = v.inner_rect?;
let min = v.outer_rect.map_or(pos2(window.rect[0], window.rect[1]), |outer| outer.min);
Some([min.x, min.y, inner.width(), inner.height()])
});
}
});
if closed {
self.ui.panel_windows.retain(|w| !f.panels.contains(&w.panel));
ctx.data_mut(|d| d.remove::<[f32; 4]>(spawn_id));
return;
}
// Remember where the window is, so the workspace reopens it there.
if let Some(rect) = placed.map(PanelWindow::sanitized)
&& rect != window.rect
&& let Some(w) = self.ui.panel_windows.iter_mut().find(|w| w.panel == window.panel)
{
w.rect = rect;
}
}
/// A tab being dragged. Over a tab strip (or the middle of a group) it shows where the tab
/// will land: an insertion mark between two tabs (a drop there reorders a group's own tabs
/// too); near a group's edge, the half it will split off. On release it lands there (or
@@ -460,6 +600,16 @@ fn insertion_mark(painter: &egui::Painter, x: f32, strip: Rect, col: Color32) {
}
}
/// The native window of the floating group whose window entry names `panel`.
pub fn panel_window_id(panel: PanelKind) -> egui::ViewportId {
egui::ViewportId::from_hash_of(("effectcraft-panel-window", panel.id()))
}
/// Where a native panel window was told to open (kept for as long as it stays open).
fn panel_window_spawn_id(panel: PanelKind) -> egui::Id {
egui::Id::new(("panel-window-spawn", panel.id()))
}
/// A new floating group's default rect near the centre of `screen`.
pub fn default_float_rect(screen: Rect) -> [f32; 4] {
let c = screen.center();
@@ -0,0 +1,479 @@
//! Cached viewer diagnostics. Native scans run on one persistent worker, never while painting.
//! Each viewer keeps only its newest request; obsolete scans stop between properties. On the
//! single-threaded web build, one shared scan runs after interaction settles (no thread fallback).
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(not(target_arch = "wasm32"))]
use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use effectcraft_engine::Session;
use effectcraft_engine::commands::expr_tools::{self, ExprError};
use effectcraft_engine::project::{ItemId, Project};
use effectcraft_engine::render::{EvalCtx, ExprHost, FootageSource};
use effectcraft_engine::time::Tick;
use web_time::Instant;
const QUIET: Duration = Duration::from_millis(150);
const MAX_VIEWERS: usize = 8;
type Errors = Arc<[ExprError]>;
type SyntaxCheck = fn(&str) -> Result<(), String>;
#[derive(Clone)]
struct Snapshot {
project: Arc<Project>,
revision: u64,
comp: ItemId,
time: Tick,
expr: Option<Arc<dyn ExprHost>>,
footage: Arc<dyn FootageSource>,
check: Option<SyntaxCheck>,
}
impl Snapshot {
fn new(s: &Session, comp: ItemId) -> Self {
Self {
project: s.project.clone(),
revision: s.revision,
comp,
time: s.time_of(comp),
expr: s.expr.clone(),
footage: s.footage.clone(),
check: s.expr_check,
}
}
fn matches(&self, s: &Session, comp: ItemId) -> bool {
self.revision == s.revision && self.comp == comp && self.time == s.time_of(comp) && Arc::ptr_eq(&self.project, &s.project)
}
}
struct Request {
snapshot: Snapshot,
cancelled: Arc<AtomicBool>,
#[cfg(not(target_arch = "wasm32"))]
repaint: egui::Context,
}
struct Completed {
#[cfg(not(target_arch = "wasm32"))]
comp: ItemId,
#[cfg(not(target_arch = "wasm32"))]
cancelled: Arc<AtomicBool>,
result: Result<Option<Vec<ExprError>>, String>,
}
impl Request {
fn run(&self) -> Completed {
let s = &self.snapshot;
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let comp = s.project.comp(s.comp)?;
let ctx = EvalCtx { expr: s.expr.as_deref(), footage: Some(s.footage.as_ref()), ..EvalCtx::new(&s.project, s.comp, comp, s.time) };
expr_tools::errors_in(&ctx, s.check, || !self.cancelled.load(Ordering::Relaxed))
}))
.map_err(|_| "Expression diagnostics stopped unexpectedly; edit an expression to retry.".to_string());
Completed {
#[cfg(not(target_arch = "wasm32"))]
comp: s.comp,
#[cfg(not(target_arch = "wasm32"))]
cancelled: self.cancelled.clone(),
result,
}
}
}
struct Entry {
snapshot: Snapshot,
changed: Instant,
cancelled: Arc<AtomicBool>,
submitted: bool,
errors: Errors,
}
impl Drop for Entry {
fn drop(&mut self) {
self.cancelled.store(true, Ordering::Relaxed);
}
}
#[derive(Default)]
pub(crate) struct Diagnostics {
entries: VecDeque<Entry>,
#[cfg(not(target_arch = "wasm32"))]
worker: Option<Worker>,
failure: Option<String>,
}
impl Diagnostics {
pub fn clear(&mut self) {
self.entries.clear();
}
pub fn take_failure(&mut self) -> Option<String> {
self.failure.take()
}
/// Paint from completed results only. Changes discard stale results immediately, including
/// errors whose layer/property no longer exists. Pointer interaction and playback defer scans.
pub fn errors(&mut self, s: &Session, ctx: &egui::Context, comp: ItemId, interacting: bool) -> Errors {
self.update(s, ctx, comp, interacting, Instant::now())
}
fn update(&mut self, s: &Session, ctx: &egui::Context, comp: ItemId, interacting: bool, now: Instant) -> Errors {
if !s.prefs.scripting.error_banner || s.expr.is_none() {
self.clear();
return Arc::from([]);
}
let mut entry = self.entries.iter().position(|e| e.snapshot.comp == comp).and_then(|i| self.entries.remove(i));
if entry.as_ref().is_none_or(|e| !e.snapshot.matches(s, comp)) {
entry = Some(Entry {
snapshot: Snapshot::new(s, comp),
changed: now,
cancelled: Arc::new(AtomicBool::new(false)),
submitted: false,
errors: Arc::from([]),
});
}
let Some(mut entry) = entry else { return Arc::from([]) };
if interacting {
entry.changed = now;
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(worker) = &self.worker {
let done: Vec<_> = worker.shared.completed.lock().unwrap_or_else(PoisonError::into_inner).drain(..).collect();
for done in done {
let target = if done.comp == comp { Some(&mut entry) } else { self.entries.iter_mut().find(|e| e.snapshot.comp == done.comp) };
if let Some(target) = target
&& Arc::ptr_eq(&target.cancelled, &done.cancelled)
&& !done.cancelled.load(Ordering::Relaxed)
{
match done.result {
Ok(Some(errors)) => target.errors = errors.into(),
Ok(None) => {}
Err(e) => self.failure = Some(e),
}
}
}
}
if !entry.submitted && !interacting {
let quiet = now.saturating_duration_since(entry.changed);
if quiet < QUIET {
ctx.request_repaint_after(QUIET - quiet);
} else {
entry.submitted = true;
let request = Request {
snapshot: entry.snapshot.clone(),
cancelled: entry.cancelled.clone(),
#[cfg(not(target_arch = "wasm32"))]
repaint: ctx.clone(),
};
#[cfg(not(target_arch = "wasm32"))]
{
if self.worker.is_none() {
match Worker::new() {
Ok(worker) => self.worker = Some(worker),
Err(e) => self.failure = Some(format!("Could not start expression diagnostics: {e}")),
}
}
if let Some(worker) = &self.worker {
worker.submit(request);
}
}
// wasm32 cannot spawn Rust threads. Preserve diagnostics there, but eliminate
// the duplicate scan and defer it until scrubbing/dragging/playback stops.
#[cfg(target_arch = "wasm32")]
match request.run().result {
Ok(Some(errors)) => entry.errors = errors.into(),
Ok(None) => {}
Err(e) => self.failure = Some(e),
}
}
}
let result = entry.errors.clone();
self.entries.push_back(entry);
if self.entries.len() > MAX_VIEWERS {
self.entries.pop_front();
}
result
}
}
#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
struct Shared {
pending: Mutex<VecDeque<Request>>,
completed: Mutex<VecDeque<Completed>>,
wake: std::sync::Condvar,
stopped: AtomicBool,
}
#[cfg(not(target_arch = "wasm32"))]
struct Worker {
shared: Arc<Shared>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Worker {
fn new() -> std::io::Result<Self> {
let shared = Arc::new(Shared::default());
let work = shared.clone();
std::thread::Builder::new().name("ec-expression-diagnostics".into()).spawn(move || {
loop {
let request = {
let mut pending = work.pending.lock().unwrap_or_else(PoisonError::into_inner);
while pending.is_empty() && !work.stopped.load(Ordering::Relaxed) {
pending = work.wake.wait(pending).unwrap_or_else(PoisonError::into_inner);
}
if work.stopped.load(Ordering::Relaxed) {
return;
}
pending.pop_front()
};
let Some(request) = request else { continue };
if request.cancelled.load(Ordering::Relaxed) {
continue;
}
let result = request.run();
if !result.cancelled.load(Ordering::Relaxed) {
let mut completed = work.completed.lock().unwrap_or_else(PoisonError::into_inner);
completed.retain(|r| r.comp != result.comp && !r.cancelled.load(Ordering::Relaxed));
if completed.len() >= MAX_VIEWERS {
completed.pop_front();
}
completed.push_back(result);
}
request.repaint.request_repaint();
}
})?;
Ok(Self { shared })
}
fn submit(&self, request: Request) {
let mut pending = self.shared.pending.lock().unwrap_or_else(PoisonError::into_inner);
pending.retain(|r| r.snapshot.comp != request.snapshot.comp && !r.cancelled.load(Ordering::Relaxed));
if pending.len() >= MAX_VIEWERS {
pending.pop_front();
}
pending.push_back(request);
self.shared.wake.notify_one();
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for Worker {
fn drop(&mut self) {
// Hold the predicate lock when waking, so shutdown cannot race with entering wait.
let mut pending = self.shared.pending.lock().unwrap_or_else(PoisonError::into_inner);
self.shared.stopped.store(true, Ordering::Relaxed);
pending.clear();
self.shared.wake.notify_one();
// Do not join an in-flight expression on the UI thread. Entries cancel it on drop.
}
}
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
use super::*;
use effectcraft_engine::keyframe::Value;
use effectcraft_engine::project::{Layer, Property};
use serde_json::json;
use std::sync::atomic::AtomicUsize;
use std::sync::mpsc;
struct Host {
main: std::thread::ThreadId,
on_ui: AtomicUsize,
calls: AtomicUsize,
entered: mpsc::Sender<()>,
gate: (Mutex<bool>, std::sync::Condvar),
fail: bool,
}
impl ExprHost for Host {
fn eval(&self, ctx: &EvalCtx, _: &Layer, _: &Property, value: &Value) -> Result<Value, String> {
self.calls.fetch_add(1, Ordering::Relaxed);
if std::thread::current().id() == self.main {
self.on_ui.fetch_add(1, Ordering::Relaxed);
return Err("diagnostics evaluated on UI thread".into());
}
let _ = self.entered.send(());
let (lock, wake) = &self.gate;
let guard = lock.lock().unwrap();
let (_guard, timed) = wake.wait_timeout_while(guard, Duration::from_secs(5), |open| !*open).unwrap();
assert!(!timed.timed_out(), "test did not release the worker");
if self.fail { Err(format!("failure at {}", ctx.time.0)) } else { Ok(value.clone()) }
}
}
impl Host {
fn release(&self) {
*self.gate.0.lock().unwrap() = true;
self.gate.1.notify_all();
}
}
fn fixture(fail: bool, blocked: bool) -> (Session, Arc<Host>, mpsc::Receiver<()>) {
let (tx, rx) = mpsc::channel();
let host = Arc::new(Host {
main: std::thread::current().id(),
on_ui: AtomicUsize::new(0),
calls: AtomicUsize::new(0),
entered: tx,
gate: (Mutex::new(!blocked), std::sync::Condvar::new()),
fail,
});
let mut s = Session { expr: Some(host.clone()), ..Session::default() };
s.execute("comp.new", json!({"width":320,"height":180,"duration":5})).unwrap();
let hidden = s.execute("layer.newSolid", json!({"name":"Hidden expression"})).unwrap()["layer"].as_u64().unwrap();
s.execute("prop.setExpression", json!({"layer":hidden,"path":"transform/opacity","expression":"value"})).unwrap();
let visible = s.execute("layer.newSolid", json!({"name":"Solo plate"})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setSwitch", json!({"layers":[visible],"switch":"solo","value":true})).unwrap();
s.execute("layer.select", json!({"layers":[visible]})).unwrap();
(s, host, rx)
}
fn wait_done(d: &Diagnostics) {
let until = Instant::now() + Duration::from_secs(3);
loop {
if d.worker.as_ref().is_some_and(|w| !w.shared.completed.lock().unwrap().is_empty()) {
return;
}
assert!(Instant::now() < until, "diagnostics did not finish");
std::thread::sleep(Duration::from_millis(1));
}
}
fn start(d: &mut Diagnostics, s: &Session, ctx: &egui::Context, now: Instant) {
let cid = s.active_comp_id().unwrap();
d.update(s, ctx, cid, false, now);
d.update(s, ctx, cid, false, now + QUIET);
}
#[test]
fn successful_hidden_expressions_run_once_off_the_ui_thread() {
let (s, host, _) = fixture(false, false);
let (mut d, ctx, now) = (Diagnostics::default(), egui::Context::default(), Instant::now());
let cid = s.active_comp_id().unwrap();
start(&mut d, &s, &ctx, now);
wait_done(&d);
for _ in 0..5 {
assert!(d.update(&s, &ctx, cid, false, now + QUIET).is_empty());
}
assert_eq!(host.calls.load(Ordering::Relaxed), 1);
assert_eq!(host.on_ui.load(Ordering::Relaxed), 0);
}
#[test]
fn newest_request_replaces_queued_times_and_discards_stale_errors() {
let (mut s, host, entered) = fixture(true, true);
let (mut d, ctx, now) = (Diagnostics::default(), egui::Context::default(), Instant::now());
let cid = s.active_comp_id().unwrap();
start(&mut d, &s, &ctx, now);
entered.recv_timeout(Duration::from_secs(3)).unwrap();
for i in 1..20 {
s.set_time(Tick::from_seconds_f64(i as f64 / 30.));
start(&mut d, &s, &ctx, now + Duration::from_secs(i));
assert!(d.entries.back().unwrap().errors.is_empty());
}
assert_eq!(d.worker.as_ref().unwrap().shared.pending.lock().unwrap().len(), 1);
host.release();
wait_done(&d);
let errors = d.update(&s, &ctx, cid, false, now + Duration::from_secs(30));
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].message, format!("failure at {}", s.time().0));
assert_eq!(host.calls.load(Ordering::Relaxed), 2);
assert_eq!(host.on_ui.load(Ordering::Relaxed), 0);
}
#[test]
fn warning_preference_and_interaction_prevent_scanning_and_clear_stale_results() {
let (mut s, host, _) = fixture(true, false);
let (mut d, ctx, now) = (Diagnostics::default(), egui::Context::default(), Instant::now());
let cid = s.active_comp_id().unwrap();
for i in 0..10 {
d.update(&s, &ctx, cid, true, now + Duration::from_secs(i));
}
assert!(d.worker.is_none());
s.prefs.scripting.error_banner = false;
start(&mut d, &s, &ctx, now + Duration::from_secs(10));
assert!(d.worker.is_none());
assert_eq!(host.calls.load(Ordering::Relaxed), 0);
s.prefs.scripting.error_banner = true;
start(&mut d, &s, &ctx, now + Duration::from_secs(11));
wait_done(&d);
assert_eq!(d.update(&s, &ctx, cid, false, now + Duration::from_secs(12)).len(), 1);
s.prefs.scripting.error_banner = false;
assert!(d.update(&s, &ctx, cid, false, now + Duration::from_secs(13)).is_empty());
assert!(d.entries.is_empty());
}
#[test]
fn replacement_project_with_reused_ids_does_not_reuse_errors() {
let (s, _, _) = fixture(true, false);
let (mut d, ctx, now) = (Diagnostics::default(), egui::Context::default(), Instant::now());
let cid = s.active_comp_id().unwrap();
start(&mut d, &s, &ctx, now);
wait_done(&d);
assert_eq!(d.update(&s, &ctx, cid, false, now + QUIET).len(), 1);
let (replacement, _, _) = fixture(false, false);
assert_eq!(s.revision, replacement.revision);
assert!(d.update(&replacement, &ctx, cid, false, now + QUIET).is_empty());
}
#[test]
fn scans_keep_disabled_syntax_errors_and_non_solo_runtime_errors() {
let (mut s, _, _) = fixture(true, false);
let cid = s.active_comp_id().unwrap();
let selected = s.state.selected_layers[0];
s.expr_check = Some(|_| Err("invalid syntax".into()));
s.execute("prop.setExpression", json!({"layer":selected.0,"path":"transform/rotation","expression":"bad("})).unwrap();
let (mut d, ctx, now) = (Diagnostics::default(), egui::Context::default(), Instant::now());
start(&mut d, &s, &ctx, now);
wait_done(&d);
let errors = d.update(&s, &ctx, cid, false, now + QUIET);
assert_eq!(errors.len(), 2);
assert!(errors.iter().any(|e| e.disabled && e.message == "invalid syntax"));
assert!(errors.iter().any(|e| !e.disabled && e.layer_name == "Hidden expression"));
}
#[test]
fn viewer_edits_do_not_wait_for_hidden_diagnostics_with_or_without_warnings() {
use crate::{EffectcraftApp, bench::Driver};
let (s, host, entered) = fixture(false, true);
let mut d = Driver::new(EffectcraftApp::new(s), egui::vec2(1680., 1020.));
for _ in 0..3 {
d.step();
}
let now = Instant::now() + Duration::from_secs(1);
start(&mut d.app.expression_diagnostics, &d.app.session, &d.ctx, now);
entered.recv_timeout(Duration::from_secs(3)).unwrap();
let layer = d.app.session.state.selected_layers[0];
d.app.session.state.snapping = false;
let handle = format!("viewer.handle.{}.0", layer.0);
let before = d.app.auto.find(&handle).unwrap().rect;
let comp_rect = d.app.auto.find("viewer.comp").unwrap().rect;
let from = egui::pos2(comp_rect[0] + comp_rect[2] * 0.4, comp_rect[1] + comp_rect[3] * 0.4);
let to = from + egui::vec2(40., 20.);
d.step_with(vec![
egui::Event::PointerMoved(from),
egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() },
]);
d.step_with(vec![egui::Event::PointerMoved(to)]);
d.step_with(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }]);
d.step();
let after = d.app.auto.find(&handle).unwrap().rect;
assert!(after[0] > before[0] + 30., "selection bounds did not follow the drag: {before:?} -> {after:?}");
for warnings in [true, false] {
d.app.session.prefs.scripting.error_banner = warnings;
for i in 0..4 {
d.app.session.set_time(Tick::from_seconds_f64(i as f64 / 30.));
d.app.session.execute("layer.setTransform", json!({"layer":layer.0,"prop":"position","value":[170.+i as f64,90.,0.]})).unwrap();
d.app.session.execute("layer.setSwitch", json!({"layers":[layer.0],"switch":"video","value":i%2==0})).unwrap();
d.step();
}
}
// The diagnostic expression is still blocked on the worker, but every UI frame above
// finished. This assertion also catches reintroducing a second, synchronous banner.
assert!(!*host.gate.0.lock().unwrap());
assert_eq!(host.on_ui.load(Ordering::Relaxed), 0);
host.release();
}
}
+429 -20
View File
@@ -29,7 +29,7 @@ use std::sync::{Arc, Mutex};
use effectcraft_engine::project::{Comp, ItemId, ItemKind, LayerSource, Node, Project, PropGroup};
use effectcraft_engine::render::disk_cache::{self, DiskCache};
use effectcraft_engine::render::{ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
use effectcraft_engine::render::{CancellableFootage, ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
use effectcraft_engine::time::Tick;
use effectcraft_gpu::{DisplayFrame, Gpu};
use rayon::prelude::*;
@@ -109,6 +109,38 @@ impl std::hash::Hash for FrameKey {
}
}
/// Where a playing preview is and what it plays next (see [`Frames::set_playhead`]): the RAM
/// preview renders the frames it reaches first before later ones, and keeps them over frames it
/// reaches later or not at all (#595).
#[derive(Clone, Copy, Debug)]
pub struct Playhead {
/// The frame series that plays ([`FrameKey::same_series`]; its `frame` is ignored).
pub series: FrameKey,
/// The frame on screen.
pub cur: i64,
/// The preview's range, skip step and looping (as in its `PreviewPlan`).
pub start: i64,
pub end: i64,
pub step: i64,
pub looping: bool,
}
impl Playhead {
/// How many frames the preview shows before it reaches `k` (0: on screen); `None` for
/// frames it doesn't reach (other series, outside the range, behind it without looping).
pub fn ahead(&self, k: &FrameKey) -> Option<i64> {
if !k.same_series(&self.series) || k.frame < self.start || k.frame > self.end {
return None;
}
let step = self.step.max(1);
if k.frame >= self.cur {
return Some((k.frame - self.cur) / step);
}
// Looping: through the end of the range and around from its start.
self.looping.then(|| (self.end.saturating_sub(self.cur) / step).saturating_add(1).saturating_add((k.frame - self.start) / step))
}
}
struct Cache {
map: HashMap<FrameKey, FrameImage>,
order: VecDeque<FrameKey>,
@@ -118,6 +150,8 @@ struct Cache {
budget: usize,
/// Bytes of GPU frames to keep at most ([`GPU_BUDGET`]).
gpu_budget: usize,
/// The playing preview, if any: evictions spare the frames it shows next.
playhead: Option<Playhead>,
}
impl Cache {
@@ -132,12 +166,26 @@ impl Cache {
if gpu {
self.gpu_bytes += sz;
}
while self.bytes > self.budget {
let Some(old) = self.order.pop_front() else { break };
self.remove(&old);
}
self.evict_to_budget();
self.evict_gpu();
}
/// The frame to evict next: the least recently shown, but while a preview plays, the least
/// recently shown of the frames it doesn't reach, then the one it reaches last. Plain LRU
/// evicted the frames just ahead of the playhead first (rendered a while ago, not shown yet)
/// to keep the ones just shown, so a preview longer than the cache played into a gap that
/// prefetch kept refilling while it evicted the next frames (#595).
fn victim(&self) -> Option<usize> {
let Some(p) = &self.playhead else { return (!self.order.is_empty()).then_some(0) };
let mut farthest: Option<(i64, usize)> = None;
for (i, k) in self.order.iter().enumerate() {
match p.ahead(k) {
None => return Some(i),
Some(d) if farthest.is_none_or(|(f, _)| d > f) => farthest = Some((d, i)),
Some(_) => {}
}
}
farthest.map(|(_, i)| i)
}
/// Video memory: drop the oldest GPU frames past their own budget.
fn evict_gpu(&mut self) {
while self.gpu_bytes > self.gpu_budget {
@@ -181,7 +229,7 @@ impl Cache {
}
fn evict_to_budget(&mut self) {
while self.bytes > self.budget {
let Some(old) = self.order.pop_front() else { break };
let Some(old) = self.victim().and_then(|i| self.order.remove(i)) else { break };
self.remove(&old);
}
}
@@ -213,6 +261,13 @@ type Identity = (u64, Option<Arc<Project>>);
/// Content keys of (project revision, comp), computed once per revision.
type ContentKeys = Arc<Mutex<HashMap<(u64, u64), u128>>>;
#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
struct ContentKeyJobs {
running: bool,
pending: VecDeque<(Arc<Project>, u64, u64)>,
}
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;
@@ -369,6 +424,8 @@ pub struct Frames {
/// 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,
#[cfg(not(target_arch = "wasm32"))]
content_key_jobs: Arc<Mutex<ContentKeyJobs>>,
gpu_retired: Arc<AtomicBool>,
/// [`comp_content`] identities by (revision, comp), with the project that keeps an identity
/// found by [`Frames::identity`] in another project.
@@ -388,7 +445,7 @@ impl Default for Frames {
#[cfg(not(target_arch = "wasm32"))]
let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(2, 16);
Frames {
cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, gpu_bytes: 0, budget: 3 << 30, gpu_budget: GPU_BUDGET })),
cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, gpu_bytes: 0, budget: 3 << 30, gpu_budget: GPU_BUDGET, playhead: None })),
inflight: Arc::new(Mutex::new(HashSet::new())),
queue: Arc::new(Mutex::new(Queue::default())),
#[cfg(not(target_arch = "wasm32"))]
@@ -403,6 +460,8 @@ impl Default for Frames {
ctx: None,
last_ms: Arc::new(Mutex::new(0.0)),
content_keys: Arc::default(),
#[cfg(not(target_arch = "wasm32"))]
content_key_jobs: Arc::default(),
gpu_retired: Arc::default(),
identities: Mutex::default(),
bases: Mutex::default(),
@@ -460,11 +519,27 @@ pub fn fit_texture(img: egui::ColorImage, max_side: usize) -> egui::ColorImage {
/// [`fit_texture`] averaging down by at least `min_k` (see [`fit_factor`]).
pub fn fit_texture_by(img: egui::ColorImage, max_side: usize, min_k: usize) -> egui::ColorImage {
let [w, h] = img.size;
let k = fit_factor(img.size, max_side, min_k);
if k == 1 {
return img;
}
average_down(&img, k)
}
/// A shared frame as texture data (see [`fit_texture_by`]): the frame itself when it needs no
/// averaging, without copying its pixels. The viewer puts every frame a preview shows on screen;
/// copying a 4K frame first held the UI thread for about a millisecond each time (#595).
pub fn fit_shared_texture_by(img: &Arc<egui::ColorImage>, max_side: usize, min_k: usize) -> egui::ImageData {
let k = fit_factor(img.size, max_side, min_k);
if k == 1 {
return egui::ImageData::Color(img.clone());
}
average_down(img, k).into()
}
/// `img` averaged down by `k` (rounded up at the edges).
fn average_down(img: &egui::ColorImage, k: usize) -> egui::ColorImage {
let [w, h] = img.size;
let (fw, fh) = (w.div_ceil(k), h.div_ceil(k));
let px: Vec<egui::Color32> = (0..fw * fh)
.into_par_iter()
@@ -662,7 +737,8 @@ impl Frames {
}
/// Frames of the series of `base` in the disk cache but not in RAM — the blue cache bar.
/// `opts` are the viewer's render options (part of the disk key).
/// `opts` are the viewer's render options (part of the disk key). Native queries return
/// no blue frames until the content key is ready; hashing never blocks timeline painting.
pub fn disk_frames(&self, src: &RenderSource, base: &FrameKey, frames: i64, opts: &RenderOpts) -> Vec<i64> {
let remote = self.remote.as_ref().filter(|r| r.disk());
let contains = |k: u128| match (&src.disk, remote) {
@@ -673,14 +749,64 @@ impl Frames {
if src.disk.is_none() && remote.is_none() {
return vec![];
}
#[cfg(not(target_arch = "wasm32"))]
let content = {
let known = self.content_keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(base.revision, base.comp)).copied();
let Some(content) = known else {
self.request_content_key(src.project.clone(), base.revision, base.comp);
return vec![];
};
content
};
#[cfg(target_arch = "wasm32")]
let content = content_key(&self.content_keys, &src.project, base.revision, base.comp);
let ram: HashSet<i64> = self.cached_frames(base).into_iter().collect();
let oh = opts_hash(opts);
(0..frames.clamp(0, 100_000))
.filter(|f| !ram.contains(f))
.filter(|f| contains(frame_disk_key(&self.content_keys, &src.project, &FrameKey { frame: *f, ..*base }, oh)))
.filter(|f| contains(disk_cache::frame_key(content, *f, base.scale, base.view ^ oh)))
.collect()
}
#[cfg(not(target_arch = "wasm32"))]
fn request_content_key(&self, project: Arc<Project>, revision: u64, comp: u64) {
let mut jobs = self.content_key_jobs.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
// Coalesce rapid edits. One worker hashes at most one revision at a time; retained
// snapshots are bounded even with multiple timelines open.
jobs.pending.retain(|(_, _, c)| *c != comp);
if jobs.pending.len() >= 8 {
jobs.pending.pop_front();
}
jobs.pending.push_back((project, revision, comp));
if jobs.running {
return;
}
jobs.running = true;
drop(jobs);
let (jobs, keys, ctx) = (self.content_key_jobs.clone(), self.content_keys.clone(), self.ctx.clone());
let work = move || loop {
let next = {
let mut jobs = jobs.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let next = jobs.pending.pop_back();
if next.is_none() {
jobs.running = false;
}
next
};
let Some((project, revision, comp)) = next else { return };
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| content_key(&keys, &project, revision, comp))).is_err() {
log::error!("could not compute a preview disk-cache key; the cache indicator will retry");
}
if let Some(ctx) = &ctx {
ctx.request_repaint();
}
};
match &self.pool {
Some(pool) => pool.spawn(work),
None => rayon::spawn(work),
}
}
/// Change the RAM preview cache budget (Settings ▸ Memory & CPU), evicting the oldest
/// frames when it shrinks.
pub fn set_budget(&self, bytes: usize) {
@@ -712,6 +838,26 @@ impl Frames {
}
}
/// The playing preview's position (`None` when no preview plays): prefetch renders the
/// frames it reaches first before the others, evictions spare the frames it shows next, and
/// queued prefetch frames of its series it no longer reaches are dropped (#595).
pub fn set_playhead(&self, playhead: Option<Playhead>) {
if let Ok(mut c) = self.cache.lock() {
c.playhead = playhead;
}
let Ok(mut q) = self.queue.lock() else { return };
q.playhead = playhead;
let Some(p) = playhead else { return };
let Ok(mut inf) = self.inflight.lock() else { return };
q.jobs.retain(|j| {
let gone = !j.urgent && j.key.same_series(&p.series) && p.ahead(&j.key).is_none();
if gone {
inf.remove(&j.key);
}
!gone
});
}
/// Queue a prefetch frame (no-op if cached or already queued/rendering).
pub fn request(&self, src: &RenderSource, key: FrameKey, comp: ItemId, t: Tick, opts: RenderOpts) {
self.request_with(src, key, comp, t, opts, false);
@@ -756,13 +902,22 @@ impl Frames {
for j in q.jobs.iter_mut() {
j.urgent = j.key == key;
}
// The comp's viewer frames of other times that are rendering are called off too: a
// movie seeking for each of them held the decoder the frame under the pointer
// waited for, so it came seconds after the pointer stopped (#329). Another revision
// of the same frame (a live edit) finishes, as the viewer shows it meanwhile.
for (k, cancel) in &q.urgent_cancels {
if k.comp == key.comp && k.frame != key.frame {
cancel.store(true, Ordering::Relaxed);
}
}
}
if !inf.insert(key) {
return;
}
q.seq += 1;
let seq = q.seq;
q.jobs.push(Job { key, src: src.clone(), comp, t, opts, urgent, seq });
q.jobs.push(Job { key, src: src.clone(), comp, t, opts, urgent, seq, cancel: Arc::default() });
drop(inf);
drop(q);
#[cfg(not(target_arch = "wasm32"))]
@@ -835,7 +990,7 @@ impl Frames {
}
let job = {
let Ok(mut q) = self.queue.lock() else { break };
let Some(i) = Queue::best(&q.jobs) else { break };
let Some(i) = q.best() else { break };
let job = q.jobs.swap_remove(i);
q.running.insert(job.key);
if job.urgent {
@@ -963,11 +1118,12 @@ impl Worker {
let Worker { queue, content_keys, .. } = self;
let job = {
let Ok(mut q) = queue.lock() else { return false };
let Some(i) = Queue::best(&q.jobs) else { return false };
let Some(i) = q.best() else { return false };
let job = q.jobs.swap_remove(i);
q.running.insert(job.key);
if job.urgent {
q.urgent_running += 1;
q.urgent_cancels.push((job.key, job.cancel.clone()));
}
job
};
@@ -977,10 +1133,11 @@ impl Worker {
let disk_hit = from_disk.is_some();
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 => match self.render_guarded(&job) {
None => match self.render_guarded(&job).filter(|_| !job.cancel.load(Ordering::Relaxed)) {
Some(ci) => ci,
// Called off (frames it read may be missing) or failed: not cached, and not
// "in progress" forever: the viewer asks for it again.
None => {
// Not "in progress" forever: the viewer asks for it again.
self.release(job.key, job.urgent);
return true;
}
@@ -1025,6 +1182,9 @@ impl Worker {
q.running.remove(&key);
if urgent {
q.urgent_running = q.urgent_running.saturating_sub(1);
if let Some(i) = q.urgent_cancels.iter().position(|(k, _)| *k == key) {
q.urgent_cancels.swap_remove(i);
}
}
}
if let Some(ctx) = &self.ctx {
@@ -1061,7 +1221,8 @@ impl Worker {
return None;
}
let g = job.src.gpu.as_ref()?;
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
let footage = job.footage();
let mut r = Renderer::new(&job.src.project, &footage, job.opts);
r.expr = job.src.expr.as_deref();
r.cache = Some(&job.src.layer_cache);
r.accel = Some(g as &dyn effectcraft_engine::render::Accelerator);
@@ -1077,7 +1238,8 @@ impl Worker {
/// Render a frame; `gpu: false` keeps it off the GPU compositor.
fn render_job(&self, job: &Job, gpu: bool) -> FrameImage {
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
let footage = job.footage();
let mut r = Renderer::new(&job.src.project, &footage, job.opts);
r.expr = job.src.expr.as_deref();
let gpu_allowed = gpu && !self.gpu_retired.load(Ordering::Acquire);
// A failed GPU attempt may have populated intermediate entries before its scope
@@ -1149,6 +1311,15 @@ struct Job {
opts: RenderOpts,
urgent: bool,
seq: u64,
/// Set when the viewer no longer waits for this frame (see [`Frames::request_urgent`]).
cancel: Arc<AtomicBool>,
}
impl Job {
/// The footage this job's render reads, called off with the job.
fn footage(&self) -> CancellableFootage<'_> {
CancellableFootage { inner: self.src.footage.as_ref(), cancel: self.cancel.clone() }
}
}
#[derive(Default)]
@@ -1156,13 +1327,28 @@ struct Queue {
jobs: Vec<Job>,
running: HashSet<FrameKey>,
urgent_running: usize,
/// The running viewer (urgent) frames and how to call them off.
urgent_cancels: Vec<(FrameKey, Arc<AtomicBool>)>,
seq: u64,
/// The playing preview, if any: its prefetch renders nearest first.
playhead: Option<Playhead>,
}
impl Queue {
/// The job that matters most: urgent first (newest), then prefetch in request order.
fn best(jobs: &[Job]) -> Option<usize> {
jobs.iter().enumerate().max_by_key(|(_, j)| (j.urgent, if j.urgent { j.seq as i64 } else { -(j.seq as i64) })).map(|(i, _)| i)
/// The job that matters most: urgent first (newest), then, while a preview plays, the
/// prefetch frame it reaches first, then prefetch in request order. In request order alone,
/// frames asked for again after an eviction (the ones right ahead of the playhead) waited
/// behind every frame further ahead (#595).
fn best(&self) -> Option<usize> {
let p = self.playhead.as_ref();
self.jobs
.iter()
.enumerate()
.max_by_key(|(_, j)| {
let near = if j.urgent { None } else { p.and_then(|p| p.ahead(&j.key)) };
(j.urgent, near.is_some(), near.map_or(0, |d| -d), if j.urgent { j.seq as i64 } else { -(j.seq as i64) })
})
.map(|(i, _)| i)
}
}
@@ -1170,6 +1356,67 @@ impl Queue {
mod tests {
use super::*;
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn disk_indicator_does_not_hash_on_ui_thread_and_coalesces_edits() {
use std::sync::mpsc;
use std::time::{Duration, Instant};
struct Disk(u128);
impl RemoteFrames for Disk {
fn slots(&self) -> usize {
1
}
fn disk(&self) -> bool {
true
}
fn disk_contains(&self, key: u128) -> bool {
self.0 == key
}
fn start(&self, _: RemoteJob, done: RemoteDone) {
done(Err("test has no renderer".into()));
}
}
let mut s = effectcraft_engine::Session::default();
s.execute("comp.new", serde_json::json!({"width":32,"height":18,"duration":1})).unwrap();
let cid = s.active_comp_id().unwrap();
let opts = RenderOpts::default();
let stored = disk_cache::frame_key(disk_cache::comp_content_key(&s.project, cid), 2, 1000, opts_hash(&opts));
let mut frames = Frames { pool: Some(rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap()), ..Default::default() };
frames.set_remote(Some(Arc::new(Disk(stored))));
let (entered, started) = mpsc::channel();
let (release, wait) = mpsc::channel();
frames.pool.as_ref().unwrap().spawn(move || {
entered.send(()).unwrap();
wait.recv_timeout(Duration::from_secs(5)).unwrap();
});
started.recv_timeout(Duration::from_secs(3)).unwrap();
let src = RenderSource {
project: s.project.clone(),
footage: s.footage.clone(),
expr: None,
layer_cache: Arc::default(),
gpu: None,
gpu_display: false,
disk: None,
};
let mut base = key(1, 0, 0);
base.comp = cid.0;
for revision in 1..50 {
base.revision = revision;
assert!(frames.disk_frames(&src, &base, 30, &opts).is_empty());
}
assert!(frames.content_keys.lock().unwrap().is_empty(), "painting computed a content hash while the worker was blocked");
assert_eq!(frames.content_key_jobs.lock().unwrap().pending.len(), 1);
release.send(()).unwrap();
let until = Instant::now() + Duration::from_secs(3);
while !frames.content_keys.lock().unwrap().contains_key(&(base.revision, base.comp)) {
assert!(Instant::now() < until);
std::thread::sleep(Duration::from_millis(1));
}
assert_eq!(frames.disk_frames(&src, &base, 30, &opts), vec![2], "the blue indicator must return once its key is ready");
assert_eq!(frames.content_keys.lock().unwrap().len(), 1, "superseded revisions were hashed");
}
/// Frames larger than the texture limit are averaged down by a whole factor (#201: an
/// 11000×2200 comp at Full resolution against an 8192 limit).
#[test]
@@ -1341,6 +1588,94 @@ mod tests {
assert_eq!(footage.deepest.load(Ordering::SeqCst), 1, "renders nested on a waiting thread");
}
/// #329: scrubbing a long movie, the viewer frame of every step the pointer passed started
/// rendering and seeked the movie's decoder in turn; the frame under the pointer waited for
/// all of them. A newer viewer frame of another time calls off the one rendering, which is
/// not cached (its footage may be missing).
#[test]
fn a_newer_viewer_frame_calls_off_the_one_rendering() {
use effectcraft_engine::Session;
use effectcraft_engine::project::{Footage, FootageKind};
use effectcraft_engine::render::Image;
use effectcraft_engine::time::FrameRate;
use serde_json::json;
use std::cell::RefCell;
thread_local! {
static CANCEL: RefCell<Option<Arc<AtomicBool>>> = const { RefCell::new(None) };
}
/// A movie whose first frames take a long seek, which a called-off read gives up.
#[derive(Default)]
struct Seeking {
seeking: AtomicBool,
called_off: AtomicBool,
}
impl FootageSource for Seeking {
fn cancellable(&self, cancel: &Arc<AtomicBool>, f: &mut dyn FnMut()) {
let prev = CANCEL.replace(Some(cancel.clone()));
f();
CANCEL.set(prev);
}
fn frame(&self, _: ItemId, _: &Footage, t: Tick) -> Option<Arc<Image>> {
if t < Tick::from_seconds_f64(0.25) {
self.seeking.store(true, Ordering::SeqCst);
for _ in 0..1000 {
if CANCEL.with_borrow(|c| c.as_ref().is_some_and(|c| c.load(Ordering::SeqCst))) {
self.called_off.store(true, Ordering::SeqCst);
return None;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
Some(Arc::new(Image::new(4, 4)))
}
}
let mut s = Session::default();
let cid = ItemId(s.execute("comp.new", json!({"name": "A", "width": 8, "height": 8, "duration": 10})).unwrap()["comp"].as_u64().unwrap());
let clip = Footage {
kind: FootageKind::Video,
width: 4,
height: 4,
has_video: true,
frame_rate: FrameRate::FPS_30,
duration: Tick::from_seconds_f64(10.0),
..Default::default()
};
let item = Arc::make_mut(&mut s.project).add_item("clip.mov", Default::default(), None, ItemKind::Footage(clip));
s.execute("layer.addItem", json!({"item": item.0})).unwrap();
let footage = Arc::new(Seeking::default());
let src = RenderSource {
project: s.project.clone(),
footage: footage.clone(),
expr: None,
layer_cache: Arc::default(),
gpu: None,
gpu_display: false,
disk: None,
};
let f = Frames::default();
let content = f.content_of(&s.project, s.revision, cid);
let key = |frame| FrameKey { revision: s.revision, content, comp: cid.0, frame, scale: 1000, view: 0, opts: 0 };
f.request_urgent(&src, key(0), cid, Tick::ZERO, RenderOpts::default());
for _ in 0..1000 {
if footage.seeking.load(Ordering::SeqCst) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert!(footage.seeking.load(Ordering::SeqCst), "the first frame's render reached the footage");
f.request_urgent(&src, key(150), cid, FrameRate::FPS_30.tick_of(150), RenderOpts::default());
for _ in 0..1000 {
if f.inflight() == 0 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(footage.called_off.load(Ordering::SeqCst), "the superseded frame's seek ran on");
assert!(f.is_cached(&key(150)), "the newest frame rendered");
assert!(!f.is_cached(&key(0)), "a called-off frame is not cached");
assert_eq!(f.inflight(), 0, "released");
}
/// #284: scrubbing asks for a viewer frame at every step; a newer one drops the comp's viewer
/// frames still waiting (they would all render first), but not prefetch frames or another
/// comp's viewer frame.
@@ -1406,6 +1741,80 @@ mod tests {
assert!(f.is_cached(&key(1, 2, 0)) && f.is_cached(&key(1, 3, 0)));
}
fn playhead(cur: i64, looping: bool) -> Playhead {
Playhead { series: key(1, 0, 0), cur, start: 0, end: 99, step: 1, looping }
}
/// #595: a playing preview's cache is full. The frames just ahead of the playhead were
/// rendered before the ones just shown, so plain LRU evicted them first and the preview
/// played into a gap. Frames the preview no longer reaches go first, then the ones it
/// reaches last.
#[test]
fn a_full_cache_keeps_the_frames_just_ahead_of_the_playhead() {
let f = Frames::default();
f.set_budget(4 * 16);
// Prefetch rendered 11..=13, then 10 was shown (the most recently used).
for i in [11, 12, 13, 10] {
insert(&f, key(1, i, 0));
}
let cached = |f: &Frames| f.cached_frames(&key(1, 0, 0));
f.set_playhead(Some(playhead(10, false)));
// The next frame rendered is the one the preview reaches last: the frames just ahead stay.
insert(&f, key(1, 14, 0));
assert_eq!(cached(&f), [10, 11, 12, 13]);
// Without looping, a frame behind the playhead goes before any frame ahead of it.
f.set_playhead(Some(playhead(12, false)));
insert(&f, key(1, 14, 0));
assert_eq!(cached(&f), [10, 12, 13, 14]);
// Looping, the frame just behind is the one reached last.
f.set_playhead(Some(playhead(13, true)));
insert(&f, key(1, 0, 0));
assert_eq!(cached(&f), [0, 10, 13, 14]);
// Stopped: least recently shown first again.
f.set_playhead(None);
insert(&f, key(1, 50, 0));
assert!(!f.is_cached(&key(1, 13, 0)) && f.is_cached(&key(1, 50, 0)));
}
/// #595: prefetch renders the frames the preview reaches first, whatever order they were
/// asked for in (a frame evicted and asked for again waited behind every frame further
/// ahead); queued frames the preview no longer reaches are dropped and not left in flight.
#[test]
fn prefetch_renders_the_frames_the_playhead_reaches_first() {
struct Idle;
impl RemoteFrames for Idle {
fn slots(&self) -> usize {
0
}
fn start(&self, _: RemoteJob, _: RemoteDone) {}
}
let mut f = Frames::default();
f.set_remote(Some(Arc::new(Idle)));
let src = RenderSource {
project: Arc::default(),
footage: Arc::new(effectcraft_engine::render::NoFootage),
expr: None,
layer_cache: Arc::default(),
gpu: None,
gpu_display: false,
disk: None,
};
for frame in [40, 30, 20, 5, 12, 11] {
f.request(&src, key(1, frame, 0), ItemId(1), Tick::ZERO, RenderOpts::default());
}
f.request(&src, FrameKey { comp: 2, ..key(1, 1, 0) }, ItemId(2), Tick::ZERO, RenderOpts::default());
f.set_playhead(Some(playhead(10, false)));
let mut order = vec![];
loop {
let mut q = f.queue.lock().unwrap();
let Some(i) = q.best() else { break };
let j = q.jobs.swap_remove(i);
order.push((j.key.comp, j.key.frame));
}
assert_eq!(order, [(1, 11), (1, 12), (1, 20), (1, 30), (1, 40), (2, 1)]);
assert_eq!(f.inflight(), 6, "frame 5, behind the playhead, is no longer in flight");
}
#[test]
fn frames_are_keyed_by_content_and_series_are_kept_apart() {
let f = Frames::default();
+94 -17
View File
@@ -12,7 +12,7 @@ use crate::widgets;
use crate::{Dialog, EffectcraftApp};
use effectcraft_color::BlendMode;
use effectcraft_engine::commands::shape_tool::{PaintKind, ToolPaint};
use effectcraft_engine::project::{LayerId, LayerSource};
use effectcraft_engine::project::{LayerId, LayerSource, PropGroup};
use effectcraft_engine::viewer as vw;
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
@@ -101,7 +101,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
None
};
let close_behavior = if held && resp.clicked() { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClickOutside };
egui::Popup::menu(&resp).open_memory(command).close_behavior(close_behavior).show(|ui| {
egui::Popup::menu(&resp).style(crate::widgets::menu_style).open_memory(command).close_behavior(close_behavior).show(|ui| {
for tool in slot.iter() {
let row = ui.selectable_label(app.ui.tool == *tool, tool.label());
app.auto.add(&format!("tools.select.{tool:?}"), row.rect, tool.label());
@@ -133,13 +133,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.session.state.selected_layers.iter().filter(|id| c.layer(**id).is_some_and(|l| matches!(l.source, LayerSource::Shape))).map(|id| id.0).collect()
})
.unwrap_or_default();
let layer_paint = shape_layers
.first()
.and_then(|id| app.session.active_comp()?.layer(LayerId(*id)))
.map(|l| effectcraft_engine::commands::shape_stroke::first_paint(l, l.layer_time(app.session.time())));
if let Some((fill, stroke, width)) = layer_paint {
let layer_paint = shape_layers.first().and_then(|id| app.session.active_comp()?.layer(LayerId(*id))).map(|l| {
let lt = l.layer_time(app.session.time());
(effectcraft_engine::commands::shape_stroke::first_paint(l, lt), effectcraft_engine::commands::shape_stroke::first_paint_kinds(l, lt))
});
if let Some(((fill, stroke, width), (fill_kind, stroke_kind))) = layer_paint {
let rgb = |c: [f64; 4]| [c[0] as f32, c[1] as f32, c[2] as f32];
let tool = &mut app.session.state.shape_tool;
tool.fill.kind = fill_kind;
tool.stroke.kind = stroke_kind;
if let Some(c) = fill {
tool.fill.color = rgb(c);
}
@@ -214,9 +216,35 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
};
let tip = tr_args("Appearance Mode: {}", &[&mode]);
let r = Rect::from_min_max(pos2(rx - 26.0, cy - 13.0), pos2(rx, cy + 13.0));
if widgets::icon_button(ui, r, icon, false, &t, egui::Id::new("hdr-appearance")).on_hover_text(&tip).clicked() {
let response = widgets::icon_button(ui, r, icon, false, &t, egui::Id::new("hdr-appearance")).on_hover_text(&tip);
if response.clicked() {
app.cycle_appearance(ui.ctx());
}
response.context_menu(|ui| {
let settings = ui.button(tr("Appearance Settings…"));
app.auto.add("header.appearanceSettings", settings.rect, "Appearance Settings…");
if settings.clicked() {
crate::panels::settings::open(app, "appearance");
ui.close();
}
let favorites = app.session.prefs.appearance.favorite_themes.clone();
for options in [effectcraft_engine::prefs::LIGHT_THEMES, effectcraft_engine::prefs::DARK_THEMES] {
let group: Vec<_> = options.iter().filter(|(_, id)| favorites.iter().any(|saved| saved == id)).collect();
if !group.is_empty() {
ui.separator();
}
for (label, id) in group {
let r = ui.selectable_label(app.ui.theme.name() == *id, tr(label));
app.auto.add(&format!("header.favoriteTheme.{id}"), r.rect, label);
if r.clicked() {
if let Some(kind) = crate::theme::ThemeKind::from_name(id) {
app.set_theme(ui.ctx(), kind);
}
ui.close();
}
}
}
});
app.auto.add("header.appearance", r, &tip);
rx = r.min.x - 4.0;
rx -= 10.0;
@@ -227,7 +255,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mresp = ui.interact(more, egui::Id::new("ws-more"), Sense::click());
p.text(more.center(), Align2::CENTER_CENTER, "»", Tokens::ui(15.0), if mresp.hovered() { t.text } else { t.text_dim });
app.auto.add("header.workspaces", more, "Workspaces");
mresp.context_menu(|ui| ws_menu(app, ui));
crate::widgets::context_menu(&mresp, |ui| ws_menu(app, ui));
if mresp.clicked() {
widgets::open_popup(ui, egui::Id::new("ws-pop"));
}
@@ -301,6 +329,24 @@ fn tool_options(app: &mut EffectcraftApp, v: serde_json::Value) {
}
}
/// The Colors property of the first Gradient Fill (`gfill`) or Gradient Stroke (`gstroke`) on the
/// shape `layers`, in contents order through nested groups: (layer, property uid). The toolbar's
/// gradient swatch edits it in the Gradient Editor.
fn gradient_colors(app: &EffectcraftApp, layers: &[u64], paint: &str) -> Option<(u64, u64)> {
fn find(g: &PropGroup, paint: &str, depth: usize) -> Option<u64> {
if depth >= 16 {
return None;
}
g.groups().filter(|c| c.enabled).find_map(|c| match c.match_id.as_str() {
m if m == paint => c.get("colors").map(|p| p.uid),
"group" | "contents" => find(c, paint, depth + 1),
_ => None,
})
}
let comp = app.session.active_comp()?;
layers.iter().find_map(|&l| comp.layer(LayerId(l)).and_then(|layer| layer.props.sub("contents")).and_then(|c| find(c, paint, 0)).map(|u| (l, u)))
}
/// The colour picker of the Fill or Stroke swatch.
fn picker_id(key: &str) -> egui::Id {
egui::Id::new(("tool-pick", key))
@@ -353,8 +399,9 @@ fn fill_stroke_options(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Pa
if wresp.clicked() {
widgets::open_popup(ui, opts);
}
// The swatch picks a Solid Color's colour and opens the options for the other kinds;
// Alt-click steps through the kinds (as in After Effects).
// The swatch picks a Solid Color's colour, edits a Linear or Radial Gradient's colours in
// the Gradient Editor (the selected shape layer's Gradient Fill / Gradient Stroke), and
// opens the options otherwise; Alt-click steps through the kinds (as in After Effects).
let sr = Rect::from_min_size(pos2(wr.max.x + 6.0, cy - 8.0), vec2(20.0, 16.0));
let sresp = ui.interact(sr, egui::Id::new(("tool-paint-swatch", key)), Sense::click()).on_hover_text(format!("{title}: {}", tp.kind.label()));
paint_swatch(p, sr, &tp, sresp.hovered(), &t);
@@ -363,11 +410,19 @@ fn fill_stroke_options(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Pa
if ui.input(|i| i.modifiers.alt) {
let at = PaintKind::ALL.iter().position(|k| *k == tp.kind).unwrap_or(0);
let next = PaintKind::ALL.get((at + 1) % PaintKind::ALL.len()).copied().unwrap_or_default();
let k = format!("{key}Type");
tool_options(app, json!({k: next.id()}));
paint_kind(app, shape_layers, key, next);
} else if tp.kind == PaintKind::Solid {
widgets::open_popup(ui, picker_id(key));
} else if let Some((layer, prop)) = matches!(tp.kind, PaintKind::Linear | PaintKind::Radial)
.then(|| gradient_colors(app, shape_layers, if key == "fill" { "gfill" } else { "gstroke" }))
.flatten()
{
let ctx = ui.ctx().clone();
if let Err(e) = crate::menus::invoke(app, &ctx, "prop.editGradient", json!({"layer": layer, "prop": prop})) {
app.ui.status = e;
}
} else {
// No selected shape layer with that gradient: its options (new shapes' kind).
widgets::open_popup(ui, opts);
}
}
@@ -376,7 +431,7 @@ fn fill_stroke_options(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Pa
tool_options(app, json!({key: c}));
paint(app, key, json!(c));
}
paint_options_popup(app, ui, key, &options, wr.left_bottom());
paint_options_popup(app, ui, shape_layers, key, &options, wr.left_bottom());
x = sr.max.x + 12.0;
}
let width = app.session.state.shape_tool.stroke_width;
@@ -389,9 +444,28 @@ fn fill_stroke_options(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Pa
r.max.x + 14.0
}
/// A Fill or Stroke kind: for new shapes, and (as in After Effects) for the selected shape
/// layers' fills or strokes, which None switches off (#732).
fn paint_kind(app: &mut EffectcraftApp, shape_layers: &[u64], key: &str, kind: PaintKind) {
let k_type = format!("{key}Type");
tool_options(app, json!({&k_type: kind.id()}));
if shape_layers.is_empty() {
return;
}
let mut v = json!({"layers": shape_layers, k_type: kind.id()});
// A Solid Color takes the swatch's colour.
let color = if key == "fill" { app.session.state.shape_tool.fill.color } else { app.session.state.shape_tool.stroke.color };
if let (PaintKind::Solid, Some(o)) = (kind, v.as_object_mut()) {
o.insert(key.to_string(), json!(color));
}
if let Err(e) = app.session.execute("shape.fillStroke", v) {
app.ui.status = e.to_string();
}
}
/// Fill Options / Stroke Options: None, Solid Color, Linear Gradient or Radial Gradient, and the
/// blend mode and opacity new shapes get (After Effects' dialogs, applied as they change).
fn paint_options_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui, key: &str, title: &str, pos: egui::Pos2) {
fn paint_options_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui, shape_layers: &[u64], key: &str, title: &str, pos: egui::Pos2) {
let id = egui::Id::new(("tool-paint-options", key));
if !widgets::popup_is_open(ui, id) {
return;
@@ -400,6 +474,7 @@ fn paint_options_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui, key: &str, t
let tp = if key == "fill" { &app.session.state.shape_tool.fill } else { &app.session.state.shape_tool.stroke }.clone();
let blend_pop = id.with("blend");
let mut set = None;
let mut kind = None;
let mut blend_rect = Rect::NOTHING;
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos + vec2(0.0, 4.0)).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
@@ -416,8 +491,7 @@ fn paint_options_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui, key: &str, t
paint_swatch(&p, r.shrink(3.0), &ToolPaint { kind: k, ..tp.clone() }, resp.hovered(), &t);
app.auto.add(&format!("header.{key}Options.{}", k.id()), r, k.label());
if resp.clicked() {
let k_type = format!("{key}Type");
set = Some(json!({k_type: k.id()}));
kind = Some(k);
}
}
p.text(row(33.0) + vec2(134.0, 0.0), Align2::LEFT_CENTER, tp.kind.label(), Tokens::ui(11.5), t.text_dim);
@@ -451,6 +525,9 @@ fn paint_options_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui, key: &str, t
if let Some(v) = set {
tool_options(app, v);
}
if let Some(k) = kind {
paint_kind(app, shape_layers, key, k);
}
}
/// A Fill or Stroke swatch: its colour, a gradient (white to black), or None's red slash.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+53 -3
View File
@@ -22,6 +22,7 @@ pub enum Icon {
Ellipse,
Polygon,
Star,
StarFilled,
Pen,
PenAdd,
PenDelete,
@@ -147,6 +148,8 @@ impl Pen16<'_> {
let v: Vec<Pos2> = pts.iter().map(|(x, y)| self.p(*x, *y)).collect();
self.painter.add(PathShape::closed_line(v, PathStroke::new(self.width * self.s(), self.color)));
}
/// Fill a **convex** outline: the tessellator fans a concave one into slivers across its
/// notches, so a concave glyph is drawn as overlapping convex pieces (see [`SELECTION_ARROW`]).
fn fill(&self, pts: &[(f32, f32)]) {
let v: Vec<Pos2> = pts.iter().map(|(x, y)| self.p(*x, *y)).collect();
self.painter.add(PathShape::convex_polygon(v, self.color, Stroke::NONE));
@@ -206,6 +209,25 @@ impl Pen16<'_> {
}
}
/// The convex pieces of each concave filled glyph. Pieces overlap rather than abut: abutting
/// antialiased edges would leave a faint seam.
type Pieces = &'static [&'static [(f32, f32)]];
/// The Selection tool's arrow pointer (tip upper left, a notch each side of the tail): the head
/// with its left wing, the right wing, and the tail. Only the head reaches the tip: slivers
/// meeting there would antialias into a spike past it.
const SELECTION_ARROW: Pieces = &[
&[(4.5, 2.0), (4.5, 13.0), (7.2, 10.5), (10.1, 7.39)],
&[(7.5, 9.0), (8.9, 9.9), (12.5, 9.7), (10.1, 7.39)],
&[(7.8, 8.6), (7.2, 10.5), (9.2, 14.6), (10.8, 13.9), (8.9, 9.9)],
];
/// A loudspeaker: the magnet box, running a little into the cone.
const SPEAKER: Pieces = &[&[(2.0, 6.0), (5.5, 6.0), (5.5, 10.0), (2.0, 10.0)], &[(5.0, 6.0), (9.0, 2.5), (9.0, 13.5), (5.0, 10.0)]];
/// A four-pointed star: an upright and a level diamond, whose edges cross at the inner corners.
const SPARKLE: Pieces = &[&[(8.0, 1.5), (9.784, 8.0), (8.0, 14.5), (6.216, 8.0)], &[(1.5, 8.0), (8.0, 6.216), (14.5, 8.0), (8.0, 9.784)]];
#[cfg(test)]
const CONCAVE: [Pieces; 3] = [SELECTION_ARROW, SPEAKER, SPARKLE];
/// Paint `icon` centred in `rect`.
pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {
let pen = Pen16 { painter, rect, color, width: 1.25 };
@@ -215,7 +237,7 @@ pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {
pen.closed(&[(2.5, 7.5), (8.0, 2.5), (13.5, 7.5), (13.5, 13.5), (2.5, 13.5)]);
pen.rect(6.5, 9.5, 9.5, 13.5);
}
Selection => pen.fill(&[(4.5, 2.0), (4.5, 13.0), (7.2, 10.5), (9.2, 14.6), (10.8, 13.9), (8.9, 9.9), (12.5, 9.7)]),
Selection => SELECTION_ARROW.iter().for_each(|p| pen.fill(p)),
Hand => {
pen.line(&[(5.0, 9.0), (5.0, 4.0)]);
pen.line(&[(7.3, 8.0), (7.3, 2.6)]);
@@ -273,6 +295,18 @@ pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {
let pts = pen.star(8.0, 8.6, 6.4, 2.7, 5);
pen.closed(&pts);
}
StarFilled => {
// Five triangles fill the concave star without a convex-polygon approximation.
let pts = pen.star(8.0, 8.6, 6.4, 2.7, 5);
for pair in pts.windows(2) {
if let [a, b] = pair {
pen.fill(&[(8.0, 8.6), *a, *b]);
}
}
if let (Some(first), Some(last)) = (pts.first(), pts.last()) {
pen.fill(&[(8.0, 8.6), *last, *first]);
}
}
Pen => {
pen.closed(&[(8.0, 1.8), (12.0, 9.0), (8.0, 14.0), (4.0, 9.0)]);
pen.dot(8.0, 8.6, 1.1);
@@ -355,7 +389,7 @@ pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {
pen.dot(8.0, 8.0, 2.2);
}
Speaker => {
pen.fill(&[(2.0, 6.0), (5.0, 6.0), (9.0, 2.5), (9.0, 13.5), (5.0, 10.0), (2.0, 10.0)]);
SPEAKER.iter().for_each(|p| pen.fill(p));
pen.arc(9.0, 8.0, 3.0, -50.0, 50.0);
pen.arc(9.0, 8.0, 5.5, -50.0, 50.0);
}
@@ -631,7 +665,7 @@ pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {
pen.line(&[(9.4, 2.8), (6.6, 13.2)]);
}
Sparkle => {
pen.fill(&[(8.0, 1.5), (9.4, 6.6), (14.5, 8.0), (9.4, 9.4), (8.0, 14.5), (6.6, 9.4), (1.5, 8.0), (6.6, 6.6)]);
SPARKLE.iter().for_each(|p| pen.fill(p));
}
Monitor => {
pen.rrect(1.8, 2.5, 14.2, 11.0, 1.2);
@@ -737,6 +771,22 @@ fn keyframe_shapes(
mod tests {
use effectcraft_engine::keyframe::KeyHalf as H;
/// The Selection arrow (and the Speaker and Sparkle) are concave; filled as one polygon they
/// rendered as a broken fan. Each is drawn as convex pieces instead.
#[test]
fn concave_glyphs_are_filled_as_convex_pieces() {
for piece in super::CONCAVE.iter().flat_map(|g| g.iter()) {
let n = piece.len();
let turns: Vec<f32> = (0..n)
.map(|i| {
let (a, b, c) = (piece[i], piece[(i + 1) % n], piece[(i + 2) % n]);
(b.0 - a.0) * (c.1 - b.1) - (b.1 - a.1) * (c.0 - b.0)
})
.collect();
assert!(turns.iter().all(|t| *t < 0.0) || turns.iter().all(|t| *t > 0.0), "{piece:?} is not convex: {turns:?}");
}
}
/// #284: keyframes have no dark border (overlapping keys looked messy): each half is filled
/// and edged in the key's own colour.
#[test]
+137 -24
View File
@@ -16,6 +16,7 @@ pub mod credits;
pub mod dock;
mod dock_shared;
pub mod dock_ui;
mod expression_diagnostics;
pub mod frames;
pub mod gpu_failure;
pub mod header;
@@ -94,6 +95,8 @@ pub enum Dialog {
UnsavedChanges,
/// Delete Project items that compositions use? (`panels::delete_items`).
DeleteItems,
/// A gradient property's Gradient Editor (`panels::gradient_editor`, `prop.editGradient`).
GradientEditor,
}
/// The desktop's light or dark appearance where egui cannot see it (Wayland compositors that send
@@ -323,6 +326,7 @@ pub struct EffectcraftApp {
/// Audio panel VU meters.
pub meter: audio::Meter,
/// Waveform peak summaries per footage item (see `panels::waveform`).
pub(crate) expression_diagnostics: expression_diagnostics::Diagnostics,
pub(crate) waveforms: panels::waveform::Cache,
/// Last reveal shortcut and when (double-press shortcuts such as LL).
pub(crate) last_reveal: Option<(String, f64)>,
@@ -408,6 +412,7 @@ impl EffectcraftApp {
audio: None,
scrub: None,
meter: Default::default(),
expression_diagnostics: Default::default(),
waveforms: Default::default(),
last_reveal: None,
applied_prefs: None,
@@ -544,6 +549,36 @@ impl EffectcraftApp {
self.ui.saved_workspaces.keys().filter(|k| !dock::WORKSPACES.contains(&k.as_str())).cloned().collect()
}
/// The open Gradient Editor's draft (`panels::gradient_editor`): what OK would set.
pub fn gradient_draft(&self) -> &panels::gradient_editor::Draft {
&self.dialog_state.gradient
}
/// The open Gradient Editor's draft, to edit (tests and automation; the editor's own fields
/// do the same).
pub fn gradient_draft_mut(&mut self) -> &mut panels::gradient_editor::Draft {
&mut self.dialog_state.gradient
}
/// Feed this frame's share of the queued synthetic input (control channel `ui.click`,
/// `ui.drag`…) into `raw_input`. Pointer events go one per frame so egui sees press → moves
/// → release as a real gesture.
pub fn feed_synthetic(&mut self, raw_input: &mut egui::RawInput) {
if !self.synthetic.is_empty() {
// Pointer events go one per frame so egui sees press → moves → release as a real drag.
let pointer = |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. });
let n = if pointer(&self.synthetic[0]) {
1
} else {
self.synthetic
.iter()
.position(|e| pointer(e) || matches!(e, egui::Event::Key { pressed: false, .. }))
.map_or(self.synthetic.len(), |i| if pointer(&self.synthetic[i]) { i.max(1) } else { i + 1 })
};
raw_input.events.extend(self.synthetic.drain(..n));
}
}
/// Show panel `p` (opening it in its usual place if it is closed), bring it to the front and
/// give it the focus: Window ▸ <panel>.
pub fn show_panel(&mut self, p: PanelKind) {
@@ -810,27 +845,26 @@ impl EffectcraftApp {
self.viewer_image.clone()
}
/// The viewer's Resolution: the active composition's (saved with the project).
pub fn viewer_res(&self) -> state::Resolution {
self.session.active_comp().map(|c| c.resolution).unwrap_or_default()
}
/// The render scale used by the viewer right now.
pub fn viewer_scale(&self, zoom: f32, ppp: f32) -> f64 {
// The preview's Resolution (when not Auto) while it plays.
if self.playback.playing
&& let Some(f) = self.playback.res
{
let r = match f {
1 => state::Resolution::Full,
2 => state::Resolution::Half,
3 => state::Resolution::Third,
4 => state::Resolution::Quarter,
n => state::Resolution::Custom(n.min(40) as u8),
};
return r.scale(zoom, ppp);
return state::Resolution::from_factor(f.into()).scale(zoom, ppp);
}
// Auto follows the zoom alike while playing and paused, so frames cached while scrubbing
// play back, and frames cached by a preview stay on screen when it stops.
let full = self.ui.viewer.res.scale(zoom, ppp);
let res = self.viewer_res();
let full = res.scale(zoom, ppp);
// Fast Previews ▸ Adaptive Resolution / Fast Draft: lower resolution while dragging.
let (_, k) = self.session.state.viewer.fast_previews.render(self.ui.viewer.interacting || self.ui.viewer.property_interacting);
if k < 1.0 && self.ui.viewer.res == state::Resolution::Auto {
if k < 1.0 && res.is_auto() {
return full.min((full * 0.5).max(self.session.prefs.adaptive_limit()));
}
full
@@ -1140,6 +1174,9 @@ impl EffectcraftApp {
};
let mut queued = self.frames.inflight();
let series = self.frame_series(cid, scale);
// The preview's position orders prefetch and eviction (#595).
let playhead = plan.filter(|p| p.video).map(|p| frames::Playhead { series, cur, start: p.start, end: p.end, step: p.step, looping: p.looping });
self.frames.set_playhead(playhead);
if self.playback.caching
&& let Some(p) = plan
{
@@ -1180,7 +1217,10 @@ impl EffectcraftApp {
return;
}
let step = plan.map_or(1, |p| p.step);
for k in 0..ahead * 3 {
// Never further ahead than the RAM preview holds: those frames would evict the ones the
// preview shows first, or be evicted before it gets there (#595).
let window = (ahead * 3).min(self.frames_that_fit(&c, scale) - 1);
for k in 0..window {
if queued >= ahead as usize || !video {
break;
}
@@ -1542,6 +1582,11 @@ impl EffectcraftApp {
}
}
effectcraft_engine::Event::PurgeCaches => self.frames.clear(),
effectcraft_engine::Event::CopyImage { width, height, rgba } => {
if let Err(e) = copy_image(ctx, width, height, &rgba) {
self.ui.status = e;
}
}
}
}
}
@@ -1591,6 +1636,7 @@ impl EffectcraftApp {
self.session.poll_camera(true);
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
self.run_script_tasks(&ctx);
self.apply_prefs(&ctx);
self.handle_events(&ctx);
panels::unsaved::on_close_requested(self, &ctx);
@@ -1702,6 +1748,24 @@ impl EffectcraftApp {
}
impl EffectcraftApp {
/// Scripts' `app.scheduleTask` tasks that are due (repeating ones keep a ScriptUI panel
/// fresh): errors as a toast, the last line printed in the status bar, and a repaint when
/// the next one is due.
fn run_script_tasks(&mut self, ctx: &egui::Context) {
if self.session.script_ui.task_hosts.is_empty() {
return;
}
let Some(r) = effectcraft_engine::scriptui::ScriptUi::run_tasks(&mut self.session) else { return };
if let Some(msg) = r["errors"].as_array().and_then(|e| e.first()).and_then(|e| e["message"].as_str()) {
self.toast = Some((format!("Scheduled script task: {msg}"), ctx.input(|i| i.time)));
} else if let Some(line) = r["output"].as_array().and_then(|o| o.last()).and_then(|l| l.as_str()) {
self.ui.status = line.to_string();
}
if let Some(next) = r["next"].as_u64() {
ctx.request_repaint_after(std::time::Duration::from_millis(next));
}
}
/// Auto-save a dirty project when the interval has passed (Settings ▸ Project ▸ Auto-Save).
fn tick_autosave(&mut self, ctx: &egui::Context) {
let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0);
@@ -1777,19 +1841,7 @@ impl eframe::App for EffectcraftApp {
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
let injected = !self.synthetic.is_empty();
if injected {
// Pointer events go one per frame so egui sees press → moves → release as a real drag.
let pointer = |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. });
let n = if pointer(&self.synthetic[0]) {
1
} else {
self.synthetic
.iter()
.position(|e| pointer(e) || matches!(e, egui::Event::Key { pressed: false, .. }))
.map_or(self.synthetic.len(), |i| if pointer(&self.synthetic[i]) { i.max(1) } else { i + 1 })
};
raw_input.events.extend(self.synthetic.drain(..n));
}
self.feed_synthetic(raw_input);
if pointer_wrap::prepare_input(ctx, raw_input, injected) {
self.session.history.merge_key = None;
}
@@ -1868,6 +1920,18 @@ pub(crate) fn tick_playback(app: &mut EffectcraftApp, ctx: &egui::Context, scale
app.advance_playback(ctx, scale);
}
/// Put `width` × `height` straight-alpha RGBA8 pixels on the system clipboard (Composition ▸ Copy
/// Frame to Clipboard). The pixel count is checked first: egui's image constructor panics on a
/// size that doesn't match its buffer.
fn copy_image(ctx: &egui::Context, width: u32, height: u32, rgba: &[u8]) -> Result<(), String> {
let (w, h) = (width as usize, height as usize);
if w == 0 || h == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(rgba.len()) {
return Err(format!("cannot copy a malformed {width}×{height} image to the clipboard"));
}
ctx.copy_image(egui::ColorImage::from_rgba_unmultiplied([w, h], rgba));
Ok(())
}
/// Maximize a first window that doesn't fit the screen, which fits it to the space beside the
/// taskbar or dock. The 1680 × 1020 window on a smaller screen is only shrunk to the monitor's
/// size, so with its title bar it ran under the taskbar and cut menus off at the bottom of the
@@ -1901,6 +1965,55 @@ mod fit_window_tests {
}
}
#[cfg(test)]
mod copy_frame_tests {
use super::*;
fn copied(output: &egui::FullOutput) -> Vec<&egui::ColorImage> {
output
.platform_output
.commands
.iter()
.filter_map(|c| match c {
egui::OutputCommand::CopyImage(image) => Some(image),
_ => None,
})
.collect()
}
/// Composition ▸ Copy Frame to Clipboard puts the rendered frame on the system clipboard.
#[test]
fn copy_frame_puts_the_frame_on_the_clipboard() {
let mut session = Session::default();
session.execute("comp.new", json!({"name": "Copy", "width": 8, "height": 6, "duration": 1})).unwrap();
session.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap();
let mut app = EffectcraftApp::new(session);
let ctx = egui::Context::default();
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
crate::menus::invoke(&mut app, ui.ctx(), "comp.copyFrame", json!({})).unwrap();
app.handle_events(ui.ctx());
});
output.textures_delta.clear();
let images = copied(&output);
assert_eq!(images.len(), 1);
assert_eq!(images[0].size, [8, 6]);
assert!(images[0].pixels.iter().all(|p| *p == egui::Color32::from_rgb(255, 0, 0)));
}
/// A malformed image never reaches egui's panicking constructor.
#[test]
fn a_malformed_image_is_an_error_not_a_crash() {
let ctx = egui::Context::default();
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
assert!(copy_image(ui.ctx(), 4, 4, &[0; 10]).is_err());
assert!(copy_image(ui.ctx(), 0, 4, &[]).is_err());
assert!(copy_image(ui.ctx(), u32::MAX, u32::MAX, &[0; 4]).is_err());
});
output.textures_delta.clear();
assert!(copied(&output).is_empty());
}
}
#[cfg(test)]
mod gpu_failure_tests {
use super::*;
+153 -49
View File
@@ -35,7 +35,6 @@ pub const UI_COMMANDS: &[UiCommand] = &[
uic!("playback.stop", "Stop", [], None),
uic!("view.fit", "Fit", [], Some("Shift+/")),
uic!("view.actualSize", "100%", [], Some("/")),
uic!("view.res.auto", "Resolution: Auto", [], None),
uic!("viewer.nudge.up", "Move Selected Layers Up 1 Pixel at Current Magnification", [], Some("ArrowUp")),
uic!("viewer.nudge.down", "Move Selected Layers Down 1 Pixel at Current Magnification", [], Some("ArrowDown")),
uic!("viewer.nudge.left", "Move Selected Layers Left 1 Pixel at Current Magnification", [], Some("ArrowLeft")),
@@ -127,6 +126,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[
uic!("window.dockPanel", "Dock Panel", [], None),
uic!("window.floatPanel", "Undock Panel", [], None),
uic!("window.closePanel", "Close Panel", [], None),
uic!("window.panelWindow", "Move Panel to New Window", [], None),
];
pub fn panel_command_id(p: PanelKind) -> String {
@@ -273,6 +273,12 @@ fn no_params(p: &Value) -> bool {
/// Execute a UI or engine command by id.
pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
// Layer ▸ New ▸ Text (menu, shortcut, context menus) puts an insertion point in the centre of
// the comp, as After Effects does, so typing goes into Source Text rather than running
// shortcuts (#866). `engine.execute` keeps the headless default.
if id == "layer.newText" && no_params(&params) {
return run_engine(app, ctx, id, json!({"text": "", "edit": true}));
}
if no_params(&params) && app.ui.focused == PanelKind::Project {
match id {
"edit.duplicate" => return run_engine(app, ctx, "project.duplicate", json!({})),
@@ -291,6 +297,15 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
_ => {}
}
}
// Edit ▸ Paste with SVG markup on the system clipboard pastes it as a shape layer (After
// Effects 26.3). Copying in the app replaces the system clipboard with a note naming what
// was copied, so SVG there was copied after anything copied in the app.
if id == "edit.paste" && no_params(&params) && app.session.state.text_edit.is_none() {
let text = ctx.data_mut(|d| d.remove_temp::<String>(system_paste_id())).or_else(|| app.hooks.clipboard_text.as_ref().and_then(|f| f()));
if let Some(svg) = text.filter(|t| effectcraft_engine::vector::is_svg_text(t)) {
return run_engine(app, ctx, "edit.pasteSvg", json!({"svg": svg}));
}
}
// Clear follows panel focus, including the Edit menu and keyboard shortcut.
if id == "edit.clear" && params.as_object().is_some_and(|p| p.is_empty()) && app.ui.focused == PanelKind::Project {
// Through `invoke`, so deleting items that compositions use still asks first (M3.16).
@@ -442,6 +457,22 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
}
return Ok(Value::Null);
}
// Multiple monitors: {panel, window?: bool} moves a panel into its own native window (or
// back into the main window; no `window` toggles).
if id == "window.panelWindow" {
// A panel name ("Info", "Effect Controls") or its serialized form ({"Viewer": 2}).
let value = params.get("panel").ok_or("panelWindow: need `panel`")?;
let panel = match value.as_str() {
Some(name) => PanelKind::from_name(name).ok_or(format!("unknown panel `{name}`"))?,
None => serde_json::from_value::<PanelKind>(value.clone()).map_err(|_| "panelWindow: unknown `panel`".to_string())?,
};
let window = match params.get("window") {
None | Some(Value::Null) => None,
Some(value) => Some(value.as_bool().ok_or("panelWindow: `window` must be true or false")?),
};
let window = app.set_panel_window(ctx, panel, window)?;
return Ok(json!({"window": window}));
}
// A UI-only command (not in the engine's menus), so `frontend` gets it from here.
if id == "window.maximizeApp" {
return frontend(app, ctx, id, params);
@@ -497,10 +528,7 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
crate::panels::markers_ui::open_dialog(app, crate::panels::markers_ui::MarkerRef { layer, index })?;
return Ok(json!({"dialog": id}));
}
if id == "view.res.auto" {
app.ui.viewer.res = Resolution::Auto;
return Ok(Value::Null);
}
if id == "view.theme.toggle" {
app.cycle_appearance(ctx);
return Ok(json!({"appearanceMode": app.session.prefs.appearance.appearance_mode}));
@@ -525,11 +553,23 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
app.stop();
return Ok(Value::Null);
}
// The focused Layer panel has its own magnification; otherwise the Composition viewer.
"view.fit" if app.ui.focused == PanelKind::Layer => {
app.ui.layer_zoom = None;
app.ui.layer_pan = [0.0, 0.0];
return Ok(Value::Null);
}
"view.fit" => {
app.ui.viewer.zoom = None;
app.ui.viewer.fit_up_to_100 = false;
app.ui.viewer.pan = [0.0, 0.0];
return Ok(Value::Null);
}
"view.actualSize" if app.ui.focused == PanelKind::Layer => {
app.ui.layer_zoom = Some(1.0 / ctx.pixels_per_point());
app.ui.layer_pan = [0.0, 0.0];
return Ok(Value::Null);
}
"view.actualSize" => {
app.ui.viewer.zoom = Some(1.0 / ctx.pixels_per_point());
app.ui.viewer.pan = [0.0, 0.0];
@@ -758,6 +798,8 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
"view.newViewer" => json!({"viewer": crate::panels::viewers::new_viewer(app)}),
// Run by id (control channel, MCP): the Project panel's selection, whatever has focus.
"project.deleteWithoutConfirmation" => crate::panels::delete_items::delete_confirmed(app, ctx, json!({}))?,
// A gradient property's "Edit Gradient…" (the Timeline's value): the Gradient Editor.
"prop.editGradient" => crate::panels::gradient_editor::open(app, &p)?,
"window.scriptPanel" => {
let id = p.get("window").and_then(Value::as_u64).ok_or("no ScriptUI panel window")? as u32;
app.show_panel(PanelKind::ScriptPanel(id));
@@ -773,12 +815,12 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
Value::Null
}
"app.gpuInfo" => {
let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
crate::panels::dialogs::info(
app,
"GPU Information",
&format!(
"Compositing: CPU, {threads} threads (pure Rust, rayon).\nDisplay: egui on wgpu.\nLayer cache: {} MB • Preview cache: {} MB.",
"{}Layer cache: {} MB • Preview cache: {} MB.",
effectcraft_engine::sysinfo::gpu_summary(&app.session),
app.session.layer_cache.budget() >> 20,
app.frames.budget() >> 20
),
@@ -859,44 +901,35 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
}
r
}
// Zoom In / Zoom Out act on the focused viewer: the Layer panel when it has focus, else
// the Composition viewer.
"view.zoomIn" | "view.zoomOut" if app.ui.focused == PanelKind::Layer => {
let cur = app.ui.layer_zoom.unwrap_or_else(|| crate::panels::layer_panel::last_fit(ctx));
// The Layer panel zooms in points (pixels-per-point 1).
let next = zoom_step(cur, 1.0, id == "view.zoomIn");
app.ui.layer_zoom = Some(next);
json!({"zoom": next, "panel": "layer"})
}
"view.zoomIn" | "view.zoomOut" => {
let ppp = ctx.pixels_per_point();
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)
};
let next = zoom_step(cur, ppp, id == "view.zoomIn");
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 ▸ Resolution ▸ Custom without a factor (the engine sets the comp's resolution).
"view.res.custom" => {
match p.get("factor").and_then(Value::as_u64) {
Some(n) => {
v.res = match n.clamp(1, 40) {
1 => Resolution::Full,
n => Resolution::Custom(n as u8),
};
}
None => {
let cur = match v.res {
Resolution::Custom(n) => n as f64,
_ => 2.0,
};
crate::panels::dialogs::form(
app,
"Custom Resolution",
"view.res.custom",
json!({}),
vec![crate::panels::dialogs::Field::num("factor", "Render every n-th pixel", cur)],
);
}
}
let cur = match app.viewer_res() {
Resolution::Custom(n) => f64::from(n),
_ => 2.0,
};
crate::panels::dialogs::form(
app,
"Custom Resolution",
"view.res.custom",
json!({}),
vec![crate::panels::dialogs::Field::num("factor", "Render every n-th pixel", cur)],
);
Value::Null
}
"view.rulers" => toggle(&mut v.rulers, &p),
@@ -1085,6 +1118,11 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
}
"layer.openLayer" => {
let id = p.get("layer").and_then(Value::as_u64).or_else(|| app.session.state.selected_layers.first().map(|l| l.0));
// Another layer opens at Fit.
if id != app.ui.layer_panel {
app.ui.layer_zoom = None;
app.ui.layer_pan = [0.0, 0.0];
}
app.ui.layer_panel = id;
app.ui.layer_view = None;
app.show_panel(PanelKind::Layer);
@@ -1213,7 +1251,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
"keys.rpfCameraImport" => ("path", Ask::Open(&["json", "csv", "txt"])),
"essential.exportTemplate" => ("path", Ask::Save("Template.ectemplate")),
"essential.importTemplate" => ("path", Ask::Open(&["ectemplate"])),
"file.setProxy" => ("path", Ask::Open(&["mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr"])),
"file.setProxy" => ("path", Ask::Open(&["mp4", "mov", "m4v", "mkv", "webm", "mxf", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr"])),
_ => return None,
};
if params.get(key).is_some()
@@ -1225,8 +1263,8 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
return None;
}
const MEDIA: &[&str] = &[
"mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "wav", "aif", "aiff", "mp3", "flac", "ogg",
"opus", "svg", "pdf", "ai", "eps", "psd", "psb", "gltf", "glb", "obj", "json", "csv", "tsv",
"mp4", "mov", "m4v", "mkv", "webm", "mxf", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "dpx", "cin", "wav", "aif", "aiff", "mp3",
"flac", "ogg", "opus", "svg", "pdf", "ai", "eps", "psd", "psb", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv",
];
// A host whose modal dialogs would run a nested event loop inside this frame (macOS: a
// drag over the window then re-entered winit's event handler and aborted, #511) shows the
@@ -1361,6 +1399,18 @@ pub(crate) fn entry_shortcut(app: &EffectcraftApp, e: &MenuEntry) -> Option<Stri
app.session.shortcuts().shortcut_of(&e.command, &e.params).map(str::to_string)
}
/// Whether panel `p` is on screen: the front tab of a floating window, or of a docked group
/// (an open frame in a stack) that a maximized panel does not cover.
pub(crate) fn panel_shown(app: &EffectcraftApp, p: PanelKind) -> bool {
if app.ui.floating.iter().any(|f| f.panels.get(f.active) == Some(&p)) {
return true;
}
match app.ui.maximized.filter(|m| app.ui.dock.contains(*m)) {
Some(m) => m == p,
None => app.ui.dock.is_visible(p),
}
}
/// Check-mark state of frontend toggles (engine state is answered by the engine).
pub(crate) fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option<bool> {
let v = &app.ui.viewer;
@@ -1375,10 +1425,9 @@ pub(crate) fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option<bool>
"view.layerControls" => Some(v.show_layer_controls),
"playback.cacheWhenIdle" => Some(app.ui.cache_when_idle),
"playback.audio" => Some(app.session.prefs.preview.active().include_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)),
// The Tools panel is the header toolbar: always on screen.
"window.panel" => Some(pstr("panel").is_some_and(|n| n.eq_ignore_ascii_case("tools") || PanelKind::from_name(n).is_some_and(|p| panel_shown(app, p)))),
"view.panelBackground" if e.params.get("pick").is_none() => {
let cur = match v.pasteboard {
None => "mediumGray",
@@ -1537,8 +1586,8 @@ pub type Binding = (egui::Modifiers, egui::Key, String, Value);
pub fn bindings(session: &effectcraft_engine::Session) -> Vec<Binding> {
let mut v: Vec<Binding> = Vec::new();
for (sc, b) in session.shortcuts().bindings() {
// Off macOS `Cmd` is Ctrl, so a Ctrl+Cmd shortcut (Enter Full Screen's Ctrl+Cmd+F) would
// steal the plain Cmd one (Find's Cmd+F): such macOS-only shortcuts aren't bound there.
// Off macOS `Cmd` is Ctrl, so a custom Ctrl+Cmd shortcut would
// steal the plain Cmd one: such macOS-only shortcuts aren't bound there.
if !cfg!(target_os = "macos") && sc.split('+').any(|p| p == "Ctrl") && sc.split('+').any(|p| p == "Cmd") {
continue;
}
@@ -1561,6 +1610,11 @@ fn mods_match(want: egui::Modifiers, got: egui::Modifiers) -> bool {
/// Set (egui temp data) from a plain Spacebar press until its release while a tap would still
/// run the Spacebar shortcut.
/// The system clipboard's text of this frame's paste event, for the Edit ▸ Paste it runs.
fn system_paste_id() -> egui::Id {
egui::Id::new("menus-system-paste")
}
fn space_tap_id() -> egui::Id {
egui::Id::new("spacebar-tap")
}
@@ -1606,7 +1660,8 @@ fn handle_shortcuts_impl(app: &mut EffectcraftApp, ctx: &egui::Context, tab_only
let start = modifiers_at_start(ctx);
// Dialog cancellation owns Escape even when a text field has keyboard focus.
if !tab_only && app.dialog.is_some() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::panels::shortcut_editor::recording(app) || egui::Popup::is_any_open(ctx) {
// A popup or colour picker takes Escape first (the picker goes back to its original colour).
if crate::panels::shortcut_editor::recording(app) || egui::Popup::is_any_open(ctx) || crate::color_picker::open_recently(ctx) {
return;
}
ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
@@ -1641,6 +1696,9 @@ fn handle_shortcuts_impl(app: &mut EffectcraftApp, ctx: &egui::Context, tab_only
// Text editing in the viewer takes the clipboard events itself.
let clipboard = app.session.state.text_edit.is_none();
let project = app.ui.focused == PanelKind::Project;
// The paste event's text: Edit ▸ Paste pastes SVG markup as a shape layer.
let pasted =
if clipboard { ctx.input(|i| i.events.iter().rev().find_map(|e| if let egui::Event::Paste(t) = e { Some(t.clone()) } else { None })) } else { None };
let mut events: Vec<(egui::Key, egui::Modifiers, bool)> = ctx.input(|i| {
// The windowing layer turns Ctrl+C / Ctrl+X / Ctrl+V into clipboard events instead of
// key presses: map them back to the keys (with the modifiers held) so Edit ▸ Copy, Cut,
@@ -1756,9 +1814,15 @@ fn handle_shortcuts_impl(app: &mut EffectcraftApp, ctx: &egui::Context, tab_only
}
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 id == "edit.paste"
&& let Some(t) = &pasted
{
ctx.data_mut(|d| d.insert_temp(system_paste_id(), t.clone()));
}
if let Err(e) = invoke(app, ctx, &id, params) {
app.ui.status = e;
}
ctx.data_mut(|d| d.remove_temp::<String>(system_paste_id()));
}
}
}
@@ -1770,7 +1834,7 @@ pub fn menu_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
let mut nav = crate::menu_keys::Nav::default();
ui.horizontal_centered(|ui| {
ui.add_space(6.0);
egui::MenuBar::new().ui(ui, |ui| {
egui::MenuBar::new().config(egui::containers::menu::MenuConfig::new().style(crate::widgets::menu_style)).ui(ui, |ui| {
for node in effectcraft_engine::menus::menu_bar() {
if let MenuNode::Submenu { label, children } = node {
let r = ui.menu_button(crate::i18n::label(app, "", label), |ui| {
@@ -1932,10 +1996,38 @@ fn menu_entry(app: &EffectcraftApp, ui: &mut egui::Ui, e: &MenuEntry) -> egui::R
ui.add_enabled(enabled, b)
}
/// View ▸ Zoom In / Zoom Out: the next standard magnification (as a share of screen pixels, so
/// 100 % is one comp pixel per screen pixel at any display scaling) above or below `cur`, which is
/// in points per comp pixel like the result (#882).
fn zoom_step(cur: f32, ppp: f32, zoom_in: bool) -> f32 {
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 ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 };
let shown = cur * ppp;
let next = if zoom_in {
STEPS.iter().copied().find(|s| *s > shown + 1e-3).unwrap_or(32.0)
} else {
STEPS.iter().rev().copied().find(|s| *s < shown - 1e-3).unwrap_or(0.015)
};
next / ppp
}
#[cfg(test)]
mod tests {
use super::*;
/// #882: at 125 % / 150 % display scaling Zoom In reaches 100 % (one comp pixel per screen
/// pixel), not 100 % in points (125 % / 150 % on screen).
#[test]
fn zoom_steps_land_on_whole_screen_magnifications() {
for ppp in [1.0f32, 1.25, 1.5, 2.0] {
let at_100 = zoom_step(0.7 / ppp, ppp, true);
assert!((at_100 * ppp - 1.0).abs() < 1e-6, "ppp {ppp}: {}", at_100 * ppp);
assert!((zoom_step(at_100, ppp, true) * ppp - 1.5).abs() < 1e-6);
assert!((zoom_step(at_100, ppp, false) * ppp - 0.66).abs() < 1e-6);
}
assert!(zoom_step(1.0, 0.0, true).is_finite());
}
#[test]
fn shortcut_passes_share_frame_start_modifiers() {
let ctx = egui::Context::default();
@@ -1971,6 +2063,18 @@ mod tests {
}
}
#[test]
fn full_screen_default_is_platform_specific() {
let app = EffectcraftApp::new(effectcraft_engine::Session::default());
let full_screen = app.session.shortcuts().shortcut_of("view.fullScreen", &Value::Null);
if cfg!(target_os = "macos") {
assert_eq!(full_screen, Some("Ctrl+Cmd+F"));
} else {
assert_eq!(full_screen, None);
assert_eq!(app.session.shortcuts().shortcut_of("window.maximizeApp", &Value::Null), Some("Cmd+\\"));
}
}
#[test]
fn ui_and_menu_shortcuts_do_not_collide() {
let app = EffectcraftApp::new(effectcraft_engine::Session::default());
+84 -1
View File
@@ -196,6 +196,8 @@ pub fn build(app: &EffectcraftApp) -> NativeMenu {
"Servicios"
} else if crate::i18n::brazilian_portuguese(app) {
"Serviços"
} else if crate::i18n::czech(app) {
"Služby"
} else {
"Services"
}
@@ -314,8 +316,9 @@ pub fn state_key(app: &EffectcraftApp) -> u64 {
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.session.prefs.preview.active().include_audio, &app.ui.workspace, app.dialog.is_some()).hash(&mut h);
// Window menu check marks: the panels on screen.
crate::dock::PanelKind::ALL.iter().filter(|p| crate::menus::panel_shown(app, **p)).for_each(|p| p.hash(&mut h));
h.finish()
}
@@ -345,6 +348,17 @@ fn text_field_event(command: &str, clipboard: Option<String>) -> Option<Vec<egui
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());
// The menu bar takes Cmd+D and Cmd+R before the window sees them: while a confirmation that
// answers to the key is open, hand it back. Choosing the item with the mouse (no Cmd held)
// still runs it.
if let Some(key) = crate::panels::dialogs::command_key(app)
&& item.accelerator.as_deref().is_some_and(|a| ["Cmd+", "Ctrl+"].iter().any(|m| a.strip_prefix(m) == Some(key.name())))
&& ctx.input(|i| i.modifiers.command)
{
app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });
ctx.request_repaint();
return Ok(Value::Null);
}
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) {
@@ -445,6 +459,27 @@ mod tests {
assert_eq!(translated, ["Служби", "Приховати EffectCraft", "Приховати решту", "Показати все"]);
}
#[test]
fn czech_translates_macos_predefined_items() {
if !cfg!(target_os = "macos") {
return;
}
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.execute("prefs.set", json!({"key": "general.language", "value": "cs"})).unwrap();
fn labels(nodes: &[NativeNode], out: &mut Vec<String>) {
for node in nodes {
match node {
NativeNode::Predefined { label, .. } => out.push(label.clone()),
NativeNode::Submenu { children, .. } => labels(children, out),
_ => {}
}
}
}
let mut translated = vec![];
labels(&build(&app).menus, &mut translated);
assert_eq!(translated, ["Služby", "Skrýt EffectCraft", "Skrýt ostatní", "Zobrazit vše"]);
}
#[test]
fn hide_items_are_predefined_on_macos() {
let spec = build(&app());
@@ -469,6 +504,32 @@ mod tests {
}
}
#[test]
fn a_confirmation_gets_its_command_key_back_from_the_menu_bar() {
let mut app = app();
let spec = build(&app);
let dup = spec.items().into_iter().find(|i| i.command == "edit.duplicate").map(|i| i.id.clone()).unwrap();
let ctx = egui::Context::default();
app.dialog_state.delete_items.command = Some((json!({"items": []}), json!({"items": 1, "layers": 1, "comps": 1})));
app.dialog = Some(crate::Dialog::DeleteItems);
// Chosen with the mouse, Duplicate still runs.
ctx.run_ui(Default::default(), |ui| {
let _ = activate(&mut app, ui.ctx(), &spec, &dup);
})
.textures_delta
.clear();
assert!(app.synthetic.is_empty());
// Cmd+D goes to the prompt instead.
let mut raw = egui::RawInput::default();
raw.events.push(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));
ctx.run_ui(raw, |ui| {
let _ = activate(&mut app, ui.ctx(), &spec, &dup);
})
.textures_delta
.clear();
assert!(matches!(app.synthetic.as_slice(), [egui::Event::Key { key: egui::Key::D, pressed: true, .. }]));
}
#[test]
fn accelerators_convert() {
assert_eq!(accelerator("Cmd+Shift+S").as_deref(), Some("Cmd+Shift+S"));
@@ -495,6 +556,28 @@ mod tests {
}
}
/// Window menu entries are checked while their panel is on screen.
#[test]
fn window_menu_checks_the_panels_on_screen() {
use crate::dock::PanelKind;
let mut app = app();
let checked = |app: &EffectcraftApp, panel: &str| {
build(app).items().into_iter().find(|i| i.command == "window.panel" && i.params["panel"] == panel).and_then(|i| i.checked)
};
assert_eq!(checked(&app, "timeline"), Some(true));
assert_eq!(checked(&app, "tools"), Some(true));
assert_eq!(checked(&app, "renderQueue"), Some(false));
let k0 = state_key(&app);
app.show_panel(PanelKind::RenderQueue);
assert_ne!(state_key(&app), k0);
// A tab behind another one, a closed panel and panels under a maximized one are not shown.
assert_eq!((checked(&app, "renderQueue"), checked(&app, "timeline")), (Some(true), Some(false)));
app.ui.dock.close(PanelKind::RenderQueue);
assert_eq!((checked(&app, "renderQueue"), checked(&app, "timeline")), (Some(false), Some(true)));
app.ui.maximized = Some(PanelKind::Timeline);
assert_eq!((checked(&app, "timeline"), checked(&app, "project")), (Some(true), Some(false)));
}
#[test]
fn state_changes_flow_into_the_spec() {
let mut app = app();
@@ -296,7 +296,7 @@ pub fn viewer_hook(
ui.data_mut(|d| d.insert_temp(cid, pts));
}
let base = json!({"layer": a.layer.0, "effect": a.uid});
resp.context_menu(|ui| {
crate::widgets::context_menu(&resp, |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();
+117 -11
View File
@@ -3,6 +3,8 @@
//! (`dialog.comp.<field>`).
use crate::i18n::{tr, tr_args};
use crate::icons::Icon;
use effectcraft_engine::prefs::CompPreset;
use effectcraft_engine::time::{FrameRate, format_timecode_frames, parse_timecode};
use egui::{Color32, vec2};
use serde_json::json;
@@ -96,6 +98,8 @@ pub struct CompDraft {
/// Timecode text being edited (start, duration).
pub start_tc: Option<String>,
pub dur_tc: Option<String>,
/// The name being typed for Save Preset (the name row shows while `Some`).
pub preset_name: Option<String>,
}
impl Default for CompDraft {
@@ -121,6 +125,7 @@ impl Default for CompDraft {
tab: Tab::Basic,
start_tc: None,
dur_tc: None,
preset_name: None,
}
}
}
@@ -171,12 +176,84 @@ fn timecode_field(ui: &mut egui::Ui, buf: &mut Option<String>, secs: &mut f64, r
r
}
/// Draw the dialog. Returns `Some(params)` when OK is pressed, `Some(Null)` on Cancel.
pub fn show(ui: &mut egui::Ui, d: &mut CompDraft, t: &Tokens, auto: &mut Registry) -> Option<serde_json::Value> {
fn name_focus_id() -> egui::Id {
egui::Id::new("comp-preset-name-focus")
}
/// Save Preset's Choose Name prompt (drawn in its own modal over the dialog while
/// `d.preset_name` is `Some`): OK or Enter saves the draft's frame size, pixel aspect and frame
/// rate under the name, replacing a saved preset with that name; Cancel or Escape closes it.
pub fn choose_name(
ui: &mut egui::Ui,
d: &mut CompDraft,
t: &Tokens,
auto: &mut Registry,
custom: &[CompPreset],
cmds: &mut Vec<(&'static str, serde_json::Value)>,
) {
let Some(mut name) = d.preset_name.take() else { return };
let mut keep = true;
let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width()));
auto.add("dialog.comp.presetName", r.rect, "Preset Name");
if ui.data_mut(|m| m.remove_temp::<bool>(name_focus_id())).unwrap_or(false) {
r.request_focus();
}
let trimmed = name.trim();
let builtin = PRESETS.iter().any(|p| p.0 == trimmed);
let exists = custom.iter().any(|q| q.name == trimmed);
let ok = !trimmed.is_empty() && !builtin && trimmed.chars().count() <= CompPreset::MAX_NAME;
let note = if builtin {
tr("A built-in preset has this name")
} else if exists {
tr("Replaces your preset with this name")
} else {
""
};
ui.add_space(4.0);
ui.label(egui::RichText::new(note).color(Color32::GRAY));
ui.add_space(8.0);
let mut save = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
let mut cancel = ui.input(|i| i.key_pressed(egui::Key::Escape));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let b = ui.add_enabled(ok, egui::Button::new(egui::RichText::new(tr(" OK ")).color(Color32::WHITE)).fill(t.accent));
auto.add("dialog.comp.presetNameSave", b.rect, "OK");
save |= b.clicked();
let c = ui.button(tr("Cancel"));
auto.add("dialog.comp.presetNameCancel", c.rect, "Cancel");
cancel |= c.clicked();
});
if ok && save {
cmds.push(("comp.savePreset", json!({"name": trimmed, "width": d.width, "height": d.height, "pixelAspect": d.pixel_aspect, "frameRate": d.fps})));
keep = false;
}
if cancel {
keep = false;
}
if keep {
d.preset_name = Some(name);
}
}
/// Whether the draft's frame size, pixel aspect and frame rate are those of a preset.
fn matches(d: &CompDraft, w: u32, h: u32, par: f64, fps: f64) -> bool {
w == d.width && h == d.height && (par - d.pixel_aspect).abs() < 1e-3 && (fps - d.fps).abs() < 1e-3
}
/// Draw the dialog. Returns `Some(params)` when OK is pressed, `Some(Null)` on Cancel. `custom`
/// are the presets the user saved; saving or deleting one pushes its engine command to `cmds`.
pub fn show(
ui: &mut egui::Ui,
d: &mut CompDraft,
t: &Tokens,
auto: &mut Registry,
custom: &[CompPreset],
cmds: &mut Vec<(&'static str, serde_json::Value)>,
) -> Option<serde_json::Value> {
let mut out = None;
ui.horizontal(|ui| {
ui.label(tr("Composition Name:"));
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(300.0));
crate::widgets::focus_on_open(ui.ctx(), &r, &d.name);
auto.add("dialog.comp.name", r.rect, "Composition Name");
});
ui.add_space(8.0);
@@ -195,19 +272,48 @@ pub fn show(ui: &mut egui::Ui, d: &mut CompDraft, t: &Tokens, auto: &mut Registr
Tab::Basic => {
egui::Grid::new("comp-basic").num_columns(2).spacing([12.0, 9.0]).show(ui, |ui| {
ui.label(tr("Preset:"));
let current = PRESETS
.iter()
.find(|(_, w, h, par, f)| *w == d.width && *h == d.height && (par - d.pixel_aspect).abs() < 1e-3 && (f - d.fps).abs() < 1e-3)
.map(|p| p.0)
// The user's own presets win over a built-in one with the same values.
let own = custom.iter().find(|q| matches(d, q.width, q.height, q.pixel_aspect, q.frame_rate));
let current = own
.map(|q| q.name.as_str())
.or_else(|| PRESETS.iter().find(|(_, w, h, par, f)| matches(d, *w, *h, *par, *f)).map(|p| p.0))
.unwrap_or("Custom");
let r = egui::ComboBox::from_id_salt("comp-preset").width(300.0).selected_text(current).show_ui(ui, |ui| {
for (name, w, h, par, f) in PRESETS {
if ui.selectable_label(*name == current, *name).clicked() {
(d.width, d.height, d.pixel_aspect, d.fps) = (*w, *h, *par, *f);
ui.horizontal(|ui| {
let r = egui::ComboBox::from_id_salt("comp-preset").width(300.0).selected_text(current).show_ui(ui, |ui| {
// Your own presets first, then the built-in ones.
for q in custom {
if ui.selectable_label(q.name == current, &q.name).clicked() {
(d.width, d.height, d.pixel_aspect, d.fps) = (q.width, q.height, q.pixel_aspect, q.frame_rate);
}
}
if !custom.is_empty() {
ui.separator();
}
for (name, w, h, par, f) in PRESETS {
if ui.selectable_label(*name == current, *name).clicked() {
(d.width, d.height, d.pixel_aspect, d.fps) = (*w, *h, *par, *f);
}
}
});
auto.add("dialog.comp.preset", r.response.rect, "Preset");
let (save_r, _) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::hover());
let save = crate::widgets::icon_button(ui, save_r, Icon::Plus, d.preset_name.is_some(), t, egui::Id::new("comp-preset-save"))
.on_hover_text(tr("Save Preset…"));
auto.add("dialog.comp.presetSave", save_r, "Save Preset");
if save.clicked() {
d.preset_name = Some(own.map(|q| q.name.clone()).unwrap_or_default());
ui.data_mut(|m| m.insert_temp(name_focus_id(), true));
}
if let Some(q) = own {
let (del_r, _) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::hover());
let del = crate::widgets::icon_button(ui, del_r, Icon::Trash, false, t, egui::Id::new("comp-preset-delete"))
.on_hover_text(tr("Delete Preset"));
auto.add("dialog.comp.presetDelete", del_r, "Delete Preset");
if del.clicked() {
cmds.push(("comp.deletePreset", json!({"name": q.name})));
}
}
});
auto.add("dialog.comp.preset", r.response.rect, "Preset");
ui.end_row();
ui.label(tr("Width:"));
ui.horizontal(|ui| {
+23
View File
@@ -74,6 +74,10 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
if answer.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
answer = Some(false);
}
// Cmd+D (Ctrl elsewhere) is Delete.
if answer.is_none() && super::dialogs::ui_command_key(ctx, egui::Key::D) {
answer = Some(true);
}
let Some(delete) = answer else { return };
app.dialog = None;
app.dialog_state.delete_items.command = None;
@@ -89,3 +93,22 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
pub fn delete_confirmed(app: &mut EffectcraftApp, ctx: &egui::Context, params: Value) -> Result<Value, String> {
crate::menus::run_engine(app, ctx, "project.delete", params)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn cmd_d_is_delete_and_enter_is_not() {
let ctx = egui::Context::default();
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
crate::theme::install(&ctx, &app.tokens, crate::i18n::language(&app));
app.dialog_state.delete_items.command = Some((json!({"items": []}), json!({"items": 1, "layers": 1, "comps": 1})));
app.dialog = Some(Dialog::DeleteItems);
crate::panels::dialogs::press_key(&mut app, &ctx, egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(app.dialog, Some(Dialog::DeleteItems));
crate::panels::dialogs::press_key(&mut app, &ctx, egui::Key::D, egui::Modifiers::COMMAND);
assert!(app.dialog.is_none() && app.dialog_state.delete_items.command.is_none(), "Cmd+D answered Delete");
}
}
+104 -6
View File
@@ -60,12 +60,15 @@ pub struct DialogState {
pub unsaved: super::unsaved::Pending,
/// Deleting Project items in use: the deletion waiting on the prompt.
pub delete_items: super::delete_items::Pending,
/// The Gradient Editor's draft and the property it edits.
pub gradient: super::gradient_editor::Draft,
}
pub fn open_new_comp(app: &mut EffectcraftApp) {
let n = app.session.project.comps().count() + 1;
let last = app.dialog_state.last_new_comp.clone().unwrap_or_default();
app.dialog_state.comp = CompDraft { name: format!("Comp {n}"), tab: super::comp_settings::Tab::Basic, start_tc: None, dur_tc: None, ..last };
app.dialog_state.comp =
CompDraft { name: format!("Comp {n}"), tab: super::comp_settings::Tab::Basic, start_tc: None, dur_tc: None, preset_name: None, ..last };
app.dialog_state.editing_existing = false;
app.dialog = Some(Dialog::NewComp);
}
@@ -149,9 +152,32 @@ pub fn route_layer_settings(app: &mut EffectcraftApp, id: &str, params: &Value)
}
}
/// The room a modal dialog may take: the window less a margin.
fn modal_space(ctx: &egui::Context) -> egui::Vec2 {
(ctx.content_rect().size() - vec2(48.0, 48.0)).max(vec2(120.0, 80.0))
}
pub(crate) fn modal(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui)) {
let available = (ctx.content_rect().size() - vec2(48.0, 48.0)).max(vec2(120.0, 80.0));
let size = size.min(available);
modal_with_scroll(ctx, title, size, t, false, body);
}
pub(crate) fn modal_vertical(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui)) {
modal_with_scroll(ctx, title, size, t, true, body);
}
fn modal_with_scroll(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, vertical_only: bool, body: impl FnOnce(&mut egui::Ui)) {
let max_height = (modal_space(ctx).y - 84.0).max(40.0);
modal_fit(ctx, title, size, t, |ui, _| {
let scroll = if vertical_only { egui::ScrollArea::vertical() } else { egui::ScrollArea::both() };
scroll.max_height(max_height).auto_shrink([false, true]).show(ui, body);
});
}
/// [`modal`] without its scroll area, for a dialog that keeps its buttons in view and scrolls
/// only its content: `body` gets the height left under the title, with `size` kept within the
/// window.
pub(crate) fn modal_fit(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui, f32)) {
let size = size.min(modal_space(ctx));
egui::Modal::new(egui::Id::new(("modal", title)))
.backdrop_color(Color32::from_black_alpha(120))
.frame(egui::Frame::window(&ctx.style_of(ctx.theme())).fill(t.panel_bg).inner_margin(egui::Margin::same(18)))
@@ -161,7 +187,8 @@ pub(crate) fn modal(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Toke
// The id stays keyed on the untranslated source, so switching language cannot move it.
ui.label(egui::RichText::new(tr(title)).font(Tokens::semibold(15.0)).color(t.tab_text_active));
ui.add_space(10.0);
egui::ScrollArea::both().max_height((available.y - 84.0).max(40.0)).auto_shrink([false, true]).show(ui, body);
let title_h = ui.cursor().top() - ui.min_rect().top();
body(ui, (size.y - 36.0 - title_h).max(40.0));
});
}
@@ -193,6 +220,7 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context) {
Dialog::RenderTemplates => super::rq_templates::show(app, ctx, &t),
Dialog::UnsavedChanges => super::unsaved::show(app, ctx, &t),
Dialog::DeleteItems => super::delete_items::show(app, ctx, &t),
Dialog::GradientEditor => super::gradient_editor::show(app, ctx, &t),
}
}
@@ -311,10 +339,24 @@ fn about_main(app: &mut EffectcraftApp, ui: &mut egui::Ui, t: &Tokens, cmd: &mut
fn comp_settings(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens, existing: bool) {
let mut d = app.dialog_state.comp.clone();
let mut result = None;
let custom = app.session.prefs.comp_presets.clone();
let mut cmds = Vec::new();
modal(ctx, "Composition Settings", vec2(600.0, 470.0), t, |ui| {
result = super::comp_settings::show(ui, &mut d, t, &mut app.auto);
result = super::comp_settings::show(ui, &mut d, t, &mut app.auto, &custom, &mut cmds);
});
if result.is_none() && ui_enter(ctx) {
if d.preset_name.is_some() {
// Save Preset asks for the name in its own window over the dialog, as After Effects does.
result = None;
modal(ctx, "Choose Name", vec2(360.0, 150.0), t, |ui| super::comp_settings::choose_name(ui, &mut d, t, &mut app.auto, &custom, &mut cmds));
}
// Enter that saved a preset name (or while one is typed) doesn't also press OK.
let preset_busy = !cmds.is_empty() || d.preset_name.is_some();
for (id, params) in cmds {
if let Err(e) = app.session.execute(id, params) {
app.ui.status = e.to_string();
}
}
if result.is_none() && !preset_busy && ui_enter(ctx) {
result = Some(super::comp_settings::params(&d));
}
app.dialog_state.comp = d;
@@ -334,6 +376,35 @@ fn comp_settings(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens, exis
}
}
/// One frame of the open dialog with `key` pressed.
#[cfg(test)]
pub(crate) fn press_key(app: &mut EffectcraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) {
let mut raw = egui::RawInput::default();
raw.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });
let mut out = ctx.run_ui(raw, |ui| {
app.auto.begin_frame();
show(app, ui.ctx());
});
out.textures_delta.clear();
}
/// The letter that answers the open confirmation with Cmd (Ctrl elsewhere): Cmd+D is Delete in
/// Delete Items, Cmd+R is Revert in Revert Project. The native menu bar hands these keys back
/// while the prompt is open ([`crate::native_menu::activate`]).
pub(crate) fn command_key(app: &EffectcraftApp) -> Option<egui::Key> {
match app.dialog? {
Dialog::DeleteItems => Some(egui::Key::D),
Dialog::UnsavedChanges if super::unsaved::is_revert(app) => Some(egui::Key::R),
_ => None,
}
}
/// Cmd+`key` (Ctrl elsewhere) pressed, also while a text field has focus: ask before the dialog
/// is drawn, so the field does not edit with the key first.
pub(crate) fn ui_command_key(ctx: &egui::Context, key: egui::Key) -> bool {
ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, key))
}
pub(crate) fn ui_enter(ctx: &egui::Context) -> bool {
!ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Enter))
}
@@ -353,6 +424,7 @@ fn solid(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
ui.horizontal(|ui| {
ui.label(tr("Name:"));
let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(320.0));
crate::widgets::focus_on_open(ui.ctx(), &r, &name);
auto.add("dialog.solid.name", r.rect, "Name");
});
ui.add_space(8.0);
@@ -628,6 +700,32 @@ mod tests {
assert_eq!(app.session.project.comps().count(), comps + 1, "Single Composition is the default");
}
#[test]
fn a_dialog_opens_with_its_name_field_focused_and_selected() {
let (mut app, ctx) = app();
let selected = |ctx: &egui::Context| {
let id = ctx.memory(|m| m.focused())?;
egui::TextEdit::load_state(ctx, id)?.cursor.char_range().map(|r| r.as_sorted_char_range()).map(|r| r.start.0..r.end.0)
};
open_new_comp(&mut app);
let name = app.dialog_state.comp.name.clone();
frame(&mut app, &ctx);
frame(&mut app, &ctx);
assert_eq!(selected(&ctx), Some(0..name.chars().count()), "typing replaces “{name}”");
// Afterwards the focus is the user's: it is not taken back.
ctx.memory_mut(|m| m.stop_text_input());
frame(&mut app, &ctx);
assert!(ctx.memory(|m| m.focused()).is_none());
// Closed and opened again: focused again.
app.dialog = None;
frame(&mut app, &ctx);
frame(&mut app, &ctx);
open_new_solid(&mut app).unwrap();
frame(&mut app, &ctx);
frame(&mut app, &ctx);
assert_eq!(selected(&ctx), Some(0..app.dialog_state.solid_name.chars().count()));
}
#[test]
fn composition_settings_register_every_control_and_new_comp_remembers() {
let (mut app, ctx) = app();
+4 -2
View File
@@ -173,7 +173,8 @@ pub fn camera(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
});
ui.end_row();
ui.label(tr("Name"));
ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(240.0));
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(240.0));
crate::widgets::focus_on_open(ui.ctx(), &r, &d.name);
ui.end_row();
ui.label(tr("Preset"));
let focal = focal_for_zoom(w, d.zoom);
@@ -258,7 +259,8 @@ pub fn light(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
super::dialogs::modal(ctx, "Light Settings", vec2(480.0, 470.0), t, |ui| {
egui::Grid::new("light-grid").num_columns(2).spacing([14.0, 9.0]).show(ui, |ui| {
ui.label(tr("Name"));
ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(220.0));
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(220.0));
crate::widgets::focus_on_open(ui.ctx(), &r, &d.name);
ui.end_row();
ui.label(tr("Light Type"));
egui::ComboBox::from_id_salt("light-type").selected_text(KINDS[d.kind.min(3)].label()).show_ui(ui, |ui| {
+89 -7
View File
@@ -121,7 +121,7 @@ pub fn choose_files_after_apply(app: &mut EffectcraftApp, applied: &serde_json::
/// An undo-merge key for one gesture on `id`: a new key each time a drag starts, so separate
/// drags are separate undo steps while one drag is one step.
pub(super) fn gesture_key(ui: &egui::Ui, id: egui::Id, started: bool) -> String {
pub(crate) fn gesture_key(ui: &egui::Ui, id: egui::Id, started: bool) -> String {
let kid = id.with("gesture");
let n: u64 = if started {
let n = ui.data(|d| d.get_temp::<u64>(kid)).unwrap_or(0) + 1;
@@ -194,6 +194,7 @@ pub(crate) fn toggle_pick(app: &mut EffectcraftApp, kind: &str, layer: &Layer, p
app.ui.fx_pick = None;
} else {
app.ui.fx_pick = Some(pick);
app.ui.text_color_pick = None;
app.ui.status = if kind == "point" {
format!("Click in the Composition panel to set {}", prop.name)
} else {
@@ -1158,9 +1159,35 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
app.auto.add(&format!("effectControls.effect.{}.twirl", g.uid), tw, &g.name);
let name = bp.text(pos2(tw.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, &g.name, Tokens::semibold(12.0), t.text);
app.auto.add(&format!("effectControls.effect.{}.name", g.uid), name, &g.name);
let rename_id = egui::Id::new(("ec-rename", g.uid));
let editing: Option<String> = ctx.data(|d| d.get_temp(rename_id));
let reset = Rect::from_min_size(pos2(r.max.x - 96.0, r.min.y + 4.0), vec2(40.0, 18.0));
if let Some(mut value) = editing.as_ref().cloned() {
let name_rect = Rect::from_min_max(pos2(tw.max.x + 6.0, r.min.y + 2.0), pos2(reset.min.x - 6.0, r.max.y - 2.0));
let response = ui.put(name_rect, egui::TextEdit::singleline(&mut value).id(rename_id.with("field")).font(Tokens::semibold(12.0)));
// Focus the field the frame it first exists: focusing an id not yet on screen leaves
// the accessibility tree with a focus it doesn't contain.
if ctx.data_mut(|d| d.remove_temp::<bool>(rename_id.with("start"))).is_some() {
crate::widgets::select_all(&ctx, response.id, &value);
response.request_focus();
}
app.auto.add(&format!("effectControls.effect.{}.nameEdit", g.uid), name_rect, "Effect name");
// Escape cancels. egui drops the field's focus on Escape in the same frame, so the
// key is checked on the focus being lost as well as held.
let escape = (response.has_focus() || response.lost_focus()) && ui.input(|i| i.key_pressed(egui::Key::Escape));
let commit = response.lost_focus() || (response.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)));
if escape || commit {
ctx.data_mut(|d| d.remove::<String>(rename_id));
if !escape && !value.trim().is_empty() && value != g.name {
actions.push(("prop.renameGroup".into(), json!({"layer": layer.id.0, "prop": g.uid, "name": value})));
}
} else {
ctx.data_mut(|d| d.insert_temp(rename_id, value));
}
} else {
let name = bp.text(pos2(tw.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, &g.name, Tokens::semibold(12.0), t.text);
app.auto.add(&format!("effectControls.effect.{}.name", g.uid), name, &g.name);
}
let rresp = ui.interact(reset, egui::Id::new(("ec-reset", g.uid)), Sense::click());
bp.text(reset.center(), Align2::CENTER_CENTER, crate::i18n::tr("Reset"), Tokens::ui(11.5), if rresp.hovered() { t.hot_text } else { t.text_dim });
app.auto.add(&format!("effectControls.effect.{}.reset", g.uid), reset, "Reset");
@@ -1183,8 +1210,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let hresp = ui.interact(
Rect::from_min_max(pos2(tw.max.x, r.min.y), pos2(reset.min.x - 4.0, r.max.y)),
egui::Id::new(("ec-hdr", g.uid)),
Sense::click_and_drag(),
if editing.is_some() { Sense::hover() } else { Sense::click_and_drag() },
);
if hresp.double_clicked() {
ctx.data_mut(|d| d.insert_temp(rename_id, g.name.clone()));
ctx.data_mut(|d| d.insert_temp(rename_id.with("start"), true));
}
hresp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, active, &g.name));
app.auto.add(&format!("effectControls.effect.{}", g.uid), r, &g.name);
if hresp.clicked() || hresp.drag_started() || hresp.secondary_clicked() {
@@ -1202,7 +1233,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if hresp.drag_started() {
ctx.data_mut(|d| d.insert_temp(drag_id, g.uid));
}
hresp.context_menu(|ui| {
crate::widgets::context_menu(&hresp, |ui| {
let lid = layer.id.0;
let mut item = |ui: &mut egui::Ui, label: &str, enabled: bool, cmd: &str, params: serde_json::Value| {
if ui.add_enabled(enabled, egui::Button::new(label)).clicked() {
@@ -1213,6 +1244,11 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
item(ui, "Copy", true, "effect.copy", json!({"layer": lid, "effect": g.uid}));
item(ui, "Paste", has_clip, "effect.paste", json!({"layers": [lid]}));
item(ui, "Duplicate", true, "effect.duplicate", json!({"layer": lid, "effect": g.uid}));
if ui.button(crate::i18n::tr("Rename")).clicked() {
ctx.data_mut(|d| d.insert_temp(rename_id, g.name.clone()));
ctx.data_mut(|d| d.insert_temp(rename_id.with("start"), true));
ui.close();
}
ui.separator();
item(ui, "Reset", true, "effect.reset", json!({"layer": lid, "effect": g.uid}));
item(ui, "Remove", true, "effect.remove", json!({"layer": lid, "effect": g.uid}));
@@ -1285,7 +1321,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let open = ui.input(|i| i.pointer.secondary_clicked())
&& ui.rect_contains_pointer(body)
&& (!egui::Popup::is_any_open(&ctx) || egui::Popup::is_id_open(&ctx, menu_id));
egui::Popup::context_menu(&bg).id(menu_id).open_memory(open.then_some(egui::SetOpenCommand::Bool(true))).show(|ui| {
egui::Popup::context_menu(&bg).style(crate::widgets::menu_style).id(menu_id).open_memory(open.then_some(egui::SetOpenCommand::Bool(true))).show(|ui| {
ui.set_min_width(200.0);
actions.extend(crate::menus::menu_contents(app, ui, "Effect"));
});
@@ -1425,7 +1461,50 @@ pub fn viewer_hook(
app.ui.status.clear();
}
}
let picking = app.ui.fx_pick.is_some();
if let Some(pick) = app.ui.text_color_pick.clone() {
if ectx.comp.layer(effectcraft_engine::project::LayerId(pick.layer)).is_none() {
app.ui.text_color_pick = None;
app.ui.status.clear();
} else {
app.viewer_pixels();
let resp = ui.interact(map.area, egui::Id::new("viewer-text-color-pick"), Sense::click());
app.auto.add("viewer.textColorPick", map.area, &pick.field);
let chip = Rect::from_min_size(map.area.min + vec2(10.0, 10.0), vec2(220.0, 22.0));
painter.rect_filled(chip, 11.0, Color32::from_black_alpha(180));
painter.text(chip.center(), Align2::CENTER_CENTER, crate::i18n::tr_args("Click to sample text {}", &[&pick.field]), Tokens::ui(11.5), t.text);
if let Some(pos) = resp.hover_pos() {
ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
let c = map.to_comp(pos);
app.pointer_comp = Some([c[0] as f32, c[1] as f32]);
if let Some(img) = &app.viewer_image
&& let Some(s) = fw::sample_frame(img, super::viewer_tools::shown_region(&ctx, map.comp), c)
{
let sw = Rect::from_min_size(pos + vec2(14.0, 14.0), vec2(26.0, 18.0));
painter.rect_filled(sw, 2.0, Color32::from_rgb((s[0] * 255.0) as u8, (s[1] * 255.0) as u8, (s[2] * 255.0) as u8));
painter.rect_stroke(sw, 2.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Outside);
}
}
if resp.clicked()
&& let Some(pos) = resp.interact_pointer_pos()
&& let Some(img) = &app.viewer_image
&& let Some(s) = fw::sample_frame(img, super::viewer_tools::shown_region(&ctx, map.comp), map.to_comp(pos))
{
let mut params = json!({"layer": pick.layer});
params[&pick.field] = json!([s[0], s[1], s[2]]);
if let Some(range) = pick.range {
params["range"] = json!(range);
}
actions.push(("layer.setText".into(), params));
app.ui.text_color_pick = None;
app.ui.status.clear();
}
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
app.ui.text_color_pick = None;
app.ui.status.clear();
}
}
}
let picking = app.ui.fx_pick.is_some() || app.ui.text_color_pick.is_some();
let point_pick = app.ui.fx_pick.clone().filter(|p| p.kind == "point");
if app.ui.viewer.show_layer_controls || point_pick.is_some() {
// ⊕ controls for the point parameters of the selected effects.
@@ -1454,6 +1533,9 @@ pub fn viewer_hook(
if !picking && app.ui.viewer.show_layer_controls && matches!(&g.kind, GroupKind::Effect { effect } if effect == super::fx_editors::RESHAPE) {
super::fx_editors::reshape_overlay(app, ui, painter, map, ectx, layer, g, &m, &mut actions);
}
if !picking && app.ui.viewer.show_layer_controls && matches!(&g.kind, GroupKind::Effect { effect } if effect == super::fx_editors::MESH_WARP) {
super::fx_editors::mesh_warp_overlay(app, ui, painter, map, ectx, layer, g, &fm, &mut actions);
}
let scope = FxScope { effect: &g.match_id, root: g, path: String::new() };
let mut pts = Vec::new();
visible_points(g, &scope, layer, ectx, 0, &mut pts);
+24 -4
View File
@@ -1,7 +1,7 @@
//! Effects & Presets: search (matches highlighted), the contents menu (colour-depth / GPU
//! filters, animation presets on/off, categories or alphabetical, refresh), Favorites (star an
//! effect), Recently Used, "* Animation Presets" (EffectCraft's own text animation presets and
//! the user's `.ecpreset` files) and the effect categories. Double-click applies to the
//! effect), Recently Used, "* Animation Presets" (EffectCraft's own text animation and transition
//! presets and the user's `.ecpreset` files) and the effect categories. Double-click applies to the
//! selected layers; dragging an effect onto a layer (timeline, viewer, Effect Controls) applies
//! it there.
@@ -108,6 +108,8 @@ fn highlighted(p: &egui::Painter, pos: egui::Pos2, name: &str, query: &str, t: &
enum Apply {
Effect(String),
TextPreset(String),
/// A built-in animation preset (Transitions…) by id.
Builtin(String),
PresetFile(String),
}
@@ -340,18 +342,35 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
// * Animation Presets: our text presets and the user's .ecpreset files.
// * Animation Presets: our own presets (Text, Transitions…) and the user's .ecpreset files.
if view.presets {
let text: Vec<(String, String)> =
effectcraft_engine::text_presets().into_iter().filter(|(_, n)| query.is_empty() || n.to_lowercase().contains(&query)).collect();
let builtin: Vec<(String, String, String)> =
effectcraft_engine::animation_presets().into_iter().filter(|(_, n, _)| query.is_empty() || n.to_lowercase().contains(&query)).collect();
let mut categories: Vec<&str> = Vec::new();
for (_, _, c) in &builtin {
if !categories.contains(&c.as_str()) {
categories.push(c);
}
}
let files: Vec<PresetFile> =
user_presets(&ctx, force_scan).into_iter().filter(|f| query.is_empty() || f.name.to_lowercase().contains(&query)).collect();
if (!text.is_empty() || !files.is_empty()) && folder_row(app, ui, &lp, list, &mut y, "presets", "* Animation Presets", 0.0, searching, None) {
let any = !text.is_empty() || !builtin.is_empty() || !files.is_empty();
if any && folder_row(app, ui, &lp, list, &mut y, "presets", "* Animation Presets", 0.0, searching, None) {
if !text.is_empty() && folder_row(app, ui, &lp, list, &mut y, "presets/Text", "Text", 14.0, searching, None) {
for (id, name) in text {
preset_row(app, ui, &lp, list, &mut y, &name, &format!("effects.preset.text.{id}"), &query, Apply::TextPreset(id.clone()), &mut apply);
}
}
for cat in &categories {
if !folder_row(app, ui, &lp, list, &mut y, &format!("presets/{cat}"), cat, 14.0, searching, None) {
continue;
}
for (id, name, _) in builtin.iter().filter(|(_, _, c)| c == cat) {
preset_row(app, ui, &lp, list, &mut y, name, &format!("effects.preset.builtin.{id}"), &query, Apply::Builtin(id.clone()), &mut apply);
}
}
if !files.is_empty() && folder_row(app, ui, &lp, list, &mut y, "presets/User", "User Presets", 14.0, searching, None) {
for f in files {
preset_row(
@@ -418,6 +437,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let (cmd, params) = match &apply {
Apply::Effect(id) => ("effect.apply", json!({"effect": id})),
Apply::TextPreset(id) => ("layer.applyTextPreset", json!({"preset": id})),
Apply::Builtin(id) => ("anim.applyBuiltinPreset", json!({"preset": id})),
Apply::PresetFile(path) => ("anim.applyPreset", json!({"path": path})),
};
match app.session.execute(cmd, params) {
+3 -3
View File
@@ -129,7 +129,7 @@ fn body(app: &mut EffectcraftApp, ui: &mut egui::Ui) -> (Actions, Actions) {
// ---- Bottom buttons.
ui.horizontal_wrapped(|ui| {
let r = ui.menu_button(tr("Add Formatting"), |ui| {
let r = crate::widgets::menu_button(ui, tr("Add Formatting"), |ui| {
if ui.button(tr("Add Group")).clicked() {
actions.push(("essential.addGroup".into(), json!({"comp": cid.0})));
ui.close();
@@ -143,7 +143,7 @@ fn body(app: &mut EffectcraftApp, ui: &mut egui::Ui) -> (Actions, Actions) {
// The selected property as a Font control (Source Text) or a uniform Scale slider.
let has_sel = !app.session.state.selected_props.is_empty();
let r = ui.add_enabled_ui(has_sel, |ui| {
ui.menu_button(tr("Add Selected As"), |ui| {
crate::widgets::menu_button(ui, tr("Add Selected As"), |ui| {
for (label, as_type) in [("Font Control", "font"), ("Uniform Scale", "scale")] {
if ui.button(label).clicked() {
actions.push(("essential.addProperty".into(), json!({"as": as_type})));
@@ -270,7 +270,7 @@ fn link_menu(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, c: &EgCon
_ => vec![],
};
let has_sel = !app.session.state.selected_props.is_empty();
let r = ui.menu_button(RichText::new("⋯").size(10.0), |ui| {
let r = crate::widgets::menu_button(ui, RichText::new("⋯").size(10.0), |ui| {
if ui.button(tr("Add Mirror")).clicked() {
actions.push(("essential.addMirror".into(), json!({"comp": cid.0, "control": c.id, "group": group})));
ui.close();
+21 -21
View File
@@ -4,10 +4,11 @@
//! Automation ids: `viewer.exprErrors`, `viewer.exprErrors.prev`, `viewer.exprErrors.next`.
use crate::i18n::tr;
use effectcraft_engine::commands::expr_tools::{self, ExprError};
use effectcraft_engine::commands::expr_tools::ExprError;
use effectcraft_engine::project::ItemId;
use egui::{Align2, Color32, Rect, Sense, pos2, vec2};
use serde_json::json;
use std::sync::Arc;
use crate::EffectcraftApp;
use crate::theme::Tokens;
@@ -17,35 +18,32 @@ pub const HEIGHT: f32 = 22.0;
#[derive(Clone, Default)]
struct Cache {
key: (u64, u64, i64),
errors: Vec<ExprError>,
errors: Arc<[ExprError]>,
/// Shown error (index).
current: usize,
}
fn cache_id() -> egui::Id {
egui::Id::new("expr-error-bar")
fn cache_id(cid: ItemId) -> egui::Id {
egui::Id::new(("expr-error-bar", cid.0))
}
/// The comp's failing expressions (recomputed when the project or the time changes; kept while
/// playing).
fn errors(app: &EffectcraftApp, ctx: &egui::Context, cid: ItemId) -> Cache {
let t = app.session.time_of(cid);
let key = (app.session.revision, cid.0, t.0);
let mut c: Cache = ctx.data(|d| d.get_temp(cache_id())).unwrap_or_default();
let stale = c.key != key && !(app.playback.playing && c.key.1 == cid.0);
if stale {
c.errors = expr_tools::errors(&app.session, cid, t);
c.key = key;
c.current = c.current.min(c.errors.len().saturating_sub(1));
ctx.data_mut(|d| d.insert_temp(cache_id(), c.clone()));
/// Both layout and painting read the same completed diagnostics; neither evaluates expressions.
fn errors(app: &mut EffectcraftApp, ctx: &egui::Context, cid: ItemId) -> Cache {
let mut c: Cache = ctx.data(|d| d.get_temp(cache_id(cid))).unwrap_or_default();
let interacting = app.playback.playing || ctx.input(|i| i.pointer.any_down()) || app.ui.viewer.interacting || app.ui.viewer.property_interacting;
c.errors = app.expression_diagnostics.errors(&app.session, ctx, cid, interacting);
if let Some(error) = app.expression_diagnostics.take_failure() {
log::warn!("{error}");
app.ui.status = error;
}
c.current = c.current.min(c.errors.len().saturating_sub(1));
ctx.data_mut(|d| d.insert_temp(cache_id(cid), c.clone()));
c
}
/// Height the bar needs for `cid` (0 when every expression evaluates).
pub fn height(app: &EffectcraftApp, ctx: &egui::Context, cid: ItemId) -> f32 {
if app.session.expr.is_none() || errors(app, ctx, cid).errors.is_empty() { 0.0 } else { HEIGHT }
pub fn height(app: &mut EffectcraftApp, ctx: &egui::Context, cid: ItemId) -> f32 {
if errors(app, ctx, cid).errors.is_empty() { 0.0 } else { HEIGHT }
}
pub fn draw(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, cid: ItemId) {
@@ -71,12 +69,12 @@ pub fn draw(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, cid: ItemId
app.auto.add(auto, r, label);
if resp.clicked() {
c.current = (i + d) % n;
ctx.data_mut(|dd| dd.insert_temp(cache_id(), c.clone()));
ctx.data_mut(|dd| dd.insert_temp(cache_id(cid), c.clone()));
}
}
p.text(count.center(), Align2::CENTER_CENTER, format!("{}/{n}", i + 1), Tokens::ui(11.0), t.text);
let comp_name = app.session.project.item(cid).map(|it| it.name.clone()).unwrap_or_default();
let e = c.errors[i].clone();
let Some(e) = c.errors.get(i).cloned() else { return };
let msg_rect = Rect::from_min_max(pos2(rect.min.x + 26.0, rect.min.y), pos2(prev.min.x - 6.0, rect.max.y));
let resp = ui.interact(msg_rect, egui::Id::new("expr-bar-msg"), Sense::click()).on_hover_text(tr("Click to reveal the expression in the timeline"));
p.with_clip_rect(msg_rect).text(
@@ -87,6 +85,8 @@ pub fn draw(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, cid: ItemId
if resp.hovered() { Color32::WHITE } else { t.text },
);
app.auto.add("viewer.exprErrors", msg_rect, &e.describe(&comp_name));
// Keep the former banner automation id as an alias for the unified error strip.
app.auto.add("viewer.expressionErrorBanner", msg_rect, &e.describe(&comp_name));
if resp.clicked() {
let _ = app.session.execute("layer.select", json!({"comp": cid.0, "layers": [e.layer]}));
let _ = app.session.execute("prop.select", json!({"comp": cid.0, "layer": e.layer, "prop": e.prop, "selectKeys": false}));
+1 -44
View File
@@ -1,7 +1,6 @@
//! The expression editor of the Timeline, following Settings ▸ Scripting & Expressions:
//! Font Size, Syntax Highlighting, Line Numbers, Auto-complete (Tab accepts), Bracket Matching
//! and Word Wrap; and the Composition panel's expression error banner (Show Expression Error
//! Banner).
//! and Word Wrap. The Composition viewer uses the shared diagnostics in `expr_bar`.
use effectcraft_engine::prefs::Scripting;
use egui::text::{LayoutJob, TextFormat};
@@ -381,48 +380,6 @@ pub fn editor(ui: &mut egui::Ui, id: egui::Id, buf: &mut String, rect: Rect, p:
out.response.response
}
/// Settings ▸ Scripting & Expressions ▸ Show Expression Error Banner: the first failing
/// expression of the comp at the current time, in a banner along the bottom of the viewer
/// (click it to reveal the property).
pub fn error_banner(app: &mut crate::EffectcraftApp, ui: &egui::Ui, area: Rect) {
if !app.session.prefs.scripting.error_banner {
return;
}
let Some(cid) = app.session.active_comp_id() else { return };
let key = (app.session.revision, cid.0, app.session.time().0);
let id = egui::Id::new("expr-error-banner");
let cached: Option<((u64, u64, i64), Vec<serde_json::Value>)> = ui.ctx().data(|d| d.get_temp(id));
let errors = match cached {
Some((k, e)) if k == key => e,
_ => {
let e = app.session.expression_errors(cid);
ui.ctx().data_mut(|d| d.insert_temp(id, (key, e.clone())));
e
}
};
let Some(first) = errors.first() else { return };
let layer = first["layer"].as_u64().unwrap_or(0);
let lname = app.session.active_comp().and_then(|c| c.layer(effectcraft_engine::project::LayerId(layer))).map(|l| l.name.clone()).unwrap_or_default();
let msg = format!(
"⚠ Expression error{}: {} ▸ {}: {}",
if errors.len() > 1 { format!(" (1 of {})", errors.len()) } else { String::new() },
lname,
first["name"].as_str().unwrap_or(""),
first["error"].as_str().unwrap_or("").lines().next().unwrap_or("")
);
let r = Rect::from_min_max(pos2(area.min.x, area.max.y - 22.0), area.max);
let p = ui.painter();
p.rect_filled(r, 0.0, Color32::from_rgb(0xf0, 0xc0, 0x30));
p.text(pos2(r.min.x + 8.0, r.center().y), egui::Align2::LEFT_CENTER, msg, Tokens::ui(11.5), Color32::BLACK);
app.auto.add("viewer.expressionErrorBanner", r, "Expression error banner");
if ui.interact(r, id.with("click"), egui::Sense::click()).clicked() {
let p = serde_json::json!({"props": [{"layer": layer, "prop": first["prop"]}]});
if let Err(e) = crate::menus::invoke(app, ui.ctx(), "timeline.revealProps", p) {
app.ui.status = e;
}
}
}
#[cfg(test)]
mod contrast_tests {
use super::*;
+6 -1
View File
@@ -19,7 +19,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.pasteboard);
let Some(view) = app.session.state.footage_panel.clone() else {
p.text(rect.center(), Align2::CENTER_CENTER, tr("Double-click footage in the Project panel to open it here"), Tokens::ui(12.0), t.text_faint);
// Wrapped to the panel, so a narrow panel breaks the hint into lines instead of clipping it.
let hint = tr("Double-click footage in the Project panel to open it here");
let mut job = egui::text::LayoutJob::simple(hint.to_owned(), Tokens::ui(12.0), t.text_faint, (rect.width() - 20.0).max(40.0));
job.halign = egui::Align::Center;
let galley = p.layout_job(job);
p.galley(pos2(rect.center().x, rect.center().y - galley.size().y * 0.5), galley, t.text_faint);
app.auto.add("footage.empty", rect, "Footage panel (empty)");
return;
};
+61 -15
View File
@@ -215,16 +215,15 @@ 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,
)],
),
// Photoshop files: Import Kind (Footage / Composition / – Retain Layer Sizes). Dropped
// files start at Settings ▸ Import ▸ Default Drag Import As.
"file.import" if !has(p, &["importAs"]) && is_layered(p) => {
let kinds =
[("Footage", json!("footage")), ("Composition", json!("composition")), ("Composition - Retain Layer Sizes", json!("compositionLayerSizes"))];
let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false);
let sel = if drag { kinds.iter().position(|(_, v)| v.as_str() == Some(s.prefs.drag_import_as())).unwrap_or(0) } else { 1 };
("Import Photoshop File".into(), vec![Field::choice("importAs", "Import Kind", &kinds, sel)])
}
// PDF / Illustrator files: Import Kind and the page.
"file.import" if !has(p, &["importAs", "page"]) && is_pdf(p) => (
"Import PDF / Illustrator File".into(),
@@ -766,17 +765,32 @@ pub fn show_form(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let h = 120.0 + rows;
let mut regs: Vec<(String, egui::Rect, String)> = vec![];
let mut browse: Option<usize> = None;
// Wide enough for a label column and a 240 px popup without a horizontal scroll bar.
super::dialogs::modal(ctx, &f.title.clone(), vec2(480.0, h), t, |ui| {
let mut focused = false;
// Project Settings needs room for its labels and the selected GPU adapter name. At the
// generic form width its grid overflows, pushing the buttons off the visible area (#978).
let width = if f.title == "Project Settings" { 800.0 } else { 480.0 };
super::dialogs::modal(ctx, &f.title.clone(), vec2(width, h), t, |ui| {
egui::Grid::new("form-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
for (i, fl) in f.fields.iter_mut().enumerate() {
ui.label(tr(&fl.label));
let r = match &mut fl.kind {
FieldKind::Number { value, speed } => {
let dec = if *speed < 0.01 { 5 } else { 3 };
ui.add(crate::widgets::drag_value(egui::DragValue::new(value).speed(*speed).max_decimals(dec))).rect
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(value).speed(*speed).max_decimals(dec)));
// The first field takes the keyboard when the form opens. (A number edits
// as text once focused; the selection is clamped to what it shows.)
if !std::mem::replace(&mut focused, true) {
crate::widgets::focus_on_open(ui.ctx(), &r, &" ".repeat(64));
}
r.rect
}
FieldKind::Text(s) => {
let r = ui.add(egui::TextEdit::singleline(s).desired_width(220.0));
if !std::mem::replace(&mut focused, true) {
crate::widgets::focus_on_open(ui.ctx(), &r, s);
}
r.rect
}
FieldKind::Text(s) => ui.add(egui::TextEdit::singleline(s).desired_width(220.0)).rect,
FieldKind::Path { value, .. } => {
ui.horizontal(|ui| {
let r = ui.add(egui::TextEdit::singleline(value).desired_width(150.0)).rect;
@@ -892,7 +906,8 @@ pub(crate) fn close_info(app: &mut EffectcraftApp) {
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| {
// The text wraps within this small dialog; avoid a horizontal scrollbar changing its height.
super::dialogs::modal_vertical(ctx, &title, vec2(440.0, 160.0), t, |ui| {
ui.label(tr(&body));
ui.add_space(16.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
@@ -948,6 +963,37 @@ mod tests {
assert_eq!(f.params(), json!({"prop": "position", "value": [10.0, 20.0], "mode": "b"}));
}
/// A numeric form (Layer ▸ Transform ▸ Position…) opens with its first number being edited
/// and selected: typing replaces it, and one Enter confirms.
#[test]
fn a_numeric_form_opens_with_its_first_number_selected() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
let ctx = egui::Context::default();
crate::theme::install(&ctx, &app.tokens, crate::i18n::language(&app));
app.dialog_state.form = Form {
title: "Position".into(),
command: "layer.setTransform".into(),
base: json!({"prop": "position"}),
fields: vec![Field::num("value[0]", "X", 960.0), Field::num("value[1]", "Y", 540.0)],
};
app.dialog = Some(Dialog::Form);
let frame = |app: &mut EffectcraftApp, events: Vec<egui::Event>| {
let raw = egui::RawInput { events, ..Default::default() };
ctx.run_ui(raw, |ui| {
app.auto.begin_frame();
crate::panels::dialogs::show(app, ui.ctx());
})
.textures_delta
.clear();
};
frame(&mut app, vec![]);
frame(&mut app, vec![]);
frame(&mut app, vec![egui::Event::Text("42".into())]);
assert_eq!(app.dialog_state.form.params()["value"], json!([42.0, 540.0]));
frame(&mut app, vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]);
assert!(app.dialog.is_none(), "one Enter confirms");
}
/// File ▸ Export ▸ Adobe Premiere Pro Project… opens a form that says it writes Final Cut Pro
/// XML; its fields register automation ids and OK runs `file.exportTimeline`.
#[test]
+103 -1
View File
@@ -11,7 +11,9 @@
//! - Reshape: correspondence point list buttons here, and on the Composition viewer the source
//! and destination mask outlines with draggable correspondence handles ([`reshape_overlay`]);
//! - EXtractoR: a Layer popup of the footage's OpenEXR layers, and Red / Green / Blue / Alpha
//! popups of its channels ([`channel_popup`]).
//! popups of its channels ([`channel_popup`]);
//! - Mesh Warp: on the Composition viewer, the distortion mesh's grid over the layer with a
//! draggable handle on every vertex ([`mesh_warp_overlay`], #303).
//!
//! Every edit is a `prop.set` engine command (undoable; one drag = one undo step) and every
//! handle registers an automation id.
@@ -37,6 +39,7 @@ pub const COLORAMA: &str = "ec.color.colorama";
pub const GLOW: &str = "ec.stylize.glow";
pub const RESHAPE: &str = "ec.distort.reshape";
pub const EXTRACTOR: &str = "ec.3d.extractor";
pub const MESH_WARP: &str = "ec.distort.meshwarp";
fn str_value(layer: &Layer, ectx: &EvalCtx, g: &PropGroup, id: &str) -> String {
match g.get(id).map(|p| ectx.value(layer, p)) {
@@ -1018,10 +1021,109 @@ pub fn reshape_overlay(
}
}
/// Mesh Warp's grid: (rows, columns, vertex offsets in layer pixels, row-major). A stored mesh
/// that doesn't match the grid (Rows or Columns changed since) reads as undistorted, as it
/// renders.
fn mesh_grid(layer: &Layer, ectx: &EvalCtx, g: &PropGroup) -> (usize, usize, Vec<(f64, f64)>) {
let n = |id: &str| {
let v = g.get(id).map(|p| ectx.value(layer, p).as_f64()).unwrap_or(7.0);
if v.is_finite() { v.round().clamp(1.0, 31.0) as usize } else { 7 }
};
let (rows, cols) = (n("rows"), n("columns"));
let count = (rows + 1) * (cols + 1);
let mut offs = effectcraft_engine::effects::parse_mesh(&str_value(layer, ectx, g, "mesh"));
if offs.len() != count {
offs = vec![(0.0, 0.0); count];
}
(rows, cols, offs)
}
/// The `mesh` parameter's text for these offsets (the inverse of `parse_mesh`).
fn format_mesh(offs: &[(f64, f64)]) -> String {
let r = |v: f64| if v.is_finite() { (v * 1000.0).round() / 1000.0 + 0.0 } else { 0.0 };
offs.iter().map(|o| format!("{},{}", r(o.0), r(o.1))).collect::<Vec<_>>().join(" ")
}
/// Mesh Warp on the Composition viewer (#303): the distortion mesh's grid over the layer, with
/// a handle on every vertex. Dragging a vertex moves it (its offset in the hidden `mesh`
/// parameter; the first drag of an undistorted mesh writes the whole grid). `fm` maps effect
/// space to comp.
#[allow(clippy::too_many_arguments)]
pub fn mesh_warp_overlay(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
painter: &egui::Painter,
map: &super::viewer::ViewerMap,
ectx: &EvalCtx,
layer: &Layer,
g: &PropGroup,
fm: &Mat3,
actions: &mut Actions,
) {
let (rows, cols, offs) = mesh_grid(layer, ectx, g);
let [lw, lh] = ectx.effect_bounds(layer).0;
let rest = |k: usize| [(k % (cols + 1)) as f64 / cols as f64 * lw, (k / (cols + 1)) as f64 / rows as f64 * lh];
let screen: Vec<Pos2> = offs
.iter()
.enumerate()
.map(|(k, o)| {
let r = rest(k);
map.to_screen(fw::layer_to_comp(fm, [r[0] + o.0, r[1] + o.1]))
})
.collect();
let line = Stroke::new(1.0, Color32::from_white_alpha(150));
for (k, s) in screen.iter().enumerate() {
if k % (cols + 1) < cols
&& let Some(e) = screen.get(k + 1)
{
painter.line_segment([*s, *e], line);
}
if let Some(e) = screen.get(k + cols + 1) {
painter.line_segment([*s, *e], line);
}
}
let ctx = ui.ctx().clone();
let accent = app.tokens.accent;
for (k, s) in screen.iter().enumerate() {
let hr = Rect::from_center_size(*s, vec2(10.0, 10.0));
let id = egui::Id::new(("mesh-warp-vertex", g.uid, k));
let resp = ui.interact(hr, id, Sense::drag());
let hot = resp.hovered() || resp.dragged();
let dot = Rect::from_center_size(*s, vec2(5.0, 5.0));
painter.rect_filled(dot, 0.0, if hot { accent } else { Color32::WHITE });
painter.rect_stroke(dot, 0.0, Stroke::new(1.0, Color32::BLACK), StrokeKind::Outside);
let (row, col) = (k / (cols + 1), k % (cols + 1));
app.auto.add(&format!("viewer.meshWarp.{}.{row}.{col}", g.uid), hr, &format!("Mesh vertex (row {row}, column {col})"));
if hot {
ctx.set_cursor_icon(egui::CursorIcon::Move);
}
if resp.dragged()
&& let Some(pos) = resp.interact_pointer_pos()
&& let Some(lp) = fw::comp_to_layer(fm, map.to_comp(pos))
{
let mut v = offs.clone();
let r = rest(k);
if let Some(o) = v.get_mut(k) {
*o = (lp[0] - r[0], lp[1] - r[1]);
}
let key = gesture_key(ui, id, resp.drag_started());
set_str(actions, layer, g, "mesh", format_mesh(&v), Some(key));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mesh_text_round_trips() {
let offs = vec![(0.0, 0.0), (12.5, -3.25), (1.0 / 3.0, f64::NAN)];
let s = format_mesh(&offs);
assert_eq!(s, "0,0 12.5,-3.25 0.333,0");
assert_eq!(effectcraft_engine::effects::parse_mesh(&s), vec![(0.0, 0.0), (12.5, -3.25), (0.333, 0.0)]);
}
#[test]
fn offset_points_and_palettes_round_trip() {
let p = OffsetPoints::parse("0.5,0.75 0.1,0.5");
@@ -0,0 +1,519 @@
//! The Gradient Editor (#612), opened by a gradient property's "Edit Gradient…" in the Timeline
//! (Gradient Fill / Gradient Stroke ▸ Colors, Gradient Overlay ▸ Gradient): `prop.editGradient`.
//! Opacity stops sit above the preview bar and colour stops below it. Click above or below the
//! bar to add a stop (it takes that track's value there), drag a stop to move it, edit the
//! selected stop's location, opacity or colour, and Delete removes it (never the last stop of a
//! track). The editor works on a draft: OK sets the property once with `prop.set` at the time it
//! opened (one undo step, nothing at all when nothing changed); Cancel and Escape leave it as it
//! was.
//!
//! Automation ids: `dialog.gradient.bar`, `dialog.gradient.addOpacity`, `dialog.gradient.addColor`,
//! `dialog.gradient.opacityStop.<i>`, `dialog.gradient.colorStop.<i>` (in order along the bar),
//! `dialog.gradient.location`, `dialog.gradient.opacity`, `dialog.gradient.color`,
//! `dialog.gradient.delete`, `dialog.gradient.ok`, `dialog.gradient.cancel`.
use effectcraft_engine::keyframe::{Gradient, Value};
use effectcraft_engine::project::{ItemId, LayerId};
use egui::{Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde_json::{Value as Json, json};
use crate::i18n::tr;
use crate::theme::Tokens;
use crate::{Dialog, EffectcraftApp};
/// Which row of stops: opacity (above the bar) or colour (below it).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Track {
Opacity,
Color,
}
/// A stop in the draft. `id` stays with the stop when it moves past another one (the tracks are
/// kept in order along the bar, so its index changes).
#[derive(Clone, Debug, PartialEq)]
pub struct Stop<T> {
pub id: u64,
pub pos: f64,
pub value: T,
}
/// The property being edited, as it was when the editor opened.
#[derive(Clone, Debug, PartialEq)]
pub struct Target {
pub comp: u64,
pub layer: u64,
pub prop: u64,
/// Composition seconds, snapped to the nearest frame: the value is read and set there.
pub time: f64,
}
/// The editor's draft gradient and selection.
#[derive(Clone, Debug, Default)]
pub struct Draft {
pub target: Option<Target>,
pub colors: Vec<Stop<[f32; 4]>>,
pub opacities: Vec<Stop<f32>>,
pub selected: Option<(Track, u64)>,
/// The gradient as it opened, stops in order: OK with an equal draft changes nothing.
pub baseline: Gradient,
/// Stop counts (colour, opacity) of the keyframes just before and after the edit time.
pub neighbors: Vec<(usize, usize)>,
next_id: u64,
}
fn by_pos<T>(v: &mut [Stop<T>]) {
// Stable: stops at the same location keep their order.
v.sort_by(|a, b| a.pos.total_cmp(&b.pos));
}
fn clamp_pos(p: f64) -> f64 {
if p.is_finite() { p.clamp(0.0, 1.0) } else { 0.0 }
}
impl Draft {
/// A draft of `g` (stops put in order, locations clamped to 0..1).
pub fn new(g: &Gradient, target: Option<Target>, neighbors: Vec<(usize, usize)>) -> Draft {
let mut d = Draft { target, neighbors, ..Default::default() };
for &(pos, value) in &g.colors {
let id = d.fresh();
d.colors.push(Stop { id, pos: clamp_pos(pos), value });
}
for &(pos, value) in &g.opacities {
let id = d.fresh();
d.opacities.push(Stop { id, pos: clamp_pos(pos), value });
}
by_pos(&mut d.colors);
by_pos(&mut d.opacities);
d.baseline = d.gradient();
d
}
fn fresh(&mut self) -> u64 {
self.next_id = self.next_id.saturating_add(1);
self.next_id
}
/// The draft as a gradient (the tracks are always in order).
pub fn gradient(&self) -> Gradient {
Gradient { colors: self.colors.iter().map(|s| (s.pos, s.value)).collect(), opacities: self.opacities.iter().map(|s| (s.pos, s.value)).collect() }
}
pub fn len(&self, track: Track) -> usize {
match track {
Track::Color => self.colors.len(),
Track::Opacity => self.opacities.len(),
}
}
/// The id of the stop `i`-th along the bar.
pub fn id_at(&self, track: Track, i: usize) -> Option<u64> {
match track {
Track::Color => self.colors.get(i).map(|s| s.id),
Track::Opacity => self.opacities.get(i).map(|s| s.id),
}
}
/// Where stop `id` is along the bar (its index), if it exists.
pub fn index_of(&self, track: Track, id: u64) -> Option<usize> {
match track {
Track::Color => self.colors.iter().position(|s| s.id == id),
Track::Opacity => self.opacities.iter().position(|s| s.id == id),
}
}
/// Add a stop at `pos` with that track's current value there, select it, return its id.
pub fn add(&mut self, track: Track, pos: f64) -> u64 {
let pos = clamp_pos(pos);
let g = self.gradient();
let id = self.fresh();
match track {
Track::Color => self.colors.push(Stop { id, pos, value: g.color_at(pos) }),
Track::Opacity => self.opacities.push(Stop { id, pos, value: g.opacity_at(pos) }),
}
self.sort();
self.selected = Some((track, id));
id
}
/// Move stop `id` to `pos` (clamped) and keep the track in order.
pub fn move_to(&mut self, track: Track, id: u64, pos: f64) {
let pos = clamp_pos(pos);
match track {
Track::Color => {
if let Some(s) = self.colors.iter_mut().find(|s| s.id == id) {
s.pos = pos;
}
}
Track::Opacity => {
if let Some(s) = self.opacities.iter_mut().find(|s| s.id == id) {
s.pos = pos;
}
}
}
self.sort();
}
/// Remove stop `id` unless it is the last of its track. Returns whether it went.
pub fn remove(&mut self, track: Track, id: u64) -> bool {
if self.len(track) <= 1 {
return false;
}
let before = self.len(track);
match track {
Track::Color => self.colors.retain(|s| s.id != id),
Track::Opacity => self.opacities.retain(|s| s.id != id),
}
if self.selected == Some((track, id)) {
self.selected = None;
}
self.len(track) < before
}
/// Set colour stop `id`'s RGB, keeping its alpha.
pub fn set_rgb(&mut self, id: u64, rgb: [f32; 3]) {
if let Some(s) = self.colors.iter_mut().find(|s| s.id == id) {
s.value = [rgb[0], rgb[1], rgb[2], s.value[3]];
}
}
/// Set opacity stop `id` (0..1).
pub fn set_opacity(&mut self, id: u64, a: f32) {
if let Some(s) = self.opacities.iter_mut().find(|s| s.id == id) {
s.value = if a.is_finite() { a.clamp(0.0, 1.0) } else { s.value };
}
}
fn sort(&mut self) {
by_pos(&mut self.colors);
by_pos(&mut self.opacities);
}
/// The draft's stop counts differ from a neighbouring keyframe's, so the two can't
/// interpolate (gradient keyframes blend only with the same number of stops).
pub fn mismatched(&self) -> bool {
self.neighbors.iter().any(|&(c, o)| c != self.colors.len() || o != self.opacities.len())
}
}
/// `prop.editGradient {layer, prop, comp?}`: open the editor on that gradient property at the
/// current time (snapped to the nearest frame, as `prop.set` snaps it).
pub fn open(app: &mut EffectcraftApp, p: &Json) -> Result<Json, String> {
let cid = match p.get("comp").and_then(Json::as_u64) {
Some(c) => ItemId(c),
None => app.session.active_comp_id().ok_or("no composition is open")?,
};
let comp = app.session.project.comp(cid).ok_or_else(|| format!("no composition {}", cid.0))?;
let lid = p.get("layer").and_then(Json::as_u64).ok_or("missing `layer`")?;
let layer = comp.layer(LayerId(lid)).ok_or_else(|| format!("no layer {lid}"))?;
let uid = p.get("prop").and_then(Json::as_u64).ok_or("missing `prop`")?;
let prop = layer.props.find(uid).ok_or_else(|| format!("no property @{uid}"))?;
let ct = comp.frame_rate.snap_nearest(app.session.time_of(cid));
let lt = layer.layer_time(ct);
let Value::Gradient(g) = prop.value_at(lt) else {
return Err(format!("{} is not a gradient", prop.name));
};
// The keyframes either side of the edit time (one exactly there is the one being edited).
let counts = |v: &Value| match v {
Value::Gradient(g) => Some((g.colors.len(), g.opacities.len())),
_ => None,
};
let before = prop.keys.iter().rev().find(|k| k.time < lt).and_then(|k| counts(&k.value));
let after = prop.keys.iter().find(|k| k.time > lt).and_then(|k| counts(&k.value));
let target = Target { comp: cid.0, layer: lid, prop: uid, time: ct.seconds() };
app.dialog_state.gradient = Draft::new(&g, Some(target), before.into_iter().chain(after).collect());
app.dialog = Some(Dialog::GradientEditor);
Ok(json!({"dialog": "gradientEditor"}))
}
/// Set the property to the draft: one `prop.set` at the time the editor opened, in composition
/// time, or nothing when the draft is unchanged (so OK adds no keyframe).
fn commit(app: &mut EffectcraftApp, ctx: &egui::Context) {
app.dialog = None;
let d = std::mem::take(&mut app.dialog_state.gradient);
let g = d.gradient();
let Some(tg) = d.target else { return };
if g == d.baseline {
return;
}
let params = json!({"comp": tg.comp, "layer": tg.layer, "prop": tg.prop, "time": tg.time, "timeBase": "comp", "value": Value::Gradient(g).to_json()});
if let Err(e) = crate::menus::invoke(app, ctx, "prop.set", params) {
app.ui.status = e;
}
}
fn to_color32(c: [f32; 4]) -> Color32 {
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
Color32::from_rgba_unmultiplied(b(c[0]), b(c[1]), b(c[2]), b(c[3]))
}
pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
if app.dialog_state.gradient.target.is_none() {
app.dialog = None;
return;
}
let mut answer: Option<bool> = None;
super::dialogs::modal(ctx, tr("Gradient Editor"), vec2(520.0, 270.0), t, |ui| {
let w = ui.available_width().max(200.0);
let (area, _) = ui.allocate_exact_size(vec2(w, 72.0), Sense::hover());
let bar = Rect::from_min_max(pos2(area.min.x + 8.0, area.min.y + 22.0), pos2(area.max.x - 8.0, area.min.y + 48.0));
let opacity_row = Rect::from_min_max(pos2(bar.min.x, area.min.y), pos2(bar.max.x, bar.min.y - 2.0));
let color_row = Rect::from_min_max(pos2(bar.min.x, bar.max.y + 2.0), pos2(bar.max.x, area.max.y));
let pos_of = |x: f32| ((x - bar.min.x) / bar.width().max(1.0)) as f64;
let x_of = |p: f64| bar.min.x + bar.width() * p as f32;
let painter = ui.painter().clone();
// The bar: a checkerboard under the gradient, so opacity shows.
let cell = 6.0;
let mut y = bar.min.y;
let mut row = 0;
while y < bar.max.y {
let mut x = bar.min.x;
let mut col = row;
while x < bar.max.x {
let c = if col % 2 == 0 { Color32::from_gray(200) } else { Color32::from_gray(150) };
painter.rect_filled(Rect::from_min_max(pos2(x, y), pos2((x + cell).min(bar.max.x), (y + cell).min(bar.max.y))), 0.0, c);
x += cell;
col += 1;
}
y += cell;
row += 1;
}
let g = app.dialog_state.gradient.gradient();
let n = 96;
for k in 0..n {
let x0 = bar.min.x + bar.width() * k as f32 / n as f32;
let x1 = bar.min.x + bar.width() * (k + 1) as f32 / n as f32;
let c = g.sample((k as f64 + 0.5) / n as f64);
painter.rect_filled(Rect::from_min_max(pos2(x0, bar.min.y), pos2(x1, bar.max.y)), 0.0, to_color32(c));
}
painter.rect_stroke(bar, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
app.auto.add("dialog.gradient.bar", bar, "Gradient");
// Clicking a row's empty space adds a stop there.
for (track, rowr, id) in [(Track::Opacity, opacity_row, "dialog.gradient.addOpacity"), (Track::Color, color_row, "dialog.gradient.addColor")] {
let r = ui.interact(rowr, egui::Id::new(("gradient-add", id)), Sense::click());
app.auto.add(id, rowr, id);
if r.clicked()
&& let Some(p) = r.interact_pointer_pos()
{
app.dialog_state.gradient.add(track, pos_of(p.x));
}
}
// The stops (drawn and hit-tested over the rows, so they take the clicks).
for track in [Track::Opacity, Track::Color] {
for i in 0..app.dialog_state.gradient.len(track) {
let d = &app.dialog_state.gradient;
let Some(id) = d.id_at(track, i) else { continue };
let (pos, fill) = match track {
Track::Color => d.colors.get(i).map(|s| (s.pos, to_color32([s.value[0], s.value[1], s.value[2], 1.0]))),
Track::Opacity => d.opacities.get(i).map(|s| (s.pos, Color32::from_gray((s.value.clamp(0.0, 1.0) * 255.0) as u8))),
}
.unwrap_or((0.0, Color32::WHITE));
let selected = d.selected == Some((track, id));
let x = x_of(pos);
let r = match track {
Track::Opacity => Rect::from_min_max(pos2(x - 5.0, opacity_row.max.y - 15.0), pos2(x + 5.0, opacity_row.max.y)),
Track::Color => Rect::from_min_max(pos2(x - 5.0, color_row.min.y), pos2(x + 5.0, color_row.min.y + 15.0)),
};
painter.rect_filled(r, 1.0, fill);
painter.rect_stroke(
r,
1.0,
Stroke::new(if selected { 2.0 } else { 1.0 }, if selected { t.accent } else { t.field_border }),
StrokeKind::Outside,
);
let resp = ui.interact(r.expand(2.0), egui::Id::new(("gradient-stop", track == Track::Color, id)), Sense::click_and_drag());
let name = match track {
Track::Opacity => format!("dialog.gradient.opacityStop.{i}"),
Track::Color => format!("dialog.gradient.colorStop.{i}"),
};
app.auto.add(&name, r, &name);
if resp.clicked() || resp.drag_started() {
app.dialog_state.gradient.selected = Some((track, id));
}
if resp.dragged()
&& let Some(p) = resp.interact_pointer_pos()
{
app.dialog_state.gradient.move_to(track, id, pos_of(p.x));
}
}
}
ui.add_space(8.0);
// The selected stop's fields.
let selected = app.dialog_state.gradient.selected;
let selected = selected.and_then(|(track, id)| app.dialog_state.gradient.index_of(track, id).map(|i| (track, id, i)));
ui.horizontal(|ui| {
let Some((track, id, i)) = selected else {
ui.label(egui::RichText::new(tr("Click above the bar to add an opacity stop, below it to add a color stop.")).color(t.text_dim));
return;
};
ui.label(tr("Location:"));
let d = &app.dialog_state.gradient;
let pos = match track {
Track::Color => d.colors.get(i).map(|s| s.pos),
Track::Opacity => d.opacities.get(i).map(|s| s.pos),
}
.unwrap_or(0.0);
let mut pct = pos * 100.0;
let r = ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).speed(0.5).max_decimals(1).suffix("%"));
app.auto.add("dialog.gradient.location", r.rect, "Location");
if r.changed() {
app.dialog_state.gradient.move_to(track, id, pct / 100.0);
}
// Moving can reorder the track: find the stop again by its id, so the fields below
// show this stop and not the one now at its old index.
let Some(i) = app.dialog_state.gradient.index_of(track, id) else { return };
match track {
Track::Opacity => {
ui.label(tr("Opacity:"));
let mut a = app.dialog_state.gradient.opacities.get(i).map_or(1.0, |s| s.value) as f64 * 100.0;
let r = ui.add(egui::DragValue::new(&mut a).range(0.0..=100.0).speed(0.5).max_decimals(1).suffix("%"));
app.auto.add("dialog.gradient.opacity", r.rect, "Opacity");
if r.changed() {
app.dialog_state.gradient.set_opacity(id, (a / 100.0) as f32);
}
}
Track::Color => {
ui.label(tr("Color:"));
let c = app.dialog_state.gradient.colors.get(i).map_or([1.0; 4], |s| s.value);
// The shared colour picker (sRGB, hex field, OK / Cancel); the stop keeps its alpha.
let mut rgb = [c[0], c[1], c[2]];
let swatch = crate::widgets::srgb_color_button(ui, &mut rgb);
app.auto.add("dialog.gradient.color", swatch.rect, "Color");
if swatch.changed() {
app.dialog_state.gradient.set_rgb(id, rgb);
}
}
}
let can_delete = app.dialog_state.gradient.len(track) > 1;
let r = ui.add_enabled(can_delete, egui::Button::new(tr("Delete")));
app.auto.add("dialog.gradient.delete", r.rect, "Delete");
if r.clicked() {
app.dialog_state.gradient.remove(track, id);
}
});
if app.dialog_state.gradient.mismatched() {
ui.add_space(4.0);
ui.label(egui::RichText::new(tr("These adjacent keyframes cannot interpolate because their stop counts differ.")).color(t.danger).size(11.0));
}
ui.add_space(14.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let r = ui.button(tr("Cancel"));
app.auto.add("dialog.gradient.cancel", r.rect, "Cancel");
if r.clicked() {
answer = Some(false);
}
let r = ui.button(tr("OK"));
app.auto.add("dialog.gradient.ok", r.rect, "OK");
if r.clicked() {
answer = Some(true);
}
});
});
// Delete / Backspace remove the selected stop, but not while typing in a field.
if answer.is_none()
&& !ctx.egui_wants_keyboard_input()
&& ctx.input(|i| i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace))
&& let Some((track, id)) = app.dialog_state.gradient.selected
{
app.dialog_state.gradient.remove(track, id);
}
match answer {
Some(true) => commit(app, ctx),
Some(false) => {
app.dialog = None;
app.dialog_state.gradient = Draft::default();
}
None => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn draft() -> Draft {
Draft::new(&Gradient { colors: vec![(0.0, [1.0, 0.0, 0.0, 1.0]), (1.0, [0.0, 0.0, 1.0, 1.0])], opacities: vec![(0.0, 1.0), (1.0, 0.5)] }, None, vec![])
}
/// Dragging the first stop past the second keeps the track in order and the same stop
/// selected; a stop added afterwards samples the reordered track.
#[test]
fn stops_stay_in_order_and_selected_while_moving() {
for track in [Track::Color, Track::Opacity] {
let g = Gradient { colors: vec![(0.0, [1.0, 0.0, 0.0, 1.0]), (0.6, [0.0, 0.0, 1.0, 1.0])], opacities: vec![(0.0, 1.0), (0.6, 0.5)] };
let mut d = Draft::new(&g, None, vec![]);
let first = d.id_at(track, 0).unwrap();
d.selected = Some((track, first));
d.move_to(track, first, 0.3);
d.move_to(track, first, 0.8);
assert_eq!(d.index_of(track, first), Some(1), "{track:?}: dragged past the stop at 0.6, it is now second");
assert_eq!(d.selected, Some((track, first)), "{track:?}: the selection followed it");
let g = d.gradient();
let positions: Vec<f64> = match track {
Track::Color => g.colors.iter().map(|c| c.0).collect(),
Track::Opacity => g.opacities.iter().map(|c| c.0).collect(),
};
assert!(positions.windows(2).all(|w| w[0] <= w[1]), "{track:?}: {positions:?}");
let added = d.add(track, 0.5);
assert_eq!(d.index_of(track, added), Some(0), "{track:?}: the new stop sorts before the stops at 0.6 and 0.8");
assert_eq!(d.selected, Some((track, added)));
}
// After the swap the colour track runs blue (at 0) to red (at 1): a stop added at 0.5 is
// their mix in the swapped order, not the original red-to-blue.
let mut d = draft();
let red = d.id_at(Track::Color, 0).unwrap();
let blue = d.id_at(Track::Color, 1).unwrap();
d.move_to(Track::Color, red, 1.0);
d.move_to(Track::Color, blue, 0.0);
let id = d.add(Track::Color, 0.25);
let i = d.index_of(Track::Color, id).unwrap();
let c = d.colors[i].value;
assert!(c[2] > c[0], "blue dominates near 0 after the swap: {c:?}");
}
#[test]
fn last_stop_stays_and_new_stops_keep_their_tracks_values() {
let mut d = draft();
let a = d.id_at(Track::Opacity, 0).unwrap();
let b = d.id_at(Track::Opacity, 1).unwrap();
assert!(d.remove(Track::Opacity, a));
assert!(!d.remove(Track::Opacity, b), "the last opacity stop stays");
let mut d = draft();
let id = d.add(Track::Opacity, 0.5);
let i = d.index_of(Track::Opacity, id).unwrap();
assert!((d.opacities[i].value - 0.75).abs() < 1e-6, "the opacity track's own value");
let id = d.add(Track::Color, 0.5);
let i = d.index_of(Track::Color, id).unwrap();
assert!((d.colors[i].value[3] - 1.0).abs() < 1e-6, "colour stops keep their own alpha, not times opacity");
d.set_rgb(id, [0.0, 1.0, 0.0]);
assert_eq!(d.colors[i].value, [0.0, 1.0, 0.0, 1.0]);
d.set_opacity(d.id_at(Track::Opacity, 0).unwrap(), f32::NAN);
assert!(d.opacities.iter().all(|s| s.value.is_finite()));
d.move_to(Track::Color, id, f64::INFINITY);
assert!(d.colors.iter().all(|s| (0.0..=1.0).contains(&s.pos)));
}
#[test]
fn unchanged_drafts_equal_their_baseline() {
// Out-of-order and out-of-range stops come in sorted and clamped: still "unchanged".
let g = Gradient { colors: vec![(1.2, [0.0, 0.0, 1.0, 1.0]), (0.0, [1.0, 0.0, 0.0, 1.0])], opacities: vec![(0.5, 1.0)] };
let d = Draft::new(&g, None, vec![]);
assert_eq!(d.gradient(), d.baseline);
assert_eq!(d.gradient().colors.iter().map(|c| c.0).collect::<Vec<_>>(), vec![0.0, 1.0]);
let mut e = d.clone();
e.add(Track::Opacity, 0.2);
assert_ne!(e.gradient(), e.baseline);
}
#[test]
fn the_warning_follows_the_neighbours_stop_counts() {
let mut d = Draft::new(&Gradient::default(), None, vec![(2, 2), (2, 2)]);
assert!(!d.mismatched(), "same counts as both neighbours");
d.add(Track::Color, 0.5);
assert!(d.mismatched(), "three colour stops next to keyframes with two");
assert!(!Draft::new(&Gradient::default(), None, vec![]).mismatched(), "not animated: no neighbours");
}
}
@@ -0,0 +1,104 @@
//! A shape layer's Gradient Fill / Gradient Stroke start and end points in the Composition viewer
//! (#612). With the gradient, or a property in it, selected, its Start Point and End Point show as
//! draggable ⊕ controls with a guide between them, as in After Effects. A drag sets the point with
//! `prop.set`: one undo step per drag, and on an animated point a keyframe at the current time.
//!
//! The points are in the space of the shape group holding the gradient, so they follow that
//! group's transform (and the groups around it) as well as the layer's.
//!
//! Automation ids: `viewer.gradientPoint.<uid>` (the Start Point / End Point property's uid).
use effectcraft_engine::geom::Mat3;
use effectcraft_engine::project::{Layer, LayerId, Node, PropGroup, Property};
use effectcraft_engine::render::EvalCtx;
use egui::{Color32, Rect, Sense, Stroke, vec2};
use serde_json::json;
use super::fx_widgets as fw;
use crate::EffectcraftApp;
/// Gradient Fill / Gradient Stroke groups in shape contents `g`, through nested groups.
fn gradient_paints<'a>(g: &'a PropGroup, depth: usize, out: &mut Vec<&'a PropGroup>) {
if depth >= 16 {
return;
}
for child in g.groups().filter(|c| c.enabled) {
match child.match_id.as_str() {
"gfill" | "gstroke" => out.push(child),
"group" | "contents" => gradient_paints(child, depth + 1, out),
_ => {}
}
}
}
/// `g` or something inside it is selected on `layer`.
fn selected_in(g: &PropGroup, layer: LayerId, selected: &[(LayerId, u64)]) -> bool {
fn contains(g: &PropGroup, uid: u64, depth: usize) -> bool {
g.uid == uid || (depth < 16 && g.children.iter().any(|n| n.uid() == uid || matches!(n, Node::Group(c) if contains(c, uid, depth + 1))))
}
selected.iter().any(|(l, uid)| *l == layer && contains(g, *uid, 0))
}
/// Draw and drag the selected gradients' start and end points. `l2c` is the viewer's layer→comp
/// matrix (it knows the 3D view). Called after the viewer's own gestures, so a handle takes the
/// press before the layer would move.
pub fn viewer_hook(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
painter: &egui::Painter,
map: &super::viewer::ViewerMap,
ectx: &EvalCtx,
l2c: &dyn Fn(&EvalCtx, &Layer) -> Mat3,
) {
if !app.ui.viewer.show_layer_controls {
return;
}
let t = app.tokens;
let ctx = ui.ctx().clone();
let selected_props = app.session.state.selected_props.clone();
let selected_layers = app.session.state.selected_layers.clone();
let mut actions: Vec<(String, serde_json::Value)> = vec![];
for layer in ectx.comp.layers.iter().filter(|l| selected_layers.contains(&l.id) && l.is_active_at(ectx.time)) {
let Some(contents) = layer.props.sub("contents") else { continue };
let mut paints = vec![];
gradient_paints(contents, 0, &mut paints);
if paints.is_empty() {
continue;
}
let m = l2c(ectx, layer);
for g in paints.into_iter().filter(|g| selected_in(g, layer.id, &selected_props)) {
// Gradient (group) space → comp: the enclosing groups' transforms, then the layer's.
let pm = m * effectcraft_engine::render::shapes::item_matrix(ectx, layer, g.uid).unwrap_or(Mat3::IDENTITY);
let pts: Vec<&Property> = ["start", "end"].iter().filter_map(|k| g.get(k)).collect();
let screen: Vec<egui::Pos2> = pts.iter().map(|pr| map.to_screen(fw::layer_to_comp(&pm, ectx.value(layer, pr).as_vec2()))).collect();
if let [a, b] = screen[..] {
painter.line_segment([a, b], Stroke::new(1.0, Color32::from_white_alpha(110)));
}
for (pr, s) in pts.iter().zip(screen) {
let hr = Rect::from_center_size(s, vec2(16.0, 16.0));
let id = egui::Id::new(("viewer-gradient-pt", pr.uid));
let resp = ui.interact(hr, id, Sense::drag());
let col = if resp.hovered() || resp.dragged() { t.accent } else { Color32::WHITE };
fw::draw_crosshair(painter, s + vec2(1.0, 1.0), 5.0, Color32::from_black_alpha(160));
fw::draw_crosshair(painter, s, 5.0, col);
app.auto.add(&format!("viewer.gradientPoint.{}", pr.uid), hr, &pr.name);
if resp.hovered() {
ctx.set_cursor_icon(egui::CursorIcon::Move);
resp.clone().on_hover_text(format!("{}: {}", g.name, pr.name));
}
if resp.dragged()
&& let Some(pos) = resp.interact_pointer_pos()
&& let Some(lp) = fw::comp_to_layer(&pm, map.to_comp(pos))
{
let key = super::effect_controls::gesture_key(ui, id, resp.drag_started());
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": pr.uid, "value": [lp[0], lp[1]], "merge": key})));
}
}
}
}
for (id, params) in actions {
if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) {
app.ui.status = e;
}
}
}
+23 -2
View File
@@ -419,7 +419,10 @@ pub(crate) fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painte
&& let Some((press, grabs)) = ctx.data(|dd| dd.get_temp::<HandleDrag>(handle_drag_id()))
{
ctx.data_mut(|dd| dd.insert_temp(drag_id, true));
let (dt, dv) = (tm.t(pt.x) - tm.t(press.x), vmap(pt.y) - vmap(press.y));
// Shift keeps the handle on the time or the value axis, whichever moved more (as for keys).
let (time_ok, value_ok) = shift_axes(ui.input(|i| i.modifiers.shift), pt.x - press.x, pt.y - press.y);
let dt = if time_ok { tm.t(pt.x) - tm.t(press.x) } else { 0.0 };
let dv = if value_ok { vmap(pt.y) - vmap(press.y) } else { 0.0 };
let merge = format!("ghandle-{uid}-{}", k.idx);
for g in &grabs {
actions.push(("keys.setEase".into(), g.ease(g.end.0 + dt, g.end.1 + dv, speed, &merge)));
@@ -470,7 +473,7 @@ pub(crate) fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painte
{
ctx.data_mut(|dd| dd.insert_temp(drag_id, true));
let (dx, dy) = (pt.x - g.press.x, pt.y - g.press.y);
let (time_ok, value_ok) = if mods.shift { (dx.abs() >= dy.abs(), dy.abs() > dx.abs()) } else { (true, true) };
let (time_ok, value_ok) = shift_axes(mods.shift, dx, dy);
// Graph Editor ▸ Snap: to the current time and other keys.
let others: Vec<f64> = all_key_times.iter().filter(|(u, i, _)| !(*u == uid && *i == k.idx)).map(|x| x.2).collect();
let t = if time_ok { super::graph_tools::snap_time(app, tm, (g.t + (tm.t(pt.x) - tm.t(g.press.x))).max(0.0), &others) } else { g.t };
@@ -703,3 +706,21 @@ type HandleDrag = (Pos2, Vec<HandleGrab>);
fn handle_drag_id() -> egui::Id {
egui::Id::new("graph-handle-drag")
}
/// Which axes a drag may move on (time, value): both, or with Shift only the one the pointer moved more along.
fn shift_axes(shift: bool, dx: f32, dy: f32) -> (bool, bool) {
if shift { (dx.abs() >= dy.abs(), dy.abs() > dx.abs()) } else { (true, true) }
}
#[cfg(test)]
mod tests {
use super::shift_axes;
#[test]
fn shift_locks_drag_to_dominant_axis() {
assert_eq!(shift_axes(false, 10.0, 3.0), (true, true));
assert_eq!(shift_axes(true, 10.0, -3.0), (true, false));
assert_eq!(shift_axes(true, 2.0, -9.0), (false, true));
assert_eq!(shift_axes(true, 5.0, 5.0), (true, false));
}
}
+103 -11
View File
@@ -44,6 +44,27 @@ fn tex_id() -> egui::Id {
egui::Id::new("layer-panel-tex")
}
fn fit_id() -> egui::Id {
egui::Id::new("layer-panel-fit")
}
/// The Layer panel's last Fit magnification (points per layer pixel), for View ▸ Zoom In / Zoom
/// Out from Fit.
pub fn last_fit(ctx: &egui::Context) -> f32 {
ctx.data(|d| d.get_temp::<f32>(fit_id())).unwrap_or(0.5)
}
/// Zoom to `nz` (points per layer pixel) keeping layer point `q` under screen point `at`.
fn zoom_at(app: &mut EffectcraftApp, area: Rect, size: [f64; 2], at: Pos2, q: [f64; 2], nz: f32) {
let nz = nz.clamp(0.01, 32.0);
let origin = at - vec2(q[0] as f32 * nz, q[1] as f32 * nz);
let pan = origin + vec2(size[0] as f32 * nz / 2.0, size[1] as f32 * nz / 2.0) - area.center();
if pan.x.is_finite() && pan.y.is_finite() {
app.ui.layer_zoom = Some(nz);
app.ui.layer_pan = [pan.x, pan.y];
}
}
/// The layer shown: the opened one, else the first selected layer.
pub fn current_layer(app: &EffectcraftApp) -> Option<Layer> {
let comp = app.session.active_comp()?;
@@ -83,15 +104,46 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
p.rect_filled(top, 0.0, t.panel_bg);
p.text(pos2(top.min.x + 10.0, top.center().y), Align2::LEFT_CENTER, tr_args("Layer: {}", &[&layer.name]), Tokens::semibold(12.0), t.text);
app.auto.add("layerPanel.title", top, &layer.name);
// Bottom bar: View menu.
// Canvas geometry: Fit, or the panel's own magnification and pan.
let bar = Rect::from_min_max(pos2(rect.min.x, rect.max.y - 30.0), rect.max);
let canvas_bottom = if roto.is_some() { bar.min.y - 18.0 } else { bar.min.y };
let area = Rect::from_min_max(pos2(rect.min.x, top.max.y), pos2(rect.max.x, canvas_bottom));
// The layer's effect bounds, in effect space (where paint and Roto Brush strokes are).
let [lw, lh] = effectcraft_engine::render::effect_bounds(&app.session.project, &comp, &layer).0;
let fit = ((area.width() - 40.0) as f64 / lw).min((area.height() - 40.0) as f64 / lh).max(0.01) as f32;
ctx.data_mut(|d| d.insert_temp(fit_id(), fit));
let zoom = app.ui.layer_zoom.filter(|z| z.is_finite() && *z > 0.0).unwrap_or(fit) as f64;
let pan = match app.ui.layer_pan {
[x, y] if x.is_finite() && y.is_finite() && app.ui.layer_zoom.is_some() => vec2(x, y),
_ => vec2(0.0, 0.0),
};
let origin = area.center() + pan - vec2((lw * zoom / 2.0) as f32, (lh * zoom / 2.0) as f32);
// Bottom bar: magnification and View menus.
p.rect_filled(bar, 0.0, t.panel_bg);
p.text(pos2(bar.min.x + 10.0, bar.center().y), Align2::LEFT_CENTER, tr("View:"), Tokens::ui(12.0), t.text_dim);
let mr = Rect::from_min_size(pos2(bar.min.x + 8.0, bar.center().y - 10.0), vec2(80.0, 20.0));
if let Some((z, up)) = super::viewer_tools::magnification_menu(
app,
ui,
mr,
"layer-mag",
"layerPanel.magnification",
"layerMagnification",
zoom as f32,
app.ui.layer_zoom,
false,
) {
// The Layer panel keeps no fit mode: Fit up to 100% is the fit, at most 100 %.
app.ui.layer_zoom = if up { Some(fit.min(1.0 / ui.ctx().pixels_per_point())) } else { z };
app.ui.layer_pan = [0.0, 0.0];
}
let vx = mr.max.x + 10.0;
p.text(pos2(vx, bar.center().y), Align2::LEFT_CENTER, tr("View:"), Tokens::ui(12.0), t.text_dim);
let mut names = vec!["Masks".to_string()];
if let Some(fx) = layer.effects() {
names.extend(fx.groups().map(|g| g.name.clone()));
}
let vr = Rect::from_min_size(pos2(bar.min.x + 46.0, bar.center().y - 10.0), vec2(150.0, 20.0));
let vr = Rect::from_min_size(pos2(vx + 36.0, bar.center().y - 10.0), vec2(150.0, 20.0));
let pop = egui::Id::new("layer-view-pop");
if widgets::dropdown(ui, vr, &names[view.min(names.len() - 1)], &t, egui::Id::new("layer-view")).clicked() {
widgets::open_popup(ui, pop);
@@ -103,21 +155,14 @@ 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));
let sb = Rect::from_min_max(pos2(rect.min.x, canvas_bottom), 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, canvas_bottom));
p.rect_filled(area, 0.0, t.pasteboard);
// The layer's effect bounds, in effect space (where paint and Roto Brush strokes are).
let [lw, lh] = effectcraft_engine::render::effect_bounds(&app.session.project, &comp, &layer).0;
let zoom = ((area.width() - 40.0) as f64 / lw).min((area.height() - 40.0) as f64 / lh).max(0.01);
let origin = area.center() - vec2((lw * zoom / 2.0) as f32, (lh * zoom / 2.0) as f32);
let to_screen = |q: [f64; 2]| pos2(origin.x + (q[0] * zoom) as f32, origin.y + (q[1] * zoom) as f32);
let to_layer = |s: Pos2| [((s.x - origin.x) as f64) / zoom, ((s.y - origin.y) as f64) / zoom];
let frame = Rect::from_min_max(to_screen([0.0, 0.0]), to_screen([lw, lh]));
@@ -166,6 +211,53 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.auto.add("layerPanel.canvas", frame, &layer.name);
app.auto.add("layerPanel.area", area, "Layer panel");
// Navigation (as the Composition panel): the wheel / pinch zooms around the pointer with any
// tool; the Hand tool or Space-drag pans and the Zoom tool clicks zoom in (Alt: out).
let hovered = ui.rect_contains_pointer(area);
if let Some(hp) = ui.input(|i| i.pointer.hover_pos()).filter(|_| hovered) {
let scroll = ui.input(|i| i.smooth_scroll_delta.y + i.zoom_delta().ln() * 300.0);
if scroll.is_finite() && scroll.abs() > 0.1 {
zoom_at(app, area, [lw, lh], hp, to_layer(hp), zoom as f32 * (scroll / 300.0).exp());
}
}
// A middle-drag pans with any tool; painting and Roto Brush strokes don't run meanwhile.
if hovered && ui.input(|i| i.pointer.middle_down()) {
// Movement from before the press (in its frame) is not part of the drag.
let d = ui.input(|i| if i.pointer.button_pressed(egui::PointerButton::Middle) { egui::Vec2::ZERO } else { i.pointer.delta() });
if d != egui::Vec2::ZERO && d.x.is_finite() && d.y.is_finite() {
app.ui.layer_zoom.get_or_insert(zoom as f32);
app.ui.layer_pan = [pan.x + d.x, pan.y + d.y];
}
ctx.set_cursor_icon(egui::CursorIcon::Grabbing);
return;
}
let space = super::space_hand(&ctx);
if space || matches!(app.ui.tool, Tool::Hand | Tool::Zoom) {
let resp = ui.interact(area, egui::Id::new("layer-panel-nav"), Sense::click_and_drag());
let alt = ui.input(|i| i.modifiers.alt);
if resp.hovered() {
ctx.set_cursor_icon(match app.ui.tool {
Tool::Zoom if !space && alt => egui::CursorIcon::ZoomOut,
Tool::Zoom if !space => egui::CursorIcon::ZoomIn,
_ if resp.dragged() => egui::CursorIcon::Grabbing,
_ => egui::CursorIcon::Grab,
});
}
if resp.dragged_by(egui::PointerButton::Primary) && (space || app.ui.tool == Tool::Hand) {
let d = resp.drag_delta();
app.ui.layer_zoom.get_or_insert(zoom as f32);
app.ui.layer_pan = [pan.x + d.x, pan.y + d.y];
}
if resp.clicked()
&& !space
&& app.ui.tool == Tool::Zoom
&& let Some(pos) = resp.interact_pointer_pos()
{
zoom_at(app, area, [lw, lh], pos, to_layer(pos), zoom as f32 * if alt { 0.5 } else { 2.0 });
}
app.auto.add("layerPanel.nav", area, "Layer panel navigation");
return;
}
// 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);
+34 -2
View File
@@ -124,6 +124,8 @@ fn text_field(ui: &mut egui::Ui, app: &mut EffectcraftApp, id: &str, v: &mut Str
pub fn dialog(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut d = app.dialog_state.marker.clone();
let (mut ok, mut cancel, mut delete) = (false, false, false);
// Cmd+Backspace (Ctrl elsewhere) is Delete, in a text field too.
let delete_key = super::dialogs::ui_command_key(ctx, egui::Key::Backspace);
let title = d.title.clone();
super::dialogs::modal(ctx, &title, vec2(520.0, 560.0), t, |ui| {
egui::Grid::new("marker-grid").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
@@ -137,6 +139,7 @@ pub fn dialog(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
ui.end_row();
ui.label(tr("Comment:"));
let r = ui.add(egui::TextEdit::multiline(&mut d.comment).desired_rows(3).desired_width(320.0));
crate::widgets::focus_on_open(ui.ctx(), &r, &d.comment);
app.auto.add("dialog.marker.comment", r.rect, "Comment");
ui.end_row();
ui.label(tr("Chapter:"));
@@ -217,7 +220,9 @@ pub fn dialog(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
});
});
app.dialog_state.marker = d.clone();
if ok {
delete |= delete_key && !ok && !cancel;
// Enter is OK, unless a text field has it.
if ok || (!cancel && !delete && super::dialogs::ui_enter(ctx)) {
if let Err(e) = app.session.execute("markers.set", draft_params(&d)) {
app.ui.status = e.to_string();
}
@@ -337,7 +342,7 @@ fn marker(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, comp:
ctx.data_mut(|d| d.remove::<(Option<u64>, usize, bool)>(drag_state_id()));
app.session.history.merge_key = None;
}
resp.context_menu(|ui| {
crate::widgets::context_menu(&resp, |ui| {
let run = |ui: &mut egui::Ui, label: &str, cmd: &str, params: Value, app: &mut EffectcraftApp| {
if ui.button(label).clicked() {
if cmd == "dialog" {
@@ -496,5 +501,32 @@ mod tests {
assert_eq!(m["label"], "Blue");
app.session.undo();
assert_eq!(app.session.execute("markers.list", json!({})).unwrap()[0]["chapter"], "");
// Enter is OK and Cmd+Backspace is Delete.
let ctx = egui::Context::default();
crate::theme::install(&ctx, &app.tokens, crate::i18n::language(&app));
// The dialog opens with Comment focused (#922), a multi-line field where Enter types a
// new line; with the focus elsewhere, Enter is OK.
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
app.auto.begin_frame();
crate::panels::dialogs::show(&mut app, ui.ctx());
});
out.textures_delta.clear();
ctx.memory_mut(|m| m.stop_text_input());
app.dialog_state.marker.chapter = "Entered".into();
crate::panels::dialogs::press_key(&mut app, &ctx, egui::Key::Enter, egui::Modifiers::NONE);
assert!(app.dialog.is_none());
assert_eq!(app.session.execute("markers.list", json!({})).unwrap()[0]["chapter"], "Entered");
open_dialog(&mut app, MarkerRef { layer: None, index: 0 }).unwrap();
// Also from a focused text field: Tab to one, then press the key.
for _ in 0..40 {
if ctx.egui_wants_keyboard_input() {
break;
}
crate::panels::dialogs::press_key(&mut app, &ctx, egui::Key::Tab, egui::Modifiers::NONE);
}
assert!(ctx.egui_wants_keyboard_input(), "a text field has focus");
crate::panels::dialogs::press_key(&mut app, &ctx, egui::Key::Backspace, egui::Modifiers::COMMAND);
assert!(app.dialog.is_none());
assert_eq!(app.session.execute("markers.list", json!({})).unwrap().as_array().map(Vec::len), Some(0), "deleted");
}
}
+1 -1
View File
@@ -208,7 +208,7 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if resp.drag_started() && !e.is_dir && e.kind.is_some() {
egui::DragAndDrop::set_payload(&ctx, DragPayload::Files(vec![e.path.clone()]));
}
resp.context_menu(|ui| {
crate::widgets::context_menu(&resp, |ui| {
if !e.is_dir && ui.button(tr("Import")).clicked() {
actions.push(("mediaBrowser.import", json!({"paths": [e.path]})));
ui.close();
+14
View File
@@ -17,6 +17,8 @@ pub mod footage_panel;
pub mod forms;
pub mod fx_editors;
pub mod fx_widgets;
pub mod gradient_editor;
pub mod gradient_handles;
pub mod graph;
pub mod graph_tools;
pub mod home;
@@ -174,6 +176,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
pub fn panel_menu_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
let id = egui::Id::new("panel-menu");
let Some((panel, pos)) = ui.ctx().data(|d| d.get_temp::<(PanelKind, egui::Pos2)>(id)) else { return };
// The menu opens in the window that shows the panel (a panel can have its own window).
if app.panel_viewport(ui.ctx(), panel) != ui.ctx().viewport_id() {
return;
}
let mut close = false;
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
@@ -188,6 +194,14 @@ pub fn panel_menu_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
let _ = app.dock_command(ui.ctx(), craft_ui::docking::Action::Float { panel, rect: r });
close = true;
}
// Multiple monitors: a native window of its own, which can go on another screen.
if !ui.ctx().embed_viewports() {
let windowed = app.in_panel_window(panel);
if ui.button(if windowed { tr("Move Panel to Main Window") } else { tr("Move Panel to New Window") }).clicked() {
let _ = crate::menus::invoke(app, &ui.ctx().clone(), "window.panelWindow", serde_json::json!({"panel": panel, "window": !windowed}));
close = true;
}
}
if !floating && ui.button(if app.ui.maximized == Some(panel) { tr("Restore Panel Size") } else { tr("Maximize Panel") }).clicked() {
app.toggle_maximize(panel);
close = true;
+1
View File
@@ -115,6 +115,7 @@ pub fn dialog(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
ui.horizontal(|ui| {
ui.label(tr("New composition name:"));
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(260.0));
crate::widgets::focus_on_open(ui.ctx(), &r, &d.name);
app.auto.add("dialog.precompose.name", r.rect, "New composition name");
});
ui.add_space(10.0);
+225 -20
View File
@@ -3,8 +3,9 @@
//! Media Duration, Frame Rate, File Path, Comment — shown or hidden from the header's context
//! menu), folders (drag items into and out of them), renaming (Enter, or double-click the name),
//! the label colour picker, and the bottom bar (interpret, new folder, new comp: click, or drop
//! items on it for a comp from them, bit depth, delete). Edits are engine commands, so they are
//! undoable.
//! items on it for a comp from them, bit depth, delete), and the keyboard (the arrow keys select,
//! extend the selection and open / close folders; rows and buttons carry AccessKit names and
//! states for screen readers). Edits are engine commands, so they are undoable.
use std::sync::{Arc, Mutex};
@@ -191,6 +192,130 @@ pub fn begin_rename(app: &EffectcraftApp, ctx: &egui::Context) {
}
}
/// Where a Shift-extended selection starts (the last item clicked or moved to without Shift).
fn anchor_id() -> egui::Id {
egui::Id::new("project-selection-anchor")
}
/// The item the arrow keys move from: the last item clicked or moved to.
fn cursor_id() -> egui::Id {
egui::Id::new("project-selection-cursor")
}
/// An item row's widget: its click / drag area, keyboard focus and accessibility node.
fn row_id(item: ItemId) -> egui::Id {
egui::Id::new(("pitem", item.0))
}
/// The last row drawn with keyboard focus (egui drops the focus of a row scrolled out of view).
fn focused_row_id() -> egui::Id {
egui::Id::new("project-focused-row")
}
/// The focused widget is one of the panel's rows, or nothing has keyboard focus: the panel's keys
/// apply. Any other focused widget (a text field, a button reached with Tab) keeps them.
fn keys_reach_rows(app: &EffectcraftApp, ctx: &egui::Context) -> bool {
match ctx.memory(|m| m.focused()) {
None => app.ui.focused == crate::dock::PanelKind::Project,
Some(f) => ctx.data(|d| d.get_temp::<ItemId>(focused_row_id())).is_some_and(|row| row_id(row) == f),
}
}
/// The Project panel's arrow keys, as in After Effects: Up / Down Arrow select the previous /
/// next item (the first or last when nothing is selected), Shift+Up / Down extend the selection
/// from its anchor, Right Arrow opens the selected folder and Left Arrow closes it (on an item
/// inside a folder, Left selects the folder). They apply while the panel has focus and nothing
/// else takes them: a dialog, an open menu, an inline rename. A row focused with Tab keeps them
/// too, and keyboard focus then follows the selection, so a screen reader reads the new item.
/// Returns the item the selection moved to.
fn keyboard_nav(app: &mut EffectcraftApp, ctx: &egui::Context) -> Option<ItemId> {
use egui::Key;
let keys: Vec<(Key, egui::Modifiers)> = ctx.input(|i| {
i.events
.iter()
.filter_map(|e| match e {
egui::Event::Key { key: k @ (Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight), pressed: true, modifiers, .. } => {
Some((*k, *modifiers))
}
_ => None,
})
.collect()
});
if keys.is_empty()
|| app.dialog.is_some()
|| widgets::any_menu_open(ctx)
|| ctx.data(|d| d.get_temp::<Editing>(edit_id())).is_some()
|| !keys_reach_rows(app, ctx)
{
return None;
}
let row_focused = ctx.memory(|m| m.focused()).is_some();
let mut moved = None;
for (key, m) in keys {
let (plain, shift) = (!m.any(), m.shift_only());
// Folders opened or closed by an earlier key in this frame change the rows.
let rows = visible_rows(app);
let pos = |id: ItemId| rows.iter().position(|(r, _)| *r == id);
let sel = &app.session.state.project_selection;
let cursor = ctx.data(|d| d.get_temp::<ItemId>(cursor_id())).filter(|c| sel.contains(c)).or_else(|| sel.last().copied());
let cur = cursor.and_then(pos);
let to = match key {
Key::ArrowUp | Key::ArrowDown if plain || shift => {
let Some(last) = rows.len().checked_sub(1) else { continue };
let next = match (cur, key == Key::ArrowDown) {
(Some(c), true) => c.saturating_add(1).min(last),
(Some(c), false) => c.saturating_sub(1),
(None, true) => 0,
(None, false) => last,
};
let Some((to, _)) = rows.get(next).copied() else { continue };
if shift {
let anchor = ctx.data(|d| d.get_temp::<ItemId>(anchor_id())).and_then(pos).or(cur).unwrap_or(next);
app.session.state.project_selection = rows.get(anchor.min(next)..=anchor.max(next)).unwrap_or_default().iter().map(|(i, _)| *i).collect();
to
} else {
app.session.state.project_selection = vec![to];
ctx.data_mut(|d| d.insert_temp(anchor_id(), to));
to
}
}
Key::ArrowRight | Key::ArrowLeft if plain => {
let Some((id, folder, parent)) = cursor.and_then(|c| app.session.project.item(c)).map(|it| (it.id, it.is_folder(), it.parent)) else {
continue;
};
let open = app.ui.project_open_folders.contains(&id.0);
if key == Key::ArrowRight {
if folder {
app.ui.project_open_folders.insert(id.0);
}
continue;
}
if folder && open {
app.ui.project_open_folders.remove(&id.0);
continue;
}
let Some(parent) = parent.filter(|p| pos(*p).is_some()) else { continue };
app.session.state.project_selection = vec![parent];
ctx.data_mut(|d| d.insert_temp(anchor_id(), parent));
parent
}
_ => continue,
};
ctx.data_mut(|d| d.insert_temp(cursor_id(), to));
moved = Some(to);
}
// The arrows are the list's, not egui's spatial focus moves.
if row_focused {
ctx.memory_mut(|m| {
m.move_focus(egui::FocusDirection::None);
if let Some(to) = moved {
m.request_focus(row_id(to));
}
});
}
moved
}
pub(crate) fn visible_rows(app: &EffectcraftApp) -> Vec<(ItemId, usize)> {
fn walk(app: &EffectcraftApp, folder: Option<ItemId>, depth: usize, q: &str, out: &mut Vec<(ItemId, usize)>) {
let mut kids = app.session.project.children(folder);
@@ -307,6 +432,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
));
}
app.auto.add(&format!("project.sort.{key}"), hr, if label.is_empty() { "Label" } else { label });
let column = crate::i18n::tr(if label.is_empty() { "Label" } else { label });
let order = (app.ui.project_sort == *key).then(|| crate::i18n::tr(if app.ui.project_sort_desc { "descending" } else { "ascending" }));
resp.widget_info(|| {
let name = match order {
Some(o) => crate::i18n::tr_args("Sort by {}, {}", &[&column, &o]),
None => crate::i18n::tr_args("Sort by {}", &[&column]),
};
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name)
});
if resp.clicked() {
if app.ui.project_sort == *key {
app.ui.project_sort_desc = !app.ui.project_sort_desc;
@@ -317,7 +451,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
column_menu(app, &resp);
}
let hresp = ui.interact(Rect::from_min_max(pos2(x, hdr.min.y), hdr.max), egui::Id::new("proj-hdr-rest"), Sense::click());
let hresp = ui.interact(Rect::from_min_max(pos2(x, hdr.min.y), hdr.max), egui::Id::new("proj-hdr-rest"), Sense::CLICK);
column_menu(app, &hresp);
app.auto.add("project.columns", hdr, "Columns (right-click to show or hide)");
// Rows.
@@ -327,7 +461,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
// The list's empty area (under the rows and the scroll bar, which take their own clicks):
// a click deselects, a drag draws a selection box, a double-click imports, as in After
// Effects (File ▸ Import ▸ File...).
let empty = ui.interact(list, egui::Id::new("proj-empty"), Sense::click_and_drag());
// Not a Tab stop: the keyboard reaches the rows, and nothing else here takes a key.
let empty = ui.interact(list, egui::Id::new("proj-empty"), Sense::CLICK | Sense::DRAG);
app.auto.add("project.empty", list, "Double-click to import files; drag to select items; right-click for project actions");
if overflow > 0.0 && ui.rect_contains_pointer(list) {
let (dx, dy, shift) = ui.input(|i| (i.smooth_scroll_delta.x, i.smooth_scroll_delta.y, i.modifiers.shift));
@@ -340,11 +475,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
};
app.ui.project_hscroll = (app.ui.project_hscroll - d).clamp(0.0, overflow);
}
let moved = keyboard_nav(app, &ctx);
let rows = visible_rows(app);
// Enter renames the selected item (Project panel focused, not typing).
if app.ui.focused == crate::dock::PanelKind::Project
&& app.dialog.is_none()
&& !ctx.egui_wants_keyboard_input()
&& keys_reach_rows(app, &ctx)
&& ctx.data(|d| d.get_temp::<Editing>(edit_id())).is_none()
&& ctx.input(|i| i.key_pressed(egui::Key::Enter))
{
@@ -382,6 +518,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
// The arrow keys' item scrolls into view (Shift+Up extends upward, past the selection's end).
if let Some(row) = moved.and_then(|m| rows.iter().position(|(id, _)| *id == m)) {
let top = row as f32 * ROW_H;
// Not `clamp`: a panel shorter than a row would make its bounds cross. The row's top wins.
app.ui.project_scroll = app.ui.project_scroll.max(top + ROW_H - list.height()).min(top);
}
app.ui.project_scroll = app.ui.project_scroll.clamp(0.0, max_scroll);
let scroll = app.ui.project_scroll;
let first = ((scroll / ROW_H).floor() as usize).min(rows.len());
@@ -406,14 +548,37 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
);
// The row's click / drag area goes first, so the twirl, proxy, label and comment widgets
// on top of it take their own clicks.
let mut resp = ui.interact(r.intersect(list), egui::Id::new(("pitem", id.0)), Sense::click_and_drag());
let mut resp = ui.interact(r.intersect(list), row_id(*id), Sense::click_and_drag());
app.auto.add(&format!("project.item.{}", id.0), r, &it.name);
// For screen readers: a tree item named by the item and its type, with its selection,
// depth and (a folder) open state. One Tab stop per row; the panel's keys then apply.
let open = it.is_folder().then(|| app.ui.project_open_folders.contains(&id.0) || !app.ui.project_search.is_empty());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, format!("{}, {}", it.name, crate::i18n::tr(it.type_name()))));
ctx.accesskit_node_builder(resp.id, |n| {
n.set_role(egui::accesskit::Role::TreeItem);
n.set_selected(selected);
n.set_level(depth.saturating_add(1));
if let Some(open) = open {
n.set_expanded(open);
}
});
if resp.has_focus() {
ctx.data_mut(|d| d.insert_temp(focused_row_id(), *id));
}
if resp.gained_focus() {
app.ui.focused = crate::dock::PanelKind::Project;
}
let _ = i;
let x0 = r.min.x + 8.0 + 14.0 * *depth as f32;
if it.is_folder() {
let open = app.ui.project_open_folders.contains(&id.0);
let tw = Rect::from_center_size(pos2(x0 + 4.0, r.center().y), vec2(12.0, 12.0));
if widgets::twirl(ui, tw, open, egui::Id::new(("pf", id.0)), &t).clicked() {
let tresp = widgets::twirl(ui, tw, open, egui::Id::new(("pf", id.0)), &t);
tresp.widget_info(|| {
let name = crate::i18n::tr_args(if open { "Close folder {}" } else { "Open folder {}" }, &[&it.name]);
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name)
});
if tresp.clicked() {
if open {
app.ui.project_open_folders.remove(&id.0);
} else {
@@ -437,19 +602,44 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if px.enabled { "in use" } else { "off" }
));
app.auto.add(&format!("project.item.{}.proxy", id.0), pr, if px.enabled { "Proxy in use" } else { "Proxy off" });
presp.widget_info(|| {
let name = crate::i18n::tr_args(if px.enabled { "Proxy of {}: in use" } else { "Proxy of {}: off" }, &[&it.name]);
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name)
});
if presp.clicked() {
actions.push(("file.useProxy".into(), json!({"item": id.0})));
}
}
let name_clip = Rect::from_min_max(pos2(x0 + 30.0, r.min.y), pos2(r.min.x + name_w + 4.0, r.max.y)).intersect(list);
// Footage that can't be decoded (no decoder for its codec / profile): a warning marker
// at the end of the name cell, the reason on hover.
let problem = match &it.kind {
ItemKind::Footage(f) => app.session.footage.problem(f),
_ => None,
};
let name_clip =
Rect::from_min_max(pos2(x0 + 30.0, r.min.y), pos2(r.min.x + name_w + 4.0 - if problem.is_some() { 16.0 } else { 0.0 }, r.max.y)).intersect(list);
if let Some(why) = &problem {
let m = Rect::from_center_size(pos2(r.min.x + name_w - 8.0, r.center().y), vec2(13.0, 12.0));
lp.add(egui::Shape::convex_polygon(vec![m.center_top(), m.right_bottom(), m.left_bottom()], t.warning, Stroke::NONE));
lp.text(m.center() + vec2(0.0, 1.5), Align2::CENTER_CENTER, "!", Tokens::semibold(9.0), Color32::BLACK);
ui.interact(m.expand(2.0).intersect(list), egui::Id::new(("pproblem", id.0)), Sense::hover()).on_hover_text(why.as_str());
app.auto.add(&format!("project.item.{}.problem", id.0), m, why);
}
let name_rect = Rect::from_min_max(pos2(x0 + 28.0, r.min.y + 2.0), pos2(r.min.x + name_w + 2.0, r.max.y - 2.0));
// Inline edits (rename / comment).
let cell_edit = |app: &mut EffectcraftApp, ui: &mut egui::Ui, actions: &mut Vec<(String, serde_json::Value)>, field: &str, cell: Rect| -> bool {
let Some((eid, ef, mut buf)) = editing.clone().filter(|(e, f, _)| *e == id.0 && f == field) else { return false };
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(cell));
let resp = child.add(egui::TextEdit::singleline(&mut buf).desired_width(cell.width()).font(Tokens::ui(12.0)));
// The field keeps Tab (egui would move the keyboard to the next widget, where Enter no
// longer renames, #881): Tab commits like Enter and gives the keyboard back to the panel.
let filter = egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, ..Default::default() };
let resp = child.add(egui::TextEdit::singleline(&mut buf).desired_width(cell.width()).font(Tokens::ui(12.0)).event_filter(filter));
app.auto.add(&format!("project.item.{}.{field}Edit", id.0), cell, field);
if resp.lost_focus() {
let tab = resp.has_focus() && ctx.input(|i| i.key_pressed(egui::Key::Tab));
if tab {
resp.surrender_focus();
}
if resp.lost_focus() || tab {
ctx.data_mut(|d| d.remove::<Editing>(edit_id()));
if !ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
let (cmd, params) = if ef == "name" {
@@ -485,6 +675,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
lp.rect_filled(sw, 2.0, t.label(it.label));
let sresp = ui.interact(sw.expand(3.0).intersect(list), egui::Id::new(("plabel", id.0)), Sense::click());
app.auto.add(&format!("project.item.{}.label", id.0), sw, it.label.name());
sresp.widget_info(|| {
let name = crate::i18n::tr_args("Label of {}: {}", &[&it.name, &app.session.prefs.label_name(it.label)]);
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name)
});
let pop = egui::Id::new(("plabel-pop", id.0));
if sresp.clicked() || sresp.secondary_clicked() {
widgets::open_popup(ui, pop);
@@ -510,8 +704,11 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if cell_edit(app, ui, &mut actions, "comment", cr) {
continue;
}
let cresp = ui.interact(cell, egui::Id::new(("pcomment", id.0)), Sense::click());
let cresp = ui.interact(cell, egui::Id::new(("pcomment", id.0)), Sense::CLICK);
app.auto.add(&format!("project.item.{}.comment", id.0), cell, &it.comment);
cresp.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Other, true, crate::i18n::tr_args("Comment of {}: {}", &[&it.name, &it.comment]))
});
if cresp.double_clicked() {
ctx.data_mut(|d| d.insert_temp::<Editing>(edit_id(), (id.0, "comment".into(), it.comment.clone())));
} else {
@@ -529,12 +726,18 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if dragging.is_some_and(|d| d != id.0) && drop_row == Some(*id) && it.is_folder() {
lp.rect_stroke(r.shrink(1.0), 2.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);
}
let nresp = ui.interact(name_clip, egui::Id::new(("pname", id.0)), Sense::click_and_drag());
// The row with keyboard focus (Tab, or the arrow keys after it) shows a focus ring.
if ctx.memory(|m| m.has_focus(row_id(*id))) {
lp.rect_stroke(r.shrink(0.5), 0.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside);
}
// Part of the row: not a second Tab stop.
let nresp = ui.interact(name_clip, egui::Id::new(("pname", id.0)), Sense::CLICK | Sense::DRAG);
app.auto.add(&format!("project.item.{}.name", id.0), name_clip, &it.name);
let resp = resp.union(nresp);
if resp.clicked() {
let m = ui.input(|i| i.modifiers);
let anchor_key = egui::Id::new("project-selection-anchor");
let anchor_key = anchor_id();
ctx.data_mut(|d| d.insert_temp(cursor_id(), *id));
let anchor = ctx.data(|d| d.get_temp::<ItemId>(anchor_key)).or_else(|| app.session.state.project_selection.first().copied());
if m.shift
&& let Some(a) = anchor.and_then(|a| rows.iter().position(|(i, _)| *i == a))
@@ -578,7 +781,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.session.state.project_selection = vec![*id];
}
let footage = matches!(it.kind, ItemKind::Footage(_));
resp.context_menu(|ui| {
crate::widgets::context_menu(&resp, |ui| {
if ui.button(crate::i18n::tr("Delete")).clicked() {
actions.push(("project.delete".into(), json!({"items": targets(app, *id, selected)})));
ui.close();
@@ -592,7 +795,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
ui.close();
}
if it.parent.is_some() && ui.button(crate::i18n::tr("Move to Project Root")).clicked() {
actions.push(("project.move".into(), json!({"items": [id.0], "folder": null})));
actions.push(("project.move".into(), json!({"items": targets(app, *id, selected), "folder": null})));
ui.close();
}
if !it.is_folder() && ui.button(crate::i18n::tr("Add to Composition")).clicked() {
@@ -692,6 +895,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let r = Rect::from_min_size(pos2(x, foot.min.y + 3.0), vec2(22.0, 22.0));
let resp = widgets::icon_button(ui, r, icon, false, &t, egui::Id::new(("pfoot", id))).on_hover_text(tip);
app.auto.add(&format!("project.{id}"), r, tip);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, crate::i18n::tr(tip)));
if resp.clicked() {
let footage =
app.session.state.project_selection.first().and_then(|i| app.session.project.item(*i)).is_some_and(|i| matches!(i.kind, ItemKind::Footage(_)));
@@ -724,6 +928,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let dresp = ui.interact(dr, egui::Id::new("bpc"), Sense::click());
p.text(dr.center(), Align2::CENTER_CENTER, depth, Tokens::ui(11.5), if dresp.hovered() { t.text } else { t.text_dim });
app.auto.add("project.bitDepth", dr, depth);
dresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, crate::i18n::tr_args("Project color depth: {}", &[&depth])));
// Click cycles 8/16/32 bpc; Alt-click opens Project Settings (as in After Effects).
if dresp.clicked() {
if ui.input(|i| i.modifiers.alt) {
@@ -734,16 +939,16 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
dresp.on_hover_text(crate::i18n::tr("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(crate::i18n::tr("Delete selected project items")).clicked()
&& !app.session.state.project_selection.is_empty()
{
let trash = widgets::icon_button(ui, tr, Icon::Trash, false, &t, egui::Id::new("ptrash")).on_hover_text(crate::i18n::tr("Delete selected project items"));
trash.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, crate::i18n::tr("Delete selected project items")));
if trash.clicked() && !app.session.state.project_selection.is_empty() {
actions.push(("project.delete".into(), json!({})));
}
app.auto.add("project.delete", tr, "Delete");
if empty.double_clicked() {
actions.push(("file.import".into(), json!({})));
}
empty.context_menu(|ui| {
crate::widgets::context_menu(&empty, |ui| {
for (key, label, command) in
[("newComp", "New Composition…", "comp.new"), ("newFolder", "New Folder", "project.newFolder"), ("import", "Import File…", "file.import")]
{
@@ -809,7 +1014,7 @@ fn label_index(l: Label) -> usize {
/// The column header's context menu: show or hide the optional columns.
fn column_menu(app: &mut EffectcraftApp, resp: &egui::Response) {
resp.context_menu(|ui| {
crate::widgets::context_menu(resp, |ui| {
ui.label(egui::RichText::new(crate::i18n::tr("Columns")).weak());
for (key, label, _) in COLUMNS {
let mut on = app.ui.project_columns.iter().any(|c| c == key);
+2 -2
View File
@@ -245,7 +245,7 @@ fn output_menu(it: &RenderQueueItem, available: &[OutputFormat], templates: &Ren
}
v.push((mark(o.audio_channels == 1, "Audio Channels: Mono"), json!({"audioChannels": "mono"})));
v.push((mark(o.audio_channels != 1, "Audio Channels: Stereo"), json!({"audioChannels": "stereo"})));
if matches!(o.format, OutputFormat::ProRes | OutputFormat::Wav | OutputFormat::Aiff) {
if matches!(o.format, OutputFormat::ProRes | OutputFormat::Uncompressed | OutputFormat::Wav | OutputFormat::Aiff) {
for f in [AudioFormat::S16, AudioFormat::S24, AudioFormat::F32] {
v.push((mark(o.audio_format == f, &tr_args("Sample Format: {}", &[&(f.label())])), json!({"audioFormat": f.label()})));
}
@@ -559,7 +559,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.ui.focused = crate::dock::PanelKind::RenderQueue;
}
let item_id = it.id;
row_resp.context_menu(|ui| {
crate::widgets::context_menu(&row_resp, |ui| {
if ui.button(tr("Duplicate")).clicked() {
actions.push(("renderQueue.duplicate", json!({"item": item_id})));
ui.close();
+144 -2
View File
@@ -4,7 +4,9 @@
//! `scriptui.close` commands, which run the script's handlers. Every control registers an
//! automation id `scriptui.<window>.<control>` (and `scriptui.<window>.<name>` when the script
//! named it). Controls with an `onDraw` handler are painted from their draw list; edit texts and
//! sliders send live `changing` updates (onChanging) while typing / dragging.
//! sliders send live `changing` updates (onChanging) while typing / dragging. Mouse events
//! (`mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `click`) on a control go to the
//! script through `scriptui.mouse` when a listener wants them (`Widget::mouse`).
use crate::i18n::tr;
use effectcraft_engine::Services;
@@ -22,6 +24,8 @@ enum Act {
/// A live update (each keystroke / slider step): fires onChanging.
Changing(u32, u32, Value),
Close(u32),
/// A mouse event (`scriptui.mouse` parameters without window and widget).
Mouse(u32, u32, Value),
}
fn rect_of(origin: egui::Pos2, b: [f64; 4]) -> Rect {
@@ -335,6 +339,132 @@ fn paint_image(ui: &egui::Ui, r: Rect, img: &ImageRef, services: &dyn Services)
true
}
/// Where the pointer was and what it did over one script window (for mouseover / mouseout and
/// click counts).
#[derive(Clone, Default)]
struct MouseTrack {
hover: Option<u32>,
at: Option<egui::Pos2>,
/// The last press: control, time, position (a quick second press there counts as a double
/// click).
last_down: Option<(u32, f64, egui::Pos2)>,
clicks: u32,
/// The control and button pressed (a release on the same control is a click).
down: Option<(u32, u8)>,
}
/// The deepest visible control of `w` at `p` (`w` itself when no child is there): later
/// siblings are on top; a tabbed panel shows its active tab only.
fn hit_test(w: &Widget, origin: egui::Pos2, p: egui::Pos2, depth: usize) -> Option<&Widget> {
if !w.visible || !rect_of(origin, w.bounds).contains(p) {
return None;
}
// Widget trees come from scripts: the depth is bounded.
if depth < 64 {
if w.kind == WidgetKind::TabbedPanel {
if let Some(hit) = w.children.get(w.active_tab).and_then(|t| hit_test(t, origin, p, depth + 1)) {
return Some(hit);
}
} else if let Some(hit) = w.children.iter().rev().find_map(|c| hit_test(c, origin, p, depth + 1)) {
return Some(hit);
}
}
Some(w)
}
fn wants_mouse(w: &Widget, depth: usize) -> bool {
!w.mouse.is_empty() || (depth < 64 && w.children.iter().any(|c| wants_mouse(c, depth + 1)))
}
/// Mouse events over a script window's controls (drawn at `origin`, visible in `area`) for the
/// script's listeners: mouseover / mouseout when the control under the pointer changes,
/// mousemove, mousedown / mouseup, and click (a press and release of the left button on the
/// same control; it replaces the plain click the control reported, so a checkbox toggles once).
/// Only events a listener wants are sent; none while `active` is false (a modal dialog is up).
fn mouse_events(ui: &egui::Ui, origin: egui::Pos2, area: Rect, win: u32, root: &Widget, active: bool, acts: &mut Vec<Act>) {
let id = egui::Id::new(("sui-mouse", win));
if !wants_mouse(root, 0) {
ui.data_mut(|d| d.remove::<MouseTrack>(id));
return;
}
let mut st: MouseTrack = ui.data(|d| d.get_temp(id)).unwrap_or_default();
let (latest, events, mods, time) = ui.input(|i| (i.pointer.latest_pos(), i.events.clone(), i.modifiers, i.time));
let ctx = ui.ctx();
let layer = ui.layer_id();
let target = |p: egui::Pos2| -> Option<&Widget> {
if !active || !area.contains(p) || ctx.layer_id_at(p).is_some_and(|l| l != layer) {
return None;
}
hit_test(root, origin, p, 0)
};
let send = |w: &Widget, ty: &str, p: egui::Pos2, button: u8, detail: u32, acts: &mut Vec<Act>| {
if !w.enabled || !w.mouse.iter().any(|m| m == ty) {
return;
}
let at = rect_of(origin, w.bounds).min;
acts.push(Act::Mouse(
win,
w.id,
json!({
"type": ty, "x": p.x - at.x, "y": p.y - at.y, "screenX": p.x, "screenY": p.y,
"button": button, "detail": detail,
"altKey": mods.alt, "ctrlKey": mods.ctrl, "shiftKey": mods.shift, "metaKey": mods.mac_cmd,
}),
));
};
// The pointer moved: out of the old control, over the new one, along it.
let now = latest.and_then(|p| target(p).map(|w| (w, p)));
let now_id = now.map(|(w, _)| w.id);
if now_id != st.hover {
if let Some(old) = st.hover.and_then(|h| root.find(h)) {
send(old, "mouseout", latest.unwrap_or(origin), 0, 0, acts);
}
if let Some((w, p)) = now {
send(w, "mouseover", p, 0, 0, acts);
}
st.hover = now_id;
}
if let Some((w, p)) = now
&& st.at != Some(p)
{
send(w, "mousemove", p, 0, 0, acts);
}
st.at = latest;
// Presses and releases.
for e in &events {
let egui::Event::PointerButton { pos, button, pressed, .. } = e else { continue };
let b = match button {
egui::PointerButton::Primary => 0,
egui::PointerButton::Middle => 1,
egui::PointerButton::Secondary => 2,
_ => continue,
};
let Some(w) = target(*pos) else {
if !pressed {
st.down = None;
}
continue;
};
if *pressed {
let again = st.last_down.is_some_and(|(c, t, at)| c == w.id && time - t < 0.5 && at.distance(*pos) < 6.0);
st.clicks = if again { st.clicks.saturating_add(1) } else { 1 };
st.last_down = Some((w.id, time, *pos));
st.down = Some((w.id, b));
send(w, "mousedown", *pos, b, st.clicks, acts);
} else {
send(w, "mouseup", *pos, b, st.clicks, acts);
if st.down == Some((w.id, b)) && b == 0 && w.enabled && w.mouse.iter().any(|m| m == "click") {
// The click with the pointer's details, after mousedown / mouseup, in place of
// the plain click the control reported.
acts.retain(|a| !matches!(a, Act::Click(aw, ac) if *aw == win && *ac == w.id));
send(w, "click", *pos, b, st.clicks, acts);
}
st.down = None;
}
}
ui.data_mut(|d| d.insert_temp(id, st));
}
/// Checkboxes and radio buttons sit at the left of their (possibly filled) bounds.
fn snug(r: Rect, text: &str) -> Rect {
let w = (text.chars().count() as f32 * 7.0 + 26.0).min(r.width());
@@ -348,6 +478,13 @@ fn perform(app: &mut EffectcraftApp, ctx: &egui::Context, acts: Vec<Act>) {
Act::Set(w, id, v) => ("scriptui.set", json!({"window": w, "widget": id, "value": v})),
Act::Changing(w, id, v) => ("scriptui.set", json!({"window": w, "widget": id, "value": v, "changing": true})),
Act::Close(w) => ("scriptui.close", json!({"window": w})),
Act::Mouse(w, id, mut v) => {
if let Some(o) = v.as_object_mut() {
o.insert("window".into(), json!(w));
o.insert("widget".into(), json!(id));
}
("scriptui.mouse", v)
}
};
match crate::menus::invoke(app, ctx, cmd, p) {
Ok(r) => {
@@ -372,7 +509,8 @@ pub fn show_windows(app: &mut EffectcraftApp, ctx: &egui::Context) {
let t = app.tokens;
let mut acts = vec![];
let screen = ctx.content_rect();
if windows.iter().any(|w| w.modal) {
let blocked = windows.iter().any(|w| w.modal);
if blocked {
// A modal dialog blocks the app behind it, as in After Effects.
let r = egui::Area::new(egui::Id::new("scriptui-modal-block")).order(egui::Order::Middle).fixed_pos(screen.min).show(ctx, |ui| {
ui.allocate_exact_size(screen.size(), Sense::click_and_drag());
@@ -395,6 +533,7 @@ pub fn show_windows(app: &mut EffectcraftApp, ctx: &egui::Context) {
.show(ctx, |ui| {
let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
draw_children(app, ui, rect.min, w.id, &w.root, &mut acts);
mouse_events(ui, rect.min, rect, w.id, &w.root, w.modal || !blocked, &mut acts);
rect
});
if let Some(r) = resp {
@@ -418,11 +557,14 @@ pub fn panel(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, id: u32) {
let (pw, ph) = (rect.width() as f64, rect.height() as f64);
w.root.fixed_bounds = Some([0.0, 0.0, pw.max(w.root.bounds[2]), ph.max(w.root.bounds[3])]);
layout(&mut w);
// A modal script dialog blocks the panels too.
let modal = app.session.script_ui.windows.iter().any(|w| w.modal);
let mut acts = vec![];
let content = rect;
egui::ScrollArea::both().id_salt(("scriptui-panel", id)).max_width(content.width()).max_height(content.height()).show(ui, |ui| {
let (r, _) = ui.allocate_exact_size(vec2(w.root.bounds[2] as f32, w.root.bounds[3] as f32), Sense::hover());
draw_children(app, ui, r.min, id, &w.root, &mut acts);
mouse_events(ui, r.min, r.intersect(ui.clip_rect()), id, &w.root, !modal, &mut acts);
});
app.auto.add(&format!("scriptui.{id}"), rect, &w.title);
let ctx = ui.ctx().clone();
+77 -36
View File
@@ -10,7 +10,7 @@
use crate::i18n::{tr, tr_args};
use effectcraft_engine::prefs::{APPEARANCE_MODES, DARK_THEMES, Item, Kind, LIGHT_THEMES, Page, pages};
use effectcraft_engine::segment::Task;
use egui::{Color32, RichText, vec2};
use egui::{Color32, Rect, RichText, vec2};
use serde_json::{Value, json};
use crate::theme::{ThemeKind, Tokens};
@@ -118,7 +118,10 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value
let r = match kind {
Kind::Int(lo, hi, unit) => {
let mut x = v.as_i64().unwrap_or(0);
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut x).range(lo..=hi).speed(0.25)));
// A typed number applies once entered: typing 85 into UI Scale
// doesn't resize the interface to 75 % at its first digit.
let drag = egui::DragValue::new(&mut x).range(lo..=hi).speed(0.25).update_while_editing(false);
let r = ui.add(crate::widgets::drag_value(drag));
if !unit.is_empty() {
ui.label(RichText::new(unit).color(t.text_dim));
}
@@ -152,7 +155,6 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value
r
}
Kind::Choice(opts) => {
// (A number with choices, UI Scale, shows as its text.)
let curv = v.as_str().map_or_else(|| v.to_string(), str::to_string);
let shown = opts.iter().find(|o| o.1 == curv).map(|o| o.0).unwrap_or(curv.as_str()).to_string();
egui::ComboBox::from_id_salt(("settings", key))
@@ -331,11 +333,39 @@ fn theme_card(
theme_preview(ui, kind, ui.available_width());
ui.add_space(4.0);
for (label, value) in options {
let r = ui.radio(cur == *value, tr(label));
reg(app, &format!("settings.{key}.{value}"), &r, label);
if r.clicked() && cur != *value {
acts.push(Act::Set(key.into(), json!(value)));
}
let row = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), 24.0));
let hovered = ui.ctx().pointer_hover_pos().is_some_and(|p| row.contains(p));
ui.horizontal(|ui| {
let r = ui.radio(cur == *value, tr(label));
reg(app, &format!("settings.{key}.{value}"), &r, label);
if r.clicked() && cur != *value {
acts.push(Act::Set(key.into(), json!(value)));
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut favorites = app.session.prefs.appearance.favorite_themes.clone();
let favorite = favorites.iter().any(|id| id == value);
let tip = tr(if favorite { "Remove from favorites" } else { "Add to favorites" });
let r = ui.add_visible(favorite || hovered, egui::Button::new("").min_size(vec2(24.0, 24.0)).frame(false)).on_hover_text(tip);
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("{}: {}", tip, tr(label))));
reg(app, &format!("settings.appearance.favoriteThemes.{value}"), &r, tip);
if favorite || hovered {
crate::icons::paint(
ui.painter(),
r.rect.shrink(4.0),
if favorite { crate::icons::Icon::StarFilled } else { crate::icons::Icon::Star },
if favorite { t.accent } else { t.text_dim },
);
}
if r.clicked() {
if favorite {
favorites.retain(|id| id != value);
} else {
favorites.push((*value).into());
}
acts.push(Act::Set("appearance.favoriteThemes".into(), json!(favorites)));
}
});
});
}
});
}
@@ -602,10 +632,40 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let cur = serde_json::to_value(&app.session.prefs).unwrap_or_default();
let mut acts: Vec<Act> = vec![];
let (mut ok, mut cancel) = (false, false);
super::dialogs::modal(ctx, "Settings", vec2(820.0, 600.0), t, |ui| {
let body_h = (ctx.content_rect().height() - 170.0).clamp(120.0, 470.0);
ui.allocate_ui_with_layout(vec2(ui.available_width(), body_h), egui::Layout::left_to_right(egui::Align::Min), |ui| {
ui.set_height(body_h);
super::dialogs::modal_fit(ctx, "Settings", vec2(820.0, 600.0), t, |ui, height| {
// The buttons go first, from the bottom up, and the pages get the height they leave: at
// a high UI Scale the pages scroll and the buttons stay in view.
let area = ui.allocate_space(vec2(ui.available_width(), height)).1;
let mut foot = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::bottom_up(egui::Align::Min)));
foot.horizontal(|ui| {
let r = ui.add_enabled(idx > 0, egui::Button::new(tr("Previous")));
app.auto.add("settings.previous", r.rect, "Previous");
if r.clicked() {
page = all[idx - 1].id.to_string();
}
let r = ui.add_enabled(idx + 1 < all.len(), egui::Button::new(tr("Next")));
app.auto.add("settings.next", r.rect, "Next");
if r.clicked() {
page = all[idx + 1].id.to_string();
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let r = ui.add(egui::Button::new(RichText::new(tr(" OK ")).color(Color32::WHITE)).fill(t.accent));
app.auto.add("settings.ok", r.rect, "OK");
ok |= r.clicked();
let r = ui.button(tr("Cancel"));
app.auto.add("settings.cancel", r.rect, "Cancel");
cancel |= r.clicked();
});
});
foot.separator();
foot.add_space(8.0);
let body_h = (foot.min_rect().top() - area.top()).max(0.0);
// (A child, clipped to its share, so a wide page can't widen the dialog under the buttons.)
let pages = Rect::from_min_size(area.min, vec2(area.width(), body_h));
let mut body = ui.new_child(egui::UiBuilder::new().max_rect(pages).layout(egui::Layout::left_to_right(egui::Align::Min)));
body.set_clip_rect(pages.intersect(body.clip_rect()));
{
let ui = &mut body;
// Page list (left, like After Effects).
ui.vertical(|ui| {
ui.set_width(180.0);
@@ -640,33 +700,11 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let p = &all[idx];
ui.label(RichText::new(tr(p.title)).font(Tokens::semibold(14.0)).color(t.tab_text_active));
ui.add_space(6.0);
egui::ScrollArea::vertical().max_height(body_h - 30.0).auto_shrink([false, false]).show(ui, |ui| {
egui::ScrollArea::vertical().max_height((body_h - 30.0).max(0.0)).auto_shrink([false, false]).show(ui, |ui| {
page_ui(app, ui, p, &cur, t, &mut acts);
});
});
});
ui.add_space(8.0);
ui.separator();
ui.horizontal(|ui| {
let r = ui.add_enabled(idx > 0, egui::Button::new(tr("Previous")));
app.auto.add("settings.previous", r.rect, "Previous");
if r.clicked() {
page = all[idx - 1].id.to_string();
}
let r = ui.add_enabled(idx + 1 < all.len(), egui::Button::new(tr("Next")));
app.auto.add("settings.next", r.rect, "Next");
if r.clicked() {
page = all[idx + 1].id.to_string();
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let r = ui.add(egui::Button::new(RichText::new(tr(" OK ")).color(Color32::WHITE)).fill(t.accent));
app.auto.add("settings.ok", r.rect, "OK");
ok |= r.clicked();
let r = ui.button(tr("Cancel"));
app.auto.add("settings.cancel", r.rect, "Cancel");
cancel |= r.clicked();
});
});
}
});
app.dialog_state.settings_page = page;
for a in acts {
@@ -778,6 +816,9 @@ pub fn recovery(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
}
});
});
if choice.is_none() && super::dialogs::ui_enter(ctx) {
choice = Some("autosave");
}
let Some(c) = choice else { return };
app.dialog = None;
app.recovery = None;
@@ -420,6 +420,7 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
// ---- search + command list + editor
ui.horizontal(|ui| {
let r = ui.add(egui::TextEdit::singleline(&mut st.query).hint_text(tr("Search commands or shortcuts")).desired_width(360.0));
crate::widgets::focus_on_open(ui.ctx(), &r, &st.query);
app.auto.add("shortcuts.search", r.rect, "Search");
});
ui.add_space(4.0);
+42 -5
View File
@@ -8,6 +8,7 @@ use effectcraft_engine::render::EvalCtx;
use egui::{Align2, Rect, Sense, pos2, vec2};
use serde_json::json;
use crate::state::TextColorPick;
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
@@ -201,7 +202,21 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if crate::widgets::color_popup(ui, pop, fs.left_bottom(), &mut rgb) {
actions.push(json!({key: [rgb[0], rgb[1], rgb[2]], "merge": format!("char-{key}")}));
}
p.text(pos2(fs.max.x + 6.0, y + 10.0), Align2::LEFT_CENTER, label, Tokens::ui(11.5), t.text_dim);
let er = Rect::from_min_size(pos2(fs.max.x + 4.0, y + 1.0), vec2(18.0, 18.0));
let active = app.ui.text_color_pick.as_ref().is_some_and(|pick| pick.layer == target.as_ref().map_or(0, |tt| tt.layer) && pick.field == key);
let eye = super::fx_widgets::eyedropper_button(ui, er, active, egui::Id::new(("char-eye", key)), &t);
app.auto.add(&format!("character.{key}.eyedropper"), er, &format!("{label} eyedropper"));
if eye.clicked() {
if active {
app.ui.text_color_pick = None;
app.ui.status.clear();
} else if let Some(tt) = &target {
app.ui.fx_pick = None;
app.ui.text_color_pick = Some(TextColorPick { layer: tt.layer, field: key.into(), range: tt.range });
app.ui.status = crate::i18n::tr_args("Click in the Composition panel to sample text {}", &[&label]);
}
}
p.text(pos2(er.max.x + 6.0, y + 10.0), Align2::LEFT_CENTER, label, Tokens::ui(11.5), t.text_dim);
}
y += 32.0;
// Style toggles: Faux Bold, Faux Italic, All Caps, Small Caps, Superscript, Subscript.
@@ -579,6 +594,10 @@ pub(super) fn font_picker(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: egui:
});
let preview = app.session.prefs.type_.font_preview;
let t = app.tokens;
// The Variable Fonts filter (After Effects 26.3) stays as set while the app runs, like the
// menu's other settings; the search query resets on every open.
let variable_id = id.with("variable-only");
let mut only_variable = ui.data(|d| d.get_temp::<bool>(variable_id)).unwrap_or(false);
// The font field itself becomes editable. The popup contains only results.
let arrow = Rect::from_min_max(pos2(rect.max.x - 22.0, rect.min.y), rect.max);
let edit_rect = Rect::from_min_max(rect.min, pos2(arrow.min.x, rect.max.y));
@@ -608,12 +627,28 @@ pub(super) fn font_picker(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: egui:
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).pivot(pivot).fixed_pos(anchor).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_width(rect.width().max(180.0));
// Filter row: a checkbox that keeps only the variable fonts.
let filter_h = 22.0;
let row = ui.add_sized([ui.available_width(), filter_h], egui::Button::selectable(false, ""));
let box_rect = Rect::from_min_size(row.rect.min, vec2(18.0, filter_h));
let label_rect = Rect::from_min_max(pos2(box_rect.max.x + 2.0, row.rect.min.y), row.rect.max);
let boxed = widgets::checkbox(ui, box_rect, only_variable, &t, id.with("variable-check"));
ui.painter().text(label_rect.left_center(), Align2::LEFT_CENTER, tr("Variable fonts only"), Tokens::ui(11.5), t.text);
app.auto.add(&format!("{auto}.variable"), row.rect, "Variable fonts only");
let toggled = row.clicked() || boxed.clicked();
if toggled {
only_variable = !only_variable;
ui.data_mut(|d| d.insert_temp(variable_id, only_variable));
// Typing goes on into the search field.
ui.memory_mut(|m| m.request_focus(search_id));
}
let query = state.query.trim().to_lowercase();
let mut seen = std::collections::HashSet::new();
let filtered: Vec<_> = rows
.iter()
.filter(|r| {
!r.family.is_empty()
&& (!only_variable || r.variable)
&& (query.is_empty()
|| ((r.family.to_lowercase().contains(&query) || r.display.to_lowercase().contains(&query)) && seen.insert(&r.family)))
})
@@ -621,7 +656,7 @@ pub(super) fn font_picker(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: egui:
if fresh {
state.selected = filtered.iter().position(|r| r.family == current).unwrap_or(0);
}
if search.changed() {
if search.changed() || toggled {
state.selected = 0;
}
let last = filtered.len().saturating_sub(1);
@@ -637,10 +672,12 @@ pub(super) fn font_picker(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: egui:
}
// Give the result list its actual height even when the previous query had
// only one row. A cached tiny Area must not collapse a reopened long list.
let height = (filtered.len() as f32 * (24.0 + ui.spacing().item_spacing.y) + 16.0).clamp(28.0, max_height);
ui.set_height(height);
let filter_room = filter_h + ui.spacing().item_spacing.y;
let height = (filtered.len() as f32 * (24.0 + ui.spacing().item_spacing.y) + 16.0).clamp(28.0, (max_height - filter_room).max(28.0));
// A minimum, from below the filter row (a maximum would move the cursor back up).
ui.set_min_height(height);
let mut scroll = egui::ScrollArea::vertical().id_salt(id.with("results")).max_height(height).min_scrolled_height(height);
if search.changed() {
if search.changed() || toggled {
scroll = scroll.vertical_scroll_offset(0.0);
}
scroll.show(ui, |ui| {
+242 -51
View File
@@ -488,6 +488,21 @@ impl TMap {
}
}
/// A Timeline ruler tick label for comp frame `fno`: seconds:frames (`00:15f`, AE) or, when
/// the project's Time Display Style is Frames, the frame number the current-time display shows
/// (`00015`, counted from Start Numbering Frames At) (#710).
fn ruler_label(fno: i64, fps_i: i64, settings: &effectcraft_engine::project::ProjectSettings) -> String {
if settings.time_display == effectcraft_engine::project::TimeDisplayStyle::Frames {
return format!("{:05}", fno.saturating_add(settings.frame_start));
}
let fps_i = fps_i.max(1);
if fno >= 60 * fps_i * 60 {
format!("{}:{:02}:{:02}f", fno / (fps_i * 60), (fno / fps_i) % 60, fno % fps_i)
} else {
format!("{:02}:{:02}f", fno / fps_i, fno % fps_i)
}
}
fn tl_map_id() -> egui::Id {
egui::Id::new("timeline-map")
}
@@ -563,6 +578,18 @@ pub fn begin_rename(app: &mut EffectcraftApp, ctx: &egui::Context) {
}
}
/// What double-clicking a layer's name or bar does, as in After Effects: a precomp opens, footage
/// and solids open in the Layer panel (paint happens there), text is edited in the viewer with the
/// whole text selected. `None`: the name renames, the bar does nothing.
fn double_click_action(layer: &Layer) -> Option<(String, serde_json::Value)> {
match &layer.source {
LayerSource::Comp { item } => Some(("comp.open".into(), json!({"comp": item.0}))),
LayerSource::Footage { .. } | LayerSource::Solid { .. } => Some(("layer.openLayer".into(), json!({"layer": layer.id.0}))),
LayerSource::Text => Some(("text.edit".into(), json!({"layer": layer.id.0}))),
_ => None,
}
}
/// Open the rename field on layer `id`; it takes the keyboard focus on its first frame only.
fn start_rename(ctx: &egui::Context, id: u64, name: &str) {
ctx.data_mut(|d| {
@@ -1154,9 +1181,16 @@ fn layer_switch(
id: egui::Id,
layer: u64,
name: &'static str,
others: bool,
actions: &mut Vec<(String, serde_json::Value)>,
) {
let resp = widgets::icon_toggle(ui, br, icon, on, t, id, Sense::click_and_drag());
// Alt-click on an A/V feature sets the layer apart: the other layers go off (or locked),
// and come back on the next Alt-click.
if others && resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed() && i.modifiers.alt) {
actions.push(("layer.setSwitch".into(), json!({"layers": [layer], "switch": name, "others": true})));
return;
}
if let Some((value, merge)) = switch_gesture(ui, &resp, row, name, on) {
actions.push(("layer.setSwitch".into(), json!({"layers": [layer], "switch": name, "value": value, "merge": merge})));
} else if resp.clicked() && !resp.clicked_by(egui::PointerButton::Primary) {
@@ -1404,7 +1438,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let bresp = ui.interact(bar, egui::Id::new("wa-bar"), Sense::click_and_drag());
app.auto.add("timeline.workArea.bar", bar, "Work area");
// Right-click: the work area's commands (After Effects).
bresp.context_menu(|ui| {
crate::widgets::context_menu(&bresp, |ui| {
let mut chosen = None;
for id in ["comp.trimToWorkArea", "edit.liftWorkArea", "edit.extractWorkArea"] {
crate::menus::entry_for(app, ui, id, &mut chosen);
@@ -1513,11 +1547,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let x = tm.x(s);
pr.line_segment([pos2(x, ruler.max.y - 10.0), pos2(x, ruler.max.y)], Stroke::new(1.0, t.tl_ruler_tick));
let fno = (s / fd).round() as i64;
let label = if fno >= 60 * fps_i * 60 {
format!("{}:{:02}:{:02}f", fno / (fps_i * 60), (fno / fps_i) % 60, fno % fps_i)
} else {
format!("{:02}:{:02}f", fno / fps_i, fno % fps_i)
};
let label = ruler_label(fno, fps_i, &app.session.project.settings);
pr.text(pos2(x + 3.0, ruler.max.y - 16.0), Align2::LEFT_CENTER, label, Tokens::ui(10.0), t.tl_ruler_text);
for k in 1..5 {
let xx = tm.x(s + secs_per_label * k as f64 / 5.0);
@@ -1651,7 +1681,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let under = hresp.interact_pointer_pos().and_then(|pt| column_at(&cw, pt.x));
ctx.data_mut(|d| d.insert_temp(egui::Id::new("tl-colhdr-under"), under.unwrap_or("")));
}
hresp.context_menu(|ui| {
crate::widgets::context_menu(&hresp, |ui| {
let under: &str = ctx.data(|d| d.get_temp(egui::Id::new("tl-colhdr-under"))).unwrap_or("");
if !under.is_empty() && under != "name" && ui.button(crate::i18n::tr("Hide This")).clicked() {
actions.push(("timeline.column".into(), json!({"column": under, "visible": false})));
@@ -1776,7 +1806,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
continue;
}
lp.rect_filled(br.shrink(0.5), 1.0, t.switch_well);
layer_switch(ui, &t, r, br, icon, on, egui::Id::new(("av", layer.id.0, i)), layer.id.0, name, &mut actions);
layer_switch(ui, &t, r, br, icon, on, egui::Id::new(("av", layer.id.0, i)), layer.id.0, name, true, &mut actions);
app.auto.add(&format!("timeline.layer.{}.{name}", layer.id.0), br, name);
}
// Label swatch.
@@ -1870,20 +1900,16 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
if row_resp.double_clicked() {
match &layer.source {
LayerSource::Comp { item } => actions.push(("comp.open".into(), json!({"comp": item.0}))),
// Footage and solids open in the Layer panel (paint happens there).
LayerSource::Footage { .. } | LayerSource::Solid { .. } => {
actions.push(("layer.openLayer".into(), json!({"layer": layer.id.0})));
}
_ => start_rename(&ctx, layer.id.0, &layer.name),
match double_click_action(layer) {
Some(a) => actions.push(a),
None => start_rename(&ctx, layer.id.0, &layer.name),
}
}
layer_context_menu(&row_resp, layer, &mut actions);
layer_context_menu(&row_resp, &comp, layer, &selected, vector_footage_layer(&app.session.project, layer), &mut actions);
// Switches.
let sws: [(Icon, bool, &str, bool); 8] = [
(Icon::Shy, sw.shy, "shy", true),
(Icon::Collapse, sw.collapse, "collapse", matches!(layer.source, LayerSource::Comp { .. } | LayerSource::Shape | LayerSource::Text)),
(Icon::Collapse, sw.collapse, "collapse", collapse_applies(layer, &app.session.project)),
(Icon::Quality, sw.quality == effectcraft_engine::project::Quality::Best, "quality", layer.source.is_av()),
(Icon::Fx, sw.effects, "fx", layer.effects().is_some_and(|f| !f.children.is_empty())),
(
@@ -1902,7 +1928,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
let br = Rect::from_center_size(pos2(cw.switches + SW * i as f32 + SW / 2.0, cy), vec2(16.0, 16.0));
lp.rect_filled(br.shrink(1.0), 1.0, t.switch_well);
layer_switch(ui, &t, r, br, icon, on, egui::Id::new(("sw", layer.id.0, i)), layer.id.0, name, &mut actions);
layer_switch(ui, &t, r, br, icon, on, egui::Id::new(("sw", layer.id.0, i)), layer.id.0, name, false, &mut actions);
app.auto.add(&format!("timeline.layer.{}.switch.{name}", layer.id.0), br, name);
}
// Modes.
@@ -1931,7 +1957,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
Some(m) => comp.layer(m.layer).map(|l| format!("{} {}", idx_of(l.id), l.name)).unwrap_or("None".into()),
None => "No Track Matte".into(),
};
let tresp = widgets::dropdown(ui, mr, &label, &t, egui::Id::new(("trkmat", layer.id.0)));
// The cell is too narrow for the mode as well: it is in the tooltip and ticked in the menu.
let tip = layer.track_matte.map(|m| format!("{label} · {}", crate::i18n::tr(m.kind.label())));
let tresp = widgets::dropdown_tip(ui, mr, &label, tip.as_deref(), &t, egui::Id::new(("trkmat", layer.id.0)));
app.auto.add(&format!("timeline.layer.{}.trackMatte", layer.id.0), mr, "Track Matte");
let pop = egui::Id::new(("trk-pop", layer.id.0));
if tresp.clicked() {
@@ -1951,17 +1979,11 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
opts.push(k.label().into());
}
}
if let Some(i) = widgets::popup_menu(ui, pop, mr.left_bottom(), &opts, None) {
if i == 0 {
actions.push(("layer.setTrackMatte".into(), json!({"layer": layer.id.0, "matte": null})));
} else if i >= 2 && i < 2 + candidates.len() {
let kind = layer.track_matte.map(|m| m.kind).unwrap_or_default();
actions
.push(("layer.setTrackMatte".into(), json!({"layer": layer.id.0, "matte": candidates[i - 2].id.0, "kind": kind_name(kind)})));
} else if let Some(k) = MatteKind::ALL.into_iter().find(|k| k.label() == opts[i])
&& let Some(m) = layer.track_matte
{
actions.push(("layer.setTrackMatte".into(), json!({"layer": layer.id.0, "matte": m.layer.0, "kind": kind_name(k)})));
let current = layer.track_matte.and_then(|m| opts.iter().position(|o| o == m.kind.label()));
if let Some(i) = widgets::popup_menu(ui, pop, mr.left_bottom(), &opts, current) {
let ids: Vec<LayerId> = candidates.iter().map(|l| l.id).collect();
if let Some(a) = opts.get(i).and_then(|o| track_matte_pick(layer, &ids, i, o)) {
actions.push(a);
}
}
if layer.track_matte.is_some() {
@@ -2084,6 +2106,11 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if lin.hovered() || lout.hovered() || lin.dragged() || lout.dragged() {
ctx.set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
}
if body.double_clicked()
&& let Some(a) = double_click_action(layer)
{
actions.push(a);
}
let shift = ui.input(|i| i.modifiers.shift);
if let Some(layers) = (body.clicked() && shift).then(|| shift_range(&ctx, cid, &comp, &rows, &selected, layer.id)).flatten() {
// Shift-click: the layers from the last one clicked to this one, as in
@@ -2097,7 +2124,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
set_anchor(&ctx, cid, layer.id);
}
}
layer_context_menu(&body, layer, &mut actions);
layer_context_menu(&body, &comp, layer, &selected, vector_footage_layer(&app.session.project, layer), &mut actions);
let drag_key = format!("bar-{}", layer.id.0);
for (resp, kind) in [(&body, "move"), (&lin, "in"), (&lout, "out")] {
if resp.dragged() {
@@ -2108,14 +2135,13 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if frames != 0 {
acc -= (frames as f64 * fd * pps) as f32;
let d = frames as f64 * fd;
// Moving or trimming a selected layer acts on the whole
// selection; each layer trims from its own in/out point.
let targets = if is_sel { json!(selected.iter().map(|l| l.0).collect::<Vec<_>>()) } else { json!([layer.id.0]) };
let params = match kind {
"move" => {
json!({"layers": if is_sel { json!(selected.iter().map(|l| l.0).collect::<Vec<_>>()) } else { json!([layer.id.0]) }, "delta": d, "merge": drag_key})
}
"in" => json!({"layers": [layer.id.0], "in": (layer.in_point.seconds() + d).max(0.0), "merge": drag_key}),
_ => {
json!({"layers": [layer.id.0], "out": (layer.out_point.seconds() + d).min(comp.duration.seconds()), "merge": drag_key})
}
"move" => json!({"layers": targets, "delta": d, "merge": drag_key}),
"in" => json!({"layers": targets, "inDelta": d, "merge": drag_key}),
_ => json!({"layers": targets, "outDelta": d, "merge": drag_key}),
};
actions.push(("layer.timing".into(), params));
}
@@ -2312,7 +2338,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
lp.text(lang_r.center(), Align2::CENTER_CENTER, "f", Tokens::semibold(10.0), if lang.hovered() { t.text } else { t.text_dim });
app.auto.add(&format!("timeline.prop.{uid}.exprLanguage"), lang_r, "Expression Language Menu");
let mut picked: Option<&'static str> = None;
egui::Popup::menu(&lang).show(|ui| {
egui::Popup::menu(&lang).style(crate::widgets::menu_style).show(|ui| {
for (cat, items) in effectcraft_engine::commands::expr_tools::language_menu() {
ui.menu_button(cat, |ui| {
widgets::menu_scroll(ui, |ui| {
@@ -2475,7 +2501,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if name_resp.clicked() {
actions.push(("prop.select".into(), json!({"layer": layer.id.0, "prop": uid, "add": ui.input(|i| i.modifiers.shift)})));
}
name_resp.context_menu(|ui| prop_menu(ui, &mut app.auto, cid, layer, prop, &mut actions));
crate::widgets::context_menu(&name_resp, |ui| prop_menu(ui, &mut app.auto, cid, layer, prop, &mut actions));
// Value editors.
let value = ectx.value(layer, prop);
let vx = (cw.switches + 4.0).max(name_x + 120.0);
@@ -2567,7 +2593,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
ui_actions.push(UiAct::SetTime(ct));
}
}
kresp.context_menu(|ui| {
crate::widgets::context_menu(&kresp, |ui| {
for (lbl, cmd, params) in [
("Edit Value…", "keys.set", json!({"layer": layer.id.0, "prop": uid, "time": k.time.seconds()})),
("-", "", json!({})),
@@ -2658,10 +2684,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.auto.add("timeline.empty", empty_rect, "Right-click to create a layer");
}
for (response, area) in [(&outline_empty, "outline"), (&empty, "graph")] {
response.context_menu(|ui| {
crate::widgets::context_menu(response, |ui| {
let menu = ui.menu_button(crate::i18n::tr("New"), |ui| {
for (key, label, command, params) in [
("text", "Text", "layer.newText", json!({"text": "Text"})),
("text", "Text", "layer.newText", json!({})),
("solid", "Solid…", "layer.newSolid", json!({})),
("light", "Light…", "layer.newLight", json!({})),
("camera", "Camera…", "layer.newCamera", json!({})),
@@ -2684,6 +2710,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
actions.push(("comp.settings".into(), json!({})));
ui.close();
}
let response = ui.button(crate::i18n::tr("Open in Essential Graphics"));
app.auto.add(&format!("timeline.context.{area}.essentialGraphics"), response.rect, "Open in Essential Graphics");
if response.clicked() {
actions.push(("comp.openInEssentialGraphics".into(), json!({})));
ui.close();
}
});
}
if outline_empty.clicked() && !ui.input(|i| i.modifiers.shift || i.modifiers.command) {
@@ -3257,6 +3289,11 @@ const SHAPE_ADD_ITEMS: &[(&str, &str)] = &[
("gfill", "Gradient Fill"),
("gstroke", "Gradient Stroke"),
("-", ""),
("frontColor", "Front: Color"),
("bevelColor", "Bevel: Color"),
("sideColor", "Side: Color"),
("backColor", "Back: Color"),
("-", ""),
("merge", "Merge Paths"),
("offset", "Offset Paths"),
("pucker", "Pucker & Bloat"),
@@ -3396,6 +3433,21 @@ fn text_anim_popups(
}
}
/// The command for the Track Matte menu item `i` (`choice`) of `layer`, whose menu lists "No Track
/// Matte", a separator, the matte `candidates`, a separator and the modes. A mode without a matte
/// layer takes the layer above, like Layer ▸ Track Matte (#864: it used to do nothing).
fn track_matte_pick(layer: &Layer, candidates: &[LayerId], i: usize, choice: &str) -> Option<(String, serde_json::Value)> {
if i == 0 {
return Some(("layer.setTrackMatte".into(), json!({"layer": layer.id.0, "matte": null})));
}
if let Some(m) = i.checked_sub(2).and_then(|j| candidates.get(j)) {
let kind = layer.track_matte.map(|m| m.kind).unwrap_or_default();
return Some(("layer.setTrackMatte".into(), json!({"layer": layer.id.0, "matte": m.0, "kind": kind_name(kind)})));
}
let k = MatteKind::ALL.into_iter().find(|k| k.label() == choice)?;
Some(("layer.trackMatte".into(), json!({"layers": [layer.id.0], "op": kind_name(k)})))
}
fn kind_name(k: MatteKind) -> &'static str {
match k {
MatteKind::Alpha => "alpha",
@@ -3442,12 +3494,42 @@ fn prop_menu(
item(ui, "essentialGraphics", "Add Property to Essential Graphics", false, "essential.addProperty", json!({"comp": comp.0, "layer": l, "prop": uid}));
}
fn layer_context_menu(resp: &egui::Response, layer: &Layer, actions: &mut Vec<(String, serde_json::Value)>) {
resp.context_menu(|ui| layer_menu(ui, &[layer.id.0], actions));
/// Whether `layer` shows vector footage (SVG, PDF, AI, EPS).
pub(crate) fn vector_footage_layer(project: &effectcraft_engine::project::Project, layer: &Layer) -> bool {
layer
.source
.item()
.and_then(|item| project.item(item))
.is_some_and(|item| matches!(&item.kind, effectcraft_engine::project::ItemKind::Footage(footage) if effectcraft_engine::vector::is_vector(footage)))
}
/// Whether the Collapse Transformations / Continuously Rasterize switch applies: precomps, shape and text
/// layers, and vector footage (SVG, PDF, AI, EPS), which the renderer re-rasterizes at the layer's scale.
fn collapse_applies(layer: &Layer, project: &effectcraft_engine::project::Project) -> bool {
match &layer.source {
LayerSource::Comp { .. } | LayerSource::Shape | LayerSource::Text => true,
LayerSource::Footage { item } => {
let kind = project.item(*item).map(|i| &i.kind);
matches!(kind, Some(effectcraft_engine::project::ItemKind::Footage(f)) if effectcraft_engine::render::is_vector_footage(f))
}
_ => false,
}
}
/// A layer row's or bar's context menu. As in After Effects, right-clicking a layer that is part
/// of the selection keeps the selection and the menu acts on all of it; right-clicking an
/// unselected layer selects only that layer.
fn layer_context_menu(resp: &egui::Response, comp: &Comp, layer: &Layer, selected: &[LayerId], vector: bool, actions: &mut Vec<(String, serde_json::Value)>) {
let in_selection = selected.contains(&layer.id);
if resp.secondary_clicked() && !in_selection && !layer.switches.locked {
actions.push(("layer.select".into(), json!({"layers": [layer.id.0]})));
}
let targets: Vec<u64> = if in_selection { comp.layers.iter().filter(|l| selected.contains(&l.id)).map(|l| l.id.0).collect() } else { vec![layer.id.0] };
crate::widgets::context_menu(resp, |ui| layer_menu(ui, &targets, vector, actions));
}
/// Shared layer actions for Timeline rows and Composition context menus.
pub(crate) fn layer_menu(ui: &mut egui::Ui, layers: &[u64], actions: &mut Vec<(String, serde_json::Value)>) {
pub(crate) fn layer_menu(ui: &mut egui::Ui, layers: &[u64], vector: bool, actions: &mut Vec<(String, serde_json::Value)>) {
let Some(&id) = layers.first() else { return };
let mut item = |ui: &mut egui::Ui, label: &str, cmd: &str, params: serde_json::Value| {
if ui.button(label).clicked() {
@@ -3457,7 +3539,7 @@ pub(crate) fn layer_menu(ui: &mut egui::Ui, layers: &[u64], actions: &mut Vec<(S
}
};
ui.menu_button(crate::i18n::tr("New"), |ui| {
item(ui, "Text", "layer.newText", json!({"text": "Text"}));
item(ui, "Text", "layer.newText", json!({}));
item(ui, "Solid…", "app.solidSettings", json!({}));
item(ui, "Light…", "layer.newLight", json!({}));
item(ui, "Camera…", "layer.newCamera", json!({}));
@@ -3466,6 +3548,9 @@ pub(crate) fn layer_menu(ui: &mut egui::Ui, layers: &[u64], actions: &mut Vec<(S
item(ui, "Adjustment Layer", "layer.newAdjustment", json!({}));
});
item(ui, "Layer Settings…", "layer.settings", json!({}));
if vector {
item(ui, "Create Shapes from Vector Layer", "layer.create", json!({"op": "shapesFromVector", "layers": layers}));
}
ui.separator();
ui.menu_button(crate::i18n::tr("Masks"), |ui| {
item(ui, "New Mask", "layer.addMask", json!({"layer": id}));
@@ -3530,8 +3615,14 @@ fn value_editor(
// With several layers selected the edit applies to all of them (#491): a scrub by the same
// change, a typed value as it is.
let scrub = ui.ctx().dragged_id().is_some() && ui.input(|i| i.pointer.is_decidedly_dragging());
// Proportional Scrubbing (After Effects 26.2): Ctrl+Alt (Cmd+Opt) spreads the change over the
// selected layers by selection order, the first unchanged and the last by all of it.
let proportional = scrub && ui.input(|i| widgets::proportional_scrub(i.modifiers));
let set = |actions: &mut Vec<(String, serde_json::Value)>, v: serde_json::Value| {
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": v, "merge": merge, "selected": true, "offset": scrub})))
actions.push((
"prop.set".into(),
json!({"layer": layer.id.0, "prop": uid, "value": v, "merge": merge, "selected": true, "offset": scrub, "proportional": proportional}),
))
};
let is_3d = layer.is_3d();
let mut x = at.x;
@@ -3586,8 +3677,8 @@ fn value_editor(
dims.push(r);
if let Some(nv) = nv {
let mut nc = c.clone();
// Alt edits one value of a linked pair.
let shown = if linked && !ui.input(|i| i.modifiers.alt) { n.min(c.len()) } else { 1 };
// Alt edits one value of a linked pair (Ctrl+Alt is a proportional scrub).
let shown = if linked && !ui.input(|i| i.modifiers.alt && !widgets::proportional_scrub(i.modifiers)) { n.min(c.len()) } else { 1 };
let from = if shown == 1 { d } else { 0 };
for (e, v) in widgets::constrained(c.get(from..from + shown).unwrap_or_default(), d - from, nv).into_iter().enumerate() {
if let Some(slot) = nc.get_mut(from + e) {
@@ -3671,7 +3762,16 @@ fn value_editor(
);
}
Value::Gradient(_) => {
p.text(pos2(x, at.y), Align2::LEFT_CENTER, crate::i18n::tr("Edit Gradient…"), Tokens::ui(12.0), t.hot_text);
// Opens the Gradient Editor at the current time (#612).
let r = p.text(pos2(x, at.y), Align2::LEFT_CENTER, crate::i18n::tr("Edit Gradient…"), Tokens::ui(12.0), t.hot_text);
let resp = ui.interact(r.expand(2.0), egui::Id::new(("gradient-edit", uid)), Sense::click());
if resp.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
app.auto.add(&format!("timeline.prop.{uid}.value"), r, &prop.name);
if resp.clicked() {
actions.push(("prop.editGradient".into(), json!({"layer": layer.id.0, "prop": uid})));
}
}
Value::Str(s) => {
p.text(pos2(x, at.y), Align2::LEFT_CENTER, s.chars().take(30).collect::<String>(), Tokens::ui(12.0), t.text_dim);
@@ -3684,6 +3784,23 @@ fn value_editor(
mod tests {
use super::*;
/// #710: with Time Display set to Frames the ruler labels are frame numbers (as under the
/// CTI, from Start Numbering Frames At); otherwise seconds:frames.
#[test]
fn ruler_labels_follow_the_time_display_style() {
use effectcraft_engine::project::{ProjectSettings, TimeDisplayStyle};
let mut st = ProjectSettings { time_display: TimeDisplayStyle::Timecode, frame_start: 0, ..ProjectSettings::default() };
assert_eq!(ruler_label(15, 30, &st), "00:15f");
assert_eq!(ruler_label(45, 30, &st), "01:15f");
assert_eq!(ruler_label(30 * 3600 + 31, 30, &st), "60:01:01f");
st.time_display = TimeDisplayStyle::Frames;
assert_eq!(ruler_label(0, 30, &st), "00000");
assert_eq!(ruler_label(45, 30, &st), "00045");
st.frame_start = 1;
assert_eq!(ruler_label(45, 30, &st), "00046");
assert_eq!(ruler_label(i64::MAX, 30, &st), format!("{:05}", i64::MAX));
}
/// #468: playback pages the view to the CTI; a scrub past either end scrolls that way.
#[test]
fn the_view_pages_to_the_cti() {
@@ -3698,6 +3815,58 @@ mod tests {
assert!(edge_scroll_speed_x(100.0, 500.0, 600.0) > edge_scroll_speed_x(100.0, 500.0, 520.0));
}
/// #864: picking only a mode in a layer's Track Matte menu sets a matte (the layer above);
/// it used to close the menu and change nothing.
#[test]
fn a_track_matte_mode_without_a_matte_takes_the_layer_above() {
let mut s = effectcraft_engine::Session::default();
s.execute("comp.new", json!({"name": "T", "width": 64, "height": 64, "duration": 1})).unwrap();
for name in ["Chain Bottom", "Matte", "Chain Top"] {
s.execute("layer.newSolid", json!({"name": name, "color": "#ffffff", "width": 64, "height": 64})).unwrap();
}
let find = |s: &effectcraft_engine::Session, n: &str| s.active_comp().unwrap().layers.iter().find(|l| l.name == n).unwrap().clone();
let (bottom, matte, top) = (find(&s, "Chain Bottom"), find(&s, "Matte"), find(&s, "Chain Top"));
let candidates = [top.id, matte.id];
let pick = |s: &mut effectcraft_engine::Session, name: &str, i: usize, choice: &str| {
let (id, params) = track_matte_pick(&find(s, name), &candidates, i, choice).expect("a menu item is an action");
s.execute(&id, params)
};
pick(&mut s, "Chain Bottom", 5, "Alpha Inverted Matte").unwrap();
let m = find(&s, "Chain Bottom").track_matte.expect("a matte");
assert_eq!((m.layer, m.kind), (matte.id, MatteKind::AlphaInverted));
assert!(!find(&s, "Matte").switches.video, "the matte layer is hidden");
// A mode change keeps the matte layer; a matte change keeps the mode.
pick(&mut s, "Chain Bottom", 6, "Luma Matte").unwrap();
assert_eq!(find(&s, "Chain Bottom").track_matte.map(|m| (m.layer, m.kind)), Some((matte.id, MatteKind::Luma)));
pick(&mut s, "Chain Bottom", 2, "1. Chain Top").unwrap();
assert_eq!(find(&s, "Chain Bottom").track_matte.map(|m| (m.layer, m.kind)), Some((top.id, MatteKind::Luma)));
assert!(s.undo());
assert_eq!(find(&s, "Chain Bottom").track_matte.map(|m| m.layer), Some(matte.id), "one undo step per pick");
// The top layer has nothing above it: an error for the status bar, not a silent no-op.
assert!(pick(&mut s, "Chain Top", 5, "Alpha Matte").is_err());
pick(&mut s, "Chain Bottom", 0, "No Track Matte").unwrap();
assert!(find(&s, "Chain Bottom").track_matte.is_none());
assert!(track_matte_pick(&bottom, &candidates, 1, "-").is_none(), "a separator does nothing");
}
/// #957: vector footage gets the Continuously Rasterize switch; raster footage does not.
#[test]
fn collapse_switch_shows_for_vector_footage_only() {
use effectcraft_engine::color::Label;
use effectcraft_engine::project::{Footage, ItemKind, Project};
let mut p = Project::default();
let mut layer_for = |name: &str, codec: &str| {
let footage = Footage { path: name.into(), codec: codec.into(), ..Default::default() };
let item = p.add_item(name, Label::SeaFoam, None, ItemKind::Footage(footage));
let comp = Comp::new(64, 36, effectcraft_engine::time::FrameRate::new(30, 1), Tick::from_seconds_f64(1.0));
effectcraft_engine::project::build::layer(&mut p, &comp, name, LayerSource::Footage { item }, (0, 0), None)
};
let svg = layer_for("logo.svg", "SVG");
let png = layer_for("photo.png", "PNG");
assert!(collapse_applies(&svg, &p));
assert!(!collapse_applies(&png, &p));
}
/// A comp with two solids; "Box" has an animated Position and a Gaussian Blur.
fn app() -> EffectcraftApp {
let mut s = effectcraft_engine::Session::default();
@@ -3859,6 +4028,28 @@ mod tests {
assert!(rows.iter().any(|r| r.trim() == ">Transform"), "{rows:?}");
}
/// U and UU show Time Remap on a layer with time remapping enabled.
#[test]
fn u_and_uu_reveal_time_remap() {
let mut s = effectcraft_engine::Session::default();
let inner = s.execute("comp.new", json!({"name": "Inner", "width": 32, "height": 32, "duration": 2})).unwrap()["comp"].as_u64().unwrap();
s.execute("comp.new", json!({"name": "Main", "width": 64, "height": 64, "duration": 4})).unwrap();
let nested = s.execute("layer.addItem", json!({"item": inner})).unwrap()["layer"].as_u64().unwrap();
let mut app = EffectcraftApp::new(s);
let ctx = egui::Context::default();
crate::menus::invoke(&mut app, &ctx, "layer.enableTimeRemap", json!({"layers": [nested]})).unwrap();
app.session.execute("layer.select", json!({"layers": [nested]})).unwrap();
for uu in [false, true] {
app.ui.timeline.layer_reveal.clear();
app.last_reveal = uu.then(|| ("keyframes".into(), f64::MAX));
crate::menus::invoke(&mut app, &ctx, "anim.reveal", json!({"kind": "keyframes"})).unwrap();
assert_eq!(app.ui.timeline.layer_reveal.get(&nested), Some(&vec!["props".to_string()]), "UU: {uu}");
let rows = labels(&app);
let at = rows.iter().position(|r| r == "Inner").unwrap();
assert_eq!(rows[at + 1].trim(), "Time Remap", "UU: {uu}: {rows:?}");
}
}
/// Enabling time remapping twirls the layer open on Time Remap (#157); disabling it reveals
/// nothing.
#[test]
+74 -5
View File
@@ -5,7 +5,8 @@
//! Revert only asks to discard. Agents running commands with `engine.execute` are never asked.
//!
//! Automation ids: `dialog.unsaved.save`, `dialog.unsaved.dontSave` (Revert: `dialog.unsaved.revert`),
//! `dialog.unsaved.cancel`.
//! `dialog.unsaved.cancel`. Enter answers Save, Cmd+Backspace (Ctrl elsewhere) Don't Save and, in
//! the Revert prompt, Cmd+R Revert.
use crate::i18n::tr;
use egui::{Color32, vec2};
@@ -73,6 +74,11 @@ pub fn window_title(app: &EffectcraftApp) -> String {
format!("EffectCraft - {doc}{}", if app.session.is_dirty() { " *" } else { "" })
}
/// Whether the prompt is Revert Project (Revert / Cancel) instead of Unsaved Changes.
pub(crate) fn is_revert(app: &EffectcraftApp) -> bool {
app.dialog_state.unsaved.command.as_ref().is_some_and(|(id, _)| id == "file.revert")
}
enum Answer {
Save,
Discard,
@@ -80,11 +86,11 @@ enum Answer {
}
pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let Some((id, _)) = app.dialog_state.unsaved.command.clone() else {
if app.dialog_state.unsaved.command.is_none() {
app.dialog = None;
return;
};
let revert = id == "file.revert";
}
let revert = is_revert(app);
let name = project_name(app);
let mut answer = None;
let title = if revert { "Revert Project" } else { "Unsaved Changes" };
@@ -102,7 +108,8 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
ui.add_space(18.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let (label, key) = if revert { (" Revert ", "dialog.unsaved.revert") } else { (" Save ", "dialog.unsaved.save") };
let r = ui.add(egui::Button::new(egui::RichText::new(label).color(Color32::WHITE)).fill(t.accent));
// Revert discards work: red, like Delete.
let r = ui.add(egui::Button::new(egui::RichText::new(label).color(Color32::WHITE)).fill(if revert { t.danger } else { t.accent }));
app.auto.add(key, r.rect, label.trim());
if r.clicked() {
answer = Some(if revert { Answer::Discard } else { Answer::Save });
@@ -126,6 +133,15 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
if answer.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
answer = Some(Answer::Cancel);
}
// Enter is Save, the default button; Cmd+Backspace (Ctrl elsewhere) is Don't Save, as in
// macOS save prompts. Revert discards work, so it takes neither: Cmd+R.
if answer.is_none() && !revert && super::dialogs::ui_enter(ctx) {
answer = Some(Answer::Save);
}
let discard = if revert { egui::Key::R } else { egui::Key::Backspace };
if answer.is_none() && super::dialogs::ui_command_key(ctx, discard) {
answer = Some(Answer::Discard);
}
if let Some(a) = answer {
answer_with(app, ctx, a);
}
@@ -227,6 +243,59 @@ mod tests {
assert!(app.dialog.is_none() && app.session.project.comps().count() == 0);
}
#[test]
fn cmd_backspace_is_dont_save_but_not_revert() {
let press = |app: &mut EffectcraftApp, ctx: &egui::Context| crate::panels::dialogs::press_key(app, ctx, egui::Key::Backspace, egui::Modifiers::COMMAND);
let (mut app, ctx) = app();
modified(&mut app);
crate::menus::invoke(&mut app, &ctx, "file.newProject", json!({})).unwrap();
assert_eq!(app.dialog, Some(Dialog::UnsavedChanges));
press(&mut app, &ctx);
assert!(app.dialog.is_none() && !app.session.is_dirty());
assert_eq!(app.session.project.comps().count(), 0, "closed without saving");
// The Revert prompt has no Don't Save.
let dir = std::env::temp_dir().join(format!("ec-unsaved-key-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
modified(&mut app);
app.session.execute("file.saveAs", json!({"path": dir.join("Kept.ecproj").to_string_lossy()})).unwrap();
app.session.execute("layer.newNull", json!({})).unwrap();
crate::menus::invoke(&mut app, &ctx, "file.revert", json!({})).unwrap();
press(&mut app, &ctx);
assert_eq!(app.dialog, Some(Dialog::UnsavedChanges));
assert_eq!(app.session.active_comp().unwrap().layers.len(), 1, "not reverted");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn enter_is_save_and_cmd_r_is_revert() {
let press = |app: &mut EffectcraftApp, ctx: &egui::Context| crate::panels::dialogs::press_key(app, ctx, egui::Key::Enter, egui::Modifiers::NONE);
let (mut app, ctx) = app();
let dir = std::env::temp_dir().join(format!("ec-unsaved-enter-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Kept.ecproj");
modified(&mut app);
app.session.execute("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
// The Revert prompt discards work: Enter leaves it open.
app.session.execute("layer.newNull", json!({})).unwrap();
crate::menus::invoke(&mut app, &ctx, "file.revert", json!({})).unwrap();
press(&mut app, &ctx);
assert_eq!(app.dialog, Some(Dialog::UnsavedChanges));
assert_eq!(app.session.active_comp().unwrap().layers.len(), 1, "not reverted");
// Cmd+R is Revert.
crate::panels::dialogs::press_key(&mut app, &ctx, egui::Key::R, egui::Modifiers::COMMAND);
assert!(app.dialog.is_none());
assert_eq!(app.session.active_comp().unwrap().layers.len(), 0, "reverted");
app.session.execute("layer.newNull", json!({})).unwrap();
// Save: the change is written, then the project closes.
crate::menus::invoke(&mut app, &ctx, "file.closeProject", json!({})).unwrap();
press(&mut app, &ctx);
assert!(app.dialog.is_none());
assert_eq!(app.session.project.comps().count(), 0, "closed");
app.session.execute("file.open", json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(app.session.active_comp().unwrap().layers.len(), 1, "the null was saved");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn save_saves_then_continues_and_revert_only_asks_to_discard() {
let (mut app, ctx) = app();
+250 -36
View File
@@ -210,6 +210,8 @@ use super::viewer_overlays::{self as ov, VertexHit};
use super::viewer_tools as vt;
const HANDLE: f32 = 7.0;
/// Shown when a Roto Brush tool is used in the Composition panel (#753).
const ROTO_HINT: &str = "The Roto Brush works in the Layer panel. Double-click the layer to open it.";
thread_local! {
/// The 3D view camera of the viewer being drawn (None = the comp's active camera).
@@ -527,18 +529,22 @@ fn aux_views(
return full;
}
let gap = 2.0;
let views = app.session.state.views3d.get(&cid).cloned().unwrap_or_default();
let (main, aux): (Rect, Vec<(Rect, View3D)>) = if n == 2 {
let mid = full.center().x;
(Rect::from_min_max(pos2(mid + gap / 2.0, full.min.y), full.max), vec![(Rect::from_min_max(full.min, pos2(mid - gap / 2.0, full.max.y)), View3D::Top)])
(
Rect::from_min_max(pos2(mid + gap / 2.0, full.min.y), full.max),
vec![(Rect::from_min_max(full.min, pos2(mid - gap / 2.0, full.max.y)), views.pane(0))],
)
} else {
let c = full.center();
let q = |x0: f32, y0: f32, x1: f32, y1: f32| Rect::from_min_max(pos2(x0, y0), pos2(x1, y1));
(
q(c.x + gap / 2.0, c.y + gap / 2.0, full.max.x, full.max.y),
vec![
(q(full.min.x, full.min.y, c.x - gap / 2.0, c.y - gap / 2.0), View3D::Top),
(q(c.x + gap / 2.0, full.min.y, full.max.x, c.y - gap / 2.0), View3D::Front),
(q(full.min.x, c.y + gap / 2.0, c.x - gap / 2.0, full.max.y), View3D::Right),
(q(full.min.x, full.min.y, c.x - gap / 2.0, c.y - gap / 2.0), views.pane(0)),
(q(c.x + gap / 2.0, full.min.y, full.max.x, c.y - gap / 2.0), views.pane(1)),
(q(full.min.x, c.y + gap / 2.0, c.x - gap / 2.0, full.max.y), views.pane(2)),
],
)
};
@@ -547,14 +553,23 @@ fn aux_views(
p.rect_filled(full, 0.0, Color32::from_black_alpha(200));
let t = app.session.time();
let (cw, ch) = (comp.width as f32, comp.height as f32);
let views = app.session.state.views3d.get(&cid).cloned().unwrap_or_default();
let share = app.session.state.share_view_options;
// The camera and light wireframes of each view (as in After Effects, where every view of the
// layout shows them), evaluated on a snapshot of the project.
let snap_project = app.session.project.clone();
let snap_expr = app.session.expr.clone();
let ectx = EvalCtx { project: &snap_project, comp_id: cid, comp, time: t, expr: snap_expr.as_deref(), footage: None };
let selected = app.session.state.selected_layers.clone();
let mut picked: Option<(usize, View3D)> = None;
for (i, (r, v)) in aux.into_iter().enumerate() {
p.rect_filled(r, 0.0, bg);
let fit = ((r.width() - 20.0) / cw).min((r.height() - 20.0) / ch).max(0.01);
let cr = Rect::from_center_size(r.center(), vec2(cw * fit, ch * fit));
let scale = (fit * ctx.pixels_per_point()).min(1.0) as f64;
let cam = views.cam(v, comp.width as f64, comp.height as f64).state();
// The Active Camera pane renders through the comp's own camera; the others through their
// view camera.
let through_active = v == View3D::ActiveCamera;
let cam = if through_active { three_d::active_camera(&ectx) } else { views.cam(v, comp.width as f64, comp.height as f64).state() };
let key = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
@@ -566,7 +581,12 @@ fn aux_views(
let tex = match cached {
Some((k, tex)) if k == key => tex,
_ => {
let opts = effectcraft_engine::render::RenderOpts { scale, view: comp.has_3d().then_some(cam), draft: true, ..Default::default() };
let opts = effectcraft_engine::render::RenderOpts {
scale,
view: (comp.has_3d() && !through_active).then_some(cam),
draft: true,
..Default::default()
};
let img = app.session.render(cid, t, opts);
let tex = crate::frames::load_fitted(&ctx, format!("viewer-aux-{i}"), crate::frames::to_color_image(&img), egui::TextureOptions::LINEAR);
ctx.data_mut(|d| d.insert_temp(id, (key, tex.clone())));
@@ -582,13 +602,57 @@ fn aux_views(
p.rect_stroke(Rect::from_center_size(cr.center(), cr.size() * k), 0.0, Stroke::new(1.0, Color32::from_white_alpha(120)), StrokeKind::Middle);
}
}
if comp.has_3d() {
let map = ViewerMap { origin: cr.min, zoom: fit, comp: [cw, ch], area: r };
draw_rigs(app, &p.with_clip_rect(r), &map, &ectx, &selected, cam, through_active, Some(v.id()));
}
let label = if comp.has_3d() { v.label() } else { crate::i18n::tr("Active Camera") };
p.text(r.left_bottom() + vec2(8.0, -8.0), Align2::LEFT_BOTTOM, label, Tokens::ui(11.0), Color32::from_white_alpha(200));
app.auto.add(&format!("viewer.view.{}", v.id()), r, label);
if comp.has_3d()
&& let Some(chosen) = pane_selector(app, ui, i + 1, r, v)
{
picked = Some((i + 1, chosen));
}
}
if let Some((pane, v)) = picked
&& let Err(e) = app.session.execute("view.setPaneView", json!({"pane": pane, "view": v.id(), "comp": cid.0}))
{
app.ui.status = e.to_string();
}
main
}
/// The view selector in the top-left corner of pane `pane` (1 to 3) of a multi-view layout, a
/// popup of every 3D view like the toolbar's 3D View menu. Returns the view chosen this frame.
fn pane_selector(app: &mut EffectcraftApp, ui: &mut egui::Ui, pane: usize, area: Rect, current: View3D) -> Option<View3D> {
let t = app.tokens;
let r = Rect::from_min_size(area.min + vec2(6.0, 6.0), vec2(124.0, 20.0));
let pid = egui::Id::new(("viewer-pane-view", pane));
let response = widgets::dropdown(ui, r, crate::i18n::tr(current.label()), &t, pid);
if response.clicked() {
let open = widgets::popup_is_open(ui, pid);
ui.data_mut(|d| d.insert_temp(pid.with("open"), !open));
}
app.auto.add_response(&format!("viewer.view.{pane}.type"), &response, "View of pane");
if !widgets::popup_is_open(ui, pid) {
return None;
}
let chosen = widgets::popup_list(ui, pid, r.left_bottom() + vec2(0.0, 2.0), r, View3D::ALL.len(), 0, |ui| {
ui.set_min_width(124.0);
let mut chosen = None;
for (k, v) in View3D::ALL.iter().enumerate() {
let item = ui.selectable_label(*v == current, crate::i18n::tr(v.label()));
app.auto.add(&format!("viewer.view.{pane}.typeItem.{k}"), item.rect, v.label());
if item.clicked() {
chosen = Some(*v);
}
}
chosen
});
chosen.filter(|v| *v != current)
}
/// View ▸ Split with New Locked Viewer: the locked viewer on the left of the Composition panel
/// (its comp and 3D view stay put whatever comp is active). Returns the main viewer's rectangle.
fn locked_pane(app: &mut EffectcraftApp, ui: &mut egui::Ui, full: Rect, bg: Color32) -> Rect {
@@ -735,10 +799,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
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);
// Fit up to 100% follows the panel's size like Fit does, and stops at 100%.
let fit = if app.ui.viewer.fit_up_to_100 { fit.min(1.0 / ctx.pixels_per_point()) } else { fit };
ctx.data_mut(|d| d.insert_temp(egui::Id::new("viewer-fit"), fit));
let zoom = app.ui.viewer.zoom.unwrap_or(fit);
let center = area.center() + vec2(app.ui.viewer.pan[0], app.ui.viewer.pan[1]);
let origin = center - vec2(cw * zoom / 2.0, ch * zoom / 2.0);
// On the physical pixel grid, so at 100 % every comp pixel covers exactly one screen pixel
// instead of being blended with its neighbour (#882).
let ppp = ctx.pixels_per_point();
let origin = snap_to_pixels(center - vec2(cw * zoom / 2.0, ch * zoom / 2.0), ppp);
let map = ViewerMap { origin, zoom, comp: [cw, ch], area };
ctx.data_mut(|d| d.insert_temp(map_id(), map));
let comp_rect = Rect::from_min_size(origin, vec2(cw * zoom, ch * zoom));
@@ -748,7 +817,6 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.ui.viewer.extended = extended_region(app, &comp, cid, map);
// Frame.
let ppp = ctx.pixels_per_point();
let scale = app.viewer_scale(zoom, ppp);
if !app.playback.playing {
// Queue the frame on screen before any prefetch.
@@ -1014,8 +1082,6 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.auto.add("viewer.referenceAxes", Rect::from_center_size(corner, vec2(56.0, 56.0)), "3D reference axes");
}
super::expr_editor::error_banner(app, ui, area);
// Track points of the current track (Tracker panel) on its layer, while that layer is selected.
let mut track_hits = vec![];
let track_cur = super::tracker::viewer_track(app);
@@ -1049,12 +1115,37 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.auto.add("viewer.warpBanner", r, &text);
}
// Footage that can't be decoded (no decoder for its codec / profile): say why on the layer
// instead of leaving a black picture.
let mut notices = 0;
for layer in comp.layers.iter().filter(|l| l.is_active_at(time) && l.switches.video) {
let effectcraft_engine::project::LayerSource::Footage { item } = &layer.source else { continue };
let Some(effectcraft_engine::project::ItemKind::Footage(f)) = app.session.project.item(*item).map(|i| &i.kind) else { continue };
let Some(why) = app.session.footage.problem(f) else { continue };
if notices >= 3 {
break;
}
let (m, _) = l2c(&ectx, layer);
let (w, h) = effectcraft_engine::render::source_size(&app.session.project, layer);
let c = m.apply(effectcraft_engine::geom::vec2(w as f64 / 2.0, h as f64 / 2.0));
let at = map.to_screen([c.x, c.y]);
let text = format!("{}: {}", layer.name, why);
let galley = painter.layout(text.clone(), Tokens::medium(12.0), Color32::WHITE, (map.area.width() - 40.0).clamp(80.0, 420.0));
let r = Rect::from_center_size(at + vec2(0.0, notices as f32 * 4.0), galley.size() + vec2(24.0, 16.0)).intersect(map.area);
painter.rect_filled(r, 3.0, Color32::from_rgba_unmultiplied(0x4a, 0x1a, 0x14, 0xe6));
painter.rect_stroke(r, 3.0, Stroke::new(1.0, t.warning), StrokeKind::Inside);
painter.galley(pos2(r.min.x + 12.0, r.center().y - galley.size().y / 2.0), galley, Color32::WHITE);
app.auto.add(&format!("viewer.footageProblem.{}", layer.id.0), r, &text);
notices += 1;
}
// Free transform box of a path (double-click a path with the Selection tool).
let ft = ov::draw_free_transform(app, &ctx, &painter, &map, &paths);
// Cameras and lights (wireframes) and the 3D view name.
if comp.has_3d() {
draw_rigs(app, &painter, &map, &ectx, &selected);
let through_active = VIEW_CAM.with(|c| c.get()).is_none();
draw_rigs(app, &painter, &map, &ectx, &selected, cam_state(&ectx), through_active, None);
let view = app.session.state.views3d.get(&cid).map(|v| v.current).unwrap_or_default();
let label = match (view, comp.active_camera(time)) {
(View3D::ActiveCamera, Some(c)) => format!("Active Camera ({})", c.name),
@@ -1117,7 +1208,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let context_layers: Vec<u64> =
app.session.state.selected_layers.iter().filter(|id| comp.layer(**id).is_some_and(|l| !l.switches.locked)).map(|id| id.0).collect();
let mut context_actions = Vec::new();
resp.context_menu(|ui| {
let copy_frame = crate::i18n::label(app, "comp.copyFrame", "Copy Frame to Clipboard");
crate::widgets::context_menu(&resp, |ui| {
let hits = ui.data(|d| d.get_temp::<Vec<(u64, String)>>(menu_hits_id)).unwrap_or_default();
if !hits.is_empty() {
ui.menu_button(crate::i18n::tr("Select"), |ui| {
@@ -1135,7 +1227,16 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if context_layers.is_empty() {
ui.label(crate::i18n::tr("No unlocked layer selected"));
} else {
super::timeline::layer_menu(ui, &context_layers, &mut context_actions);
let vector = context_layers
.iter()
.filter_map(|id| comp.layer(effectcraft_engine::project::LayerId(*id)))
.any(|layer| super::timeline::vector_footage_layer(&app.session.project, layer));
super::timeline::layer_menu(ui, &context_layers, vector, &mut context_actions);
}
ui.separator();
if ui.button(copy_frame).clicked() {
context_actions.push(("comp.copyFrame".to_owned(), serde_json::json!({"comp": cid.0})));
ui.close();
}
});
for (id, params) in context_actions {
@@ -1215,7 +1316,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mods = ui.input(|i| i.modifiers);
let space_pan = super::space_hand(&ctx);
// Pen tool: each press places a vertex (dragging pulls Bezier tangents); pressing on the
// first vertex closes the path.
// first vertex closes the path, pressing an open path's last vertex resumes it.
if app.ui.tool == Tool::Pen
&& !space_pan
&& resp.hovered()
@@ -1432,6 +1533,11 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
Some(Gesture::Marquee { start: press })
}
}
// The Roto Brush paints in the Layer panel only: say so instead of doing nothing.
rt if rt.roto_kind(false).is_some() => {
app.ui.status = crate::i18n::tr(ROTO_HINT).to_string();
None
}
_ => None,
};
if let Some(g) = g {
@@ -1792,6 +1898,13 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let _ = app.session.execute("mask.selectVertices", json!({"vertices": [me], "add": mods.shift, "toggle": mods.shift}));
}
}
// The Roto Brush paints in the Layer panel only: select as usual and say so.
rt if rt.roto_kind(false).is_some() => {
if pick(app, &ectx, cpt, mods.shift).is_none() {
let _ = app.session.execute("edit.deselectAll", json!({}));
}
app.ui.status = crate::i18n::tr(ROTO_HINT).to_string();
}
_ => {
if pick(app, &ectx, cpt, mods.shift).is_none() {
let _ = app.session.execute("edit.deselectAll", json!({}));
@@ -1823,10 +1936,21 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
&& let Some(pos) = resp.interact_pointer_pos()
{
let cpt = map.to_comp(pos);
if let Some(l) = pick(app, &ectx, cpt, false).and_then(|l| comp.layer(l))
&& let effectcraft_engine::project::LayerSource::Comp { item } = &l.source
{
app.session.open_comp(*item);
let roto = app.ui.tool.roto_kind(false).is_some();
if let Some(l) = pick(app, &ectx, cpt, false).and_then(|l| comp.layer(l)) {
match &l.source {
effectcraft_engine::project::LayerSource::Comp { item } => app.session.open_comp(*item),
// With a Roto Brush tool, double-clicking a layer opens it in the Layer panel,
// where the brush works (After Effects).
_ if roto => {
let id = l.id.0;
match crate::menus::invoke(app, &ctx, "layer.openLayer", json!({"layer": id})) {
Ok(_) => app.ui.status.clear(),
Err(e) => app.ui.status = e,
}
}
_ => {}
}
}
}
// 3D Camera Tracker points, targets and their menu (on top of the viewer's gestures while
@@ -1834,6 +1958,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
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);
// Selected shape gradients' start and end points (#612).
crate::panels::gradient_handles::viewer_hook(app, ui, &painter, &map, &ectx, &|c, l| l2c(c, l).0);
// Status chips (render time / caching).
if app.playback.playing && app.playback.waiting {
@@ -1844,7 +1970,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
vt::draw_snap(&ctx, &painter, &map, &ectx);
vt::rulers(app, ui, &map, outer, area);
vt::bottom_bar(app, ui, bar, zoom, fit, time, &comp);
vt::bottom_bar(app, ui, bar, zoom, time, &comp);
if err_h > 0.0 {
super::expr_bar::draw(app, ui, err_bar, cid);
}
@@ -1874,13 +2000,26 @@ fn drag_axes(ctx: &EvalCtx, l: &Layer) -> ([f64; 3], [f64; 3]) {
/// Wireframes of cameras (frustum, point of interest) and lights (position, direction) as seen
/// through the current 3D view.
fn draw_rigs(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap, ectx: &EvalCtx, selected: &[LayerId]) {
/// Camera and light wireframes seen through `cam` (`through_active`: `cam` is the active camera,
/// which is then not drawn). `pane` names the automation ids: `None` for the main view
/// (`viewer.camera.<id>`), `Some(view)` for a view of a 2- or 4-view layout
/// (`viewer.view.<view>.camera.<id>`).
#[allow(clippy::too_many_arguments)]
fn draw_rigs(
app: &mut EffectcraftApp,
painter: &egui::Painter,
map: &ViewerMap,
ectx: &EvalCtx,
selected: &[LayerId],
cam: CameraState,
through_active: bool,
pane: Option<&str>,
) {
use effectcraft_engine::geom::Vec3;
use effectcraft_engine::project::{LayerSource, LightKind};
let cam = cam_state(ectx);
let (w, h) = (ectx.comp.width as f64, ectx.comp.height as f64);
let active = ectx.comp.active_camera(ectx.time).map(|c| c.id);
let through_active = VIEW_CAM.with(|c| c.get()).is_none();
let prefix = pane.map(|v| format!("viewer.view.{v}.")).unwrap_or_else(|| "viewer.".to_string());
let proj = |p: Vec3| cam.project(w, h, p).map(|v| map.to_screen([v.x, v.y]));
let seg = |a: Vec3, b: Vec3, stroke: Stroke| {
if let (Some(x), Some(y)) = (proj(a), proj(b)) {
@@ -1917,7 +2056,7 @@ fn draw_rigs(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap,
}
}
if let Some(s) = proj(eye) {
app.auto.add(&format!("viewer.camera.{}", l.id.0), Rect::from_center_size(s, vec2(14.0, 14.0)), &l.name);
app.auto.add(&format!("{prefix}camera.{}", l.id.0), Rect::from_center_size(s, vec2(14.0, 14.0)), &l.name);
}
} else {
let LayerSource::Light { kind } = l.source else { continue };
@@ -1938,16 +2077,16 @@ fn draw_rigs(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap,
painter.circle_stroke(q, 3.0, stroke);
}
}
app.auto.add(&format!("viewer.light.{}", l.id.0), Rect::from_center_size(s, vec2(16.0, 16.0)), &l.name);
app.auto.add(&format!("{prefix}light.{}", l.id.0), Rect::from_center_size(s, vec2(16.0, 16.0)), &l.name);
}
}
}
/// Pen tool press at `pos`: continue the path in progress (pressing its first vertex closes it),
/// add a vertex on a visible path's segment, or start a new path: a mask on the selected
/// footage/solid layer (or shape layer, with Tool Creates Mask), a shape path (Shape n group with
/// the Tools bar's Fill and Stroke) on the selected shape layer, or a new shape layer when
/// nothing is selected. The placed point snaps.
/// resume an open path whose last vertex is pressed, add a vertex on a visible path's segment, or
/// start a new path: a mask on the selected footage/solid layer (or shape layer, with Tool Creates
/// Mask), a shape path (Shape n group with the Tools bar's Fill and Stroke) on the selected shape
/// layer, or a new shape layer when nothing is selected. The placed point snaps.
/// Add a Position keyframe at a motion path's frame, keeping the path where it is.
fn add_motion_key(app: &mut EffectcraftApp, f: ov::PathFrame) {
if let Err(e) = app.session.execute("prop.addKey", json!({"layer": f.layer.0, "prop": f.prop, "time": f.time.seconds()})) {
@@ -2033,6 +2172,11 @@ fn pen_press(
}
return;
}
// Clicking the last vertex of an open path (e.g. after Esc ended it) resumes drawing it.
if let Some(cur) = ov::open_end_at(paths, map, pos, 8.0) {
ui.data_mut(|d| d.insert_temp(pen_id(), cur));
return;
}
// On a visible path's segment the Pen adds a vertex there; on a motion path, a keyframe.
if let Some(f) = motion_frame {
add_motion_key(app, f);
@@ -2298,7 +2442,7 @@ fn create_shape(app: &mut EffectcraftApp, tool: Tool, a: [f64; 2], b: [f64; 2],
fn empty_state(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter();
let p = ui.painter().clone();
p.rect_filled(rect, 0.0, t.pasteboard);
let c = rect.center();
p.text(c - vec2(0.0, 40.0), Align2::CENTER_CENTER, crate::i18n::tr("Composition"), Tokens::semibold(16.0), t.text);
@@ -2312,6 +2456,36 @@ fn empty_state(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let _ = crate::menus::invoke(app, &ui.ctx().clone(), "file.import", json!({}));
}
app.auto.add("viewer.empty.import", b2, "New Composition From Footage");
// A Project item dropped on the empty viewer creates the first composition,
// just like dropping it onto an empty Timeline (#684). Multiple selected
// items use the existing New Comp from Selection dialog.
let ctx = ui.ctx().clone();
if let Some(crate::panels::DragPayload::Item(dragged)) = egui::DragAndDrop::payload::<crate::panels::DragPayload>(&ctx).as_deref()
&& ui.rect_contains_pointer(rect)
{
let items: Vec<effectcraft_engine::project::ItemId> = crate::panels::project_drop_items(app, *dragged)
.into_iter()
.map(effectcraft_engine::project::ItemId)
.filter(|id| {
app.session.project.item(*id).is_some_and(|item| match &item.kind {
effectcraft_engine::project::ItemKind::Footage(f) => f.kind != effectcraft_engine::project::FootageKind::Data,
effectcraft_engine::project::ItemKind::Solid(_) | effectcraft_engine::project::ItemKind::Comp(_) => true,
_ => false,
})
})
.collect();
if !items.is_empty() {
p.rect_stroke(rect.shrink(2.0), 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);
app.auto.add("viewer.newCompDrop", rect, "Drop footage to create a composition");
if ctx.input(|i| i.pointer.any_released()) {
app.session.state.project_selection = items;
if let Err(e) = crate::menus::invoke(app, &ctx, "file.newCompFromSelection", json!({})) {
app.ui.status = e;
}
egui::DragAndDrop::clear_payload(&ctx);
}
}
}
}
/// `#rrggbb` → sRGB bytes.
@@ -2330,21 +2504,32 @@ pub(crate) fn styled_line(painter: &egui::Painter, pts: [Pos2; 2], stroke: Strok
}
}
/// Texture filtering for Viewer Zoom Quality: More Accurate = bilinear, Faster = nearest.
/// `p` (points) moved to the nearest physical pixel corner at `ppp` pixels per point.
pub(crate) fn snap_to_pixels(p: Pos2, ppp: f32) -> Pos2 {
if !(ppp.is_finite() && ppp > 0.0 && p.x.is_finite() && p.y.is_finite()) {
return p;
}
pos2((p.x * ppp).round() / ppp, (p.y * ppp).round() / ppp)
}
/// Texture filtering for Viewer Zoom Quality: More Accurate = bilinear, Faster = nearest. As in
/// After Effects, a magnified frame (above 100 %, or a lower Resolution) always shows its pixels
/// as blocks, never smoothed, in either mode (#882).
pub(crate) fn zoom_texture_options(smooth: bool) -> egui::TextureOptions {
if smooth { egui::TextureOptions::LINEAR } else { egui::TextureOptions::NEAREST }
if smooth { egui::TextureOptions { magnification: egui::TextureFilter::Nearest, ..egui::TextureOptions::LINEAR } } else { egui::TextureOptions::NEAREST }
}
/// The sampler GPU frames (mipmapped display textures) are drawn with: More Accurate filters
/// bilinearly within and between mip levels, so a frame shown below 100 % is averaged instead of
/// skipping pixels (#417); Faster takes the nearest pixel of the full-size frame.
/// skipping pixels (#417); Faster takes the nearest pixel of the full-size frame. Magnified, both
/// show the nearest pixel (#882).
pub(crate) fn zoom_sampler(smooth: bool) -> eframe::wgpu::SamplerDescriptor<'static> {
use eframe::wgpu::{FilterMode, MipmapFilterMode, SamplerDescriptor};
let label = Some("viewer frame");
if smooth {
SamplerDescriptor {
label,
mag_filter: FilterMode::Linear,
mag_filter: FilterMode::Nearest,
min_filter: FilterMode::Linear,
mipmap_filter: MipmapFilterMode::Linear,
..Default::default()
@@ -2405,9 +2590,9 @@ fn show_frame(app: &mut EffectcraftApp, ctx: &egui::Context, key: crate::frames:
FrameImage::Cpu(img) => {
// Frames wider or taller than the GPU's texture limit go up averaged down too (#201).
let max = crate::frames::max_texture_side(ctx);
let fitted = crate::frames::fit_texture_by((*img).clone(), max, minify);
let fitted = crate::frames::fit_shared_texture_by(&img, max, minify);
match &mut app.viewer_tex {
Some((tex, k, m)) if tex.size() == fitted.size => {
Some((tex, k, m)) if tex.size() == fitted.size() => {
tex.set(fitted, opts);
(*k, *m) = (key, minify);
}
@@ -2442,6 +2627,35 @@ mod tests {
use super::*;
use effectcraft_engine::geom::{Mat4, vec3};
/// #882: the frame's corner sits on a physical pixel at any display scaling, so 100 % maps
/// comp pixels 1:1 onto screen pixels.
#[test]
fn frame_origin_snaps_to_physical_pixels() {
for ppp in [1.0f32, 1.25, 1.5, 1.75, 2.0] {
for p in [pos2(-201.12, 72.4), pos2(689.8, 239.75), pos2(0.3, -0.37)] {
let s = snap_to_pixels(p, ppp);
for v in [s.x * ppp, s.y * ppp] {
assert!((v - v.round()).abs() < 1e-3, "ppp {ppp}: {p:?} → {s:?}");
}
assert!((s - p).length() <= 0.71 / ppp, "moved by at most half a pixel: {p:?} → {s:?}");
}
}
assert_eq!(snap_to_pixels(pos2(1.3, 2.0), 0.0), pos2(1.3, 2.0));
}
/// #882: a magnified frame shows its pixels as blocks in both Zoom Quality modes; More
/// Accurate only smooths when the frame is shown smaller.
#[test]
fn magnified_frames_are_never_smoothed() {
use eframe::wgpu::FilterMode;
for smooth in [true, false] {
assert_eq!(zoom_texture_options(smooth).magnification, egui::TextureFilter::Nearest);
assert_eq!(zoom_sampler(smooth).mag_filter, FilterMode::Nearest);
}
assert_eq!(zoom_texture_options(true).minification, egui::TextureFilter::Linear);
assert_eq!(zoom_sampler(true).min_filter, FilterMode::Linear);
}
/// A perspective-like homography: w = 100 + y (the plane crosses the camera at y = −100).
fn tilted() -> Mat3 {
Mat3([[100.0, 0.0, 0.0], [0.0, 100.0, 0.0], [0.0, 1.0, 100.0]])
@@ -87,6 +87,15 @@ pub(crate) fn segment_at(paths: &[PathInfo], map: &ViewerMap, pos: Pos2, tol: f3
best.map(|b| b.1)
}
/// The open path whose last vertex lies within `tol` points of `pos`: the Pen resumes it there.
pub(crate) fn open_end_at(paths: &[PathInfo], map: &ViewerMap, pos: Pos2, tol: f32) -> Option<(LayerId, u64)> {
paths.iter().find_map(|p| {
let v = p.sp.vertices.last().filter(|_| !p.sp.closed)?;
let q = p.m.apply(gv2(v[0], v[1]));
(map.to_screen([q.x, q.y]).distance(pos) < tol).then_some((p.layer, p.uid))
})
}
/// A mask or shape path of a layer by group uid, evaluated at the context time.
pub(crate) fn path_of(ectx: &EvalCtx, layer: LayerId, uid: u64) -> Option<PathInfo> {
let l = ectx.comp.layer(layer)?;
@@ -640,3 +649,26 @@ pub(crate) fn update(
Drag::Roi { .. } => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn info(vertices: Vec<[f64; 2]>, closed: bool) -> PathInfo {
let n = vertices.len();
let sp = ShapePath { vertices, in_tangents: vec![[0.0; 2]; n], out_tangents: vec![[0.0; 2]; n], closed, feather: Vec::new() };
PathInfo { layer: LayerId(3), uid: 7, m: Mat3::IDENTITY, sp, is_mask: true, feather: Vec::new() }
}
/// #912: clicking the last vertex of an open path with the Pen resumes that path.
#[test]
fn pen_resumes_an_open_path_at_its_last_vertex() {
let map = ViewerMap { origin: Pos2::ZERO, zoom: 1.0, comp: [100.0, 100.0], area: Rect::EVERYTHING };
let open = info(vec![[10.0, 10.0], [50.0, 10.0], [50.0, 50.0]], false);
assert_eq!(open_end_at(std::slice::from_ref(&open), &map, egui::pos2(52.0, 49.0), 8.0), Some((LayerId(3), 7)));
assert_eq!(open_end_at(std::slice::from_ref(&open), &map, egui::pos2(10.0, 10.0), 8.0), None, "first vertex");
assert_eq!(open_end_at(std::slice::from_ref(&open), &map, egui::pos2(80.0, 80.0), 8.0), None, "far away");
let closed = info(vec![[10.0, 10.0], [50.0, 10.0], [50.0, 50.0]], true);
assert_eq!(open_end_at(&[closed], &map, egui::pos2(50.0, 50.0), 8.0), None, "closed path");
}
}
+27 -5
View File
@@ -26,6 +26,7 @@ use serde_json::{Value, json};
use super::viewer::ViewerMap;
use crate::EffectcraftApp;
use crate::dock::PanelKind;
use crate::state::Tool;
/// Pointer interaction owned by text editing (kept across frames while the button is down).
@@ -135,6 +136,21 @@ fn exec(app: &mut EffectcraftApp, id: &str, p: Value) -> Option<Value> {
}
}
/// The panels a text edit stays open across: the viewers, and Character, Paragraph and
/// Properties, which format the selected characters.
fn keeps_text_edit(p: PanelKind) -> bool {
super::viewers::id_of(p).is_some() || matches!(p, PanelKind::Character | PanelKind::Paragraph | PanelKind::Properties)
}
/// A click in panel `p`. Any other panel (the Timeline, the Project panel, …) ends the edit, as a
/// click outside the text does, and gives the keyboard back to the app (#831).
pub fn panel_clicked(app: &mut EffectcraftApp, ctx: &egui::Context, p: PanelKind) {
if app.session.state.text_edit.is_some() && !keeps_text_edit(p) {
exec(app, "text.endEdit", json!({}));
ctx.memory_mut(|m| m.surrender_focus(focus_id()));
}
}
/// Typing merge key: consecutive keystrokes fold into one undo step until the caret moves.
fn typing_key(ui: &egui::Ui, bump: bool) -> String {
let id = egui::Id::new("viewer-text-typing");
@@ -332,16 +348,18 @@ pub fn hook(
ui.memory_mut(|m| {
m.set_focus_lock_filter(focus_id(), egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true });
});
// A session started elsewhere (menu, agent, Properties) takes the keyboard once.
// A session started elsewhere (menu, agent, Properties) takes the keyboard once…
let seen = egui::Id::new("viewer-text-seen");
let key = app.session.state.text_edit.as_ref().map(|e| e.layer.0);
// …and gets it back whenever nothing else holds it (after a panel click, say).
if ui.data(|d| d.get_temp::<Option<u64>>(seen)).flatten() != key || ui.memory(|m| m.focused().is_none()) {
// …and gets it back when a click in the viewer or a formatting panel left nothing holding
// it; not merely because nothing has the focus (#831).
let regain = ui.memory(|m| m.focused().is_none()) && keeps_text_edit(app.ui.focused);
if ui.data(|d| d.get_temp::<Option<u64>>(seen)).flatten() != key || regain {
ui.data_mut(|d| d.insert_temp(seen, key));
ui.memory_mut(|m| m.request_focus(focus_id()));
}
if ui.memory(|m| m.has_focus(focus_id())) {
keyboard(app, ui);
keyboard(app, ui, resp.rect);
}
} else {
ui.data_mut(|d| d.insert_temp::<Option<u64>>(egui::Id::new("viewer-text-seen"), None));
@@ -359,12 +377,16 @@ pub fn hook(
owns
}
fn keyboard(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
/// This frame's keys, in order, into the edited text, up to a press outside the `viewer`: the
/// panel it lands in decides (after this frame's panels) whether the edit ends, so the keys after
/// it in this frame are neither typed nor run as shortcuts (#831).
fn keyboard(app: &mut EffectcraftApp, ui: &mut egui::Ui, viewer: Rect) {
let events = ui.input(|i| i.events.clone());
let ctx = ui.ctx().clone();
for ev in events {
let Some(sel) = app.session.state.text_edit.clone() else { return };
match ev {
egui::Event::PointerButton { pos, pressed: true, .. } if !viewer.contains(pos) => return,
egui::Event::Text(t) if !t.chars().any(char::is_control) => {
let k = typing_key(ui, false);
exec(app, "text.insert", json!({"text": t, "merge": k}));
+58 -30
View File
@@ -403,7 +403,8 @@ pub(crate) fn draw_frame(app: &mut EffectcraftApp, ctx: &egui::Context, painter:
_ => {
let img = crate::frames::to_color_image(&s.image);
let img = if plain { img } else { transformed(&img, opts.channel, opts.colorized, opts.exposure, dc) };
let tex = crate::frames::load_fitted(ctx, "viewer-snapshot", img, egui::TextureOptions::LINEAR);
let opts = super::viewer::zoom_texture_options(app.session.prefs.viewer_zoom_smooth());
let tex = crate::frames::load_fitted(ctx, "viewer-snapshot", img, opts);
ctx.data_mut(|d| d.insert_temp(id, (key, tex.clone())));
tex
}
@@ -509,6 +510,53 @@ fn toggle_popup(ui: &egui::Ui, id: &str) {
ui.data_mut(|d| d.insert_temp(pid, !open));
}
/// A magnification ratio dropdown (the Composition and Layer panels' footers): `zoom` is the
/// shown magnification and `current` the stored one (None = fit), both in points per pixel.
/// Returns the chosen magnification (`Some(None)` = Fit).
#[allow(clippy::too_many_arguments)]
pub(crate) fn magnification_menu(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
r: Rect,
id: &str,
auto_id: &str,
auto_items: &str,
zoom: f32,
current: Option<f32>,
fit_up: bool,
) -> Option<(Option<f32>, bool)> {
let t = app.tokens;
let ppp = ui.ctx().pixels_per_point();
let pop = format!("{id}-pop");
let response =
widgets::dropdown(ui, r, &magnification_label(zoom * ppp * 100.0), &t, egui::Id::new(id)).on_hover_text(crate::i18n::tr("Magnification ratio popup"));
if response.clicked() {
toggle_popup(ui, &pop);
}
app.auto.add_response(auto_id, &response, "Magnification");
const MAGS: [&str; 15] = ["Fit", "Fit up to 100%", "-", "1.5%", "3.1%", "6.25%", "12.5%", "25%", "33.3%", "50%", "100%", "200%", "400%", "800%", "1600%"];
let cur = (zoom * ppp * 100.0 * 10.0).round() / 10.0;
let items: Vec<(String, bool)> = MAGS
.iter()
.map(|m| {
let on = match *m {
"Fit" => current.is_none() && !fit_up,
"Fit up to 100%" => current.is_none() && fit_up,
s => s.trim_end_matches('%').parse::<f32>().is_ok_and(|v| current.is_some() && (v - cur).abs() < 0.06),
};
(m.to_string(), on)
})
.collect();
let i = popup(app, ui, &pop, r, &items, auto_items)?;
// `(zoom, fit up to 100 %)`: Fit and Fit up to 100% leave the zoom unset (it follows the
// panel size).
match *MAGS.get(i)? {
"Fit" => Some((None, false)),
"Fit up to 100%" => Some((None, true)),
s => s.trim_end_matches('%').parse::<f32>().ok().map(|v| (Some(v / 100.0 / ppp), false)),
}
}
/// Magnification as After Effects shows it: "136.1 %", "100 %".
pub(crate) fn magnification_label(pct: f32) -> String {
if (pct - pct.round()).abs() < 0.05 { format!("{:.0} %", pct.round()) } else { format!("{pct:.1} %") }
@@ -538,7 +586,7 @@ pub(crate) fn resolution_label(res: Resolution, scale: f64) -> String {
/// transparency grid, mask and shape path visibility, region of interest, grid and guide
/// options, show channel, reset exposure, exposure, take / show snapshot, Fast Previews, the 3D
/// renderer and view, and the current time.
pub(crate) fn bottom_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, zoom: f32, fit: f32, time: Tick, comp: &Comp) {
pub(crate) fn bottom_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, zoom: f32, time: Tick, comp: &Comp) {
let t = app.tokens;
let p = ui.painter().clone();
p.rect_filled(bar, 0.0, t.panel_bg);
@@ -554,7 +602,7 @@ pub(crate) fn bottom_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect,
egui::ScrollArea::horizontal().id_salt("viewer-controls").auto_shrink([false, false]).show(ui, |ui| {
let row = Rect::from_min_size(ui.max_rect().min, vec2(bar.width(), 30.0));
let first_control = app.auto.elements.len();
let width = bottom_bar_contents(app, ui, row, zoom, fit, time, comp);
let width = bottom_bar_contents(app, ui, row, zoom, time, comp);
ui.allocate_rect(Rect::from_min_size(row.min, vec2(width, row.height())), Sense::hover());
if let Some(focused) = ui.ctx().memory(|memory| memory.focused())
&& app.auto.elements.get(first_control..).is_some_and(|controls| controls.iter().any(|control| control.response_id == Some(focused)))
@@ -567,7 +615,7 @@ pub(crate) fn bottom_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect,
});
}
fn bottom_bar_contents(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, zoom: f32, fit: f32, time: Tick, comp: &Comp) -> f32 {
fn bottom_bar_contents(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, zoom: f32, time: Tick, comp: &Comp) -> f32 {
let t = app.tokens;
let p = ui.painter().clone();
let cy = bar.center().y;
@@ -576,44 +624,24 @@ fn bottom_bar_contents(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, z
// Magnification.
let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(80.0, 20.0));
let response = widgets::dropdown(ui, r, &magnification_label(zoom * ppp * 100.0), &t, egui::Id::new("vw-mag"))
.on_hover_text(crate::i18n::tr("Magnification ratio popup"));
if response.clicked() {
toggle_popup(ui, "vw-mag-pop");
}
app.auto.add_response("viewer.magnification", &response, "Magnification");
const MAGS: [&str; 15] = ["Fit", "Fit up to 100%", "-", "1.5%", "3.1%", "6.25%", "12.5%", "25%", "33.3%", "50%", "100%", "200%", "400%", "800%", "1600%"];
let cur = (zoom * ppp * 100.0 * 10.0).round() / 10.0;
let items: Vec<(String, bool)> = MAGS
.iter()
.map(|m| {
let on = match *m {
"Fit" => app.ui.viewer.zoom.is_none(),
s => s.trim_end_matches('%').parse::<f32>().is_ok_and(|v| app.ui.viewer.zoom.is_some() && (v - cur).abs() < 0.06),
};
(m.to_string(), on)
})
.collect();
if let Some(i) = popup(app, ui, "vw-mag-pop", r, &items, "magnification") {
let fit_up = app.ui.viewer.fit_up_to_100;
if let Some((z, up)) = magnification_menu(app, ui, r, "vw-mag", "viewer.magnification", "magnification", zoom, app.ui.viewer.zoom, fit_up) {
app.ui.viewer.pan = [0.0, 0.0];
app.ui.viewer.zoom = match MAGS[i] {
"Fit" => None,
"Fit up to 100%" => Some(fit.min(1.0 / ppp)),
s => s.trim_end_matches('%').parse::<f32>().ok().map(|v| v / 100.0 / ppp),
};
app.ui.viewer.fit_up_to_100 = up;
app.ui.viewer.zoom = z;
}
x = r.max.x + 4.0;
// Resolution / down-sample factor.
let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(84.0, 20.0));
let scale = app.viewer_scale(zoom, ppp);
let response = widgets::dropdown(ui, r, &resolution_label(app.ui.viewer.res, scale), &t, egui::Id::new("vw-res"))
let res = app.viewer_res();
let response = widgets::dropdown(ui, r, &resolution_label(res, scale), &t, egui::Id::new("vw-res"))
.on_hover_text(crate::i18n::tr("Resolution/Down Sample Factor Popup"));
if response.clicked() {
toggle_popup(ui, "vw-res-pop");
}
app.auto.add_response("viewer.resolution", &response, "Resolution/Down Sample Factor");
let res = app.ui.viewer.res;
let items: Vec<(String, bool)> = vec![
("Full".into(), res == Resolution::Full),
("Half".into(), res == Resolution::Half),
+31 -2
View File
@@ -7,7 +7,8 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use effectcraft_engine::project::{ItemId, ItemKind, Layer, LayerSource, Project};
use effectcraft_engine::project::{ItemId, ItemKind, Layer, LayerSource, Project, Property};
use effectcraft_engine::render::audio::db_to_gain;
use effectcraft_engine::time::Tick;
use egui::{Color32, Painter, Rect, Stroke, pos2};
@@ -75,6 +76,17 @@ pub fn summary(app: &EffectcraftApp, ctx: &egui::Context, item: ItemId) -> Optio
None
}
/// Left/right gain of the layer's Audio Levels (dB) at comp time `t`; unity without the property.
fn level_gains(levels: Option<&Property>, t: Tick) -> [f32; 2] {
match levels {
Some(p) => {
let [l, r] = p.value_at(t).as_vec2();
[db_to_gain(l), db_to_gain(r)]
}
None => [1.0, 1.0],
}
}
/// 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) {
@@ -83,6 +95,7 @@ pub(crate) fn draw(p: &Painter, rect: Rect, tm: &TMap, layer: &Layer, s: &Summar
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;
let levels = layer.props.sub("audio").and_then(|g| g.get("levels"));
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)));
}
@@ -101,10 +114,26 @@ pub(crate) fn draw(p: &Painter, rect: Rect, tm: &TMap, layer: &Layer, s: &Summar
agg[2] = agg[2].min(b[2]);
agg[3] = agg[3].max(b[3]);
}
let gain = level_gains(levels, Tick::from_seconds_f64((ta + tb) * 0.5));
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 (lo, hi) = ((agg[c * 2] * gain[c]).clamp(-1.0, 1.0), (agg[c * 2 + 1] * gain[c]).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));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use effectcraft_engine::project::Value;
#[test]
fn waveform_follows_audio_levels() {
let p = Property::new(1, "levels", "Audio Levels", Value::Vec2([-6.0206, -96.0]));
let g = level_gains(Some(&p), Tick::ZERO);
assert!((g[0] - 0.5).abs() < 1e-3, "{}", g[0]);
assert_eq!(g[1], 0.0);
assert_eq!(level_gains(None, Tick::ZERO), [1.0, 1.0]);
}
}
+6 -1
View File
@@ -91,14 +91,19 @@ pub fn dropped_files(app: &mut EffectcraftApp, ui: &egui::Ui, bounds: Rect) {
// Dropped files import as stills and folders' numbered stills as sequences; Alt-drag
// imports a folder's files one by one (After Effects).
let alt = ctx.input(|i| i.modifiers.alt);
// A dropped Photoshop file asks how to import it (the Import Photoshop File dialog, its
// Import Kind starting at Default Drag Import As), as File ▸ Import ▸ File… does (#678).
let layered = rest.iter().any(|p| p.rsplit('.').next().is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "psd" | "psb")));
let mut params = json!({
"paths": rest,
"drag": true,
"importAs": app.session.prefs.drag_import_as(),
"addToComp": at.is_some(),
"position": at,
"background": true
});
if !layered {
params["importAs"] = json!(app.session.prefs.drag_import_as());
}
if alt {
params["sequence"] = json!(false);
}
+34 -45
View File
@@ -229,58 +229,19 @@ impl Tool {
}
}
/// Viewer resolution (Auto follows the magnification).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Resolution {
#[default]
Auto,
Full,
Half,
Third,
Quarter,
/// View ▸ Resolution ▸ Custom: render every n-th pixel (2..=40).
Custom(u8),
}
impl Resolution {
pub const ALL: [Resolution; 5] = [Resolution::Auto, Resolution::Full, Resolution::Half, Resolution::Third, Resolution::Quarter];
pub fn label(self) -> &'static str {
match self {
Resolution::Auto => "Auto",
Resolution::Full => "Full",
Resolution::Half => "Half",
Resolution::Third => "Third",
Resolution::Quarter => "Quarter",
Resolution::Custom(_) => "Custom",
}
}
/// Render scale for a viewer magnification (and display pixel density).
pub fn scale(self, zoom: f32, ppp: f32) -> f64 {
match self {
// As in After Effects, Auto renders the pixels the magnification needs: the coarsest
// whole factor that still gives every screen pixel a rendered one (Full above 50 %,
// Half down to 33.3 %, Third down to 25 %, Quarter below), never fewer (#417).
Resolution::Auto => {
let n = (1.0 / (zoom * ppp) as f64 + 1e-3).floor();
if n >= 1.0 { 1.0 / n.min(4.0) } else { 1.0 }
}
Resolution::Full => 1.0,
Resolution::Half => 0.5,
Resolution::Third => 1.0 / 3.0,
Resolution::Quarter => 0.25,
Resolution::Custom(n) => 1.0 / n.max(1) as f64,
}
}
}
/// The viewer's Resolution: each composition keeps its own in the project
/// ([`effectcraft_engine::project::Comp::resolution`], `EffectcraftApp::viewer_res`).
pub use effectcraft_engine::project::Resolution;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct ViewerState {
/// Magnification (1 = 100%); None = fit.
pub zoom: Option<f32>,
/// Fit up to 100%: while fitting (`zoom` is None), the comp is never magnified past 100%.
pub fit_up_to_100: bool,
/// Pan offset in points from the centred position.
pub pan: [f32; 2],
pub res: Resolution,
pub transparency_grid: bool,
pub show_masks: bool,
pub safe_margins: bool,
@@ -318,8 +279,8 @@ impl Default for ViewerState {
fn default() -> Self {
ViewerState {
zoom: None,
fit_up_to_100: false,
pan: [0.0, 0.0],
res: Resolution::Auto,
transparency_grid: false,
show_masks: true,
safe_margins: false,
@@ -493,6 +454,15 @@ pub struct FxPick {
pub name: String,
}
/// A Character panel Fill or Stroke eyedropper waiting for a Composition viewer click.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TextColorPick {
pub layer: u64,
pub field: String,
/// Preserve the edited character range when focus moves from the panel to the viewer.
pub range: Option<[usize; 2]>,
}
/// Effects & Presets contents-menu options.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EffectsView {
@@ -571,6 +541,10 @@ pub struct UiState {
/// Floating panels of the saved workspaces.
#[serde(default)]
pub saved_floating: std::collections::BTreeMap<String, Vec<crate::dock::Floating>>,
/// Floating groups shown in their own native window instead of over the dock (Move Panel
/// to New Window), so they can be placed on another monitor.
#[serde(default)]
pub panel_windows: Vec<crate::dock::PanelWindow>,
/// The panel maximized to fill the dock area (`~`), if any.
#[serde(default)]
pub maximized: Option<PanelKind>,
@@ -620,6 +594,9 @@ pub struct UiState {
/// Effect Controls: a point crosshair or colour eyedropper waiting for a viewer click.
#[serde(default)]
pub fx_pick: Option<FxPick>,
/// Character panel colour eyedropper waiting for a viewer click.
#[serde(default)]
pub text_color_pick: Option<TextColorPick>,
/// Curves editor: shown channel (index into RGB/Red/Green/Blue/Alpha) per effect uid.
#[serde(default)]
pub fx_curve_channel: BTreeMap<u64, usize>,
@@ -660,6 +637,14 @@ pub struct UiState {
/// Layer panel View: number of effects rendered (None = through the last Paint effect).
#[serde(default)]
pub layer_view: Option<usize>,
/// Layer panel magnification in points per layer pixel (None = fit), set by its
/// magnification menu, View ▸ Zoom In / Zoom Out while it is focused, the mouse wheel and the
/// Zoom tool.
#[serde(default)]
pub layer_zoom: Option<f32>,
/// Layer panel pan offset in points from the centred position (Hand tool, Space-drag).
#[serde(default)]
pub layer_pan: [f32; 2],
/// Wiggler / Smoother / Motion Sketch settings.
#[serde(default)]
pub anim_tools: AnimToolsState,
@@ -685,6 +670,7 @@ impl Default for UiState {
saved_workspaces: Default::default(),
floating: vec![],
saved_floating: Default::default(),
panel_windows: vec![],
maximized: None,
locked_tabs: BTreeSet::new(),
viewers: Default::default(),
@@ -707,6 +693,7 @@ impl Default for UiState {
fx_closed: BTreeSet::new(),
fx_slider_open: BTreeSet::new(),
fx_pick: None,
text_color_pick: None,
fx_curve_channel: BTreeMap::new(),
fx_curve_pencil: BTreeSet::new(),
fx_levels_channel: BTreeMap::new(),
@@ -722,6 +709,8 @@ impl Default for UiState {
tracker_source: None,
layer_panel: None,
layer_view: None,
layer_zoom: None,
layer_pan: [0.0, 0.0],
anim_tools: AnimToolsState::default(),
mini_flowchart: None,
flowchart: Default::default(),
+20
View File
@@ -340,6 +340,13 @@ pub fn install(ctx: &egui::Context, t: &Tokens, language: &str) {
fonts.families.entry(FontFamily::Monospace).or_default().insert(0, "jbmono".into());
fonts.families.insert(FontFamily::Name("semibold".into()), vec!["inter-semibold".into(), "inter".into()]);
fonts.families.insert(FontFamily::Name("medium".into()), vec!["inter-medium".into(), "inter".into()]);
// Inter and egui's own fallbacks have no small triangles (the `▸` of "File ▸ Import"), which
// would draw as missing-glyph boxes: JetBrains Mono fills in the symbols the others lack.
for (family, stack) in &mut fonts.families {
if *family != FontFamily::Monospace {
stack.push("jbmono".into());
}
}
install_script_fallbacks(&mut fonts, language);
ctx.set_fonts(fonts);
apply_visuals(ctx, t);
@@ -649,6 +656,19 @@ mod tests {
install_script_fallbacks(&mut english, "en");
}
#[test]
fn interface_symbols_have_a_glyph_in_every_family() {
let ctx = egui::Context::default();
install(&ctx, &Tokens::for_kind(Default::default()), "en");
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
for family in [FontFamily::Proportional, FontFamily::Monospace, FontFamily::Name("medium".into()), FontFamily::Name("semibold".into())] {
let id = FontId::new(12.0, family);
for c in "▸•›·▶◀●○⚠…×".chars() {
assert!(ctx.fonts_mut(|f| f.has_glyph(&id, c)), "{c} has no glyph in {id:?}");
}
}
}
#[test]
fn hangul_gets_a_face_when_one_is_installed() {
use effectcraft_text::fonts;
+55 -1
View File
@@ -121,7 +121,7 @@ pub fn hot_number_at(
let mult = ui.input(|i| {
if i.modifiers.shift {
10.0
} else if i.modifiers.command {
} else if i.modifiers.command && !proportional_scrub(i.modifiers) {
0.1
} else {
1.0
@@ -138,6 +138,13 @@ pub fn hot_number_at(
(rect, out, resp.drag_stopped())
}
/// Ctrl+Alt (Cmd+Opt on macOS) held while scrubbing hot text: After Effects' Proportional
/// Scrubbing, which spreads the change over the selected layers by selection order. Ctrl alone
/// still scrubs finely and Shift by tens.
pub fn proportional_scrub(m: egui::Modifiers) -> bool {
m.command && m.alt
}
/// [`hot_number_at`] for a whole number (an angle's revolutions): a drag steps it once every
/// `1 / speed` pixels however slowly the pointer moves (the fractions add up between frames),
/// and a typed value is truncated. Returns (rect, Some(new value) when changed, drag finished).
@@ -187,6 +194,24 @@ pub fn keep_focus(ctx: &egui::Context, field: &Response, text: &str) {
}
}
/// Put the keyboard on a dialog's first text field the frame the dialog opens, with its whole
/// `text` selected, so typing replaces the value without a click. Unlike [`keep_focus`] the
/// focus is the user's afterwards.
pub fn focus_on_open(ctx: &egui::Context, field: &Response, text: &str) {
// The dialog is open in consecutive passes; a gap means it was closed and opened again.
let shown = field.id.with("focus-on-open-pass");
let pass = ctx.cumulative_pass_nr();
let previous = ctx.data_mut(|d| {
let previous = d.get_temp::<u64>(shown);
d.insert_temp(shown, pass);
previous
});
if previous.is_none_or(|p| p.saturating_add(1) < pass) {
select_all(ctx, field.id, text);
field.request_focus();
}
}
/// Select all of the text field `id`'s `text`, so typing replaces it.
pub fn select_all(ctx: &egui::Context, id: egui::Id, text: &str) {
let mut state = egui::TextEdit::load_state(ctx, id).unwrap_or_default();
@@ -307,6 +332,11 @@ fn field(ui: &mut Ui, rect: Rect, text: &mut String, hint: &str, t: &Tokens, sea
/// Dropdown-looking control ("Full ▾").
pub fn dropdown(ui: &mut Ui, rect: Rect, text: &str, t: &Tokens, id: egui::Id) -> Response {
dropdown_tip(ui, rect, text, None, t, id)
}
/// [`dropdown`] with a tooltip `tip` (shown always; it replaces the elided text's tooltip).
pub fn dropdown_tip(ui: &mut Ui, rect: Rect, text: &str, tip: Option<&str>, t: &Tokens, id: egui::Id) -> Response {
let resp = ui.interact(rect, id, Sense::click());
ui.painter().rect_filled(rect, 3.0, if resp.hovered() { t.hover } else { t.field_bg });
ui.painter().rect_stroke(rect, 3.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
@@ -328,6 +358,9 @@ pub fn dropdown(ui: &mut Ui, rect: Rect, text: &str, t: &Tokens, id: egui::Id) -
};
ui.painter().text(pos2(rect.min.x + 7.0, rect.center().y), Align2::LEFT_CENTER, shown, Tokens::ui(11.5), t.text);
icons::paint(ui.painter(), Rect::from_center_size(pos2(rect.max.x - 9.0, rect.center().y), vec2(8.0, 8.0)), Icon::ChevronDown, t.text_dim);
if let Some(tip) = tip {
return resp.on_hover_text(tip.to_string());
}
if text.chars().count() > 0 && !fits(text) {
return resp.on_hover_text(text.to_string());
}
@@ -579,6 +612,27 @@ pub fn menu_scroll<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R {
egui::ScrollArea::vertical().max_height(max_h).min_scrolled_height(max_h).show(ui, add).inner
}
/// egui's menu style with no gap between the rows: the gap the app's item spacing left between
/// two entries highlighted neither and swallowed a click there. The rows grow by that gap, so a
/// menu keeps its size.
pub fn menu_style(style: &mut egui::Style) {
egui::containers::menu::menu_style(style);
style.spacing.interact_size.y += style.spacing.item_spacing.y;
style.spacing.item_spacing.y = 0.0;
}
/// `resp`'s context menu in the app's [`menu_style`] (its submenus inherit it).
pub fn context_menu(resp: &Response, add_contents: impl FnOnce(&mut Ui)) -> Option<egui::InnerResponse<()>> {
egui::Popup::context_menu(resp).style(menu_style).show(add_contents)
}
/// A button opening a menu in the app's [`menu_style`], for one outside the menu bar.
pub fn menu_button<'a, R>(ui: &mut Ui, atoms: impl egui::IntoAtoms<'a>, add_contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<Option<R>> {
let config = egui::containers::menu::MenuConfig::new().style(menu_style);
let (response, inner) = egui::containers::menu::MenuButton::new(atoms).config(config).ui(ui, add_contents);
egui::InnerResponse::new(inner.map(|i| i.inner), response)
}
/// Whether a [`popup_menu`] is open (build its options only then: they can be long).
pub fn popup_is_open(ui: &Ui, id: egui::Id) -> bool {
ui.data(|d| d.get_temp(id.with("open")).unwrap_or(false))
+18 -2
View File
@@ -5,7 +5,7 @@ use std::collections::BTreeMap;
use effectcraft_engine::config::ConfigStore;
use serde::{Deserialize, Serialize};
use crate::dock::{DockNode, Floating, PanelKind, SplitSize};
use crate::dock::{DockNode, Floating, PanelKind, PanelWindow, SplitSize};
use crate::state::UiState;
const FILE: &str = "workspaces.json";
@@ -28,6 +28,9 @@ struct Snapshot {
maximized: Option<PanelKind>,
saved_workspaces: BTreeMap<String, DockNode>,
saved_floating: BTreeMap<String, Vec<Floating>>,
/// Floating groups in their own native window (absent from files of earlier versions).
#[serde(default)]
panel_windows: Vec<PanelWindow>,
}
impl Snapshot {
@@ -41,6 +44,7 @@ impl Snapshot {
maximized: ui.maximized,
saved_workspaces: ui.saved_workspaces.clone(),
saved_floating: ui.saved_floating.clone(),
panel_windows: ui.panel_windows.clone(),
}
}
@@ -52,6 +56,14 @@ impl Snapshot {
ui.maximized = self.maximized;
ui.saved_workspaces = self.saved_workspaces;
ui.saved_floating = self.saved_floating;
// A window is only kept for a panel that still floats, and only where a window can be.
let floating = |panel: PanelKind| ui.floating.iter().any(|group| group.panels.contains(&panel));
ui.panel_windows = self
.panel_windows
.into_iter()
.filter(|window| floating(window.panel))
.map(|window| PanelWindow { panel: window.panel, rect: PanelWindow::sanitized(window.rect) })
.collect();
// Reserve restored viewer slots without restoring any project-specific composition
// links. New Viewer allocates from this map, including after switching named layouts.
let mut panels = Vec::new();
@@ -89,7 +101,7 @@ impl Snapshot {
PanelKind::Viewer(id) => (1..=MAX_VIEWER_ID).contains(&id),
_ => true,
};
if !panel_ok(self.focused) || self.maximized.is_some_and(|panel| !panel_ok(panel)) {
if !panel_ok(self.focused) || self.maximized.is_some_and(|panel| !panel_ok(panel)) || self.panel_windows.iter().any(|w| !panel_ok(w.panel)) {
return Err("workspace viewer ID is outside the supported range 1–65535".into());
}
let mut nodes = 0usize;
@@ -134,6 +146,9 @@ impl Snapshot {
}
}
}
if self.panel_windows.len() > MAX_PANELS || self.panel_windows.iter().any(|w| !w.rect.iter().all(|v| v.is_finite())) {
return Err("invalid workspace panel windows".into());
}
for groups in std::iter::once(&self.floating).chain(self.saved_floating.values()) {
if groups.len() > MAX_PANELS {
return Err("too many floating workspace groups".into());
@@ -229,6 +244,7 @@ impl WorkspaceStore {
|| self.saved.maximized != ui.maximized
|| self.saved.saved_workspaces != ui.saved_workspaces
|| self.saved.saved_floating != ui.saved_floating
|| self.saved.panel_windows != ui.panel_windows
}
pub(crate) fn save(&mut self, config: Option<&dyn ConfigStore>, ui: &UiState) -> Result<bool, String> {
+70
View File
@@ -3,6 +3,7 @@
//! --test ui_3d -- --ignored`); the other test only runs the UI logic.
use effectcraft_engine::Session;
use effectcraft_engine::render::three_d::View3D;
use effectcraft_ui_egui::EffectcraftApp;
use egui_kittest::Harness;
use serde_json::json;
@@ -195,3 +196,72 @@ fn extended_viewer_renders_past_the_comp_frame() {
h.step();
assert!(h.state().ui.viewer.extended.is_none());
}
/// #875: the Top / Front / Right views of a 4-view layout draw the camera wireframe (they drew
/// none, so moving the camera showed nothing there), and it follows the camera's Position.
#[test]
fn layout_views_draw_the_camera_and_follow_its_position() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "C", "width": 640, "height": 360, "duration": 2})).unwrap();
let solid = s.execute("layer.newSolid", json!({"color": "#ff0000", "width": 200, "height": 200})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setSwitch", json!({"layer": solid, "switch": "threeD", "value": true})).unwrap();
let cam = s.execute("layer.newCamera", json!({"position": [320, 180, -300], "poi": [320, 180, 0]})).unwrap()["layer"].as_u64().unwrap();
s.execute("view.layout", json!({"views": 4})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
settle(&mut h);
let centre = |h: &Harness<'_, EffectcraftApp>, view: &str| {
let id = format!("viewer.view.{view}.camera.{cam}");
let [x, y, w, hh] = h.state().auto.find(&id).unwrap_or_else(|| panic!("{id} is registered")).rect;
(x + w / 2.0, y + hh / 2.0)
};
for v in ["top", "front", "right"] {
centre(&h, v);
}
let before = centre(&h, "top");
h.state_mut().session.execute("prop.set", json!({"layer": cam, "path": "transform/position", "value": [480, 180, -300]})).unwrap();
settle(&mut h);
let after = centre(&h, "top");
assert!(after.0 - before.0 > 10.0, "the camera moves right in the Top view: {before:?} -> {after:?}");
assert!((after.1 - before.1).abs() < 1.0, "{before:?} -> {after:?}");
}
/// A 4-view layout over a comp with a 3D solid and a camera.
fn four_views() -> Harness<'static, EffectcraftApp> {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "C", "width": 640, "height": 360, "duration": 2})).unwrap();
let solid = s.execute("layer.newSolid", json!({"color": "#ff0000", "width": 200, "height": 200})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setSwitch", json!({"layer": solid, "switch": "threeD", "value": true})).unwrap();
s.execute("layer.newCamera", json!({"position": [320, 180, -300], "poi": [320, 180, 0]})).unwrap();
s.execute("view.layout", json!({"views": 4})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
settle(&mut h);
h
}
/// #670: every pane of a multi-view layout has its own view selector; choosing a view changes
/// that pane (its camera and its wireframes) and no other, and it is remembered for the comp.
#[test]
fn each_layout_pane_chooses_its_own_view() {
let mut h = four_views();
let present = |h: &Harness<'_, EffectcraftApp>, view: &str| h.state().auto.find(&format!("viewer.view.{view}")).is_some();
let has_camera = |h: &Harness<'_, EffectcraftApp>, view: &str| h.state().auto.query(&format!("viewer.view.{view}.camera.")).len() == 1;
for p in 1..=3 {
assert!(h.state().auto.find(&format!("viewer.view.{p}.type")).is_some(), "pane {p} has a selector");
}
assert!(present(&h, "front") && has_camera(&h, "front"));
// Pane 2 (the Front view) becomes the Left view.
let left = View3D::ALL.iter().position(|v| *v == View3D::Left).unwrap();
click_id(&mut h, "viewer.view.2.type");
click_id(&mut h, &format!("viewer.view.2.typeItem.{left}"));
settle(&mut h);
assert_eq!(h.state().auto.find("viewer.view.2.type").unwrap().label, "View of pane");
assert!(present(&h, "left") && has_camera(&h, "left"), "pane 2 shows the Left view with its wireframe");
assert!(!present(&h, "front"), "pane 2 no longer shows Front");
assert!(present(&h, "top") && present(&h, "right"), "the other panes keep their views");
let cid = h.state().session.active_comp_id().unwrap();
assert_eq!(h.state().session.state.views3d[&cid].pane(1), View3D::Left);
// The Active Camera view of a pane does not draw the camera it looks through.
h.state_mut().session.execute("view.setPaneView", json!({"pane": 1, "view": "activeCamera"})).unwrap();
settle(&mut h);
assert!(present(&h, "activeCamera") && !has_camera(&h, "activeCamera"));
}
+32 -1
View File
@@ -1,6 +1,6 @@
//! Right-click actions in the blank Project and Timeline areas, and on Timeline property names.
use effectcraft_engine::Session;
use effectcraft_ui_egui::{Dialog, EffectcraftApp};
use effectcraft_ui_egui::{Dialog, EffectcraftApp, dock::PanelKind};
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, pos2, vec2};
use egui_kittest::{Harness, kittest::Queryable as _};
use serde_json::json;
@@ -132,6 +132,23 @@ fn timeline_blank_menu_opens_composition_settings() {
assert_eq!(h.state().dialog, Some(Dialog::CompSettings));
}
#[test]
fn timeline_blank_menu_opens_current_comp_in_essential_graphics() {
for graph in [false, true] {
let mut h = harness();
let comp = h.state().session.active_comp_id().unwrap();
let area = rect(&h, "timeline.layerMarquee");
let p = if graph { pos2(area.max.x + 150.0, area.center().y) } else { area.center() };
right_click(&mut h, p);
let target = if graph { "timeline.context.graph.essentialGraphics" } else { "timeline.context.outline.essentialGraphics" };
assert!(h.state().auto.find(target).is_some());
h.get_by_label("Open in Essential Graphics").click();
h.run_steps(3);
assert_eq!(h.state().session.state.essential_primary, Some(comp));
assert!(h.state().ui.dock.contains(PanelKind::EssentialGraphics));
}
}
/// #407: right-clicking a property's name in the Timeline opens After Effects' property menu:
/// Reset, Edit Value…, Separate Dimensions (Position only, checked once separated), Add or
/// Remove Expression and Add Property to Essential Graphics.
@@ -195,3 +212,17 @@ fn timeline_property_names_have_the_property_menu() {
choose(&mut h, scale, "editValue");
assert_eq!(h.state().dialog, Some(Dialog::Form));
}
/// The rows of a context menu touch: a gap between two entries highlighted neither and
/// swallowed a click there.
#[test]
fn context_menu_rows_leave_no_gap_between_them() {
let mut h = harness();
let p = rect(&h, "project.empty").center();
right_click(&mut h, p);
let rows = ["newComp", "newFolder", "import"].map(|key| rect(&h, &format!("project.context.{key}")));
for pair in rows.windows(2) {
assert!((pair[1].top() - pair[0].bottom()).abs() < 0.5, "gap between {:?} and {:?}", pair[0], pair[1]);
}
snapshot(&mut h, "project-rows");
}
@@ -0,0 +1,96 @@
//! Character Fill and Stroke can sample a displayed Composition pixel.
use effectcraft_engine::{Session, commands::text_edit::layer_doc, project::LayerId};
use effectcraft_ui_egui::{
EffectcraftApp,
dock::{DockNode, PanelKind, SplitSize},
panels::viewer::comp_to_screen,
};
use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
fn click(h: &mut Harness<'_, EffectcraftApp>, pos: Pos2) {
h.event(Event::PointerMoved(pos));
h.step();
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(2);
}
fn click_auto(h: &mut Harness<'_, EffectcraftApp>, id: &str) {
let e = h.state().auto.find(id).unwrap_or_else(|| panic!("missing {id}")).clone();
click(h, pos2(e.rect[0] + e.rect[2] * 0.5, e.rect[1] + e.rect[3] * 0.5));
}
fn settle(h: &mut Harness<'_, EffectcraftApp>) {
for _ in 0..600 {
h.step();
if h.state().frames.inflight() == 0 && h.state().frames.last_ms.lock().is_ok_and(|v| *v > 0.0) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
h.run_steps(4);
}
#[test]
fn character_fill_eyedropper_samples_viewer_and_keeps_text_selection() {
let mut s = Session::default();
s.execute("comp.new", json!({"width": 320, "height": 180, "duration": 2})).unwrap();
s.execute("layer.newSolid", json!({"name": "Background", "color": "#20c040"})).unwrap();
let text = s.execute("layer.newText", json!({"text": "First second", "font": "Inter"})).unwrap()["layer"].as_u64().unwrap();
s.execute("text.edit", json!({"layer": text})).unwrap();
s.execute("text.setSelection", json!({"start": 0, "end": 5})).unwrap();
let mut app = EffectcraftApp::new(s);
app.set_workspace("Text");
let builder = Harness::builder().with_size(vec2(1600.0, 1400.0));
let mut h = if std::env::var_os("EC_SNAPSHOT_DIR").is_some() { builder.wgpu().build_eframe(|_| app) } else { builder.build_eframe(|_| app) };
h.state_mut().show_panel(PanelKind::Character);
settle(&mut h);
click_auto(&mut h, "character.fill.eyedropper");
assert_eq!(h.state().ui.text_color_pick.as_ref().unwrap().range, Some([0, 5]));
let sample = comp_to_screen(&h.ctx, [20.0, 20.0]).unwrap();
click(&mut h, sample);
assert!(h.state().ui.text_color_pick.is_none());
let doc = layer_doc(&h.state().session, LayerId(text)).unwrap();
let want = [0x20 as f32 / 255.0, 0xc0 as f32 / 255.0, 0x40 as f32 / 255.0];
for (actual, expected) in doc.style_at(0).fill.iter().zip(want) {
assert!((actual - expected).abs() < 0.02);
}
assert_ne!(doc.style_at(8).fill, doc.style_at(0).fill, "unselected text keeps its colour");
}
#[test]
fn character_stroke_eyedropper_samples_viewer() {
let mut s = Session::default();
s.execute("comp.new", json!({"width": 320, "height": 180, "duration": 2})).unwrap();
s.execute("layer.newSolid", json!({"name": "brat green", "color": "#8ACE00"})).unwrap();
let text = s.execute("layer.newText", json!({"text": "brat", "font": "Inter"})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setText", json!({"layer": text, "fill": [0.0, 0.0, 0.0], "size": 32.0})).unwrap();
let mut app = EffectcraftApp::new(s);
app.ui.viewer.show_layer_controls = false;
app.ui.dock = DockNode::Split {
vertical: false,
size: SplitSize::FixedB(360.0),
a: Box::new(DockNode::Tabs { panels: vec![PanelKind::Composition], active: 0 }),
b: Box::new(DockNode::Tabs { panels: vec![PanelKind::Character], active: 0 }),
};
let builder = Harness::builder().with_size(vec2(1200.0, 760.0));
let mut h = if std::env::var_os("EC_SNAPSHOT_DIR").is_some() { builder.wgpu().build_eframe(|_| app) } else { builder.build_eframe(|_| app) };
h.state_mut().show_panel(PanelKind::Character);
h.state_mut().show_panel(PanelKind::Composition);
settle(&mut h);
click_auto(&mut h, "character.stroke.eyedropper");
if let Ok(dir) = std::env::var("EC_SNAPSHOT_DIR") {
h.render().unwrap().save(format!("{dir}/character-eyedropper.png")).unwrap();
}
let sample = comp_to_screen(&h.ctx, [20.0, 20.0]).unwrap();
click(&mut h, sample);
let doc = layer_doc(&h.state().session, LayerId(text)).unwrap();
let want = [0x8a as f32 / 255.0, 0xce as f32 / 255.0, 0.0];
for (actual, expected) in doc.stroke.iter().zip(want) {
assert!((actual - expected).abs() < 0.02);
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Composition Settings: saving, picking and deleting your own presets (egui_kittest).
use effectcraft_engine::Session;
use effectcraft_ui_egui::{Dialog, EffectcraftApp};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2};
use egui_kittest::Harness;
use serde_json::json;
fn harness() -> Harness<'static, EffectcraftApp> {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Edit", "width": 2560, "height": 1440, "frameRate": 60, "duration": 4})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
h
}
fn center(h: &Harness<'_, EffectcraftApp>, id: &str) -> Pos2 {
let e = h.state().auto.find(id).unwrap_or_else(|| panic!("no {id}"));
pos2(e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0)
}
fn click(h: &mut Harness<'_, EffectcraftApp>, id: &str) {
let p = center(h, id);
h.input_mut().events.push(Event::PointerMoved(p));
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
// The automation registry still holds the previous frame's elements: one more frame.
h.run_steps(3);
}
fn key(h: &mut Harness<'_, EffectcraftApp>, key: Key) {
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(3);
}
fn open_settings(h: &mut Harness<'_, EffectcraftApp>) {
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "comp.settings", json!({})).unwrap();
h.run_steps(3);
assert_eq!(h.state().dialog, Some(Dialog::CompSettings));
}
fn preset_names(h: &Harness<'_, EffectcraftApp>) -> Vec<String> {
h.state().session.prefs.comp_presets.iter().map(|q| q.name.clone()).collect()
}
/// Save the comp's size and rate as a preset (Enter saves without pressing OK), then delete it.
#[test]
fn composition_settings_save_and_delete_your_own_preset() {
let mut h = harness();
open_settings(&mut h);
assert!(h.state().auto.find("dialog.comp.presetDelete").is_none(), "nothing of yours to delete yet");
click(&mut h, "dialog.comp.presetSave");
// Choose Name opens with the keyboard in its field.
h.input_mut().events.push(Event::Text("1440p 60".into()));
h.run_steps(2);
key(&mut h, Key::Enter);
assert_eq!(preset_names(&h), ["1440p 60"]);
let q = &h.state().session.prefs.comp_presets[0];
assert_eq!((q.width, q.height, q.pixel_aspect, q.frame_rate), (2560, 1440, 1.0, 60.0));
assert_eq!(h.state().dialog, Some(Dialog::CompSettings), "Enter in the name field doesn't press OK");
assert!(h.state().auto.find("dialog.comp.presetName").is_none(), "the name row closes");
// The comp's values are now that preset, so it can be deleted.
click(&mut h, "dialog.comp.presetDelete");
assert!(preset_names(&h).is_empty());
assert!(h.state().auto.find("dialog.comp.presetDelete").is_none());
}
/// A built-in preset's name can't be taken; Cancel closes the name row without saving.
#[test]
fn a_preset_name_cannot_be_a_built_in_one() {
let mut h = harness();
open_settings(&mut h);
click(&mut h, "dialog.comp.presetSave");
click(&mut h, "dialog.comp.presetName");
h.input_mut().events.push(Event::Text("HDTV 1080 24".into()));
h.run_steps(2);
click(&mut h, "dialog.comp.presetNameSave");
assert!(preset_names(&h).is_empty(), "the built-in name is refused");
click(&mut h, "dialog.comp.presetNameCancel");
assert!(h.state().auto.find("dialog.comp.presetName").is_none());
assert!(preset_names(&h).is_empty());
}
@@ -0,0 +1,62 @@
//! Control-channel clicks and drags hold their modifiers for the whole gesture: egui takes
//! `i.modifiers` from `ModifiersChanged` events, not from the pointer events, and synthetic
//! events arrive one per frame, so a Shift-click must hold Shift from its press to its release.
use effectcraft_engine::Session;
use effectcraft_ui_egui::EffectcraftApp;
use effectcraft_ui_egui::control::{self, ControlRequest};
use serde_json::{Value, json};
/// Feed the queued synthetic input frame by frame; per frame: (has a press/release, the
/// modifiers egui holds in that frame, which only `ModifiersChanged` events change).
fn frames(app: &mut EffectcraftApp) -> Vec<(bool, egui::Modifiers)> {
let mut out = vec![];
let mut held = egui::Modifiers::NONE;
for _ in 0..64 {
let mut raw = egui::RawInput::default();
app.feed_synthetic(&mut raw);
if raw.events.is_empty() {
break;
}
let mut button = false;
for e in &raw.events {
match e {
egui::Event::ModifiersChanged(m) => held = *m,
egui::Event::PointerButton { .. } => button = true,
_ => {}
}
}
out.push((button, held));
}
out
}
fn send(app: &mut EffectcraftApp, method: &str, params: Value) {
let ctx = egui::Context::default();
let (req, _rx) = ControlRequest::new(method, params);
let _ = control::handle(app, &ctx, &req);
}
#[test]
fn shift_click_holds_shift_from_press_to_release() {
let mut app = EffectcraftApp::new(Session::default());
send(&mut app, "ui.click", json!({"x": 10, "y": 10, "modifiers": {"shift": true}}));
let f = frames(&mut app);
let buttons: Vec<_> = f.iter().filter(|(b, _)| *b).collect();
assert_eq!(buttons.len(), 2, "press and release: {f:?}");
assert!(buttons.iter().all(|(_, m)| m.shift), "Shift on the press and the release: {f:?}");
// Afterwards the modifiers are released again.
send(&mut app, "ui.click", json!({"x": 10, "y": 10}));
assert!(frames(&mut app).iter().all(|(_, m)| !m.shift), "a plain click after it has no Shift");
}
#[test]
fn shift_drag_holds_shift_through_the_moves() {
let mut app = EffectcraftApp::new(Session::default());
send(&mut app, "ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 90, "y": 40}, "steps": 4, "modifiers": {"shift": true}}));
let f = frames(&mut app);
let first = f.iter().position(|(b, _)| *b).expect("press");
let last = f.iter().rposition(|(b, _)| *b).expect("release");
assert!(last > first + 1, "moves between press and release: {f:?}");
assert!(f[first..=last].iter().all(|(_, m)| m.shift), "Shift held for the whole drag: {f:?}");
}
+72
View File
@@ -15,6 +15,7 @@ use effectcraft_ui_egui::dock::PanelKind;
use effectcraft_ui_egui::panels::viewer::{comp_to_screen, last_fit};
use egui::{Event, Modifiers, Pos2, Rect, pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
/// Comp "Main" (4 s at 30 fps, current time 1 s) with solids Top, Middle and Bottom, and comp
@@ -252,6 +253,48 @@ fn multiple_selected_footage_dropped_on_empty_timeline_asks_how_to_create_comps(
assert!(h.state().session.active_comp().is_none(), "no composition until the user chooses");
}
/// #684: dropping imported footage onto the empty Composition viewer creates
/// a composition that matches the source, with that source as its first layer.
#[test]
fn project_footage_dropped_on_empty_viewer_creates_first_comp() {
let mut s = Session::default();
let footage =
s.execute("file.importPlaceholder", json!({"name": "Landscape.png", "width": 640, "height": 360, "frameRate": 24, "duration": 5})).unwrap()["item"]
.as_u64()
.unwrap();
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
assert!(h.state().session.active_comp().is_none());
let from = rect(&h, &format!("project.item.{footage}.name")).center();
let viewer = rect(&h, "panel.Composition");
drag(&mut h, from, pos2(viewer.min.x + 40.0, viewer.min.y + 70.0), Modifiers::NONE);
let comp = h.state().session.active_comp().expect("created a composition");
assert_eq!((comp.width, comp.height), (640, 360));
assert_eq!(comp.frame_rate, effectcraft_engine::time::FrameRate::from_f64(24.0));
assert_eq!(comp.duration.seconds(), 5.0);
assert_eq!(comp.layers.len(), 1);
assert_eq!(comp.layers[0].name, "Landscape.png");
assert!(h.state().dialog.is_none());
}
/// Several dragged sources must ask whether to create one or multiple comps,
/// rather than silently discarding the other selected items.
#[test]
fn multiple_selected_footage_dropped_on_empty_viewer_asks_how_to_create_comps() {
let mut s = Session::default();
let first = s.execute("file.importPlaceholder", json!({"name": "First.png", "width": 160, "height": 90})).unwrap()["item"].as_u64().unwrap();
let second = s.execute("file.importPlaceholder", json!({"name": "Second.png", "width": 300, "height": 200})).unwrap()["item"].as_u64().unwrap();
s.state.project_selection = vec![effectcraft_engine::project::ItemId(first), effectcraft_engine::project::ItemId(second)];
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
let from = rect(&h, &format!("project.item.{first}.name")).center();
let viewer = rect(&h, "panel.Composition");
drag(&mut h, from, pos2(viewer.min.x + 40.0, viewer.min.y + 70.0), Modifiers::NONE);
assert_eq!(h.state().dialog, Some(effectcraft_ui_egui::Dialog::Form));
assert!(h.state().auto.find("form.field.single").is_some());
assert!(h.state().session.active_comp().is_none(), "no composition until the user chooses");
}
/// A file dropped on the window (egui hands it over as a dropped file).
#[derive(Debug)]
struct Dropped(std::path::PathBuf);
@@ -379,6 +422,35 @@ fn dropped_file_on_viewer_imports_and_adds_layer_at_pointer() {
assert!((p[0] - 80.0).abs() <= tol && (p[1] - 45.0).abs() <= tol, "{p:?}");
}
/// #678: a dropped Photoshop file asks how to import it, as File ▸ Import ▸ File… does; the
/// Import Kind starts at Settings ▸ Import ▸ Default Drag Import As, and OK imports the drop.
#[test]
fn dropped_photoshop_file_shows_the_import_photoshop_file_dialog() {
let (mut h, _) = harness();
h.state_mut().session.importer = Some(Arc::new(Gated { started: AtomicUsize::new(0), allow: Arc::new(AtomicUsize::new(usize::MAX)) }));
h.state_mut().session.prefs.import.drag_import_as = "compLayerSizes".into();
h.event(Event::PointerMoved(rect(&h, "panel.Project").center()));
h.step();
h.input_mut().dropped_files.push(Arc::new(Dropped(std::env::temp_dir().join("Layers.PSD"))));
h.run_steps(2);
assert_eq!(h.state().dialog, Some(effectcraft_ui_egui::Dialog::Form), "the drop asks first");
h.run_steps(2);
assert!(h.query_by_label("Import Photoshop File").is_some());
assert!(h.query_by_value("Composition - Retain Layer Sizes").is_some(), "Import Kind starts at Default Drag Import As");
assert!(!h.state().session.project.items.values().any(|i| i.name == "Layers.PSD"), "nothing imported before OK");
click_id(&mut h, "form.cancel");
assert_eq!(h.state().dialog, None);
// With Default Drag Import As at Footage, OK imports the file as one item.
h.state_mut().session.prefs.import.drag_import_as = "footage".into();
h.input_mut().dropped_files.push(Arc::new(Dropped(std::env::temp_dir().join("Layers.PSD"))));
h.run_steps(4);
assert_eq!(h.state().dialog, Some(effectcraft_ui_egui::Dialog::Form));
assert!(h.query_by_value("Footage").is_some());
click_id(&mut h, "form.ok");
step_until(&mut h, |h| h.state().session.project.items.values().any(|i| i.name == "Layers.PSD"));
}
#[test]
fn an_unsupported_drop_reports_the_error_and_keeps_valid_files() {
let (mut h, _) = harness();
+53 -1
View File
@@ -528,7 +528,7 @@ fn radial_center_stays_draggable_when_its_property_is_selected() {
#[test]
fn clicking_an_effect_parameter_activates_its_header_and_handles() {
let (app, x) = app();
let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).build_eframe(|_| app);
let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app);
settle(&mut h);
let name = rect_of(&h, &format!("effectControls.prop.{}.name", x.point)).center();
click(&mut h, name);
@@ -656,3 +656,55 @@ fn file_and_text_parameters_have_widgets() {
assert_eq!(v, KV::Str("left*".into()));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn effect_control_name_can_be_renamed_from_its_header() {
let (app, x) = app();
let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app);
settle(&mut h);
let name = format!("effectControls.effect.{}.name", x.point_fx);
let point = rect_of(&h, &name).center();
double_click(&mut h, point);
h.run_steps(3);
assert!(ids(&h).contains(&format!("effectControls.effect.{}.nameEdit", x.point_fx)));
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("Speed".into()));
h.step();
h.key_press(egui::Key::Enter);
h.run_steps(3);
let current_name =
|h: &Harness<'_, EffectcraftApp>| layer(&h.state().session, x.small).effects().unwrap().groups().find(|g| g.uid == x.point_fx).unwrap().name.clone();
assert_eq!(current_name(&h), "Speed");
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
assert_eq!(current_name(&h), "Point Control");
}
#[test]
fn effect_rename_escape_keeps_the_name() {
let (app, x) = app();
let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app);
settle(&mut h);
let point = rect_of(&h, &format!("effectControls.effect.{}.name", x.point_fx)).center();
double_click(&mut h, point);
h.run_steps(3);
assert!(ids(&h).contains(&format!("effectControls.effect.{}.nameEdit", x.point_fx)));
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("Speed".into()));
h.step();
h.key_press(egui::Key::Escape);
h.run_steps(3);
let name = layer(&h.state().session, x.small).effects().unwrap().groups().find(|g| g.uid == x.point_fx).unwrap().name.clone();
assert_eq!(name, "Point Control");
assert!(!ids(&h).contains(&format!("effectControls.effect.{}.nameEdit", x.point_fx)));
}
/// Two presses within egui's double-click time (one frame apart).
fn double_click(h: &mut Harness<'_, EffectcraftApp>, pos: egui::Pos2) {
h.event(egui::Event::PointerMoved(pos));
h.step();
for pressed in [true, false, true, false] {
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
h.step();
}
h.run_steps(2);
}
+71
View File
@@ -105,3 +105,74 @@ fn font_search_preserves_edited_text_and_applies_only_to_selected_characters() {
assert_eq!(doc.style_at(0).font, "Noto Serif");
assert_eq!(doc.style_at(8).font, "Inter");
}
/// A font file of just `name` (the family, Regular) and an `fvar` table with one axis pinned at
/// 400: a variable font as far as the font menu's filter is concerned.
fn pinned_variable_font(family: &str) -> Vec<u8> {
let u16s = |v: &[u16]| -> Vec<u8> { v.iter().flat_map(|x| x.to_be_bytes()).collect() };
let strings: Vec<Vec<u8>> = [family, "Regular"].iter().map(|s| s.encode_utf16().flat_map(|u| u.to_be_bytes()).collect()).collect();
let mut name = u16s(&[0, 2, 30]);
let mut off = 0;
for (id, st) in strings.iter().enumerate() {
name.extend(u16s(&[3, 1, 0x409, id as u16 + 1, st.len() as u16, off]));
off += st.len() as u16;
}
strings.iter().for_each(|st| name.extend(st));
let mut fvar = u16s(&[1, 0, 16, 2, 1, 20, 0, 8]);
fvar.extend(b"wght".iter().copied().chain(u16s(&[0x190, 0, 0x190, 0, 0x190, 0, 0, 256])));
let mut out = u16s(&[1, 0, 2, 0, 0, 0]);
let mut body: Vec<u8> = vec![];
for (tag, data) in [(b"fvar", fvar), (b"name", name)] {
out.extend(tag);
out.extend([0u8; 4]);
out.extend(((12 + 32 + body.len()) as u32).to_be_bytes());
out.extend((data.len() as u32).to_be_bytes());
body.extend(data);
}
out.extend(body);
out
}
/// The font menu's Variable Fonts filter (After Effects 26.3): the checkbox keeps only variable
/// families, works with the typed search (which keeps the keyboard), and stays on when the menu
/// is reopened until it is turned off.
#[test]
fn font_menu_filters_variable_fonts() {
const FAMILY: &str = "Inter Variable Menu Test";
assert_eq!(effectcraft_engine::text::fonts::add_font_data(pinned_variable_font(FAMILY)).len(), 1);
let variable = effectcraft_engine::text::fonts::variable_families();
let mut s = Session::default();
s.execute("comp.new", json!({"width": 320, "height": 180})).unwrap();
let lid = s.execute("layer.newText", json!({"text": "Var", "font": "Inter"})).unwrap()["layer"].as_u64().unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(move |_| EffectcraftApp::new(s));
h.state_mut().show_panel(PanelKind::Character);
h.run_steps(3);
let families = |h: &Harness<'_, EffectcraftApp>| -> Vec<String> {
h.state().auto.query("character.font.option.").iter().map(|e| e.id.trim_start_matches("character.font.option.").to_string()).collect()
};
click(&mut h, "character.font");
type_text(&mut h, "inter");
let shown = families(&h);
assert!(shown.iter().any(|f| f == "Inter") && shown.iter().any(|f| f == FAMILY), "unfiltered at first: {shown:?}");
click(&mut h, "character.font.variable");
let shown = families(&h);
assert!(shown.iter().any(|f| f == FAMILY), "{shown:?}");
assert!(shown.iter().all(|f| variable.contains(f)), "only variable families: {shown:?}");
// The search field keeps the keyboard and narrows the filtered list further.
type_text(&mut h, " variable menu");
assert_eq!(families(&h), vec![FAMILY.to_string()]);
type_text(&mut h, "x");
assert!(families(&h).is_empty());
assert!(h.state().auto.find("character.font.empty").is_some());
key(&mut h, Key::Escape);
// Reopened: still filtered; turning it off lists the static families again.
click(&mut h, "character.font");
h.run_steps(2);
let shown = families(&h);
assert!(!shown.is_empty() && shown.iter().all(|f| variable.contains(f)), "the filter stays on: {shown:?}");
click(&mut h, "character.font.variable");
type_text(&mut h, "inter");
assert!(families(&h).iter().any(|f| f == "Inter"), "{:?}", families(&h));
key(&mut h, Key::Escape);
assert_eq!(layer_doc(&h.state().session, LayerId(lid)).unwrap().font, "Inter", "filtering changes nothing");
}
+44
View File
@@ -0,0 +1,44 @@
//! Stepping the current time from the keyboard: Page Down / Page Up and Cmd+Right / Cmd+Left
//! Arrow move one frame, with Shift ten.
use effectcraft_engine::Session;
use effectcraft_ui_egui::EffectcraftApp;
use egui::{Event, Key, Modifiers};
use egui_kittest::Harness;
use serde_json::json;
fn key(h: &mut Harness<'_, EffectcraftApp>, key: Key, modifiers: Modifiers) {
h.event(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });
h.step();
h.event(Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers });
h.step();
}
#[test]
fn cmd_arrows_step_the_current_frame() {
let mut session = Session::default();
session.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30.0, "duration": 4.0})).unwrap();
let cid = session.state.active_comp.unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| EffectcraftApp::new(session));
h.run_steps(2);
let frame = |h: &Harness<'_, EffectcraftApp>| {
let app = h.state();
app.session.project.comp(cid).unwrap().frame_rate.frame_at(app.session.time())
};
assert_eq!(frame(&h), 0);
let cmd = Modifiers::COMMAND;
let cmd_shift = Modifiers::COMMAND | Modifiers::SHIFT;
key(&mut h, Key::ArrowRight, cmd);
assert_eq!(frame(&h), 1);
key(&mut h, Key::PageDown, Modifiers::NONE);
assert_eq!(frame(&h), 2);
key(&mut h, Key::ArrowRight, cmd_shift);
assert_eq!(frame(&h), 12);
key(&mut h, Key::ArrowLeft, cmd);
assert_eq!(frame(&h), 11);
key(&mut h, Key::ArrowLeft, cmd_shift);
assert_eq!(frame(&h), 1);
// The plain arrows still nudge layers, not the time.
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert_eq!(frame(&h), 1);
}
+30
View File
@@ -250,6 +250,36 @@ fn reshape_correspondence_points_on_the_viewer() {
assert_eq!(h.state().session.history.undo.len(), undo_len + 1);
}
/// #303: with Mesh Warp selected, the viewer shows its grid; dragging a vertex warps the mesh
/// (one undo step), and the other vertices stay put.
#[test]
fn mesh_warp_vertices_drag_on_the_viewer() {
let (mut s0, l, fx) = with_effect("Mesh Warp");
let g = s0.active_comp().unwrap().layer(LayerId(l)).unwrap().props.find_group(fx).unwrap().clone();
s0.execute("prop.set", json!({"layer": l, "prop": g.get("rows").unwrap().uid, "value": 2})).unwrap();
s0.execute("prop.set", json!({"layer": l, "prop": g.get("columns").unwrap().uid, "value": 2})).unwrap();
let mut h = harness(s0);
h.state_mut().toggle_maximize(PanelKind::EffectControls);
h.state_mut().session.state.selected_props = vec![(LayerId(l), fx)];
for _ in 0..6 {
h.step();
}
let v = |r: usize, c: usize| format!("viewer.meshWarp.{fx}.{r}.{c}");
let (tl, mid, br) = (rect(&h, &v(0, 0)).center(), rect(&h, &v(1, 1)).center(), rect(&h, &v(2, 2)).center());
assert!(((tl.x + br.x) / 2.0 - mid.x).abs() < 1.0 && ((tl.y + br.y) / 2.0 - mid.y).abs() < 1.0, "{tl:?} {mid:?} {br:?}");
assert!(br.x - tl.x > 100.0, "the grid spans the layer: {tl:?} {br:?}");
assert_eq!(s(value(&h, l, fx, "mesh")), "");
let undo_len = h.state().session.history.undo.len();
drag(&mut h, mid, mid + egui::vec2(40.0, 0.0));
let mesh = effectcraft_engine::effects::parse_mesh(&s(value(&h, l, fx, "mesh")));
assert_eq!(mesh.len(), 9, "{mesh:?}");
assert!(mesh[4].0 > 10.0 && mesh[4].1.abs() < 1.0, "the centre vertex moved right: {mesh:?}");
assert!(mesh.iter().enumerate().all(|(i, o)| i == 4 || *o == (0.0, 0.0)), "{mesh:?}");
assert_eq!(h.state().session.history.undo.len(), undo_len + 1);
let moved = rect(&h, &v(1, 1)).center();
assert!((moved.x - mid.x - 40.0).abs() < 2.0, "the handle follows the vertex: {mid:?} → {moved:?}");
}
/// UI fixes of M13.10: the Composition / Timeline tabs' close button, swatch and lock; the
/// Preview panel scrolls in the default workspace (where it shows just the transport).
#[test]
+493
View File
@@ -0,0 +1,493 @@
//! The Gradient Editor (#612): the Timeline's "Edit Gradient…" opens it on a gradient property
//! (here a shape layer's Gradient Fill ▸ Colors). OK sets the edited gradient with one undo step
//! at the composition time it opened at (offset and stretched layers too); OK with no change, Cancel
//! and Escape change nothing; on an animated gradient only the keyframe at that time changes, with
//! a warning when its stop counts no longer match a neighbour's.
use effectcraft_engine::Session;
use effectcraft_engine::keyframe::{Gradient, Value};
use effectcraft_engine::project::{LayerId, PropGroup};
use effectcraft_engine::time::Tick;
use effectcraft_ui_egui::panels::gradient_editor::Track;
use effectcraft_ui_egui::{Dialog, EffectcraftApp};
use egui::accesskit::Role;
use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
const WARNING: &str = "These adjacent keyframes cannot interpolate because their stop counts differ.";
/// The uids from the layer's root down to the Gradient Fill group, and its Colors property.
fn gradient_fill(g: &PropGroup) -> Option<(Vec<u64>, u64)> {
for x in g.groups() {
if x.match_id == "gfill" {
return Some((vec![x.uid], x.get("colors")?.uid));
}
if let Some((mut path, colors)) = gradient_fill(x) {
path.insert(0, x.uid);
return Some((path, colors));
}
}
None
}
/// A 20 s comp with a rectangle shape layer holding a Gradient Fill, its rows open in the
/// Timeline. `timing` runs on the layer first (start, stretch). Returns (harness, layer, Colors uid).
fn setup(timing: &[(&str, serde_json::Value)]) -> (Harness<'static, EffectcraftApp>, u64, u64) {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "duration": 20})).unwrap();
let l = s.execute("layer.newShape", json!({"kind": "rect"})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.addShapeItem", json!({"layer": l, "kind": "gfill"})).unwrap();
for (cmd, p) in timing {
let mut p = p.clone();
p["layers"] = json!([l]);
s.execute(cmd, p).unwrap();
}
let (groups, colors) = gradient_fill(&s.active_comp().unwrap().layer(LayerId(l)).unwrap().props).expect("a Gradient Fill");
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.state_mut().ui.timeline.open_layers.insert(l);
h.state_mut().ui.timeline.open_groups.extend(groups);
h.run_steps(3);
(h, l, colors)
}
fn rect(h: &Harness<'_, EffectcraftApp>, id: &str) -> [f32; 4] {
h.state().auto.find(id).unwrap_or_else(|| panic!("no automation id {id}")).rect
}
fn center(h: &Harness<'_, EffectcraftApp>, id: &str) -> Pos2 {
let r = rect(h, id);
pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0)
}
/// The point at `f` (0..1) along the bar, at the height of automation id `row`.
fn along(h: &Harness<'_, EffectcraftApp>, row: &str, f: f32) -> Pos2 {
let bar = rect(h, "dialog.gradient.bar");
pos2(bar[0] + bar[2] * f, center(h, row).y)
}
fn click_at(h: &mut Harness<'_, EffectcraftApp>, p: Pos2) {
h.input_mut().events.push(Event::PointerMoved(p));
h.step();
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
}
fn click(h: &mut Harness<'_, EffectcraftApp>, id: &str) {
let p = center(h, id);
click_at(h, p);
}
fn drag(h: &mut Harness<'_, EffectcraftApp>, from: Pos2, to: Pos2) {
h.input_mut().events.push(Event::PointerMoved(from));
h.step();
h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
for k in 1..=6 {
let f = k as f32 / 6.0;
h.input_mut().events.push(Event::PointerMoved(from + (to - from) * f));
h.step();
}
h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
}
fn key(h: &mut Harness<'_, EffectcraftApp>, k: Key) {
h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(3);
}
fn colors_prop(h: &Harness<'_, EffectcraftApp>, l: u64, uid: u64) -> effectcraft_engine::project::Property {
h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().props.find(uid).unwrap().clone()
}
fn gradient(v: &Value) -> Gradient {
match v {
Value::Gradient(g) => g.clone(),
other => panic!("not a gradient: {other:?}"),
}
}
fn open_editor(h: &mut Harness<'_, EffectcraftApp>, colors: u64) {
let id = format!("timeline.prop.{colors}.value");
assert!(h.state().auto.find(&id).is_some(), "no automation id {id}: the Timeline's gradient value isn't clickable");
click(h, &id);
h.run_steps(2);
}
fn set_time(h: &mut Harness<'_, EffectcraftApp>, t: f64) {
h.state_mut().session.execute("time.set", json!({"time": t})).unwrap();
h.run_steps(2);
}
fn add_key(h: &mut Harness<'_, EffectcraftApp>, l: u64, colors: u64, comp_t: f64, g: &Gradient) {
h.state_mut()
.session
.execute("prop.addKey", json!({"layer": l, "prop": colors, "time": comp_t, "timeBase": "comp", "value": Value::Gradient(g.clone()).to_json()}))
.unwrap();
}
fn near(a: [f32; 4], b: [f32; 4]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4)
}
/// The shared colour picker is showing (its colour field is in the accessibility tree).
fn picker_open(h: &Harness<'_, EffectcraftApp>) -> bool {
h.query_by_label("Color field").is_some()
}
/// Type `hex` into the open picker's Hex field, over the code it shows.
fn type_hex(h: &mut Harness<'_, EffectcraftApp>, hex: &str) {
let at = h.get_by_role_and_label(Role::TextInput, "#").rect().center();
click_at(h, at);
for pressed in [true, false] {
h.input_mut().events.push(Event::Key { key: Key::A, physical_key: None, pressed, repeat: false, modifiers: Modifiers::COMMAND });
}
h.step();
h.input_mut().events.push(Event::Text(hex.into()));
h.run_steps(3);
}
fn stop_color(h: &Harness<'_, EffectcraftApp>, id: u64) -> [f32; 4] {
h.state().gradient_draft().colors.iter().find(|s| s.id == id).expect("the stop").value
}
/// The numbers the editor's fields show (their accessibility values).
fn shown_numbers(h: &Harness<'_, EffectcraftApp>) -> Vec<f64> {
h.query_all_by(|n| n.numeric_value().is_some()).filter_map(|n| n.accesskit_node().numeric_value()).collect()
}
fn undo_len(h: &Harness<'_, EffectcraftApp>) -> usize {
h.state().session.history.undo.len()
}
#[test]
fn stop_edits_ok_sets_the_gradient_in_one_undo_step() {
let (mut h, l, colors) = setup(&[]);
let before = colors_prop(&h, l, colors).value.clone();
let undo = undo_len(&h);
open_editor(&mut h, colors);
assert_eq!(h.state().dialog, Some(Dialog::GradientEditor));
// Add a colour stop a quarter along, recolour it, and drag the right opacity stop to the middle.
let p = along(&h, "dialog.gradient.addColor", 0.25);
click_at(&mut h, p);
let (track, id) = h.state().gradient_draft().selected.expect("the new stop is selected");
assert_eq!(track, Track::Color);
let sampled = stop_color(&h, id);
// The swatch opens the shared colour picker over the modal editor. A click in its colour field
// reaches it (a modal blocks the layers below it), and so does typing a hex code.
click(&mut h, "dialog.gradient.color");
assert!(picker_open(&h), "the colour picker opened");
let field = h.get_by_label("Color field").rect().center();
click_at(&mut h, field + egui::vec2(20.0, -20.0));
assert_ne!(stop_color(&h, id), sampled, "a click in the picker's colour field changed the stop");
type_hex(&mut h, "336699");
let picked = stop_color(&h, id);
assert!(near(picked, [0.2, 0.4, 0.6, sampled[3]]), "the hex code's colour, and the stop kept its alpha: {picked:?}");
// Clicking outside the picker keeps the colour and closes it; the editor stays.
let title = h.get_by_label("Gradient Editor").rect().center();
click_at(&mut h, title);
assert!(!picker_open(&h), "the picker closed");
assert_eq!(h.state().dialog, Some(Dialog::GradientEditor));
assert_eq!(stop_color(&h, id), picked);
let from = center(&h, "dialog.gradient.opacityStop.1");
let to = along(&h, "dialog.gradient.opacityStop.1", 0.5);
drag(&mut h, from, to);
assert_eq!(undo_len(&h), undo, "nothing is set while editing");
click(&mut h, "dialog.gradient.ok");
assert_eq!(h.state().dialog, None);
let g = gradient(&colors_prop(&h, l, colors).value);
assert_eq!(g.colors.len(), 3, "{g:?}");
assert!((g.colors[1].0 - 0.25).abs() < 0.02 && g.colors[1].1 == picked, "{g:?}");
assert!((g.opacities[1].0 - 0.5).abs() < 0.02, "{g:?}");
assert_eq!(undo_len(&h), undo + 1, "one undo step");
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
assert_eq!(colors_prop(&h, l, colors).value, before, "one undo restores it");
}
#[test]
fn cancel_and_escape_change_nothing() {
for cancel in ["button", "escape"] {
let (mut h, _, colors) = setup(&[]);
let project = h.state().session.project.clone();
let undo = undo_len(&h);
open_editor(&mut h, colors);
let p = along(&h, "dialog.gradient.addOpacity", 0.4);
click_at(&mut h, p);
assert_eq!(h.state().gradient_draft().opacities.len(), 3);
if cancel == "button" {
click(&mut h, "dialog.gradient.cancel");
} else {
key(&mut h, Key::Escape);
}
assert_eq!(h.state().dialog, None, "{cancel}");
assert_eq!(h.state().session.project, project, "{cancel} leaves the project as it was");
assert_eq!(undo_len(&h), undo);
}
}
/// OK without a change adds no keyframe between two (prop.set would add one).
#[test]
fn ok_without_changes_adds_no_keyframe() {
let (mut h, l, colors) = setup(&[]);
add_key(&mut h, l, colors, 1.0, &Gradient::default());
add_key(&mut h, l, colors, 3.0, &Gradient::default());
set_time(&mut h, 2.0);
let undo = undo_len(&h);
open_editor(&mut h, colors);
click(&mut h, "dialog.gradient.ok");
assert_eq!(h.state().dialog, None);
assert_eq!(colors_prop(&h, l, colors).keys.len(), 2, "still the two keyframes");
assert_eq!(undo_len(&h), undo, "no undo step");
}
/// On an animated gradient OK sets the keyframe at the edit time (adding one between keys) and no
/// other.
#[test]
fn animated_edits_change_only_the_keyframe_at_the_edit_time() {
let (mut h, l, colors) = setup(&[]);
let red = Gradient { colors: vec![(0.0, [1.0, 0.0, 0.0, 1.0]), (1.0, [0.0, 0.0, 0.0, 1.0])], ..Gradient::default() };
add_key(&mut h, l, colors, 1.0, &Gradient::default());
add_key(&mut h, l, colors, 3.0, &red);
let first = colors_prop(&h, l, colors).keys[0].clone();
for (t, keys) in [(3.0, 2), (2.0, 3)] {
set_time(&mut h, t);
open_editor(&mut h, colors);
let d = &h.state().gradient_draft();
let id = d.id_at(Track::Color, 1).unwrap();
h.state_mut().gradient_draft_mut().set_rgb(id, [0.0, 0.0, 1.0]);
click(&mut h, "dialog.gradient.ok");
let pr = colors_prop(&h, l, colors);
assert_eq!(pr.keys.len(), keys, "at {t} s");
assert_eq!(pr.keys[0], first, "the keyframe at 1 s is untouched");
let layer = h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().clone();
// The edit time snapped to the nearest frame (29.97 fps), as prop.set snaps it.
let at = h.state().session.active_comp().unwrap().frame_rate.snap_nearest(Tick::from_seconds_f64(t)).seconds();
let k = pr.keys.iter().find(|k| (layer.comp_time(k.time).seconds() - at).abs() < 1e-6).expect("a keyframe at the edit time");
assert_eq!(gradient(&k.value).colors[1].1, [0.0, 0.0, 1.0, 1.0], "at {t} s");
}
}
/// The key goes at the composition time the editor opened at, on a layer that starts late or is
/// stretched (layer time differs from composition time).
#[test]
fn offset_and_stretched_layers_get_the_keyframe_at_the_comp_time() {
for timing in
[vec![("layer.timing", json!({"start": 5.0}))], vec![("layer.timing", json!({"start": 5.0})), ("layer.timeStretch", json!({"percent": 200.0}))]]
{
let (mut h, l, colors) = setup(&timing);
set_time(&mut h, 5.5);
h.state_mut().session.execute("prop.toggleAnimation", json!({"layer": l, "prop": colors})).unwrap();
set_time(&mut h, 6.0);
open_editor(&mut h, colors);
let p = along(&h, "dialog.gradient.addColor", 0.5);
click_at(&mut h, p);
click(&mut h, "dialog.gradient.ok");
let layer = h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().clone();
let pr = layer.props.find(colors).unwrap();
let comp_times: Vec<f64> = pr.keys.iter().map(|k| layer.comp_time(k.time).seconds()).collect();
assert_eq!(pr.keys.len(), 2, "{timing:?}: {comp_times:?}");
// Composition time 6 s snapped to the nearest frame (29.97 fps: 6.006 s), as prop.set snaps
// it: the layer's start and stretch don't move it.
let at = h.state().session.active_comp().unwrap().frame_rate.snap_nearest(Tick::from_seconds_f64(6.0)).seconds();
let k = pr.keys.iter().find(|k| (layer.comp_time(k.time).seconds() - at).abs() < 1e-6);
let k = k.unwrap_or_else(|| panic!("{timing:?}: no keyframe at comp time {at} s: {comp_times:?}"));
assert_eq!(gradient(&k.value).colors.len(), 3, "{timing:?}");
}
}
/// Adding a stop next to keyframes with fewer stops warns that they can't interpolate; it still
/// saves, the neighbour keeps its stops, and the animation holds until the edited keyframe.
#[test]
fn mismatched_stop_counts_warn_and_neighbours_stay() {
let (mut h, l, colors) = setup(&[]);
add_key(&mut h, l, colors, 1.0, &Gradient::default());
add_key(&mut h, l, colors, 3.0, &Gradient::default());
set_time(&mut h, 3.0);
open_editor(&mut h, colors);
assert!(h.query_by_label(WARNING).is_none(), "same counts: no warning");
let p = along(&h, "dialog.gradient.addColor", 0.5);
click_at(&mut h, p);
assert!(h.query_by_label(WARNING).is_some(), "three colour stops next to a keyframe with two");
click(&mut h, "dialog.gradient.ok");
let pr = colors_prop(&h, l, colors);
assert_eq!(pr.keys.len(), 2);
assert_eq!(gradient(&pr.keys[0].value), Gradient::default(), "the neighbour keeps its stops");
assert_eq!(gradient(&pr.keys[1].value).colors.len(), 3);
let layer = h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().clone();
let mid = pr.value_at(layer.layer_time(Tick::from_seconds_f64(2.0)));
assert_eq!(gradient(&mid), Gradient::default(), "it holds the first keyframe instead of blending");
}
/// Delete removes the selected stop (never a layer, and never the last stop of a track), but not
/// while typing in a field.
#[test]
fn delete_removes_the_selected_stop_but_not_the_last_or_while_typing() {
let (mut h, _, colors) = setup(&[]);
let layers = h.state().session.active_comp().unwrap().layers.len();
open_editor(&mut h, colors);
click(&mut h, "dialog.gradient.colorStop.0");
key(&mut h, Key::Delete);
assert_eq!(h.state().gradient_draft().colors.len(), 1, "Delete removed the selected stop");
click(&mut h, "dialog.gradient.colorStop.0");
key(&mut h, Key::Delete);
click(&mut h, "dialog.gradient.delete");
assert_eq!(h.state().gradient_draft().colors.len(), 1, "the last colour stop stays");
assert_eq!(h.state().session.active_comp().unwrap().layers.len(), layers, "Delete never reaches the layer");
assert_eq!(h.state().dialog, Some(Dialog::GradientEditor));
// Typing in Location: Delete edits the text, not the stops.
click(&mut h, "dialog.gradient.opacityStop.0");
click(&mut h, "dialog.gradient.location");
assert!(h.ctx.egui_wants_keyboard_input(), "the Location field takes the keyboard");
key(&mut h, Key::Delete);
assert_eq!(h.state().gradient_draft().opacities.len(), 2, "typing doesn't delete a stop");
}
/// One colour stop saves (the typed form; plain JSON needs two) and one undo brings both back.
#[test]
fn a_single_colour_stop_saves_and_undoes() {
let (mut h, l, colors) = setup(&[]);
let before = colors_prop(&h, l, colors).value.clone();
let undo = undo_len(&h);
open_editor(&mut h, colors);
click(&mut h, "dialog.gradient.colorStop.1");
click(&mut h, "dialog.gradient.delete");
assert_eq!(h.state().gradient_draft().colors.len(), 1);
click(&mut h, "dialog.gradient.ok");
let g = gradient(&colors_prop(&h, l, colors).value);
assert_eq!(g.colors, gradient(&before).colors[..1].to_vec(), "{g:?}");
assert_eq!(g.opacities, gradient(&before).opacities, "opacity stops unchanged");
assert_eq!(undo_len(&h), undo + 1);
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
assert_eq!(colors_prop(&h, l, colors).value, before);
}
/// Typing a Location that moves a stop past its neighbour keeps the selection on that stop, and
/// in the same frame the Opacity field shows its value, not the neighbour's (now at its old index).
#[test]
fn location_moves_past_a_neighbour_and_the_fields_follow_the_stop() {
let (mut h, _, colors) = setup(&[]);
open_editor(&mut h, colors);
// Opacity 100% at 0 and 40% at 1, plus a stop at 0.5 sampled from them: 70%.
let right = h.state().gradient_draft().opacities[1].id;
h.state_mut().gradient_draft_mut().set_opacity(right, 0.4);
let p = along(&h, "dialog.gradient.addOpacity", 0.5);
click_at(&mut h, p);
let middle = h.state().gradient_draft().selected.expect("the new stop").1;
let i = h.state().gradient_draft().index_of(Track::Opacity, middle).unwrap();
assert!((h.state().gradient_draft().opacities[i].value - 0.7).abs() < 0.02, "it sampled 70%");
// Select the 100% stop at 0 and type 80 into Location: it passes the stop at 0.5.
let first = h.state().gradient_draft().opacities[0].id;
click(&mut h, "dialog.gradient.opacityStop.0");
click(&mut h, "dialog.gradient.location");
assert!(h.ctx.egui_wants_keyboard_input(), "the Location field is being typed in");
h.input_mut().events.push(Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
h.input_mut().events.push(Event::Text("80".into()));
h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.step();
let d = h.state().gradient_draft();
assert_eq!(d.selected, Some((Track::Opacity, first)), "the moved stop stays selected");
assert_eq!(d.index_of(Track::Opacity, first), Some(1), "it is now after the stop at 0.5");
// The frame that moved it: Opacity already shows this stop's 100%, never the neighbour's 70%
// that is now at its old index. (Location itself was drawn before the move: 0 until the next.)
let shown = shown_numbers(&h);
assert!(shown.contains(&100.0), "this stop's 100%: {shown:?}");
assert!(!shown.iter().any(|v| (v - 70.0).abs() < 1.0), "never the neighbour's 70%: {shown:?}");
h.run_steps(2);
let shown = shown_numbers(&h);
assert!(shown.contains(&80.0) && shown.contains(&100.0), "Location 80 and Opacity 100%: {shown:?}");
assert!(!shown.iter().any(|v| (v - 70.0).abs() < 1.0), "{shown:?}");
}
/// A layer deleted while the editor is open: OK reports it, without a crash.
#[test]
fn a_layer_deleted_while_editing_is_reported() {
let (mut h, l, colors) = setup(&[]);
open_editor(&mut h, colors);
let p = along(&h, "dialog.gradient.addColor", 0.5);
click_at(&mut h, p);
h.state_mut().session.execute("edit.clear", json!({"layers": [l]})).unwrap();
h.run_steps(2);
click(&mut h, "dialog.gradient.ok");
assert_eq!(h.state().dialog, None);
assert!(!h.state().ui.status.is_empty(), "the failed set is reported");
}
/// `prop.editGradient` by id (agents, MCP, the control channel) is an error for a target that
/// isn't a gradient property, from the engine and through the UI, and opens nothing.
#[test]
fn edit_gradient_by_id_rejects_bad_targets() {
let (mut h, l, colors) = setup(&[]);
let ctx = h.ctx.clone();
let opacity = h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().props.prop("transform/opacity").unwrap().uid;
for (p, err) in [(json!({"layer": 9999, "prop": colors}), "no layer"), (json!({"layer": l, "prop": opacity}), "not a gradient")] {
let e = h.state_mut().session.execute_checked("prop.editGradient", p.clone()).expect_err("the engine refuses it");
assert!(e.to_string().contains(err), "{p}: {e}");
let e = effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "prop.editGradient", p.clone()).expect_err("so does the UI");
assert!(e.contains(err), "{p}: {e}");
h.run_steps(2);
assert_eq!(h.state().dialog, None, "{p}");
}
let r = effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "prop.editGradient", json!({"layer": l, "prop": colors}));
assert!(r.is_ok(), "{r:?}");
h.run_steps(2);
assert_eq!(h.state().dialog, Some(Dialog::GradientEditor));
}
/// In the editor, the colour picker's Escape and Cancel go back to the stop's colour and close only
/// the picker: the editor and its other edits stay (dialogs leave Escape to an open picker).
#[test]
fn picker_escape_and_cancel_restore_the_stop_and_keep_the_editor() {
let (mut h, _, colors) = setup(&[]);
open_editor(&mut h, colors);
let added = along(&h, "dialog.gradient.addOpacity", 0.3);
click_at(&mut h, added);
click(&mut h, "dialog.gradient.colorStop.0");
let id = h.state().gradient_draft().selected.expect("a selected stop").1;
let original = stop_color(&h, id);
for how in ["escape", "cancel"] {
click(&mut h, "dialog.gradient.color");
assert!(picker_open(&h), "{how}: the picker opened");
type_hex(&mut h, "ff8000");
assert!(near(stop_color(&h, id), [1.0, 128.0 / 255.0, 0.0, original[3]]), "{how}: the picker previews as it goes");
if how == "escape" {
key(&mut h, Key::Escape);
} else {
// The picker's Cancel, not the editor's.
let editor_cancel = rect(&h, "dialog.gradient.cancel");
let cancel =
h.query_all_by_label("Cancel").map(|n| n.rect()).find(|r| (r.min.x - editor_cancel[0]).abs() > 1.0 || (r.min.y - editor_cancel[1]).abs() > 1.0);
click_at(&mut h, cancel.expect("the picker's Cancel").center());
}
assert!(!picker_open(&h), "{how}: the picker closed");
assert_eq!(h.state().dialog, Some(Dialog::GradientEditor), "{how}: the editor stays open");
assert_eq!(stop_color(&h, id), original, "{how}: the stop's colour is back");
assert_eq!(h.state().gradient_draft().opacities.len(), 3, "{how}: the editor's other edits stay");
}
}
/// The Escape that closes the picker is its own: the next Escape, even in the very next pass,
/// cancels the editor (a closed picker doesn't keep the dialog from it).
#[test]
fn the_escape_after_the_picker_closes_cancels_the_editor() {
let (mut h, _, colors) = setup(&[]);
let project = h.state().session.project.clone();
open_editor(&mut h, colors);
click(&mut h, "dialog.gradient.colorStop.0");
click(&mut h, "dialog.gradient.color");
assert!(picker_open(&h), "the picker opened");
let escape = |h: &mut Harness<'_, EffectcraftApp>| {
h.input_mut().events.push(Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::Key { key: Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
h.step();
};
escape(&mut h);
assert_eq!(h.state().dialog, Some(Dialog::GradientEditor), "the first Escape closed only the picker");
escape(&mut h);
assert_eq!(h.state().dialog, None, "the next pass's Escape cancels the editor");
assert_eq!(h.state().session.project, project, "and changes nothing");
}
+158
View File
@@ -0,0 +1,158 @@
//! #612: a shape layer's Gradient Fill start and end points are dragged in the Composition viewer,
//! as in After Effects. With the gradient (or a property in it) selected, `viewer.gradientPoint.*`
//! handles sit on the points, in the space of the group holding the gradient; a drag sets the
//! point in one undo step and doesn't move the layer. Uses only APIs that existed before the
//! handles, so it runs (and fails) on the code without them.
use effectcraft_engine::Session;
use effectcraft_engine::project::{LayerId, PropGroup};
use effectcraft_ui_egui::EffectcraftApp;
use effectcraft_ui_egui::panels::viewer::comp_to_screen;
use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
/// The Gradient Fill group in shape contents `g`, through nested groups.
fn gfill(g: &PropGroup) -> Option<&PropGroup> {
for x in g.groups() {
if x.match_id == "gfill" {
return Some(x);
}
if let Some(found) = gfill(x) {
return Some(found);
}
}
None
}
struct Ids {
layer: u64,
gfill: u64,
start: u64,
end: u64,
}
/// A 640×360 comp with a rectangle shape layer, a Gradient Fill added inside the rectangle's group
/// (`in_group`) or at the top of its contents, after `prep` runs on the session.
fn setup(in_group: bool, prep: impl FnOnce(&mut Session, u64, u64)) -> (Session, Ids) {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Main", "width": 640, "height": 360, "duration": 4})).unwrap();
let l = s.execute("layer.newShape", json!({"kind": "rect"})).unwrap()["layer"].as_u64().unwrap();
let group = s.active_comp().unwrap().layer(LayerId(l)).unwrap().props.sub("contents").unwrap().groups().next().unwrap().uid;
let mut p = json!({"layer": l, "kind": "gfill"});
if in_group {
p["group"] = json!(group);
}
s.execute("layer.addShapeItem", p).unwrap();
prep(&mut s, l, group);
let layer = s.active_comp().unwrap().layer(LayerId(l)).unwrap();
let g = gfill(&layer.props).expect("a Gradient Fill");
let ids = Ids { layer: l, gfill: g.uid, start: g.get("start").unwrap().uid, end: g.get("end").unwrap().uid };
s.state.selected_layers = vec![LayerId(l)];
(s, ids)
}
fn harness(s: Session) -> Harness<'static, EffectcraftApp> {
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(4);
h
}
fn handle(h: &Harness<'_, EffectcraftApp>, uid: u64) -> Option<Pos2> {
h.state().auto.find(&format!("viewer.gradientPoint.{uid}")).map(|e| pos2(e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0))
}
fn point(h: &Harness<'_, EffectcraftApp>, ids: &Ids, uid: u64) -> [f64; 2] {
h.state().session.active_comp().unwrap().layer(LayerId(ids.layer)).unwrap().props.find(uid).unwrap().value.as_vec2()
}
/// Screen pixels per comp pixel.
fn zoom(h: &Harness<'_, EffectcraftApp>) -> f32 {
let a = comp_to_screen(&h.ctx, [0.0, 0.0]).unwrap();
let b = comp_to_screen(&h.ctx, [100.0, 0.0]).unwrap();
(b.x - a.x) / 100.0
}
fn drag(h: &mut Harness<'_, EffectcraftApp>, from: Pos2, to: Pos2) {
h.event(Event::PointerMoved(from));
h.step();
h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
for k in 1..=8 {
h.event(Event::PointerMoved(from + (to - from) * (k as f32 / 8.0)));
h.step();
}
h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
}
fn near(a: [f64; 2], b: [f64; 2], tol: f64) -> bool {
(a[0] - b[0]).abs() <= tol && (a[1] - b[1]).abs() <= tol
}
/// With the Gradient Fill selected, its End Point is a handle on the point; dragging it moves the
/// point by the drag (in comp pixels, the layer and group being unscaled), as one undo step,
/// without moving the layer.
#[test]
fn dragging_the_end_point_moves_it_in_one_undo_step() {
let (mut s, ids) = setup(false, |_, _, _| {});
s.state.selected_props = vec![(LayerId(ids.layer), ids.gfill)];
let mut h = harness(s);
let at = handle(&h, ids.end).unwrap_or_else(|| panic!("no viewer.gradientPoint.{}: the Gradient Fill's End Point isn't draggable in the viewer", ids.end));
assert!(handle(&h, ids.start).is_some(), "and its Start Point");
let (end, start) = (point(&h, &ids, ids.end), point(&h, &ids, ids.start));
let position = h.state().session.active_comp().unwrap().layer(LayerId(ids.layer)).unwrap().props.prop("transform/position").unwrap().value.clone();
let undo = h.state().session.history.undo.len();
let z = zoom(&h);
drag(&mut h, at, at + vec2(60.0, 30.0) * z);
let moved = point(&h, &ids, ids.end);
assert!(near(moved, [end[0] + 60.0, end[1] + 30.0], 1.5), "End Point {end:?} moved by the drag: {moved:?}");
assert_eq!(point(&h, &ids, ids.start), start, "the Start Point stays");
let layer = h.state().session.active_comp().unwrap().layer(LayerId(ids.layer)).unwrap().clone();
assert_eq!(layer.props.prop("transform/position").unwrap().value, position, "the layer didn't move");
assert_eq!(h.state().session.history.undo.len(), undo + 1, "the drag is one undo step");
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
assert_eq!(point(&h, &ids, ids.end), end, "one undo puts it back");
}
/// A gradient inside a moved and scaled group: its handles sit where the group draws the points,
/// and a drag converts back into the group's space (half as far at 200%).
#[test]
fn points_follow_the_group_transform() {
let (mut s, ids) = setup(true, |s, l, group| {
let tr = s.active_comp().unwrap().layer(LayerId(l)).unwrap().props.find_group(group).unwrap().sub("transform").unwrap().clone();
s.execute("prop.set", json!({"layer": l, "prop": tr.get("scale").unwrap().uid, "value": [200.0, 200.0]})).unwrap();
s.execute("prop.set", json!({"layer": l, "prop": tr.get("position").unwrap().uid, "value": [40.0, -20.0]})).unwrap();
});
s.state.selected_props = vec![(LayerId(ids.layer), ids.start)];
let mut h = harness(s);
// Layer at the comp's centre (320, 180); group: position (40, -20), scale 200%.
let start = point(&h, &ids, ids.start);
let want = comp_to_screen(&h.ctx, [(320.0 + 40.0 + 2.0 * start[0]) as f32, (180.0 - 20.0 + 2.0 * start[1]) as f32]).unwrap();
let at = handle(&h, ids.start).expect("a Start Point handle (selecting a property in the gradient shows it)");
assert!((at - want).length() < 1.5, "the handle is where the group draws the point: {at:?} vs {want:?}");
let z = zoom(&h);
drag(&mut h, at, at + vec2(40.0, 20.0) * z);
let moved = point(&h, &ids, ids.start);
assert!(near(moved, [start[0] + 20.0, start[1] + 10.0], 1.0), "in group space, half the comp drag: {start:?} → {moved:?}");
}
/// No handles unless the gradient (or a property in it) is selected, or with layer controls off.
#[test]
fn handles_show_only_for_a_selected_gradient() {
let (s, ids) = setup(false, |_, _, _| {});
let h = harness(s);
assert!(handle(&h, ids.end).is_none(), "only the layer is selected");
let (mut s, ids) = setup(false, |_, _, _| {});
let position = s.active_comp().unwrap().layer(LayerId(ids.layer)).unwrap().props.prop("transform/position").unwrap().uid;
s.state.selected_props = vec![(LayerId(ids.layer), position)];
let h = harness(s);
assert!(handle(&h, ids.end).is_none(), "another property is selected");
let (mut s, ids) = setup(false, |_, _, _| {});
s.state.selected_props = vec![(LayerId(ids.layer), ids.gfill)];
let mut h = harness(s);
assert!(handle(&h, ids.end).is_some());
h.state_mut().ui.viewer.show_layer_controls = false;
h.run_steps(3);
assert!(handle(&h, ids.end).is_none(), "View ▸ Show Layer Controls off hides them");
}
+49
View File
@@ -0,0 +1,49 @@
//! #612: a gradient property's "Edit Gradient…" in the Timeline opens an editor. Before the fix
//! the value only painted its label: no automation id, nothing to click. This test uses only APIs
//! that existed before the Gradient Editor, so it runs (and fails) on the code without it; the
//! editor itself is tested in `ui_gradient_editor`.
use effectcraft_engine::Session;
use effectcraft_engine::project::{LayerId, PropGroup};
use effectcraft_ui_egui::EffectcraftApp;
use egui::{Event, Modifiers, PointerButton, pos2};
use egui_kittest::Harness;
use serde_json::json;
/// The uids from the layer's root down to the Gradient Fill group, and its Colors property.
fn gradient_fill(g: &PropGroup) -> Option<(Vec<u64>, u64)> {
for x in g.groups() {
if x.match_id == "gfill" {
return Some((vec![x.uid], x.get("colors")?.uid));
}
if let Some((mut path, colors)) = gradient_fill(x) {
path.insert(0, x.uid);
return Some((path, colors));
}
}
None
}
#[test]
fn the_timeline_gradient_value_opens_an_editor() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "duration": 4})).unwrap();
let l = s.execute("layer.newShape", json!({"kind": "rect"})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.addShapeItem", json!({"layer": l, "kind": "gfill"})).unwrap();
let (groups, colors) = gradient_fill(&s.active_comp().unwrap().layer(LayerId(l)).unwrap().props).expect("a Gradient Fill");
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.state_mut().ui.timeline.open_layers.insert(l);
h.state_mut().ui.timeline.open_groups.extend(groups);
h.run_steps(3);
assert!(h.state().dialog.is_none());
let id = format!("timeline.prop.{colors}.value");
let r = h.state().auto.find(&id).unwrap_or_else(|| panic!("no automation id {id}: the Timeline's Edit Gradient… isn't clickable")).rect;
let p = pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
h.input_mut().events.push(Event::PointerMoved(p));
h.step();
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(4);
assert!(h.state().dialog.is_some(), "clicking Edit Gradient… opens an editor");
}
+24
View File
@@ -72,6 +72,30 @@ fn project_rename_replaces_the_name() {
assert!(!h.ctx.egui_wants_keyboard_input(), "Enter releases the keyboard");
}
/// #881: Tab in the Project panel's rename field commits the name like Enter and gives the keyboard
/// back to the panel; it doesn't leave keyboard focus on another widget (the row's label swatch),
/// where Enter would no longer rename and the arrow keys would move between widgets.
#[test]
fn tab_in_the_project_rename_field_commits_and_keeps_enter_renaming() {
let (mut h, comp) = harness();
let name = |h: &Harness<'_, EffectcraftApp>| h.state().session.project.items.values().find(|i| i.id.0 == comp).unwrap().name.clone();
let edit = format!("project.item.{comp}.nameEdit");
let editing = |h: &Harness<'_, EffectcraftApp>| h.state().auto.elements.iter().any(|e| e.id == edit);
let p = center(&h, &format!("project.item.{comp}.name"));
click(&mut h, p, 1);
key(&mut h, Key::Enter);
type_text(&mut h, "Hero");
key(&mut h, Key::Tab);
assert_eq!(name(&h), "Hero", "Tab commits the name");
assert!(!editing(&h), "Tab closes the rename field");
assert_eq!(h.ctx.memory(|m| m.focused()), None, "no other widget takes the keyboard");
key(&mut h, Key::Enter);
assert!(editing(&h), "Enter renames again");
type_text(&mut h, "Main");
key(&mut h, Key::Enter);
assert_eq!(name(&h), "Main");
}
#[test]
fn timecode_field_replaces_commits_and_cancels() {
let (mut h, _) = harness();
+37
View File
@@ -398,3 +398,40 @@ fn properties_panel_edits_every_selected_layer() {
assert!((a - b - d).abs() < 1e-6, "same change on every layer: {before:?} → {after:?}");
}
}
/// #770: Proportional Scrubbing (After Effects 26.2). With three layers selected, a Ctrl+Alt
/// (Cmd+Opt) scrub of Position X in the Timeline leaves the first selected layer where it is,
/// moves the last by the whole change and the middle one by half, whichever layer is scrubbed.
#[test]
fn ctrl_alt_scrub_in_the_timeline_is_proportional() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Three", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap();
let mut ids = vec![];
for c in ["#e04020", "#20e040", "#2040e0"] {
let l = s.execute("layer.newSolid", json!({"color": c, "width": 40, "height": 40})).unwrap()["layer"].as_u64().unwrap();
s.execute("prop.set", json!({"layer": l, "path": "transform/position", "value": [100.0, 90.0]})).unwrap();
ids.push(l);
}
// Selection order: the first created, then the second, then the third.
for (i, l) in ids.iter().enumerate() {
s.execute("layer.select", json!({"layers": [l], "add": i > 0})).unwrap();
}
let middle = ids[1];
let uid = s.active_comp().unwrap().layer(LayerId(middle)).unwrap().props.prop("transform/position").unwrap().uid;
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "timeline.reveal.position", json!({})).unwrap();
h.run_steps(4);
let x = |h: &Harness<'_, EffectcraftApp>, l: u64| {
h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().props.prop("transform/position").unwrap().value.components()[0]
};
let e = h.state().auto.find(&format!("timeline.prop.{uid}.value.0")).cloned().expect("the middle layer's Position X shows");
let from = pos2(e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0);
let ctrl_alt = egui::Modifiers { alt: true, ctrl: true, command: true, ..Default::default() };
drag(&mut h, from, from + egui::vec2(40.0, 0.0), ctrl_alt);
let moved: Vec<f64> = ids.iter().map(|l| x(&h, *l) - 100.0).collect();
assert!(moved[2] > 1.0, "the last selected layer moved: {moved:?}");
assert!(moved[0].abs() < 1e-9, "the first selected layer stays: {moved:?}");
assert!((moved[1] - moved[2] / 2.0).abs() < 1e-6, "the middle one moves by half: {moved:?}");
}
+177
View File
@@ -0,0 +1,177 @@
//! #753: the Layer panel zooms and pans (magnification menu, View ▸ Zoom In / Zoom Out while it
//! is focused, the wheel, the Zoom and Hand tools), and the Roto Brush explains itself in the
//! Composition panel (egui_kittest, UI logic only).
use effectcraft_engine::Session;
use effectcraft_ui_egui::EffectcraftApp;
use effectcraft_ui_egui::dock::PanelKind;
use effectcraft_ui_egui::state::Tool;
use egui::{Event, Pos2, Rect, pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
fn app() -> EffectcraftApp {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "View", "width": 640, "height": 360, "duration": 4})).unwrap();
s.execute("layer.newSolid", json!({"name": "Box", "color": "#e04020", "width": 80, "height": 80})).unwrap();
EffectcraftApp::new(s)
}
fn box_id(h: &Harness<'_, EffectcraftApp>) -> u64 {
h.state().session.active_comp().unwrap().layers.iter().find(|l| l.name == "Box").unwrap().id.0
}
/// The harness with Box open in the Layer panel (focused).
fn harness() -> Harness<'static, EffectcraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| app());
h.run_steps(3);
let id = box_id(&h);
h.state_mut().session.execute("layer.select", json!({"layers": [id]})).unwrap();
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "layer.openLayer", json!({"layer": id})).unwrap();
h.run_steps(3);
assert_eq!(h.state().ui.focused, PanelKind::Layer);
h
}
fn rect(h: &Harness<'_, EffectcraftApp>, id: &str) -> Rect {
let e = h.state().auto.find(id).unwrap_or_else(|| panic!("no {id}"));
Rect::from_min_size(pos2(e.rect[0], e.rect[1]), vec2(e.rect[2], e.rect[3]))
}
fn press(h: &mut Harness<'_, EffectcraftApp>, p: Pos2, button: egui::PointerButton, pressed: bool) {
h.input_mut().events.push(Event::PointerButton { pos: p, button, pressed, modifiers: Default::default() });
}
fn click(h: &mut Harness<'_, EffectcraftApp>, p: Pos2) {
h.input_mut().events.push(Event::PointerMoved(p));
h.step();
press(h, p, egui::PointerButton::Primary, true);
h.step();
press(h, p, egui::PointerButton::Primary, false);
h.run_steps(2);
}
fn drag_with(h: &mut Harness<'_, EffectcraftApp>, button: egui::PointerButton, from: Pos2, to: Pos2) {
h.input_mut().events.push(Event::PointerMoved(from));
press(h, from, button, true);
h.step();
for i in 1..=8 {
h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (i as f32 / 8.0)));
h.step();
}
press(h, to, button, false);
h.run_steps(2);
}
fn command(h: &mut Harness<'_, EffectcraftApp>, id: &str) {
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, id, json!({})).unwrap();
h.run_steps(3);
}
/// Shown magnification: the canvas width per layer pixel (Box is 80 px wide).
fn shown(h: &Harness<'_, EffectcraftApp>) -> f32 {
rect(h, "layerPanel.canvas").width() / 80.0
}
#[test]
fn zoom_commands_act_on_the_focused_layer_panel() {
let mut h = harness();
assert!(h.state().auto.find("layerPanel.magnification").is_some(), "the Layer panel has a magnification menu");
let fit = shown(&h);
let comp_zoom = h.state().ui.viewer.zoom;
command(&mut h, "view.zoomOut");
let z = h.state().ui.layer_zoom.expect("Zoom Out sets the Layer panel's magnification");
assert!(z < fit, "{z} < {fit}");
assert!((shown(&h) - z).abs() < 0.01, "the canvas is drawn at the new magnification");
assert_eq!(h.state().ui.viewer.zoom, comp_zoom, "the Composition viewer keeps its magnification");
command(&mut h, "view.zoomIn");
assert!(h.state().ui.layer_zoom.unwrap() > z);
command(&mut h, "view.fit");
assert_eq!(h.state().ui.layer_zoom, None);
assert!((shown(&h) - fit).abs() < 0.01);
// With the Composition panel focused, the same commands zoom it instead.
h.state_mut().show_panel(PanelKind::Composition);
h.run_steps(2);
command(&mut h, "view.zoomIn");
assert!(h.state().ui.viewer.zoom.is_some());
assert_eq!(h.state().ui.layer_zoom, None);
}
#[test]
fn wheel_zooms_around_the_pointer_and_hand_tool_pans() {
let mut h = harness();
let canvas = rect(&h, "layerPanel.canvas");
// A point a quarter of the way into the layer stays under the pointer.
let at = canvas.min + canvas.size() * 0.25;
h.input_mut().events.push(Event::PointerMoved(at));
h.input_mut().events.push(Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: vec2(0.0, 120.0),
modifiers: Default::default(),
phase: egui::TouchPhase::Move,
});
h.run_steps(20);
let after = rect(&h, "layerPanel.canvas");
assert!(after.width() > canvas.width(), "the wheel zooms in: {} → {}", canvas.width(), after.width());
let still = after.min + after.size() * 0.25;
assert!(still.distance(at) < 2.0, "the point under the pointer stays put: {at:?} vs {still:?}");
// Hand tool drag pans; no paint or Roto stroke is made.
h.state_mut().ui.tool = Tool::Hand;
h.run_steps(2);
let before = rect(&h, "layerPanel.canvas").min;
let c = rect(&h, "layerPanel.area").center();
drag_with(&mut h, egui::PointerButton::Primary, c, c + vec2(60.0, 30.0));
let moved = rect(&h, "layerPanel.canvas").min - before;
assert!((moved.x - 60.0).abs() < 1.0 && (moved.y - 30.0).abs() < 1.0, "{moved:?}");
// Middle-drag pans with a Roto Brush tool, painting nothing.
h.state_mut().ui.tool = Tool::RotoBrush;
h.run_steps(2);
let before = rect(&h, "layerPanel.canvas").min;
drag_with(&mut h, egui::PointerButton::Middle, c, c - vec2(40.0, 20.0));
let moved = rect(&h, "layerPanel.canvas").min - before;
assert!((moved.x + 40.0).abs() < 1.0 && (moved.y + 20.0).abs() < 1.0, "{moved:?}");
let layer = h.state().session.active_comp().unwrap().layer(effectcraft_engine::project::LayerId(box_id(&h))).unwrap().clone();
assert!(layer.effects().is_none_or(|fx| fx.groups().count() == 0), "panning adds no Roto Brush effect");
}
#[test]
fn zoom_tool_click_zooms_in_the_layer_panel() {
let mut h = harness();
let fit = shown(&h);
h.state_mut().ui.tool = Tool::Zoom;
h.run_steps(2);
let c = rect(&h, "layerPanel.canvas").center();
click(&mut h, c);
let z = h.state().ui.layer_zoom.expect("the Zoom tool sets the Layer panel's magnification");
assert!((z - fit * 2.0).abs() < 0.01, "{fit} → {z}");
assert_eq!(h.state().ui.viewer.zoom, None, "the Composition viewer keeps Fit");
}
#[test]
fn roto_brush_in_the_composition_panel_says_where_it_works() {
let mut h = harness();
h.state_mut().show_panel(PanelKind::Composition);
h.state_mut().ui.layer_panel = None;
h.state_mut().ui.tool = Tool::RotoBrush;
h.run_steps(3);
let comp = rect(&h, "viewer.comp");
let c = comp.center();
click(&mut h, c);
assert!(h.state().ui.status.contains("Layer panel"), "a hint, not silence: {:?}", h.state().ui.status);
// Double-clicking the layer opens it in the Layer panel.
h.run_steps(30);
h.input_mut().events.push(Event::PointerMoved(c));
h.step();
// Both clicks inside egui's double-click time; the second release (its own frame, as with a
// real mouse) opens the layer after the press has focused the Composition panel.
press(&mut h, c, egui::PointerButton::Primary, true);
press(&mut h, c, egui::PointerButton::Primary, false);
press(&mut h, c, egui::PointerButton::Primary, true);
h.step();
press(&mut h, c, egui::PointerButton::Primary, false);
h.run_steps(3);
assert_eq!(h.state().ui.layer_panel, Some(box_id(&h)));
assert_eq!(h.state().ui.focused, PanelKind::Layer);
}
+21
View File
@@ -204,3 +204,24 @@ fn relink_restores_decoded_pixels_and_invalidates_viewer_content() {
assert_eq!(s.render(cid, Tick::ZERO, RenderOpts::default()).data, expected.data);
std::fs::remove_dir_all(dir).unwrap();
}
/// #767: File ▸ Import ▸ File… offers MXF footage (OP1a / OP-Atom from broadcast cameras and
/// Avid), which the Media Browser lists and the importer reads.
#[test]
fn import_dialog_offers_mxf() {
use std::cell::RefCell;
use std::rc::Rc;
let mut app = EffectcraftApp::new(Session::default());
let offered = Rc::new(RefCell::new(Vec::<String>::new()));
let seen = offered.clone();
app.hooks.pick_files = Some(Box::new(move |exts: &[&str]| {
*seen.borrow_mut() = exts.iter().map(|e| e.to_string()).collect();
Vec::new()
}));
let result = effectcraft_ui_egui::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({})).unwrap();
assert!(result.is_null(), "cancelled: nothing imported");
let offered = offered.borrow();
assert!(offered.iter().any(|e| e == "mxf"), "offered {offered:?}");
assert!(offered.iter().any(|e| e == "mov"));
}
+87
View File
@@ -0,0 +1,87 @@
//! Multiple monitors (#486): a panel moves out of the main window into a native window of its
//! own (Move Panel to New Window), which can be placed on another screen, and back.
use effectcraft_engine::Session;
use effectcraft_ui_egui::EffectcraftApp;
use effectcraft_ui_egui::dock::{PanelKind, PanelWindow};
use egui::vec2;
use egui_kittest::Harness;
use serde_json::json;
fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, params: serde_json::Value) -> Result<serde_json::Value, String> {
effectcraft_ui_egui::menus::invoke(app, ctx, "window.panelWindow", params)
}
#[test]
fn panel_window_command_moves_a_docked_panel_into_its_own_window_and_back() {
let mut app = EffectcraftApp::new(Session::default());
let ctx = egui::Context::default();
assert!(app.ui.dock.contains(PanelKind::Project));
assert_eq!(invoke(&mut app, &ctx, json!({"panel": "Project", "window": true})).unwrap(), json!({"window": true}));
// Undocked first, then given a window of its own.
assert!(!app.ui.dock.contains(PanelKind::Project));
assert!(app.ui.floating.iter().any(|group| group.panels == [PanelKind::Project]));
assert!(app.in_panel_window(PanelKind::Project));
let window = app.ui.panel_windows.iter().find(|w| w.panel == PanelKind::Project).copied().unwrap();
assert_eq!(window.rect, PanelWindow::sanitized(window.rect));
// Asking again changes nothing; no `window` toggles.
assert_eq!(invoke(&mut app, &ctx, json!({"panel": "Project", "window": true})).unwrap(), json!({"window": true}));
assert_eq!(app.ui.panel_windows.len(), 1);
assert_eq!(invoke(&mut app, &ctx, json!({"panel": "Project"})).unwrap(), json!({"window": false}));
// Back in the main window, still floating where it was.
assert!(!app.in_panel_window(PanelKind::Project));
assert!(app.ui.panel_windows.is_empty());
assert!(app.ui.floating.iter().any(|group| group.panels == [PanelKind::Project]));
// The serialized panel form works too.
assert_eq!(invoke(&mut app, &ctx, json!({"panel": PanelKind::Project})).unwrap(), json!({"window": true}));
// Bad requests are errors and change nothing.
let before = app.ui.panel_windows.clone();
for params in [json!({}), json!({"panel": "Nope"}), json!({"panel": 7}), json!({"panel": "Project", "window": "yes"}), json!({"panel": {"Viewer": 9}})] {
assert!(invoke(&mut app, &ctx, params.clone()).is_err(), "{params} must be rejected");
}
assert_eq!(app.ui.panel_windows, before);
}
#[test]
fn a_panel_in_its_own_window_leaves_the_main_window() {
let mut app = EffectcraftApp::new(Session::default());
app.ui.start_screen = false;
let mut h = Harness::builder().with_size(vec2(1200.0, 760.0)).build_eframe(move |_| app);
h.run_steps(3);
let ctx = h.ctx.clone();
invoke(h.state_mut(), &ctx, json!({"panel": "Project", "window": true})).unwrap();
h.run_steps(3);
// No in-window floating group is drawn for it (no move strip, no floating area)...
assert!(!h.state().auto.elements.iter().any(|e| e.id.starts_with("panel.float.")));
let area = egui::Id::new(("floating-panel", PanelKind::Project.id()));
assert!(!h.ctx.memory(|m| m.layer_ids().any(|layer| layer.id == area && m.areas().is_visible(&layer))));
// ...the window draws it (here embedded: the test harness has no native windows).
assert!(h.state().auto.elements.iter().any(|e| e.id == "panel.Project"));
// Docking it back into the main window closes the window entry.
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "window.dockPanel", json!({"panel": "Project", "anchor": "Timeline"})).unwrap();
h.run_steps(2);
assert!(h.state().ui.panel_windows.is_empty());
assert!(!h.state().in_panel_window(PanelKind::Project));
}
#[test]
fn panel_windows_survive_restart_with_hostile_places_made_safe() {
use effectcraft_engine::config::MemoryConfig;
use std::sync::Arc;
let store = Arc::new(MemoryConfig::default());
let mut app = EffectcraftApp::new(Session { config: Some(store.clone()), ..Default::default() });
let ctx = egui::Context::default();
invoke(&mut app, &ctx, json!({"panel": "Project", "window": true})).unwrap();
let hostile = [1.0e9, -3.0e12, 1.0e9, 0.5];
if let Some(w) = app.ui.panel_windows.first_mut() {
w.rect = hostile;
}
// A window for a panel that doesn't float is dropped on load.
app.ui.panel_windows.push(PanelWindow { panel: PanelKind::Timeline, rect: [10.0, 10.0, 300.0, 200.0] });
eframe::App::on_exit(&mut app);
let restarted = EffectcraftApp::new(Session { config: Some(store), ..Default::default() });
assert_eq!(restarted.ui.panel_windows, vec![PanelWindow { panel: PanelKind::Project, rect: PanelWindow::sanitized(hostile) }]);
let [x, y, w, h] = PanelWindow::sanitized(hostile);
assert!(x <= 100_000.0 && y >= -100_000.0 && (160.0..=16_384.0).contains(&w) && (100.0..=16_384.0).contains(&h));
assert!(PanelWindow::sanitized([f32::NAN, f32::INFINITY, f32::NAN, f32::NEG_INFINITY]).iter().all(|v| v.is_finite()));
}
+157 -26
View File
@@ -2,7 +2,9 @@
//! registers its automation ids; the Footage panel's buttons edit into the comp; the Progress
//! panel lists and cancels a job; Lumetri Scopes switch scope through their dropdown.
use effectcraft_engine::Session;
use std::sync::Arc;
use effectcraft_engine::{Session, config::MemoryConfig};
use effectcraft_ui_egui::EffectcraftApp;
use effectcraft_ui_egui::dock::PanelKind;
use egui::{Event, Pos2, pos2};
@@ -237,46 +239,147 @@ fn leaving_the_learn_workspace_closes_its_tutorials() {
}
}
/// #284: Settings ▸ Appearance ▸ UI Scale sizes the whole interface as soon as it is chosen,
/// Cancel puts it back, OK keeps it; Ctrl+0 (Window ▸ Project) doesn't reset it.
fn open_settings(h: &mut Harness<'_, EffectcraftApp>) {
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "app.settings", json!({"page": "appearance"})).unwrap();
h.run_steps(3);
}
fn key(h: &mut Harness<'_, EffectcraftApp>, key: egui::Key, modifiers: egui::Modifiers) {
for pressed in [true, false] {
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed, repeat: false, modifiers });
h.step();
}
}
/// The UI Scale setting and the zoom it gives.
fn scale(h: &Harness<'_, EffectcraftApp>) -> (u32, f32) {
(h.state().session.prefs.appearance.ui_scale, h.ctx.zoom_factor())
}
/// Types `text` into Settings' UI Scale a key at a time: nothing applies (and the field keeps
/// the keyboard) until Enter.
fn type_scale(h: &mut Harness<'_, EffectcraftApp>, text: &str) {
let before = scale(h);
click(h, "settings.appearance.uiScale");
for c in text.chars() {
h.input_mut().events.push(Event::Text(c.to_string()));
h.run_steps(2);
assert_eq!(scale(h), before, "{text}: not while typing");
assert!(h.ctx.memory(|m| m.focused().is_some()), "{text}: the field keeps the keyboard");
}
key(h, egui::Key::Enter, egui::Modifiers::NONE);
// (Settings re-centres a frame after the zoom changes.)
h.run_steps(4);
}
/// #284, #682: Settings ▸ Appearance ▸ UI Scale takes any typed percentage from 75 to 200 and
/// sizes the whole interface once it is entered, Cancel puts it back, OK keeps it and later
/// sessions start with it; Ctrl+0 (Window ▸ Project) doesn't reset it.
#[test]
fn ui_scale_setting_sizes_the_interface() {
let mut h = harness();
let ctx = h.ctx.clone();
let choose = |h: &mut Harness<'_, EffectcraftApp>, label: &str| {
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "app.settings", json!({"page": "appearance"})).unwrap();
h.run_steps(3);
click(h, "settings.appearance.uiScale");
let option = h.query_by_label(label).unwrap_or_else(|| panic!("the {label} choice")).rect().center();
click_at(h, option);
h.run_steps(2);
};
assert_eq!(ctx.zoom_factor(), 1.0);
choose(&mut h, "150%");
assert_eq!(h.state().session.prefs.appearance.ui_scale, 150);
assert_eq!(ctx.zoom_factor(), 1.5, "live");
open_settings(&mut h);
type_scale(&mut h, "85");
assert_eq!(scale(&h), (85, 0.85), "live");
click(&mut h, "settings.cancel");
h.run_steps(2);
assert_eq!((h.state().session.prefs.appearance.ui_scale, ctx.zoom_factor()), (100, 1.0), "Cancel put it back");
choose(&mut h, "125%");
assert_eq!(scale(&h), (100, 1.0), "Cancel put it back");
open_settings(&mut h);
type_scale(&mut h, "300");
assert_eq!(scale(&h), (200, 2.0), "at most 200");
click(&mut h, "settings.cancel");
h.run_steps(2);
assert_eq!(scale(&h), (100, 1.0), "Cancel put it back from 200 %");
open_settings(&mut h);
type_scale(&mut h, "50");
assert_eq!(scale(&h), (75, 0.75), "at least 75");
type_scale(&mut h, "90");
click(&mut h, "settings.ok");
h.run_steps(2);
assert_eq!(h.state().dialog, None);
assert_eq!((h.state().session.prefs.appearance.ui_scale, ctx.zoom_factor()), (125, 1.25), "OK kept it");
assert_eq!(scale(&h), (90, 0.9), "OK kept it");
// Ctrl+0 opens the Project panel; egui's own Ctrl+0 zoom reset stays out of it.
for pressed in [true, false] {
h.input_mut().events.push(Event::Key { key: egui::Key::Num0, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::COMMAND });
h.step();
}
key(&mut h, egui::Key::Num0, egui::Modifiers::COMMAND);
h.run_steps(2);
assert_eq!(ctx.zoom_factor(), 1.25);
assert_eq!(ctx.zoom_factor(), 0.9);
// A saved scale applies from the first frame.
let mut s = Session::default();
s.prefs.set("appearance.uiScale", json!(175)).unwrap();
let s = Session { prefs: effectcraft_engine::prefs::Prefs::from_json(&h.state().session.prefs.to_json()), ..Default::default() };
let mut h2 = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h2.run_steps(3);
assert_eq!(h2.ctx.zoom_factor(), 1.75);
assert_eq!(h2.ctx.zoom_factor(), 0.9);
}
/// Settings' Previous / Next / Cancel / OK stay whole and in view at 200 % in a 1600×1000
/// window (they scrolled out of the dialog with its pages): the page scrolls under them, Cancel
/// restores the settings and OK saves them.
#[test]
fn settings_buttons_stay_in_view_at_200_percent() {
let store = Arc::new(MemoryConfig::default());
let saved = || {
let mut s = Session { config: Some(store.clone()), ..Default::default() };
s.prefs.disk.disk_cache_enabled = false;
s.load_settings();
s.prefs.appearance.ui_scale
};
let mut s = Session { config: Some(store.clone()), ..Default::default() };
s.prefs.disk.disk_cache_enabled = false;
s.prefs.set("appearance.uiScale", json!(200)).unwrap();
s.save_prefs();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
assert_eq!(scale(&h), (200, 2.0));
let rect = |h: &Harness<'_, EffectcraftApp>, id: &str| {
let e = h.state().auto.find(id).unwrap_or_else(|| panic!("no {id}"));
egui::Rect::from_min_size(pos2(e.rect[0], e.rect[1]), egui::vec2(e.rect[2], e.rect[3]))
};
// Whole: inside the window, and painted with none of them clipped away.
let buttons = |h: &Harness<'_, EffectcraftApp>| {
["previous", "next", "cancel", "ok"].map(|b| {
let r = rect(h, &format!("settings.{b}"));
let clip = h
.output()
.shapes
.iter()
.find(|c| matches!(&c.shape, egui::Shape::Rect(s) if (s.rect.center() - r.center()).length() < 0.5))
.map(|c| c.clip_rect);
assert!(h.ctx.content_rect().contains_rect(r) && clip.is_some_and(|c| c.contains_rect(r)), "{b} is cut off: {r:?} in {clip:?}");
r
})
};
let scroll_page = |h: &mut Harness<'_, EffectcraftApp>| {
let at = rect(h, "settings.appearance.appearanceMode").center();
h.input_mut().events.push(Event::PointerMoved(at));
h.input_mut().events.push(Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -1000.0),
modifiers: Default::default(),
phase: egui::TouchPhase::Move,
});
h.run_steps(5);
};
open_settings(&mut h);
let footer = buttons(&h);
let field = rect(&h, "settings.appearance.uiScale");
scroll_page(&mut h);
assert_eq!(buttons(&h), footer, "the buttons don't scroll with the page");
let scrolled = rect(&h, "settings.appearance.uiScale");
assert!(scrolled.top() < field.top() && scrolled.bottom() < footer[2].top(), "the page scrolled to UI Scale: {field:?} -> {scrolled:?}");
for (button, kept) in [("settings.cancel", 200), ("settings.ok", 150)] {
if h.state().dialog.is_none() {
open_settings(&mut h);
scroll_page(&mut h);
}
type_scale(&mut h, "150");
assert_eq!(scale(&h), (150, 1.5));
buttons(&h);
click(&mut h, button);
h.run_steps(2);
assert_eq!(h.state().dialog, None, "{button} closed Settings");
assert_eq!((scale(&h), saved()), ((kept, kept as f32 / 100.0), kept), "{button}");
}
}
/// Headless look at the panels (wgpu offscreen; needs a GPU adapter). Run with
@@ -362,3 +465,31 @@ fn essential_graphics_scale_keeps_constrain_proportions() {
let unlinked = scale(&h);
assert!(unlinked[0] > linked[0] && unlinked[1] == linked[1], "unlinked, X moves alone: {unlinked:?}");
}
/// #757: Effects & Presets lists the built-in Transitions presets under * Animation Presets;
/// double-clicking one applies it to the selected layer (effect plus keyframes).
#[test]
fn transition_presets_apply_from_effects_and_presets() {
let mut h = harness();
let layer = h.state().session.active_comp().unwrap().layers[0].id.0;
h.state_mut().session.execute("layer.select", json!({"layers": [layer]})).unwrap();
open(&mut h, "effectsPresets");
h.state_mut().ui.effects_search = "clock reveal".into();
h.run_steps(3);
assert!(h.state().auto.find("effects.category.presets/Transitions").is_some(), "the Transitions folder is listed");
let e = h.state().auto.find("effects.preset.builtin.clockReveal").expect("Clock Reveal is listed").clone();
let p: Pos2 = pos2(e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0);
h.input_mut().events.push(Event::PointerMoved(p));
h.step();
// Both clicks in one frame: the harness' frame time is longer than a double-click's.
for _ in 0..2 {
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
}
}
h.run_steps(3);
let comp = h.state().session.active_comp().unwrap();
let fx = comp.layers[0].effects().unwrap().groups().next().expect("an effect was added").clone();
assert_eq!(fx.name, "Radial Wipe");
assert_eq!(fx.prop("completion").unwrap().keys.len(), 2);
}
+224
View File
@@ -0,0 +1,224 @@
//! Project panel keyboard navigation and accessibility (#776): the arrow keys move and extend the
//! selection and open / close folders, as in After Effects; the rows, sort headers and row buttons
//! reach screen readers with names, roles and states; a row focused with Tab keeps the arrows, and
//! keyboard focus follows the selection.
use effectcraft_engine::Session;
use effectcraft_engine::project::{ItemId, ItemKind};
use effectcraft_ui_egui::EffectcraftApp;
use effectcraft_ui_egui::dock::PanelKind;
use egui::accesskit::Role;
use egui::{Event, Key, Modifiers, Pos2, pos2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
/// A closed folder holding a comp, and a solid at the project root: (harness, folder, comp, solid).
fn harness() -> (Harness<'static, EffectcraftApp>, ItemId, ItemId, ItemId) {
let mut s = Session::default();
let comp = ItemId(s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "duration": 4})).unwrap()["comp"].as_u64().unwrap());
s.execute("layer.newSolid", json!({"name": "Solid", "color": "#406080"})).unwrap();
let solid = s.project.items.values().find(|i| matches!(i.kind, ItemKind::Solid(_))).unwrap().id;
let folder = ItemId(s.execute("project.newFolder", json!({"name": "Folder"})).unwrap()["item"].as_u64().unwrap());
s.execute("project.move", json!({"items": [comp.0], "folder": folder.0})).unwrap();
s.execute("project.move", json!({"items": [solid.0], "folder": null})).unwrap();
s.execute("project.select", json!({"items": []})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
(h, folder, comp, solid)
}
fn center(h: &Harness<'_, EffectcraftApp>, id: &str) -> Pos2 {
let e = h.state().auto.find(id).unwrap_or_else(|| panic!("no {id}")).clone();
pos2(e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0)
}
fn click(h: &mut Harness<'_, EffectcraftApp>, id: &str) {
let p = center(h, id);
h.input_mut().events.push(Event::PointerMoved(p));
h.step();
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(3);
}
/// Press and release `key` with `modifiers` (one frame each), then let the UI settle.
fn key(h: &mut Harness<'_, EffectcraftApp>, key: Key, modifiers: Modifiers) {
for pressed in [true, false] {
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed, repeat: false, modifiers });
h.step();
}
h.run_steps(2);
}
/// The item rows on screen, top to bottom.
fn rows(h: &Harness<'_, EffectcraftApp>) -> Vec<ItemId> {
let mut rows: Vec<(f32, ItemId)> = h
.state()
.auto
.query("project.item.")
.into_iter()
.filter_map(|e| e.id.strip_prefix("project.item.").and_then(|n| n.parse().ok()).map(|n| (e.rect[1], ItemId(n))))
.collect();
rows.sort_by(|a, b| a.0.total_cmp(&b.0));
rows.into_iter().map(|(_, id)| id).collect()
}
fn selection(h: &Harness<'_, EffectcraftApp>) -> Vec<ItemId> {
h.state().session.state.project_selection.clone()
}
#[test]
fn arrow_keys_move_and_extend_the_project_selection() {
let (mut h, _, _, _) = harness();
let rows = rows(&h);
assert!(rows.len() >= 2, "rows: {rows:?}");
let (first, second) = (rows[0], rows[1]);
click(&mut h, &format!("project.item.{}.name", first.0));
assert_eq!(h.state().ui.focused, PanelKind::Project);
assert_eq!(selection(&h), vec![first]);
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection(&h), vec![second], "Down Arrow selects the next item");
key(&mut h, Key::ArrowUp, Modifiers::NONE);
assert_eq!(selection(&h), vec![first], "Up Arrow selects the previous item");
key(&mut h, Key::ArrowUp, Modifiers::NONE);
assert_eq!(selection(&h), vec![first], "the first item stays selected at the top");
for _ in 0..rows.len() + 1 {
key(&mut h, Key::ArrowDown, Modifiers::SHIFT);
}
assert_eq!(selection(&h), rows, "Shift+Down Arrow extends the selection to the last item");
key(&mut h, Key::ArrowUp, Modifiers::SHIFT);
assert_eq!(selection(&h), rows[..rows.len() - 1], "Shift+Up Arrow shrinks it back toward the anchor");
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection(&h), vec![rows[rows.len() - 1]], "a plain arrow selects one item again");
// With nothing selected, Down selects the first item and Up the last.
h.state_mut().session.state.project_selection.clear();
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection(&h), vec![first]);
h.state_mut().session.state.project_selection.clear();
key(&mut h, Key::ArrowUp, Modifiers::NONE);
assert_eq!(selection(&h), vec![rows[rows.len() - 1]]);
}
#[test]
fn right_and_left_arrows_open_and_close_the_selected_folder() {
let (mut h, folder, comp, _) = harness();
click(&mut h, &format!("project.item.{}.name", folder.0));
assert!(!rows(&h).contains(&comp), "the folder starts closed");
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert!(h.state().ui.project_open_folders.contains(&folder.0), "Right Arrow opens the selected folder");
assert!(rows(&h).contains(&comp));
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection(&h), vec![comp], "Down Arrow walks into the open folder");
key(&mut h, Key::ArrowLeft, Modifiers::NONE);
assert_eq!(selection(&h), vec![folder], "Left Arrow on an item in a folder selects the folder");
key(&mut h, Key::ArrowLeft, Modifiers::NONE);
assert!(!h.state().ui.project_open_folders.contains(&folder.0), "Left Arrow closes the selected folder");
assert_eq!(selection(&h), vec![folder]);
}
#[test]
fn arrows_leave_the_project_selection_alone_when_another_panel_has_focus() {
let (mut h, folder, _, _) = harness();
click(&mut h, &format!("project.item.{}.name", folder.0));
h.state_mut().ui.focused = PanelKind::Timeline;
key(&mut h, Key::ArrowDown, Modifiers::NONE);
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert_eq!(selection(&h), vec![folder]);
assert!(!h.state().ui.project_open_folders.contains(&folder.0));
}
#[test]
fn rows_and_headers_have_accessible_names_roles_and_states() {
let (mut h, folder, _, _) = harness();
click(&mut h, &format!("project.item.{}.name", folder.0));
let row = h.get_by_label("Folder, Folder");
let node = row.accesskit_node();
assert_eq!(node.role(), Role::TreeItem);
assert_eq!(node.is_selected(), Some(true), "the selected row says so");
assert_eq!(node.data().is_expanded(), Some(false), "a closed folder says so");
assert_eq!(node.data().level(), Some(1));
let solid = h.get_by_label("Solid, Solid");
assert_eq!(solid.accesskit_node().is_selected(), Some(false));
assert_eq!(solid.accesskit_node().data().is_expanded(), None, "only folders open");
assert_eq!(h.get_by_label("Sort by Name, ascending").accesskit_node().role(), Role::Button);
assert_eq!(h.get_by_label("Open folder Folder").accesskit_node().role(), Role::Button);
assert_eq!(h.get_by_label("Delete selected project items").accesskit_node().role(), Role::Button);
assert!(h.query_by_label_contains("Label of Folder: ").is_some(), "the label swatch is named");
assert!(h.query_by_label("Create a new Folder").is_some());
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert_eq!(h.get_by_label("Folder, Folder").accesskit_node().data().is_expanded(), Some(true));
assert_eq!(h.get_by_label("Main, Composition").accesskit_node().data().level(), Some(2), "the comp sits one level down");
}
#[test]
fn a_focused_row_keeps_the_arrows_and_focus_follows_the_selection() {
let (mut h, _, _, _) = harness();
let rows = rows(&h);
let names: Vec<String> = rows
.iter()
.map(|id| {
let it = h.state().session.project.item(*id).unwrap();
format!("{}, {}", it.name, it.type_name())
})
.collect();
// Focus the first row the way a screen reader (or Tab) does, without a click: the panel
// takes focus with it.
h.state_mut().ui.focused = PanelKind::Timeline;
h.get_by_label(&names[0]).focus();
h.run_steps(3);
assert!(h.get_by_label(&names[0]).is_focused());
assert_eq!(h.state().ui.focused, PanelKind::Project, "keyboard focus on a row focuses the panel");
// A plain arrow moved egui's focus to the widget below; here it moves the selection and the
// focus with it.
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection(&h), vec![rows[0]], "nothing was selected: Down selects the first item");
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection(&h), vec![rows[1]]);
assert!(h.get_by_label(&names[1]).is_focused(), "keyboard focus follows the selection");
key(&mut h, Key::ArrowUp, Modifiers::NONE);
assert_eq!(selection(&h), vec![rows[0]]);
assert!(h.get_by_label(&names[0]).is_focused());
}
/// A mouse click on a row gives no keyboard focus to the row, so the app's shortcuts run as
/// before the arrow keys came: Delete / Backspace delete, Cmd+D duplicates, Enter renames, also
/// after an arrow key moved the selection.
#[test]
fn shortcuts_still_run_after_a_mouse_click_and_the_arrows() {
let focus = |h: &Harness<'_, EffectcraftApp>| h.ctx.memory(|m| m.focused());
for delete_key in [Key::Delete, Key::Backspace] {
let (mut h, folder, _, _) = harness();
let empty = ItemId(h.state_mut().session.execute("project.newFolder", json!({"name": "Empty"})).unwrap()["item"].as_u64().unwrap());
h.run_steps(2);
click(&mut h, &format!("project.item.{}.name", empty.0));
assert_eq!(selection(&h), vec![empty]);
assert_eq!(focus(&h), None, "a click gives the row no keyboard focus");
key(&mut h, delete_key, Modifiers::NONE);
assert!(h.state().session.project.item(empty).is_none(), "{delete_key:?} deletes the clicked item");
// Click, an arrow, then the shortcut.
let empty2 = ItemId(h.state_mut().session.execute("project.newFolder", json!({"name": "Empty 2"})).unwrap()["item"].as_u64().unwrap());
h.run_steps(2);
let rows = rows(&h);
let at = rows.iter().position(|r| *r == empty2).unwrap();
let from = if at > 0 { rows[at - 1] } else { rows[at + 1] };
click(&mut h, &format!("project.item.{}.name", from.0));
key(&mut h, if at > 0 { Key::ArrowDown } else { Key::ArrowUp }, Modifiers::NONE);
assert_eq!(selection(&h), vec![empty2]);
assert_eq!(focus(&h), None, "the arrows don't take keyboard focus after a click");
key(&mut h, delete_key, Modifiers::NONE);
assert!(h.state().session.project.item(empty2).is_none(), "{delete_key:?} deletes the item the arrow moved to");
assert!(h.state().session.project.item(folder).is_some());
}
let (mut h, folder, _, solid) = harness();
// Folders can't be duplicated (engine rule): duplicate the solid.
click(&mut h, &format!("project.item.{}.name", solid.0));
let n = h.state().session.project.items.len();
key(&mut h, Key::D, Modifiers::COMMAND);
assert_eq!(h.state().session.project.items.len(), n + 1, "Cmd+D duplicates the clicked item");
click(&mut h, &format!("project.item.{}.name", folder.0));
key(&mut h, Key::Enter, Modifiers::NONE);
assert!(h.state().auto.find(&format!("project.item.{}.nameEdit", folder.0)).is_some(), "Enter renames the clicked item");
}
+7 -2
View File
@@ -127,16 +127,21 @@ fn footage_context_menu_interprets_the_footage() {
}
h.run_steps(2);
};
// The menu's Interpret Footage entry, not the panel's footer button of the same name.
let menu_entry = |h: &Harness<'_, EffectcraftApp>| {
let footer = center(h, "project.interpret");
h.query_all_by_label_contains("Interpret Footage").find(|n| !n.rect().contains(footer)).map(|n| n.rect())
};
let at = center(&h, &format!("project.item.{}.name", solid.0));
right_click(&mut h, at);
assert_eq!(h.state().session.state.project_selection, vec![solid]);
assert!(h.query_by_label_contains("Interpret Footage").is_none(), "a solid isn't footage");
assert!(menu_entry(&h).is_none(), "a solid isn't footage");
h.input_mut().events.push(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(2);
let at = center(&h, &format!("project.item.{}.name", clip.0));
right_click(&mut h, at);
assert_eq!(h.state().session.state.project_selection, vec![clip], "right-click selects the item");
let sub = h.query_by_label_contains("Interpret Footage").expect("Interpret Footage in the menu").rect();
let sub = menu_entry(&h).expect("Interpret Footage in the menu");
h.input_mut().events.push(Event::PointerMoved(sub.center()));
h.run_steps(3);
let main = h.query_by_label_contains("Main...").expect("Interpret Footage ▸ Main...").rect();
+4 -1
View File
@@ -136,8 +136,11 @@ fn cached_frames_are_counted_at_one_third_resolution() {
let mut s = Session::default();
let c = s.execute("comp.new", json!({"name": "Third", "width": 64, "height": 36, "duration": 1})).unwrap()["comp"].as_u64().unwrap();
s.execute("layer.newSolid", json!({"color": "#3080ff"})).unwrap();
// Each composition keeps its own Resolution (#417).
if let Some(comp) = std::sync::Arc::make_mut(&mut s.project).comp_mut(ItemId(c)) {
comp.resolution = res;
}
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| EffectcraftApp::new(s));
h.state_mut().ui.viewer.res = res;
settle(&mut h);
let series = h.state().shown_series(ItemId(c));
assert_eq!(series.scale, (res.scale(1.0, 1.0) * 1000.0).round() as u32, "{res:?}");
+47
View File
@@ -224,3 +224,50 @@ fn on_draw_concave_fills_and_images_render() {
h.state_mut().session.execute("scriptui.close", json!({})).unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// ScriptUI mouse events (#766): the pointer over a script window reaches the script's
/// `addEventListener` listeners (element-relative position, button, click count), and a
/// pointer click on a checkbox with a click listener toggles it once.
#[test]
fn script_windows_send_mouse_events_to_listeners() {
let mut h = harness();
let code = r#"
var w = new Window("palette", "Pad");
var pad = w.add("group", undefined, undefined, { name: "pad" });
pad.preferredSize = [120, 80];
var log = w.add("statictext", undefined, "", { name: "log" });
log.preferredSize = [400, 20];
var snap = w.add("checkbox", undefined, "Snap", { name: "snap" });
var seen = [];
var rec = function (e) { seen.push(e.type + " " + Math.round(e.clientX) + "," + Math.round(e.clientY) + " b" + e.button + " d" + e.detail); log.text = seen.join("|"); };
pad.addEventListener("mouseover", rec);
pad.addEventListener("mousedown", rec);
pad.addEventListener("mouseup", rec);
pad.addEventListener("click", rec);
snap.addEventListener("click", function (e) { log.text = "snap " + snap.value + " d" + e.detail; });
w.show();
"#;
let r = h.state_mut().session.execute("script.run", json!({"code": code, "name": "pad.jsx"})).unwrap();
assert_eq!(r["ok"], true, "{r}");
h.run_steps(3);
let win = h.state().session.script_ui.windows[0].id;
let text = |h: &Harness<'_, EffectcraftApp>, name: &str| h.state().session.script_ui.windows[0].root.lookup(&json!(name)).cloned().unwrap();
let pad = rect(&h, &format!("scriptui.{win}.pad"));
let at = pad.min + vec2(10.0, 20.0);
click_at(&mut h, at);
assert_eq!(text(&h, "log").text, "mouseover 10,20 b0 d0|mousedown 10,20 b0 d1|mouseup 10,20 b0 d1|click 10,20 b0 d1");
click(&mut h, &format!("scriptui.{win}.snap"));
let (snap, log) = (text(&h, "snap"), text(&h, "log"));
assert!(snap.checked, "toggled once");
assert_eq!(log.text, "snap true d1");
h.state_mut().session.execute("scriptui.close", json!({})).unwrap();
}
fn click_at(h: &mut Harness<'_, EffectcraftApp>, c: egui::Pos2) {
h.input_mut().events.push(Event::PointerMoved(c));
h.run_steps(1);
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerButton { pos: c, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
}
h.run_steps(3);
}
+46 -3
View File
@@ -47,11 +47,15 @@ fn check_info_transaction(via_escape: bool) {
let edited_brightness = h.state().session.prefs.appearance.brightness;
assert!((edited_brightness - original_brightness).abs() > 0.01, "real brightness slider changed");
assert_eq!(saved(&store).prefs.appearance.brightness, original_brightness, "unconfirmed edit is not saved");
// Use the upstream percent-valued Scale choice; keyboard zoom is deliberately disabled.
// Type a UI Scale; keyboard zoom is deliberately disabled.
let at = rect(&h, "settings.appearance.uiScale").center();
click(&mut h, at);
let at = h.get_by_label("125%").rect().center();
click(&mut h, at);
h.event(Event::Text("125".into()));
for pressed in [true, false] {
h.event(Event::Key { key: Key::Enter, physical_key: Some(Key::Enter), pressed, repeat: false, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(2);
assert_eq!(h.state().session.prefs.appearance.ui_scale, 125);
assert_eq!(saved(&store).prefs.appearance.ui_scale, 100, "unconfirmed scale edit is not saved");
// Let UI Scale settle the centered dialog before reading its next hit target.
@@ -111,3 +115,42 @@ fn gpu_information_ok_returns_to_settings_and_cancel_restores_preferences() {
fn gpu_information_escape_returns_to_settings_and_ok_saves_preferences() {
check_info_transaction(true);
}
/// GPU Information names the adapter the window got and says why the compositor is off, so a
/// card that the compositor could not use does not look undetected (#596).
#[test]
fn gpu_information_names_the_adapter_and_why_the_gpu_is_off() {
let session = Session {
accel_note: Some("GPU compositor unavailable: no compute shaders".into()),
window_adapter: Some("NVIDIA GeForce RTX 4070 (Dx12, DiscreteGpu)".into()),
..Default::default()
};
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(session));
h.run_steps(4);
let ctx = h.ctx.clone();
menus::invoke(h.state_mut(), &ctx, "app.gpuInfo", json!({})).unwrap();
h.run_steps(3);
assert_eq!(h.state().dialog, Some(Dialog::Info));
assert!(h.query_by_label_contains("Window graphics: NVIDIA GeForce RTX 4070").is_some(), "the window's adapter is shown");
assert!(h.query_by_label_contains("GPU compositing is off: GPU compositor unavailable").is_some(), "the reason is shown");
}
#[test]
fn gpu_information_dialog_stays_in_place() {
let mut session = Session::default();
session.prefs.appearance.ui_scale = 125;
session.execute("comp.new", json!({"width":32,"height":32,"duration":2})).unwrap();
let mut h = Harness::builder().with_size(vec2(1280.0, 720.0)).build_eframe(|_| EffectcraftApp::new(session));
h.run_steps(4);
let ctx = h.ctx.clone();
menus::invoke(h.state_mut(), &ctx, "app.settings", json!({"page":"previews"})).unwrap();
h.run_steps(3);
let button = rect(&h, "settings.button.GPU Information").center();
click(&mut h, button);
let start = h.get_by_label("GPU Information").rect();
for _ in 0..20 {
h.step();
let current = h.get_by_label("GPU Information").rect();
assert!((current.min - start.min).length() < 1.0, "GPU Information dialog moved");
}
}
+12
View File
@@ -167,6 +167,18 @@ fn nested_comp_markers_show_on_the_precomp_bar() {
assert!((h.state().session.time().seconds() - 1.0).abs() < 0.034, "{}", h.state().session.time().seconds());
}
/// #637: double-clicking a precomp layer's bar opens its comp, as double-clicking its name does.
#[test]
fn double_clicking_a_precomp_bar_opens_its_comp() {
let (mut h, pre, main) = harness();
h.state_mut().session.execute("comp.open", json!({"comp": main})).unwrap();
h.run_steps(4);
let l = h.state().session.project.comp(ItemId(main)).unwrap().layers[0].id.0;
let bar = rect(&h, &format!("timeline.layer.{l}.bar"));
click_n(&mut h, bar.center(), 2);
assert_eq!(h.state().session.active_comp_id(), Some(ItemId(pre)));
}
/// Issue #46: a panel dragged by its panel-menu (hamburger) button onto the left edge of another
/// group docks there as its own group; dragging the gap between panels resizes them.
#[test]
+187
View File
@@ -160,6 +160,137 @@ fn type_tool_click_type_edit_and_commit() {
assert!(h.state().session.state.text_edit.is_none());
}
/// #831: clicking another panel (a solid's row in the Timeline) ends text editing and gives the
/// keyboard back, whether the edit began with the Type tool (which stays selected) or by command:
/// typed characters change no text and Space plays. The Character panel keeps the edit, and a
/// text layer clicked into being and left empty goes away.
#[test]
fn clicking_another_panel_stops_typing_into_text() {
for type_tool in [false, true] {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Type", "width": 640, "height": 360, "duration": 2})).unwrap();
let solid = s.execute("layer.newSolid", json!({"name": "Plate", "color": "#406080"})).unwrap()["layer"].as_u64().unwrap();
let title =
s.execute("layer.newText", json!({"text": "Title", "size": 80, "position": [100, 120], "justify": "left"})).unwrap()["layer"].as_u64().unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_| EffectcraftApp::new(s));
h.state_mut().show_panel(PanelKind::Composition);
h.run_steps(3);
let layers = |h: &Harness<'_, EffectcraftApp>| h.state().session.active_comp().unwrap().layers.len();
// (Its row moves down as text layers are added.)
let row = |h: &Harness<'_, EffectcraftApp>| rect(h, &format!("timeline.layer.{solid}.row")).center();
if type_tool {
h.state_mut().ui.tool = effectcraft_ui_egui::state::Tool::Type;
h.run_steps(1);
let at = rect(&h, "viewer.comp").center();
click(&mut h, at, Modifiers::NONE);
assert_eq!(layers(&h), 3, "the Type tool started a text layer");
let at_row = row(&h);
click(&mut h, at_row, Modifiers::NONE);
assert_eq!(layers(&h), 2, "left empty, it is removed");
click(&mut h, at, Modifiers::NONE);
} else {
h.state_mut().session.execute("text.edit", json!({"layer": title})).unwrap();
h.run_steps(2);
}
type_text(&mut h, "Hello");
// The Character panel formats the selection and keeps the edit: typing carries on.
key(&mut h, Key::ArrowLeft, Modifiers::SHIFT);
let range = edited(&h);
h.state_mut().show_panel(PanelKind::Character);
h.run_steps(3);
let bold = rect(&h, "character.fauxBold").center();
click(&mut h, bold, Modifiers::NONE);
assert_eq!(edited(&h), range, "type_tool {type_tool}: Character keeps the edit and its selection");
key(&mut h, Key::End, Modifiers::NONE);
type_text(&mut h, "!");
let (lid, text, ..) = edited(&h);
assert!(text.ends_with("Hello!"), "typing goes into the text: {text:?}");
let at_row = row(&h);
click(&mut h, at_row, Modifiers::NONE);
assert!(h.state().session.state.text_edit.is_none(), "type_tool {type_tool}: clicking the Timeline ends the edit");
assert_eq!(h.state().session.state.selected_layers, vec![LayerId(solid)]);
assert!(!h.ctx.memory(|m| m.focused().is_some()), "the keyboard is the app's again");
type_text(&mut h, "abc");
assert!(!h.state().playback.playing);
h.input_mut().events.push(Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::Text(" ".into()));
h.input_mut().events.push(Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(2);
assert_eq!(layer_doc(&h.state().session, LayerId(lid)).unwrap().text, text, "type_tool {type_tool}: the text is unchanged");
assert!(h.state().playback.playing, "type_tool {type_tool}: Space plays");
assert_eq!(type_tool, matches!(h.state().ui.tool, effectcraft_ui_egui::state::Tool::Type), "the tool is kept");
}
}
/// #831: opening a formatting panel's tab behind Effects & Presets in its group (Properties, in
/// Undocked Panels) keeps the edit and its selected characters: the press on the tab used to
/// focus the shown panel and end the edit, after which Faux Bold styled the whole layer.
#[test]
fn opening_a_formatting_tab_keeps_the_text_selection() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Type", "width": 640, "height": 360, "duration": 2})).unwrap();
let lid =
s.execute("layer.newText", json!({"text": "Hello world", "size": 80, "position": [60, 200], "justify": "left"})).unwrap()["layer"].as_u64().unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_| EffectcraftApp::new(s));
h.run_steps(3);
let ctx = h.ctx.clone();
// Effects & Presets shown, Properties, Character and Paragraph behind it.
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "window.workspace", json!({"name": "Undocked Panels"})).unwrap();
h.state_mut().session.execute("text.edit", json!({"layer": lid})).unwrap();
h.state_mut().session.execute("text.setSelection", json!({"anchor": 0, "caret": 5})).unwrap();
h.run_steps(3);
assert!(h.state().auto.find("properties.text.style").is_none(), "Properties is behind Effects & Presets");
let tab = rect(&h, "panel.tab.Properties").center();
click(&mut h, tab, Modifiers::NONE);
assert!(h.state().auto.find("properties.text.style").is_some(), "the tab opened Properties");
assert_eq!(edited(&h), (lid, "Hello world".into(), 0, 5), "the edit and its selection are kept");
h.state_mut().show_panel(PanelKind::Character);
h.run_steps(3);
let bold = rect(&h, "character.fauxBold").center();
click(&mut h, bold, Modifiers::NONE);
let doc = layer_doc(&h.state().session, LayerId(lid)).unwrap();
assert!(doc.style_at(1).faux_bold && !doc.style_at(7).faux_bold, "only \"Hello\" is bold");
}
/// #831: a click away and keys in one frame's input. The text gets the keys typed before the
/// click and none after it; those later keys don't run as shortcuts either (Delete would remove a
/// layer). From the next frame the keys are the app's: Space plays.
#[test]
fn keys_after_a_click_away_in_the_same_frame_skip_the_text() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Type", "width": 640, "height": 360, "duration": 2})).unwrap();
let solid = s.execute("layer.newSolid", json!({"name": "Plate", "color": "#406080"})).unwrap()["layer"].as_u64().unwrap();
let lid = s.execute("layer.newText", json!({"text": "Hello", "size": 80, "position": [60, 200], "justify": "left"})).unwrap()["layer"].as_u64().unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_| EffectcraftApp::new(s));
h.state_mut().show_panel(PanelKind::Composition);
h.run_steps(3);
h.state_mut().session.execute("text.edit", json!({"layer": lid, "caret": 5})).unwrap();
h.run_steps(2);
let row = rect(&h, &format!("timeline.layer.{solid}.row")).center();
let key = |key: Key, pressed: bool| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE };
h.input_mut().events.extend([
Event::Text("A".into()),
Event::PointerMoved(row),
Event::PointerButton { pos: row, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
Event::PointerButton { pos: row, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
Event::Text("x".into()),
key(Key::Space, true),
Event::Text(" ".into()),
key(Key::Space, false),
key(Key::Delete, true),
key(Key::Delete, false),
]);
h.run_steps(3);
let comp = |h: &Harness<'_, EffectcraftApp>| h.state().session.active_comp().unwrap().layers.len();
assert_eq!(layer_doc(&h.state().session, LayerId(lid)).unwrap().text, "HelloA", "only the key before the click");
assert!(h.state().session.state.text_edit.is_none(), "the click ended the edit");
assert_eq!((comp(&h), h.state().playback.playing), (2, false), "the keys after it ran no shortcut");
h.input_mut().events.extend([key(Key::Space, true), Event::Text(" ".into()), key(Key::Space, false)]);
h.run_steps(2);
assert!(h.state().playback.playing, "Space plays");
assert_eq!(layer_doc(&h.state().session, LayerId(lid)).unwrap().text, "HelloA");
}
#[test]
fn switching_from_type_to_selection_commits_and_moves_text_layer() {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app());
@@ -277,3 +408,59 @@ fn type_tool_drag_makes_paragraph_text_with_box_handles() {
assert!(doc2.box_size.unwrap()[0] > bs[0] + 20.0, "{:?}", doc2.box_size);
assert!(h.state().session.state.text_edit.is_some(), "still editing after resizing");
}
/// #866: Layer ▸ New ▸ Text (menu or its shortcut) puts an insertion point in the comp, as After
/// Effects does, so typed keys reach Source Text (and the layer name follows) instead of running
/// shortcuts while the layer keeps the placeholder "Text".
#[test]
fn layer_new_text_menu_and_shortcut_start_typing_into_source_text() {
for via_shortcut in [false, true] {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Type", "width": 640, "height": 360, "duration": 2})).unwrap();
s.execute("layer.newSolid", json!({"color": "#ffffff"})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_| EffectcraftApp::new(s));
h.state_mut().show_panel(PanelKind::Composition);
h.run_steps(3);
if via_shortcut {
key(&mut h, Key::T, Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT);
} else {
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "layer.newText", json!({})).unwrap();
h.run_steps(2);
}
let (lid, text, _, _) = edited(&h);
assert_eq!(text, "", "no placeholder to type over (shortcut: {via_shortcut})");
type_text(&mut h, "My First Project");
key(&mut h, Key::Escape, Modifiers::NONE);
assert!(h.state().session.state.text_edit.is_none(), "Escape commits");
let s = &h.state().session;
assert_eq!(layer_doc(s, LayerId(lid)).unwrap().text, "My First Project", "typed text is the Source Text");
assert_eq!(s.active_comp().unwrap().layer(LayerId(lid)).unwrap().name, "My First Project", "the name follows the text");
}
}
/// Double-clicking a text layer in the Timeline, on its name or on its bar, edits its text in the
/// Composition viewer with the whole text selected, as in After Effects (Enter renames).
#[test]
fn timeline_double_click_on_a_text_layer_edits_its_text() {
for target in ["row", "bar"] {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Type", "width": 640, "height": 360, "duration": 2})).unwrap();
let lid = s.execute("layer.newText", json!({"text": "alpha beta"})).unwrap()["layer"].as_u64().unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_| EffectcraftApp::new(s));
h.state_mut().show_panel(PanelKind::Composition);
h.run_steps(3);
let p = rect(&h, &format!("timeline.layer.{lid}.{target}")).center();
click(&mut h, p, Modifiers::NONE);
click(&mut h, p, Modifiers::NONE);
let (layer, text, anchor, caret) = edited(&h);
assert_eq!(layer, lid, "{target}");
assert_eq!((anchor.min(caret), anchor.max(caret)), (0, 10), "everything selected ({target})");
assert!(h.state().auto.find(&format!("timeline.layer.{lid}.nameEdit")).is_none(), "no rename field ({target})");
assert_eq!(text, "alpha beta");
type_text(&mut h, "gamma");
key(&mut h, Key::Escape, Modifiers::NONE);
assert!(h.state().session.state.text_edit.is_none(), "Escape commits ({target})");
assert_eq!(layer_doc(&h.state().session, LayerId(lid)).unwrap().text, "gamma", "typing replaced the text ({target})");
}
}
@@ -0,0 +1,68 @@
use effectcraft_engine::{Session, config::MemoryConfig, prefs::Prefs};
use effectcraft_ui_egui::{EffectcraftApp, menus};
use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
use std::sync::Arc;
fn at(h: &Harness<'_, EffectcraftApp>, id: &str) -> Pos2 {
let r = h.state().auto.find(id).unwrap_or_else(|| panic!("missing {id}")).rect;
pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0)
}
fn click(h: &mut Harness<'_, EffectcraftApp>, p: Pos2, button: PointerButton) {
h.event(Event::PointerMoved(p));
h.step();
for pressed in [true, false] {
h.event(Event::PointerButton { pos: p, button, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(3);
}
#[test]
fn favorites_validate_and_survive_settings_reload() {
let loaded = Prefs::from_json(r#"{"appearance":{"favoriteThemes":["dark","unknown","dark","light"]}}"#);
assert_eq!(loaded.appearance.favorite_themes, vec!["dark", "light"]);
let mut p = Prefs::default();
for bad in [json!(["dark", "dark"]), json!(["unknown"]), json!([3]), json!("dark")] {
assert!(p.set("appearance.favoriteThemes", bad).is_err());
assert!(p.appearance.favorite_themes.is_empty());
}
p.set("appearance.favoriteThemes", json!(["light", "darker"])).unwrap();
let loaded = Prefs::from_json(&p.to_json());
assert_eq!(loaded.appearance.favorite_themes, p.appearance.favorite_themes);
}
#[test]
fn star_controls_save_and_favorite_menu_selects_the_family() {
let store = Arc::new(MemoryConfig::default());
let mut session = Session { config: Some(store.clone()), ..Default::default() };
session.execute("comp.new", json!({"width":32,"height":32,"duration":2})).unwrap();
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(session));
h.run_steps(4);
let ctx = h.ctx.clone();
menus::invoke(h.state_mut(), &ctx, "app.settings", json!({"page":"appearance"})).unwrap();
h.run_steps(3);
let p = at(&h, "settings.appearance.lightTheme.light");
h.event(Event::PointerMoved(p));
h.run_steps(2);
let p = at(&h, "settings.appearance.favoriteThemes.light");
click(&mut h, p, PointerButton::Primary);
assert_eq!(h.state().session.prefs.appearance.favorite_themes, vec!["light"]);
if let Some(path) = std::env::var_os("FAVORITES_SCREENSHOT_DIR") {
std::fs::create_dir_all(&path).unwrap();
h.render().unwrap().save(std::path::Path::new(&path).join("effectcraft-favorites.png")).unwrap();
}
assert_eq!(h.state().session.prefs.appearance.appearance_mode, "dark");
let p = at(&h, "settings.ok");
click(&mut h, p, PointerButton::Primary);
let mut saved = Session { config: Some(store), ..Default::default() };
saved.load_settings();
assert_eq!(saved.prefs.appearance.favorite_themes, vec!["light"]);
h.state_mut().set_pref("appearance.favoriteThemes", json!(["darker", "light"])).unwrap();
let p = at(&h, "header.appearance");
click(&mut h, p, PointerButton::Secondary);
let p = at(&h, "header.favoriteTheme.light");
assert!(p.y < at(&h, "header.favoriteTheme.darker").y);
click(&mut h, p, PointerButton::Primary);
assert_eq!(h.state().session.prefs.appearance.appearance_mode, "light");
assert_eq!(h.state().session.prefs.appearance.dark_theme, "dark");
}
+29 -1
View File
@@ -1,7 +1,7 @@
//! Timeline rows for shape layers, masks and keyframing: the Contents "Add:" menu and the Classic
//! 3D "Change Renderer…" row (#206), Alt+Shift+P revealing the key it adds and clicks below the
//! layers deselecting them (#205), Mask Feather's linked values (#203), and copying shape items
//! between shape layers (#227).
//! between shape layers (#227), and Ctrl+V of SVG markup making a shape layer (#738).
use effectcraft_engine::Session;
use effectcraft_engine::project::LayerId;
@@ -243,3 +243,31 @@ fn timeline_colour_eyedropper_samples_the_comp() {
assert!((c[k] - want[k]).abs() < 0.02, "{c:?} vs {want:?}");
}
}
/// Ctrl+V with SVG markup on the system clipboard pastes it as a shape layer (After Effects
/// 26.3), even with layers on the app's clipboard: copying in the app replaces the system
/// clipboard, so the SVG was copied later (#738).
#[test]
fn ctrl_v_pastes_svg_markup_as_a_shape_layer() {
let (mut h, a, b, _) = two_shape_layers();
click(&mut h, &format!("timeline.layer.{b}.row"));
h.input_mut().events.push(Event::Copy);
h.step();
assert_eq!(h.state().session.state.clipboard.len(), 1, "a layer on the app's clipboard");
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><circle cx="10" cy="10" r="8" fill="#00ff00"/><rect x="20" width="20" height="20"/></svg>"##;
h.input_mut().events.push(Event::Paste(svg.into()));
h.run_steps(3);
let c = h.state().session.active_comp().unwrap().clone();
assert_eq!(c.layers.len(), 3, "{:?}", h.state().ui.status);
let top = &c.layers[0];
assert!(top.id != LayerId(a) && top.id != LayerId(b));
assert_eq!(top.name, "Shape Layer 3");
assert_eq!(top.props.sub("contents").unwrap().groups().count(), 2);
assert_eq!(h.state().session.state.selected_layers, vec![top.id]);
// The app's own clipboard note pastes the copied layer as before.
h.input_mut().events.push(Event::Paste("EffectCraft: 1 layer".into()));
h.run_steps(3);
let c = h.state().session.active_comp().unwrap();
assert_eq!(c.layers.len(), 4);
assert_eq!(c.layers[0].name, "Oval 2");
}
@@ -100,6 +100,37 @@ fn dragging_over_layer_switches_sets_them_all() {
assert_eq!(states(&h, &ids, video), [false, true, false, true], "other switches untouched");
}
/// Alt-click on an A/V feature sets the layer apart (the other layers hidden / locked), and the
/// next Alt-click brings the others back; the Switches column is not affected by Alt.
#[test]
fn alt_click_on_av_feature_switches_the_other_layers() {
let (mut h, ids) = harness();
let alt_click = |h: &mut Harness<'_, EffectcraftApp>, id: String| {
let p = rect(h, &id).center();
let modifiers = Modifiers::ALT;
h.event(Event::PointerMoved(p));
h.event(Event::ModifiersChanged(modifiers));
h.step();
h.event(Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers });
h.step();
h.event(Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers });
h.event(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(3);
};
let steps = h.state().session.history.undo.len();
alt_click(&mut h, format!("timeline.layer.{}.video", ids[1]));
assert_eq!(states(&h, &ids, video), [false, true, false, false]);
assert_eq!(h.state().session.history.undo.len(), steps + 1, "one undo step");
alt_click(&mut h, format!("timeline.layer.{}.video", ids[1]));
assert_eq!(states(&h, &ids, video), [true; 4]);
alt_click(&mut h, format!("timeline.layer.{}.lock", ids[2]));
assert_eq!(states(&h, &ids, |l| l.switches.locked), [true, true, false, true]);
alt_click(&mut h, format!("timeline.layer.{}.solo", ids[0]));
assert_eq!(states(&h, &ids, |l| l.switches.solo), [true, false, false, false]);
alt_click(&mut h, format!("timeline.layer.{}.switch.motionBlur", ids[0]));
assert_eq!(states(&h, &ids, motion_blur), [true, false, false, false]);
}
/// #284: pressing a stopwatch and dragging over the stopwatches below gives every property the
/// state the first one got (animated or not), in one undo step; Alt+click still adds an
/// expression and a click toggles one property.
+140
View File
@@ -0,0 +1,140 @@
//! The toolbar's Fill / Stroke swatch with Linear or Radial Gradient (#612, reported on Discord):
//! it opens the Gradient Editor on the selected shape layer's Gradient Fill / Gradient Stroke
//! Colors, as in After Effects, instead of Fill / Stroke Options. The words still open the
//! options, a Solid Color swatch the colour picker, Alt-click still steps through the kinds, and
//! with no such gradient selected the swatch opens the options as before.
use effectcraft_engine::Session;
use effectcraft_engine::keyframe::Value;
use effectcraft_engine::project::{LayerId, PropGroup};
use effectcraft_ui_egui::state::Tool;
use effectcraft_ui_egui::{Dialog, EffectcraftApp};
use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
/// The Colors uid of the first `paint` ("gfill" / "gstroke") group in `g`, through nested groups.
fn colors(g: &PropGroup, paint: &str) -> Option<u64> {
g.groups().find_map(|x| if x.match_id == paint { x.get("colors").map(|p| p.uid) } else { colors(x, paint) })
}
/// A rectangle shape layer (selected unless `select` is false) with `items` added to its
/// contents, and the toolbar set with `tool` (shape.toolOptions).
fn setup(items: &[&str], tool: serde_json::Value, select: bool) -> (Harness<'static, EffectcraftApp>, u64) {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Main", "width": 640, "height": 360, "duration": 4})).unwrap();
let l = s.execute("layer.newShape", json!({"kind": "rect"})).unwrap()["layer"].as_u64().unwrap();
for kind in items {
s.execute("layer.addShapeItem", json!({"layer": l, "kind": kind})).unwrap();
}
s.execute("shape.toolOptions", tool.clone()).unwrap();
// The toolbar shows a selected shape layer's own Fill / Stroke kind (#732), so the layer gets
// the kind too.
if select && let Some(o) = tool.as_object() {
let mut p = o.clone();
p.insert("layers".into(), json!([l]));
s.execute("shape.fillStroke", serde_json::Value::Object(p)).unwrap();
}
s.state.selected_layers = if select { vec![LayerId(l)] } else { vec![] };
s.state.selected_props.clear();
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
// With no shape layer selected, Fill / Stroke show while a shape tool is active.
if !select {
h.state_mut().ui.tool = Tool::Rectangle;
}
h.run_steps(4);
(h, l)
}
fn center(h: &Harness<'_, EffectcraftApp>, id: &str) -> Pos2 {
let r = h.state().auto.find(id).unwrap_or_else(|| panic!("no automation id {id}")).rect;
pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0)
}
fn click(h: &mut Harness<'_, EffectcraftApp>, id: &str, modifiers: Modifiers) {
let p = center(h, id);
h.input_mut().events.push(Event::ModifiersChanged(modifiers));
h.input_mut().events.push(Event::PointerMoved(p));
h.step();
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers });
h.step();
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers });
h.step();
h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(3);
}
fn layer_colors(h: &Harness<'_, EffectcraftApp>, l: u64, paint: &str) -> u64 {
colors(&h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().props, paint).expect("the gradient")
}
/// The options popup is open (its kind buttons are in the automation tree).
fn options_open(h: &Harness<'_, EffectcraftApp>, key: &str) -> bool {
h.state().auto.find(&format!("header.{key}Options.solid")).is_some()
}
/// The reported bug: a Linear Gradient Fill swatch opened Fill Options. It opens the Gradient
/// Editor on the selected layer's Gradient Fill Colors, and OK sets them.
#[test]
fn a_gradient_fill_swatch_opens_the_gradient_editor() {
let (mut h, l) = setup(&["gfill"], json!({"fillType": "linear"}), true);
let uid = layer_colors(&h, l, "gfill");
click(&mut h, "header.fill", Modifiers::NONE);
assert_eq!(h.state().dialog, Some(Dialog::GradientEditor), "the swatch opens the Gradient Editor, not Fill Options");
assert!(!options_open(&h, "fill"), "and not the options");
let target = h.state().gradient_draft().target.clone().expect("a target");
assert_eq!((target.layer, target.prop), (l, uid), "on the layer's Gradient Fill Colors");
// Edit and save it: the property really changes.
let bar = h.state().auto.find("dialog.gradient.addColor").unwrap().rect;
let at = pos2(bar[0] + bar[2] * 0.5, bar[1] + bar[3] / 2.0);
h.input_mut().events.push(Event::PointerMoved(at));
h.step();
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
click(&mut h, "dialog.gradient.ok", Modifiers::NONE);
let v = h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().props.find(uid).unwrap().value.clone();
let Value::Gradient(g) = v else { panic!("not a gradient: {v:?}") };
assert_eq!(g.colors.len(), 3, "the added stop was saved: {g:?}");
}
/// The Stroke swatch with Radial Gradient edits the Gradient Stroke's Colors (not the fill's).
#[test]
fn a_gradient_stroke_swatch_edits_the_gradient_stroke() {
let (mut h, l) = setup(&["gfill", "gstroke"], json!({"strokeType": "radial"}), true);
let uid = layer_colors(&h, l, "gstroke");
click(&mut h, "header.stroke", Modifiers::NONE);
assert_eq!(h.state().dialog, Some(Dialog::GradientEditor));
let target = h.state().gradient_draft().target.clone().expect("a target");
assert_eq!((target.layer, target.prop), (l, uid), "on the Gradient Stroke's Colors");
}
/// With no shape layer selected the swatch opens the options (the kind new shapes get) as before.
/// (A selected shape layer shows its own kind, #732, so a gradient kind always has its gradient.)
#[test]
fn without_a_selected_gradient_the_swatch_opens_the_options() {
let (mut h, _) = setup(&["gfill"], json!({"fillType": "linear"}), false);
click(&mut h, "header.fill", Modifiers::NONE);
assert_eq!(h.state().dialog, None, "no editor");
assert!(options_open(&h, "fill"), "Fill Options");
}
/// The rest of the toolbar is unchanged: the words open the options, a Solid Color swatch opens the
/// colour picker, and Alt-click steps to the next kind.
#[test]
fn words_solid_swatches_and_alt_click_are_unchanged() {
let (mut h, _) = setup(&["gfill"], json!({"fillType": "linear"}), true);
click(&mut h, "header.fillOptions", Modifiers::NONE);
assert!(options_open(&h, "fill"), "the word opens Fill Options");
assert_eq!(h.state().dialog, None);
let (mut h, _) = setup(&["gfill"], json!({"fillType": "solid"}), true);
click(&mut h, "header.fill", Modifiers::NONE);
assert!(h.query_by_label("Color field").is_some(), "a Solid Color swatch opens the colour picker");
assert_eq!(h.state().dialog, None);
let (mut h, _) = setup(&["gfill"], json!({"fillType": "linear"}), true);
click(&mut h, "header.fill", Modifiers::ALT);
assert_eq!(h.state().dialog, None, "Alt-click doesn't open the editor");
assert_eq!(h.state().session.state.shape_tool.fill.kind.id(), "radial", "it steps Linear → Radial");
}
@@ -0,0 +1,63 @@
//! Footage whose codec the decoders lack says so: a warning marker in the Project panel and a
//! notice on the layer in the Composition viewer, instead of a black picture with no reason.
use std::sync::Arc;
use effectcraft_engine::Session;
use effectcraft_engine::project::{Footage, FootageKind, ItemId, ItemKind};
use effectcraft_engine::render::FootageSource;
use effectcraft_render::Image;
use effectcraft_time::Tick;
use effectcraft_ui_egui::EffectcraftApp;
use egui_kittest::Harness;
use serde_json::json;
const WHY: &str = "H.264 (High 4:2:2) isn't supported by the built-in decoder: chroma_format_idc 2 (only 4:2:0 is implemented)";
/// A source that decodes nothing and, for `broken` movies, says why.
struct Stub(bool);
impl FootageSource for Stub {
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
None
}
fn problem(&self, _: &Footage) -> Option<String> {
self.0.then(|| WHY.to_string())
}
}
fn harness(broken: bool) -> (Harness<'static, EffectcraftApp>, ItemId) {
let mut s = Session { footage: Arc::new(Stub(broken)), ..Default::default() };
s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "duration": 4})).unwrap();
let footage = Footage {
kind: FootageKind::Video,
path: "clip.mp4".into(),
width: 64,
height: 36,
has_video: true,
duration: Tick::from_seconds_f64(2.0),
..Default::default()
};
let clip = std::sync::Arc::make_mut(&mut s.project).add_item("Clip", Default::default(), None, ItemKind::Footage(footage));
s.execute("layer.addItem", json!({"item": clip.0})).unwrap();
s.execute("project.select", json!({"items": []})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(4);
(h, clip)
}
#[test]
fn undecodable_footage_is_marked_in_the_project_panel_and_the_viewer() {
let (h, clip) = harness(true);
let marker = h.state().auto.find(&format!("project.item.{}.problem", clip.0)).expect("a warning on the footage item").clone();
assert!(marker.label.contains("4:2:2"), "{marker:?}");
let notice = h.state().auto.query("viewer.footageProblem.").first().copied().expect("a notice in the viewer").clone();
assert!(notice.label.contains(WHY), "{notice:?}");
}
#[test]
fn readable_footage_has_no_notice() {
let (h, clip) = harness(false);
assert!(h.state().auto.find(&format!("project.item.{}.problem", clip.0)).is_none());
assert!(h.state().auto.query("viewer.footageProblem.").is_empty());
}
+142 -2
View File
@@ -162,6 +162,56 @@ fn viewer_press_prefers_a_selected_layer_under_the_pointer() {
assert_eq!(h.state().session.state.selected_layers, vec![front], "nothing selected: the topmost layer");
}
/// Each composition keeps its Resolution, saved with the project as in After Effects: chosen for
/// comp A in the viewer's popup, it is still A's after showing comp B, costs no undo step, keeps
/// A's cached frames and is read back from the saved file (#417).
#[test]
fn each_comp_keeps_its_viewer_resolution() {
use effectcraft_ui_egui::state::Resolution;
let mut h = harness();
let a = h.state().session.active_comp_id().unwrap();
let content = |h: &Harness<'_, EffectcraftApp>, c| {
let s = h.state();
s.frames.content_of(&s.session.project, s.session.revision, c)
};
let (before, steps) = (content(&h, a), h.state().session.history.undo.len());
for id in ["viewer.resolution", "viewer.resolutionItem.1"] {
let at = rect(&h, id).center();
click(&mut h, at);
}
assert_eq!(h.state().viewer_res(), Resolution::Half);
assert_eq!(h.state().session.project.comp(a).unwrap().resolution, Resolution::Half);
assert_eq!(h.state().session.history.undo.len(), steps, "no undo step");
assert_eq!(content(&h, a), before, "the comp's cached frames stay valid");
// Comp B starts at Auto and gets its own (here through the control channel's `ui.set`).
h.state_mut().session.execute("comp.new", json!({"name": "Other", "width": 320, "height": 180, "duration": 2})).unwrap();
h.run_steps(3);
let b = h.state().session.active_comp_id().unwrap();
assert_ne!(a, b);
assert_eq!(h.state().viewer_res(), Resolution::Auto);
let (req, _reply) = effectcraft_ui_egui::control::ControlRequest::new("ui.set", json!({"viewer": {"res": "quarter"}}));
let ctx = h.ctx.clone();
let _ = effectcraft_ui_egui::control::handle(h.state_mut(), &ctx, &req);
assert_eq!(h.state().viewer_res(), Resolution::Quarter);
let ctx = h.ctx.clone();
assert_eq!(effectcraft_ui_egui::control::inspect(h.state(), &ctx)["ui"]["viewer"]["res"], json!("Quarter"));
// Back to comp A: its resolution again.
h.state_mut().session.open_comp(a);
h.run_steps(3);
assert_eq!(h.state().viewer_res(), Resolution::Half);
assert!(h.state().viewer_scale(1.0, 1.0) == 0.5);
// Saved and opened again.
let path = std::env::temp_dir().join(format!("ec-viewer-res-{}.ecproj", std::process::id()));
h.state_mut().session.execute("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
let mut s = Session::default();
s.execute("file.open", json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
s.open_comp(b);
let app = EffectcraftApp::new(s);
assert_eq!(app.viewer_res(), Resolution::Quarter);
assert_eq!(app.session.project.comp(a).unwrap().resolution, Resolution::Half);
}
#[test]
fn bottom_bar_in_after_effects_order() {
let h = harness();
@@ -601,6 +651,32 @@ fn fill_options_paint_the_next_shape() {
assert_eq!(gfill.get("opacity").unwrap().value.as_f64(), 40.0);
}
/// With a shape layer selected, Fill Options' None switches its fill off and Solid Color turns
/// it back on, and the Fill swatch shows the layer's kind (#732).
#[test]
fn fill_options_change_the_selected_shape_layer() {
let mut h = harness();
let l = h.state_mut().session.execute("layer.newShape", json!({"kind": "rect", "size": [100, 100], "position": [320, 180]})).unwrap()["layer"]
.as_u64()
.unwrap();
h.run_steps(2);
let fill_on = |h: &Harness<'_, EffectcraftApp>| {
let layer = h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().clone();
layer.props.group("contents/group/contents/fill").unwrap().enabled
};
assert!(fill_on(&h));
for (kind, on) in [("none", false), ("solid", true)] {
let at = rect(&h, "header.fillOptions").center();
click(&mut h, at);
let at = rect(&h, &format!("header.fillOptions.{kind}")).center();
click(&mut h, at);
h.input_mut().events.push(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
h.run_steps(3);
assert_eq!(fill_on(&h), on, "{kind}");
assert_eq!(h.state().session.state.shape_tool.fill.kind.id(), kind);
}
}
#[test]
fn shape_pen_draws_a_closed_shape_layer() {
let mut h = harness();
@@ -1852,7 +1928,7 @@ fn full_resolution_frames_wider_than_the_texture_limit_fit() {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
// (egui's font atlas needs 1024.)
h.input_mut().max_texture_side = Some(1024);
h.state_mut().ui.viewer.res = effectcraft_ui_egui::state::Resolution::Full;
h.state_mut().session.execute("view.res.full", json!({})).unwrap();
let full = |h: &mut Harness<'_, EffectcraftApp>| h.state_mut().viewer_pixels().is_some_and(|px| px.size == [2400, 400]);
for _ in 0..400 {
h.step();
@@ -1861,7 +1937,7 @@ fn full_resolution_frames_wider_than_the_texture_limit_fit() {
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(full(&mut h), "the full-size frame is shown (and stays readable): {:?}", h.state().ui.viewer.res);
assert!(full(&mut h), "the full-size frame is shown (and stays readable): {:?}", h.state().viewer_res());
assert_eq!(h.state().viewer_texture_size(), Some([800, 134]), "2400×400 averaged by 3");
}
@@ -1948,3 +2024,67 @@ fn vertex_tools_edit_motion_path_keyframes() {
click(&mut h, quarter);
assert_eq!(keys(&h).len(), 3);
}
/// #882: at 100 % (and 200 %) on a scaled display the frame's corner sits on a physical pixel, so
/// every comp pixel covers whole screen pixels instead of being blended with its neighbour.
#[test]
fn frame_sits_on_the_physical_pixel_grid() {
for ppp in [1.0f32, 1.25, 1.5] {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Grid", "width": 301, "height": 201, "duration": 1})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_pixels_per_point(ppp).build_eframe(move |_| EffectcraftApp::new(s));
h.run_steps(3);
for (mag, pan) in [(1.0f32, [0.3f32, 0.37]), (2.0, [-0.45, 0.2])] {
h.state_mut().ui.viewer.zoom = Some(mag / ppp);
h.state_mut().ui.viewer.pan = pan;
h.run_steps(2);
let c = rect(&h, "viewer.comp");
for v in [c.min.x * ppp, c.min.y * ppp] {
assert!((v - v.round()).abs() < 1e-3, "ppp {ppp}, {mag}×: corner at {v} physical px");
}
assert!((c.width() * ppp - 301.0 * mag).abs() < 1e-2, "ppp {ppp}, {mag}×: {} physical px wide", c.width() * ppp);
}
}
}
/// Magnification ▸ Fit up to 100% keeps fitting as the panel changes size (Maximize Panel), like
/// Fit, and never magnifies past 100%.
#[test]
fn fit_up_to_100_follows_the_maximized_panel() {
use effectcraft_ui_egui::dock::PanelKind;
let pick = |h: &mut Harness<'_, EffectcraftApp>| {
let at = rect(h, "viewer.magnification").center();
click(h, at);
let at = rect(h, "viewer.magnification.1").center();
click(h, at);
assert_eq!(h.state().ui.viewer.zoom, None, "a fit mode, not a fixed magnification");
assert!(h.state().ui.viewer.fit_up_to_100);
h.run_steps(2);
};
// A comp larger than the panel: it fills the docked panel, then the maximized one.
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Big", "width": 3840, "height": 2160, "duration": 4})).unwrap();
EffectcraftApp::new(s)
});
h.run_steps(3);
pick(&mut h);
let docked = rect(&h, "viewer.comp").width();
h.state_mut().toggle_maximize(PanelKind::Composition);
h.run_steps(3);
let area = rect(&h, "viewer.area");
let maximized = rect(&h, "viewer.comp");
assert!(maximized.width() > docked + 100.0, "{docked} -> {}", maximized.width());
assert!(area.contains_rect(maximized), "{maximized:?} in {area:?}");
h.state_mut().toggle_maximize(PanelKind::Composition);
h.run_steps(3);
assert_eq!(rect(&h, "viewer.comp").width(), docked, "and back when the panel is restored");
// A comp smaller than the panel stops at 100%.
let mut h = harness();
pick(&mut h);
let ppp = h.ctx.pixels_per_point();
assert!(rect(&h, "viewer.comp").width() <= 640.0 / ppp + 0.01);
h.state_mut().toggle_maximize(PanelKind::Composition);
h.run_steps(3);
assert!((rect(&h, "viewer.comp").width() - 640.0 / ppp).abs() < 0.01);
}
+9 -1
View File
@@ -170,7 +170,15 @@ fn gpu_worker_renders_effect_frames_and_the_disk_cache_survives_a_reload() {
let mut frames2 = Frames::default();
frames2.set_remote(Some(worker2.clone()));
assert!(frames2.remote_disk());
let bar = frames2.disk_frames(&source(&s, None), &key(fx), 30, &opts);
let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
let bar = loop {
let bar = frames2.disk_frames(&source(&s, None), &key(fx), 30, &opts);
if !bar.is_empty() {
break bar;
}
assert!(std::time::Instant::now() < until, "disk-cache indicator did not finish hashing");
std::thread::sleep(std::time::Duration::from_millis(1));
};
assert_eq!(bar, vec![0], "the blue cache bar shows the stored frame");
frames2.request_urgent(&source(&s, Some(page_gpu)), key(fx), fx, t, opts);
frames2.dispatch_remote();
+81 -3
View File
@@ -177,7 +177,6 @@ fn effect_scrubbing_uses_adaptive_resolution_and_settles_on_release() {
h.state_mut().session.execute("layer.select", json!({"layers":[id.0]})).unwrap();
h.state_mut().session.execute("effect.apply", json!({"effect":"Gaussian Blur"})).unwrap();
h.state_mut().session.execute("view.fastPreviewMode", json!({"mode":"adaptive"})).unwrap();
h.state_mut().ui.viewer.res = effectcraft_ui_egui::state::Resolution::Auto;
let ctx = h.ctx.clone();
effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "window.panel", json!({"panel":"effectControls"})).unwrap();
h.run_steps(3);
@@ -188,12 +187,12 @@ fn effect_scrubbing_uses_adaptive_resolution_and_settles_on_release() {
h.run_steps(2);
assert!(h.state().ui.viewer.property_interacting);
assert!(h.state().viewer_scale(1.0, 1.0) < 1.0);
h.state_mut().ui.viewer.res = effectcraft_ui_egui::state::Resolution::Full;
h.state_mut().session.execute("view.res.full", json!({})).unwrap();
assert_eq!(h.state().viewer_scale(1.0, 1.0), 1.0);
pointer(&mut h, a + vec2(30.0, 0.0), false, Modifiers::NONE);
h.run_steps(2);
assert!(!h.state().ui.viewer.property_interacting);
h.state_mut().ui.viewer.res = effectcraft_ui_egui::state::Resolution::Auto;
h.state_mut().session.execute("view.res.auto", json!({})).unwrap();
assert_eq!(h.state().viewer_scale(1.0, 1.0), 1.0);
}
@@ -430,3 +429,82 @@ fn timeline_selected_effect_row_highlights() {
assert!(h.state().session.state.selected_props.contains(&(id, fx)), "the click selects the effect");
assert!(highlighted(&h), "the selected effect's row is highlighted");
}
/// Right-clicking a layer in the Timeline keeps the selection when the layer is part of it,
/// so the context menu's commands act on every selected layer; right-clicking an unselected
/// layer selects only it (After Effects). Reported on Discord: Pre-compose and Delete from the
/// menu acted on the right-clicked layer only (#878).
#[test]
fn timeline_context_menu_acts_on_the_whole_selection() {
let right_click = |h: &mut Harness<'_, EffectcraftApp>, p: Pos2| {
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerMoved(p));
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(3);
};
let row = |h: &Harness<'_, EffectcraftApp>, id: LayerId| {
let r = rect(h, &format!("timeline.layer.{}.row", id.0));
pos2(r.min.x + 210.0, r.center().y)
};
let bar = |h: &Harness<'_, EffectcraftApp>, id: LayerId| rect(h, &format!("timeline.layer.{}.bar", id.0)).center();
let mut h = harness();
let ids: Vec<LayerId> = h.state().session.active_comp().unwrap().layers.iter().map(|l| l.id).collect();
// Outline row: Delete removes both selected layers.
h.state_mut().session.execute("layer.select", json!({"layers":[ids[0].0, ids[1].0]})).unwrap();
h.run_steps(3);
let p = row(&h, ids[1]);
right_click(&mut h, p);
assert_eq!(h.state().session.state.selected_layers, vec![ids[0], ids[1]]);
h.get_by_label("Delete").click();
h.run_steps(3);
let left: Vec<LayerId> = h.state().session.active_comp().unwrap().layers.iter().map(|l| l.id).collect();
assert_eq!(left, vec![ids[2], ids[3]]);
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
// Layer bar: same, with Duplicate.
h.state_mut().session.execute("layer.select", json!({"layers":[ids[2].0, ids[3].0]})).unwrap();
h.run_steps(3);
let p = bar(&h, ids[3]);
right_click(&mut h, p);
h.get_by_label("Duplicate").click();
h.run_steps(3);
assert_eq!(h.state().session.active_comp().unwrap().layers.len(), 6);
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
// An unselected row: right-clicking selects only it.
h.state_mut().session.execute("layer.select", json!({"layers":[ids[0].0, ids[1].0]})).unwrap();
h.run_steps(3);
let p = row(&h, ids[3]);
right_click(&mut h, p);
assert_eq!(h.state().session.state.selected_layers, vec![ids[3]]);
}
/// The Project panel's Move to Project Root acts on every selected item when the right-clicked
/// item is part of the selection, as Delete and Label do.
#[test]
fn project_context_move_to_root_acts_on_the_whole_selection() {
let mut h = harness();
let solids: Vec<u64> = {
let p = &h.state().session.project;
p.items.values().filter(|i| matches!(i.kind, effectcraft_engine::project::ItemKind::Solid(_))).map(|i| i.id.0).collect()
};
assert!(solids.len() >= 2);
let folder = h.state_mut().session.execute("project.newFolder", json!({"name":"Bin"})).unwrap()["item"].as_u64().unwrap();
h.state_mut().session.execute("project.move", json!({"items": solids, "folder": folder})).unwrap();
h.state_mut().ui.project_open_folders.insert(folder);
h.state_mut().session.execute("project.select", json!({"items": [solids[0], solids[1]]})).unwrap();
h.run_steps(3);
let p = rect(&h, &format!("project.item.{}.name", solids[1])).center();
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerMoved(p));
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(3);
h.get_by_label("Move to Project Root").click();
h.run_steps(3);
let project = &h.state().session.project;
for id in &solids[..2] {
assert_eq!(project.item(effectcraft_engine::project::ItemId(*id)).unwrap().parent, None);
}
}