GitCorner

Code

ossartcrafteffectcraft🌐
665bfac0b339
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"]);
}

/// #2788: Save As, Save a Copy (`<name> copy`) and Save a Copy As XML start from the open
/// project's name (in its folder), not Untitled Project.
#[test]
fn save_as_dialogs_start_from_the_open_project() {
    use std::cell::RefCell;
    use std::rc::Rc;
    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();
    let dir = std::env::temp_dir().join(format!("ec-save-as-name-{}", std::process::id()));
    let project = dir.join("Intro.ecproj");
    app.session.path = Some(project.to_string_lossy().to_string());
    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 ["file.saveAs", "file.saveCopy", "file.saveCopyAsXml"] {
        invoke(&mut app, &ctx, id, json!({})).unwrap();
    }
    let xml = dir.join("Intro.ecprojx").to_string_lossy().to_string();
    // Save a Copy names another file: it would refuse to write over the open project.
    assert_eq!(*asked.borrow(), ["project Intro.ecproj".to_string(), "project Intro copy.ecproj".into(), format!("file {xml} [ecprojx]")]);
    // An open XML project's XML copy is another file too.
    app.session.path = Some(dir.join("Intro.ecprojx").to_string_lossy().to_string());
    asked.borrow_mut().clear();
    invoke(&mut app, &ctx, "file.saveCopyAsXml", json!({})).unwrap();
    let copy = dir.join("Intro copy.ecprojx").to_string_lossy().to_string();
    assert_eq!(*asked.borrow(), [format!("file {copy} [ecprojx]")]);
    app.session.path = Some(project.to_string_lossy().to_string());
    // The non-blocking dialog gets the whole path, so it opens in the project's folder.
    let pending: Arc<Mutex<Vec<crate::FileDialog>>> = Arc::default();
    let queue = pending.clone();
    app.hooks.file_dialog_async = Some(Box::new(move |dialog, _done| queue.lock().unwrap().push(dialog)));
    invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();
    let dialog = pending.lock().unwrap().pop().expect("a dialog was shown");
    assert_eq!(dialog, crate::FileDialog::Save { default: project.to_string_lossy().to_string(), ext: "ecproj".into(), project: true });
}

/// 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(Ok(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(Ok(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(Ok(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(Ok(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");
}

/// While a native file dialog is up, the Edit menu is disabled on macOS so the OS hands Cmd+A
/// to the dialog instead of selecting in the Project panel behind it (#1986). Elsewhere the
/// menu stays as it was.
#[test]
fn edit_menu_is_disabled_while_a_file_dialog_is_open() {
    use std::sync::{Arc, Mutex};
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    app.session.execute("file.openDemoProject", json!({})).unwrap();
    app.ui.focused = PanelKind::Project;
    let ctx = egui::Context::default();
    let entries = effectcraft_engine::menus::entries();
    let select_all = entries.iter().map(|(_, e)| e).find(|e| e.command == "edit.selectAll").expect("Select All is in the menu");
    let import = entries.iter().map(|(_, e)| e).find(|e| e.command == "file.import").expect("Import is in the menu");
    assert!(entry_enabled(&app, select_all));
    let steps_aside = cfg!(target_os = "macos");
    let pending: Arc<Mutex<Vec<crate::DialogDone>>> = Arc::default();
    let queue = pending.clone();
    app.hooks.file_dialog_async = Some(Box::new(move |_, done| queue.lock().unwrap().push(done)));
    invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap();
    assert_eq!(!entry_enabled(&app, select_all), steps_aside, "Cmd+A must reach the dialog on macOS only");
    assert!(entry_enabled(&app, import), "only the Edit menu steps aside");
    // Cancelled: the menu is back.
    let done = pending.lock().unwrap().pop().expect("a dialog was shown");
    done(Ok(Vec::new()));
    app.run_dialog_answers();
    assert!(entry_enabled(&app, select_all));
    // Ended without answering: the menu is back once the dialog is taken for gone.
    invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap();
    assert_eq!(!entry_enabled(&app, select_all), steps_aside);
    let _ = app.file_dialogs.up(true, 0.0);
    let _ = app.file_dialogs.up(false, 0.1);
    let _ = app.file_dialogs.up(true, 0.2);
    assert!(entry_enabled(&app, select_all));
}

