FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
feat(ui): save your own workspaces, like Premiere
Peet Guerciofc5fcd332262
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 547cdeb41..e491e36ae 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -116,8 +116,8 @@ pub fn handle(app: &mut FilmcraftApp, ctx: &egui::Context, req: &ControlRequest)}}if let Some(w) = s("workspace") {- match crate::dock::WORKSPACES.iter().find(|x| x.eq_ignore_ascii_case(w)) {- Some(w) => app.set_workspace(w),+ match crate::dock::find(&app.workspaces, w) {+ Some(w) => app.set_workspace(&w),None => return err(format!("unknown workspace `{w}`")),}}diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rsindex 93c5458d6..1252914e3 100644--- a/crates/ui-egui/src/dock.rs+++ b/crates/ui-egui/src/dock.rs@@ -161,6 +161,73 @@ fn vsplit(size: SplitSize, a: DockNode, b: DockNode) -> DockNode {pub const WORKSPACES: [&str; 9] = ["Editing", "Assembly", "Color", "Effects", "Audio", "Captions and Graphics", "Learning", "Review", "All Panels"];+/// The user's workspaces file, beside `preferences.json` in the data directory.+pub const WORKSPACES_FILE: &str = "workspaces.json";++/// Window ▸ Workspaces: the user's own workspaces and saved changes to the built-in ones, and the+/// workspace in use (reopened at launch).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct WorkspacePrefs {+ pub saved: Vec<SavedWorkspace>,+ pub current: String,+}++/// A named layout. `layout` is a [`DockNode`] kept as JSON, so one unreadable entry (a panel a+/// newer version added) doesn't lose the others.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct SavedWorkspace {+ pub name: String,+ pub layout: serde_json::Value,+}++impl WorkspacePrefs {+ pub fn load(path: &std::path::Path) -> Self {+ std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()+ }+ pub fn save(&self, path: &std::path::Path) -> std::io::Result<()> {+ if let Some(d) = path.parent() {+ std::fs::create_dir_all(d)?;+ }+ let tmp = path.with_extension("json.tmp");+ std::fs::write(&tmp, serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?)?;+ std::fs::rename(tmp, path)+ }+}++/// A workspace's command-id key: `Captions and Graphics` → `captionsandgraphics`.+pub fn slug(name: &str) -> String {+ name.to_ascii_lowercase().replace(' ', "")+}++pub fn is_builtin(name: &str) -> bool {+ WORKSPACES.contains(&name)+}++/// Every workspace, built-in and the user's own, in one alphabetical list (Premiere's Window ▸+/// Workspaces).+pub fn names(prefs: &WorkspacePrefs) -> Vec<String> {+ let mut v: Vec<String> = WORKSPACES.iter().map(|s| s.to_string()).collect();+ for s in &prefs.saved {+ if !v.contains(&s.name) {+ v.push(s.name.clone());+ }+ }+ v.sort_by_key(|n| n.to_lowercase());+ v+}++/// The workspace called `query` (any case, spaces optional).+pub fn find(prefs: &WorkspacePrefs, query: &str) -> Option<String> {+ names(prefs).into_iter().find(|n| slug(n) == slug(query))+}++/// The saved layout of a workspace: the user's saved version, else the built-in default.+pub fn saved_layout(prefs: &WorkspacePrefs, name: &str) -> DockNode {+ prefs.saved.iter().find(|s| s.name == name).and_then(|s| serde_json::from_value(s.layout.clone()).ok()).unwrap_or_else(|| workspace(name))+}+/// The default layout of a named workspace.pub fn workspace(name: &str) -> DockNode {use PanelKind::*;diff --git a/crates/ui-egui/src/header.rs b/crates/ui-egui/src/header.rsindex 96acc8113..ed1fd3886 100644--- a/crates/ui-egui/src/header.rs+++ b/crates/ui-egui/src/header.rs@@ -150,10 +150,10 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {let area = egui::Area::new(popup_id.with("area")).order(egui::Order::Foreground).fixed_pos(anchor).show(ui.ctx(), |ui| {egui::Frame::popup(ui.style()).show(ui, |ui| {ui.set_min_width(220.0);- for w in crate::dock::WORKSPACES {+ for w in crate::dock::names(&app.workspaces) {let sel = app.ui.workspace == w;- if ui.selectable_label(sel, w).clicked() {- app.set_workspace(w);+ if ui.selectable_label(sel, &w).clicked() {+ app.set_workspace(&w);ui.ctx().data_mut(|d| d.insert_temp(popup_id, false));}}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex fc9f6fc3d..98dd04633 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -195,6 +195,11 @@ pub struct FilmcraftApp {watched_render: Option<(u64, Tick)>,/// Settings last applied to the UI (theme, tooltips, frame cache, audio device).applied_prefs: Option<filmcraft_engine::autosave::Preferences>,+ workspace_restored: bool,+ /// Window ▸ Workspaces: saved layouts ([`dock::WORKSPACES_FILE`] in the data directory).+ pub workspaces: dock::WorkspacePrefs,+ /// Workspace names and the current one, as last handed to the native menu.+ menu_workspaces: (Vec<String>, String),}pub struct GpuState {@@ -327,6 +332,8 @@ impl FilmcraftApp {session.shortcuts.register_external(menus::external_commands());let recovery = !session.recovery_candidates().is_empty();let frames = Arc::new(FrameServer::new(session.media.clone(), session.services.clone(), session.previews.clone(), FrameServer::default_workers()));+ let workspaces =+ session.prefs_path.as_ref().and_then(|p| p.parent()).map(|d| dock::WorkspacePrefs::load(&d.join(dock::WORKSPACES_FILE))).unwrap_or_default();Self {session,ui: UiState::default(),@@ -369,6 +376,9 @@ impl FilmcraftApp {gpu: None,watched_render: None,applied_prefs: None,+ workspace_restored: false,+ workspaces,+ menu_workspaces: Default::default(),}}@@ -437,12 +447,39 @@ impl FilmcraftApp {self.start_audio();}}+ if prev.is_none() && !self.workspace_restored {+ // reopen the workspace in use when the app last closed+ self.workspace_restored = true;+ if let Some(w) = dock::find(&self.workspaces, &self.workspaces.current) {+ self.set_workspace(&w);+ }+ }self.applied_prefs = Some(p);}+ fn workspaces_path(&self) -> Option<std::path::PathBuf> {+ self.session.prefs_path.as_ref().and_then(|p| p.parent()).map(|d| d.join(dock::WORKSPACES_FILE))+ }++ /// Replace the saved workspaces and write them to the data directory.+ pub fn set_workspaces(&mut self, w: dock::WorkspacePrefs) -> Result<(), String> {+ self.workspaces = w;+ match self.workspaces_path() {+ Some(p) => self.workspaces.save(&p).map_err(|e| format!("saving workspaces: {e}")),+ None => Ok(()),+ }+ }+pub fn set_workspace(&mut self, name: &str) {self.ui.workspace = name.to_string();- self.ui.dock = dock::workspace(name);+ self.ui.dock = dock::saved_layout(&self.workspaces, name);+ if self.workspaces.current != name {+ let mut next = self.workspaces.clone();+ next.current = name.to_string();+ if let Err(e) = self.set_workspaces(next) {+ self.ui.status = e;+ }+ }if name == "Color" {self.ui.show_scopes = false;}@@ -852,7 +889,9 @@ impl FilmcraftApp {// ---------------------------------------------------------------- inputfn handle_shortcuts(&mut self, ctx: &egui::Context) {- if self.bindings_rev != self.session.shortcuts.revision {+ let workspaces = (dock::names(&self.workspaces), self.ui.workspace.clone());+ if self.bindings_rev != self.session.shortcuts.revision || workspaces != self.menu_workspaces {+ self.menu_workspaces = workspaces;self.bindings = menus::bindings(self);self.bindings_rev = self.session.shortcuts.revision;let items = menus::menu_items(self);diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 14966f38e..51cedfe06 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -96,6 +96,9 @@ pub const UI_COMMANDS: &[UiCommand] = &[uic!("window.workspace.captionsandgraphics", "Captions and Graphics", ["Window", "Workspaces"], Some("Alt+Shift+6")),uic!("window.workspace.allpanels", "All Panels", ["Window", "Workspaces"], None),uic!("window.workspace.reset", "Reset to Saved Layout", ["Window", "Workspaces"], Some("Alt+Shift+0")),+ uic!("window.workspace.saveChanges", "Save Changes to this Workspace", ["Window", "Workspaces"], None),+ uic!("window.workspace.saveAs", "Save as New Workspace…", ["Window", "Workspaces"], None),+ uic!("window.workspace.edit", "Edit Workspaces…", ["Window", "Workspaces"], None),uic!("tool.selection", "Selection Tool", [], Some("V")),uic!("tool.trackSelectForward", "Track Select Forward Tool", [], Some("A")),uic!("tool.trackSelectBackward", "Track Select Backward Tool", [], Some("Shift+A")),@@ -168,15 +171,8 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Valapp.show_panel(p);return Ok(Value::Null);}- if let Some(ws) = id.strip_prefix("window.workspace.") {- if ws == "reset" {- let name = app.ui.workspace.clone();- app.set_workspace(&name);- return Ok(Value::Null);- }- let name = crate::dock::WORKSPACES.iter().find(|w| w.to_ascii_lowercase().replace(' ', "") == ws).ok_or_else(|| format!("unknown workspace `{ws}`"))?;- app.set_workspace(name);- return Ok(json!({"workspace": name}));+ if let Some(r) = crate::panels::workspaces::route(app, id, ¶ms) {+ return r;}if let Some(t) = id.strip_prefix("tool.") {let tool = Tool::from_name(t).ok_or_else(|| format!("unknown tool `{t}`"))?;@@ -408,6 +404,7 @@ pub fn menu_items(app: &FilmcraftApp) -> Vec<MenuItem> {it.enabled &= crate::panels::monitor_view::enabled(app, &it.id);}}+ crate::panels::workspaces::menu(app, &mut v);v}diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rsindex 61b9088db..3032b53d0 100644--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@ -14,6 +14,7 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {crate::panels::multicam::show_dialog(app, ctx);crate::panels::multicam::show_edit_cameras(app, ctx);crate::panels::monitor_view::dialogs(app, ctx);+ crate::panels::workspaces::dialogs(app, ctx);crate::panels::voiceover::show(app, ctx);crate::panels::remix::show(app, ctx);crate::panels::interchange_export::show(app, ctx);diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex e49d67f85..9bf62cc22 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -46,6 +46,7 @@ pub mod timeline_captions;pub mod tools;pub mod trim_monitor;pub mod voiceover;+pub mod workspaces;use egui::{Align2, Color32, Rect};use filmcraft_project::ItemId;diff --git a/crates/ui-egui/src/panels/workspaces.rs b/crates/ui-egui/src/panels/workspaces.rsnew file mode 100644index 000000000..31e3ea37e--- /dev/null+++ b/crates/ui-egui/src/panels/workspaces.rs@@ -0,0 +1,246 @@+//! Window ▸ Workspaces, like Premiere: the built-in and the user's own workspaces in one+//! alphabetical list, then Reset to Saved Layout, Save Changes to this Workspace, Save as New+//! Workspace… and Edit Workspaces… (rename, delete). Saved layouts live in `workspaces.json` beside the+//! preferences file. A built-in workspace can be changed and reset but not deleted or renamed;+//! deleting its saved changes brings back the original.++use egui::Align2;+use serde_json::{Value, json};++use crate::FilmcraftApp;+use crate::dock::{self, is_builtin, slug};+use crate::menus::MenuItem;+use crate::state::WorkspaceDialog;++/// Command ids under `window.workspace.` that are not workspace names.+const ACTIONS: [&str; 6] = ["reset", "saveChanges", "saveAs", "edit", "rename", "delete"];++/// `window.workspace.*`: switch (`window.workspace.<name>`), `reset`, `saveChanges`,+/// `saveAs {name?}` (no name: open the dialog), `edit`, `rename {from, to}`, `delete {name}`.+pub fn route(app: &mut FilmcraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {+ let ws = id.strip_prefix("window.workspace.")?;+ let arg = |k: &str| params.get(k).and_then(Value::as_str).map(str::to_string);+ let r = match ws {+ "reset" => {+ let n = app.ui.workspace.clone();+ app.set_workspace(&n);+ Ok(json!({"workspace": n}))+ }+ "saveChanges" => {+ let n = app.ui.workspace.clone();+ save(app, &n).map(|_| json!({"saved": n}))+ }+ "saveAs" => match arg("name") {+ Some(n) => save_new(app, &n),+ None => {+ app.ui.workspace_dialog = Some(WorkspaceDialog::SaveAs { name: "Untitled Workspace".into() });+ Ok(json!({"dialog": "saveWorkspace"}))+ }+ },+ "edit" => {+ app.ui.workspace_dialog = Some(WorkspaceDialog::Edit { selected: None, name: String::new() });+ Ok(json!({"dialog": "editWorkspaces", "workspaces": dock::names(&app.workspaces)}))+ }+ "rename" => rename(app, &arg("from").unwrap_or_default(), &arg("to").unwrap_or_default()),+ "delete" => delete(app, &arg("name").unwrap_or_default()),+ key => match dock::names(&app.workspaces).into_iter().find(|n| slug(n) == key) {+ Some(n) => {+ app.set_workspace(&n);+ Ok(json!({"workspace": n}))+ }+ None => Err(format!("unknown workspace `{key}`")),+ },+ };+ Some(r)+}++/// Save the current layout as the saved layout of `name`.+fn save(app: &mut FilmcraftApp, name: &str) -> Result<(), String> {+ let layout = serde_json::to_value(&app.ui.dock).map_err(|e| e.to_string())?;+ let mut next = app.workspaces.clone();+ let saved = &mut next.saved;+ match saved.iter_mut().find(|s| s.name == name) {+ Some(s) => s.layout = layout,+ None => saved.push(dock::SavedWorkspace { name: name.to_string(), layout }),+ }+ next.current = name.to_string();+ app.set_workspaces(next)+}++/// A trimmed new workspace name, or why it can't be used.+fn new_name(app: &FilmcraftApp, name: &str) -> Result<String, String> {+ let name = name.trim();+ if name.is_empty() {+ return Err("the workspace needs a name".into());+ }+ if ACTIONS.iter().any(|a| a.eq_ignore_ascii_case(&slug(name))) {+ return Err(format!("`{name}` can't be used as a workspace name"));+ }+ if let Some(n) = dock::find(&app.workspaces, name) {+ return Err(format!("a workspace named `{n}` already exists"));+ }+ Ok(name.to_string())+}++fn save_new(app: &mut FilmcraftApp, name: &str) -> Result<Value, String> {+ let name = new_name(app, name)?;+ save(app, &name)?;+ app.ui.workspace = name.clone();+ Ok(json!({"saved": name, "workspace": name}))+}++fn rename(app: &mut FilmcraftApp, from: &str, to: &str) -> Result<Value, String> {+ if is_builtin(from) {+ return Err(format!("`{from}` is a built-in workspace and keeps its name"));+ }+ if !app.workspaces.saved.iter().any(|s| s.name == from) {+ return Err(format!("unknown workspace `{from}`"));+ }+ let to = new_name(app, to)?;+ let mut next = app.workspaces.clone();+ for s in next.saved.iter_mut().filter(|s| s.name == from) {+ s.name = to.clone();+ }+ if next.current == from {+ next.current = to.clone();+ }+ app.set_workspaces(next)?;+ if app.ui.workspace == from {+ app.ui.workspace = to.clone();+ }+ Ok(json!({"renamed": from, "to": to}))+}++/// Delete a user workspace; on a built-in, drop its saved changes (back to the original).+fn delete(app: &mut FilmcraftApp, name: &str) -> Result<Value, String> {+ let mut next = app.workspaces.clone();+ let before = next.saved.len();+ next.saved.retain(|s| s.name != name);+ if next.saved.len() == before {+ return Err(if is_builtin(name) { format!("`{name}` is a built-in workspace and can't be deleted") } else { format!("unknown workspace `{name}`") });+ }+ app.set_workspaces(next)?;+ if app.ui.workspace == name {+ app.set_workspace(if is_builtin(name) { name } else { "Editing" });+ }+ Ok(if is_builtin(name) { json!({"restored": name}) } else { json!({"deleted": name}) })+}++/// Rebuild the Window ▸ Workspaces submenu: every workspace (the current one checked), then the+/// layout commands in table order.+pub fn menu(app: &FilmcraftApp, items: &mut Vec<MenuItem>) {+ let is_ws = |it: &MenuItem| it.path.len() == 2 && it.path[0] == "Window" && it.path[1] == "Workspaces";+ let Some(at) = items.iter().position(is_ws) else { return };+ let actions: Vec<MenuItem> =+ items.iter().filter(|it| is_ws(it) && it.id.strip_prefix("window.workspace.").is_some_and(|k| ACTIONS.contains(&k))).cloned().collect();+ items.retain(|it| !is_ws(it));+ let mut sub: Vec<MenuItem> = dock::names(&app.workspaces)+ .into_iter()+ .map(|n| {+ let id = format!("window.workspace.{}", slug(&n));+ MenuItem {+ label: app.ui.language.tr(&n).to_string(),+ path: vec!["Window".into(), "Workspaces".into()],+ shortcut: app.session.shortcuts.primary(&id),+ enabled: true,+ checked: Some(n == app.ui.workspace),+ id,+ }+ })+ .collect();+ sub.extend(actions);+ items.splice(at..at, sub);+}++/// Save as New Workspace… and Edit Workspaces… dialogs.+pub fn dialogs(app: &mut FilmcraftApp, ctx: &egui::Context) {+ let Some(mut d) = app.ui.workspace_dialog.clone() else { return };+ let mut elems: Vec<(String, egui::Rect, String)> = Vec::new();+ let mut push = |id: &str, r: &egui::Response, label: &str| elems.push((id.to_string(), r.rect, label.to_string()));+ let mut close = ctx.input(|i| i.key_pressed(egui::Key::Escape));+ let mut act: Option<(&str, Value)> = None;+ let names = dock::names(&app.workspaces);+ let changed: Vec<String> = app.workspaces.saved.iter().map(|s| s.name.clone()).collect();+ let title = match &d {+ WorkspaceDialog::SaveAs { .. } => "New Workspace",+ WorkspaceDialog::Edit { .. } => "Edit Workspaces",+ };+ egui::Window::new(title).collapsible(false).resizable(false).anchor(Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| match &mut d {+ WorkspaceDialog::SaveAs { name } => {+ ui.horizontal(|ui| {+ ui.label("Name:");+ let r = ui.text_edit_singleline(name);+ push("workspaces.save.name", &r, "Name");+ });+ ui.horizontal(|ui| {+ let r = ui.button("Cancel");+ push("workspaces.save.cancel", &r, "Cancel");+ close |= r.clicked();+ let r = ui.button("OK");+ push("workspaces.save.ok", &r, "OK");+ if r.clicked() {+ act = Some(("window.workspace.saveAs", json!({"name": name.clone()})));+ }+ });+ }+ WorkspaceDialog::Edit { selected, name } => {+ for (i, n) in names.iter().enumerate() {+ let r = ui.selectable_label(selected.as_ref() == Some(n), n);+ push(&format!("workspaces.edit.row.{i}"), &r, n);+ if r.clicked() {+ *selected = Some(n.clone());+ *name = n.clone();+ }+ }+ ui.separator();+ let sel = selected.clone().filter(|s| names.contains(s));+ let own = sel.as_deref().is_some_and(|s| !is_builtin(s));+ ui.horizontal(|ui| {+ ui.label("Name:");+ let r = ui.add_enabled(own, egui::TextEdit::singleline(name));+ push("workspaces.edit.name", &r, "Name");+ let r = ui.add_enabled(own && sel.as_deref() != Some(name.trim()), egui::Button::new("Rename"));+ push("workspaces.edit.rename", &r, "Rename");+ if r.clicked()+ && let Some(s) = &sel+ {+ act = Some(("window.workspace.rename", json!({"from": s, "to": name.clone()})));+ *selected = Some(name.trim().to_string());+ }+ });+ ui.horizontal(|ui| {+ // a built-in workspace can't be deleted; its saved changes can+ let restore = sel.as_deref().is_some_and(|s| is_builtin(s) && changed.iter().any(|c| c == s));+ let label = if restore { "Restore Original" } else { "Delete" };+ let r = ui.add_enabled(own || restore, egui::Button::new(label));+ push("workspaces.edit.delete", &r, label);+ if r.clicked()+ && let Some(s) = &sel+ {+ act = Some(("window.workspace.delete", json!({"name": s})));+ if own {+ *selected = None;+ name.clear();+ }+ }+ let r = ui.button("Close");+ push("workspaces.edit.close", &r, "Close");+ close |= r.clicked();+ });+ }+ });+ for (id, r, l) in elems {+ app.auto.add(&id, r, &l);+ }+ let keep_open = matches!(d, WorkspaceDialog::Edit { .. });+ app.ui.workspace_dialog = Some(d);+ if let Some((id, p)) = act {+ match route(app, id, &p) {+ Some(Err(e)) => app.ui.status = e,+ _ => close |= !keep_open,+ }+ }+ if close {+ app.ui.workspace_dialog = None;+ }+}diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 2468c94ec..04c290906 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -320,6 +320,19 @@ impl MonitorView {}}+/// Window ▸ Workspaces dialogs: Save as New Workspace… and Edit Workspaces….+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub enum WorkspaceDialog {+ SaveAs {+ name: String,+ },+ /// `selected`: the workspace picked in the list; `name`: its new name being typed.+ Edit {+ selected: Option<String>,+ name: String,+ },+}+/// Guide dialogs (View ▸ Add Guide…, Guide Templates ▸ Save Guides as Template… / Manage Guides…).#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub enum GuideDialog {@@ -454,6 +467,9 @@ pub struct UiState {/// Open guide dialog (Add Guide / Save Guides as Template / Manage Guides).#[serde(default)]pub guide_dialog: Option<GuideDialog>,+ /// Open Window ▸ Workspaces dialog.+ #[serde(default)]+ pub workspace_dialog: Option<WorkspaceDialog>,/// Edit / Clip / File menu dialog (Paste Attributes, Make Subclip, Frame Hold Options, …;/// open when Some). See `panels::clip_dialogs`.#[serde(default)]@@ -769,6 +785,7 @@ impl Default for UiState {multicam_record: true,edit_cameras: None,guide_dialog: None,+ workspace_dialog: None,clip_dialog: None,extras: Default::default(),gfx_templates: Default::default(),diff --git a/crates/ui-egui/tests/workspaces_ui.rs b/crates/ui-egui/tests/workspaces_ui.rsnew file mode 100644index 000000000..a5e4d8d9a--- /dev/null+++ b/crates/ui-egui/tests/workspaces_ui.rs@@ -0,0 +1,280 @@+//! 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()+}++#[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",+ "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));++ // 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"));++ // 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);+}++#[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);+}