GitCorner

Code

ossartcraftfilmcraft🌐
f67d38b35cc5
//! Window ▸ Workspaces, driven headless through the control channel: save a layout as a new
//! workspace, switch away and back, Reset to Saved Layout, save changes to a built-in and restore
//! it, rename and delete in the Edit Workspaces dialog, and the saved workspaces (and the one in use)
//! surviving a restart through `workspaces.json` in the data directory.
//!
//! Set `FILMCRAFT_UI_SNAPSHOT_DIR=<dir>` to also render offscreen with wgpu and write
//! `workspaces-*.png`.

use std::path::{Path, PathBuf};
use std::sync::mpsc::{Sender, channel};

use egui_kittest::Harness;
use filmcraft_engine::Session;
use filmcraft_ui_egui::FilmcraftApp;
use filmcraft_ui_egui::control::ControlRequest;
use filmcraft_ui_egui::dock::PanelKind;
use serde_json::{Value, json};

struct Driver {
    harness: Harness<'static, FilmcraftApp>,
    tx: Sender<ControlRequest>,
    snapshots: Option<PathBuf>,
}

impl Driver {
    /// The demo project with its preferences (and workspaces) in `data`.
    fn launch(data: &Path) -> Self {
        let mut session = Session::default();
        session.execute("file.openDemoProject", json!({})).expect("demo project");
        session.prefs_path = Some(data.join("preferences.json"));
        let (tx, rx) = channel();
        let app = FilmcraftApp::new(session).with_control(rx);
        let snapshots = std::env::var_os("FILMCRAFT_UI_SNAPSHOT_DIR").map(PathBuf::from);
        let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000);
        if snapshots.is_some() {
            b = b.wgpu();
        }
        let harness = b.build_eframe(move |_cc| app);
        let mut d = Driver { harness, tx, snapshots };
        d.frames(4);
        d
    }

    fn frames(&mut self, n: usize) {
        for _ in 0..n {
            let ctx = self.harness.ctx.clone();
            let mut raw = std::mem::take(self.harness.input_mut());
            eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);
            *self.harness.input_mut() = raw;
            self.harness.step();
        }
    }

    fn call(&mut self, method: &str, params: Value) -> Value {
        let (req, reply) = ControlRequest::new(method, params.clone());
        self.tx.send(req).unwrap();
        for _ in 0..600 {
            self.frames(1);
            if let Ok(v) = reply.try_recv() {
                return v;
            }
        }
        panic!("no reply to {method} {params}");
    }

    fn ok(&mut self, method: &str, params: Value) -> Value {
        let v = self.call(method, params.clone());
        assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");
        v["result"].clone()
    }

    fn menu(&mut self, id: &str, params: Value) -> Value {
        self.ok("ui.menu.invoke", json!({"id": id, "params": params}))
    }

    fn menu_err(&mut self, id: &str, params: Value) -> String {
        let v = self.call("ui.menu.invoke", json!({"id": id, "params": params}));
        assert_eq!(v["ok"], json!(false), "{id} {params} should fail: {v}");
        v["error"].as_str().unwrap_or_default().to_string()
    }

    fn click(&mut self, id: &str) {
        self.ok("ui.click", json!({"id": id}));
        self.frames(2);
    }

    /// Replace the text of the field `id`.
    fn retype(&mut self, id: &str, text: &str) {
        self.click(id);
        self.ok("ui.key", json!({"key": "A", "command": true}));
        self.ok("ui.type", json!({"text": text}));
        self.frames(2);
    }

    fn has(&mut self, id: &str) -> bool {
        let v = self.ok("ui.elements", json!({"prefix": id}));
        v.as_array().unwrap().iter().any(|e| e["id"] == json!(id))
    }

    fn app(&mut self) -> &mut FilmcraftApp {
        self.harness.state_mut()
    }

    fn workspace(&mut self) -> String {
        self.app().ui.workspace.clone()
    }

    fn shows(&mut self, p: PanelKind) -> bool {
        self.app().ui.dock.contains(&p)
    }

    /// Window ▸ Workspaces as (label, checked) in menu order.
    fn workspaces_menu(&mut self) -> Vec<(String, bool)> {
        let items = self.ok("ui.menu.list", json!({}));
        items
            .as_array()
            .unwrap()
            .iter()
            .filter(|i| i["path"] == json!(["Window", "Workspaces"]))
            .map(|i| (i["label"].as_str().unwrap().to_string(), i["checked"] == json!(true)))
            .collect()
    }

    fn snapshot(&mut self, name: &str) {
        let Some(dir) = self.snapshots.clone() else { return };
        self.frames(2);
        match self.harness.render() {
            Ok(img) => {
                std::fs::create_dir_all(&dir).unwrap();
                img.save(dir.join(format!("workspaces-{name}.png"))).unwrap();
            }
            Err(e) => eprintln!("snapshot {name} skipped: {e}"),
        }
    }
}