/// #3084: a host whose dialog couldn't open (macOS: `+[NSOpenPanel openPanel]` returned nil)
/// answers with the error. The status line says why, the command doesn't run and the dialog
/// no longer blocks floating windows; the next dialog opens as usual.
#[test]
fn a_dialog_that_cannot_open_reports_an_error() {
    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
    };
    let items = app.session.project.items.len();
    assert_eq!(invoke(&mut app, &ctx, "file.importAep", json!({})).unwrap(), json!({"dialog": "file.importAep"}));
    assert!(blocked(&mut app, true, 0.1));
    let done = pending.lock().unwrap().pop().expect("a dialog was asked for");
    std::thread::spawn(move || done(Err("The Open dialog couldn't open".into()))).join().unwrap();
    app.run_dialog_answers();
    assert_eq!(app.ui.status, "The Open dialog couldn't open");
    assert_eq!(app.session.project.items.len(), items, "nothing was imported");
    assert!(!blocked(&mut app, false, 0.2), "the failed dialog doesn't block floating windows");
    invoke(&mut app, &ctx, "file.importAep", json!({})).unwrap();
    assert_eq!(pending.lock().unwrap().len(), 1, "the next dialog opens");
}

/// Coverage for #3084 (not its regression test, which needs macOS): every enabled File ▸ Import
/// item that asks for a file asks through the host's one dialog path (`Hooks::file_dialog_async`
/// where the host has it), never through a blocking picker; After Effects Project is no
/// different from the others.
#[test]
fn every_import_item_asks_through_the_shared_dialog_path() {
    use std::sync::{Arc, Mutex};
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let ctx = egui::Context::default();
    app.hooks.pick_files = Some(Box::new(|_: &[&str]| panic!("the blocking picker is not used")));
    app.hooks.pick_open_project = Some(Box::new(|| panic!("the blocking picker is not used")));
    app.hooks.pick_folder = Some(Box::new(|| panic!("the blocking picker is not used")));
    let pending: Arc<Mutex<Vec<crate::FileDialog>>> = Arc::default();
    let queue = pending.clone();
    app.hooks.file_dialog_async = Some(Box::new(move |dialog, _done| queue.lock().unwrap().push(dialog)));
    // Placeholder and Solid open a form of the app's own and ask for no file.
    const IN_APP_FORM: &[&str] = &["file.importPlaceholder", "file.importSolid"];
    let import: Vec<_> = effectcraft_engine::menus::entries()
        .into_iter()
        .filter(|(path, _)| path.iter().map(String::as_str).eq(["File", "Import"]))
        .map(|(_, e)| e)
        .filter(|e| app.session.is_enabled(&e.command) && !IN_APP_FORM.contains(&e.command.as_str()))
        .collect();
    assert!(import.iter().any(|e| e.command == "file.importAep"), "File ▸ Import has After Effects Project");
    for entry in import {
        let r = invoke(&mut app, &ctx, &entry.command, entry.params_or_empty());
        assert_eq!(r, Ok(json!({"dialog": entry.command})), "{}", entry.command);
        let dialog = pending.lock().unwrap().pop();
        assert!(dialog.is_some(), "{}: asks through the shared dialog path", entry.command);
        if entry.command == "file.importAep" {
            assert_eq!(dialog, Some(crate::FileDialog::Open { exts: vec!["aep".into(), "aepx".into()], many: false }));
        }
    }
}

