EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Preserve recent script files across menu and settings module changes
dotCooCoo2c2c51ca0c88
diff --cc crates/engine/src/services.rsindex 000000000,01a2102ec..a8ee48060mode 000000,100644..100644--- a/crates/engine/src/services.rs+++ b/crates/engine/src/services.rs@@@ -1,0 -1,65 +1,71 @@@+ use super::*;++ /// 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()+ }++ /// `path` as a list of recent files keeps it (File ▸ Scripts ▸ Recent Script Files): a++ /// relative path is made absolute against the working directory, so it opens the same file++ /// after the working directory changes.++ fn full_path(&self, path: &str) -> String {++ std::path::absolute(path).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| path.to_string())++ }+ }++ /// 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]) {}+ }diff --cc crates/engine/src/settings/prefs.rsindex 000000000,1ed7fea2a..03b2516d3mode 000000,100644..100644--- a/crates/engine/src/settings/prefs.rs+++ b/crates/engine/src/settings/prefs.rs@@@ -1,0 -1,128 +1,132 @@@+ //! Settings (After Effects' Preferences): a versioned serde model, addressed by dotted keys+ //! (`general.undoLevels`, `autoSave.intervalMinutes`, `labels.3.name`), plus the page schema the+ //! Settings dialog and agents (`prefs.pages`) are built from.+ //!+ //! Settings are stored as JSON (`prefs.json`) through the session's [`crate::config::ConfigStore`].+ //! Loading is forgiving: missing keys take their defaults, unknown keys (written by a newer+ //! version) are kept and written back, and older layouts are migrated ([`migrate`]).+ //!+ //! Every setting in [`pages`] says whether it already changes behaviour (`live`). Settings that+ //! don't yet are still shown (After Effects parity of the dialog) and are listed in+ //! `docs/preferences.md`; a test keeps that list in step with the schema.++ use std::collections::BTreeMap;++ use effectcraft_color::Label;+ use effectcraft_time::Tick;+ use serde::{Deserialize, Serialize};+ use serde_json::{Map, Value, json};++ mod choices;+ mod dialog;+ mod document;+ mod queries;+ mod recent;+ mod sections;++ pub use choices::{APPEARANCE_MODES, DARK_THEMES, LANGUAGES, LIGHT_THEMES, THEMES, WINDOW_GRAPHICS, theme_family};+ pub use dialog::{Item, Kind, Page, pages, pages_json, todo_keys};+ pub use document::{migrate, page_id, section_key};+ pub use queries::{CacheBudgets, WEB_LAYER_CACHE, WEB_MEDIA_CACHE, mask_color};++pub use recent::{MAX_RECENT_SCRIPTS, RecentScript};+ pub use sections::{+ Appearance, Audio, AutoSave, CompPreset, CompositionPrefs, Disk, Export, FacePrefs, General, Grids, Import, LabelPref, Memory, Previews, ProjectPrefs,+ RotoPrefs, Scripting, Startup, ThreeD, TypePrefs, Video,+ };+ use sections::{Extra, default_labels, lenient_comp_presets};++ /// Current settings layout version.+ pub const PREFS_VERSION: u32 = 2;+ /// Settings file name in the config store.+ pub const PREFS_FILE: &str = "prefs.json";++ /// All settings.+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+ #[serde(default, rename_all = "camelCase")]+ pub struct Prefs {+ pub version: u32,+ pub general: General,+ pub startup: Startup,+ pub project: ProjectPrefs,+ pub auto_save: AutoSave,+ pub composition: CompositionPrefs,+ pub previews: Previews,+ pub appearance: Appearance,+ pub grids: Grids,+ /// The 16 labels (Red … Dark Green), in order.+ pub labels: Vec<LabelPref>,+ #[serde(rename = "type")]+ pub type_: TypePrefs,+ pub import: Import,+ pub export: Export,+ pub audio: Audio,+ pub disk: Disk,+ pub memory: Memory,+ pub video: Video,+ #[serde(rename = "threeD")]+ pub three_d: ThreeD,+ pub scripting: Scripting,+ pub roto: RotoPrefs,+ pub face: FacePrefs,+ /// File ▸ Open Recent, newest first.+ pub recent_projects: Vec<String>,+ /// File ▸ Import Recent Footage, newest first.+ pub recent_footage: Vec<String>,+ /// Animation ▸ Recent Animation Presets (`.ecpreset` paths or built-in preset ids), newest+ /// first.+ pub recent_presets: Vec<String>,++ /// File ▸ Scripts ▸ Recent Script Files, newest first, at most [`MAX_RECENT_SCRIPTS`].++ pub recent_scripts: Vec<RecentScript>,+ /// Character panel: recently used font families, newest first.+ pub recent_fonts: Vec<String>,+ /// Effects & Presets: the starred effects' ids, in the order starred.+ pub effects_favorites: Vec<String>,+ /// Preview panel: every shortcut's options.+ pub preview: crate::preview::PreviewSettings,+ /// View ▸ Simulate Output ▸ My Custom RGB.+ pub custom_rgb: crate::viewer::CustomRgb,+ /// Composition Settings presets the user saved, in the order saved.+ #[serde(deserialize_with = "lenient_comp_presets")]+ pub comp_presets: Vec<CompPreset>,+ /// Top-level keys this version doesn't know (kept for newer versions).+ #[serde(flatten)]+ pub extra: Extra,+ }++ impl Default for Prefs {+ fn default() -> Self {+ Prefs {+ version: PREFS_VERSION,+ general: General::default(),+ startup: Startup::default(),+ project: ProjectPrefs::default(),+ auto_save: AutoSave::default(),+ composition: CompositionPrefs::default(),+ previews: Previews::default(),+ appearance: Appearance::default(),+ grids: Grids::default(),+ labels: default_labels(),+ type_: TypePrefs::default(),+ import: Import::default(),+ export: Export::default(),+ audio: Audio::default(),+ disk: Disk::default(),+ memory: Memory::default(),+ video: Video::default(),+ three_d: ThreeD::default(),+ scripting: Scripting::default(),+ roto: RotoPrefs::default(),+ face: FacePrefs::default(),+ recent_projects: vec![],+ recent_footage: vec![],+ recent_presets: vec![],++ recent_scripts: vec![],+ recent_fonts: vec![],+ effects_favorites: vec![],+ preview: crate::preview::PreviewSettings::default(),+ custom_rgb: crate::viewer::CustomRgb::default(),+ comp_presets: vec![],+ extra: Extra::new(),+ }+ }+ }diff --cc crates/engine/src/settings/prefs/document.rsindex 000000000,49f2e5e9d..1a7ec6182mode 000000,100644..100644--- a/crates/engine/src/settings/prefs/document.rs+++ b/crates/engine/src/settings/prefs/document.rs@@@ -1,0 -1,315 +1,317 @@@+ use super::choices::{APPEARANCE_MODES, DARK_THEMES, LANGUAGES, LIGHT_THEMES, THEMES, WINDOW_GRAPHICS, choices, is_choice, theme_family};+ use super::recent::MAX_EFFECTS_FAVORITES;+ use super::sections::{CompPreset, default_labels, parse_hex};+ use super::*;++ /// Bring an older settings document up to [`PREFS_VERSION`].+ ///+ /// - version 0/1 (early builds) kept a flat object: `undoLevels`, `autoSaveEnabled`,+ /// `autoSaveMinutes`, `autoSaveVersions`, `labelNames` (array) and `theme` at the top level.+ pub fn migrate(mut v: Value) -> Value {+ let Some(obj) = v.as_object_mut() else { return json!({}) };+ let version = obj.get("version").and_then(Value::as_u64).unwrap_or(0);+ if version < 2 {+ let moved = |from: &str, page: &str, key: &str, obj: &mut Map<String, Value>| {+ if let Some(x) = obj.remove(from) {+ let p = obj.entry(page.to_string()).or_insert_with(|| json!({}));+ if let Some(p) = p.as_object_mut() {+ p.entry(key.to_string()).or_insert(x);+ }+ }+ };+ moved("undoLevels", "general", "undoLevels", obj);+ moved("autoSaveEnabled", "autoSave", "enabled", obj);+ moved("autoSaveMinutes", "autoSave", "intervalMinutes", obj);+ moved("autoSaveVersions", "autoSave", "maxVersions", obj);+ moved("theme", "appearance", "theme", obj);+ if let Some(Value::Array(names)) = obj.remove("labelNames") {+ let mut labels = default_labels();+ for (l, n) in labels.iter_mut().zip(names) {+ if let Some(n) = n.as_str() {+ l.name = n.to_string();+ }+ }+ obj.insert("labels".into(), serde_json::to_value(labels).unwrap_or_default());+ }+ }+ // Settings saved before appearance modes had one theme: keep showing it, as a fixed Dark or+ // Light mode, instead of switching established users to Auto.+ if let Some(a) = obj.get_mut("appearance").and_then(Value::as_object_mut)+ && !a.contains_key("appearanceMode")+ && let Some(theme) = a.get("theme").and_then(Value::as_str).map(str::to_string)+ && let Some((mode, slot)) = theme_family(&theme)+ {+ a.insert("appearanceMode".into(), json!(mode));+ a.insert(slot.into(), json!(theme));+ }+ obj.insert("version".into(), json!(PREFS_VERSION));+ v+ }++ impl Prefs {+ /// Parse a settings document (migrating older layouts; unknown keys are kept, bad values+ /// fall back to defaults).+ pub fn from_json(text: &str) -> Prefs {+ let v: Value = serde_json::from_str(text).unwrap_or_else(|_| json!({}));+ let v = migrate(v);+ let mut p: Prefs = match serde_json::from_value(v.clone()) {+ Ok(p) => p,+ // One bad value shouldn't lose everything: take each page that parses.+ Err(_) => {+ let mut base = serde_json::to_value(Prefs::default()).unwrap_or_default();+ if let (Some(b), Some(o)) = (base.as_object_mut(), v.as_object()) {+ for (k, x) in o {+ let mut trial = b.clone();+ trial.insert(k.clone(), x.clone());+ if serde_json::from_value::<Prefs>(Value::Object(trial)).is_ok() {+ b.insert(k.clone(), x.clone());+ }+ }+ }+ serde_json::from_value(base).unwrap_or_default()+ }+ };+ p.normalize();+ p+ }++ pub fn to_json(&self) -> String {+ serde_json::to_string_pretty(self).unwrap_or_default()+ }++ /// Clamp values into their valid ranges and fill missing labels.+ pub fn normalize(&mut self) {+ self.version = PREFS_VERSION;+ self.comp_presets.retain(CompPreset::is_valid);+ let mut seen = std::collections::HashSet::new();+ self.effects_favorites.retain(|id| !id.is_empty() && seen.insert(id.clone()));+ self.effects_favorites.truncate(MAX_EFFECTS_FAVORITES);+ if !is_choice(WINDOW_GRAPHICS, &self.startup.window_graphics) {+ self.startup.window_graphics = Startup::default().window_graphics;+ }+ let g = &mut self.general;+ if !is_choice(LANGUAGES, &g.language) {+ g.language = General::default().language;+ }+ g.undo_levels = g.undo_levels.clamp(1, 99);+ g.path_point_size = g.path_point_size.clamp(3, 20);+ g.recent_items = g.recent_items.clamp(1, 30);+ let a = &mut self.auto_save;+ a.interval_minutes = a.interval_minutes.clamp(1, 240);+ a.max_versions = a.max_versions.clamp(1, 99);+ let ap = &mut self.appearance;+ let mut seen = std::collections::BTreeSet::new();+ ap.favorite_themes.retain(|id| is_choice(THEMES, id) && seen.insert(id.clone()));+ if !is_choice(APPEARANCE_MODES, &ap.appearance_mode) {+ ap.appearance_mode = Appearance::default().appearance_mode;+ }+ if !is_choice(DARK_THEMES, &ap.dark_theme) {+ ap.dark_theme = Appearance::default().dark_theme;+ }+ if !is_choice(LIGHT_THEMES, &ap.light_theme) {+ ap.light_theme = Appearance::default().light_theme;+ }+ // The legacy single theme mirrors the theme a fixed mode shows (Auto depends on the+ // system, so it keeps the last one).+ match ap.appearance_mode.as_str() {+ "dark" => ap.theme = ap.dark_theme.clone(),+ "light" => ap.theme = ap.light_theme.clone(),+ _ if !is_choice(THEMES, &ap.theme) => ap.theme = ap.dark_theme.clone(),+ _ => {}+ }+ self.appearance.brightness = self.appearance.brightness.clamp(-1.0, 1.0);+ self.appearance.ui_scale = self.appearance.ui_scale.clamp(75, 200);+ let defaults = default_labels();+ self.labels.truncate(defaults.len());+ for d in defaults.iter().skip(self.labels.len()) {+ self.labels.push(d.clone());+ }+ for (l, d) in self.labels.iter_mut().zip(&defaults) {+ if parse_hex(&l.color).is_none() {+ l.color = d.color.clone();+ }+ }+ let m = &mut self.memory;+ m.layer_cache_mb = m.layer_cache_mb.clamp(64, 1 << 20);+ m.media_cache_mb = m.media_cache_mb.clamp(64, 1 << 20);+ m.preview_cache_mb = m.preview_cache_mb.clamp(64, 1 << 20);+ self.grids.grid_spacing = self.grids.grid_spacing.clamp(1.0, 10_000.0);+ let n = self.general.recent_items as usize;+ self.recent_projects.truncate(n);++ self.recent_scripts.truncate(MAX_RECENT_SCRIPTS);+ }++ /// The value at a dotted key (`general.undoLevels`, `labels.3.color`); `""` = everything.+ pub fn get(&self, key: &str) -> Option<Value> {+ let v = serde_json::to_value(self).ok()?;+ if key.is_empty() {+ return Some(v);+ }+ let ptr = format!("/{}", key.replace('.', "/"));+ v.pointer(&ptr).cloned()+ }++ /// Set the value at a dotted key. The key must exist and the value must have its type.+ pub fn set(&mut self, key: &str, value: Value) -> Result<(), String> {+ if let Some(c) = choices(key)+ && !value.as_str().is_some_and(|v| is_choice(c, v))+ {+ let all: Vec<&str> = c.iter().map(|(_, v)| *v).collect();+ return Err(format!("`{key}` expects one of {}", all.join(", ")));+ }+ let favorites = if key == "appearance.favoriteThemes" {+ Some(&value)+ } else if key == "appearance" {+ value.get("favoriteThemes")+ } else {+ None+ };+ if let Some(favorites) = favorites {+ let values = favorites.as_array().ok_or("favorite themes must be a list")?;+ let mut seen = std::collections::BTreeSet::new();+ for value in values {+ let id = value.as_str().ok_or("favorite theme must be a string")?;+ if !is_choice(THEMES, id) || !seen.insert(id) {+ return Err("unknown or duplicate favorite theme".into());+ }+ }+ }+ // Older clients set the single theme (by key, or inside the page object): it still picks+ // a visible theme, fixing the mode to its family.+ let legacy_theme = key == "appearance.theme" || (key == "appearance" && value.get("theme").is_some() && value.get("appearanceMode").is_none());+ let mut v = serde_json::to_value(&*self).map_err(|e| e.to_string())?;+ let ptr = format!("/{}", key.replace('.', "/"));+ let slot = v.pointer_mut(&ptr).ok_or_else(|| format!("unknown setting `{key}`"))?;+ let value = coerce(slot, value).ok_or_else(|| format!("`{key}` expects a {}", kind_name(slot)))?;+ *slot = value;+ let mut next: Prefs = serde_json::from_value(v).map_err(|e| format!("`{key}`: {e}"))?;+ let (a, b) = (&self.appearance, &next.appearance);+ let only_theme_changed = a.theme != b.theme && a.appearance_mode == b.appearance_mode && a.dark_theme == b.dark_theme && a.light_theme == b.light_theme;+ if legacy_theme || only_theme_changed {+ next.appearance.select_theme();+ }+ next.normalize();+ *self = next;+ Ok(())+ }++ /// Reset one page (`general`, `labels`, `autoSave`…) or everything (`None`). Open Recent and+ /// the saved composition presets are kept.+ pub fn reset(&mut self, page: Option<&str>) -> Result<(), String> {+ let d = Prefs::default();+ let Some(page) = page else {+ *self = Prefs {+ recent_projects: std::mem::take(&mut self.recent_projects),+ recent_footage: std::mem::take(&mut self.recent_footage),+ recent_presets: std::mem::take(&mut self.recent_presets),++ recent_scripts: std::mem::take(&mut self.recent_scripts),+ recent_fonts: std::mem::take(&mut self.recent_fonts),+ effects_favorites: std::mem::take(&mut self.effects_favorites),+ preview: std::mem::take(&mut self.preview),+ comp_presets: std::mem::take(&mut self.comp_presets),+ ..d+ };+ return Ok(());+ };+ let keys: Vec<&str> = match page {+ "project" => vec!["project", "autoSave"],+ p => vec![section_key(p).ok_or_else(|| format!("unknown settings page `{p}`"))?],+ };+ let dv = serde_json::to_value(&d).map_err(|e| e.to_string())?;+ for k in keys {+ if let Some(x) = dv.get(k) {+ self.set(k, x.clone())?;+ }+ }+ Ok(())+ }+ }++ /// Settings key of a page id (`3d` → `threeD`).+ pub fn section_key(page: &str) -> Option<&'static str> {+ Some(match page {+ "general" => "general",+ "startup" => "startup",+ "project" => "project",+ "autoSave" | "autosave" => "autoSave",+ "composition" | "display" => "composition",+ "previews" => "previews",+ "appearance" => "appearance",+ "grids" => "grids",+ "labels" => "labels",+ "type" => "type",+ "import" => "import",+ "export" => "export",+ "audio" => "audio",+ "disk" => "disk",+ "memory" => "memory",+ "video" => "video",+ "3d" | "threeD" => "threeD",+ "scripting" => "scripting",+ "roto" => "roto",+ "face" => "face",+ _ => return None,+ })+ }++ /// Settings page id for a page name, including older After Effects page names+ /// (Auto-Save → Project, Media & Disk Cache → Disk, Memory & Performance → Memory & CPU…).+ pub fn page_id(name: &str) -> Option<&'static str> {+ let n = name.to_ascii_lowercase().replace([' ', '&', '-', '_'], "");+ let id = match n.as_str() {+ "general" => "general",+ "startup" | "startuprepair" => "startup",+ "project" | "autosave" | "newproject" => "project",+ "composition" | "display" => "composition",+ "previews" | "preview" => "previews",+ "appearance" => "appearance",+ "grids" | "gridsguides" => "grids",+ "labels" => "labels",+ "type" => "type",+ "import" => "import",+ "export" | "output" => "export",+ "audio" | "audiohardware" | "audiooutputmapping" => "audio",+ "disk" | "mediadiskcache" | "mediacache" => "disk",+ "memory" | "memorycpu" | "memoryperformance" => "memory",+ "video" | "videopreview" => "video",+ "3d" | "threed" => "3d",+ "scripting" | "scriptingexpressions" => "scripting",+ "roto" | "rotobrush" | "models" => "roto",+ "face" | "facetracking" => "face",+ _ => return None,+ };+ Some(id)+ }++ fn kind_name(v: &Value) -> &'static str {+ match v {+ Value::Bool(_) => "boolean",+ Value::Number(_) => "number",+ Value::String(_) => "string",+ Value::Array(_) => "list",+ Value::Object(_) => "object",+ Value::Null => "value",+ }+ }++ /// `value` converted to the type of `slot` (numbers from strings, booleans from 0/1…).+ fn coerce(slot: &Value, value: Value) -> Option<Value> {+ Some(match (slot, value) {+ (Value::Bool(_), Value::Bool(b)) => json!(b),+ (Value::Bool(_), Value::Number(n)) => json!(n.as_f64()? != 0.0),+ (Value::Bool(_), Value::String(s)) => json!(matches!(s.as_str(), "true" | "on" | "1" | "yes")),+ (Value::Number(cur), v) => {+ let f = match &v {+ Value::Number(n) => n.as_f64()?,+ Value::String(s) => s.trim().parse().ok()?,+ _ => return None,+ };+ if cur.is_u64() || cur.is_i64() { json!(f.round().max(0.0) as u64) } else { json!(f) }+ }+ (Value::String(_), Value::String(s)) => json!(s),+ (Value::String(_), Value::Number(n)) => json!(n.to_string()),+ (Value::Array(_), v @ Value::Array(_)) => v,+ (Value::Object(_), v @ Value::Object(_)) => v,+ _ => return None,+ })+ }diff --cc crates/engine/src/settings/prefs/recent.rsindex 000000000,c5321490d..777a5129cmode 000000,100644..100644--- a/crates/engine/src/settings/prefs/recent.rs+++ b/crates/engine/src/settings/prefs/recent.rs@@@ -1,0 -1,57 +1,85 @@@+ use super::*;++ impl Prefs {+ /// Remember a project in File ▸ Open Recent.+ pub fn push_recent(&mut self, path: &str) {+ self.recent_projects.retain(|p| p != path);+ self.recent_projects.insert(0, path.to_string());+ self.recent_projects.truncate(self.general.recent_items as usize);+ }++ /// Remember a font in the Character panel's recent fonts (Type ▸ Number of Recent Fonts).+ pub fn push_recent_font(&mut self, family: &str) {+ push_mru(&mut self.recent_fonts, family, 30);+ }++ /// Is effect `id` starred in Effects & Presets?+ pub fn is_effect_favorite(&self, id: &str) -> bool {+ self.effects_favorites.iter().any(|f| f == id)+ }++ /// Star effect `id` in Effects & Presets, or un-star it; true when it is starred now.+ pub fn toggle_effect_favorite(&mut self, id: &str) -> bool {+ if self.is_effect_favorite(id) {+ self.effects_favorites.retain(|f| f != id);+ false+ } else {+ self.effects_favorites.push(id.to_string());+ self.effects_favorites.truncate(MAX_EFFECTS_FAVORITES);+ self.is_effect_favorite(id)+ }+ }++ /// The recent fonts the Character panel shows (at most Number of Recent Fonts to Display).+ pub fn recent_fonts_shown(&self) -> &[String] {+ let n = (self.type_.recent_fonts as usize).min(self.recent_fonts.len());+ &self.recent_fonts[..n]+ }++ /// Remember imported footage for File ▸ Import Recent Footage.+ pub fn push_recent_footage(&mut self, path: &str) {+ push_mru(&mut self.recent_footage, path, self.general.recent_items as usize);+ }++ /// Remember an applied animation preset for Animation ▸ Recent Animation Presets.+ pub fn push_recent_preset(&mut self, path: &str) {+ push_mru(&mut self.recent_presets, path, self.general.recent_items as usize);+ }++++ /// Remember a script that ran for File ▸ Scripts ▸ Recent Script Files.++ pub fn push_recent_script(&mut self, script: RecentScript) {++ self.recent_scripts.retain(|x| *x != script);++ self.recent_scripts.insert(0, script);++ self.recent_scripts.truncate(MAX_RECENT_SCRIPTS);++ }++}++++/// Most scripts File ▸ Scripts ▸ Recent Script Files lists.++pub const MAX_RECENT_SCRIPTS: usize = 10;++++/// A File ▸ Scripts ▸ Recent Script Files entry, stored as the `file.runScript` parameter that++/// ran it: `{"path": …}` for a script file, `{"name": …}` for an installed or bundled script.++#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]++#[serde(rename_all = "camelCase")]++pub enum RecentScript {++ Path(String),++ Name(String),++}++++impl RecentScript {++ /// The file's path or the script's name.++ pub fn text(&self) -> &str {++ match self {++ RecentScript::Path(s) | RecentScript::Name(s) => s,++ }++ }+ }++ /// Most effects Effects & Presets keeps starred (a hand-edited settings file can hold more).+ pub(super) const MAX_EFFECTS_FAVORITES: usize = 1000;++ fn push_mru(list: &mut Vec<String>, v: &str, max: usize) {+ list.retain(|x| x != v);+ list.insert(0, v.to_string());+ list.truncate(max.max(1));+ }diff --cc crates/ui-egui/src/menus/bar.rsindex 000000000,1a7f6e2a3..ee4598828mode 000000,100644..100644--- a/crates/ui-egui/src/menus/bar.rs+++ b/crates/ui-egui/src/menus/bar.rs@@@ -1,0 -1,289 +1,290 @@@+ use super::entries::{entry_checked, entry_enabled, entry_label, entry_shortcut, menu_choice};+ use super::invoke::invoke;+ use super::shortcuts::shortcut_text;+ use super::*;++ /// The id under which [`menu_bar`] remembers which of its menus was open at the end of the last+ /// frame (its title's open look, and the hover that switches between the titles).+ fn open_menu_id() -> egui::Id {+ egui::Id::unique("menu-bar-open")+ }++ /// The id under which [`menu_bar`] remembers a title press still in progress (press-and-browse).+ fn browse_menu_id() -> egui::Id {+ egui::Id::unique("menu-bar-browse")+ }++ /// Draw the in-window menu bar (the engine's AE menu tree).+ ///+ /// The titles open on the press, not the release (native menu bars): while one is held the menus+ /// can be browsed by moving onto them, and releasing over an entry chooses it. Hovering another+ /// title switches the open menu to it, and the open one closes on a press outside it or when the+ /// window loses focus. The pointer leaving the window — onto the OS title bar, directly above the+ /// bar — closes nothing, however long: the platform forwards none of the title bar's clicks to+ /// egui (only the cursor leaving), so there is no click to close on and a graze must not drop the+ /// menu. The closing press itself still reaches the widget under it, as a click does in After+ /// Effects.+ pub fn menu_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui) {+ let ctx = ui.ctx().clone();+ let mut clicked: Option<(String, Value)> = None;+ let mut nav = crate::menu_keys::Nav::default();+ // The open menu as of the last frame: the titles are drawn before this frame can open or+ // close anything, and what happened last frame is what they must react to.+ let open_prev: Option<usize> = ctx.data(|d| d.get_temp(open_menu_id())).flatten();+ if ctx.data(|d| d.get_temp(browse_menu_id())).unwrap_or(false) {+ nav.set_browsing();+ }+ let mut drawn = 0;+ ui.horizontal_centered(|ui| {+ ui.add_space(6.0);+ egui::MenuBar::new().config(egui::containers::menu::MenuConfig::new().style(crate::widgets::menu_style)).ui(ui, |ui| {+ for node in effectcraft_engine::menus::menu_bar() {+ let MenuNode::Submenu { label, children } = node else { continue };+ // The open title takes the open button's look while its menu is up (as in AE).+ let inactive = ui.style().visuals.widgets.inactive;+ if open_prev == Some(drawn) {+ ui.style_mut().visuals.widgets.inactive = ui.style().visuals.widgets.open;+ }+ let mut response = ui.add(egui::Button::new(crate::i18n::label(app, "", label)));+ ui.style_mut().visuals.widgets.inactive = inactive;+ // A press on a title opens its menu at once (a second press on the open one closes+ // it), and while it is held the menus below are browsable. The keyboard and the+ // accessibility activation report `clicked` without the primary button (the press+ // then happened somewhere else), and toggle the menu. Hovering another title+ // switches to it once the pointer has moved: merely resting there must not take a+ // keyboard-driven menu over.+ let moved = ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO);+ // With the button down elsewhere nothing is hovered, so the title under the+ // pointer takes the highlight by hand: the hover-switch to it shows, one frame+ // later like egui's own hover (the open title keeps its open look).+ if moved && response.contains_pointer() && open_prev.is_some_and(|p| p != drawn) {+ response = response.highlight();+ }+ let pressed = ctx.input(|i| i.pointer.button_pressed(egui::PointerButton::Primary)) && response.hovered();+ let cmd = if pressed {+ nav.set_browsing();+ Some(egui::SetOpenCommand::Bool(open_prev != Some(drawn)))+ } else if response.clicked() && !response.clicked_by(egui::PointerButton::Primary) {+ Some(egui::SetOpenCommand::Toggle)+ } else if moved && response.enabled() && response.contains_pointer() && open_prev.is_some_and(|p| p != drawn) {+ Some(egui::SetOpenCommand::Bool(true))+ } else {+ None+ };+ let inner = egui::Popup::menu(&response)+ .close_behavior(egui::PopupCloseBehavior::IgnoreClicks)+ .style(crate::widgets::menu_style)+ .open_memory(cmd)+ .show(|ui| {+ ui.set_min_width(if label == "Effect" { 200.0 } else { 280.0 });+ let browsing = nav.browsing();+ crate::widgets::menu_scroll(ui, browsing, |ui| menu_nodes(app, ui, children, &mut clicked, &mut nav, 0));+ });+ nav.top(&response);+ // The titles and the open menus: a press inside them is not an outside press.+ nav.cover(response.rect);+ if let Some(inner) = &inner {+ nav.cover(inner.response.rect);+ }+ app.auto.add(&format!("menu.{label}"), response.rect, label);+ drawn += 1;+ }+ });+ });+ crate::menu_keys::handle(&ctx, &nav);+ // egui leaves the closing to us (`IgnoreClicks`), so the menus close here: at once on a press+ // outside them (the press itself still reaches the widget below) and when the window loses+ // focus. The pointer leaving the window closes nothing: moving onto the OS title bar fires+ // the cursor-left event and the platform forwards none of its clicks to egui, so there is no+ // click to close on — and a graze or a stay must not drop the menu, as in native apps.+ if let Some(top) = nav.open_popup(&ctx) {+ let focus_lost = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(false))));+ let outside_press = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !nav.covers(p)));+ if focus_lost || outside_press {+ egui::Popup::close_id(&ctx, top);+ }+ }+ if let Some((id, params)) = clicked.map(|(id, params)| menu_choice(app, id, params))+ && let Err(e) = invoke(app, &ctx, &id, if params.is_null() { json!({}) } else { params })+ {+ app.ui.status = e;+ }+ // What the next frame starts from: the open title, and a title press still in progress.+ let open = nav.open_index(&ctx);+ let browsing = open.is_some() && nav.browsing() && ctx.input(|i| i.pointer.primary_down());+ ctx.data_mut(|d| {+ d.insert_temp(open_menu_id(), open);+ d.insert_temp(browse_menu_id(), browsing);+ });+ }++ /// The entries of top-level menu `name` (the Effect menu is the Effect Controls panel's context+ /// menu); returns the chosen command and its params.+ pub(crate) fn menu_contents(app: &mut EffectcraftApp, ui: &mut egui::Ui, name: &str) -> Option<(String, Value)> {+ let mut clicked = None;+ if let Some(MenuNode::Submenu { children, .. }) =+ effectcraft_engine::menus::menu_bar().iter().find(|n| matches!(n, MenuNode::Submenu { label, .. } if label == name))+ {+ menu_nodes(app, ui, children, &mut clicked, &mut crate::menu_keys::Nav::default(), 0);+ }+ clicked.map(|(id, params)| (id, if params.is_null() { json!({}) } else { params }))+ }++ /// The entries `nodes` of a menu `depth` submenus deep, registered with `nav` for the keyboard.+ fn menu_nodes(+ app: &mut EffectcraftApp,+ ui: &mut egui::Ui,+ nodes: &[MenuNode],+ clicked: &mut Option<(String, Value)>,+ nav: &mut crate::menu_keys::Nav,+ depth: usize,+ ) {+ for n in nodes {+ match n {+ MenuNode::Separator => {+ ui.separator();+ }+ MenuNode::Dynamic { name } => {+ // Recent projects / footage / presets, undo history, shortcut slots, viewers,+ // saved workspaces.+ let ws = app.ui.workspace.clone();+ let saved = app.saved_workspace_names();+ let (entries, empty) = effectcraft_engine::menus::dynamic(&app.session, name, &dyn_ctx(&ws, &saved));+ if entries.is_empty()+ && let Some(e) = empty+ {+ ui.add_enabled(false, egui::Button::new((gutter(false), e)));+ }+ for (i, e) in entries.iter().enumerate() {+ let tip = match name.as_str() {+ "recentProjects" => app.session.prefs.recent_projects.get(i).cloned(),+ "recentFootage" => app.session.prefs.recent_footage.get(i).cloned(),+ "recentPresets" => app.session.prefs.recent_presets.get(i).cloned(),++ "recentScripts" => app.session.prefs.recent_scripts.get(i).map(|r| r.text().to_string()),+ _ => None,+ };+ let r = ui.add_enabled(entry_enabled(app, e), egui::Button::new((gutter(entry_checked(app, e) == Some(true)), e.label.as_str())));+ let r = match &tip {+ Some(t) => r.on_hover_text(t),+ None => r,+ };+ let r = browse_hover(nav, r);+ app.auto.add(&format!("menu.{name}.{i}"), r.rect, &e.label);+ nav.entry(ui, depth, &r, false);+ if r.clicked() || browse_pick(nav, ui, &r) {+ *clicked = Some((e.command.clone(), e.params.clone()));+ ui.close();+ }+ }+ }+ MenuNode::Submenu { label, children } => {+ let ws = app.ui.workspace.clone();+ // The generated Effect menu's category submenus draw the catalog's name (#821);+ // every other submenu goes through the menu catalog.+ let shown = crate::i18n::effect_category(children, label)+ .unwrap_or_else(|| crate::i18n::submenu(app, label, effectcraft_engine::menus::submenu_label(&app.session, label, &dyn_ctx(&ws, &[]))));+ let browsing = nav.browsing();+ let egui::InnerResponse { inner, response } = ui.menu_button((gutter(false), shown.as_str()), |ui| {+ ui.set_min_width(if children.len() > 30 { 200.0 } else { 240.0 });+ crate::widgets::menu_scroll(ui, browsing, |ui| menu_nodes(app, ui, children, clicked, nav, depth + 1));+ });+ let response = browse_hover(nav, response);+ nav.entry(ui, depth, &response, true);+ if inner.is_some() {+ // `ui.menu_button` drops the popup's own response on the floor: read it back,+ // so that a press inside this submenu doesn't count as an outside press.+ let sub = egui::containers::menu::SubMenu::id_from_widget_id(response.id);+ if let Some(resp) = ui.ctx().read_response(sub) {+ nav.cover(resp.rect);+ }+ nav.opened(depth, &response);+ }+ }+ MenuNode::Item(e) => {+ let r = browse_hover(nav, menu_entry(app, ui, e));+ nav.entry(ui, depth, &r, false);+ if r.clicked() || browse_pick(nav, ui, &r) {+ *clicked = Some((e.command.clone(), e.params.clone()));+ ui.close();+ }+ }+ }+ }+ }++ /// The row `r` highlighted while the bar is mid press-and-browse: with a button down egui reports+ /// nothing as hovered — which would leave browsing with no hover feedback at all — so the row+ /// under the pointer takes the highlight by hand. It reads as the hover look one frame later,+ /// exactly egui's own hover latency; disabled rows ignore it (`Noninteractive`), as in native+ /// menus. Context menus use their own [`crate::menu_keys::Nav`], where the bar never browses.+ fn browse_hover(nav: &crate::menu_keys::Nav, r: egui::Response) -> egui::Response {+ if nav.browsing() && r.contains_pointer() { r.highlight() } else { r }+ }++ /// Whether a press-and-browse (a menu-bar title still held down) releases over entry `r`, which+ /// then chooses it like a click does. egui reports neither for it: the release is far from the+ /// press, so there is no click, and nothing but the pressed widget is hovered while a button is+ /// down, so the row has to be tested by the pointer being over it.+ fn browse_pick(nav: &crate::menu_keys::Nav, ui: &egui::Ui, r: &egui::Response) -> bool {+ nav.browsing() && r.enabled() && r.contains_pointer() && ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary))+ }++ /// The menu bar's submenu at `path` (`["File", "Interpret Footage"]`) in a panel's context menu,+ /// with the menu bar's labels, shortcuts and enabled state; a chosen entry goes to `clicked`.+ pub(crate) fn submenu_at(app: &mut EffectcraftApp, ui: &mut egui::Ui, path: &[&str], clicked: &mut Option<(String, Value)>) {+ let mut nodes = effectcraft_engine::menus::menu_bar();+ let mut found = None;+ for label in path {+ let Some(n) = nodes.iter().find(|n| matches!(n, MenuNode::Submenu { label: l, .. } if l == label)) else { return };+ if let MenuNode::Submenu { children, .. } = n {+ nodes = children;+ }+ found = Some(n);+ }+ if let Some(n) = found {+ menu_nodes(app, ui, std::slice::from_ref(n), clicked, &mut crate::menu_keys::Nav::default(), 0);+ }+ if let Some((_, p)) = clicked.as_mut()+ && p.is_null()+ {+ *p = json!({});+ }+ }++ /// The menu bar's entry for `command` in a panel's context menu (see [`submenu_at`]).+ pub(crate) fn entry_for(app: &EffectcraftApp, ui: &mut egui::Ui, command: &str, clicked: &mut Option<(String, Value)>) {+ if let Some((_, e)) = effectcraft_engine::menus::entries().into_iter().find(|(_, e)| e.command == command)+ && menu_entry(app, ui, e).clicked()+ {+ *clicked = Some((e.command.clone(), e.params_or_empty()));+ ui.close();+ }+ }++ /// Frontend state for dynamic menus (the current workspace and the saved ones).+ pub(crate) fn dyn_ctx<'a>(workspace: &'a str, saved_workspaces: &'a [String]) -> effectcraft_engine::menus::DynCtx<'a> {+ effectcraft_engine::menus::DynCtx { workspace: Some(workspace), saved_workspaces }+ }++ /// The check-mark column every menu row reserves (like macOS / After Effects menus).+ fn gutter(checked: bool) -> egui::Atom<'static> {+ use egui::AtomExt;+ (if checked { "✔" } else { "" }).atom_size(egui::vec2(14.0, 14.0))+ }++ fn menu_entry(app: &EffectcraftApp, ui: &mut egui::Ui, e: &MenuEntry) -> egui::Response {+ let (label, check, enabled) = (entry_label(app, e), gutter(entry_checked(app, e) == Some(true)), entry_enabled(app, e));+ // Edit ▸ Label's entries show the label's colour before its name.+ if e.command == "edit.label"+ && let Some(l) = e.params.get("label").and_then(Value::as_str).and_then(effectcraft_engine::color::Label::from_name)+ {+ let out = ui.add_enabled_ui(enabled, |ui| egui::Button::new((check, crate::widgets::label_swatch(), label)).atom_ui(ui)).inner;+ crate::widgets::paint_label_swatch(ui, &out, l, &app.tokens);+ return out.response;+ }+ let mut b = egui::Button::new((check, label));+ if let Some(s) = entry_shortcut(app, e) {+ b = b.shortcut_text(shortcut_text(&s));+ }+ ui.add_enabled(enabled, b)+ }diff --cc crates/ui-egui/src/menus/frontend.rsindex 000000000,d808b4620..442fe7137mode 000000,100644..100644--- a/crates/ui-egui/src/menus/frontend.rs+++ b/crates/ui-egui/src/menus/frontend.rs@@@ -1,0 -1,684 +1,684 @@@+ 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 {+ let st = &s.state;+ 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));+ }+ 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.runScript" if params.get("name").is_none() && params.get("recent").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+ }diff --cc crates/ui-egui/src/menus/tests.rsindex 000000000,6c125d178..ed2fcf6camode 000000,100644..100644--- a/crates/ui-egui/src/menus/tests.rs+++ b/crates/ui-egui/src/menus/tests.rs@@@ -1,0 -1,406 +1,425 @@@+ use super::*;++ /// #882: at 125 % / 150 % display scaling Zoom In reaches 100 % (one comp pixel per screen+ /// pixel), not 100 % in points (125 % / 150 % on screen).+ #[test]+ fn zoom_steps_land_on_whole_screen_magnifications() {+ for ppp in [1.0f32, 1.25, 1.5, 2.0] {+ let at_100 = zoom_step(0.7 / ppp, ppp, true);+ assert!((at_100 * ppp - 1.0).abs() < 1e-6, "ppp {ppp}: {}", at_100 * ppp);+ assert!((zoom_step(at_100, ppp, true) * ppp - 1.5).abs() < 1e-6);+ assert!((zoom_step(at_100, ppp, false) * ppp - 0.66).abs() < 1e-6);+ }+ assert!(zoom_step(1.0, 0.0, true).is_finite());+ }++ #[test]+ fn shortcut_passes_share_frame_start_modifiers() {+ let ctx = egui::Context::default();+ let mut starts = Vec::new();+ let mut output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT)], ..Default::default() }, |ui| {+ let ctx = ui.ctx();+ starts.push(modifiers_at_start(ctx));+ starts.push(modifiers_at_start(ctx));+ });+ output.textures_delta.clear();+ assert_eq!(starts, vec![None, None]);+ starts.clear();+ let mut output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)], ..Default::default() }, |ui| {+ let ctx = ui.ctx();+ starts.push(modifiers_at_start(ctx));+ starts.push(modifiers_at_start(ctx));+ });+ output.textures_delta.clear();+ assert_eq!(starts, vec![Some(egui::Modifiers::SHIFT), Some(egui::Modifiers::SHIFT)]);+ }++ #[test]+ fn every_ui_shortcut_parses() {+ for c in UI_COMMANDS {+ if let Some(sc) = c.shortcut {+ assert!(parse_shortcut(sc).is_some() || sc == "Num*", "{sc}");+ }+ }+ for (_, e) in effectcraft_engine::menus::entries() {+ if let Some(sc) = &e.shortcut {+ assert!(parse_shortcut(sc).is_some() || sc == "Num*", "{} ({sc})", e.label);+ }+ }+ }++ #[test]+ fn full_screen_default_is_platform_specific() {+ let app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let full_screen = app.session.shortcuts().shortcut_of("view.fullScreen", &Value::Null);+ if cfg!(target_os = "macos") {+ assert_eq!(full_screen, Some("Ctrl+Cmd+F"));+ } else {+ assert_eq!(full_screen, None);+ assert_eq!(app.session.shortcuts().shortcut_of("window.maximizeApp", &Value::Null), Some("Cmd+\\"));+ }+ }++ #[test]+ fn ui_and_menu_shortcuts_do_not_collide() {+ let app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let mut seen: std::collections::BTreeMap<(String, String), (String, String)> = Default::default();+ for (m, k, id, params) in bindings(&app.session) {+ let key = (format!("{m:?}"), format!("{k:?}"));+ let target = (id.clone(), params.to_string());+ if let Some(prev) = seen.get(&key) {+ assert_eq!(prev, &target, "{key:?} bound to {prev:?} and {target:?}");+ } else {+ seen.insert(key, target);+ }+ }+ }++ /// #336: Ctrl+\ (Cmd+\ on macOS) maximizes the application window, and again restores+ /// it, as in After Effects.+ #[test]+ fn ctrl_backslash_maximizes_or_restores_the_window() {+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let (m, k) = parse_shortcut("Cmd+\\").unwrap();+ assert!(m.command && k == egui::Key::Backslash, "{m:?} {k:?}");+ assert!(bindings(&app.session).iter().any(|b| (b.0, b.1) == (m, k) && b.2 == "window.maximizeApp"));+ let ctx = egui::Context::default();+ let run = |app: &mut EffectcraftApp, maximized: bool| {+ let input = egui::RawInput {+ viewports: std::iter::once((egui::ViewportId::ROOT, egui::ViewportInfo { maximized: Some(maximized), ..Default::default() })).collect(),+ ..Default::default()+ };+ let mut r = Value::Null;+ let mut out = ctx.run_ui(input, |ui| r = invoke(app, ui.ctx(), "window.maximizeApp", json!({})).unwrap());+ out.textures_delta.clear();+ let cmds = out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default();+ (r, cmds)+ };+ let (r, cmds) = run(&mut app, false);+ assert_eq!(r, json!({"maximized": true}));+ assert!(cmds.contains(&egui::ViewportCommand::Maximized(true)), "{cmds:?}");+ let (r, cmds) = run(&mut app, true);+ assert_eq!(r, json!({"maximized": false}));+ assert!(cmds.contains(&egui::ViewportCommand::Maximized(false)), "{cmds:?}");+ }++ /// The default keys of the keyboard-only commands parse and reach them.+ #[test]+ fn keyboard_only_commands_are_bound() {+ let app = EffectcraftApp::new(effectcraft_engine::Session::default());+ for (id, keys) in [+ ("time.workAreaStart", "Shift+Home"),+ ("time.workAreaEnd", "Shift+End"),+ ("time.previousInOut", "Cmd+Alt+Shift+ArrowLeft"),+ ("time.nextInOut", "Cmd+Alt+Shift+ArrowRight"),+ ("comp.workAreaToSelection", "Cmd+Alt+B"),+ ("comp.activateRecent", "Shift+Escape"),+ ("keys.deselectAll", "Shift+F2"),+ ("keys.deselectAll", "Cmd+Alt+Shift+A"),+ ("layer.extendSelectionNext", "Cmd+Shift+ArrowDown"),+ ("layer.moveInToStart", "Alt+Home"),+ ("layer.moveEarlier", "Alt+PageUp"),+ ("layer.moveLater10", "Alt+Shift+PageDown"),+ ("layer.stretchInToTime", "Cmd+Shift+,"),+ ("layer.stretchOutToTime", "Cmd+Alt+,"),+ ("layer.mask.selectNext", "Alt+`"),+ ("layer.mask.selectPrevious", "Alt+Shift+`"),+ ("layer.castsShadows", "Alt+Shift+C"),+ ("timeline.scrollToTime", "D"),+ ("timeline.scrollToLayer", "X"),+ ("timeline.parentColumn", "Shift+F4"),+ ("view.fitUpTo100", "Alt+/"),+ ("view.nextItem", "Shift+."),+ ("view.previousItem", "Shift+,"),+ ("window.toggleCompTimeline", "\\"),+ ("window.nextPanel", "Alt+Shift+."),+ ("window.previousPanel", "Alt+Shift+,"),+ ("window.closeAll", "Cmd+Shift+W"),+ ("tool.camera", "C"),+ ] {+ assert!(bindings(&app.session).into_iter().any(|x| x.2 == id && Some((x.0, x.1)) == parse_shortcut(keys)), "{id} on {keys}");+ }+ }++ #[test]+ fn timeline_keys_scroll_and_toggle_the_parent_column() {+ let ctx = egui::Context::default();+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let run = |app: &mut EffectcraftApp, id: &str| invoke(app, &ctx, id, json!({})).unwrap();+ // D and X leave a scroll for the Timeline to do when it is drawn.+ run(&mut app, "timeline.scrollToTime");+ assert_eq!(app.ui.timeline.scroll_to, Some(crate::state::ScrollTo::Time));+ run(&mut app, "timeline.scrollToLayer");+ assert_eq!(app.ui.timeline.scroll_to, Some(crate::state::ScrollTo::Layer));+ // Shift+F4 shows and hides the Parent column.+ let parent = crate::panels::timeline::column_visible(&app.ui.timeline, "parent");+ run(&mut app, "timeline.parentColumn");+ assert_eq!(crate::panels::timeline::column_visible(&app.ui.timeline, "parent"), !parent);+ run(&mut app, "timeline.parentColumn");+ assert_eq!(crate::panels::timeline::column_visible(&app.ui.timeline, "parent"), parent);+ }++ #[test]+ fn viewer_keys_fit_and_step_through_open_comps() {+ let ctx = egui::Context::default();+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let run = |app: &mut EffectcraftApp, id: &str| invoke(app, &ctx, id, json!({})).unwrap();+ let new = |app: &mut EffectcraftApp, name: &str| app.session.execute("comp.new", json!({"name": name, "duration": 4})).unwrap()["comp"].as_u64();+ let active = |app: &EffectcraftApp| app.session.state.active_comp.map(|c| c.0);+ // With one composition open there is nothing to step to.+ let a = new(&mut app, "A");+ run(&mut app, "view.nextItem");+ assert_eq!(active(&app), a);+ // Shift+, / Shift+.: through the open compositions, wrapping.+ let b = new(&mut app, "B");+ assert_eq!(active(&app), b);+ run(&mut app, "view.nextItem");+ assert_eq!(active(&app), a);+ run(&mut app, "view.previousItem");+ assert_eq!(active(&app), b);+ // Alt+/ fits the viewer without magnifying past 100 %; Shift+/ fits fully again.+ app.ui.viewer.zoom = Some(3.0);+ run(&mut app, "view.fitUpTo100");+ assert!(app.ui.viewer.zoom.is_none() && app.ui.viewer.fit_up_to_100);+ run(&mut app, "view.fit");+ assert!(!app.ui.viewer.fit_up_to_100);+ }++ #[test]+ fn panel_keys_switch_cycle_and_close() {+ let ctx = egui::Context::default();+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let run = |app: &mut EffectcraftApp, id: &str| invoke(app, &ctx, id, json!({})).unwrap();+ for name in ["A", "B"] {+ app.session.execute("comp.new", json!({"name": name, "duration": 4})).unwrap();+ }+ // \\ switches between the Timeline and the Composition viewer.+ app.ui.focused = PanelKind::Timeline;+ run(&mut app, "window.toggleCompTimeline");+ assert_eq!(app.ui.focused, PanelKind::Composition);+ run(&mut app, "window.toggleCompTimeline");+ assert_eq!(app.ui.focused, PanelKind::Timeline);+ // Alt+Shift+. / Alt+Shift+,: the tabs of the focused panel's group, wrapping.+ let group = app.ui.dock.group_of(PanelKind::Timeline);+ assert!(group.len() > 1, "{group:?}");+ run(&mut app, "window.nextPanel");+ assert_eq!(app.ui.focused, group[(group.iter().position(|p| *p == PanelKind::Timeline).unwrap() + 1) % group.len()]);+ run(&mut app, "window.previousPanel");+ assert_eq!(app.ui.focused, PanelKind::Timeline);+ // Ctrl+Shift+W with the Timeline active closes every composition.+ run(&mut app, "window.closeAll");+ assert!(app.session.state.open_comps.is_empty());+ // With another panel active it closes that panel.+ app.show_panel(PanelKind::Project);+ run(&mut app, "window.closeAll");+ assert!(!app.ui.dock.is_open(PanelKind::Project));+ }++ #[test]+ fn c_cycles_the_camera_tools() {+ let ctx = egui::Context::default();+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ app.ui.tool = Tool::Selection;+ let mut seen = vec![];+ for _ in 0..4 {+ invoke(&mut app, &ctx, "tool.camera", json!({})).unwrap();+ seen.push(app.ui.tool);+ }+ assert_eq!(seen, [Tool::Orbit, Tool::PanCamera, Tool::Dolly, Tool::Orbit]);+ }++ #[test]+ fn dispatch_uses_the_active_custom_preset() {+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let find = |app: &EffectcraftApp, id: &str| bindings(&app.session).into_iter().filter(|b| b.2 == id).map(|b| (b.0, b.1)).collect::<Vec<_>>();+ let (m, k) = parse_shortcut("Cmd+Alt+Shift+Y").unwrap();+ assert!(find(&app, "layer.newNull").contains(&(m, k)));+ // A UI command rebound in a custom preset.+ app.session.execute("shortcuts.set", json!({"command": "tool.hand", "keys": "Ctrl+Alt+H"})).unwrap();+ assert_eq!(app.session.keymaps.active, "Custom");+ let (m2, k2) = parse_shortcut("Ctrl+Alt+H").unwrap();+ assert_eq!(find(&app, "tool.hand"), vec![(m2, k2)]);+ app.session.execute("shortcuts.set", json!({"command": "layer.newNull", "keys": "F6"})).unwrap();+ assert_eq!(find(&app, "layer.newNull"), vec![(egui::Modifiers::NONE, egui::Key::F6)]);+ // The menus show the preset's shortcut.+ let item = menu_items(&app).into_iter().find(|i| i.id == "layer.newNull").unwrap();+ assert_eq!(item.shortcut.as_deref(), Some("F6"));+ // Back to the default preset.+ app.session.execute("shortcuts.preset", json!({"op": "select", "name": effectcraft_engine::shortcuts::DEFAULT_PRESET})).unwrap();+ assert!(find(&app, "layer.newNull").contains(&(m, k)));+ }++ #[test]+ fn renamed_label_shows_in_the_label_menu() {+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ app.set_pref("labels.1.name", json!("Sunflower")).unwrap();+ let labels: Vec<String> = menu_items(&app).into_iter().filter(|i| i.id == "edit.label").map(|i| i.label).collect();+ assert!(labels.contains(&"Sunflower".to_string()), "{labels:?}");+ assert!(!labels.contains(&"Yellow".to_string()));+ }++ /// Saving anything but a project asks the save dialog for that file's extension (#293): the+ /// project dialog, filtered to `.ecproj`, made macOS append `.ecproj` (`Frame.png.ecproj`).+ /// Hosts with only the project dialog (the web) still get it, given the file name.+ #[test]+ fn save_dialogs_offer_the_file_extension() {+ use std::cell::RefCell;+ use std::rc::Rc;+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ app.session.execute("comp.new", json!({"name": "A", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();+ let ctx = egui::Context::default();+ let asked: Rc<RefCell<Vec<String>>> = Rc::default();+ let (a, b) = (asked.clone(), asked.clone());+ app.hooks.pick_save = Some(Box::new(move |name: &str| {+ a.borrow_mut().push(format!("project {name}"));+ None+ }));+ app.hooks.pick_save_file = Some(Box::new(move |name: &str, ext: &str| {+ b.borrow_mut().push(format!("file {name} [{ext}]"));+ None+ }));+ for id in ["comp.saveFrameAs", "render.saveCurrentPreview", "file.exportLottie", "file.saveCopyAsXml", "file.collectFiles", "file.saveAs"] {+ invoke(&mut app, &ctx, id, json!({})).unwrap();+ }+ assert_eq!(+ *asked.borrow(),+ [+ "file Frame.png [png]",+ "file Preview.mp4 [mp4]",+ "file Animation.json [json]",+ "file Untitled Project.ecprojx [ecprojx]",+ "file Collected Files []",+ "project Untitled Project.ecproj",+ ]+ );+ // Without the other dialog, the project one names any file.+ app.hooks.pick_save_file = None;+ asked.borrow_mut().clear();+ invoke(&mut app, &ctx, "comp.saveFrameAs", json!({})).unwrap();+ assert_eq!(*asked.borrow(), ["project Frame.png"]);+ }+++/// File ▸ Scripts ▸ Recent Script Files and its key run a script again without a file dialog.++#[test]++fn recent_script_files_run_without_a_dialog() {++ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());++ let ctx = egui::Context::default();++ let dir = std::env::temp_dir().join(format!("ec-recent-script-{}", std::process::id()));++ std::fs::create_dir_all(&dir).unwrap();++ let script = dir.join("New Comp.jsonl");++ std::fs::write(&script, r#"{"command": "comp.new", "params": {"name": "From Script", "width": 64, "height": 36, "frameRate": 30, "duration": 1}}"#)++ .unwrap();++ app.session.execute("file.runScript", json!({"path": script.to_string_lossy()})).unwrap();++ let (m, k, id, params) =++ bindings(&app.session).into_iter().find(|b| b.2 == "file.runScript" && b.3 == json!({"recent": 0})).expect("the most recent script has a key");++ assert_eq!((m, k), parse_shortcut("Cmd+Alt+Shift+D").unwrap());++ assert_eq!(invoke(&mut app, &ctx, &id, params).unwrap()["steps"], 1);++ assert_eq!(app.session.project.items.values().filter(|i| i.name.starts_with("From Script")).count(), 2);++ let _ = std::fs::remove_dir_all(&dir);++}+++ /// #511: with a host's non-blocking dialogs, a command's file dialog opens without running+ /// a nested event loop inside the frame (a drag over the window then aborted the app on+ /// macOS); the command runs on a later frame with the answer, and a cancelled one not at all.+ #[test]+ fn file_dialogs_can_answer_on_a_later_frame() {+ use std::sync::{Arc, Mutex};+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ app.session.execute("comp.new", json!({"name": "A", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();+ let ctx = egui::Context::default();+ app.hooks.pick_save = Some(Box::new(|_: &str| panic!("the blocking dialog is not used")));+ let pending: Arc<Mutex<Vec<(crate::FileDialog, crate::DialogDone)>>> = Arc::default();+ let queue = pending.clone();+ app.hooks.file_dialog_async = Some(Box::new(move |dialog, done| queue.lock().unwrap().push((dialog, done))));+ assert_eq!(invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap(), json!({"dialog": "file.saveAs"}));+ let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");+ assert_eq!(dialog, crate::FileDialog::Save { default: "Untitled Project.ecproj".into(), ext: "ecproj".into(), project: true });+ assert!(app.session.path.is_none(), "nothing saved until the dialog answers");+ let dir = std::env::temp_dir().join(format!("ec-dialog-answer-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("Answered.ecproj");+ // Answered from another thread, as the host's dialog does.+ std::thread::spawn(move || done(vec![path.to_string_lossy().to_string()])).join().unwrap();+ app.run_dialog_answers();+ assert_eq!(app.session.path.as_deref(), Some(dir.join("Answered.ecproj").to_string_lossy().as_ref()));+ assert!(dir.join("Answered.ecproj").is_file());+ // Cancelled: nothing runs.+ invoke(&mut app, &ctx, "comp.saveFrameAs", json!({})).unwrap();+ let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");+ assert_eq!(dialog, crate::FileDialog::Save { default: "Frame.png".into(), ext: "png".into(), project: false });+ done(Vec::new());+ app.run_dialog_answers();+ assert!(!dir.join("Frame.png").exists());+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// While a command's OS file dialog is up, floating panels' OS windows are blocked, as for+ /// a modal dialog; a dialog that ends, answered or not, unblocks them, and Save As opens a+ /// dialog again. A macOS sheet can end without answering (its window went away): once one of+ /// the app's windows has the keyboard again, or keeps it as if no dialog showed, floating+ /// windows are not left blocked.+ #[test]+ fn file_dialogs_block_floating_windows_only_while_up() {+ use std::sync::{Arc, Mutex};+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let ctx = egui::Context::default();+ let pending: Arc<Mutex<Vec<crate::DialogDone>>> = Arc::default();+ let queue = pending.clone();+ app.hooks.file_dialog_async = Some(Box::new(move |_dialog, done| queue.lock().unwrap().push(done)));+ let blocked = |app: &mut EffectcraftApp, focused: bool, time: f64| {+ let input = egui::RawInput { focused, time: Some(time), ..Default::default() };+ let mut out = false;+ ctx.run_ui(input, |ui| out = app.floats_blocked(ui.ctx())).textures_delta.clear();+ out+ };+ assert!(!blocked(&mut app, true, 0.0));+ // Cancelled.+ invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();+ assert!(blocked(&mut app, true, 0.1), "blocked while the dialog takes the keyboard");+ assert!(blocked(&mut app, false, 0.2));+ let done = pending.lock().unwrap().pop().expect("a dialog was shown");+ done(Vec::new());+ app.run_dialog_answers();+ assert!(!blocked(&mut app, false, 0.3));+ // Save As asks again; the sheet ends without answering.+ invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();+ assert_eq!(pending.lock().unwrap().len(), 1, "Save As opens a dialog again");+ assert!(blocked(&mut app, true, 1.0));+ assert!(blocked(&mut app, false, 1.1));+ assert!(blocked(&mut app, false, 9.0), "a dialog may stay up for long");+ assert!(!blocked(&mut app, true, 9.1), "an app window has the keyboard again");+ // A dialog that never takes the keyboard.+ invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();+ assert!(blocked(&mut app, true, 10.0));+ assert!(blocked(&mut app, true, 11.0));+ assert!(!blocked(&mut app, true, 12.5));+ // Answers of dialogs taken for gone arrive late: nothing stays blocked.+ for done in pending.lock().unwrap().drain(..) {+ done(Vec::new());+ }+ app.run_dialog_answers();+ assert!(!blocked(&mut app, false, 13.0));+ invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();+ assert!(blocked(&mut app, false, 13.1), "a later dialog blocks again");+ }++ #[test]+ fn tga_is_available_in_import_replace_and_proxy_dialogs() {+ use std::sync::{Arc, Mutex};+ let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());+ let ctx = egui::Context::default();+ let pending = Arc::new(Mutex::new(Vec::new()));+ let queue = pending.clone();+ app.hooks.file_dialog_async = Some(Box::new(move |dialog, _done| queue.lock().unwrap().push(dialog)));+ for command in ["file.import", "file.importMultiple", "file.replaceFootage", "file.setProxy"] {+ assert_eq!(invoke(&mut app, &ctx, command, json!({})).unwrap(), json!({"dialog": command}));+ let crate::FileDialog::Open { exts, .. } = pending.lock().unwrap().pop().unwrap() else { panic!("not an open dialog") };+ assert!(exts.iter().any(|ext| ext == "tga"), "{command}: {exts:?}");+ }+ }++ #[test]+ fn menu_items_cover_the_tree() {+ assert_eq!(menus().last(), Some(&"Help"));+ assert!(effectcraft_engine::menus::entries().len() > 500);+ }