Skip to content

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

Merge pull request #844 from Ni-zav/fix/810-bounded-undo-group-s20261011T141200Z-fd2e

Brandon Thomasd6bd27db8f85
diff --cc crates/script/src/runtime.rs
index 225790c48,91c95ce7d..2683c25dd
--- a/crates/script/src/runtime.rs
+++ b/crates/script/src/runtime.rs
@@@ -63,12 -64,13 +64,13 @@@ impl Outcome
pub(crate) struct Active {
pub(crate) session: Session,
pub(crate) output: Vec<String>,
- /// Open undo groups: (name, project snapshot when the outermost group began).
- pub(crate) groups: Vec<(String, Arc<Project>)>,
+ /// Open groups: name, project snapshot, original bounded history and saved-project
+ /// identity. The history snapshot preserves earlier steps if long groups hit the limit.
+ pub(crate) groups: Vec<(String, Arc<Project>, History, Arc<Project>)>,
- /// `app.scheduleTask` queue: (id, code, repeat).
- pub(crate) tasks: Vec<(u32, String, bool)>,
- pub(crate) next_task: u32,
pub(crate) name: String,
+ /// The script context running (its `app.scheduleTask` tasks are kept under this id, see
+ /// [`crate::tasks`]).
+ pub(crate) host: u32,
/// Running on a script-host thread: modal dialogs hand the session back to the caller
/// through this link while they wait.
pub(crate) link: Option<crate::ui::Link>,
@@@ -257,21 -263,32 +265,33 @@@ fn native_undo(_: &JsValue, args: &[JsV
Ok(JsValue::undefined())
}
- /// Fold the undo steps recorded since the project was `snap` into one step called `name`.
- pub(crate) fn collapse(s: &mut Session, name: &str, snap: &Arc<Project>) {
+ /// Fold every command in a group into a single bounded-history entry, even if the
+ /// oldest intermediate undo state was trimmed before the group ended.
+ pub(crate) fn collapse(
+ s: &mut Session,
+ name: &str,
+ snap: &Arc<Project>,
+ prior: &History,
+ saved: &Arc<Project>,
+ ) {
let h = &mut s.history;
- let Some(start) = h.undo.iter().rposition(|(_, p)| Arc::ptr_eq(p, snap)) else {
- // Nothing was recorded (or history was reset by New / Open Project).
- return;
- };
- let first = h.undo[start].1.clone();
- h.undo.truncate(start);
- h.undo.push((name.to_string(), first));
- h.merge_key = None;
+ if let Some(start) = h.undo.iter().rposition(|(_, p)| Arc::ptr_eq(p, snap)) {
+ // The group is short enough that its opening snapshot is still in history.
+ let first = h.undo[start].1.clone();
+ h.undo.truncate(start);
+ h.undo.push((name.to_string(), first));
+ h.merge_key = None;
+ } else if !Arc::ptr_eq(&s.project, snap) && Arc::ptr_eq(&s.saved_project, saved) && !h.undo.is_empty() {
+ // The group exceeded Levels of Undo. Restore the pre-group history (including
+ // older steps and redo branches) and record one step for the *whole* group.
+ // A New / Open Project changes saved_project; never resurrect the old history.
+ *h = prior.clone();
+ h.record(name, snap.clone(), s.prefs.general.undo_levels.max(1) as usize);
+ }
}
-/// `__task("schedule", code, repeat)` → id; `__task("cancel", id)`.
+/// `__task("schedule", code, delayMs, repeat)` → id; `__task("cancel", id)` (see
+/// [`crate::tasks`]).
fn native_task(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let op = arg_string(args, 0, ctx)?;
if op == "cancel" {
diff --cc crates/script/src/tests.rs
index a8bed8a5d,b5819c116..34ac592fa
--- a/crates/script/src/tests.rs
+++ b/crates/script/src/tests.rs
@@@ -731,65 -731,24 +731,87 @@@ fn import_options_sequence_picks_one_st
let _ = std::fs::remove_dir_all(&dir);
}
+
+#[test]
+fn binary_file_io_preserves_all_byte_values() {
+ let dir = std::env::temp_dir().join(format!("ec-script-binary-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let src = dir.join("sig.bin");
+ let dst = dir.join("written.bin");
+ let copied = dir.join("copied.bin");
+ let original = [0x89u8, 0x50, 0x4e, 0x47, 0x00, 0x7f, 0x80, 0xff, 0x0a];
+ std::fs::write(&src, original).unwrap();
+ let mut s = session();
+ s.path = Some(dir.join("project.ecproj").to_string_lossy().to_string());
+ s.prefs.scripting.allow_scripts_write_files = true;
+ let q = |p: &std::path::Path| serde_json::to_string(&p.to_string_lossy()).unwrap();
+
+ let read = ok(&mut s, &format!(
+ "var f = new File({}); f.encoding = 'BINARY'; f.open('r'); var data = f.read(); f.close(); [data.length, data.charCodeAt(0), data.charCodeAt(6), data.charCodeAt(7)]",
+ q(&src)
+ ));
+ assert_eq!(read.result, json!([9, 0x89, 0x80, 0xff]));
+
+ ok(&mut s, &format!(
+ "var f = new File({}); f.encoding = 'BINARY'; f.open('w'); f.write(String.fromCharCode(0x89, 0x50, 0x4e, 0x47, 0, 127, 128, 255, 10)); f.close();",
+ q(&dst)
+ ));
+ assert_eq!(std::fs::read(&dst).unwrap(), original);
+
+ let copy = ok(&mut s, &format!("new File({}).copy({})", q(&src), q(&copied)));
+ assert_eq!(copy.result, json!(true));
+ assert_eq!(std::fs::read(&copied).unwrap(), original);
+
+ ok(&mut s, &format!(
+ "var f = new File({}); f.encoding = 'BINARY'; f.open('a'); f.write(String.fromCharCode(0xfe)); f.close();",
+ q(&dst)
+ ));
+ assert_eq!(std::fs::read(&dst).unwrap(), [original.as_slice(), &[0xfe]].concat());
+
+ let invalid = run_code(
+ &mut s,
+ &format!("var f = new File({}); f.encoding = 'BINARY'; f.open('w'); f.write(String.fromCharCode(0x100)); f.close();", q(&dst)),
+ "invalid-binary.jsx",
+ );
+ assert!(invalid.error.is_some(), "code points above 255 must not be truncated");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn script_undo_uses_stable_after_effects_command_id() {
+ let mut s = session();
+ let lookup = ok(&mut s, "app.findMenuCommandId('Undo')");
+ assert_eq!(lookup.result, json!(16));
+ // ID 16 used to index an unrelated command as the registry grew. It must
+ // undo the preceding layer creation rather than dispatching by position.
+ let r = ok(
+ &mut s,
+ "var c = app.project.items.addComp('Undo ID', 100, 100, 1, 1, 24); c.layers.addNull(); app.executeCommand(16); c.numLayers",
+ );
+ assert_eq!(r.result, json!(0));
+ assert_eq!(s.project.comp(ItemId(1)).unwrap().layers.len(), 0);
+ // Lookup of other command names still uses the existing registry.
+ assert!(ok(&mut s, "app.findMenuCommandId('New Project')").result.as_u64().unwrap_or(0) > 0);
+}
++
+ #[test]
+ fn long_script_undo_group_counts_as_one_level() {
+ let mut s = session();
+ s.prefs.general.undo_levels = 3;
+ ok(&mut s, "var c = app.project.items.addComp('Long Undo', 100, 100, 1, 1, 24); c.layers.addNull();");
+ assert_eq!(s.history.undo.len(), 2);
+ // More edits than the history cap must still be one undoable group.
+ ok(
+ &mut s,
+ "var c = app.project.item(1); app.beginUndoGroup('Forty layers'); for (var i = 0; i < 40; i++) c.layers.addNull(); app.endUndoGroup();",
+ );
+ assert_eq!(s.project.comp(ItemId(1)).unwrap().layers.len(), 41);
+ assert_eq!(s.history.undo.len(), 3);
+ assert_eq!(s.history.undo[2].0, "Forty layers");
+ s.undo();
+ assert_eq!(s.project.comp(ItemId(1)).unwrap().layers.len(), 1);
+ // Entries preceding the group remain available instead of being trimmed by
+ // the forty intermediate operations.
+ s.undo();
+ assert_eq!(s.project.comp(ItemId(1)).unwrap().layers.len(), 0);
+ }