#[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]
#[cfg(not(target_arch = "wasm32"))]
fn dropped_files_keep_import_errors_alongside_local_drop_errors() {
    #[derive(Debug)]
    struct Drop(std::path::PathBuf);
    impl egui::DroppedFile for Drop {
        fn path(&self) -> &std::path::Path {
            &self.0
        }
        fn bytes(&self) -> Result<Vec<u8>, String> {
            std::fs::read(&self.0).map_err(|e| e.to_string())
        }
    }
    let folder = std::env::temp_dir().join(format!("effectcraft-mixed-drop-{}", std::process::id()));
    std::fs::create_dir_all(&folder).unwrap();
    let path = folder.join("no-pdf.vectorcraft");
    std::fs::write(&path, br#"{"format":"vectorcraft","version":4,"document":{"artboards":[],"layers":[]}}"#).unwrap();
    let second = folder.join("also-no-pdf.vectorcraft");
    std::fs::copy(&path, &second).unwrap();
    let footage = folder.join("pending.png");
    std::fs::write(&footage, b"not a PNG").unwrap();
    for (bad_import, background) in [(false, false), (true, false), (true, true)] {
        let mut app = EffectcraftApp::new(effectcraft_host::session());
        app.session.prefs.import.drag_import_as = "comp".into();
        let ctx = egui::Context::default();
        let mut dropped_files: Vec<egui::DroppedFileHandle> = vec![std::sync::Arc::new(Drop("no-local-path".into()))];
        if bad_import {
            dropped_files.push(std::sync::Arc::new(Drop(path.clone())));
            dropped_files.push(std::sync::Arc::new(Drop(second.clone())));
        }
        if background {
            dropped_files.push(std::sync::Arc::new(Drop(footage.clone())));
        }
        ctx.run_ui(egui::RawInput { dropped_files, ..Default::default() }, |ui| {
            crate::prefs_live::dropped_files(&mut app, ui, ui.max_rect());
        })
        .textures_delta
        .clear();
        assert!(app.ui.status.contains("without a local path"), "{}", app.ui.status);
        if bad_import {
            assert!(app.ui.status.contains("no-pdf.vectorcraft") && app.ui.status.contains("Create PDF-Compatible File"), "{}", app.ui.status);
            let details = &app.error_toasts.back().expect("all import errors remain available").message;
            assert!(details.contains("also-no-pdf.vectorcraft"), "{details}");
            if background {
                app.session.execute("jobs.wait", json!({})).unwrap();
                app.handle_events(&ctx);
                let details = &app.error_toasts.back().unwrap().message;
                for name in ["no-pdf.vectorcraft", "also-no-pdf.vectorcraft", "pending.png"] {
                    assert!(details.contains(name), "{details}");
                }
                assert!(app.ui.status.contains("without a local path"));
            }
        } else {
            assert!(!app.ui.status.contains(";"), "{}", app.ui.status);
        }
    }
    std::fs::remove_dir_all(folder).unwrap();
}

#[test]
fn importing_without_a_form_shows_immediate_file_errors() {
    let folder = std::env::temp_dir().join(format!("effectcraft-drop-import-{}", std::process::id()));
    std::fs::create_dir_all(&folder).unwrap();
    let path = folder.join("no-pdf.vectorcraft");
    std::fs::write(&path, br#"{"format":"vectorcraft","version":4,"document":{"artboards":[],"layers":[]}}"#).unwrap();
    let mut app = EffectcraftApp::new(effectcraft_host::session());
    let ctx = egui::Context::default();
    let r = invoke(&mut app, &ctx, "file.import", json!({"paths": [path], "importAs": "composition", "background": true, "drag": true})).unwrap();
    assert!(app.dialog.is_none());
    assert!(r["errors"][0].as_str().unwrap().contains("Create PDF-Compatible File"));
    assert!(app.ui.status.contains("no-pdf.vectorcraft") && app.ui.status.contains("Create PDF-Compatible File"), "{}", app.ui.status);
    std::fs::remove_dir_all(folder).unwrap();
}

/// Cmd+W with the Render Queue focused closes the queue; the composition next to it stays
/// open (it used to be closed, and the queue stayed).
#[test]
fn cmd_w_in_the_render_queue_closes_the_queue_not_the_comp() {
    let ctx = egui::Context::default();
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let a = app.session.execute("comp.new", json!({"name": "A", "duration": 4})).unwrap()["comp"].as_u64();
    app.show_panel(PanelKind::RenderQueue);
    assert_eq!(app.ui.focused, PanelKind::RenderQueue);
    invoke(&mut app, &ctx, "file.close", json!({})).unwrap();
    assert!(!app.ui.dock.is_visible(PanelKind::RenderQueue));
    assert_eq!(app.session.state.active_comp.map(|c| c.0), a);
    assert_eq!(app.session.state.open_comps.len(), 1);
    // The focus left the closed queue: the next Close closes the composition.
    assert_ne!(app.ui.focused, PanelKind::RenderQueue);
    invoke(&mut app, &ctx, "file.close", json!({})).unwrap();
    assert_eq!(app.session.state.open_comps.len(), 0, "a second Close acts on the composition");
}

#[test]
fn file_close_is_available_for_an_empty_render_queue_without_a_comp() {
    for params in [Value::Null, json!({})] {
        let ctx = egui::Context::default();
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        assert!(app.session.active_comp().is_none());
        app.show_panel(PanelKind::RenderQueue);
        assert!(menu_items(&app).iter().find(|item| item.id == "file.close").unwrap().enabled);
        invoke(&mut app, &ctx, "file.close", params).unwrap();
        assert!(!app.ui.dock.is_open(PanelKind::RenderQueue));
    }
}

#[test]
fn closing_the_render_queue_reveals_the_panel_receiving_focus() {
    for maximized in [false, true] {
        let ctx = egui::Context::default();
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.close_panel(PanelKind::Timeline);
        app.close_panel(PanelKind::Composition);
        app.show_panel(PanelKind::EffectControls);
        assert!(!app.ui.dock.is_visible(PanelKind::Project));
        app.show_panel(PanelKind::RenderQueue);
        if maximized {
            app.apply_dock(craft_ui::docking::Action::Float { panel: PanelKind::RenderQueue, rect: [50.0, 60.0, 400.0, 200.0] }).unwrap();
            app.toggle_maximize(PanelKind::EffectControls);
            app.ui.focused = PanelKind::RenderQueue;
            assert!(app.ui.dock.is_floating(PanelKind::RenderQueue));
        }
        invoke(&mut app, &ctx, "file.close", json!({})).unwrap();
        assert_eq!(app.ui.focused, PanelKind::Project);
        assert!(app.ui.dock.is_visible(app.ui.focused), "focus must belong to a front tab");
        assert_eq!(app.ui.maximized, None, "the focused docked panel must be on screen");
    }
}

/// Closing a floating queue must focus the viewer that is actually shown, retaining maximization.
#[test]
fn closing_a_floating_queue_preserves_the_maximized_composition() {
    let mut session = effectcraft_engine::Session::default();
    session.execute("comp.new", json!({"name": "A", "width": 32, "height": 32, "duration": 2})).unwrap();
    let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_| EffectcraftApp::new(session));
    h.run_steps(3);
    let ctx = h.ctx.clone();
    let app = h.state_mut();
    app.show_panel(PanelKind::Composition);
    app.show_panel(PanelKind::RenderQueue);
    app.apply_dock(craft_ui::docking::Action::Float { panel: PanelKind::RenderQueue, rect: [50.0, 60.0, 400.0, 200.0] }).unwrap();
    app.toggle_maximize(PanelKind::Composition);
    app.ui.focused = PanelKind::RenderQueue;
    assert!(app.ui.dock.is_visible(PanelKind::Timeline), "the hidden underlying tab triggers the regression");
    assert!(!panel_shown(app, PanelKind::Timeline));
    invoke(app, &ctx, "file.close", json!({})).unwrap();
    h.run_steps(3);
    assert_eq!(h.state().ui.focused, PanelKind::Composition);
    assert_eq!(h.state().ui.maximized, Some(PanelKind::Composition));
    assert!(!h.state().ui.dock.is_open(PanelKind::RenderQueue));
    assert_eq!(h.state().session.state.open_comps.len(), 1);
}

#[test]
fn queue_close_preserves_state_when_workspace_is_locked() {
    let ctx = egui::Context::default();
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    app.session.execute("comp.new", json!({"name": "A", "duration": 2})).unwrap();
    app.show_panel(PanelKind::RenderQueue);
    app.ui.dock.locked = true;
    let workspace = app.ui.dock.clone();
    let comp = app.session.active_comp_id();
    for _ in 0..2 {
        assert!(invoke(&mut app, &ctx, "file.close", Value::Null).is_err());
        assert_eq!(app.ui.dock, workspace);
        assert_eq!(app.ui.focused, PanelKind::RenderQueue);
        assert_eq!(app.session.active_comp_id(), comp);
    }
    assert!(!menu_items(&app).iter().find(|item| item.id == "file.close").unwrap().enabled);
    app.ui.dock.locked = false;
    invoke(&mut app, &ctx, "file.close", Value::Null).unwrap();
    assert!(!app.ui.dock.is_open(PanelKind::RenderQueue));
}

#[test]
fn queue_close_preserves_viewer_command_target() {
    let ctx = egui::Context::default();
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let a = app.session.execute("comp.new", json!({"name": "A", "duration": 2})).unwrap()["comp"].as_u64().unwrap();
    let b = app.session.execute("comp.new", json!({"name": "B", "duration": 2})).unwrap()["comp"].as_u64().unwrap();
    app.show_panel(PanelKind::Viewer(1));
    app.ui.viewers.insert(0, Some(a));
    app.ui.viewers.insert(1, Some(b));
    app.ui.active_viewer = 1;
    app.apply_dock(craft_ui::docking::Action::Move {
        panel: PanelKind::Timeline,
        anchor: PanelKind::Composition,
        placement: craft_ui::docking::Placement::Tab { before: None },
    })
    .unwrap();
    app.close_panel(PanelKind::Timeline);
    app.show_panel(PanelKind::Composition);
    app.show_panel(PanelKind::RenderQueue);
    assert_eq!(app.session.active_comp_id().map(|id| id.0), Some(b));
    invoke(&mut app, &ctx, "file.close", json!({})).unwrap();
    assert_eq!(app.ui.focused, PanelKind::Composition);
    assert_eq!(app.ui.active_viewer, 0);
    assert_eq!(app.session.active_comp_id().map(|id| id.0), Some(a));
    invoke(&mut app, &ctx, "file.close", json!({})).unwrap();
    assert!(!app.session.state.open_comps.iter().any(|id| id.0 == a));
    assert!(app.session.state.open_comps.iter().any(|id| id.0 == b));
}

#[test]
fn queue_close_keeps_passive_viewer_focus_across_frames() {
    let mut session = effectcraft_engine::Session::default();
    let a = session.execute("comp.new", json!({"name": "A", "width": 32, "height": 32, "duration": 2})).unwrap()["comp"].as_u64().unwrap();
    let b = session.execute("comp.new", json!({"name": "B", "width": 32, "height": 32, "duration": 2})).unwrap()["comp"].as_u64().unwrap();
    let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_| EffectcraftApp::new(session));
    h.run_steps(3);
    let ctx = h.ctx.clone();
    let app = h.state_mut();
    app.show_panel(PanelKind::Viewer(1));
    app.ui.viewers.insert(0, Some(a));
    app.ui.viewers.insert(1, Some(b));
    app.ui.active_viewer = 1;
    app.apply_dock(craft_ui::docking::Action::Move {
        panel: PanelKind::Timeline,
        anchor: PanelKind::Composition,
        placement: craft_ui::docking::Placement::Tab { before: None },
    })
    .unwrap();
    app.close_panel(PanelKind::Timeline);
    app.show_panel(PanelKind::Composition);
    app.show_panel(PanelKind::RenderQueue);
    invoke(app, &ctx, "file.close", Value::Null).unwrap();
    h.run_steps(4);
    let app = h.state_mut();
    assert_eq!(app.ui.focused, PanelKind::Composition);
    assert_eq!(app.ui.active_viewer, 0);
    assert_eq!(app.session.active_comp_id().map(|id| id.0), Some(a));
    assert!(app.ui.dock.is_visible(PanelKind::Composition));
    assert!(!app.ui.dock.is_open(PanelKind::RenderQueue));
    invoke(app, &ctx, "file.close", json!({})).unwrap();
    assert!(!app.session.state.open_comps.iter().any(|id| id.0 == a));
    assert!(app.session.state.open_comps.iter().any(|id| id.0 == b));
    // A later explicit Open still routes normally, rather than inheriting a deferred focus override.
    invoke(app, &ctx, "comp.open", json!({"comp": b})).unwrap();
    h.run_steps(3);
    assert!(h.state().ui.dock.is_visible(PanelKind::Timeline));
    assert_eq!(h.state().session.active_comp_id().map(|id| id.0), Some(b));
}

