Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

Merge remote-tracking branch 'origin/main' into enhance/keyframe-text-clipboard

tylerjenningswecc3e673bc3e
diff --cc crates/engine/src/doc_state.rs
index 000000000,e5fb1791b..d6e25de57
mode 000000,100644..100644
--- a/crates/engine/src/doc_state.rs
+++ b/crates/engine/src/doc_state.rs
@@@ -1,0 -1,197 +1,201 @@@
+ use super::*;
+
+ /// A keyframe reference: layer, property uid, key time (layer time).
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+ pub struct KeyRef {
+ pub layer: LayerId,
+ pub prop: Uid,
+ pub time: Tick,
+ }
+
+ /// A keyframe drag in progress (`keys.move` steps sharing a merge key): the selection it
+ /// started from and the total offset so far, so every step is applied to the keys as they were
+ /// before the drag. A key passed over on the way is never overwritten; only the drop position
+ /// counts, as in After Effects.
+ #[derive(Clone, Debug)]
+ pub struct KeyMove {
+ pub merge: String,
+ pub from: Vec<KeyRef>,
+ pub total: Tick,
+ }
+
+ /// Keyframes of one property on the keyframe clipboard.
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ pub struct KeyClip {
+ pub layer: LayerId,
+ /// Match-id path relative to the layer (`transform/position`), portable between layers.
+ pub path: String,
+ /// Keys with times relative to the earliest copied key (layer time).
+ pub keys: Vec<effectcraft_keyframe::Keyframe>,
+ }
+
+ /// A selected mask vertex: layer, mask group uid, vertex index.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+ pub struct VertexRef {
+ pub layer: LayerId,
+ pub mask: Uid,
+ pub index: usize,
+ }
+
+ /// One composition's selection. The active comp's copy lives in [`EditorState::selected_layers`]
+ /// (and the property, key, and vertex lists); every other comp keeps its own here (#1001).
+ #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+ pub struct CompSelection {
+ pub layers: Vec<LayerId>,
+ pub props: Vec<(LayerId, Uid)>,
+ pub keys: Vec<KeyRef>,
+ pub vertices: Vec<VertexRef>,
+ }
+
+ impl CompSelection {
+ pub(crate) fn is_empty(&self) -> bool {
+ self.layers.is_empty() && self.props.is_empty() && self.keys.is_empty() && self.vertices.is_empty()
+ }
+ }
+
+ /// Editing state that commands depend on (headless-relevant, serde for agents).
+ #[derive(Clone, Debug, Default, Serialize, Deserialize)]
+ pub struct EditorState {
+ pub active_comp: Option<ItemId>,
+ /// Open compositions (viewer/timeline tabs), in tab order.
+ pub open_comps: Vec<ItemId>,
+ /// Compositions that were active before the current one, most recent first (Shift+Esc).
+ #[serde(default)]
+ pub recent_comps: Vec<ItemId>,
+ /// Current time per comp (the CTI).
+ pub times: std::collections::BTreeMap<ItemId, Tick>,
+ /// Layer selection of the active comp. Other comps' selections are in [`Self::comp_selections`].
+ pub selected_layers: Vec<LayerId>,
+ /// Selections of comps that are not active, keyed by comp id (#1001).
+ #[serde(default)]
+ pub comp_selections: std::collections::BTreeMap<ItemId, CompSelection>,
+ /// Selected properties / groups (by uid) of selected layers.
+ pub selected_props: Vec<(LayerId, Uid)>,
+ pub selected_keys: Vec<KeyRef>,
+ pub project_selection: Vec<ItemId>,
+ /// Layer clipboard (serialized layers) and keyframe clipboard.
+ #[serde(skip)]
+ pub clipboard: Vec<Layer>,
+ /// Copied keyframes (times relative to the earliest copied key).
+ #[serde(skip)]
+ pub key_clipboard: Vec<KeyClip>,
+ /// The last copy was keyframes (Paste pastes keys at the CTI).
+ #[serde(skip)]
+ pub clip_is_keys: bool,
+ /// Values of selected unanimated properties (match path, value), copied with Edit ▸ Copy;
+ /// Paste sets the same properties of the selected layers.
+ #[serde(skip)]
+ pub value_clipboard: Vec<(String, effectcraft_keyframe::Value)>,
++ /// The copied keyframes and values as After Effects keyframe text (one layer's Transform
++ /// properties), for the system clipboard.
++ #[serde(skip)]
++ pub keyframe_text: Option<String>,
+ /// Copied effect instances, with comp-time key offsets from the earliest copied key.
+ /// Paste adds them to the selected layers at the destination comp's CTI.
+ #[serde(skip)]
+ pub effect_clipboard: Vec<effectcraft_project::PropGroup>,
+ /// Copied shape items (Edit ▸ Copy with groups, paths, paints or path operations selected in
+ /// a shape layer's Contents); Paste adds them to the selected shape layers.
+ #[serde(skip)]
+ pub contents_clipboard: Vec<effectcraft_project::PropGroup>,
+ /// Selected mask vertices (viewer Selection tool / pen).
+ #[serde(default)]
+ pub selected_vertices: Vec<VertexRef>,
+ pub snapping: bool,
+ /// Tools bar ▸ Snapping options (which features snap, Snap Edges Extended).
+ #[serde(default)]
+ pub snap_features: viewer::SnapFeatures,
+ /// Last applied effect id (Effect ▸ last effect).
+ pub last_effect: Option<String>,
+ /// Viewer region of interest `[x, y, w, h]` in comp pixels (Composition ▸ Crop Comp to Region
+ /// of Interest).
+ #[serde(default)]
+ pub region_of_interest: Option<[f64; 4]>,
+ /// Property-link clipboard (Edit ▸ Copy with Property Links / Copy Expression Only).
+ #[serde(skip)]
+ pub link_clipboard: Option<LinkClip>,
+ /// File ▸ Interpret Footage ▸ Remember Interpretation.
+ #[serde(skip)]
+ pub interpretation: Option<effectcraft_project::Footage>,
+ /// Viewer 3D view per comp (Active Camera / Front / … / Custom View 3 and edited view cameras).
+ #[serde(default)]
+ pub views3d: std::collections::BTreeMap<ItemId, effectcraft_render::three_d::Views3D>,
+ /// Tracker panel ▸ Current Track: (tracked layer, tracker group uid) in the active comp.
+ #[serde(default)]
+ pub current_track: Option<(LayerId, Uid)>,
+ /// Tracker panel ▸ Method in mask mode (Track Mask).
+ #[serde(default)]
+ pub mask_track_method: mask_track::MaskMethod,
+ /// 3D Camera Tracker: the selected track points (ids) in the viewer.
+ #[serde(default)]
+ pub camera_points: Vec<u32>,
+ /// Mask Interpolation panel options.
+ #[serde(default)]
+ pub mask_interp: commands::mask_interp::MaskInterpOptions,
+ /// Paint and Brushes panel options (Brush, Clone Stamp and Eraser tools).
+ #[serde(default)]
+ pub paint: commands::paint::PaintOptions,
+ /// Roto Brush and Refine Edge tool options.
+ #[serde(default)]
+ pub roto: roto::RotoOptions,
+ /// Puppet tool options for new meshes.
+ #[serde(default)]
+ pub puppet: commands::puppet::PuppetOptions,
+ /// The shape tools' and the Pen's options (Tool Creates Shape / Mask, Fill and Stroke).
+ #[serde(default)]
+ pub shape_tool: commands::shape_tool::ShapeTool,
+ /// View ▸ Switch View Layout: 1, 2 or 4 views side by side in the Composition viewer.
+ #[serde(default = "one_view")]
+ pub view_layout: u8,
+ /// View ▸ Switch View Layout ▸ Share View Options (grid, guides… in every view).
+ #[serde(default)]
+ pub share_view_options: bool,
+ /// Layer ▸ Mask ▸ Hide Locked Masks (viewer outlines).
+ #[serde(default)]
+ pub hide_locked_masks: bool,
+ /// On-canvas text editing (Type tool): the edited layer, selection and insertion style.
+ #[serde(default)]
+ pub text_edit: Option<commands::text_edit::TextEdit>,
+ /// Text copied while editing (with its formatting), for Paste / Paste Text Formatting Only.
+ #[serde(skip)]
+ pub text_clipboard: Option<effectcraft_keyframe::TextDoc>,
+ /// Composition viewer display options (Show Channel, exposure, snapshot, Fast Previews).
+ #[serde(default)]
+ pub viewer: commands::viewer_cmds::ViewOptions,
+ /// Essential Graphics panel ▸ Primary composition (`None` = the active comp).
+ #[serde(default)]
+ pub essential_primary: Option<ItemId>,
+ /// Essential Graphics panel ▸ Solo Supported Properties (the timeline shows only properties
+ /// Essential Graphics can expose).
+ #[serde(default)]
+ pub essential_solo: bool,
+ /// File ▸ Watch Folder: the folder being watched for projects to render (frontends call
+ /// `file.watchFolder.poll` periodically while it is set).
+ #[serde(default)]
+ pub watch_folder: Option<String>,
+ /// The Footage panel: the footage shown, its time and In/Out marks (source time).
+ #[serde(default)]
+ pub footage_panel: Option<commands::footage_panel::FootageView>,
+ /// Media Browser: the folder shown and the favourites.
+ #[serde(default)]
+ pub media_browser: media_browser::BrowserState,
+ /// Content-Aware Fill panel settings.
+ #[serde(default)]
+ pub content_fill: commands::content_fill::FillSettings,
+ /// View ▸ Split with New Locked Viewer: the second viewer's comp and 3D view.
+ #[serde(default)]
+ pub locked_viewer: Option<commands::viewer_cmds::LockedViewer>,
+ }
+
+ fn one_view() -> u8 {
+ 1
+ }
+
+ /// What Copy with Property Links / Copy Expression Only put on the clipboard.
+ #[derive(Clone, Debug, PartialEq)]
+ pub enum LinkClip {
+ /// Expressions that link back to the source properties: (match path, expression text).
+ Links { relative: bool, links: Vec<(String, String)> },
+ /// Expressions only: (match path, expression).
+ Expressions(Vec<(String, effectcraft_project::Expression)>),
+ }
diff --cc crates/engine/src/interchange.rs
index 000000000,ec4cff579..3b166b83e
mode 000000,100644..100644
--- a/crates/engine/src/interchange.rs
+++ b/crates/engine/src/interchange.rs
@@@ -1,0 -1,3 +1,5 @@@
++pub(crate) mod keyframe_text;
++pub(crate) mod keyframe_text_effects;
+ pub mod psd_import;
+ pub mod vector;
+ pub mod xml_project;
diff --cc crates/engine/src/interchange/keyframe_text.rs
index 5f8ba9441,000000000..5f8ba9441
mode 100644,000000..100644
--- a/crates/engine/src/interchange/keyframe_text.rs
+++ b/crates/engine/src/interchange/keyframe_text.rs
diff --cc crates/engine/src/interchange/keyframe_text_effects.rs
index 83f5b6c20,000000000..83f5b6c20
mode 100644,000000..100644
--- a/crates/engine/src/interchange/keyframe_text_effects.rs
+++ b/crates/engine/src/interchange/keyframe_text_effects.rs
diff --cc crates/engine/src/lib.rs
index 930415d1c,2174a87ca..dfd765210
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -73,328 -56,45 +56,46 @@@ pub use effectcraft_segment as segment
pub use effectcraft_text as text;
pub use effectcraft_time as time;
pub use effectcraft_track as track;
+ pub use footage::doc_path;
+ pub use footage::footage_check;
+ pub use footage::footage_reload;
+ pub use footage::media_browser;
+ pub use footage::media_cache;
+ pub use footage::sequence;
pub use history::{Branch, History, HistoryNode};
+ pub use home::demo;
+ pub use home::learn;
+ pub use home::links;
+ pub use home::templates;
++use interchange::{keyframe_text, keyframe_text_effects};
+ pub use interchange::psd_import;
+ pub use interchange::vector;
+ pub use interchange::xml_project;
pub use render_queue::{ExportJob, ExportResult, Exporter, JobState};
-
- #[derive(Debug, thiserror::Error)]
- pub enum EngineError {
- #[error("unknown command `{0}`")]
- UnknownCommand(String),
- #[error("command `{0}` is not available right now: {1}")]
- Disabled(String, String),
- #[error("invalid parameters for `{cmd}`: {msg}")]
- BadParams { cmd: String, msg: String },
- #[error("no active composition")]
- NoComp,
- /// A `comp` reference (name or id) that names no composition.
- #[error("no composition {0}")]
- NoSuchComp(String),
- #[error("{0}")]
- Project(#[from] effectcraft_project::ProjectError),
- #[error("{0}")]
- Other(String),
- }
-
- pub type Result<T> = std::result::Result<T, EngineError>;
-
- /// Host services (file access) injected by the frontend.
- pub trait Services: Send + Sync {
- fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>>;
- fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()>;
- /// Whether a file exists (the background footage check after open).
- fn exists(&self, path: &str) -> bool {
- std::path::Path::new(path).exists()
- }
- /// A file's size and modification time (nanoseconds since 1970), to notice that it changed
- /// on disk (Settings ▸ Import ▸ Reload Footage Changed on Disk); `None` when it can't be read.
- fn stamp(&self, path: &str) -> Option<(u64, u128)> {
- let meta = std::fs::metadata(path).ok()?;
- let modified = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?;
- Some((meta.len(), modified.as_nanos()))
- }
- /// Keep a file the app made for itself (footage extracted from a template): like
- /// [`Services::write_file`], creating its folder, but never offered as a download (web: it
- /// goes to browser storage only).
- fn store_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> {
- if let Some(d) = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) {
- let _ = std::fs::create_dir_all(d);
- }
- self.write_file(path, data)
- }
- /// The files in folder `dir` (full paths; no folders, no hidden files), for image-sequence
- /// detection on import. Empty when it can't be read.
- fn list_dir(&self, dir: &str) -> Vec<String> {
- let Ok(rd) = std::fs::read_dir(if dir.is_empty() { "." } else { dir }) else { return vec![] };
- rd.filter_map(|e| e.ok())
- .filter(|e| e.file_type().is_ok_and(|t| t.is_file()) && !e.file_name().to_string_lossy().starts_with('.'))
- .map(|e| e.path().to_string_lossy().to_string())
- .collect()
- }
- /// Whether `path` is a folder (dropped or picked folders import their files).
- fn is_dir(&self, path: &str) -> bool {
- std::path::Path::new(path).is_dir()
- }
- }
-
- /// Native filesystem.
- pub struct FsServices;
- impl Services for FsServices {
- fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
- std::fs::read(path)
- }
- fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> {
- config::atomic_write(std::path::Path::new(path), data)
- }
- }
-
- /// Imports media files into the project (implemented by the media layer).
- pub trait Importer: Send + Sync {
- /// Probe one file and return footage metadata. Image sequences are the engine's
- /// ([`sequence`]): it groups numbered stills and probes their first file here.
- fn probe(&self, path: &str) -> std::result::Result<effectcraft_project::Footage, String>;
- /// A footage file's bytes are now at `path` (extracted from a template): hosts whose media
- /// layer reads from memory (the browser) register them; file-based ones need nothing.
- fn register(&self, _path: &str, _data: &[u8]) {}
- /// An image sequence's other frames (its first was probed) are footage now: hosts whose
- /// media layer reads from memory (the browser) register them; file-based ones need nothing.
- fn add_frames(&self, _paths: &[String]) {}
- }
-
- /// A keyframe reference: layer, property uid, key time (layer time).
- #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
- pub struct KeyRef {
- pub layer: LayerId,
- pub prop: Uid,
- pub time: Tick,
- }
-
- /// A keyframe drag in progress (`keys.move` steps sharing a merge key): the selection it
- /// started from and the total offset so far, so every step is applied to the keys as they were
- /// before the drag. A key passed over on the way is never overwritten; only the drop position
- /// counts, as in After Effects.
- #[derive(Clone, Debug)]
- pub struct KeyMove {
- pub merge: String,
- pub from: Vec<KeyRef>,
- pub total: Tick,
- }
-
- /// Keyframes of one property on the keyframe clipboard.
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct KeyClip {
- pub layer: LayerId,
- /// Match-id path relative to the layer (`transform/position`), portable between layers.
- pub path: String,
- /// Keys with times relative to the earliest copied key (layer time).
- pub keys: Vec<effectcraft_keyframe::Keyframe>,
- }
-
- /// A selected mask vertex: layer, mask group uid, vertex index.
- #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
- pub struct VertexRef {
- pub layer: LayerId,
- pub mask: Uid,
- pub index: usize,
- }
-
- /// One composition's selection. The active comp's copy lives in [`EditorState::selected_layers`]
- /// (and the property, key, and vertex lists); every other comp keeps its own here (#1001).
- #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
- pub struct CompSelection {
- pub layers: Vec<LayerId>,
- pub props: Vec<(LayerId, Uid)>,
- pub keys: Vec<KeyRef>,
- pub vertices: Vec<VertexRef>,
- }
-
- impl CompSelection {
- fn is_empty(&self) -> bool {
- self.layers.is_empty() && self.props.is_empty() && self.keys.is_empty() && self.vertices.is_empty()
- }
- }
-
- /// Editing state that commands depend on (headless-relevant, serde for agents).
- #[derive(Clone, Debug, Default, Serialize, Deserialize)]
- pub struct EditorState {
- pub active_comp: Option<ItemId>,
- /// Open compositions (viewer/timeline tabs), in tab order.
- pub open_comps: Vec<ItemId>,
- /// Compositions that were active before the current one, most recent first (Shift+Esc).
- #[serde(default)]
- pub recent_comps: Vec<ItemId>,
- /// Current time per comp (the CTI).
- pub times: std::collections::BTreeMap<ItemId, Tick>,
- /// Layer selection of the active comp. Other comps' selections are in [`Self::comp_selections`].
- pub selected_layers: Vec<LayerId>,
- /// Selections of comps that are not active, keyed by comp id (#1001).
- #[serde(default)]
- pub comp_selections: std::collections::BTreeMap<ItemId, CompSelection>,
- /// Selected properties / groups (by uid) of selected layers.
- pub selected_props: Vec<(LayerId, Uid)>,
- pub selected_keys: Vec<KeyRef>,
- pub project_selection: Vec<ItemId>,
- /// Layer clipboard (serialized layers) and keyframe clipboard.
- #[serde(skip)]
- pub clipboard: Vec<Layer>,
- /// Copied keyframes (times relative to the earliest copied key).
- #[serde(skip)]
- pub key_clipboard: Vec<KeyClip>,
- /// The last copy was keyframes (Paste pastes keys at the CTI).
- #[serde(skip)]
- pub clip_is_keys: bool,
- /// Values of selected unanimated properties (match path, value), copied with Edit ▸ Copy;
- /// Paste sets the same properties of the selected layers.
- #[serde(skip)]
- pub value_clipboard: Vec<(String, effectcraft_keyframe::Value)>,
- /// The copied keyframes and values as After Effects keyframe text (one layer's Transform
- /// properties), for the system clipboard.
- #[serde(skip)]
- pub keyframe_text: Option<String>,
- /// Copied effect instances, with comp-time key offsets from the earliest copied key.
- /// Paste adds them to the selected layers at the destination comp's CTI.
- #[serde(skip)]
- pub effect_clipboard: Vec<effectcraft_project::PropGroup>,
- /// Copied shape items (Edit ▸ Copy with groups, paths, paints or path operations selected in
- /// a shape layer's Contents); Paste adds them to the selected shape layers.
- #[serde(skip)]
- pub contents_clipboard: Vec<effectcraft_project::PropGroup>,
- /// Selected mask vertices (viewer Selection tool / pen).
- #[serde(default)]
- pub selected_vertices: Vec<VertexRef>,
- pub snapping: bool,
- /// Tools bar ▸ Snapping options (which features snap, Snap Edges Extended).
- #[serde(default)]
- pub snap_features: viewer::SnapFeatures,
- /// Last applied effect id (Effect ▸ last effect).
- pub last_effect: Option<String>,
- /// Viewer region of interest `[x, y, w, h]` in comp pixels (Composition ▸ Crop Comp to Region
- /// of Interest).
- #[serde(default)]
- pub region_of_interest: Option<[f64; 4]>,
- /// Property-link clipboard (Edit ▸ Copy with Property Links / Copy Expression Only).
- #[serde(skip)]
- pub link_clipboard: Option<LinkClip>,
- /// File ▸ Interpret Footage ▸ Remember Interpretation.
- #[serde(skip)]
- pub interpretation: Option<effectcraft_project::Footage>,
- /// Viewer 3D view per comp (Active Camera / Front / … / Custom View 3 and edited view cameras).
- #[serde(default)]
- pub views3d: std::collections::BTreeMap<ItemId, effectcraft_render::three_d::Views3D>,
- /// Tracker panel ▸ Current Track: (tracked layer, tracker group uid) in the active comp.
- #[serde(default)]
- pub current_track: Option<(LayerId, Uid)>,
- /// Tracker panel ▸ Method in mask mode (Track Mask).
- #[serde(default)]
- pub mask_track_method: mask_track::MaskMethod,
- /// 3D Camera Tracker: the selected track points (ids) in the viewer.
- #[serde(default)]
- pub camera_points: Vec<u32>,
- /// Mask Interpolation panel options.
- #[serde(default)]
- pub mask_interp: commands::mask_interp::MaskInterpOptions,
- /// Paint and Brushes panel options (Brush, Clone Stamp and Eraser tools).
- #[serde(default)]
- pub paint: commands::paint::PaintOptions,
- /// Roto Brush and Refine Edge tool options.
- #[serde(default)]
- pub roto: roto::RotoOptions,
- /// Puppet tool options for new meshes.
- #[serde(default)]
- pub puppet: commands::puppet::PuppetOptions,
- /// The shape tools' and the Pen's options (Tool Creates Shape / Mask, Fill and Stroke).
- #[serde(default)]
- pub shape_tool: commands::shape_tool::ShapeTool,
- /// View ▸ Switch View Layout: 1, 2 or 4 views side by side in the Composition viewer.
- #[serde(default = "one_view")]
- pub view_layout: u8,
- /// View ▸ Switch View Layout ▸ Share View Options (grid, guides… in every view).
- #[serde(default)]
- pub share_view_options: bool,
- /// Layer ▸ Mask ▸ Hide Locked Masks (viewer outlines).
- #[serde(default)]
- pub hide_locked_masks: bool,
- /// On-canvas text editing (Type tool): the edited layer, selection and insertion style.
- #[serde(default)]
- pub text_edit: Option<commands::text_edit::TextEdit>,
- /// Text copied while editing (with its formatting), for Paste / Paste Text Formatting Only.
- #[serde(skip)]
- pub text_clipboard: Option<effectcraft_keyframe::TextDoc>,
- /// Composition viewer display options (Show Channel, exposure, snapshot, Fast Previews).
- #[serde(default)]
- pub viewer: commands::viewer_cmds::ViewOptions,
- /// Essential Graphics panel ▸ Primary composition (`None` = the active comp).
- #[serde(default)]
- pub essential_primary: Option<ItemId>,
- /// Essential Graphics panel ▸ Solo Supported Properties (the timeline shows only properties
- /// Essential Graphics can expose).
- #[serde(default)]
- pub essential_solo: bool,
- /// File ▸ Watch Folder: the folder being watched for projects to render (frontends call
- /// `file.watchFolder.poll` periodically while it is set).
- #[serde(default)]
- pub watch_folder: Option<String>,
- /// The Footage panel: the footage shown, its time and In/Out marks (source time).
- #[serde(default)]
- pub footage_panel: Option<commands::footage_panel::FootageView>,
- /// Media Browser: the folder shown and the favourites.
- #[serde(default)]
- pub media_browser: media_browser::BrowserState,
- /// Content-Aware Fill panel settings.
- #[serde(default)]
- pub content_fill: commands::content_fill::FillSettings,
- /// View ▸ Split with New Locked Viewer: the second viewer's comp and 3D view.
- #[serde(default)]
- pub locked_viewer: Option<commands::viewer_cmds::LockedViewer>,
- }
-
- fn one_view() -> u8 {
- 1
- }
-
- /// `t` as a current time of `comp`: a frame within its duration.
- fn comp_frame_at(comp: &Comp, t: Tick) -> Tick {
- comp.frame_rate.snap_nearest(t.min(comp.duration - comp.frame_duration()).max(Tick::ZERO))
- }
-
- /// What Copy with Property Links / Copy Expression Only put on the clipboard.
- #[derive(Clone, Debug, PartialEq)]
- pub enum LinkClip {
- /// Expressions that link back to the source properties: (match path, expression text).
- Links { relative: bool, links: Vec<(String, String)> },
- /// Expressions only: (match path, expression).
- Expressions(Vec<(String, effectcraft_project::Expression)>),
- }
-
- /// Events for frontends (drained each frame).
- #[derive(Clone, Debug, PartialEq, Serialize)]
- pub enum Event {
- ProjectChanged {
- revision: u64,
- },
- Toast {
- message: String,
- error: bool,
- },
- OpenComp(ItemId),
- OpenUrl(String),
- /// A frontend-only command (viewer zoom, panels, dialogs…) ran: the UI performs it. Headless
- /// sessions ignore these.
- Frontend {
- command: String,
- params: Value,
- },
- /// Drop cached frames / renders (Edit ▸ Purge).
- PurgeCaches,
- /// Put an image on the system clipboard (Composition ▸ Copy Frame to Clipboard): `rgba` is
- /// `width` × `height` straight-alpha RGBA8 rows. Headless sessions ignore it; the pixels are
- /// not serialized.
- CopyImage {
- width: u32,
- height: u32,
- #[serde(skip)]
- rgba: Vec<u8>,
- },
- }
+ pub use settings::autosave;
+ pub use settings::config;
+ pub use settings::prefs;
+ pub use settings::shortcuts;
+ pub use system::guard;
+ pub use system::logging;
+ pub use system::perf;
+ pub use system::storage;
+ pub use system::sysinfo;
+
+ mod doc_state;
+ mod error;
+ mod event;
+ mod fonts;
+ mod services;
+ mod session;
+
+ pub use cmd::{animation_presets, text_presets};
+ pub use doc_state::{CompSelection, EditorState, KeyClip, KeyMove, KeyRef, LinkClip, VertexRef};
+ pub use error::{EngineError, Result};
+ pub use event::Event;
+ pub use fonts::{FontRow, font_features, font_menu, font_preview, font_styles, text_families};
+ pub use services::{FsServices, Importer, Services};
+ pub use session::upgrade_effects;
pub struct Session {
pub project: Arc<Project>,
diff --cc crates/engine/src/tests.rs
index b3f0602b3,579d3d30d..25237493c
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -1,735 -1,53 +1,54 @@@
- use serde_json::json;
-
- use crate::Session;
-
- fn demo() -> Session {
- let mut s = Session::default();
- s.execute("file.openDemoProject", json!({})).unwrap();
- s
- }
-
- #[test]
- fn demo_opens_and_renders() {
- let s = demo();
- let cid = s.active_comp_id().unwrap();
- let img = s.render(cid, s.time(), effectcraft_render::RenderOpts { scale: 0.25, ..Default::default() });
- assert_eq!((img.width, img.height), (480, 270));
- let lit = img.data.iter().filter(|p| p[3] > 0.99).count();
- assert!(lit > 100_000, "{lit}");
- }
-
- /// The session's layer cache never changes pixels: scrubbing the demo (including back and
- /// forth, and across an edit made through a command) matches cache-less renders exactly.
- #[test]
- fn demo_layer_cache_is_transparent() {
- let mut s = demo();
- let cid = s.active_comp_id().unwrap();
- let opts = effectcraft_render::RenderOpts { scale: 0.25, ..Default::default() };
- let uncached = |s: &Session, t: f64| {
- let mut r = effectcraft_render::Renderer::new(&s.project, s.footage.as_ref(), opts);
- r.expr = s.expr.as_deref();
- r.comp_frame(cid, effectcraft_time::Tick::from_seconds_f64(t))
- };
- let check = |s: &Session, t: f64| {
- let a = s.render(cid, effectcraft_time::Tick::from_seconds_f64(t), opts);
- let b = uncached(s, t);
- assert!(a.data.iter().zip(&b.data).all(|(p, q)| (0..4).all(|c| (p[c] - q[c]).abs() < 1e-6)), "t={t}");
- };
- for t in [0.5, 1.0, 3.0, 3.0334, 6.0, 3.0, 0.5] {
- check(&s, t);
- }
- assert!(s.layer_cache.stats().hits > 0);
- // Edit the title's glow through the command layer, then scrub again.
- let title = s.project.comp(cid).unwrap().layers.iter().find(|l| l.name == "EFFECTCRAFT").map(|l| l.id.0).unwrap();
- s.execute("prop.set", json!({"layer": title, "path": "effects/#1/radius", "value": 5.0})).unwrap();
- for t in [3.0, 0.5] {
- check(&s, t);
- }
- }
-
- /// `layer.addItem` puts the layer at `index` (1-based) in the stack and starts it at `time`, as a
- /// drop in the Timeline does (#89).
- #[test]
- fn add_item_at_a_stack_index_and_time() {
- let mut s = Session::default();
- let clip = s.execute("comp.new", json!({"name": "Clip", "width": 16, "height": 16, "frameRate": 30, "duration": 1})).unwrap()["comp"].as_u64().unwrap();
- s.execute("comp.new", json!({"name": "Main", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap();
- for name in ["C", "B", "A"] {
- s.execute("layer.newSolid", json!({"name": name})).unwrap();
- }
- let names = |s: &Session| s.active_comp().unwrap().layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
- s.execute("layer.addItem", json!({"item": clip, "index": 2, "time": 1.01})).unwrap();
- assert_eq!(names(&s), ["A", "Clip", "B", "C"]);
- let l = &s.active_comp().unwrap().layers[1];
- assert_eq!(l.in_point, effectcraft_time::Tick::from_seconds_f64(1.0), "on the nearest frame");
- // Past the bottom: the bottom.
- s.execute("layer.addItem", json!({"item": clip, "index": 99})).unwrap();
- assert_eq!(names(&s).last().map(String::as_str), Some("Clip 2"));
- assert!(s.execute("layer.addItem", json!({"item": clip, "index": 0})).is_err(), "1-based");
- }
-
- /// Files dropped on the Timeline or the Composition viewer (`file.import {addToComp}`) become
- /// layers of the comp that was active, one under the other, where they were dropped (#85, #89).
- #[test]
- fn imported_files_go_into_the_comp_where_they_were_dropped() {
- use effectcraft_project::{Footage, FootageKind};
- struct Probe;
- impl crate::Importer for Probe {
- fn probe(&self, path: &str) -> Result<Footage, String> {
- Ok(Footage { path: path.into(), kind: FootageKind::Still, width: 64, height: 32, has_video: true, ..Default::default() })
- }
- }
- let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() };
- s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap();
- s.execute("layer.newSolid", json!({"name": "Bg"})).unwrap();
- let params = json!({"paths": ["/drop/a.png", "/drop/b.png"], "addToComp": true, "position": [40.0, 50.0], "index": 1, "time": 1.0});
- s.execute("file.import", params).unwrap();
- let comp = s.active_comp().unwrap();
- assert_eq!(comp.layers.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["a.png", "b.png", "Bg"]);
- for l in &comp.layers[..2] {
- assert_eq!(l.props.prop("transform/position").map(|p| p.value.clone()), Some(effectcraft_keyframe::Value::Vec3([40.0, 50.0, 0.0])));
- assert_eq!(l.in_point, effectcraft_time::Tick::from_seconds_f64(1.0));
- }
- // Without `addToComp` they only import.
- s.execute("file.import", json!({"paths": ["/drop/c.png"]})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.len(), 3);
- assert!(s.execute("layer.addItem", json!({"item": "a.png", "position": [1.0]})).is_err(), "position needs x and y");
- }
-
- /// #270: files dropped or picked in the Import dialog (`file.import {background}`) are probed in
- /// a background job that says which file it is reading and how many are left; then they arrive
- /// in one undo step, all selected, with a count. The same file imported again arrives again.
- #[test]
- fn background_imports_report_progress_and_select_what_arrived() {
- use effectcraft_project::{Footage, FootageKind, ItemId};
- use std::sync::Arc;
- use std::sync::atomic::{AtomicUsize, Ordering};
- /// Probes file k once `allow` > k (a slow video; 5 s at most, so an import that waits for it
- /// fails the test instead of hanging it); `.xyz` files fail.
- struct Gated {
- started: AtomicUsize,
- allow: Arc<AtomicUsize>,
- }
- impl crate::Importer for Gated {
- fn probe(&self, path: &str) -> Result<Footage, String> {
- let k = self.started.fetch_add(1, Ordering::SeqCst);
- let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
- while self.allow.load(Ordering::SeqCst) <= k && std::time::Instant::now() < until {
- std::thread::sleep(std::time::Duration::from_millis(1));
- }
- if path.ends_with(".xyz") {
- return Err("unsupported file".into());
- }
- Ok(Footage { path: path.into(), kind: FootageKind::Still, width: 64, height: 32, has_video: true, ..Default::default() })
- }
- }
- let allow = Arc::new(AtomicUsize::new(1));
- let mut s = Session { importer: Some(Arc::new(Gated { started: AtomicUsize::new(0), allow: allow.clone() })), ..Default::default() };
- s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap();
- let undo = s.history.undo.len();
- let r = s.execute("file.import", json!({"paths": ["/drop/a.png", "/drop/b.png", "/drop/a.png"], "background": true})).unwrap();
- let job = r["job"].as_str().unwrap().to_string();
- // The first file is through; the second is being read.
- let running = |s: &mut Session| s.execute("jobs.list", json!({})).unwrap()["running"].as_array().unwrap().clone();
- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
- while running(&mut s)[0]["done"] != json!(1) && std::time::Instant::now() < deadline {
- std::thread::sleep(std::time::Duration::from_millis(2));
- }
- let row = running(&mut s)[0].clone();
- assert_eq!(row["id"], json!(job));
- assert_eq!(row["label"], json!("Importing 3 files"));
- assert_eq!(row["message"], json!("b.png (2 of 3)"));
- assert_eq!((row["done"].as_u64(), row["total"].as_u64()), (Some(1), Some(3)));
- assert!(s.project.items.values().all(|i| i.name != "a.png"), "nothing is added before the import finishes");
- allow.store(usize::MAX, Ordering::SeqCst);
- s.execute("jobs.wait", json!({})).unwrap();
- let names = |s: &Session, ids: &[ItemId]| ids.iter().map(|i| s.project.item(*i).unwrap().name.clone()).collect::<Vec<_>>();
- assert_eq!(names(&s, &s.state.project_selection), ["a.png", "b.png", "a.png"], "everything imported is selected, the same file twice too");
- assert_eq!(s.history.undo.len(), undo + 1, "one undo step");
- let rec = s.job_log.last().unwrap();
- assert_eq!((rec.status.as_str(), rec.message.as_str()), ("done", "Imported 3 items"));
- assert!(s.drain_events().iter().any(|e| matches!(e, crate::Event::Toast { message, .. } if message == "Imported 3 items")));
- // Dropped on the viewer: they become layers too; a file that can't be read is reported.
- s.execute("file.import", json!({"paths": ["/drop/c.png", "/drop/d.xyz"], "background": true, "addToComp": true, "position": [10.0, 20.0]})).unwrap();
- s.execute("jobs.wait", json!({})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["c.png"]);
- assert_eq!(s.job_log.last().unwrap().message, "Imported 1 item. /drop/d.xyz: unsupported file");
- // Agents and scripts import at once by default.
- let r = s.execute("file.import", json!({"paths": ["/drop/e.png"]})).unwrap();
- assert_eq!(r["items"].as_array().map(Vec::len), Some(1));
- }
-
- /// Audio, Lock and Shy don't change pixels: toggling them keeps the cached layers (#103).
- #[test]
- fn audio_lock_and_shy_keep_cached_layers() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "C", "width": 160, "height": 90, "frameRate": 30, "duration": 1})).unwrap();
- s.execute("layer.newSolid", json!({"color": "#3080ff", "width": 80, "height": 40})).unwrap();
- s.execute("effect.apply", json!({"layer": "#1", "effect": "Gaussian Blur"})).unwrap();
- s.execute("prop.set", json!({"layer": "#1", "path": "effects/#1/blurriness", "value": 12})).unwrap();
- let cid = s.active_comp_id().unwrap();
- let t = s.time();
- s.render(cid, t, Default::default());
- let before = s.layer_cache.stats();
- for sw in ["audio", "lock", "shy"] {
- s.execute("layer.setSwitch", json!({"layers": ["#1"], "switch": sw, "value": sw != "audio"})).unwrap();
- }
- s.render(cid, t, Default::default());
- let after = s.layer_cache.stats();
- assert_eq!(after.misses, before.misses, "no layer rendered again");
- assert!(after.hits > before.hits);
- }
-
- #[test]
- fn every_command_has_unique_id_and_runs_or_reports() {
- let mut ids = std::collections::HashSet::new();
- for c in crate::command_specs() {
- assert!(ids.insert(c.id), "duplicate {}", c.id);
- }
- assert!(ids.len() >= 90, "{}", ids.len());
- }
-
- #[test]
- fn layer_workflow_with_undo() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "Test", "width": 640, "height": 360, "frameRate": 30, "duration": 4})).unwrap();
- let r = s.execute("layer.newSolid", json!({"color": "#336699"})).unwrap();
- let lid = r["layer"].as_u64().unwrap();
- s.execute("prop.set", json!({"layer": lid, "path": "transform/opacity", "value": 50})).unwrap();
- let tree = s.execute("layer.tree", json!({"layer": lid})).unwrap();
- assert!(tree.to_string().contains("\"value\":50.0"));
- s.execute("prop.toggleAnimation", json!({"layer": lid, "path": "transform/position"})).unwrap();
- s.execute("time.set", json!({"time": 2.0})).unwrap();
- s.execute("prop.set", json!({"layer": lid, "path": "transform/position", "value": [100, 100]})).unwrap();
- let comp = s.active_comp().unwrap();
- let pos = comp.layers[0].props.prop("transform/position").unwrap();
- assert_eq!(pos.keys.len(), 2);
- s.execute("prop.select", json!({"layer": lid, "path": "transform/position"})).unwrap();
- assert_eq!(s.state.selected_keys.len(), 2);
- s.execute("keys.easyEase", json!({})).unwrap();
- s.execute("keys.move", json!({"delta": 0.5})).unwrap();
- let pos = s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().clone();
- assert!((pos.keys[0].time.seconds() - 0.5).abs() < 0.02);
- assert_eq!(pos.keys[0].out_interp, effectcraft_keyframe::Interp::Bezier);
- // undo back to before the move
- s.execute("edit.undo", json!({})).unwrap();
- let pos = s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().clone();
- assert!(pos.keys[0].time.seconds().abs() < 0.02);
- s.execute("effect.apply", json!({"layer": lid, "effect": "Gaussian Blur"})).unwrap();
- s.execute("prop.set", json!({"layer": lid, "path": "effects/#1/blurriness", "value": 12})).unwrap();
- // Applying selects the new effect (Edit ▸ Duplicate would duplicate it); select the layer.
- s.execute("layer.select", json!({"layers": [lid]})).unwrap();
- s.execute("edit.duplicate", json!({})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.len(), 2);
- s.execute("layer.precompose", json!({"layers": [1, 2], "name": "Pre"})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.len(), 1);
- }
-
- #[test]
- fn text_shape_mask_matte_parent() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"width": 800, "height": 450, "duration": 3})).unwrap();
- let t = s.execute("layer.newText", json!({"text": "Hello", "size": 90})).unwrap()["layer"].as_u64().unwrap();
- s.execute("layer.addTextAnimator", json!({"layer": t, "properties": ["position", "opacity"]})).unwrap();
- let sh = s.execute("layer.newShape", json!({"kind": "star", "fill": "#ffcc00"})).unwrap()["layer"].as_u64().unwrap();
- s.execute("layer.addShapeItem", json!({"layer": sh, "kind": "trim"})).unwrap();
- s.execute("layer.addMask", json!({"layer": sh, "shape": "ellipse"})).unwrap();
- s.execute("layer.setMask", json!({"layer": sh, "mask": 1, "mode": "Subtract", "inverted": true})).unwrap();
- s.execute("layer.setTrackMatte", json!({"layer": sh, "matte": t, "kind": "luma"})).unwrap();
- s.execute("layer.setParent", json!({"layers": [sh], "parent": t})).unwrap();
- assert!(s.execute("layer.setParent", json!({"layers": [t], "parent": sh})).is_err());
- s.execute("layer.setBlendMode", json!({"layers": [sh], "mode": "Screen"})).unwrap();
- s.execute("layer.setSwitch", json!({"layers": [sh], "switch": "threeD"})).unwrap();
- let cid = s.active_comp_id().unwrap();
- let _ = s.render(cid, s.time(), Default::default());
- let info = s.execute("comp.info", json!({})).unwrap();
- assert_eq!(info["layers"].as_array().unwrap().len(), 2);
- }
-
- /// The toolbar's Fill / Stroke change a selected shape layer's paint (#205): a shape drawn
- /// without a stroke gets one, later edits change it, and the Contents "Add:" items (#206) include
- /// an empty Path and a Gradient Stroke that render.
- #[test]
- fn toolbar_fill_and_stroke_paint_selected_shape_layers() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();
- let sh = s.execute("layer.newShape", json!({"kind": "rect", "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
- let paint = |s: &mut Session| s.execute("shape.fillStroke", json!({})).unwrap();
- assert_eq!(paint(&mut s)["stroke"], serde_json::Value::Null, "drawn without a stroke");
- s.execute("shape.fillStroke", json!({"stroke": "#00ff00", "strokeWidth": 6})).unwrap();
- let p = paint(&mut s);
- assert_eq!((p["stroke"][1].as_f64(), p["strokeWidth"].as_f64()), (Some(1.0), Some(6.0)), "{p}");
- s.execute("shape.fillStroke", json!({"fill": "#0000ff", "strokeWidth": 3})).unwrap();
- let p = paint(&mut s);
- assert_eq!((p["fill"][2].as_f64(), p["strokeWidth"].as_f64()), (Some(1.0), Some(3.0)), "{p}");
- // One stroke, before the fill (paths, stroke, fill), and each change is one undo step.
- let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap().clone();
- let group = l.props.group("contents/group").unwrap();
- let order: Vec<&str> = group.sub("contents").unwrap().groups().map(|g| g.match_id.as_str()).collect();
- assert_eq!(order, ["rect", "stroke", "fill"]);
- s.execute("edit.undo", json!({})).unwrap();
- assert_eq!(paint(&mut s)["strokeWidth"].as_f64(), Some(6.0));
- // Only shape layers.
- s.execute("layer.newSolid", json!({"color": "#808080"})).unwrap();
- assert!(s.execute("shape.fillStroke", json!({"fill": "#ffffff"})).is_err());
- for kind in ["path", "gstroke"] {
- let r = s.execute("layer.addShapeItem", json!({"layer": sh, "kind": kind})).unwrap();
- assert!(r["path"].as_str().is_some_and(|p| p.starts_with("contents/")), "{r}");
- }
- let cid = s.active_comp_id().unwrap();
- let _ = s.render(cid, s.time(), Default::default());
- }
-
- /// The toolbar's Fill Options / Stroke Options change a selected shape layer's paint kind (#732):
- /// None switches the fill off, a gradient turns the Fill into a Gradient Fill that keeps its
- /// opacity, Solid Color turns it back, and a Stroke kind adds a stroke where there is none.
- #[test]
- fn toolbar_fill_and_stroke_kinds_change_selected_shape_layers() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();
- let sh = s.execute("layer.newShape", json!({"kind": "rect", "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
- let items = |s: &Session| -> Vec<(String, bool)> {
- let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap();
- l.props.group("contents/group/contents").unwrap().groups().map(|g| (g.match_id.clone(), g.enabled)).collect()
- };
- let kinds = |s: &mut Session| {
- let p = s.execute("shape.fillStroke", json!({})).unwrap();
- (p["fillType"].as_str().unwrap().to_string(), p["strokeType"].as_str().unwrap().to_string())
- };
- assert_eq!(kinds(&mut s), ("solid".into(), "none".into()));
- let cid = s.active_comp_id().unwrap();
- let centre = |s: &Session| s.render(cid, s.time(), Default::default()).get(200, 150);
- let red = centre(&s);
- // None switches the fill off: nothing is drawn, and the item stays.
- s.execute("shape.fillStroke", json!({"fillType": "none"})).unwrap();
- assert_eq!(items(&s), [("rect".into(), true), ("fill".into(), false)]);
- assert_eq!(kinds(&mut s).0, "none");
- assert_ne!(centre(&s), red, "the fill is off");
- // A radial gradient: the Fill becomes a Gradient Fill (switched on) that keeps its opacity.
- s.execute("shape.fillStroke", json!({"fillType": "solid", "fill": "#ff0000"})).unwrap();
- assert_eq!(centre(&s), red);
- let opacity = |s: &Session, m: &str| {
- let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap();
- l.props.group(&format!("contents/group/contents/{m}")).unwrap().get("opacity").unwrap().value.as_f64()
- };
- s.execute("prop.set", json!({"layer": sh, "path": "contents/group/contents/fill/opacity", "value": 40})).unwrap();
- s.execute("shape.fillStroke", json!({"fillType": "radial"})).unwrap();
- assert_eq!(items(&s), [("rect".into(), true), ("gfill".into(), true)]);
- assert_eq!((kinds(&mut s).0.as_str(), opacity(&s, "gfill")), ("radial", 40.0));
- s.execute("shape.fillStroke", json!({"fillType": "linear"})).unwrap();
- assert_eq!(kinds(&mut s).0, "linear");
- s.execute("shape.fillStroke", json!({"fillType": "solid", "fill": "#00ff00"})).unwrap();
- assert_eq!(items(&s), [("rect".into(), true), ("fill".into(), true)]);
- assert_eq!(opacity(&s, "fill"), 40.0);
- // A Stroke kind adds a stroke (before the fill); None switches it off again; undo is per step.
- s.execute("shape.fillStroke", json!({"strokeType": "linear"})).unwrap();
- assert_eq!(items(&s), [("rect".into(), true), ("gstroke".into(), true), ("fill".into(), true)]);
- s.execute("shape.fillStroke", json!({"strokeType": "none"})).unwrap();
- assert_eq!(kinds(&mut s), ("solid".into(), "none".into()));
- s.execute("edit.undo", json!({})).unwrap();
- assert_eq!(kinds(&mut s), ("solid".into(), "linear".into()));
- assert!(s.execute("shape.fillStroke", json!({"fillType": "plaid"})).is_err());
- }
-
- /// Selecting a mask in the Timeline (its row or its Mask Path) selects all of its points, so the
- /// viewer drags the whole mask (#203); a shape's Path item works the same way.
- #[test]
- fn selecting_a_mask_selects_its_points() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();
- let l = s.execute("layer.newSolid", json!({"color": "#808080"})).unwrap()["layer"].as_u64().unwrap();
- let m1 = s.execute("layer.addMask", json!({"layer": l, "shape": "rect"})).unwrap()["mask"].as_u64().unwrap();
- let m2 = s.execute("layer.addMask", json!({"layer": l, "shape": "ellipse"})).unwrap()["mask"].as_u64().unwrap();
- let points = |s: &Session, m: u64| s.state.selected_vertices.iter().filter(|v| v.mask == m).count();
- s.execute("prop.select", json!({"layer": l, "prop": m1, "selectKeys": false})).unwrap();
- assert_eq!((points(&s, m1), s.state.selected_vertices.len()), (4, 4));
- // Mask Path selects them too; Shift-adding another mask keeps the first.
- let path = s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().props.find_group(m2).unwrap().get("path").unwrap().uid;
- s.execute("prop.select", json!({"layer": l, "prop": path, "add": true})).unwrap();
- assert_eq!((points(&s, m1), points(&s, m2)), (4, 4));
- // Another mask replaces them; another property deselects them.
- s.execute("prop.select", json!({"layer": l, "prop": m2})).unwrap();
- assert_eq!((points(&s, m1), points(&s, m2)), (0, 4));
- // Delete removes the selected mask (not only its points).
- s.execute("edit.clear", json!({})).unwrap();
- let masks = |s: &Session| s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().masks().unwrap().children.len();
- assert_eq!(masks(&s), 1);
- s.execute("prop.select", json!({"layer": l, "path": "transform/opacity"})).unwrap();
- assert!(s.state.selected_vertices.is_empty());
- let sh = s.execute("layer.newShape", json!({"kind": "star"})).unwrap()["layer"].as_u64().unwrap();
- let star = s.execute("layer.addShapeItem", json!({"layer": sh, "kind": "path"})).unwrap()["uid"].as_u64().unwrap();
- s.execute("prop.select", json!({"layer": sh, "prop": star})).unwrap();
- assert_eq!(s.state.selected_vertices.len(), 0, "an empty Path has no points");
- }
-
- #[test]
- fn save_and_open_roundtrip() {
- let mut s = demo();
- let dir = std::env::temp_dir().join(format!("ec-test-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join("demo.ecproj").to_string_lossy().to_string();
- s.execute("file.saveAs", json!({"path": path})).unwrap();
- let before = s.project.clone();
- let mut s2 = Session::default();
- s2.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!(*before, *s2.project);
- let _ = std::fs::remove_dir_all(dir);
- }
-
- #[test]
- fn help_links_emit_urls() {
- let mut s = Session::default();
- let r = s.execute("help.discord", json!({})).unwrap();
- assert_eq!(r["url"], "https://discord.gg/artcraft");
- assert!(s.drain_events().iter().any(|e| matches!(e, crate::Event::OpenUrl(u) if u.contains("discord"))));
- assert_eq!(s.execute("help.github", json!({})).unwrap()["url"], "https://github.com/storytold/effectcraft");
- }
-
- #[test]
- fn time_navigation() {
- let mut s = demo();
- s.execute("time.start", json!({})).unwrap();
- let r = s.execute("time.nextKey", json!({})).unwrap();
- assert!(r["time"].as_f64().unwrap() > 0.0);
- s.execute("time.set", json!({"frame": 45})).unwrap();
- assert_eq!(s.execute("time.step", json!({"frames": 5})).unwrap()["frame"], 50);
- }
-
- #[test]
- fn time_navigation_per_property() {
- let mut s = demo();
- // An animated property and the comp times of its keys.
- let comp = s.active_comp().unwrap().clone();
- let mut found = None;
- for l in &comp.layers {
- l.props.walk("", &mut |_, pr| {
- if found.is_none() && pr.keys.len() >= 2 {
- found = Some((pr.uid, pr.keys.iter().map(|k| l.comp_time(k.time)).collect::<Vec<_>>()));
- }
- });
- }
- let (uid, times) = found.expect("demo has an animated property");
- s.set_time(effectcraft_time::Tick::ZERO);
- let half = comp.frame_duration().0 / 2;
- let expect = times.iter().copied().filter(|t| t.0 > half).min().unwrap();
- s.execute("time.go", json!({"to": "nextKey", "prop": uid})).unwrap();
- let snap = |t| comp.frame_rate.snap(t);
- assert_eq!(s.time(), snap(expect));
- // Going back from past the last key lands on the last key.
- s.set_time(comp.duration);
- s.execute("time.go", json!({"to": "prevKey", "prop": uid})).unwrap();
- assert_eq!(s.time(), snap(*times.iter().max().unwrap()));
- }
-
- #[test]
- fn set_text_paragraph_fill_and_leading() {
- use effectcraft_keyframe::{Justify, Value as KValue};
- let mut s = demo();
- let t = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();
- let doc = |s: &Session| {
- let l = s.active_comp().unwrap().layer(crate::project::LayerId(t)).unwrap().clone();
- match &l.props.prop("text/sourceText").unwrap().value {
- KValue::Text(d) => (**d).clone(),
- v => panic!("{v:?}"),
- }
- };
- for (key, j) in [
- ("justifyLeft", Justify::JustifyLastLeft),
- ("justifyCenter", Justify::JustifyLastCenter),
- ("justifyRight", Justify::JustifyLastRight),
- ("justifyAll", Justify::JustifyAll),
- ("center", Justify::Center),
- ] {
- s.execute("layer.setText", json!({"layer": t, "justify": key})).unwrap();
- assert_eq!(doc(&s).justify, j, "{key}");
- }
- s.execute("layer.setText", json!({"layer": t, "leading": 50, "applyFill": false, "applyStroke": true})).unwrap();
- let d = doc(&s);
- assert_eq!((d.leading, d.apply_fill, d.apply_stroke), (Some(50.0), false, true));
- s.execute("layer.setText", json!({"layer": t, "leading": "auto"})).unwrap();
- assert_eq!(doc(&s).leading, None);
- s.execute("layer.setText", json!({"layer": t, "hScale": 120, "vScale": 80, "baselineShift": 4, "smallCaps": true, "strokeOverFill": true})).unwrap();
- let d = doc(&s);
- assert_eq!((d.h_scale, d.v_scale, d.baseline_shift, d.small_caps, d.stroke_over_fill), (120.0, 80.0, 4.0, true, true));
- }
-
- #[test]
- fn property_groups_report_actionable_errors() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "T"})).unwrap();
- let l = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();
- let uid = s.active_comp().unwrap().layer(crate::project::LayerId(l)).unwrap().props.group("text/pathOptions").unwrap().uid;
- for selector in [json!({"path": "text"}), json!({"path": "text/pathOptions"}), json!({"path": format!("@{uid}")}), json!({"prop": uid})] {
- let mut params = selector;
- params["layer"] = json!(l);
- for cmd in ["prop.get", "prop.set"] {
- let err = s.execute(cmd, params.clone()).unwrap_err().to_string();
- assert!(err.contains("is a property group"), "{cmd}: {err}");
- assert!(err.contains("get_layer"), "{cmd}: {err}");
- }
- }
- assert!(s.execute("prop.get", json!({"layer": l, "path": "text/sourceText"})).is_ok());
- let err = s.execute("prop.get", json!({"layer": l, "path": "missing"})).unwrap_err().to_string();
- assert!(err.contains("no property `missing`"), "{err}");
- }
-
- #[test]
- fn prop_get_and_render_rgba8() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "T", "width": 320, "height": 180, "duration": 2.0, "frameRate": 30})).unwrap();
- let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
- s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [0, 0]})).unwrap();
- s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 1.0, "value": [100, 50]})).unwrap();
- let v = s.execute("prop.get", json!({"layer": l, "path": "transform/position", "time": 1.0})).unwrap();
- assert_eq!(v["animated"], true);
- assert_eq!(v["keys"].as_array().unwrap().len(), 2);
- assert_eq!(v["value"][0].as_f64().unwrap(), 100.0);
- let cid = s.resolve_comp(Some(&json!("T"))).unwrap();
- let (w, h, rgba) = s.render_rgba8(cid, effectcraft_time::Tick::ZERO, 160).unwrap();
- assert_eq!((w, h), (160, 90));
- assert_eq!(rgba.len(), (w * h * 4) as usize);
- }
-
- #[test]
- fn params_docs_parse() {
- use crate::commands::accepted_params;
- let k = |d: &str| accepted_params(d).unwrap();
- assert_eq!(k("{layers: [id|name|#n], add?, toggle?}"), ["layers", "add", "toggle"]);
- assert_eq!(k("{time? (s) | frame? | timecode?}"), ["time", "frame", "timecode"]);
- assert_eq!(k("{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}"), ["interpolation", "in", "out", "autoBezier"]);
- assert_eq!(k("{keys: [{layer, prop, time}], add?}"), ["keys", "add"]);
- assert_eq!(k("{label: Red|Yellow|Aqua|…, layers?}"), ["label", "layers"]);
- assert_eq!(k("{name?, background? [r,g,b]|#hex, open?}"), ["name", "background", "open"]);
- assert!(k("{}").is_empty());
- assert!(accepted_params("free text").is_none());
- // Every registered command documents its params as a parseable key list.
- for c in crate::command_specs() {
- assert!(accepted_params(c.params).is_some(), "{}: {}", c.id, c.params);
- }
- }
-
- #[test]
- fn execute_checked_rejects_unknown_params() {
- let mut s = demo();
- let e = s.execute_checked("layer.select", json!({"index": 2})).unwrap_err().to_string();
- assert!(e.contains("`index`") && e.contains("layers, add, toggle"), "{e}");
- s.execute_checked("layer.select", json!({"layers": ["#2"]})).unwrap();
- assert_eq!(s.state.selected_layers.len(), 1);
- // Aliases and always-accepted keys.
- s.execute_checked("layer.select", json!({"layer": "#1", "comp": s.active_comp_id().unwrap().0})).unwrap();
- s.execute_checked("time.set", json!({"frame": 3})).unwrap();
- assert!(s.execute_checked("edit.undo", json!({"steps": 2})).is_err());
- // Non-object params are not validated; the unchecked path stays lenient.
- s.execute("layer.select", json!({"layers": ["#1"], "index": 2})).unwrap();
- }
-
- #[test]
- fn layer_tree_paths_resolve() {
- let mut s = demo();
- s.execute("effect.apply", json!({"layer": 1, "effect": "Gaussian Blur"})).unwrap();
- let comp = s.execute("comp.info", json!({})).unwrap();
- let mut checked = 0;
- for l in comp["layers"].as_array().unwrap() {
- let tree = s.execute("layer.tree", json!({"layer": l["id"]})).unwrap();
- let mut stack = vec![tree["properties"].clone()];
- while let Some(n) = stack.pop() {
- if let Some(ch) = n["children"].as_array() {
- stack.extend(ch.iter().cloned());
- continue;
- }
- let path = n["path"].as_str().unwrap();
- let got = s.execute("prop.get", json!({"layer": l["id"], "path": path})).unwrap();
- assert_eq!(got["uid"], n["uid"], "path {path} on layer {}", l["name"]);
- checked += 1;
- }
- }
- assert!(checked > 20, "{checked}");
- }
-
- #[test]
- fn comp_settings_anchor_start_timecode_renderer() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "A", "width": 100, "height": 100, "duration": 2.0})).unwrap();
- let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
- s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [10, 20]})).unwrap();
- let pos = |s: &Session| {
- let pr = s.active_comp().unwrap().layer(crate::project::LayerId(l)).unwrap().props.prop("transform/position").unwrap().clone();
- pr.keys[0].value.components()
- };
- // Center anchor: grow by 100x50 → shift by half.
- s.execute("comp.settings", json!({"width": 200, "height": 150})).unwrap();
- assert_eq!(pos(&s)[..2], [60.0, 45.0]);
- // Top-left anchor: no shift. Bottom-right: full shift.
- s.execute("comp.settings", json!({"width": 300, "anchor": 0})).unwrap();
- assert_eq!(pos(&s)[..2], [60.0, 45.0]);
- s.execute("comp.settings", json!({"width": 200, "height": 100, "anchor": 8})).unwrap();
- assert_eq!(pos(&s)[..2], [-40.0, -5.0]);
- s.execute("comp.settings", json!({"startTimecode": "0:00:01:00", "renderer": "advanced3D"})).unwrap();
- let c = s.active_comp().unwrap();
- assert_eq!(c.display_start, c.frame_rate.tick_of(30));
- assert_eq!(c.renderer, crate::project::Renderer::Advanced3D);
- }
-
- /// `advanced3D` is a value of `renderer`, not a key: comp.new / comp.settings don't advertise it
- /// in their schemas and reject it as unknown instead of ignoring it (#177).
- #[test]
- fn renderer_values_are_not_parameter_keys() {
- let mut s = Session::default();
- for (id, p) in [("comp.new", json!({"name": "A"})), ("comp.settings", json!({}))] {
- let spec = crate::command_specs().iter().find(|c| c.id == id).unwrap();
- let keys = crate::commands::accepted_params(spec.params).unwrap();
- assert!(keys.contains(&"renderer".to_string()) && !keys.contains(&"advanced3D".to_string()), "{id}: {keys:?}");
- let mut bad = p.clone();
- bad["advanced3D"] = json!(true);
- let e = s.execute_checked(id, bad).unwrap_err().to_string();
- assert!(e.contains("unknown parameter(s) `advanced3D`"), "{id}: {e}");
- let mut good = p;
- good["renderer"] = json!("advanced3D");
- s.execute_checked(id, good).unwrap();
- assert_eq!(s.active_comp().unwrap().renderer, crate::project::Renderer::Advanced3D, "{id}");
- s.execute("comp.renderer", json!({"renderer": "classic3d"})).unwrap();
- }
- }
-
- #[test]
- fn comp_rejects_zero_and_negative_frame_rates() {
- let mut s = Session::default();
- for fps in [0.0, -30.0, 0.0001] {
- assert!(s.execute("comp.new", json!({"frameRate": fps})).is_err(), "{fps}");
- }
- s.execute("comp.new", json!({"frameRate": 30, "duration": 1})).unwrap();
- assert!(s.execute("comp.settings", json!({"frameRate": 0})).is_err());
- assert_eq!(s.active_comp().unwrap().frame_rate, crate::time::FrameRate::FPS_30);
- }
-
- #[test]
- fn render_queue_add_accepts_documented_settings_when_checked() {
- let mut s = demo();
- let r = s.execute_checked(
- "renderQueue.add",
- json!({"format": "gif", "output": "/tmp/x.gif", "resolution": "quarter", "timeSpan": "custom", "start": 0.0, "end": 0.5, "quality": "draft", "loop": true}),
- );
- // Without an exporter the add itself still succeeds (rendering is what needs one).
- assert!(r.is_ok(), "{r:?}");
- assert!(s.execute_checked("renderQueue.add", json!({"bogus": 1})).is_err());
- }
-
- #[test]
- fn new_text_rejects_malformed_positions_without_creating_a_layer() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "C", "width": 64, "height": 64, "duration": 1})).unwrap();
- for position in [json!([]), json!([10]), json!(["x", 20]), json!([null, 20])] {
- let err = s.execute("layer.newText", json!({"text": "Hello", "position": position})).unwrap_err();
- assert!(err.to_string().contains("position: [x, y]"), "{err}");
- assert!(s.active_comp().unwrap().layers.is_empty());
- }
- s.execute("layer.newText", json!({"name": "Valid", "text": "Hello", "position": [10, 20]})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().value, effectcraft_keyframe::Value::Vec3([10.0, 20.0, 0.0]));
- s.execute("layer.newText", json!({"text": "No explicit position"})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.len(), 2);
- }
-
- /// The active comp and the open comp tabs are saved with the project and restored on open (#748).
- #[test]
- fn reopening_a_project_restores_its_active_comp() {
- use effectcraft_project::ItemId;
- let dir = std::env::temp_dir().join(format!("ec-test-748-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join("view.ecproj").to_string_lossy().to_string();
- let mut s = Session::default();
- let a = s.execute("comp.new", json!({"name": "CompA"})).unwrap()["comp"].as_u64().unwrap();
- let b = s.execute("comp.new", json!({"name": "CompB"})).unwrap()["comp"].as_u64().unwrap();
- let c = s.execute("comp.new", json!({"name": "CompC"})).unwrap()["comp"].as_u64().unwrap();
- s.execute("comp.open", json!({"comp": "CompB"})).unwrap();
- s.state.open_comps.retain(|id| id.0 != c);
- s.execute("file.saveAs", json!({"path": path})).unwrap();
- let mut s2 = Session::default();
- s2.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!(s2.state.active_comp, Some(ItemId(b)));
- assert_eq!(s2.state.open_comps, vec![ItemId(a), ItemId(b)]);
- assert!(!s2.is_dirty());
-
- // A file from before the view was saved opens on its first comp, as it always did.
- let text = std::fs::read_to_string(&path).unwrap();
- let mut old: serde_json::Value = serde_json::from_str(&text).unwrap();
- let obj = old.as_object_mut().unwrap();
- obj.remove("activeComp");
- obj.remove("openComps");
- std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();
- let mut s3 = Session::default();
- s3.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!((s3.state.active_comp, s3.state.open_comps.clone()), (Some(ItemId(a)), vec![ItemId(a)]));
-
- // Ids that no longer name a comp (edited by hand, or written by another tool) fall back.
- obj_set(&mut old, json!(999), json!([999, b, "x"]));
- std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();
- let mut s4 = Session::default();
- s4.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!((s4.state.active_comp, s4.state.open_comps.clone()), (Some(ItemId(b)), vec![ItemId(b)]));
- obj_set(&mut old, json!(999), json!([]));
- std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();
- let mut s5 = Session::default();
- s5.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!((s5.state.active_comp, s5.state.open_comps.clone()), (Some(ItemId(a)), vec![ItemId(a)]));
-
- // XML copies carry it too.
- let xml = dir.join("view.ecprojx").to_string_lossy().to_string();
- s.execute("file.saveAs", json!({"path": xml})).unwrap();
- let mut s6 = Session::default();
- s6.execute("file.open", json!({"path": xml})).unwrap();
- assert_eq!(s6.state.active_comp, Some(ItemId(b)));
- let _ = std::fs::remove_dir_all(dir);
-
- fn obj_set(v: &mut serde_json::Value, active: serde_json::Value, open: serde_json::Value) {
- let o = v.as_object_mut().unwrap();
- o.insert("activeComp".into(), active);
- o.insert("openComps".into(), open);
- }
- }
-
- /// Layer times are saved as exact ticks and read back unchanged, and each comp reopens at the
- /// current time it was saved at, not at 0, where a layer starting later shows nothing (#1714).
- #[test]
- fn reopening_a_project_restores_layer_times_and_current_time() {
- use effectcraft_project::ItemId;
- use effectcraft_time::{FrameRate, Tick};
- let dir = std::env::temp_dir().join(format!("ec-test-1714-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join("times.ecproj").to_string_lossy().to_string();
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "C", "width": 108, "height": 192, "duration": 60})).unwrap();
- s.execute("layer.newSolid", json!({"name": "crown"})).unwrap();
- let cid = s.active_comp_id().unwrap();
- let comp = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap();
- comp.frame_rate = FrameRate::FPS_59_94;
- // The layer from the issue: 34f, 315f and 3033f at 59.94 fps.
- let l = comp.layers.first_mut().unwrap();
- (l.start_time, l.in_point, l.out_point) = (Tick(144_086_342_400), Tick(1_334_917_584_000), Tick(12_853_349_308_800));
- s.execute("time.set", json!({"time": 6.0})).unwrap();
- let t = s.time();
- // A second comp keeps its own time.
- let b = ItemId(s.execute("comp.new", json!({"name": "B"})).unwrap()["comp"].as_u64().unwrap());
- s.execute("time.set", json!({"time": 2.0})).unwrap();
- let tb = s.time();
- s.execute("comp.open", json!({"comp": "C"})).unwrap();
- s.execute("file.saveAs", json!({"path": path})).unwrap();
-
- let mut s2 = Session::default();
- s2.execute("file.open", json!({"path": path})).unwrap();
- let l = s2.project.comp(cid).unwrap().layers.first().unwrap();
- assert_eq!((l.start_time, l.in_point, l.out_point), (Tick(144_086_342_400), Tick(1_334_917_584_000), Tick(12_853_349_308_800)));
- assert_eq!((s2.time(), s2.state.times.get(&b).copied()), (t, Some(tb)));
- assert!(l.in_point <= s2.time() && s2.time() < l.out_point, "the layer shows at the reopened time");
- assert!(!s2.is_dirty());
-
- // Hand-edited times past the end or before the start land on the last or first frame.
- let mut file: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
- file["compTimes"] = json!({cid.0.to_string(): i64::MAX, b.0.to_string(): -5});
- std::fs::write(&path, file.to_string()).unwrap();
- let mut s3 = Session::default();
- s3.execute("file.open", json!({"path": path})).unwrap();
- let c = s3.project.comp(cid).unwrap();
- assert_eq!(s3.time(), c.frame_rate.snap_nearest(c.duration - c.frame_duration()));
- assert_eq!(s3.time(), c.frame_rate.snap_nearest(c.duration - c.frame_duration()));
- assert_eq!(s3.state.times.get(&b).copied(), Some(Tick::ZERO));
- }
+ mod anim_presets;
+ mod anim_tools;
+ mod camera_track;
+ mod codec_options;
+ mod color_view;
+ mod crypto_pick;
+ mod delete_keys;
+ mod disk_cache;
+ mod effects;
+ mod essential;
+ mod essential_more;
+ mod face;
+ mod fidelity;
+ mod frame_export;
+ mod fuzz_open;
+ mod history;
+ mod import_project;
+ mod key_metadata_order;
+ mod key_time;
++mod keyframe_text;
+ mod keylight;
+ mod limits;
+ mod lottie;
+ mod m137;
+ mod m145;
+ mod markers;
+ mod mask_warp;
+ mod menu_cmds;
+ mod model3d;
+ mod models;
+ mod motion_blur_depth;
+ mod paint;
+ mod panels;
+ mod project_items;
+ mod proxy;
+ mod quick_offset;
+ mod replace_source;
+ mod rig3d;
+ pub(crate) mod roto;
+ mod sequence;
+ mod session;
+ mod settings;
+ mod shortcut_cmds;
+ pub(crate) mod stubs;
+ mod styles;
+ mod tail;
+ mod text;
+ mod text_edit;
+ mod three_d;
+ mod timeline;
+ mod timeline_interchange;
+ pub(crate) mod track;
+ mod vector_import;
+ mod viewer;
diff --cc crates/engine/src/tests/keyframe_text.rs
index 30d3b436e,000000000..30d3b436e
mode 100644,000000..100644
--- a/crates/engine/src/tests/keyframe_text.rs
+++ b/crates/engine/src/tests/keyframe_text.rs
diff --cc crates/ui-egui/src/menus/frontend.rs
index 000000000,d808b4620..a05cce92c
mode 000000,100644..100644
--- a/crates/ui-egui/src/menus/frontend.rs
+++ b/crates/ui-egui/src/menus/frontend.rs
@@@ -1,0 -1,684 +1,689 @@@
+ use super::*;
+
+ /// Run an engine command and perform the frontend events it emitted right away.
+ /// Commands that fill the internal clipboard.
+ const COPY_COMMANDS: &[&str] =
+ &["edit.copy", "edit.cut", "edit.copyWithPropertyLinks", "edit.copyWithRelativePropertyLinks", "edit.copyExpressionOnly", "keys.copy", "effect.copy"];
+
-/// A line for the system clipboard naming what EffectCraft copied. The system clipboard must
-/// hold something: with nothing on it, the windowing layer sends no paste event for Ctrl+V.
-fn clipboard_note(s: &effectcraft_engine::Session) -> String {
++/// Text for the system clipboard: copied keyframes and values as After Effects keyframe text,
++/// for other applications (#1908), else a line naming what EffectCraft copied. The system
++/// clipboard must hold something: with nothing on it, the windowing layer sends no paste event
++/// for Ctrl+V. Paste in EffectCraft uses its own clipboard either way.
++fn clipboard_text(s: &effectcraft_engine::Session) -> String {
+ let st = &s.state;
++ if let Some(text) = &st.keyframe_text {
++ return text.clone();
++ }
+ let n = |n: usize, one: &str, many: &str| format!("EffectCraft: {n} {}", if n == 1 { one } else { many });
+ if st.clip_is_keys && !st.key_clipboard.is_empty() {
+ n(st.key_clipboard.iter().map(|c| c.keys.len()).sum(), "keyframe", "keyframes")
+ } else if !st.effect_clipboard.is_empty() {
+ n(st.effect_clipboard.len(), "effect", "effects")
+ } else if !st.contents_clipboard.is_empty() {
+ n(st.contents_clipboard.len(), "shape item", "shape items")
+ } else if st.link_clipboard.is_some() {
+ "EffectCraft: property links".into()
+ } else {
+ n(st.clipboard.len(), "layer", "layers")
+ }
+ }
+
+ pub(crate) fn run_engine(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
+ // Events already queued belong to earlier invocations (`engine.execute` defers them).
+ let queued = app.session.events.len();
+ let mut r = app.session.execute(id, params).map_err(|e| e.to_string());
+ if let Err(e) = &r {
+ app.ui.status = e.clone();
+ } else if COPY_COMMANDS.contains(&id) && app.session.state.text_edit.is_none() {
- ctx.copy_text(clipboard_note(&app.session));
++ ctx.copy_text(clipboard_text(&app.session));
+ }
+ let events = app.session.drain_events();
+ for (index, ev) in events.into_iter().enumerate() {
+ match ev {
+ effectcraft_engine::Event::Frontend { command, params } => {
+ if let Err(e) = frontend(app, ctx, &command, params) {
+ app.ui.status = e.clone();
+ // A frontend-only command's own failure is the command's result (#696: a
+ // workspace save that didn't reach disk reported success). An earlier
+ // invocation's failure only sets the status.
+ if index >= queued && command == id && r.is_ok() {
+ r = Err(e);
+ }
+ }
+ }
+ other => app.session.events.push(other),
+ }
+ }
+ r
+ }
+
+ fn toggle(slot: &mut bool, p: &Value) -> Value {
+ *slot = p.get("value").and_then(Value::as_bool).unwrap_or(!*slot);
+ json!(*slot)
+ }
+
+ /// Perform a frontend command (from `Event::Frontend`).
+ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Value) -> Result<Value, String> {
+ let now = app.now();
+ let v = &mut app.ui.viewer;
+ Ok(match id {
+ "mediaBrowser.copySourcePath" => {
+ let path = p.get("path").and_then(Value::as_str).filter(|path| !path.is_empty()).ok_or("A source path is required")?;
+ ctx.copy_text(path.to_string());
+ json!({"path": path})
+ }
+ "effects.copyPresetsFolderPath" => {
+ if cfg!(target_arch = "wasm32") {
+ return Err("The web app has no local presets folder".into());
+ }
+ let path = crate::panels::effects_presets::presets_dir().filter(|path| !path.as_os_str().is_empty()).ok_or("No presets folder is configured")?;
+ let path = std::path::absolute(path).map_err(|e| format!("Cannot resolve the presets folder path: {e}"))?;
+ let path = path.to_str().ok_or("The presets folder path is not valid UTF-8")?;
+ ctx.copy_text(path.to_string());
+ json!({"path": path})
+ }
+ "app.checkForUpdates" | "help.checkForUpdates" => {
+ crate::updates_ui::check(app);
+ Value::Null
+ }
+ "app.about" => {
+ app.dialog = Some(crate::Dialog::About);
+ Value::Null
+ }
+ // Window ▸ <ScriptUI panel>: dock (or bring forward) the panel the script built.
+ // Audio scrubbing: one frame of audio at `time` (default the current time).
+ "playback.scrubAudio" => {
+ let cid = app.session.active_comp_id().ok_or("no composition")?;
+ let t = p.get("time").and_then(Value::as_f64).map_or(app.session.time(), effectcraft_engine::time::Tick::from_seconds_f64);
+ app.scrub_audio(cid, t, now);
+ json!({"playing": app.scrub.is_some()})
+ }
+ // View ▸ New Viewer.
+ "view.newViewer" => json!({"viewer": crate::panels::viewers::new_viewer(app)}),
+ // Reveal Layer Source / Reveal Composition: show the Project panel on the item, opening
+ // its folders and clearing the search so the row is visible.
+ "project.reveal" => {
+ let ids: Vec<effectcraft_engine::project::ItemId> = p
+ .get("items")
+ .and_then(Value::as_array)
+ .map(|items| items.iter().filter_map(Value::as_u64).map(effectcraft_engine::project::ItemId).collect())
+ .or_else(|| p.get("item").and_then(Value::as_u64).map(|item| vec![effectcraft_engine::project::ItemId(item)]))
+ .unwrap_or_default();
+ crate::panels::project::reveal(app, ctx, &ids);
+ json!({"items": ids.iter().map(|item| item.0).collect::<Vec<_>>()})
+ }
+ // 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));
+ json!({"window": id})
+ }
+ "layer.style.options" => {
+ crate::panels::layer_styles_dialog::open(app, &p)?;
+ Value::Null
+ }
+ "app.settings" => {
+ let page = p.get("page").and_then(Value::as_str).unwrap_or("general");
+ crate::panels::settings::open(app, effectcraft_engine::prefs::page_id(page).unwrap_or("general"));
+ Value::Null
+ }
+ "app.gpuInfo" => {
+ crate::panels::dialogs::info(
+ app,
+ "GPU Information",
+ &format!(
+ "{}Layer cache: {} MB • Preview cache: {} MB.",
+ effectcraft_engine::sysinfo::gpu_summary(&app.session),
+ app.session.layer_cache.budget() >> 20,
+ app.frames.budget() >> 20
+ ),
+ );
+ Value::Null
+ }
+ "app.hide" | "app.hideOthers" | "app.showAll" => {
+ // The desktop app asks macOS (NSApplication hide / hideOtherApplications /
+ // unhideAllApplications); elsewhere Hide minimizes and the others don't apply.
+ if app.hooks.app_action.as_ref().is_some_and(|f| f(id)) {
+ return Ok(Value::Null);
+ }
+ match id {
+ "app.hide" => ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true)),
+ _ => return Err(format!("`{id}` is only available on macOS")),
+ }
+ Value::Null
+ }
+ "app.quit" => {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+ Value::Null
+ }
+ "app.commandPalette" => {
+ app.dialog_state.palette_query = p.get("query").and_then(Value::as_str).unwrap_or_default().to_string();
+ app.dialog_state.palette_sel = 0;
+ app.dialog = Some(crate::Dialog::CommandPalette);
+ Value::Null
+ }
+ "app.keyboardShortcuts" => {
+ crate::panels::shortcut_editor::open(app);
+ Value::Null
+ }
+ "app.templates" => {
+ let kind = p.get("kind").and_then(Value::as_str).unwrap_or("renderSettings");
+ crate::panels::rq_templates::open(app, ctx, kind);
+ Value::Null
+ }
+ "renderQueue.notify" => {
+ // Render finished with Notify on: a toast, the dock/taskbar attention request, and the
+ // host's system sound (the desktop app handles `renderQueue.notify`).
+ let msg = p.get("message").and_then(Value::as_str).unwrap_or("Render finished").to_string();
+ app.toast = Some((msg, now));
+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(egui::UserAttentionType::Informational));
+ if let Some(f) = app.hooks.app_action.as_ref() {
+ f("renderQueue.notify");
+ }
+ Value::Null
+ }
+ "app.find" => {
+ if let Some(q) = p.get("query").and_then(Value::as_str) {
+ app.ui.project_search = q.to_string();
+ }
+ app.show_panel(PanelKind::Project);
+ Value::Null
+ }
+ "playback.toggle" => {
+ // The play button and Spacebar: `{shortcut?}` picks which Preview panel shortcut's
+ // options to play with (default Spacebar).
+ let sc = match p.get("shortcut").and_then(Value::as_str) {
+ Some(k) => effectcraft_engine::preview::PreviewShortcut::parse(k).ok_or_else(|| format!("unknown preview shortcut `{k}`"))?,
+ None => effectcraft_engine::preview::PreviewShortcut::Spacebar,
+ };
+ app.toggle_play_with(now, sc);
+ json!({"playing": app.playback.playing, "shortcut": sc.id()})
+ }
+ "playback.cacheWhenIdle" => {
+ let r = toggle(&mut app.ui.cache_when_idle, &p);
+ app.set_pref("previews.cacheFramesWhenIdle", r.clone())?;
+ r
+ }
+ "playback.audio" => {
+ // Include Audio of the shortcut shown in the Preview panel.
+ let mut on = app.session.prefs.preview.active().include_audio;
+ let r = toggle(&mut on, &p);
+ app.session.execute("playback.settings.set", json!({"includeAudio": on})).map_err(|e| e.to_string())?;
+ if !on {
+ app.audio = None;
+ }
+ 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));
+ let next = zoom_step(cur, ppp, id == "view.zoomIn");
+ v.zoom = Some(next);
+ json!({"zoom": next})
+ }
+ // View ▸ Resolution ▸ Custom without a factor (the engine sets the comp's resolution).
+ "view.res.custom" => {
+ 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),
+ "view.guides" => toggle(&mut v.guides, &p),
+ "view.snapToGuides" => toggle(&mut v.snap_guides, &p),
+ "view.lockGuides" => toggle(&mut v.lock_guides, &p),
+ "view.grid" => toggle(&mut v.grid, &p),
+ "view.snapToGrid" => toggle(&mut v.snap_grid, &p),
+ "view.layerControls" => toggle(&mut v.show_layer_controls, &p),
+ "view.options" => {
+ app.dialog = Some(crate::Dialog::ViewOptions);
+ Value::Null
+ }
+ "view.panelBackground" => {
+ if p.get("pick").and_then(Value::as_bool) == Some(true) {
+ let [r, g, b] = v.custom_pasteboard;
+ crate::panels::dialogs::form(
+ app,
+ "Panel Background Color",
+ "view.panelBackground",
+ json!({}),
+ vec![crate::panels::dialogs::Field::text("color", "Color (#rrggbb)", &format!("#{r:02x}{g:02x}{b:02x}"))],
+ );
+ return Ok(Value::Null);
+ }
+ let c = p.get("color").and_then(Value::as_str).unwrap_or("mediumGray");
+ v.pasteboard = match c {
+ "black" => Some([0, 0, 0]),
+ "darkGray" => Some([0x2a, 0x2a, 0x2a]),
+ "mediumGray" => None,
+ "lightGray" => Some([0xb4, 0xb4, 0xb4]),
+ "white" => Some([0xff, 0xff, 0xff]),
+ "custom" => Some(v.custom_pasteboard),
+ hex => {
+ let c = effectcraft_engine::color::Rgba::from_hex(hex).ok_or_else(|| format!("unknown colour `{hex}`"))?;
+ let rgb = [(c.r * 255.0).round() as u8, (c.g * 255.0).round() as u8, (c.b * 255.0).round() as u8];
+ v.custom_pasteboard = rgb;
+ Some(rgb)
+ }
+ };
+ Value::Null
+ }
+ // Ctrl+\ / Cmd+\, as in After Effects (#336): `{maximized}`, the window's new state.
+ "window.maximizeApp" => {
+ let maximized = !ctx.input(|i| i.viewport().maximized.unwrap_or(false));
+ ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(maximized));
+ json!({"maximized": maximized})
+ }
+ "view.fullScreen" => {
+ let full = ctx.input(|i| i.viewport().fullscreen.unwrap_or(false));
+ ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(!full));
+ json!(!full)
+ }
+ "window.panel" => {
+ let name = p.get("panel").and_then(Value::as_str).unwrap_or_default();
+ if name.eq_ignore_ascii_case("tools") {
+ app.ui.status = "The Tools panel is the toolbar in the header".into();
+ return Ok(Value::Null);
+ }
+ let panel = PanelKind::from_name(name).ok_or_else(|| format!("unknown panel `{name}`"))?;
+ app.show_panel(panel);
+ Value::Null
+ }
+ "window.workspace" => {
+ let want = p.get("name").and_then(Value::as_str).unwrap_or("Default").to_ascii_lowercase().replace(' ', "");
+ let name = app
+ .workspace_names()
+ .into_iter()
+ .find(|w| w.to_ascii_lowercase().replace(' ', "") == want)
+ .ok_or_else(|| format!("unknown workspace `{want}`"))?;
+ app.set_workspace(&name);
+ json!({"workspace": name})
+ }
+ "window.resetWorkspace" => {
+ let name = app.ui.workspace.clone();
+ app.set_workspace(&name);
+ Value::Null
+ }
+ "window.saveWorkspace" => {
+ let name = app.ui.workspace.clone();
+ app.ui.saved_workspaces.insert(name.clone(), app.ui.dock.clone());
+ app.store_saved_workspaces()?;
+ json!({"workspace": name})
+ }
+ "window.saveWorkspaceAs" => {
+ let Some(name) = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string) else {
+ crate::panels::dialogs::form(
+ app,
+ "New Workspace",
+ "window.saveWorkspaceAs",
+ json!({}),
+ vec![crate::panels::dialogs::Field::text("name", "Name", "Untitled Workspace")],
+ );
+ return Ok(Value::Null);
+ };
+ app.ui.saved_workspaces.insert(name.clone(), app.ui.dock.clone());
+ app.ui.workspace = name.clone();
+ app.store_saved_workspaces()?;
+ json!({"workspace": name})
+ }
+ "window.editWorkspaces" => {
+ let Some(name) = p.get("name").and_then(Value::as_str).map(str::to_string) else {
+ let cur = app.ui.workspace.clone();
+ crate::panels::dialogs::form(
+ app,
+ "Edit Workspaces",
+ "window.editWorkspaces",
+ json!({}),
+ vec![
+ crate::panels::dialogs::Field::text("name", "Workspace", &cur),
+ crate::panels::dialogs::Field::text("rename", "Rename to", &cur),
+ crate::panels::dialogs::Field::bool("delete", "Delete", false),
+ ],
+ );
+ return Ok(Value::Null);
+ };
+ let builtin = crate::dock::WORKSPACES.contains(&name.as_str());
+ if p.get("delete").and_then(Value::as_bool) == Some(true) {
+ if app.ui.saved_workspaces.remove(&name).is_none() && !builtin {
+ return Err(format!("no workspace `{name}`"));
+ }
+ // Leave the deleted workspace first: a current workspace needs a definition.
+ if app.ui.workspace == name {
+ app.set_workspace("Default");
+ }
+ app.store_saved_workspaces()?;
+ return Ok(json!({"deleted": name}));
+ }
+ if let Some(new) = p.get("rename").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty() && *n != name) {
+ if builtin {
+ return Err(format!("`{name}` is a built-in workspace: save it as a new workspace instead"));
+ }
+ let dock = app.ui.saved_workspaces.remove(&name).ok_or_else(|| format!("no workspace `{name}`"))?;
+ app.ui.saved_workspaces.insert(new.to_string(), dock);
+ if app.ui.workspace == name {
+ app.ui.workspace = new.to_string();
+ }
+ app.store_saved_workspaces()?;
+ return Ok(json!({"renamed": new}));
+ }
+ json!({"workspaces": app.workspace_names()})
+ }
+ "view.lookAt" => {
+ let r: Vec<f64> = p.get("rect").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
+ if r.len() == 4 {
+ let map: Option<crate::panels::viewer::ViewerMap> = ctx.data(|d| d.get_temp(egui::Id::unique("viewer-map")));
+ if let Some(m) = map {
+ let (rw, rh) = (((r[2] - r[0]) as f32).max(1.0), ((r[3] - r[1]) as f32).max(1.0));
+ let zoom = ((m.area.width() - 40.0) / rw).min((m.area.height() - 40.0) / rh).clamp(0.015, 32.0);
+ let rc = [(r[0] + r[2]) as f32 / 2.0, (r[1] + r[3]) as f32 / 2.0];
+ let v = &mut app.ui.viewer;
+ v.zoom = Some(zoom);
+ v.pan = [m.comp[0] * zoom / 2.0 - rc[0] * zoom, m.comp[1] * zoom / 2.0 - rc[1] * zoom];
+ }
+ }
+ Value::Null
+ }
+ "comp.flowchart" => {
+ // Chart the active comp; Layer ▸ Reveal ▸ Reveal Layer in Project Flowchart shows
+ // layers and selects the layer's node.
+ app.ui.flowchart.root = app.session.active_comp_id().map(|c| c.0);
+ if let (Some(c), Some(l)) = (app.session.active_comp_id(), app.session.state.selected_layers.first()) {
+ app.ui.flowchart.layers = true;
+ app.ui.flowchart.selected = Some(format!("layer:{}:{}", c.0, l.0));
+ }
+ app.show_panel(PanelKind::Flowchart);
+ Value::Null
+ }
+ "comp.miniFlowchart" => {
+ let at = ctx.input(|i| i.pointer.hover_pos()).unwrap_or_else(|| ctx.content_rect().center());
+ app.ui.mini_flowchart = Some([at.x, at.y]);
+ Value::Null
+ }
+ "track.editTargetDialog" => {
+ crate::panels::tracker::open_target(app)?;
+ Value::Null
+ }
+ "track.optionsDialog" => {
+ crate::panels::tracker::open_options(app)?;
+ Value::Null
+ }
+ "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);
+ Value::Null
+ }
+ "app.confirmExecute" => {
+ // Settings ▸ Scripting ▸ Warn User When Executing Files.
+ let path = p.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
+ crate::panels::forms::form(
+ app,
+ "A script wants to open a file",
+ "file.executeFile",
+ json!({"path": path, "confirmed": true}),
+ vec![crate::panels::forms::Field::text("path", "Open", &path)],
+ );
+ Value::Null
+ }
+ "app.showReport" => {
+ let title = p.get("title").and_then(Value::as_str).unwrap_or("Report").to_string();
+ let text = p.get("text").and_then(Value::as_str).unwrap_or_default().to_string();
+ crate::panels::dialogs::info(app, &title, &text);
+ Value::Null
+ }
+ "window.assignWorkspaceShortcut" => {
+ let mut q = p.clone();
+ q["workspace"] = json!(app.ui.workspace);
+ return run_engine(app, ctx, "window.assignWorkspaceShortcut", q);
+ }
+ "file.interpretFootage" => {
+ // Import ▸ Interpret Unlabeled Alpha As: Ask User.
+ if let Some(i) = p.get("item").and_then(Value::as_u64) {
+ app.session.state.project_selection = vec![effectcraft_engine::project::ItemId(i)];
+ }
+ crate::panels::dialogs::open_form(app, "file.interpretFootage", &json!({}));
+ Value::Null
+ }
+ // Help ▸ In-App Tutorials: the Home screen's Learn tab.
+ "help.inAppTutorials" => {
+ app.ui.start_screen = true;
+ app.ui.home_learn = true;
+ app.ui.home_templates = false;
+ Value::Null
+ }
+ // File ▸ New ▸ New Project from Template…: the Home screen's Templates tab.
+ "file.newFromTemplate" => {
+ app.ui.start_screen = true;
+ app.ui.home_learn = false;
+ app.ui.home_templates = true;
+ Value::Null
+ }
+ "effect.manage" | "anim.browsePresets" => {
+ app.show_panel(PanelKind::EffectsPresets);
+ Value::Null
+ }
+ "timeline.revealProps" => {
+ let props = p.get("props").and_then(Value::as_array).cloned().unwrap_or_default();
+ let uids = |k: &str| -> Vec<u64> { props.iter().filter_map(|x| x.get(k).and_then(Value::as_u64)).collect() };
+ let (found, with_props) = (uids("prop"), uids("layer"));
+ // The layers it looked at (`layers`), else those it found something on. Layers that
+ // have nothing to show close; the others' reveals stay.
+ let targets: Vec<u64> = match p.get("layers").and_then(Value::as_array) {
+ Some(l) => l.iter().filter_map(Value::as_u64).collect(),
+ None => with_props.clone(),
+ };
+ // The targets' earlier picks go (U after UU shows the keyframed ones only).
+ let comp = app.session.active_comp_arc();
+ let theirs = |u: u64| {
+ comp.as_ref().is_some_and(|c| {
+ targets
+ .iter()
+ .filter_map(|l| c.layer(effectcraft_engine::project::LayerId(*l)))
+ .any(|l| l.props.find(u).is_some() || l.props.find_group(u).is_some())
+ })
+ };
+ let tl = &mut app.ui.timeline;
+ tl.reveal_props.retain(|u| !theirs(*u));
+ tl.reveal_props.extend(found.iter().copied());
+ let (shown, hidden): (Vec<u64>, Vec<u64>) = targets.into_iter().partition(|l| with_props.contains(l));
+ tl.apply_reveal(&hidden, vec![]);
+ if !shown.is_empty() {
+ tl.apply_reveal(&shown, vec!["props".into()]);
+ }
+ // Properties inside effects (puppet pins…) show under their effect, twirled open.
+ for (layer, prop) in props.iter().filter_map(|x| Some((x.get("layer")?.as_u64()?, x.get("prop")?.as_u64()?))) {
+ crate::panels::timeline::open_effect_paths(app, layer, &[prop]);
+ }
+ json!({"revealed": found.len()})
+ }
+ _ => return Err(format!("`{id}` is not a frontend command")),
+ })
+ }
+
+ /// Commands that need a file or folder path: ask the host's file dialog when `params` lacks one.
+ pub(super) fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ enum Ask {
+ Folder,
+ Import,
+ OpenProject,
+ Save(&'static str),
+ Open(&'static [&'static str]),
+ }
+ let (key, ask) = match id {
+ "file.import" | "file.importMultiple" => ("paths", Ask::Import),
+ "file.open" => ("path", Ask::OpenProject),
+ "file.save" if app.session.path.is_none() => ("path", Ask::Save("Untitled Project.ecproj")),
+ "file.saveAs" | "file.saveCopy" => ("path", Ask::Save("Untitled Project.ecproj")),
+ "comp.saveFrameAs" => ("path", Ask::Save("Frame.png")),
+ "comp.saveFrameAsPsd" => ("path", Ask::Save("Frame.psd")),
+ "comp.saveFrameAsExr" => ("path", Ask::Save("Frame.exr")),
+ "file.watchFolder" if params.get("stop").is_none() => ("folder", Ask::Save("Watch Folder")),
+ "anim.savePreset" => ("path", Ask::Save("Preset.ecpreset")),
+ "anim.applyPreset" => ("path", Ask::Open(&["ecpreset", "json"])),
+ "view.exportGuides" => ("path", Ask::Save("Guides.json")),
+ "view.importGuides" => ("path", Ask::Open(&["json"])),
+ "file.exportLottie" => ("path", Ask::Save("Animation.json")),
+ "file.importLottie" => ("path", Ask::Open(&["json", "lottie"])),
+ "file.importProject" => ("path", Ask::Open(&["ecproj", "ecprojx"])),
+ "file.importTimeline" => ("path", Ask::Open(&["xml", "fcpxml", "otio", "edl", "aaf", "omf"])),
+ "render.saveCurrentPreview" => ("path", Ask::Save("Preview.mp4")),
+ "file.runScript" if params.get("name").is_none() => ("path", Ask::Open(&["jsx", "js", "jsonl", "json", "txt"])),
+ "file.installScript" | "file.installScriptUIPanel" => ("path", Ask::Open(&["jsx", "js"])),
+ "effect.plugins.load" if params.get("folder").is_none() => ("path", Ask::Open(&["wasm", "wat"])),
+ "file.replaceFootage" => ("path", Ask::Import),
+ "file.relinkFootage" => ("folder", Ask::Folder),
+ "file.collectFiles" => ("folder", Ask::Save("Collected Files")),
+ "file.saveCopyAsXml" => ("path", Ask::Save("Untitled Project.ecprojx")),
+ "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", "mxf", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "tga", "exr"]))
+ }
+ _ => return None,
+ };
+ if params.get(key).is_some()
+ || params.get("path").is_some()
+ || params.get("paths").is_some()
+ || params.get("steps").is_some()
+ || params.get("preset").is_some()
+ {
+ return None;
+ }
+ const MEDIA: &[&str] = &[
+ "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 blocking dialogs are unsafe inside this frame shows the dialog without
+ // blocking — macOS: the nested event loop re-entered winit's handler on a drag over the
+ // window and aborted the app (#511); Linux: the desktop portal's answer never gets pumped,
+ // so the compositor marks the window as not responding (#1275) — and the command continues
+ // when the answer arrives.
+ if let Some(spawn) = app.hooks.file_dialog_async.as_ref() {
+ let request = match ask {
+ Ask::Folder => crate::FileDialog::Folder,
+ Ask::Import => crate::FileDialog::Open { exts: MEDIA.iter().map(|e| e.to_string()).collect(), many: key == "paths" },
+ Ask::OpenProject => crate::FileDialog::OpenProject,
+ Ask::Open(exts) => crate::FileDialog::Open { exts: exts.iter().map(|e| e.to_string()).collect(), many: false },
+ Ask::Save(default) => crate::FileDialog::save(default),
+ };
+ let tx = app.dialog_answers.0.clone();
+ let answer = crate::DialogAnswer { command: id.to_string(), key, params: params.clone(), paths: Vec::new() };
+ app.file_dialogs.opened();
+ spawn(
+ request,
+ Box::new(move |paths| {
+ let _ = tx.send(crate::DialogAnswer { paths, ..answer });
+ }),
+ );
+ return Some(Ok(json!({"dialog": id})));
+ }
+ let picked: Option<Value> = match ask {
+ Ask::Folder => {
+ let Some(f) = app.hooks.pick_folder.as_ref() else { return Some(Err("no folder dialog available (pass `folder`)".into())) };
+ f().map(Value::from)
+ }
+ Ask::Import => {
+ let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `paths`)".into())) };
+ picked_value(key, f(MEDIA))
+ }
+ Ask::OpenProject => {
+ let Some(f) = app.hooks.pick_open_project.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
+ f().map(|s| json!(s))
+ }
+ Ask::Open(exts) => {
+ let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
+ f(exts).first().map(|s| json!(s))
+ }
+ Ask::Save(default) => {
+ let Some(picked) = app.hooks.save_dialog(default) else { return Some(Err("no file dialog available (pass `path`)".into())) };
+ picked.map(|s| json!(s))
+ }
+ };
+ let Some(v) = picked else { return Some(Ok(Value::Null)) };
+ Some(run_with_picked(app, id, key, params, v))
+ }
+
+ /// The dialog's answer as the command's `key` parameter (`None`: cancelled).
+ fn picked_value(key: &str, paths: Vec<String>) -> Option<Value> {
+ match (paths.is_empty(), key) {
+ (true, _) => None,
+ (false, "paths") => Some(json!(paths)),
+ (false, _) => paths.into_iter().next().map(Value::from),
+ }
+ }
+
+ /// A file dialog shown without blocking ([`crate::Hooks::file_dialog_async`]) answered: run its
+ /// command with the picked path (nothing when it was cancelled).
+ pub(crate) fn dialog_answered(app: &mut EffectcraftApp, answer: crate::DialogAnswer) {
+ let Some(v) = picked_value(answer.key, answer.paths) else { return };
+ if let Err(e) = run_with_picked(app, &answer.command, answer.key, &answer.params, v) {
+ app.ui.status = e;
+ }
+ }
+
+ /// Run command `id` with the path picked for it in parameter `key`.
+ fn run_with_picked(app: &mut EffectcraftApp, id: &str, key: &str, params: &Value, v: Value) -> Result<Value, String> {
+ let mut p = params.as_object().cloned().unwrap_or_default();
+ p.insert(key.to_string(), v);
+ // Picked files import in the background, with the Importing card showing progress (#270).
+ if matches!(id, "file.import" | "file.importMultiple") {
+ p.insert("background".into(), Value::Bool(true));
+ }
+ // Photoshop files ask how to import them first; numbered stills whether to import them as an
+ // image sequence.
+ let picked = Value::Object(p.clone());
+ if id == "file.import" && crate::panels::dialogs::open_form(app, id, &picked)
+ || matches!(id, "file.import" | "file.importMultiple") && crate::panels::forms::open_import_sequence(app, &picked)
+ {
+ return Ok(json!({"dialog": id}));
+ }
+ // Save (untitled) becomes Save As.
+ let id = if id == "file.save" { "file.saveAs" } else { id };
+ let r = app.session.execute(id, Value::Object(p)).map_err(|e| e.to_string());
+ if let Err(e) = &r {
+ app.ui.status = e.clone();
+ }
+ r
+ }
+
+ /// 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).
+ pub(super) 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
+ }