fn data_dir(name: &str) -> PathBuf {
    let d = std::env::temp_dir().join(format!("filmcraft-workspaces-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&d);
    std::fs::create_dir_all(&d).unwrap();
    d
}

fn saved_file(data: &Path) -> Value {
    serde_json::from_slice(&std::fs::read(data.join("workspaces.json")).expect("workspaces.json written")).unwrap()
}

fn built_in_keeps_saved_changes_and_restores(d: &mut Driver) {
    // Save Changes to this Workspace on a built-in; it can't be deleted, only restored
    d.ok("ui.set", json!({"workspace": "Assembly"}));
    d.ok("ui.panel.close", json!({"panel": "History"}));
    d.menu("window.workspace.saveChanges", json!({}));
    d.ok("ui.set", json!({"workspace": "Cutting"}));
    d.ok("ui.set", json!({"workspace": "Assembly"}));
    assert!(!d.shows(PanelKind::History), "the built-in keeps its saved changes");
    assert_eq!(d.menu("window.workspace.delete", json!({"name": "Assembly"}))["restored"], "Assembly");
    assert!(d.shows(PanelKind::History), "restoring the current built-in shows its original layout");
    assert!(d.menu_err("window.workspace.delete", json!({"name": "Assembly"})).contains("can't be deleted"));
    assert!(d.menu_err("window.workspace.rename", json!({"from": "Assembly", "to": "Mine"})).contains("keeps its name"));
}

/// Window ▸ Workspaces end to end: save a new workspace, switch away and back, reset, save changes
/// to a built-in and restore it, rename and delete, and the saved ones surviving a restart.
#[test]
fn save_switch_reset_rename_delete_and_restart() {
    let data = data_dir("cycle");
    let mut d = Driver::launch(&data);
    assert_eq!(d.workspace(), "Editing");
    assert!(d.shows(PanelKind::Metadata));

    // Save as New Workspace: the current layout under a new name, now the current workspace
    d.ok("ui.panel.close", json!({"panel": "Metadata"}));
    assert_eq!(d.menu("window.workspace.saveAs", json!({"name": "Cutting"}))["workspace"], "Cutting");
    assert_eq!(d.workspace(), "Cutting");
    assert_eq!(saved_file(&data)["saved"][0]["name"], "Cutting");
    let menu = d.workspaces_menu();
    let names: Vec<&str> = menu.iter().map(|(l, _)| l.as_str()).collect();
    assert_eq!(
        names,
        [
            "All Panels",
            "Assembly",
            "Audio",
            "Captions and Graphics",
            "Color",
            "Cutting",
            "Editing",
            "Effects",
            "Learning",
            "Review",
            "Vertical",
            "Reset to Saved Layout",
            "Save Changes to this Workspace",
            "Save as New Workspace…",
            "Edit Workspaces…"
        ],
        "one alphabetical list, then the layout commands"
    );
    assert!(menu.iter().any(|(l, c)| l == "Cutting" && *c), "the current workspace is checked: {menu:?}");
    d.snapshot("menu-list");

    // a name in use, an empty one or a command's name is refused
    assert!(d.menu_err("window.workspace.saveAs", json!({"name": "editing"})).contains("already exists"));
    assert!(d.menu_err("window.workspace.saveAs", json!({"name": "  "})).contains("needs a name"));
    assert!(d.menu_err("window.workspace.saveAs", json!({"name": "Reset"})).contains("can't be used"));

    // switch away and back (by menu and by ui.set): the saved layout comes back
    d.menu("window.workspace.color", json!({}));
    assert_eq!(d.workspace(), "Color");
    assert!(d.shows(PanelKind::LumetriColor));
    d.ok("ui.set", json!({"workspace": "cutting"}));
    assert_eq!(d.workspace(), "Cutting");
    assert!(!d.shows(PanelKind::Metadata) && !d.shows(PanelKind::LumetriColor));

    // Reset to Saved Layout undoes changes made since the save
    d.ok("ui.panel.close", json!({"panel": "Project"}));
    assert!(!d.shows(PanelKind::Project));
    d.menu("window.workspace.reset", json!({}));
    assert!(d.shows(PanelKind::Project) && !d.shows(PanelKind::Metadata));

    built_in_keeps_saved_changes_and_restores(&mut d);

    // rename follows the current workspace
    d.ok("ui.set", json!({"workspace": "Cutting"}));
    d.menu("window.workspace.rename", json!({"from": "Cutting", "to": "Fine Cut"}));
    assert_eq!(d.workspace(), "Fine Cut");
    assert!(d.call("ui.set", json!({"workspace": "Cutting"}))["ok"] == json!(false));
    drop(d);

    // restart: the saved workspaces and the one in use come back
    let mut d = Driver::launch(&data);
    assert_eq!(d.workspace(), "Fine Cut");
    assert!(!d.shows(PanelKind::Metadata));
    assert!(d.workspaces_menu().iter().any(|(l, c)| l == "Fine Cut" && *c));

    // delete the current user workspace: back to Editing, gone from the menu and the file
    assert_eq!(d.menu("window.workspace.delete", json!({"name": "Fine Cut"}))["deleted"], "Fine Cut");
    assert_eq!(d.workspace(), "Editing");
    assert!(!d.workspaces_menu().iter().any(|(l, _)| l == "Fine Cut"));
    assert_eq!(saved_file(&data)["saved"], json!([]));
    let _ = std::fs::remove_dir_all(&data);
}

/// #2421: panel changes made without Save Changes to this Workspace come back after a restart
/// (the layout in use when the app closed is remembered per workspace); Reset to Saved Layout
/// still returns to the saved layout, and another workspace's remembered layout is not applied.
#[test]
fn the_layout_in_use_at_close_comes_back_without_saving() {
    let data = data_dir("remember");
    let mut d = Driver::launch(&data);
    assert_eq!(d.workspace(), "Editing");
    assert!(d.shows(PanelKind::Metadata));
    d.ok("ui.panel.close", json!({"panel": "Metadata"}));
    // the exit path is what remembers it
    eframe::App::on_exit(d.app());
    assert_eq!(saved_file(&data)["last"]["name"], "Editing");
    assert_eq!(saved_file(&data)["saved"], json!([]), "nothing was saved as a workspace");
    drop(d);

    let mut d = Driver::launch(&data);
    assert_eq!(d.workspace(), "Editing");
    assert!(!d.shows(PanelKind::Metadata), "the layout in use at close comes back");
    d.menu("window.workspace.reset", json!({}));
    assert!(d.shows(PanelKind::Metadata), "Reset to Saved Layout returns to the saved layout");

    // closed in Color: Color comes back as it was, Editing opens its saved layout
    d.ok("ui.set", json!({"workspace": "Color"}));
    assert!(d.shows(PanelKind::LumetriScopes));
    d.ok("ui.panel.close", json!({"panel": "LumetriScopes"}));
    d.app().remember_layout();
    drop(d);
    let mut d = Driver::launch(&data);
    assert_eq!(d.workspace(), "Color");
    assert!(!d.shows(PanelKind::LumetriScopes));
    d.ok("ui.set", json!({"workspace": "Editing"}));
    assert!(d.shows(PanelKind::Metadata), "another workspace's remembered layout does not apply");
    let _ = std::fs::remove_dir_all(&data);
}

/// A window closed before its first frame has not brought the workspace back yet: what the last
/// launch remembered stays, not the default workspace's layout.
#[test]
fn closing_before_the_first_frame_keeps_the_remembered_layout() {
    let data = data_dir("remember-early");
    let mut d = Driver::launch(&data);
    d.ok("ui.set", json!({"workspace": "Color"}));
    d.ok("ui.panel.close", json!({"panel": "LumetriScopes"}));
    d.app().remember_layout();
    drop(d);
    let before = saved_file(&data);
    assert_eq!(before["last"]["name"], "Color");

    let mut session = Session::default();
    session.prefs_path = Some(data.join("preferences.json"));
    FilmcraftApp::new(session).remember_layout();
    assert_eq!(saved_file(&data), before);
    let _ = std::fs::remove_dir_all(&data);
}

/// A `workspaces.json` whose workspace in use names no workspace (edited or damaged): the launch
/// keeps the default layout, and closing it does not replace the remembered one.
#[test]
fn a_current_workspace_that_names_none_keeps_the_remembered_layout() {
    let data = data_dir("remember-unknown");
    let mut d = Driver::launch(&data);
    d.ok("ui.set", json!({"workspace": "Color"}));
    d.ok("ui.panel.close", json!({"panel": "LumetriScopes"}));
    d.app().remember_layout();
    drop(d);
    let mut file = saved_file(&data);
    file["current"] = json!("Gone");
    std::fs::write(data.join("workspaces.json"), serde_json::to_vec_pretty(&file).unwrap()).unwrap();

    let mut d = Driver::launch(&data);
    eframe::App::on_exit(d.app());
    drop(d);
    assert_eq!(saved_file(&data), file, "the remembered layout stays");
    let _ = std::fs::remove_dir_all(&data);
}

/// A layout saved on purpose is never beaten by an older remembered one: Save Changes to this
/// Workspace, Reset to Saved Layout and deleting a built-in's changes drop the remembered layout
/// (so a session that ends without `on_exit` still reopens the saved layout), and a rename keeps
/// the remembered layout with its workspace.
#[test]
fn a_saved_layout_wins_over_an_older_remembered_one() {
    let data = data_dir("remember-saved");
    let mut d = Driver::launch(&data);
    d.ok("ui.panel.close", json!({"panel": "Metadata"}));
    d.app().remember_layout();
    assert!(saved_file(&data)["last"].is_object());
    drop(d);

    // save a different layout, then end without remembering (a crash): the saved layout comes back
    let mut d = Driver::launch(&data);
    assert!(!d.shows(PanelKind::Metadata));
    d.ok("ui.panel.close", json!({"panel": "Info"}));
    d.ok("ui.panel.show", json!({"panel": "Metadata"}));
    d.menu("window.workspace.saveChanges", json!({}));
    assert!(saved_file(&data)["last"].is_null(), "Save Changes drops the remembered layout");
    drop(d);
    let mut d = Driver::launch(&data);
    assert!(d.shows(PanelKind::Metadata) && !d.shows(PanelKind::Info), "the saved layout, not the remembered one");

    // Reset to Saved Layout drops it too
    d.ok("ui.panel.close", json!({"panel": "Metadata"}));
    d.app().remember_layout();
    assert!(saved_file(&data)["last"].is_object());
    d.menu("window.workspace.reset", json!({}));
    assert!(d.shows(PanelKind::Metadata));
    assert!(saved_file(&data)["last"].is_null(), "Reset to Saved Layout drops the remembered layout");

    // a rename keeps the remembered layout with its workspace; deleting the workspace drops it
    d.menu("window.workspace.saveAs", json!({"name": "Mine"}));
    d.ok("ui.panel.close", json!({"panel": "Metadata"}));
    d.app().remember_layout();
    assert_eq!(saved_file(&data)["last"]["name"], "Mine");
    d.menu("window.workspace.rename", json!({"from": "Mine", "to": "Ours"}));
    assert_eq!(saved_file(&data)["last"]["name"], "Ours");
    d.menu("window.workspace.delete", json!({"name": "Ours"}));
    assert!(saved_file(&data)["last"].is_null(), "deleting the workspace drops its remembered layout");
    let _ = std::fs::remove_dir_all(&data);
}

/// The Save as New Workspace… and Edit Workspaces… dialogs driven by their own fields and buttons.
#[test]
fn save_rename_and_delete_through_the_dialogs() {
    let data = data_dir("dialogs");
    let mut d = Driver::launch(&data);
    d.ok("ui.panel.close", json!({"panel": "Metadata"}));

    // Save as New Workspace… asks for a name
    assert_eq!(d.menu("window.workspace.saveAs", json!({}))["dialog"], "saveWorkspace");
    d.frames(2);
    d.retype("workspaces.save.name", "Mountain");
    d.snapshot("save-dialog");
    d.click("workspaces.save.ok");
    assert!(!d.has("workspaces.save.ok"), "the dialog closes");
    assert_eq!(d.workspace(), "Mountain");

    // Edit Workspaces…: a built-in can't be renamed or deleted; the user's own can
    d.menu("window.workspace.edit", json!({}));
    d.frames(2);
    let names = d.app().workspaces.saved.iter().map(|s| s.name.clone()).collect::<Vec<_>>();
    assert_eq!(names, ["Mountain"]);
    let row = |n: &str| {
        let all = filmcraft_ui_egui::dock::names(&Default::default());
        let mut all = all;
        all.push("Mountain".into());
        all.sort_by_key(|x| x.to_lowercase());
        format!("workspaces.edit.row.{}", all.iter().position(|x| x == n).unwrap())
    };
    d.click(&row("Editing"));
    d.click("workspaces.edit.delete");
    assert_eq!(d.workspace(), "Mountain", "a built-in with no saved changes can't be deleted");
    d.click(&row("Mountain"));
    d.retype("workspaces.edit.name", "Peak");
    d.snapshot("edit-dialog");
    d.click("workspaces.edit.rename");
    assert_eq!(d.workspace(), "Peak");
    assert_eq!(saved_file(&data)["saved"][0]["name"], "Peak");
    d.click("workspaces.edit.delete");
    assert_eq!(d.workspace(), "Editing");
    assert_eq!(saved_file(&data)["saved"], json!([]));
    d.frames(4); // the window shrinks to the shorter list
    d.click("workspaces.edit.close");
    assert!(d.app().ui.workspace_dialog.is_none(), "Close closes the dialog");
    let _ = std::fs::remove_dir_all(&data);
}

/// The workspace menu in the header (the workspace's name at the top of the window) offers the
/// actions of Window ▸ Workspaces under the list: Reset to Saved Layout, Save Changes to this
/// Workspace, Save as New Workspace… and Edit Workspaces….
#[test]
fn the_header_workspace_menu_saves_resets_and_opens_the_dialogs() {
    use filmcraft_ui_egui::state::WorkspaceDialog;
    let data = data_dir("header");
    let mut d = Driver::launch(&data);
    let ws = d.workspace();
    d.ok("ui.panel.close", json!({"panel": "Metadata"}));

    d.click("header.workspaceName");
    d.snapshot("header-menu");
    d.click("header.workspaces.saveChanges");
    assert!(!d.has("header.workspaces.saveChanges"), "the menu closes");
    assert_eq!(saved_file(&data)["saved"][0]["name"], json!(ws), "the layout is saved to the workspace in use");

    d.ok("ui.panel.show", json!({"panel": "Metadata"}));
    d.frames(2);
    assert!(d.shows(PanelKind::Metadata));
    d.click("header.workspaceName");
    d.click("header.workspaces.reset");
    assert!(!d.shows(PanelKind::Metadata), "Reset to Saved Layout brings back the saved layout");
    assert_eq!(d.workspace(), ws);

    d.click("header.workspaceName");
    d.click("header.workspaces.saveAs");
    assert!(matches!(d.app().ui.workspace_dialog, Some(WorkspaceDialog::SaveAs { .. })), "Save as New Workspace… asks for a name");
    d.click("workspaces.save.cancel");
    assert!(d.app().ui.workspace_dialog.is_none());

    d.click("header.workspaceName");
    d.click("header.workspaces.edit");
    assert!(matches!(d.app().ui.workspace_dialog, Some(WorkspaceDialog::Edit { .. })), "Edit Workspaces… opens its dialog");
    let _ = std::fs::remove_dir_all(&data);
}