#[test]
fn menu_items_cover_the_tree() {
    assert_eq!(menus().last(), Some(&"Help"));
    assert!(effectcraft_engine::menus::entries().len() > 500);
}

/// A command run from the menu that opens a composition (File ▸ Import ▸ After Effects
/// Project… after Import Anyway, a new composition) leaves the Home screen: it stayed over the
/// imported project, which looked as if nothing was imported. A command that opens none keeps it.
#[test]
fn a_menu_command_that_opens_a_composition_leaves_the_home_screen() {
    let ctx = egui::Context::default();
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    app.ui.start_screen = true;
    run_engine(&mut app, &ctx, "project.summary", json!({})).unwrap();
    assert!(app.ui.start_screen);
    assert!(run_engine(&mut app, &ctx, "file.importAep", json!({"path": "/no/such/file.aep", "allowLosses": true})).is_err());
    assert!(app.ui.start_screen);
    run_engine(&mut app, &ctx, "comp.new", json!({"name": "Opened", "width": 64, "height": 36, "duration": 1})).unwrap();
    assert!(!app.ui.start_screen);
    // Asked for again (Home button, Help ▸ In-App Tutorials) it stays while the comp is open.
    app.ui.start_screen = true;
    run_engine(&mut app, &ctx, "layer.newSolid", json!({"color": "#ff0000"})).unwrap();
    assert!(app.ui.start_screen);
}

/// Opening a project leaves the Home screen also when its composition has the id of the one open
/// before (the project changed, the id did not), from the menu and from a file dialog's answer.
#[test]
fn opening_a_project_leaves_the_home_screen_whatever_its_composition_id() {
    let ctx = egui::Context::default();
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    app.session.execute("comp.new", json!({"name": "Saved", "width": 64, "height": 36, "duration": 1})).unwrap();
    let dir = std::env::temp_dir().join(format!("ec-home-open-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("Home.ecproj").to_string_lossy().to_string();
    app.session.execute("file.saveAs", json!({"path": path})).unwrap();
    let comp = app.session.active_comp_id();
    // File ▸ Open with the path given (the menu path, `run_engine`).
    app.ui.start_screen = true;
    run_engine(&mut app, &ctx, "file.open", json!({"path": path})).unwrap();
    assert_eq!(app.session.active_comp_id(), comp, "the same composition id");
    assert!(!app.ui.start_screen, "File ▸ Open leaves the Home screen");
    // The path picked in a file dialog (`run_with_picked`).
    app.ui.start_screen = true;
    super::frontend::dialog_answered(
        &mut app,
        crate::DialogAnswer { command: "file.open".into(), key: "path", params: json!({}), paths: Ok(vec![path.clone()]) },
    );
    assert_eq!(app.session.active_comp_id(), comp);
    assert!(!app.ui.start_screen, "a picked project leaves the Home screen");
    let _ = std::fs::remove_dir_all(&dir);
}

/// A successful command that reports per-item problems (`errors`) shows a compact, readable
/// report in the status line: `file: error; …`, first three and a count, never raw JSON.
#[test]
fn bundle_result_errors_show_compactly_in_the_status_line() {
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let result = json!({"installed": [], "errors": [
        {"file": "a.wasm", "error": "already installed"},
        {"file": "b.wasm", "error": "does not load"},
        {"file": "c.wasm", "error": "cannot read it"},
        {"error": "cannot read the bundle folder"},
    ]});
    super::frontend::show_result_errors(&mut app, &result);
    assert_eq!(app.ui.status, "a.wasm: already installed; b.wasm: does not load; c.wasm: cannot read it; +1 more");
    // A clean success leaves the status line alone.
    super::frontend::show_result_errors(&mut app, &json!({"installed": ["x.wasm"], "errors": []}));
    assert_eq!(app.ui.status, "a.wasm: already installed; b.wasm: does not load; c.wasm: cannot read it; +1 more");
}

/// A picked or menu import reports its errors twice: `report_import_errors` queues the details
/// with a short status, and the command's result then writes the longer status. Dismissing that
/// status still acknowledges the queued details, also when After Effects project errors lead it.
/// Another command's errors do not take over an import's details, even with the same text.
#[test]
fn an_import_status_rewritten_by_its_result_still_acknowledges_its_details() {
    let long = format!("first failed file {}", "x".repeat(20_000));
    for first in ["first failed file", "first failed file\nwith a second line", long.as_str()] {
        let import = json!({"errors": [first, "second failed file"]});
        let with_aep = json!({"errors": ["project.aep: cannot read it", first, "second failed file"]});
        for result in [&import, &with_aep] {
            let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
            app.report_import_errors("file.import", &import);
            super::frontend::show_command_result_errors(&mut app, "file.import", result);
            assert!(app.ui.status.contains("first failed file"), "{}", app.ui.status);
            assert_eq!(app.error_toasts.len(), 1);
            assert!(app.error_toasts.back().unwrap().reported_by(&app.ui.status), "{first:.40}: {:.80}", app.ui.status);
        }
    }
    let import = json!({"errors": ["first failed file", "second failed file"]});
    for other in [json!({"errors": [{"file": "a.wasm", "error": "does not load"}]}), import.clone()] {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.report_import_errors("file.import", &import);
        super::frontend::show_command_result_errors(&mut app, "effect.installBundle", &other);
        assert!(!app.ui.status.contains("(and"), "{}", app.ui.status);
        assert!(!app.error_toasts.back().unwrap().reported_by(&app.ui.status), "{}", app.ui.status);
    }
}

/// Effect ▸ Install Effect Plug-in… picks its dialog by params: a bundle asks for a folder,
/// a plain install asks for a `.wasm`, and with both given inline nothing asks at all.
#[test]
fn effect_plugin_install_dialog_router() {
    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)));
    // The bundle menu entry: a folder picker.
    assert_eq!(invoke(&mut app, &ctx, "effect.plugins.install", json!({"bundle": true})).unwrap(), json!({"dialog": "effect.plugins.install"}));
    assert_eq!(pending.lock().unwrap().pop().unwrap(), crate::FileDialog::Folder, "the bundle asks for a folder");
    // The plain command: a `.wasm` file picker.
    assert_eq!(invoke(&mut app, &ctx, "effect.plugins.install", json!({})).unwrap(), json!({"dialog": "effect.plugins.install"}));
    let crate::FileDialog::Open { exts, many } = pending.lock().unwrap().pop().unwrap() else { panic!("not an open dialog") };
    assert_eq!(exts, vec!["wasm".to_string()], "{exts:?}");
    assert!(!many);
    // `path` given inline overrides the bundle ask: the command runs directly, opening no dialog
    // (this session has no plug-in loader, so it errors — but nothing was asked).
    let r = invoke(&mut app, &ctx, "effect.plugins.install", json!({"bundle": true, "path": "x.wasm"}));
    assert!(r.is_err(), "{r:?}");
    assert!(pending.lock().unwrap().is_empty(), "no dialog for an inline path");
    // A supplied `folder` is a bundle source too: asking for a file would let the install take
    // the picked file and ignore the folder, so nothing is asked.
    let r = invoke(&mut app, &ctx, "effect.plugins.install", json!({"folder": "some/where"}));
    assert!(r.is_err(), "{r:?}");
    assert!(pending.lock().unwrap().is_empty(), "no dialog for an inline folder");
}

/// File ▸ Import ▸ File… in the non-blocking dialog (macOS, Linux) offers After Effects projects
/// next to footage, and a picked one imports as File ▸ Import ▸ Adobe After Effects Project… does: its
/// folder, its composition open.
#[test]
fn import_file_dialog_offers_and_imports_after_effects_projects() {
    use std::sync::{Arc, Mutex};
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let ctx = egui::Context::default();
    let dir = std::env::temp_dir().join(format!("ec-import-aep-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let aep = dir.join("Intro.aep").to_string_lossy().to_string();
    let mut source = effectcraft_engine::Session::default();
    source.execute("comp.new", json!({"name": "Intro", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();
    source.execute("file.exportAep", json!({"path": aep, "allowLosses": true})).unwrap();

    let pending: Arc<Mutex<Vec<crate::FileDialog>>> = Arc::default();
    let queue = pending.clone();
    app.hooks.file_dialog_async = Some(Box::new(move |dialog, _done| queue.lock().unwrap().push(dialog)));
    invoke(&mut app, &ctx, "file.import", json!({})).unwrap();
    let Some(crate::FileDialog::Open { exts, many }) = pending.lock().unwrap().pop() else { panic!("an Open dialog was shown") };
    assert!(many && exts.iter().any(|e| e == "aep") && exts.iter().any(|e| e == "aepx"), "{exts:?}");
    assert!(exts.iter().any(|e| e == "png"), "footage too");

    super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(vec![aep]) });
    let comp = app.session.project.item(app.session.active_comp_id().expect("a composition is open")).unwrap();
    assert_eq!(comp.name, "Intro");
    assert_eq!(app.session.project.item(comp.parent.expect("in a folder")).unwrap().name, "Intro.aep");
    let _ = std::fs::remove_dir_all(&dir);
}

/// Footage with unlabeled alpha asks how to interpret it (Interpret Unlabeled Alpha As: Ask
/// User), but not over a dialog that already waits (the After Effects losses prompt of the same
/// drop, which a background import can finish behind): that dialog stays, and a note says where
/// to choose the interpretation.
#[test]
fn the_unlabeled_alpha_question_does_not_replace_an_open_dialog() {
    use effectcraft_engine::project::{Footage, FootageKind, ItemKind};
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let ctx = egui::Context::default();
    let footage = Footage { path: "/m/matte.tga".into(), kind: FootageKind::Still, width: 4, height: 4, has_video: true, ..Default::default() };
    let item = std::sync::Arc::make_mut(&mut app.session.project).add_item("matte.tga", Default::default(), None, ItemKind::Footage(footage)).0;
    app.dialog = Some(crate::Dialog::AepLosses);
    super::frontend(&mut app, &ctx, "file.interpretFootage", json!({"item": item, "reason": "unlabeledAlpha"})).unwrap();
    assert_eq!(app.dialog, Some(crate::Dialog::AepLosses), "the waiting dialog stays");
    assert!(app.ui.status.contains("Interpret Footage"), "{}", app.ui.status);
    assert!(app.session.state.project_selection.is_empty(), "the selection is left alone");

    app.dialog = None;
    super::frontend(&mut app, &ctx, "file.interpretFootage", json!({"item": item, "reason": "unlabeledAlpha"})).unwrap();
    assert_eq!(app.dialog, Some(crate::Dialog::Form), "with no dialog open it asks");
}

/// File ▸ Import ▸ File… and Multiple Files… offer projects next to footage; File ▸ Replace
/// Footage offers footage only.
#[test]
fn only_the_import_dialogs_offer_projects() {
    use std::sync::{Arc, Mutex};
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let pending: Arc<Mutex<Vec<crate::FileDialog>>> = Arc::default();
    let queue = pending.clone();
    app.hooks.file_dialog_async = Some(Box::new(move |dialog, _done| queue.lock().unwrap().push(dialog)));
    let projects = ["aep", "aepx", "ecproj", "ecprojx"];
    for (id, offered) in [("file.import", true), ("file.importMultiple", true), ("file.replaceFootage", false)] {
        assert!(super::frontend::file_dialog(&mut app, id, &json!({})).is_some(), "{id} asks for a file");
        let Some(crate::FileDialog::Open { exts, .. }) = pending.lock().unwrap().pop() else { panic!("{id}: an Open dialog") };
        assert!(exts.iter().any(|e| e == "png"), "{id} offers footage");
        assert_eq!(projects.iter().all(|p| exts.iter().any(|e| e == p)), offered, "{id}: {exts:?}");
        assert!(offered || !projects.iter().any(|p| exts.iter().any(|e| e == p)), "{id} offers no project: {exts:?}");
    }
}

/// Picked After Effects projects that cannot be imported keep their errors next to the other
/// files': a broken `.aep` and a broken `.ecproj` are both named in the status line.
#[test]
fn picked_projects_report_every_error() {
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let dir = std::env::temp_dir().join(format!("ec-picked-errors-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let aep = dir.join("broken.aep");
    let ecproj = dir.join("broken.ecproj");
    std::fs::write(&aep, b"not an aep").unwrap();
    std::fs::write(&ecproj, b"not a project").unwrap();
    let paths = vec![aep.to_string_lossy().to_string(), ecproj.to_string_lossy().to_string()];
    super::frontend::dialog_answered(
        &mut app,
        crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(paths.clone()) },
    );
    let status = &app.ui.status;
    assert!(status.contains("broken.aep") && status.contains("broken.ecproj"), "{status}");
    assert!(!status.contains('"'), "messages, not quoted JSON: {status}");
    assert!(app.dialog.is_none() && app.session.project.items.is_empty());

    // The blocking dialog (Windows), whose callers drop the result: the status line still has both.
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let ctx = egui::Context::default();
    app.hooks.pick_files = Some(Box::new(move |_: &[&str]| paths.clone()));
    let _ = invoke(&mut app, &ctx, "file.import", json!({}));
    let status = &app.ui.status;
    assert!(status.contains("broken.aep") && status.contains("broken.ecproj"), "{status}");
    let _ = std::fs::remove_dir_all(&dir);
}

/// A picked After Effects project with parts that cannot come over asks first; one picked with
/// it waits for the answer.
#[test]
fn a_picked_project_with_losses_asks_and_the_next_waits() {
    let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
    let dir = std::env::temp_dir().join(format!("ec-picked-losses-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let lossy = dir.join("Synthetic.aep");
    std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/../aep/tests/fixtures/synthetic.aep"), &lossy).unwrap();
    let intro = dir.join("Intro.aep").to_string_lossy().to_string();
    let mut source = effectcraft_engine::Session::default();
    source.execute("comp.new", json!({"name": "Intro", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();
    source.execute("file.exportAep", json!({"path": intro, "allowLosses": true})).unwrap();
    let paths = vec![lossy.to_string_lossy().to_string(), intro.clone()];
    super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(paths) });
    assert_eq!(app.dialog, Some(crate::Dialog::AepLosses));
    assert_eq!(app.dialog_state.aep_losses.queue, [intro]);
    assert!(app.session.project.items.is_empty(), "nothing imported before the answer");
    let _ = std::fs::remove_dir_all(&dir);
}