From 6be3259f6c2a24607a70cbbcade8d1025ec8b47e Mon Sep 17 00:00:00 2001 From: PiJellyPin Date: Wed, 18 Nov 2026 08:33:49 +0100 Subject: [PATCH 1/4] works looks like it works --- crates/engine/src/commands.rs | 1 + crates/engine/src/file_cmds.rs | 32 ++- crates/engine/src/lib.rs | 1 + crates/engine/src/material_preview.rs | 2 +- crates/engine/src/save_all_commands.rs | 49 ++++ crates/engine/src/session.rs | 3 + crates/engine/tests/it/material_preview.rs | 13 + crates/engine/tests/it/open_documents.rs | 51 ++++ crates/ui-egui/src/autosave_versions.rs | 61 ++++ crates/ui-egui/src/cook.rs | 46 ++- crates/ui-egui/src/function/input.rs | 9 +- crates/ui-egui/src/function/render.rs | 2 +- crates/ui-egui/src/graph/canvas.rs | 2 +- crates/ui-egui/src/graph/graph_camera.rs | 5 +- crates/ui-egui/src/graph/input.rs | 18 +- crates/ui-egui/src/help_links.rs | 38 +++ crates/ui-egui/src/home_screen.rs | 146 ++++++++++ crates/ui-egui/src/i18n/ar.rs | 123 +++++++++ crates/ui-egui/src/lib.rs | 9 + crates/ui-egui/src/material_craft_app.rs | 28 +- crates/ui-egui/src/menus.rs | 68 ++++- crates/ui-egui/src/native_dialogs.rs | 13 + crates/ui-egui/src/new_graph_dialog.rs | 209 ++++++++++++++ crates/ui-egui/src/node_shortcuts.rs | 82 ++++++ crates/ui-egui/src/pattern/canvas.rs | 2 +- crates/ui-egui/src/plugin_manager.rs | 55 ++++ crates/ui-egui/src/preferences.rs | 144 ++++++++++ .../ui-egui/src/preferences/general_page.rs | 74 +++++ crates/ui-egui/src/preferences/graph_page.rs | 20 ++ .../ui-egui/src/preferences/library_page.rs | 36 +++ .../src/preferences/preferences_page.rs | 34 +++ .../src/preferences/preferences_state.rs | 16 ++ .../ui-egui/src/preferences/projects_page.rs | 41 +++ .../ui-egui/src/preferences/shortcuts_page.rs | 138 +++++++++ crates/ui-egui/src/preferences/view3d_page.rs | 37 +++ crates/ui-egui/src/shell/modality.rs | 10 +- crates/ui-egui/src/state/prefs.rs | 44 +++ crates/ui-egui/src/state/ui_state.rs | 31 ++- crates/ui-egui/src/state/windows.rs | 1 + crates/ui-egui/src/template_card.rs | 90 ++++++ crates/ui-egui/src/toolbar.rs | 6 +- crates/ui-egui/src/view2d/viewport.rs | 2 +- crates/ui-egui/src/view3d/navigation.rs | 2 +- crates/ui-egui/src/windows.rs | 261 +++--------------- crates/ui-egui/src/windows.test.rs | 6 +- crates/ui-egui/tests/it/main.rs | 3 + crates/ui-egui/tests/it/menu_bar.rs | 72 +++++ crates/ui-egui/tests/it/new_graph_dialog.rs | 65 +++++ crates/ui-egui/tests/it/preferences_window.rs | 96 +++++++ crates/ui-egui/tests/snapshot.rs | 18 +- .../tests/snapshot/menus_and_preferences.rs | 48 ++++ docs/control-protocol.md | 3 +- docs/target-app-parity.md | 5 +- 53 files changed, 2079 insertions(+), 292 deletions(-) create mode 100644 crates/engine/src/save_all_commands.rs create mode 100644 crates/ui-egui/src/autosave_versions.rs create mode 100644 crates/ui-egui/src/help_links.rs create mode 100644 crates/ui-egui/src/home_screen.rs create mode 100644 crates/ui-egui/src/new_graph_dialog.rs create mode 100644 crates/ui-egui/src/node_shortcuts.rs create mode 100644 crates/ui-egui/src/plugin_manager.rs create mode 100644 crates/ui-egui/src/preferences.rs create mode 100644 crates/ui-egui/src/preferences/general_page.rs create mode 100644 crates/ui-egui/src/preferences/graph_page.rs create mode 100644 crates/ui-egui/src/preferences/library_page.rs create mode 100644 crates/ui-egui/src/preferences/preferences_page.rs create mode 100644 crates/ui-egui/src/preferences/preferences_state.rs create mode 100644 crates/ui-egui/src/preferences/projects_page.rs create mode 100644 crates/ui-egui/src/preferences/shortcuts_page.rs create mode 100644 crates/ui-egui/src/preferences/view3d_page.rs create mode 100644 crates/ui-egui/src/template_card.rs create mode 100644 crates/ui-egui/tests/it/menu_bar.rs create mode 100644 crates/ui-egui/tests/it/new_graph_dialog.rs create mode 100644 crates/ui-egui/tests/it/preferences_window.rs create mode 100644 crates/ui-egui/tests/snapshot/menus_and_preferences.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index d2f2450c..2a682496 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -89,6 +89,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::view_cmds::specs()); v.extend(crate::display_cmds::specs()); v.extend(crate::view3d_commands::specs()); + v.extend(crate::save_all_commands::specs()); v.extend(crate::material_preview_commands::specs()); v.extend(crate::wire_cmds::specs()); v diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 81179615..2ae6f4e1 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -6,7 +6,7 @@ use serde_json::{Value as J, json}; use materialcraft_core::{Package, Resource, ResourceBytes}; use materialcraft_formats::{Depth, encode, output_name}; -use crate::commands::{CommandSpec, always, bad, has_graph, has_package, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, boolp, has_graph, has_package, strp, u64p}; use crate::samples::{TEMPLATES, template}; use crate::{ExportRequest, Result, Session, cmd}; @@ -17,7 +17,7 @@ pub(crate) fn specs() -> Vec { "Graph...", ["File", "New"], Some("Ctrl+N"), - "{name?, folder?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it", + "{name?, folder?, kind? (material|function), template? (see graph.templates), size? (px, power of two), height? (px, power of two; default size), newPackage? (create the graph in a new package)} adds a new graph to the package and opens it", always, new_graph ), @@ -69,26 +69,38 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result { } else { TEMPLATES.iter().find(|entry| entry.0 == template_id).map_or("Graph", |entry| entry.1) }; - let size = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192); - let log2 = 63 - size.leading_zeros(); + let width = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192); + let height = u64p(parameters, "height").unwrap_or(width).clamp(16, 8192); + let [width_log2, height_log2] = [width, height].map(|side| 63 - side.leading_zeros()); let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_")); let folder = strp(parameters, "folder").unwrap_or(""); - crate::folder_path::require(&session.pkg, folder)?; + let in_new_package = boolp(parameters, "newPackage").unwrap_or(false); + if in_new_package && !folder.is_empty() { + return Err(bad("file.new", "a new package has no folders yet: leave `folder` out")); + } + if !in_new_package { + crate::folder_path::require(&session.pkg, folder)?; + } crate::folder_path::require_graph_folder(folder)?; let base = crate::folder_path::name(&base)?; - let name = crate::folder_path::unique(&session.pkg, folder, base); let mut graph = if kind == materialcraft_core::GraphKind::Function { - let mut graph = materialcraft_core::Graph::new(&name); + let mut graph = materialcraft_core::Graph::new(base); graph.function = Some(materialcraft_core::FunctionGraph::default()); graph } else { - template(template_id, &name, log2)? + template(template_id, base, width_log2)? }; - graph.folder = folder.into(); - if !session.has_package() { + + // Everything is checked before a package opens, so a refused request leaves the workspace as it was + if in_new_package || !session.has_package() { session.open_package(Package::new("Untitled package"), None)?; } + + let name = crate::folder_path::unique(&session.pkg, folder, base); + graph.name = name.clone(); + graph.size = [width_log2, height_log2]; + graph.folder = folder.into(); session.edit("New graph", |session| { session.pkg.graphs.push(graph); session.graph = session.pkg.graphs.len() - 1; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0361306a..176b2860 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -42,6 +42,7 @@ mod package_file_commands; mod preview_cook; mod preview_fingerprint; mod resource_commands; +mod save_all_commands; pub use material_preview::MaterialPreview; pub use material_source::MaterialSource; pub use open_document::OpenDocument; diff --git a/crates/engine/src/material_preview.rs b/crates/engine/src/material_preview.rs index ef500a82..65f6f95e 100644 --- a/crates/engine/src/material_preview.rs +++ b/crates/engine/src/material_preview.rs @@ -78,7 +78,7 @@ impl Session { /// Show a material graph on open, retaining the material while editing functions pub(crate) fn open_material_preview(&mut self) { - if self.graph().is_ok_and(|graph| graph.function.is_none()) { + if self.view_outputs_on_open && self.graph().is_ok_and(|graph| graph.function.is_none()) { self.material_preview = MaterialPreview::for_graph(&self.pkg, self.graph); } } diff --git a/crates/engine/src/save_all_commands.rs b/crates/engine/src/save_all_commands.rs new file mode 100644 index 00000000..cb9aa562 --- /dev/null +++ b/crates/engine/src/save_all_commands.rs @@ -0,0 +1,49 @@ +//! File ▸ Save all: write every open package that has unsaved edits to its own file + +use crate::commands::{CommandSpec, has_package}; +use crate::{Result, Session, cmd}; +use serde_json::{Value, json}; + +/// Register the command that saves every modified package +pub(crate) fn specs() -> Vec { + vec![cmd!( + "file.saveAll", + "Save all", + ["File"], + None, + "{} saves every modified package that has a file; returns the saved paths, the packages that still need Save as (no file yet), and any that failed", + has_package, + save_all + )] +} + +/// Save each modified package in turn, then make the package that was active the active one again +fn save_all(session: &mut Session, _parameters: &Value) -> Result { + let active = session.document_id; + let modified: Vec<(u64, String, Option)> = session + .open_packages() + .into_iter() + .filter(|(_, _, _, modified)| *modified) + .map(|(id, package, path, _)| (id, package.name.clone(), path.map(str::to_string))) + .collect(); + + let (mut saved, mut without_file, mut failed) = (Vec::new(), Vec::new(), Vec::new()); + for (id, name, path) in modified { + // A package from a library alias or with no file yet needs a name chosen in Save as + if path.as_deref().is_none_or(|path| path.contains("://")) { + without_file.push(name); + continue; + } + + let result = session.activate_document(id).and_then(|()| crate::execute(session, "file.save", &json!({}))); + match result { + Ok(reply) => saved.push(reply["path"].clone()), + Err(error) => failed.push(json!({"package": name, "error": error.to_string()})), + } + } + + if session.document_id != active { + session.activate_document(active)?; + } + Ok(json!({"saved": saved, "withoutFile": without_file, "failed": failed})) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 5e9f4b6b..64c8f51d 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -68,6 +68,8 @@ pub struct Session { pub view3d: View3d, /// The 3D view a reset goes back to, when the user saved one as the default pub default_view3d: Option, + /// Opening a material graph shows its outputs in the 3D view (Preferences ▸ Graph) + pub view_outputs_on_open: bool, pub material_preview: crate::MaterialPreview, pub(crate) cooked_graph: Option, pub(crate) material_cooked: std::collections::BTreeMap, @@ -143,6 +145,7 @@ impl Session { view2d: View2d::default(), view3d: View3d::default(), default_view3d: None, + view_outputs_on_open: true, preview_size: Some(512), camera: CameraPrefs::default(), history_prefs: crate::HistoryPrefs::default(), diff --git a/crates/engine/tests/it/material_preview.rs b/crates/engine/tests/it/material_preview.rs index 52b081dc..c23e6e9a 100644 --- a/crates/engine/tests/it/material_preview.rs +++ b/crates/engine/tests/it/material_preview.rs @@ -270,3 +270,16 @@ fn extracted_graph_outputs_remain_unclassified() { let output = graph.nodes.iter().find(|node| node.def == "output").unwrap(); assert_eq!(materialcraft_engine::eval::output_usage(output), "any"); } + +#[test] +fn opening_a_graph_shows_its_outputs_only_while_the_preference_is_on() { + let mut session = new_session(); + let shown = session.material_preview.clone(); + session.view_outputs_on_open = false; + execute(&mut session, "file.new", &json!({"template": "pbr", "name": "Quiet"})).unwrap(); + assert_eq!(session.material_preview, shown, "the 3D view keeps what it showed"); + + session.view_outputs_on_open = true; + execute(&mut session, "file.new", &json!({"template": "pbr", "name": "Shown"})).unwrap(); + assert_eq!(session.material_preview.graph, Some(session.graph)); +} diff --git a/crates/engine/tests/it/open_documents.rs b/crates/engine/tests/it/open_documents.rs index 944dd153..e61b9660 100644 --- a/crates/engine/tests/it/open_documents.rs +++ b/crates/engine/tests/it/open_documents.rs @@ -134,3 +134,54 @@ fn saving_a_new_file_preserves_its_identity_across_path_aliases() { } std::fs::remove_dir_all(directory).unwrap(); } + +#[test] +fn save_all_writes_every_modified_package_with_a_file_and_lists_the_rest() { + let folder = std::env::temp_dir().join(format!("materialcraft-save-all-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let first_path = folder.join("first.sbs"); + let second_path = folder.join("second.sbs"); + + let mut session = Session::new(Package::new("First")); + execute(&mut session, "file.save", &json!({"path": first_path.to_str().unwrap()})).unwrap(); + execute(&mut session, "file.new", &json!({"template": "empty"})).unwrap(); + let first = session.document_id; + + execute(&mut session, "file.newPackage", &json!({"name": "Second"})).unwrap(); + execute(&mut session, "file.save", &json!({"path": second_path.to_str().unwrap()})).unwrap(); + let unchanged = std::fs::metadata(&second_path).unwrap().modified().unwrap(); + + execute(&mut session, "file.newPackage", &json!({"name": "Unsaved"})).unwrap(); + execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap(); + let active = session.document_id; + + let reply = execute(&mut session, "file.saveAll", &json!({})).unwrap(); + + assert_eq!(reply["saved"], json!([first_path.to_str().unwrap()])); + assert_eq!(reply["withoutFile"], json!(["Unsaved"])); + assert_eq!(reply["failed"], json!([])); + assert_eq!(session.document_id, active, "the package that was active stays active"); + assert!(session.open_packages().iter().any(|entry| entry.0 == first && !entry.3), "the first package is saved"); + assert!(session.open_packages().iter().any(|entry| entry.0 == active && entry.3), "the package without a file keeps its edits"); + assert_eq!(std::fs::metadata(&second_path).unwrap().modified().unwrap(), unchanged, "an unmodified package is not written again"); + + std::fs::remove_dir_all(&folder).unwrap(); +} + +#[test] +fn a_new_graph_can_start_its_own_package_and_take_any_size() { + let mut session = Session::new(Package::new("Existing")); + let existing = session.document_id; + + let reply = execute(&mut session, "file.new", &json!({"template": "pbr", "name": "Tall", "size": 512, "height": 2048, "newPackage": true})).unwrap(); + + assert_eq!(reply["name"], "Tall"); + assert_ne!(session.document_id, existing); + assert_eq!(session.open_packages().len(), 2); + assert_eq!(session.graph().unwrap().size, [9, 11]); + + // A refused request opens nothing + assert!(execute(&mut session, "file.new", &json!({"template": "invalid", "newPackage": true})).is_err()); + assert!(execute(&mut session, "file.new", &json!({"folder": "Missing", "newPackage": true})).is_err()); + assert_eq!(session.open_packages().len(), 2); +} diff --git a/crates/ui-egui/src/autosave_versions.rs b/crates/ui-egui/src/autosave_versions.rs new file mode 100644 index 00000000..26ec52d3 --- /dev/null +++ b/crates/ui-egui/src/autosave_versions.rs @@ -0,0 +1,61 @@ +//! The autosaved copies of a package: numbered files in the autosave folder, the newest kept + +use std::path::{Path, PathBuf}; + +const EXTENSION: &str = "mcraft"; + +/// The file name stem of `package`'s copies, before the copy's number +fn prefix(package: &str) -> String { + format!("{}-autosave-", materialcraft_engine::formats::safe_file_name(package)) +} + +/// The numbers of `package`'s copies in `folder`, lowest first +fn numbers(folder: &Path, package: &str) -> Vec { + let prefix = prefix(package); + let Ok(entries) = std::fs::read_dir(folder) else { return Vec::new() }; + + let mut numbers: Vec = entries + .filter_map(|entry| entry.ok()?.file_name().into_string().ok()) + .filter_map(|name| name.strip_prefix(&prefix)?.strip_suffix(&format!(".{EXTENSION}"))?.parse().ok()) + .collect(); + numbers.sort_unstable(); + numbers +} + +/// Where the next copy of `package` goes: one number past the newest +pub(crate) fn next_path(folder: &Path, package: &str) -> PathBuf { + let next = numbers(folder, package).last().map_or(1, |newest| newest.saturating_add(1)); + folder.join(format!("{}{next}.{EXTENSION}", prefix(package))) +} + +/// Delete all but the newest `keep` copies of `package`; returns how many were deleted +pub(crate) fn prune(folder: &Path, package: &str, keep: u32) -> usize { + let numbers = numbers(folder, package); + let surplus = numbers.len().saturating_sub(keep.max(1) as usize); + + numbers.iter().take(surplus).filter(|number| std::fs::remove_file(folder.join(format!("{}{number}.{EXTENSION}", prefix(package)))).is_ok()).count() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn copies_are_numbered_and_only_the_newest_are_kept() { + let folder = std::env::temp_dir().join(format!("materialcraft-autosave-versions-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + + for _ in 0..5 { + std::fs::write(next_path(&folder, "Wood"), b"copy").unwrap(); + } + std::fs::write(next_path(&folder, "Metal"), b"copy").unwrap(); + assert_eq!(next_path(&folder, "Wood"), folder.join("Wood-autosave-6.mcraft")); + + assert_eq!(prune(&folder, "Wood", 2), 3); + assert_eq!(numbers(&folder, "Wood"), vec![4, 5]); + assert_eq!(numbers(&folder, "Metal"), vec![1], "another package's copies stay"); + assert_eq!(prune(&folder, "Wood", 0), 1, "at least one copy is always kept"); + + std::fs::remove_dir_all(&folder).unwrap(); + } +} diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index d9abab25..d61fee04 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -61,12 +61,43 @@ pub struct Cooker { pub started: Option, /// `Session::cook_epoch` when the running cook started epoch: u64, + /// Tools ▸ Suspend engine: nothing cooks until it is resumed + pub suspended: bool, + /// Tools ▸ Cancel rendering stopped the running cook: it does not start again until the next edit + stopped_by_user: bool, } impl Cooker { pub fn busy(&self) -> bool { self.rx.is_some() } + + /// Ask the running cook to stop between nodes + fn stop(&self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(flag) = &self.cancel { + flag.store(true, std::sync::atomic::Ordering::Relaxed); + } + } +} + +/// Tools ▸ Cancel rendering: stop the running cook; the next edit cooks again +pub fn cancel(app: &mut MaterialCraftApp) { + if app.cooker.busy() { + app.cooker.stop(); + app.cooker.stopped_by_user = true; + } + app.session.dirty = false; +} + +/// Tools ▸ Suspend engine: stop cooking until it is chosen again, then cook what changed meanwhile +pub fn toggle_suspended(app: &mut MaterialCraftApp) { + app.cooker.suspended = !app.cooker.suspended; + if app.cooker.suspended { + app.cooker.stop(); + } else { + app.session.dirty = true; + } } /// Collect a finished cook and start the next one if the graph changed @@ -81,11 +112,12 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { app.cooker.cancel = None; } match result { - // A stopped cook is partial: keep the previous results and cook again + // A stopped cook is partial: keep the previous results and cook again, unless the user stopped it Ok(c) if c.cancelled() => { - if app.cooker.epoch == app.session.cook_epoch { + if app.cooker.epoch == app.session.cook_epoch && !app.cooker.stopped_by_user { app.session.dirty = true; } + app.cooker.stopped_by_user = false; } Ok(c) => { if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch { @@ -98,12 +130,8 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { ctx.request_repaint(); } Err(TryRecvError::Empty) if app.session.dirty => { - // Stop between nodes, but wait for this worker to finish before starting - // another. A slow node must not accumulate workers during rapid edits - #[cfg(not(target_arch = "wasm32"))] - if let Some(flag) = &app.cooker.cancel { - flag.store(true, std::sync::atomic::Ordering::Relaxed); - } + // Stop between nodes and wait for this worker: rapid edits must not pile up workers + app.cooker.stop(); ctx.request_repaint_after(std::time::Duration::from_millis(16)); return; } @@ -124,7 +152,7 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { } } } - if app.session.dirty { + if app.session.dirty && !app.cooker.suspended { start(app, ctx.input(|i| i.time)); ctx.request_repaint(); } diff --git a/crates/ui-egui/src/function/input.rs b/crates/ui-egui/src/function/input.rs index 4c8273c3..1be76454 100644 --- a/crates/ui-egui/src/function/input.rs +++ b/crates/ui-egui/src/function/input.rs @@ -120,7 +120,7 @@ pub(super) fn handle( Some(FunctionDrag::Wire(from)) => match pointer.map(|pointer| (pointer, near(pointer))) { Some((_, Some((to, Some(input))))) if from != to => editor.edit(app, FunctionEdit::Connect { from, to, input }, false), // Dropped on empty canvas: search for a node that takes the wire - Some((pointer, None)) if canvas_bounds.contains(pointer) => { + Some((pointer, None)) if canvas_bounds.contains(pointer) && app.ui.prefs.wire_drop_opens_node_search => { editor.search = Some(FunctionSearch::at(camera.to_graph(pointer), Some(SearchWire::From(from)))); } _ => {} @@ -128,7 +128,7 @@ pub(super) fn handle( Some(FunctionDrag::InputWire(to, input)) => match pointer.map(|pointer| (pointer, near(pointer))) { Some((_, Some((from, None)))) if from != to => editor.edit(app, FunctionEdit::Connect { from, to, input }, false), // Dropped on empty canvas: search for a node whose output feeds the input - Some((pointer, None)) if canvas_bounds.contains(pointer) => { + Some((pointer, None)) if canvas_bounds.contains(pointer) && app.ui.prefs.wire_drop_opens_node_search => { editor.search = Some(FunctionSearch::at(camera.to_graph(pointer), Some(SearchWire::To(to, input)))); } _ => {} @@ -189,7 +189,10 @@ pub(super) fn handle( // Space or Tab over the canvas, or a double-click on empty canvas, searches for a node to add // Tab moves focus between widgets, so it waits only for text fields and focus held before this frame let space = !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::Space)); - let tab = !app.graph.keyboard_was_focused && !ui.ctx().text_edit_focused() && ui.input(|input| input.key_pressed(egui::Key::Tab)); + let tab = app.ui.prefs.tab_opens_node_search + && !app.graph.keyboard_was_focused + && !ui.ctx().text_edit_focused() + && ui.input(|input| input.key_pressed(egui::Key::Tab)); let keys = space || tab; let on_node = pointer.is_some_and(|pointer| geometry.rects.iter().any(|(_, bounds)| bounds.contains(pointer))); let double_click = response.double_clicked() && !on_wire && !on_annotation && !on_node && pointer.and_then(near).is_none(); diff --git a/crates/ui-egui/src/function/render.rs b/crates/ui-egui/src/function/render.rs index ad73c119..d30c3e77 100644 --- a/crates/ui-egui/src/function/render.rs +++ b/crates/ui-egui/src/function/render.rs @@ -55,7 +55,7 @@ pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: } let mut camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; - camera.zoom_from_input(ui, canvas_bounds); + camera.zoom_from_input(ui, canvas_bounds, app.ui.prefs.zoom_direction()); editor.pan = camera.pan; editor.zoom = camera.zoom; diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 9d607d8f..86543d58 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -66,7 +66,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // Background and grid painter.rect_filled(rect, 0.0, Color32::from_rgb(0x2b, 0x2d, 0x31)); let mut camera = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; - camera.zoom_from_input(ui, rect); + camera.zoom_from_input(ui, rect, app.ui.prefs.zoom_direction()); app.ui.graph_camera = camera.state(); super::grid::paint(&painter, &camera, rect); let pointer = context.input(|input| input.pointer.hover_pos()); diff --git a/crates/ui-egui/src/graph/graph_camera.rs b/crates/ui-egui/src/graph/graph_camera.rs index 472969c6..9b3bbdcc 100644 --- a/crates/ui-egui/src/graph/graph_camera.rs +++ b/crates/ui-egui/src/graph/graph_camera.rs @@ -31,7 +31,8 @@ impl GraphCamera { Self { origin: view.min, pan, zoom } } - pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect) { + /// Zoom around the pointer by the wheel or a pinch; `direction` is -1 when the preferences invert the zoom + pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect, direction: f32) { self.zoom = self.zoom.clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); if !ui.rect_contains_pointer(view) { return; @@ -39,7 +40,7 @@ impl GraphCamera { let Some(pointer) = ui.input(|input| input.pointer.hover_pos()).filter(|pointer| view.contains(*pointer)) else { return }; - let scroll = ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0); + let scroll = direction * ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0); if scroll.is_finite() && scroll != 0.0 { let before = self.to_graph(pointer); self.zoom = (self.zoom * (scroll * 0.0025).exp()).clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs index 49ad962d..e536bbc5 100644 --- a/crates/ui-egui/src/graph/input.rs +++ b/crates/ui-egui/src/graph/input.rs @@ -146,6 +146,7 @@ pub(super) fn handle( app.run("graph.disconnect", json!({"to": node.0, "toPort": port})); } else if let Some(position) = pointer && rect.contains(position) + && app.ui.prefs.wire_drop_opens_node_search { open_search(app, &context, camera.to_graph(position), Some(from)); } @@ -158,6 +159,7 @@ pub(super) fn handle( } else if let Some(position) = pointer && rect.contains(position) && nearest_port(&app.graph.ports, position, 12.0).is_none() + && app.ui.prefs.wire_drop_opens_node_search { // Dropped on empty canvas: search for a node whose output feeds the input open_search_to(app, &context, camera.to_graph(position), to); @@ -275,12 +277,26 @@ pub(super) fn handle( let hovered = pointer.is_some_and(|position| rect.contains(position)); if hovered && app.graph.search.is_none() && !crate::shell::modality::Modality::capture(app, &context).is_blocked() { let space = !context.egui_wants_keyboard_input() && context.input(|input| input.key_pressed(egui::Key::Space)); - let tab = !app.graph.keyboard_was_focused && !context.text_edit_focused() && context.input(|input| input.key_pressed(egui::Key::Tab)); + let tab = app.ui.prefs.tab_opens_node_search + && !app.graph.keyboard_was_focused + && !context.text_edit_focused() + && context.input(|input| input.key_pressed(egui::Key::Tab)); if (space || tab) && let Some(position) = pointer { open_search(app, &context, camera.to_graph(position), None); } + + // A node creation shortcut adds its entry under the pointer + let typing = context.egui_wants_keyboard_input(); + if !typing + && let Some(position) = pointer + && let Some(entry) = context.input(|input| crate::node_shortcuts::pressed(&app.ui.prefs.node_shortcuts, input)) + { + let under_pointer = camera.to_graph(position); + let at = [under_pointer.x - NODE_W * 0.5, under_pointer.y - 20.0]; + app.run("library.add", json!({"entry": entry, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid})); + } if GraphCamera::frame_key(ui, rect) { let selected = !app.session.selection.is_empty(); frame(app, rect, selected); diff --git a/crates/ui-egui/src/help_links.rs b/crates/ui-egui/src/help_links.rs new file mode 100644 index 00000000..d9302735 --- /dev/null +++ b/crates/ui-egui/src/help_links.rs @@ -0,0 +1,38 @@ +//! Where the Help menu's links go: the ArtCraft website, the Craft wiki and this app's repository + +/// Help menu ids and the pages they open +pub(crate) const HELP_LINKS: &[(&str, &str)] = &[ + ("ui.help.tutorials", "https://getartcraft.com/tutorials"), + ("ui.help.releaseNotes", "https://github.com/storytold/materialcraft/releases"), + ("ui.help.requirements", "https://craft.wiki/apps/materialcraft/install-update/"), + ("ui.help.docs", "https://craft.wiki/apps/materialcraft/overview/"), + ("ui.help.automation", "https://github.com/storytold/materialcraft/blob/main/docs/control-protocol.md"), + ("ui.help.troubleshooting", "https://craft.wiki/apps/materialcraft/troubleshooting/"), + ("ui.help.discord", "https://discord.gg/artcraft"), + ("ui.help.bug", "https://github.com/storytold/materialcraft/issues/new"), + ("ui.help.feedback", "https://getartcraft.com/support"), + ("ui.help.apps", "https://getartcraft.com/apps"), + ("ui.help.website", "https://getartcraft.com/apps/materialcraft"), + ("ui.help.news", "https://getartcraft.com/news"), +]; + +/// The page a Help menu id opens +pub(crate) fn url(id: &str) -> Option<&'static str> { + HELP_LINKS.iter().find(|(link, _)| *link == id).map(|(_, url)| *url) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_link_is_an_https_page_of_artcraft_or_this_repository() { + for (id, url) in HELP_LINKS { + let host = url.strip_prefix("https://").and_then(|rest| rest.split('/').next()).unwrap_or_default(); + assert!(["getartcraft.com", "craft.wiki", "github.com", "discord.gg"].contains(&host), "{id}: {url}"); + assert!(!url.contains("github.com") || url.contains("/storytold/materialcraft"), "{id}: {url}"); + } + assert_eq!(url("ui.help.docs"), Some("https://craft.wiki/apps/materialcraft/overview/")); + assert_eq!(url("ui.about"), None); + } +} diff --git a/crates/ui-egui/src/home_screen.rs b/crates/ui-egui/src/home_screen.rs new file mode 100644 index 00000000..a56889fb --- /dev/null +++ b/crates/ui-egui/src/home_screen.rs @@ -0,0 +1,146 @@ +//! Help ▸ Home screen, also shown at startup: start a graph from a template, open a package or a +//! recent one, and find the tutorials, documentation and community + +use egui::{RichText, Ui, vec2}; +use egui_phosphor::regular as icon; + +use crate::MaterialCraftApp; +use crate::i18n::tr; +use crate::shell::modality::Modality; +use crate::template_card::{CARD_SIZE, TemplateCard}; +use crate::theme::Tokens; + +const WINDOW_SIZE: egui::Vec2 = vec2(1000.0, 620.0); +const RAIL_WIDTH: f32 = 220.0; +const CARD_GAP: f32 = 14.0; +/// The links down the left side, under their headings: (heading, [(label, Help menu id)]) +const LINKS: [(&str, &[(&str, &str)]); 2] = [ + ("Learn", &[("Tutorials", "ui.help.tutorials"), ("Documentation", "ui.help.docs"), ("What's new", "ui.help.news")]), + ("Community", &[("Community (Discord)", "ui.help.discord"), ("Report a bug", "ui.help.bug"), ("All Craft apps", "ui.help.apps")]), +]; + +pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { + let mut open = true; + crate::windows::modal(ctx, "home", tr("Home"), &mut open, WINDOW_SIZE, |ui| { + ui.set_min_size(WINDOW_SIZE); + let whole = ui.available_rect_before_wrap(); + let rail = egui::Rect::from_min_max(whole.min, egui::pos2(whole.left() + RAIL_WIDTH, whole.bottom())); + let content = egui::Rect::from_min_max(egui::pos2(rail.right() + 24.0, whole.top()), whole.max); + + left_rail(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(rail))); + start(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(content))); + ui.advance_cursor_after_rect(whole); + }); + if !open { + app.ui.windows.home = false; + } +} + +/// The app's name, the two ways to begin, the links and the startup switch +fn left_rail(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let modality = Modality::capture(app, ui.ctx()); + ui.painter().rect_filled(ui.max_rect(), 6.0, tokens.row); + ui.add_space(12.0); + + ui.horizontal(|ui| { + ui.add_space(12.0); + ui.vertical(|ui| { + ui.label(RichText::new("MaterialCraft").size(22.0).strong().color(tokens.accent)); + ui.label(RichText::new(format!("{} {}", tr("Version"), materialcraft_engine::VERSION)).small().color(tokens.text_dim)); + ui.add_space(16.0); + + let width = RAIL_WIDTH - 24.0; + let new_graph = crate::widgets::primary_button(ui, &format!("{} {}", icon::FILE_PLUS, tr("New graph..."))); + if ui.add_enabled_ui(!modality.is_blocked(), |ui| ui.add_sized([width, 30.0], new_graph)).inner.clicked() { + app.ui.windows.home = false; + crate::new_graph_dialog::open(app, materialcraft_engine::core::GraphKind::Material); + } + let open_package = egui::Button::new(format!("{} {}", icon::FOLDER_OPEN, tr("Open package..."))); + if ui.add_enabled_ui(modality.allows("file.open"), |ui| ui.add_sized([width, 30.0], open_package)).inner.clicked() { + app.ui.windows.home = false; + crate::menus::invoke(app, ui.ctx(), "file.open"); + } + + for (heading, links) in LINKS { + ui.add_space(18.0); + ui.label(RichText::new(tr(heading).to_uppercase()).small().strong().color(tokens.text_dim)); + for (label, id) in links { + if let Some(url) = crate::help_links::url(id) { + ui.hyperlink_to(tr(label), url); + } + } + } + }); + }); + + let bottom = egui::Rect::from_min_max(egui::pos2(ui.max_rect().left() + 12.0, ui.max_rect().bottom() - 32.0), ui.max_rect().right_bottom()); + ui.new_child(egui::UiBuilder::new().max_rect(bottom)).checkbox(&mut app.ui.prefs.show_home, tr("Show at startup")); +} + +/// The welcome, the template cards and the recent packages +fn start(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let free = !Modality::capture(app, ui.ctx()).is_blocked(); + ui.label(RichText::new(tr("Welcome to MaterialCraft")).size(20.0).strong().color(tokens.text_strong)); + ui.label( + RichText::new(tr("Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.")) + .color(tokens.text_dim), + ); + ui.add_space(14.0); + + ui.label(RichText::new(tr("Start from a template")).size(15.0).strong()); + ui.add_space(6.0); + let cards = crate::template_card::cards(); + let columns = ((ui.available_width() + CARD_GAP) / (CARD_SIZE.x + CARD_GAP)).floor().max(1.0) as usize; + for row in cards.chunks(columns) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = CARD_GAP; + if !free { + ui.disable(); + } + for card in row { + let preview = crate::windows::template_preview(ui.ctx(), card.id); + if crate::template_card::show(ui, card, false, preview).clicked() && free { + begin_with(app, card); + } + } + }); + ui.add_space(CARD_GAP); + } + + ui.add_space(6.0); + ui.label(RichText::new(tr("Recent packages")).size(15.0).strong()); + recent(app, ui); +} + +/// A card opens the New graph dialog with its template chosen +fn begin_with(app: &mut MaterialCraftApp, card: &TemplateCard) { + app.ui.windows.home = false; + crate::new_graph_dialog::open(app, card.kind); + app.ui.new_graph_template = card.id.to_string(); +} + +/// The recently opened packages, newest first: the file's name, then where it is +fn recent(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + if app.ui.recent.is_empty() { + ui.label(RichText::new(tr("No recent packages")).color(tokens.text_dim)); + return; + } + + #[cfg(not(target_arch = "wasm32"))] + egui::ScrollArea::vertical().id_salt("home-recent").show(ui, |ui| { + let free = !Modality::capture(app, ui.ctx()).is_blocked(); + for path in app.ui.recent.clone() { + let file = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |name| name.to_string_lossy().into_owned()); + let text = egui::text::LayoutJob::simple_singleline(format!("{} {file}", icon::PACKAGE), egui::FontId::proportional(13.0), tokens.text); + let row = ui.add_enabled(free, egui::Button::new(text).frame_when_inactive(false)).on_hover_text(&path); + ui.label(RichText::new(&path).small().color(tokens.text_dim)); + if row.clicked() { + crate::windows::open_path(app, &path); + app.ui.windows.home = false; + } + } + }); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 3b30be52..d8d796ed 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -22,6 +22,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("8 bits", "8 بت"), ("8 bits per channel", "8 بت لكل قناة"), ("A folder: material.mtlx, material.json, resources/ and the optional preview.png", "مجلد: material.mtlx وmaterial.json وresources/ وpreview.png الاختياري"), + ("A graph's name is unique in its package; a taken name gets a number", "اسم المخطط فريد في حزمته؛ يُضاف رقم إلى الاسم المستخدم"), + ("A saved default is in use", "إعداد افتراضي محفوظ قيد الاستخدام"), + ("A small graph of atomic nodes working together", "مخطط صغير لعقد ذرية تعمل معاً"), ("Abbe number", "عدد آبي"), ("About MaterialCraft", "حول MaterialCraft"), ("About MaterialCraft...", "حول MaterialCraft..."), @@ -45,27 +48,35 @@ pub const TABLE: &[(&str, &str)] = &[ ("Align left", "محاذاة لليسار"), ("Align top", "محاذاة للأعلى"), ("All", "الكل"), + ("All Craft apps", "جميع تطبيقات Craft"), + ("All Craft apps...", "جميع تطبيقات Craft..."), ("All nodes", "كل العقد"), + ("All templates", "جميع القوالب"), ("Alpha", "ألفا"), ("Alpha channel", "قناة ألفا"), ("Amber", "كهرماني"), ("Ambient Light", "الضوء المحيط"), ("Ambient occlusion", "الإطباق المحيط"), ("Ambient occlusion rays", "أشعة الإطباق المحيط"), + ("An empty function graph: a value computed from function nodes", "مخطط دالة فارغ: قيمة تُحسب من عقد الدوال"), + ("An empty material graph", "مخطط مادة فارغ"), ("An open-source Crafting App by the ArtCraft team and community.", "تطبيق تصميم مفتوح المصدر من قِبل فريق ومجتمع ArtCraft."), ("And", "و (And)"), ("Angle above the horizon", "الزاوية فوق الأفق"), ("Angle around the scene", "الزاوية حول المشهد"), ("Anisotropy", "تباين الخواص"), + ("Appearance", "المظهر"), ("Apply", "تطبيق"), ("Arc tangent 2", "ظل زاوية قوسي 2"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("As JSON", "بصيغة JSON"), ("Atomic nodes", "عقد أولية"), ("Attributes", "السمات"), + ("Auto backup", "النسخ الاحتياطي التلقائي"), ("Automatic (16 bits for normal and height)", "تلقائي (16 بت للناظم والارتفاع)"), ("Automatic Clip Planes", "مستويات قطع تلقائية"), ("Automatic export when outputs change", "تصدير تلقائي عند تغيّر المخرجات"), + ("Automation documentation...", "توثيق الأتمتة..."), ("Autosave every (minutes, 0 = off)", "الحفظ التلقائي كل (دقائق، 0 = معطل)"), ("Axis", "المحاور"), ("Back", "الخلف"), @@ -77,6 +88,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bad function", "دالة غير صالحة"), ("Bake every control", "خَبز كل عناصر التحكم في الخامات"), ("Base", "الأساس"), + ( + "Base color, normal, roughness, metallic, height and ambient occlusion outputs, ready to connect", + "مخرجات اللون الأساسي والناظم والخشونة والمعدنية والارتفاع والإطباق المحيط، جاهزة للتوصيل", + ), ("Base parameters", "المعلمات الأساسية"), ("Batch", "دفعة"), ("Bind to input", "ربط بالمدخل"), @@ -90,6 +105,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bounding box", "الصندوق المحيط"), ("Brick wall", "جدار طوب"), ("Brightness", "السطوع"), + ("Browse...", "استعراض..."), ( "Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.", "أنشئ مواد قابلة للتكرار من التشويش والأنماط والمرشحات، وعاينها مباشرة ثنائية وثلاثية الأبعاد، وصدّر الخرائط لأي محرك.", @@ -98,7 +114,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Camera", "الكاميرا"), ("Camera: drag to orbit, pan and zoom (C)", "الكاميرا: اسحب للدوران والتحريك والتكبير (C)"), ("Cancel", "إلغاء"), + ("Cancel rendering", "إلغاء التصيير"), ("Cast", "تحويل النوع"), + ("Category", "الفئة"), ("Ceil", "الحد الأعلى (Ceil)"), ("Channels shown", "القنوات المعروضة"), ("Check at least one output to export", "حدّد مخرجًا واحدًا على الأقل للتصدير"), @@ -108,6 +126,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Clamp", "تقييد النطاق (Clamp)"), ("Clear cache", "مسح الذاكرة المؤقتة"), ("Clear material assignments", "مسح تعيينات المادة"), + ("Clear nodes thumbnails", "مسح صور العقد المصغرة"), ("Clear recent packages", "مسح الحزم الأخيرة"), ("Click a node to show it here", "انقر على عقدة لعرضها هنا"), ("Clip planes", "مستويات القطع"), @@ -120,13 +139,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color", "اللون"), ("Color sampler: click the image to place it", "أداة التقاط اللون: انقر على الصورة لوضعها"), ("color space", "فضاء الألوان"), + ("Common", "عام"), + ("Community", "المجتمع"), ("Community (Discord)", "المجتمع (Discord)"), + ("Community (Discord)...", "المجتمع (Discord)..."), ("Comparison", "مقارنة"), ("Compute graph", "حساب المخطط"), + ("Compute nodes thumbnails", "حساب صور العقد المصغرة"), ("Computing...", "جاري الحساب..."), ("Console", "وحدة التحكم"), ("Constant", "ثابت"), ("Control", "تحكم"), + ("Cooker", "المعالِج"), ("Copper", "نحاسي"), ("Copy", "نسخ"), ("Copy image to the clipboard", "نسخ الصورة إلى الحافظة"), @@ -143,6 +167,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Create", "إنشاء"), ("Create graph from selection", "إنشاء مخطط من التحديد"), ("Create graph in", "إنشاء مخطط في"), + ("Create nodes by dropping a wire on empty canvas", "إنشاء العقد بإفلات سلك على لوحة فارغة"), ("Cube", "مكعب"), ("Cut", "قص"), ("Cyan", "سماوي"), @@ -150,6 +175,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dark", "داكن"), ("Darkening", "التعتيم"), ("Default", "افتراضي"), + ("Default 3D view", "العرض ثلاثي الأبعاد الافتراضي"), + ("Default environment", "البيئة الافتراضية"), + ("Default lighting state", "حالة الإضاءة الافتراضية"), ("Delete", "حذف"), ("Delete and relink", "حذف وإعادة ربط"), ("Delete input", "حذف المدخل"), @@ -160,6 +188,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Diffuse roughness", "خشونة الانتشار"), ("DirectX (Y-)", "DirectX (Y-)"), ("Disable selection", "تعطيل التحديد"), + ("Disk limit (MiB, 0 = off)", "حد القرص (ميبيبايت، 0 = إيقاف)"), ("Dispersion scale", "مقياس التشتت"), ("Displacement", "الإزاحة"), ("Displacement scale", "مقياس الإزاحة"), @@ -181,6 +210,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Duplicate selection without link", "تكرار التحديد بدون ربط"), ("Edit", "تحرير"), ("Edit function graph...", "تحرير مخطط الدوال..."), + ("Edit node graph", "تحرير مخطط العقدة"), ("Edit properties", "تعديل الخصائص"), ("Edit settings", "تعديل الإعدادات"), ("Emission", "الانبعاث"), @@ -189,14 +219,20 @@ pub const TABLE: &[(&str, &str)] = &[ ("Enable physical size from graph", "تفعيل الحجم الفيزيائي من المخطط"), ("Enabled", "مفعّل"), ("Engine", "المحرك"), + ( + "Engine suspended: choose Suspend engine in the Tools menu again (Shift+Escape) to resume", + "المحرك متوقف مؤقتاً: اختر «إيقاف المحرك مؤقتاً» من قائمة الأدوات مرة أخرى (Shift+Escape) للاستئناف", + ), ("Environment", "البيئة"), ("Environment background", "خلفية البيئة"), ("Environment image", "صورة البيئة"), + ("Environment shown behind the mesh by default", "إظهار البيئة خلف المجسم افتراضياً"), ("Equal", "مساوٍ"), ("Exit", "خروج"), ("Explorer", "المستكشف"), ("Exponential", "دالة أسية (Exp)"), ("Export", "تصدير"), + ("Export log...", "تصدير السجل..."), ("Export material...", "تصدير المادة..."), ("Export outputs", "تصدير المخرجات"), ("Export outputs...", "تصدير المخرجات..."), @@ -212,6 +248,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("File", "ملف"), ("File names", "أسماء الملفات"), ("files", "ملفات"), + ("Filter", "تصفية"), ("Filters", "مرشحات"), ("Fit", "ملاءمة"), ("Flip normal map Y (DirectX)", "قلب Y لخريطة النواظم (DirectX)"), @@ -223,6 +260,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Floor", "الحد الأدنى (Floor)"), ("Focal Length (mm)", "البعد البؤري (مم)"), ("Folder", "المجلد"), + ( + "For the material graph: press the keys over the graph to add the node under the pointer", + "لمخطط المادة: اضغط المفاتيح فوق المخطط لإضافة العقدة تحت المؤشر", + ), ("Format", "الصيغة"), ("Fractional part", "الجزء الكسري"), ("Frame", "تأطير"), @@ -240,8 +281,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("function nodes", "عقد الدوال"), ("Function of", "دالة لـ"), ("Fuzz", "الزغب"), + ("General", "عام"), ("Geometry", "الهندسة"), ("Get variable", "جلب متغير"), + ("Give feedback...", "إرسال ملاحظات..."), ("Glossiness", "اللمعان"), ("Go to pin", "الانتقال إلى الدبوس"), ("Graph", "مخطط"), @@ -263,6 +306,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Height scale", "مقياس الارتفاع"), ("Height technique", "تقنية الارتفاع"), ("Help", "مساعدة"), + ("High (16 spp)", "مرتفع (16 عينة/بكسل)"), ("Histogram", "المخطط البياني (Histogram)"), ("History", "السجل"), ("Hollow box", "صندوق أجوف"), @@ -273,29 +317,38 @@ pub const TABLE: &[(&str, &str)] = &[ ("Image copied to the clipboard", "تم نسخ الصورة إلى الحافظة"), ("Image information", "معلومات الصورة"), ("Import bitmap...", "استيراد صورة نقطية..."), + ("Import vector graphics...", "استيراد رسومات متجهية..."), ("Imported", "تم الاستيراد"), ("Include preview.png", "تضمين preview.png"), ("Information", "المعلومات"), ("Inner box", "صندوق داخلي"), ("Input parameters", "معلمات المدخلات"), ("Input previews", "معاينات المدخلات"), + ("Install...", "تثبيت..."), ("Instance parameters", "معلمات النسخة"), ("Integer", "عدد صحيح"), ("Intensity", "الشدة"), ("Interface scale", "حجم واجهة المستخدم"), + ("Invert zoom in views", "عكس التكبير في العروض"), + ("is already the shortcut of", "هو بالفعل اختصار"), ("Join the community (Discord)...", "انضم إلى المجتمع (Discord)..."), ("Keep supported controls", "إبقاء عناصر التحكم المدعومة"), + ("Keep the width and height the same", "إبقاء العرض والارتفاع متساويين"), ( "Keep the zoom when the image size changes; off keeps the image's size on screen", "الحفاظ على نسبة التكبير عند تغيّر حجم الصورة؛ عند الإيقاف يبقى حجم الصورة على الشاشة ثابتًا", ), + ("Keep up to", "الاحتفاظ بما يصل إلى"), ("Key at", "مفتاح عند"), ("Language", "اللغة"), ("Last compute", "آخر حساب"), ("Lava rock", "صخور بركانية"), + ("Layout", "التخطيط"), + ("Learn", "تعلّم"), ("Left", "اليسار"), ("Length", "الطول"), ("Library", "المكتبة"), + ("Library preview cache", "ذاكرة معاينات المكتبة"), ("Light", "فاتح"), ("Light: drag to move the first point light, which switches it on (L)", "الضوء: اسحب لتحريك الضوء النقطي الأول، وهذا يشغّله (L)"), ("Lights", "الأضواء"), @@ -305,17 +358,23 @@ pub const TABLE: &[(&str, &str)] = &[ ("Load mesh...", "تحميل مجسم..."), ("Load State File With Mesh...", "تحميل ملف حالة مع المجسم..."), ("Load State File...", "تحميل ملف حالة..."), + ("Loaded", "محمّلة"), ("Logarithm", "لوغاريتم"), ("Logical", "منطقي"), + ("Low (1 spp)", "منخفض (1 عينة/بكسل)"), ("Lower", "أصغر من"), ("Lower or equal", "أصغر من أو يساوي"), ("Luminance", "النصوع"), + ("Main toolbar", "شريط الأدوات الرئيسي"), ("Mat ball", "كرة المادة"), ("Material", "المادة"), ("Material filters", "مرشحات المواد"), + ("Material graph", "مخطط مادة"), ("Materials", "المواد"), ("MaterialX export isn't available yet (#190)", "تصدير MaterialX غير متاح بعد (#190)"), ("Maximum", "الحد الأقصى"), + ("Maximum stored previews", "أقصى عدد للمعاينات المخزنة"), + ("Medium (4 spp)", "متوسط (4 عينات/بكسل)"), ("Medium dark", "داكن متوسط"), ("Medium light", "فاتح متوسط"), ("Mesh Info", "معلومات المجسم"), @@ -326,6 +385,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Metalness", "المعدنية"), ("Meters per scene unit", "الأمتار لكل وحدة مشهد"), ("Minimum", "الحد الأدنى"), + ("Misc", "متفرقات"), ("Modulo", "باقي القسمة (Modulo)"), ("Mossy ground", "أرضية مغطاة بالطحالب"), ("Move the pointer over the image to read its pixels", "حرّك المؤشر فوق الصورة لقراءة بكسلاتها"), @@ -334,17 +394,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Near Clip Plane", "مستوى القطع القريب"), ("Negation", "نفي / سالب"), ("New", "جديد"), + ("New function graph", "مخطط دالة جديد"), ("New graph", "مخطط جديد"), ("New graph...", "مخطط جديد..."), ("New graph... (Ctrl+N)", "مخطط جديد... (Ctrl+N)"), + ("New package", "حزمة جديدة"), ("New random seed", "بذرة عشوائية جديدة"), + ("Next pin", "الدبوس التالي"), ("Night", "ليل"), ("No font on this system can show this language", "لا يوجد خط على هذا النظام يمكنه عرض هذه اللغة"), ("No graph is open", "لا يوجد مخطط مفتوح"), ("No graph with outputs", "لا يوجد مخطط له مخرجات"), ("No matching node", "لا توجد عقدة مطابقة"), + ("No plugins are installed. MaterialCraft does not load plugins yet.", "لا توجد إضافات مثبتة. لا يحمّل MaterialCraft الإضافات بعد."), ("No presets yet", "لا توجد إعدادات مسبقة بعد"), ("No recent packages", "لا توجد حزم حديثة"), + ("Node creation shortcuts", "اختصارات إنشاء العقد"), ("Node search (over the graph)", "البحث عن عقدة (فوق المخطط)"), ("Node-based procedural materials, built in pure Rust.", "مواد إجرائية قائمة على العقد، مبنية بلغة Rust النقية."), ("Noises", "تشويشات"), @@ -353,9 +418,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal orientation", "اتجاه الناظم (Normal)"), ("Normalize", "تسوية (Normalize)"), ("Not", "ليس (Not)"), + ("Not applied: the active graph or package changed while the file dialog was open", "لم يُطبّق: تغيّر المخطط أو الحزمة النشطة أثناء فتح نافذة الملفات"), ("not available yet", "غير متاح بعد"), ("Not equal", "غير مساوٍ"), + ("Not saved:", "لم يُحفظ:"), ("Nothing matches", "لا توجد تطابقات"), + ("OK", "موافق"), ( "One .mcmat archive: material.mtlx, material.json, resources/ and the optional preview.png", "أرشيف .mcmat واحد: material.mtlx وmaterial.json وresources/ وpreview.png الاختياري", @@ -367,6 +435,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Open package... (Ctrl+O)", "فتح حزمة... (Ctrl+O)"), ("Open...", "فتح..."), ("Opened", "تم الفتح"), + ("Opened with", "فُتح مع"), ("OpenGL (Y+)", "OpenGL (Y+)"), ("Operator", "معامل حسابي"), ("Ops", "عمليات"), @@ -378,10 +447,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Outputs", "المخرجات"), ("Overcast", "غائم"), ("Override Render Resolution", "تجاوز دقة التصيير"), + ("packages", "حزم"), + ("packages saved", "حزم حُفظت"), ("Painted metal plates", "صفائح معدنية مطلية"), ("Pan the camera", "تحريك الكاميرا"), ("Pan the graph", "تحريك المخطط"), ("Parallax Occlusion", "إطباق المنظور"), + ("Parent graph", "المخطط الأب"), ("Parent size:", "حجم العنصر الأصل:"), ("Paste", "لصق"), ("Pattern", "النمط"), @@ -394,9 +466,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Pick an image file (a mesh map baked in TextureCraft)", "اختر ملف صورة (خريطة مجسم مخبوزة في TextureCraft)"), ("Pink", "وردي"), ("Pixels", "البكسلات"), + ( + "placeholder node(s) stand in for nodes MaterialCraft doesn't have yet (see the warnings above)", + "عقدة (عقد) بديلة تحل محل عقد لا يملكها MaterialCraft بعد (انظر التحذيرات أعلاه)", + ), ("Plane", "مستوى"), ("Plane (hi-res)", "مستوٍ (عالي الدقة)"), ("Plot the square root of the counts, so small counts stay visible", "رسم الجذر التربيعي للأعداد لتبقى الأعداد الصغيرة ظاهرة"), + ("Plugin Manager", "مدير الإضافات"), + ("Plugin Manager...", "مدير الإضافات..."), + ("Plugins", "الإضافات"), + ("Plugins are not supported yet", "الإضافات غير مدعومة بعد"), ("Point Light 1", "الضوء النقطي 1"), ("Point Light 2", "الضوء النقطي 2"), ("Polished marble", "رخام مصقول"), @@ -406,11 +486,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Preferences...", "التفضيلات..."), ("Preset name", "اسم الإعداد المسبق"), ("Presets", "الإعدادات المسبقة"), + ("Press keys, Backspace to clear, Esc to cancel", "اضغط المفاتيح، Backspace للمسح، Esc للإلغاء"), ("Preview", "معاينة"), ("Preview resolution", "دقة المعاينة"), ("Preview size", "حجم المعاينة"), ("Preview size while editing", "حجم المعاينة أثناء التحرير"), + ("Previews rebuild as they come into view.", "تُعاد بناء المعاينات عند ظهورها."), + ("Previous pin", "الدبوس السابق"), ("Projection", "الإسقاط"), + ("Projects", "المشاريع"), ("Properties", "الخصائص"), ("Publishing arrives with the new .mcmat format (#190); these options are kept for it", "يصل النشر مع صيغة .mcmat الجديدة (#190)؛ وتُحفظ هذه الخيارات لها"), ("Radius", "نصف القطر"), @@ -419,14 +503,20 @@ pub const TABLE: &[(&str, &str)] = &[ ("Random", "عشوائي"), ("Random seed", "بذرة عشوائية"), ("Range", "النطاق"), + ("Rebuild thumbnails", "إعادة بناء الصور المصغرة"), ("Recent", "الأخيرة"), + ("Recent documents", "المستندات الأخيرة"), ("Recent packages", "الحزم الأخيرة"), + ("Recent packages list contains", "قائمة الحزم الأخيرة تحتوي"), ("Red", "أحمر"), ("Redo", "إعادة"), ("Redo (Ctrl+Y)", "إعادة (Ctrl+Y)"), + ("Refresh", "تحديث"), ("Relative to input", "نسبي إلى المدخل"), ("Relative to parent", "نسبي إلى الأصل"), + ("Release notes...", "ملاحظات الإصدار..."), ("Reload resources", "إعادة تحميل الموارد"), + ("Remove every node creation shortcut", "إزالة كل اختصارات إنشاء العقد"), ("Remove function", "إزالة الدالة"), ("Remove the background image", "إزالة صورة الخلفية"), ("Remove the color sampler", "إزالة أداة التقاط اللون"), @@ -439,7 +529,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Renderer", "المصير"), ("Renderer settings", "إعدادات المصيِّر"), ("Repeat the image to check its tiling", "تكرار الصورة للتحقق من تكرارها"), + ("Report a bug", "الإبلاغ عن خطأ"), ("Report a bug...", "الإبلاغ عن خطأ..."), + ("Reset and view outputs in 3D view", "إعادة الضبط وعرض المخرجات في العرض ثلاثي الأبعاد"), ("Reset Common Parameters", "إعادة ضبط المعاملات المشتركة"), ("Reset Environment", "إعادة ضبط البيئة"), ("Reset layout", "إعادة ضبط التخطيط"), @@ -467,14 +559,20 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rounded cylinder", "أسطوانة مستديرة الحواف"), ("Rusty metal", "معدن صدئ"), ("Sample Color", "عينة لونية"), + ("Sample count", "عدد العينات"), ("Sample Gray", "عينة تدرج رمادي"), ("Samplers", "عينات"), ("Samples", "عينات"), ("Samples per pixel side", "العينات لكل ضلع بكسل"), ("Save", "حفظ"), ("Save (Ctrl+S)", "حفظ (Ctrl+S)"), + ("Save all", "حفظ الكل"), ("Save as...", "حفظ باسم..."), ("Save Current State As Default", "حفظ الحالة الحالية كافتراضية"), + ( + "Save Current State As Default, in the 3D view's Scene menu, saves the whole view here", + "«حفظ الحالة الحالية كافتراضية» في قائمة المشهد بالعرض ثلاثي الأبعاد يحفظ العرض كاملاً هنا", + ), ("Save Current State...", "حفظ الحالة الحالية..."), ("Save image...", "حفظ الصورة..."), ("Save package", "حفظ الحزمة"), @@ -483,11 +581,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save settings", "حفظ الإعدادات"), ("Saved", "تم الحفظ"), ("Saved as the default 3D view", "حُفظ كعرض ثلاثي الأبعاد افتراضي"), + ("saved; use Save as for packages without a file", "حُفظت؛ استخدم «حفظ باسم» للحزم التي ليس لها ملف"), ("Saving a render needs the desktop app; copy it to the clipboard instead", "حفظ التصيير يتطلب تطبيق سطح المكتب؛ انسخه إلى الحافظة بدلاً من ذلك"), ("Scene", "المشهد"), ("Scene browser", "متصفح المشهد"), ("Scene stats", "إحصاءات المشهد"), ("Search", "بحث"), + ("Search by shortcut", "البحث بالاختصار"), ("Search nodes...", "البحث في العقد..."), ("Select all", "تحديد الكل"), ("Select downstream nodes", "تحديد العقد اللاحقة"), @@ -506,16 +606,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("Shortcuts", "الاختصارات"), ("Shortcuts list...", "قائمة الاختصارات..."), ("Show a checkerboard behind transparent pixels", "إظهار رقعة شطرنج خلف البكسلات الشفافة"), + ("Show all assigned", "عرض كل المعيّن"), ("Show at startup", "إظهار عند بدء التشغيل"), ("Show in the 2D view", "إظهار في العرض ثنائي الأبعاد"), ("Show node thumbnails", "إظهار الصور المصغرة للعقد"), ("Show the environment behind the mesh", "إظهار البيئة خلف المجسم"), ("Show the image in the proportions of the graph's physical size", "عرض الصورة بنسب الحجم الفعلي للمخطط"), + ("Show the library as a list", "عرض المكتبة كقائمة"), ("Showing", "عرض"), ("Shown on the mesh", "المعروض على المجسم"), ("Side", "جانبي"), ("Sine", "جيب الزاوية (Sine)"), ("Size", "الحجم"), + ("Snap to grid", "المحاذاة إلى الشبكة"), ("Specific parameters", "المعلمات المخصصة"), ("Specular", "الانعكاس"), ("Specular Glossiness", "انعكاس ولمعان"), @@ -524,6 +627,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Sqrt", "الجذر التربيعي"), ("Square root", "جذر تربيعي"), ("Start export", "بدء التصدير"), + ("Start from a template", "ابدأ من قالب"), ("Stone tiles", "بلاط حجري"), ("Stored with the state; this renderer does not show it", "يُحفظ مع الحالة؛ هذا المصيِّر لا يعرضه"), ("Studio", "استوديو"), @@ -531,9 +635,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsurface", "تحت السطح"), ("Subtraction", "طرح"), ("Sunset", "غروب"), + ("Suspend engine", "إيقاف المحرك مؤقتاً"), ("SVG", "رسوم متجهة (SVG)"), ("Swizzle", "إعادة ترتيب القنوات (Swizzle)"), + ("Tab key shows the node search", "مفتاح Tab يعرض البحث عن العقد"), ("Tangent", "ظل الزاوية (Tangent)"), + ("Technical requirements...", "المتطلبات التقنية..."), ("Templates", "القوالب"), ("Tessellation", "التقسيم"), ("Tessellation + Displacement", "تقسيم + إزاحة"), @@ -541,8 +648,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Texture generators", "مولدات الخامات"), ("Textures", "الخامات"), ("The background image could not be shown", "تعذّر عرض صورة الخلفية"), + ("The built-in default is in use", "الإعداد الافتراضي المدمج قيد الاستخدام"), ("The colors are already multiplied by their alpha", "الألوان مضروبة مسبقًا في قناة ألفا"), + ("The copies are numbered files in", "النسخ ملفات مرقمة في"), + ("The file dialog could not be shown", "تعذّر عرض نافذة الملفات"), ("The instanced graph is missing", "المخطط المنسوخ مفقود"), + ("The log could not be saved", "تعذّر حفظ السجل"), ("The pixel under the color sampler", "البكسل تحت أداة التقاط اللون"), ("The pixel under the pointer", "البكسل تحت المؤشر"), ("The point lights cast shadows", "الأضواء النقطية تلقي ظلالاً"), @@ -567,13 +678,18 @@ pub const TABLE: &[(&str, &str)] = &[ ("Transmission", "النفاذية"), ("Transparency (alpha)", "الشفافية (ألفا)"), ("Triangles", "المثلثات"), + ("Troubleshooting...", "استكشاف الأخطاء..."), ("Turn the environment", "تدوير البيئة"), + ("Tutorials", "الدروس"), + ("Tutorials...", "الدروس..."), ("Unbind", "فك الارتباط"), ("Undo", "تراجع"), ("Undo (Ctrl+Z)", "تراجع (Ctrl+Z)"), + ("Undo history (steps)", "سجل التراجع (خطوات)"), ("Uniform Color", "لون موحّد"), ("Unlit", "غير مضاء"), ("Use as result", "استخدام كنتيجة"), + ("Use the built-in default", "استخدام الإعداد الافتراضي المدمج"), ("Use this parameter; off reads as if the material had none", "استخدام هذا المعامل؛ عند الإيقاف يُقرأ كأن المادة لا تحتويه"), ("Use viewport resolution", "استخدام دقة منفذ العرض"), ("Used range", "النطاق المستخدم"), @@ -587,15 +703,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Vector Float3", "متجه ثلاثي (Float3)"), ("Vector Float4", "متجه رباعي (Float4)"), ("Version", "الإصدار"), + ("versions", "نسخ"), ("Vertex Color", "لون الرؤوس"), ("Vertex tangent space", "فضاء المماس للرؤوس"), ("Vertices", "الرؤوس"), ("View in 2D view", "عرض في العرض ثنائي الأبعاد"), + ("View outputs in 3D view", "عرض المخرجات في العرض ثلاثي الأبعاد"), + ("View outputs in 3D view when opening a graph", "عرض المخرجات في العرض ثلاثي الأبعاد عند فتح مخطط"), ("Viewpoint", "نقطة النظر"), + ("Views", "العروض"), ("Violet", "بنفسجي"), + ("warnings: see the Console", "تحذيرات: انظر وحدة التحكم"), ("Weathering", "التجوية والتقادم"), ("Weight", "الوزن"), ("Welcome to MaterialCraft", "مرحباً بك في MaterialCraft"), + ("What's new", "ما الجديد"), + ("What's new...", "ما الجديد..."), ("Wicker weave", "نسيج قش"), ("Windows", "نوافذ"), ("Wireframe", "إطار سلكي"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4442b24d..5f722e38 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -11,13 +11,17 @@ pub mod fonts; pub mod function; pub mod graph; mod graph_drag_payload; +mod help_links; mod history; +mod home_screen; pub mod i18n; pub mod levels_editor; pub mod library; mod material_preview_menu; mod menu_item; pub mod menus; +mod new_graph_dialog; +mod node_shortcuts; mod preview_resolution; #[path = "property/mod.rs"] pub mod properties; @@ -34,10 +38,15 @@ pub mod web_files; pub mod widgets; pub mod windows; +#[cfg(not(target_arch = "wasm32"))] +mod autosave_versions; mod material_craft_app; #[cfg(not(target_arch = "wasm32"))] mod native_dialogs; pub mod pattern; +mod plugin_manager; +pub mod preferences; +mod template_card; mod toast; #[cfg(not(target_arch = "wasm32"))] pub mod updates_ui; diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index a440c11f..8f780a2e 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -155,6 +155,9 @@ impl MaterialCraftApp { let _ = materialcraft_engine::execute(&mut self.session, "session.history", &serde_json::json!(self.ui.prefs.history)); } + self.ui.recent.truncate(self.ui.prefs.recent_limit.clamp(1, crate::state::Prefs::MAX_RECENT)); + self.session.view_outputs_on_open = self.ui.prefs.view_outputs_on_open; + if self.session.camera != self.ui.prefs.camera.sanitized() { self.session.set_camera_prefs(self.ui.prefs.camera); } @@ -367,21 +370,26 @@ impl MaterialCraftApp { } self.next_autosave = now + period; - let dir = user_dir("autosave"); - let path = dir.join(format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name))); + let folder = user_dir("autosave"); let pkg = self.session.pkg.clone(); + let keep = self.ui.prefs.autosave_versions.clamp(1, crate::state::Prefs::MAX_AUTOSAVE_VERSIONS); let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || { - let result = std::fs::create_dir_all(&dir) - .map_err(|e| e.to_string()) + let path = crate::autosave_versions::next_path(&folder, &pkg.name); + let result = std::fs::create_dir_all(&folder) + .map_err(|error| error.to_string()) .and_then(|_| { materialcraft_engine::formats::project::ProjectFiles::build(&pkg, "autosave.mcraft", true) .and_then(|files| files.zip()) - .map_err(|e| e.to_string()) + .map_err(|error| error.to_string()) }) - .and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|e| e.to_string())); + .and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|error| error.to_string())); + match result { - Ok(()) => log::info!("autosaved {}", path.display()), - Err(e) => log::warn!("autosave to {} failed: {e}", path.display()), + Ok(()) => { + crate::autosave_versions::prune(&folder, &pkg.name, keep); + log::info!("autosaved {}", path.display()); + } + Err(error) => log::warn!("autosave to {} failed: {error}", path.display()), } }); if let Err(e) = spawned { @@ -505,7 +513,9 @@ impl MaterialCraftApp { // Tab can focus a menu or toolbar button while drawing; preserve keyboard ownership self.graph.keyboard_was_focused = ctx.egui_wants_keyboard_input(); menus::menu_bar(self, ui); - toolbar::main_toolbar(self, ui); + if self.ui.prefs.show_toolbar { + toolbar::main_toolbar(self, ui); + } toolbar::status_bar(self, ui); self.ui.explorer.hovered = false; egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui)); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 37275d92..b18c05db 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -87,12 +87,13 @@ pub(crate) const EXPLORER_GRAPH: &[ExplorerRow] = &[ /// The menu catalog (the target menu tree with our ids) pub const CATALOG: &[MenuItem] = &[ sub("File", "New", "Graph...", "ui.newGraph", Some("Ctrl+N")), - sub("File", "New", "Function Graph...", "ui.newFunctionGraph", None), + sub("File", "New", "Function graph", "ui.newFunctionGraph", None), sub("File", "New", "Empty package", "file.newPackage", None), it("File", "Open...", "file.open", Some("Ctrl+O")), sep("File"), it("File", "Save", "file.save", Some("Ctrl+S")), it("File", "Save as...", "file.saveAs", Some("Ctrl+Shift+S")), + it("File", "Save all", "file.saveAll", None), it("File", "Close all", "ui.closeAll", None), sep("File"), it("File", "Import bitmap...", "file.importBitmap", None), @@ -100,6 +101,7 @@ pub const CATALOG: &[MenuItem] = &[ it("File", "Export outputs...", "ui.export", Some("Ctrl+Shift+E")), it("File", "Export material...", "file.exportMaterial", None), it("File", "Send to TextureCraft", "file.sendToTextureCraft", None), + sep("File"), it("File", "Reload resources", "ui.reloadResources", None), sep("File"), it("File", "Exit", "ui.quit", Some("Ctrl+Q")), @@ -117,6 +119,9 @@ pub const CATALOG: &[MenuItem] = &[ it("Edit", "Parent graph", "ui.graph.parent", Some("Alt+ArrowLeft")), sep("Edit"), it("Edit", "Preferences...", "ui.preferences", None), + it("Tools", "Cancel rendering", "ui.cook.cancel", Some("Escape")), + it("Tools", "Suspend engine", "ui.cook.suspend", Some("Shift+Escape")), + sep("Tools"), it("Tools", "Compute graph", "graph.cook", None), it("Tools", "Snap to grid", "ui.graph.snapToGrid", None), it("Tools", "Compute nodes thumbnails", "ui.graph.computeThumbnails", None), @@ -132,6 +137,10 @@ pub const CATALOG: &[MenuItem] = &[ sub("Tools", "Preview size", "2048 px", "ui.preview.2048", None), sub("Tools", "Preview size", "Full size", "ui.preview.0", None), it("Tools", "Create graph from selection", "graph.createFromSelection", None), + sep("Tools"), + it("Tools", "Plugin Manager...", "ui.pluginManager", None), + it("Windows", "Reset layout", "ui.resetLayout", None), + sep("Windows"), it("Windows", "Explorer", "ui.view.explorer", None), it("Windows", "Graph", "ui.view.graph", None), it("Windows", "Properties", "ui.view.properties", None), @@ -141,14 +150,26 @@ pub const CATALOG: &[MenuItem] = &[ it("Windows", "Library", "ui.view.library", None), it("Windows", "History", "ui.view.history", None), sep("Windows"), - it("Windows", "Reset layout", "ui.resetLayout", None), - it("Help", "Home screen...", "ui.home", None), + it("Windows", "Main toolbar", "ui.view.toolbar", None), + it("Help", "Tutorials...", "ui.help.tutorials", None), + it("Help", "Release notes...", "ui.help.releaseNotes", None), + it("Help", "Technical requirements...", "ui.help.requirements", None), it("Help", "Documentation...", "ui.help.docs", None), + it("Help", "Automation documentation...", "ui.help.automation", None), it("Help", "Shortcuts list...", "ui.help.shortcuts", None), sep("Help"), - it("Help", "Join the community (Discord)...", "ui.help.discord", None), - it("Help", "ArtCraft website...", "ui.help.website", None), + it("Help", "Community (Discord)...", "ui.help.discord", None), it("Help", "Report a bug...", "ui.help.bug", None), + #[cfg(not(target_arch = "wasm32"))] + it("Help", "Export log...", "ui.help.exportLog", None), + it("Help", "Give feedback...", "ui.help.feedback", None), + it("Help", "Troubleshooting...", "ui.help.troubleshooting", None), + sep("Help"), + it("Help", "All Craft apps...", "ui.help.apps", None), + it("Help", "ArtCraft website...", "ui.help.website", None), + sep("Help"), + it("Help", "Home screen...", "ui.home", None), + it("Help", "What's new...", "ui.help.news", None), sep("Help"), #[cfg(not(target_arch = "wasm32"))] it("Help", "Check for updates...", "ui.help.checkForUpdates", None), @@ -173,6 +194,10 @@ pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool { return enabled; } + if id == "ui.cook.cancel" { + return app.cooker.busy(); + } + if matches!(id, "edit.paste" | "edit.pasteWithoutLinks") { return app.session.graph().is_ok() && app.session.clipboard.as_ref().is_some_and(|clip| !clip.nodes.is_empty()); } @@ -212,11 +237,8 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { return; } match id { - "ui.newGraph" | "ui.newFunctionGraph" => { - app.ui.new_graph_kind = - if id == "ui.newFunctionGraph" { materialcraft_engine::core::GraphKind::Function } else { materialcraft_engine::core::GraphKind::Material }; - app.ui.windows.new_graph = true; - } + "ui.newGraph" => crate::new_graph_dialog::open(app, materialcraft_engine::core::GraphKind::Material), + "ui.newFunctionGraph" => crate::new_graph_dialog::open(app, materialcraft_engine::core::GraphKind::Function), "ui.export" => crate::export::open(app, crate::export::ExportTab::FromGraph), "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), "ui.preferences" => app.ui.windows.preferences = true, @@ -237,10 +259,17 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { "ui.about" => app.ui.windows.about = true, #[cfg(not(target_arch = "wasm32"))] "ui.help.checkForUpdates" => crate::updates_ui::check(app), - "ui.help.discord" => ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft")), - "ui.help.website" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/apps/materialcraft")), - "ui.help.docs" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft#readme")), - "ui.help.bug" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/issues")), + "ui.cook.cancel" => crate::cook::cancel(app), + "ui.cook.suspend" => crate::cook::toggle_suspended(app), + "ui.pluginManager" => app.ui.windows.plugin_manager = true, + "ui.view.toolbar" => app.ui.prefs.show_toolbar = !app.ui.prefs.show_toolbar, + #[cfg(not(target_arch = "wasm32"))] + "ui.help.exportLog" => crate::native_dialogs::export_log(app), + id if crate::help_links::url(id).is_some() => { + if let Some(url) = crate::help_links::url(id) { + ctx.open_url(egui::OpenUrl::new_tab(url)); + } + } _ => { if crate::windows::file_action(app, ctx, id) { return; @@ -363,6 +392,8 @@ fn menu_item(app: &mut MaterialCraftApp, context: &egui::Context, ui: &mut egui: let checked = match item.id { "ui.view.graph" => Some(true), "ui.graph.snapToGrid" => Some(app.ui.prefs.snap_to_grid), + "ui.cook.suspend" => Some(app.cooker.suspended), + "ui.view.toolbar" => Some(app.ui.prefs.show_toolbar), id if id.starts_with("ui.preview.") => { id.strip_prefix("ui.preview.").and_then(|size| size.parse::().ok()).map(|size| size == app.ui.prefs.preview_size) } @@ -441,10 +472,17 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { let label_selected = label_text_selected(ctx); // A clipboard chord with nothing to copy or paste leaves its event to egui instead of reporting an error let unavailable_clipboard_commands: Vec<&str> = ["edit.copy", "edit.cut", "edit.paste"].into_iter().filter(|id| !enabled(app, id)).collect(); + // A drag in progress keeps Escape so the gesture can cancel itself + let gesture_in_progress = ctx.input(|i| i.pointer.any_down()); let hits = ctx.input_mut(|i| { app.dispatcher.dispatch_filtered(i, &app.keymap, &Active::NONE, |hit| { let id = hit.command.id.as_str(); - modality.allows(id) && !(label_selected && matches!(id, "edit.copy" | "edit.cut")) && !unavailable_clipboard_commands.contains(&id) + // Escape cancels a cook only while one runs and no drag is held, so it keeps closing and clearing everything else + let cancels_nothing = id == "ui.cook.cancel" && (!app.cooker.busy() || gesture_in_progress); + modality.allows(id) + && !(label_selected && matches!(id, "edit.copy" | "edit.cut")) + && !unavailable_clipboard_commands.contains(&id) + && !cancels_nothing }) }); for hit in hits { diff --git a/crates/ui-egui/src/native_dialogs.rs b/crates/ui-egui/src/native_dialogs.rs index 5c02ae0b..577fa2e1 100644 --- a/crates/ui-egui/src/native_dialogs.rs +++ b/crates/ui-egui/src/native_dialogs.rs @@ -41,6 +41,8 @@ pub(crate) enum Then { }, /// The image file the 2D view draws behind transparent pixels BackgroundImage, + /// Help ▸ Export log: the Console's messages, one per line + ExportLog(String), /// The parameters `graph.input.bind` runs with, before the path BindInput(Value, GraphRef), } @@ -94,6 +96,13 @@ pub(crate) fn save_package(app: &mut MaterialCraftApp, copy: bool) { ask(app, dialog, then); } +/// Help ▸ Export log: ask where to write the Console's messages as a text file +pub(crate) fn export_log(app: &mut MaterialCraftApp) { + let text = app.session.log.join("\n"); + let dialog = craft_dialogs::FileDialog::save().file_name("materialcraft-log.txt").filter(tr("Text"), &["txt"]); + ask(app, dialog, Then::ExportLog(text)); +} + /// Save in the unsaved-changes prompt, for a package without a path: waits behind any open dialog pub(crate) fn save_before_action(app: &mut MaterialCraftApp) { let then = Then::SavePackage { document: app.session.document_id, copy: false, before_action: true }; @@ -179,6 +188,10 @@ fn chosen(app: &mut MaterialCraftApp, then: Then, path: &std::path::Path) { app.toast(format!("{} {picked}", tr("Saved")), false); } } + Then::ExportLog(text) => match materialcraft_engine::formats::write_atomic(path, text.as_bytes()) { + Ok(()) => app.toast(format!("{} {picked}", tr("Saved")), false), + Err(error) => app.toast(format!("{}: {error}", tr("The log could not be saved")), true), + }, Then::SaveViewState => { if app.run("view.3d.saveState", json!({"path": picked})).is_some() { app.toast(format!("{} {picked}", tr("Saved")), false); diff --git a/crates/ui-egui/src/new_graph_dialog.rs b/crates/ui-egui/src/new_graph_dialog.rs new file mode 100644 index 00000000..32fc6c51 --- /dev/null +++ b/crates/ui-egui/src/new_graph_dialog.rs @@ -0,0 +1,209 @@ +//! File ▸ New ▸ Graph: template cards by category on the left; the graph's name, size and the +//! package it goes in on the right + +use egui::{RichText, Ui, vec2}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::GraphKind; +use serde_json::json; + +use crate::MaterialCraftApp; +use crate::i18n::tr; +use crate::template_card::{CARD_SIZE, FUNCTION_TEMPLATE, TemplateCard}; +use crate::theme::Tokens; + +const WINDOW_SIZE: egui::Vec2 = vec2(1000.0, 640.0); +const SETTINGS_WIDTH: f32 = 340.0; +const CARD_GAP: f32 = 14.0; +const BUTTON_WIDTH: f32 = 120.0; +/// The sides a new graph can have, in pixels +const SIDES: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192]; +/// The categories the dialog lists: every template, or the templates of one kind of graph +const CATEGORIES: [(Option, &str); 3] = + [(None, "All templates"), (Some(GraphKind::Material), "Material graph"), (Some(GraphKind::Function), "Function graph")]; + +/// Open the dialog for a kind of graph, aimed at the active package (or a new one when none is open) +pub(crate) fn open(app: &mut MaterialCraftApp, kind: GraphKind) { + app.ui.new_graph_kind = kind; + app.ui.new_graph_category = Some(kind); + if kind == GraphKind::Function { + app.ui.new_graph_template = FUNCTION_TEMPLATE.into(); + } else if app.ui.new_graph_template == FUNCTION_TEMPLATE { + app.ui.new_graph_template = "pbr".into(); + } + app.ui.new_graph_package = app.session.has_package().then_some(app.session.document_id); + app.ui.windows.new_graph = true; +} + +/// Pick a card: its kind decides the graph's kind +fn choose(app: &mut MaterialCraftApp, card: &TemplateCard) { + app.ui.new_graph_kind = card.kind; + app.ui.new_graph_template = card.id.to_string(); +} + +pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { + let mut open = true; + let mut create = false; + let title = if app.ui.new_graph_kind == GraphKind::Function { tr("New function graph") } else { tr("New graph") }; + crate::windows::modal(ctx, "new-graph", title, &mut open, WINDOW_SIZE, |ui| { + ui.set_min_size(WINDOW_SIZE); + let whole = ui.available_rect_before_wrap(); + let cards = egui::Rect::from_min_max(whole.min, egui::pos2(whole.right() - SETTINGS_WIDTH - 24.0, whole.bottom())); + let settings = egui::Rect::from_min_max(egui::pos2(whole.right() - SETTINGS_WIDTH, whole.top()), whole.max); + + card_grid(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(cards))); + create = graph_settings(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(settings))); + ui.advance_cursor_after_rect(whole); + }); + + if create { + open = !run(app); + } + if !open { + app.ui.windows.new_graph = false; + } +} + +/// Create the graph. Returns true when it was created +fn run(app: &mut MaterialCraftApp) -> bool { + let target = app.ui.new_graph_package; + if let Some(document) = target + && document != app.session.document_id + && app.run("package.activate", json!({"document": document})).is_none() + { + return false; + } + + let kind = if app.ui.new_graph_kind == GraphKind::Function { "function" } else { "material" }; + let height = if app.ui.new_graph_linked { app.ui.new_graph_size } else { app.ui.new_graph_height }; + let parameters = json!({ + "kind": kind, + "template": app.ui.new_graph_template, + "name": app.ui.new_graph_name, + "size": app.ui.new_graph_size, + "height": height, + "newPackage": target.is_none(), + }); + let created = app.run("file.new", parameters).is_some(); + if created { + app.ui.frame_all = true; + } + created +} + +/// The category list and the cards of the chosen category +fn card_grid(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Category")).strong()); + let current = CATEGORIES.iter().find(|(kind, _)| *kind == app.ui.new_graph_category).map_or("", |(_, label)| label); + let combo = egui::ComboBox::from_id_salt("new-graph-category").width(220.0).selected_text(tr(current)).show_ui(ui, |ui| { + for (kind, label) in CATEGORIES { + ui.selectable_value(&mut app.ui.new_graph_category, kind, tr(label)); + } + }); + crate::widgets::name(&combo.response, egui::Role::ComboBox, "Category"); + }); + ui.add_space(10.0); + + let cards: Vec = + crate::template_card::cards().into_iter().filter(|card| app.ui.new_graph_category.is_none_or(|kind| card.kind == kind)).collect(); + egui::ScrollArea::vertical().id_salt("new-graph-cards").auto_shrink([false, false]).show(ui, |ui| { + for kind in [GraphKind::Material, GraphKind::Function] { + let group: Vec<&TemplateCard> = cards.iter().filter(|card| card.kind == kind).collect(); + let Some(first) = group.first() else { continue }; + + ui.horizontal(|ui| { + ui.label(RichText::new(tr(first.kind_label())).size(16.0).color(tokens.text_dim)); + let line = ui.available_rect_before_wrap(); + ui.painter().hline(line.left() + 8.0..=line.right(), line.center().y, egui::Stroke::new(1.0, tokens.separator)); + }); + ui.add_space(6.0); + let columns = ((ui.available_width() + CARD_GAP) / (CARD_SIZE.x + CARD_GAP)).floor().max(1.0) as usize; + for row in group.chunks(columns) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = CARD_GAP; + for card in row { + let chosen = app.ui.new_graph_kind == card.kind && app.ui.new_graph_template == card.id; + let preview = crate::windows::template_preview(ui.ctx(), card.id); + let response = crate::template_card::show(ui, card, chosen, preview); + if response.clicked() { + choose(app, card); + } + if response.double_clicked() { + choose(app, card); + app.ui.new_graph_create_now = true; + } + } + }); + ui.add_space(CARD_GAP); + } + } + }); +} + +/// The graph's name, size and package, and the Create and Cancel buttons. Returns true for Create +fn graph_settings(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Graph name")).strong()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(icon::QUESTION).color(tokens.text_dim)) + .on_hover_text(tr("A graph's name is unique in its package; a taken name gets a number")); + }); + }); + let name = ui.add(egui::TextEdit::singleline(&mut app.ui.new_graph_name).desired_width(f32::INFINITY)); + crate::widgets::name(&name, egui::Role::TextInput, "Graph name"); + ui.add_space(14.0); + + if app.ui.new_graph_kind == GraphKind::Material { + ui.label(RichText::new(tr("Size")).strong()); + ui.horizontal(|ui| { + let side_width = (ui.available_width() - 40.0) * 0.5; + side_combo(ui, "new-graph-width", "Width", &mut app.ui.new_graph_size, side_width); + let link = crate::widgets::icon_button(ui, icon::LINK, tr("Keep the width and height the same"), app.ui.new_graph_linked, 24.0); + if link.clicked() { + app.ui.new_graph_linked = !app.ui.new_graph_linked; + } + if app.ui.new_graph_linked { + app.ui.new_graph_height = app.ui.new_graph_size; + } + ui.add_enabled_ui(!app.ui.new_graph_linked, |ui| side_combo(ui, "new-graph-height", "Height", &mut app.ui.new_graph_height, side_width)); + }); + ui.add_space(14.0); + } + + ui.label(RichText::new(tr("Create graph in")).strong()); + let packages: Vec<(u64, String)> = app.session.open_packages().into_iter().map(|(id, package, _, _)| (id, package.name.clone())).collect(); + let current = app + .ui + .new_graph_package + .and_then(|id| packages.iter().find(|(package, _)| *package == id)) + .map_or_else(|| tr("New package").to_string(), |(_, name)| name.clone()); + let combo = egui::ComboBox::from_id_salt("new-graph-package").width(ui.available_width()).selected_text(current).show_ui(ui, |ui| { + ui.selectable_value(&mut app.ui.new_graph_package, None, tr("New package")); + for (id, name) in &packages { + ui.selectable_value(&mut app.ui.new_graph_package, Some(*id), name); + } + }); + crate::widgets::name(&combo.response, egui::Role::ComboBox, "Create graph in"); + + let mut create = std::mem::take(&mut app.ui.new_graph_create_now); + let bottom = ui.max_rect().bottom(); + let bar = egui::Rect::from_min_max(egui::pos2(ui.max_rect().left(), bottom - 32.0), ui.max_rect().right_bottom()); + let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); + if bar_ui.add_sized([BUTTON_WIDTH, 28.0], egui::Button::new(tr("Cancel"))).clicked() { + app.ui.windows.new_graph = false; + } + create |= bar_ui.add_sized([BUTTON_WIDTH, 28.0], crate::widgets::primary_button(&bar_ui, tr("Create"))).clicked(); + create +} + +/// A list of the sides a graph can have +fn side_combo(ui: &mut Ui, id: &str, label: &str, side: &mut u32, width: f32) { + let combo = egui::ComboBox::from_id_salt(id).width(width).selected_text(format!("{side} px")).show_ui(ui, |ui| { + for option in SIDES { + ui.selectable_value(side, option, format!("{option} px")); + } + }); + crate::widgets::name(&combo.response, egui::Role::ComboBox, label); +} diff --git a/crates/ui-egui/src/node_shortcuts.rs b/crates/ui-egui/src/node_shortcuts.rs new file mode 100644 index 00000000..aab3e489 --- /dev/null +++ b/crates/ui-egui/src/node_shortcuts.rs @@ -0,0 +1,82 @@ +//! Node creation shortcuts (Preferences ▸ Shortcuts): a key with modifiers that adds a library +//! entry under the pointer in the graph. The text of a shortcut is the menus' form, "Ctrl+Shift+B", +//! where Ctrl is Command on macOS + +use egui::{Key, Modifiers}; + +/// The library categories whose entries can have a creation shortcut: the atomic nodes and the graph items +pub(crate) const CATEGORIES: [&str; 2] = ["Atomic nodes", "Graph items"]; + +/// The text of a key pressed with `modifiers`, or `None` for a key that cannot start a shortcut +pub(crate) fn text(modifiers: Modifiers, key: Key) -> Option { + // Plain Escape, Tab and Enter keep their usual work: closing, moving focus and confirming + if modifiers.is_none() && matches!(key, Key::Escape | Key::Tab | Key::Enter) { + return None; + } + + let mut parts = Vec::new(); + if modifiers.command { + parts.push("Ctrl"); + } + if modifiers.alt { + parts.push("Alt"); + } + if modifiers.shift { + parts.push("Shift"); + } + parts.push(key.name()); + Some(parts.join("+")) +} + +/// The modifiers and key a shortcut text names +pub(crate) fn parse(text: &str) -> Option<(Modifiers, Key)> { + let mut modifiers = Modifiers::NONE; + let mut key = None; + for part in text.split('+') { + match part { + "Ctrl" | "Cmd" => modifiers.command = true, + "Alt" => modifiers.alt = true, + "Shift" => modifiers.shift = true, + name if key.is_none() => key = Some(Key::from_name(name)?), + _ => return None, + } + } + key.map(|key| (modifiers, key)) +} + +/// The entry whose shortcut was pressed this frame, if any +pub(crate) fn pressed(shortcuts: &std::collections::BTreeMap, input: &egui::InputState) -> Option { + shortcuts.iter().find_map(|(entry, text)| { + let (modifiers, key) = parse(text)?; + (input.modifiers.matches_logically(modifiers) && input.modifiers.shift == modifiers.shift && input.key_pressed(key)).then(|| entry.clone()) + }) +} + +/// The app command a shortcut text already starts, if any +pub(crate) fn taken_by(text: &str) -> Option<&'static str> { + let wanted = parse(text)?; + crate::menus::shortcut_table().into_iter().find(|(_, shortcut)| parse(shortcut) == Some(wanted)).map(|(id, _)| id) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_shortcut_reads_back_as_the_keys_that_made_it() { + let both = Modifiers { command: true, shift: true, ..Modifiers::NONE }; + assert_eq!(text(both, Key::B).as_deref(), Some("Ctrl+Shift+B")); + assert_eq!(parse("Ctrl+Shift+B"), Some((both, Key::B))); + assert_eq!(text(Modifiers::ALT, Key::Num1).and_then(|text| parse(&text)), Some((Modifiers::ALT, Key::Num1))); + + assert_eq!(text(Modifiers::NONE, Key::Escape), None); + assert_eq!(parse("Ctrl+Nope"), None); + assert_eq!(parse("Ctrl+B+C"), None); + } + + #[test] + fn a_shortcut_the_app_already_uses_is_named() { + assert_eq!(taken_by("Ctrl+S"), Some("file.save")); + assert_eq!(taken_by("Ctrl+Shift+B"), None); + } +} diff --git a/crates/ui-egui/src/pattern/canvas.rs b/crates/ui-egui/src/pattern/canvas.rs index b8b1f2c5..e08af383 100644 --- a/crates/ui-egui/src/pattern/canvas.rs +++ b/crates/ui-egui/src/pattern/canvas.rs @@ -87,7 +87,7 @@ fn paint(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> } let mut camera = GraphCamera { origin: bounds.min, pan: editor.pan, zoom: editor.zoom }; - camera.zoom_from_input(ui, bounds); + camera.zoom_from_input(ui, bounds, app.ui.prefs.zoom_direction()); editor.pan = camera.pan; editor.zoom = camera.zoom; crate::graph::grid::paint(&painter, &camera, bounds); diff --git a/crates/ui-egui/src/plugin_manager.rs b/crates/ui-egui/src/plugin_manager.rs new file mode 100644 index 00000000..b255be17 --- /dev/null +++ b/crates/ui-egui/src/plugin_manager.rs @@ -0,0 +1,55 @@ +//! Tools ▸ Plugin Manager: the window only, for now. MaterialCraft loads no plugins yet, so the list +//! is empty and its buttons wait for the plugin system + +use egui::{RichText, vec2}; + +use crate::MaterialCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; + +const WINDOW_SIZE: egui::Vec2 = vec2(700.0, 460.0); +const LOADED_WIDTH: f32 = 110.0; +const BUTTON_WIDTH: f32 = 130.0; + +pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { + let mut open = true; + crate::windows::modal(ctx, "plugin-manager", tr("Plugin Manager"), &mut open, WINDOW_SIZE, |ui| { + let tokens = Tokens::get(ui.ctx()); + ui.set_min_size(WINDOW_SIZE); + let filter = ui.add(egui::TextEdit::singleline(&mut app.ui.plugin_filter).hint_text(tr("Filter")).desired_width(f32::INFINITY)); + crate::widgets::name(&filter, egui::Role::SearchInput, "Filter"); + ui.add_space(6.0); + + // The table's header row, then its rows + let header = ui.available_rect_before_wrap().with_max_y(ui.cursor().top() + 24.0); + ui.painter().rect_filled(header, 0.0, tokens.row_hover); + ui.horizontal(|ui| { + ui.set_height(24.0); + ui.add_space(6.0); + let left = egui::Layout::left_to_right(egui::Align::Center); + let plugins_width = ui.available_width() - LOADED_WIDTH; + ui.allocate_ui_with_layout(vec2(plugins_width, 24.0), left, |ui| { + ui.set_min_width(plugins_width); + ui.label(RichText::new(tr("Plugins")).strong()); + }); + ui.label(RichText::new(tr("Loaded")).strong()); + }); + + let list = ui.available_rect_before_wrap().with_max_y(ui.max_rect().bottom() - 44.0); + ui.painter().rect_filled(list, 0.0, tokens.row); + ui.new_child(egui::UiBuilder::new().max_rect(list.shrink(10.0))) + .label(RichText::new(tr("No plugins are installed. MaterialCraft does not load plugins yet.")).color(tokens.text_dim)); + ui.advance_cursor_after_rect(list); + ui.add_space(8.0); + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let waiting = tr("Plugins are not supported yet"); + for label in ["Refresh", "Install...", "Browse..."] { + ui.add_enabled(false, egui::Button::new(tr(label)).min_size(vec2(BUTTON_WIDTH, 28.0))).on_disabled_hover_text(waiting); + } + }); + }); + if !open { + app.ui.windows.plugin_manager = false; + } +} diff --git a/crates/ui-egui/src/preferences.rs b/crates/ui-egui/src/preferences.rs new file mode 100644 index 00000000..ce737f10 --- /dev/null +++ b/crates/ui-egui/src/preferences.rs @@ -0,0 +1,144 @@ +//! Edit ▸ Preferences: pages listed down the left side, and OK, Cancel and Apply. Changes show as +//! they are made; Cancel (or closing the window) goes back to the preferences as they were when +//! the window opened or Apply was last pressed + +mod general_page; +mod graph_page; +mod library_page; +mod preferences_page; +mod preferences_state; +mod projects_page; +mod shortcuts_page; +mod view3d_page; + +use egui::{RichText, Ui, vec2}; + +pub use preferences_page::PreferencesPage; +pub use preferences_state::PreferencesState; + +use crate::MaterialCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; + +const WINDOW_SIZE: egui::Vec2 = vec2(900.0, 620.0); +const PAGE_LIST_WIDTH: f32 = 150.0; +const PAGE_ROW_HEIGHT: f32 = 36.0; +const BUTTON_WIDTH: f32 = 110.0; +const BUTTON_BAR_HEIGHT: f32 = 40.0; + +/// What the buttons at the bottom of the window asked for +#[derive(Clone, Copy, PartialEq, Eq)] +enum Choice { + Ok, + Cancel, + Apply, +} + +/// A section heading of a page, in capitals like the reference layout +pub(super) fn heading(ui: &mut Ui, title: &str) { + ui.add_space(10.0); + ui.label(RichText::new(tr(title).to_uppercase()).size(13.0).strong().color(Tokens::get(ui.ctx()).text_strong)); + ui.add_space(2.0); +} + +/// A labelled whole-number field with a unit after it. Returns true when it changed +pub(super) fn number_row(ui: &mut Ui, label: &str, value: &mut T, range: std::ops::RangeInclusive, unit: &str) -> bool { + ui.horizontal(|ui| { + let caption = ui.label(tr(label)); + let changed = ui.add(egui::DragValue::new(value).range(range).speed(0.2)).labelled_by(caption.id).changed(); + ui.label(tr(unit)); + changed + }) + .inner +} + +pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { + if app.ui.preferences.applied.is_none() { + app.ui.preferences.applied = Some(app.ui.prefs.clone()); + } + + let mut open = true; + let mut choice = None; + let mut rebuild_previews = false; + crate::windows::modal(ctx, "prefs", tr("Preferences"), &mut open, WINDOW_SIZE, |ui| { + ui.set_min_size(WINDOW_SIZE); + let whole = ui.available_rect_before_wrap(); + let bar_top = whole.bottom() - BUTTON_BAR_HEIGHT; + let list = egui::Rect::from_min_max(whole.min, egui::pos2(whole.left() + PAGE_LIST_WIDTH, bar_top)); + let page = egui::Rect::from_min_max(egui::pos2(list.right() + 16.0, whole.top()), egui::pos2(whole.right(), bar_top)); + + page_list(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(list))); + + let mut page_ui = ui.new_child(egui::UiBuilder::new().max_rect(page)); + egui::ScrollArea::vertical().id_salt("preferences-page").auto_shrink([false, false]).show(&mut page_ui, |ui| { + ui.set_width(page.width() - 12.0); + match app.ui.preferences.page { + PreferencesPage::General => general_page::show(app, ui), + PreferencesPage::Projects => projects_page::show(app, ui), + PreferencesPage::Graph => graph_page::show(app, ui), + PreferencesPage::View3d => view3d_page::show(app, ui), + PreferencesPage::Library => rebuild_previews = library_page::show(app, ui), + PreferencesPage::Shortcuts => shortcuts_page::show(app, ui), + } + }); + + let bar = egui::Rect::from_min_max(egui::pos2(whole.left(), bar_top), whole.max); + let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); + for (label, pressed) in [("Apply", Choice::Apply), ("Cancel", Choice::Cancel), ("OK", Choice::Ok)] { + let button = if pressed == Choice::Ok { crate::widgets::primary_button(&bar_ui, tr(label)) } else { egui::Button::new(tr(label)) }; + if bar_ui.add_sized([BUTTON_WIDTH, 28.0], button).clicked() { + choice = Some(pressed); + } + } + ui.advance_cursor_after_rect(whole); + }); + + if rebuild_previews { + app.run("library.cache.clear", serde_json::json!({})); + } + + // Closing the window is Cancel + let choice = if open { choice } else { Some(Choice::Cancel) }; + match choice { + Some(Choice::Apply) => app.ui.preferences.applied = Some(app.ui.prefs.clone()), + Some(Choice::Cancel) => { + if let Some(applied) = app.ui.preferences.applied.take() { + app.ui.prefs = applied; + } + close(app); + } + Some(Choice::Ok) => close(app), + None => {} + } + app.apply_prefs(); +} + +fn close(app: &mut MaterialCraftApp) { + app.ui.windows.preferences = false; + app.ui.preferences.applied = None; + app.ui.preferences.capturing = None; +} + +/// The pages down the left side; the chosen one is highlighted +fn page_list(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.painter().rect_filled(ui.max_rect(), 0.0, tokens.row); + + for page in PreferencesPage::ALL { + let chosen = app.ui.preferences.page == page; + let label = RichText::new(tr(page.label()).to_uppercase()).size(14.0).color(if chosen { tokens.text_strong } else { tokens.text }); + let button = egui::Button::selectable(chosen, label).frame_when_inactive(false); + let row = ui + .allocate_ui_with_layout( + vec2(ui.available_width(), PAGE_ROW_HEIGHT), + egui::Layout::left_to_right(egui::Align::Center).with_main_justify(true).with_main_align(egui::Align::LEFT), + |ui| ui.add(button), + ) + .inner; + crate::widgets::name(&row, egui::Role::Tab, page.label()); + if row.clicked() { + app.ui.preferences.page = page; + app.ui.preferences.capturing = None; + } + } +} diff --git a/crates/ui-egui/src/preferences/general_page.rs b/crates/ui-egui/src/preferences/general_page.rs new file mode 100644 index 00000000..c9e53562 --- /dev/null +++ b/crates/ui-egui/src/preferences/general_page.rs @@ -0,0 +1,74 @@ +//! Preferences ▸ General: recent packages, history, language, appearance, views, autosave and previews + +use egui::Ui; + +use super::{heading, number_row}; +use crate::MaterialCraftApp; +use crate::i18n::tr; +use crate::state::Prefs; +use crate::theme::{Accent, Brightness}; + +/// The most undo steps the history slider reaches +const MAX_UNDO_STEPS: f32 = 10_000.0; +/// The longest autosave interval the slider reaches, in minutes +const MAX_AUTOSAVE_MINUTES: f32 = 60.0; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let prefs = &mut app.ui.prefs; + + heading(ui, "Recent documents"); + number_row(ui, "Recent packages list contains", &mut prefs.recent_limit, 1..=Prefs::MAX_RECENT, "packages"); + + heading(ui, "History"); + let mut undo_limit = prefs.history.undo_limit as f32; + if crate::widgets::slider(ui, tr("Undo history (steps)"), &mut undo_limit, 1.0..=MAX_UNDO_STEPS, 0).changed() { + prefs.history.undo_limit = undo_limit.round() as u32; + } + + heading(ui, "Language"); + crate::widgets::combo(ui, tr("Language"), crate::i18n::current().name, |ui| { + for language in &crate::i18n::LANGUAGES { + if ui.selectable_label(prefs.language == language.code, language.name).clicked() { + prefs.language = language.code.to_owned(); + crate::i18n::set_language(&prefs.language); + } + } + }); + + heading(ui, "Appearance"); + crate::widgets::combo(ui, tr("Brightness"), tr(prefs.brightness.label()), |ui| { + for brightness in Brightness::ALL { + ui.selectable_value(&mut prefs.brightness, brightness, tr(brightness.label())); + } + }); + crate::widgets::combo(ui, tr("Accent color"), tr(prefs.accent.label()), |ui| { + for accent in Accent::ALL { + ui.selectable_value(&mut prefs.accent, accent, tr(accent.label())); + } + }); + crate::widgets::slider(ui, tr("Interface scale"), &mut prefs.ui_scale, 0.75..=2.0, 2); + + heading(ui, "Views"); + ui.checkbox(&mut prefs.invert_zoom, tr("Invert zoom in views")); + + heading(ui, "Auto backup"); + let mut minutes = prefs.autosave_minutes as f32; + if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut minutes, 0.0..=MAX_AUTOSAVE_MINUTES, 0).changed() { + prefs.autosave_minutes = minutes.round() as u32; + } + let mut versions = prefs.autosave_versions as usize; + if number_row(ui, "Keep up to", &mut versions, 1..=Prefs::MAX_AUTOSAVE_VERSIONS as usize, "versions") { + prefs.autosave_versions = versions as u32; + } + #[cfg(not(target_arch = "wasm32"))] + ui.label( + egui::RichText::new(format!("{} {}", tr("The copies are numbered files in"), crate::user_dir("autosave").display())) + .small() + .color(crate::theme::Tokens::get(ui.ctx()).text_dim), + ); + + heading(ui, "Cooker"); + crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(prefs.preview_size), |ui| { + crate::preview_resolution::choices(ui, &mut prefs.preview_size); + }); +} diff --git a/crates/ui-egui/src/preferences/graph_page.rs b/crates/ui-egui/src/preferences/graph_page.rs new file mode 100644 index 00000000..1e251730 --- /dev/null +++ b/crates/ui-egui/src/preferences/graph_page.rs @@ -0,0 +1,20 @@ +//! Preferences ▸ Graph: how the graph canvases respond and what opening a graph shows + +use egui::Ui; + +use super::heading; +use crate::MaterialCraftApp; +use crate::i18n::tr; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let prefs = &mut app.ui.prefs; + + heading(ui, "Common"); + ui.checkbox(&mut prefs.tab_opens_node_search, tr("Tab key shows the node search")); + ui.checkbox(&mut prefs.wire_drop_opens_node_search, tr("Create nodes by dropping a wire on empty canvas")); + ui.checkbox(&mut prefs.view_outputs_on_open, tr("View outputs in 3D view when opening a graph")); + + heading(ui, "Material graph"); + ui.checkbox(&mut prefs.thumbnails, tr("Show node thumbnails")); + ui.checkbox(&mut prefs.snap_to_grid, tr("Snap to grid")); +} diff --git a/crates/ui-egui/src/preferences/library_page.rs b/crates/ui-egui/src/preferences/library_page.rs new file mode 100644 index 00000000..e4545104 --- /dev/null +++ b/crates/ui-egui/src/preferences/library_page.rs @@ -0,0 +1,36 @@ +//! Preferences ▸ Library: the library's previews, their cache and its layout + +use egui::Ui; + +use super::heading; +use crate::MaterialCraftApp; +use crate::i18n::tr; + +/// Width of the Rebuild thumbnails button +const REBUILD_WIDTH: f32 = 360.0; + +/// Returns true when the stored previews should be thrown away, which happens after the window drew +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { + let prefs = &mut app.ui.prefs; + let rebuild = ui.add_sized([ui.available_width().min(REBUILD_WIDTH), 24.0], egui::Button::new(tr("Rebuild thumbnails"))).clicked(); + ui.label(tr("Previews rebuild as they come into view.")); + + heading(ui, "Library preview cache"); + #[cfg(not(target_arch = "wasm32"))] + { + use materialcraft_engine::LibraryCachePrefs; + + ui.horizontal(|ui| { + let label = ui.label(tr("Disk limit (MiB, 0 = off)")); + ui.add(egui::DragValue::new(&mut prefs.library_cache.disk_mib).range(0..=LibraryCachePrefs::MAX_DISK_MIB)).labelled_by(label.id); + }); + ui.horizontal(|ui| { + let label = ui.label(tr("Maximum stored previews")); + ui.add(egui::DragValue::new(&mut prefs.library_cache.max_previews).range(1..=LibraryCachePrefs::MAX_PREVIEWS)).labelled_by(label.id); + }); + } + + heading(ui, "Layout"); + ui.checkbox(&mut prefs.library_list, tr("Show the library as a list")); + rebuild +} diff --git a/crates/ui-egui/src/preferences/preferences_page.rs b/crates/ui-egui/src/preferences/preferences_page.rs new file mode 100644 index 00000000..9eb94b02 --- /dev/null +++ b/crates/ui-egui/src/preferences/preferences_page.rs @@ -0,0 +1,34 @@ +/// A page of the Preferences window, listed down its left side +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PreferencesPage { + #[default] + General, + Projects, + Graph, + View3d, + Library, + Shortcuts, +} + +impl PreferencesPage { + pub const ALL: [PreferencesPage; 6] = [ + PreferencesPage::General, + PreferencesPage::Projects, + PreferencesPage::Graph, + PreferencesPage::View3d, + PreferencesPage::Library, + PreferencesPage::Shortcuts, + ]; + + /// The English name in the page list; the UI translates it + pub fn label(self) -> &'static str { + match self { + PreferencesPage::General => "General", + PreferencesPage::Projects => "Projects", + PreferencesPage::Graph => "Graph", + PreferencesPage::View3d => "3D View", + PreferencesPage::Library => "Library", + PreferencesPage::Shortcuts => "Shortcuts", + } + } +} diff --git a/crates/ui-egui/src/preferences/preferences_state.rs b/crates/ui-egui/src/preferences/preferences_state.rs new file mode 100644 index 00000000..e716399b --- /dev/null +++ b/crates/ui-egui/src/preferences/preferences_state.rs @@ -0,0 +1,16 @@ +use super::PreferencesPage; +use crate::state::Prefs; + +/// What the open Preferences window keeps between frames +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PreferencesState { + pub page: PreferencesPage, + /// The preferences as they were when the window opened or Apply was last pressed; Cancel goes back to them + pub applied: Option, + /// The Shortcuts page's search texts and filter + pub shortcut_search: String, + pub shortcut_key_search: String, + pub only_assigned: bool, + /// The library entry whose shortcut field waits for keys + pub capturing: Option, +} diff --git a/crates/ui-egui/src/preferences/projects_page.rs b/crates/ui-egui/src/preferences/projects_page.rs new file mode 100644 index 00000000..2c24a46d --- /dev/null +++ b/crates/ui-egui/src/preferences/projects_page.rs @@ -0,0 +1,41 @@ +//! Preferences ▸ Projects: the 3D view a new package and a reset start from + +use egui::Ui; +use materialcraft_engine::view_cmds::ENVIRONMENTS; + +use super::heading; +use crate::MaterialCraftApp; +use crate::i18n::tr; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = crate::theme::Tokens::get(ui.ctx()); + let prefs = &mut app.ui.prefs; + let mut view = prefs.default_view3d.clone().unwrap_or_default(); + + heading(ui, "Default 3D view"); + let saved = if prefs.default_view3d.is_some() { tr("A saved default is in use") } else { tr("The built-in default is in use") }; + ui.label(egui::RichText::new(saved).color(tokens.text_dim)); + ui.label(egui::RichText::new(tr("Save Current State As Default, in the 3D view's Scene menu, saves the whole view here")).small().color(tokens.text_dim)); + + let current = ENVIRONMENTS.iter().find(|(id, _)| *id == view.environment).map_or(view.environment.clone(), |(_, label)| tr(label).to_string()); + crate::widgets::combo(ui, tr("Default environment"), current, |ui| { + for (id, label) in ENVIRONMENTS { + ui.selectable_value(&mut view.environment, (*id).to_string(), tr(label)); + } + }); + + heading(ui, "Default lighting state"); + ui.checkbox(&mut view.ambient.enabled, tr("Ambient Light")); + ui.checkbox(&mut view.lights[0].enabled, tr("Point Light 1")); + ui.checkbox(&mut view.lights[1].enabled, tr("Point Light 2")); + + // Only an actual change makes a saved default out of the built-in one + if view != prefs.default_view3d.clone().unwrap_or_default() { + prefs.default_view3d = Some(view); + } + + ui.add_space(8.0); + if ui.add_enabled(prefs.default_view3d.is_some(), egui::Button::new(tr("Use the built-in default"))).clicked() { + prefs.default_view3d = None; + } +} diff --git a/crates/ui-egui/src/preferences/shortcuts_page.rs b/crates/ui-egui/src/preferences/shortcuts_page.rs new file mode 100644 index 00000000..fa244d01 --- /dev/null +++ b/crates/ui-egui/src/preferences/shortcuts_page.rs @@ -0,0 +1,138 @@ +//! Preferences ▸ Shortcuts: keys that add an atomic node or a graph item under the pointer + +use egui::{Key, RichText, Ui}; +use egui_phosphor::regular as icon; +use materialcraft_engine::node_library::LibraryItem; + +use super::heading; +use crate::MaterialCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; + +const ROW_HEIGHT: f32 = 28.0; +const ICON_SIDE: f32 = 22.0; +const LABEL_WIDTH: f32 = 260.0; +const FIELD_WIDTH: f32 = 220.0; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + heading(ui, "Node creation shortcuts"); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let any = !app.ui.prefs.node_shortcuts.is_empty(); + if ui + .add_enabled_ui(any, |ui| { + crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Remove every node creation shortcut"), false, 22.0) + }) + .inner + .clicked() + { + app.ui.prefs.node_shortcuts.clear(); + } + }); + }); + ui.label(RichText::new(tr("For the material graph: press the keys over the graph to add the node under the pointer")).color(tokens.text_dim)); + + let state = &mut app.ui.preferences; + ui.horizontal(|ui| { + let search = ui.add(egui::TextEdit::singleline(&mut state.shortcut_search).hint_text(tr("Search")).desired_width(LABEL_WIDTH)); + crate::widgets::name(&search, egui::Role::SearchInput, "Search"); + let by_key = ui.add(egui::TextEdit::singleline(&mut state.shortcut_key_search).hint_text(tr("Search by shortcut")).desired_width(FIELD_WIDTH)); + crate::widgets::name(&by_key, egui::Role::SearchInput, "Search by shortcut"); + ui.toggle_value(&mut state.only_assigned, tr("Show all assigned")); + }); + ui.add_space(4.0); + + let (search, key_search, only_assigned) = (state.shortcut_search.to_lowercase(), state.shortcut_key_search.to_lowercase(), state.only_assigned); + let entries: Vec<_> = app + .session + .library_entries() + .into_iter() + .filter(|entry| entry.missing.is_none() && crate::node_shortcuts::CATEGORIES.contains(&entry.category.as_str())) + .filter(|entry| search.is_empty() || entry.label.to_lowercase().contains(&search)) + .filter(|entry| { + let shortcut = app.ui.prefs.node_shortcuts.get(&entry.id).map(|text| text.to_lowercase()); + (!only_assigned || shortcut.is_some()) && (key_search.is_empty() || shortcut.is_some_and(|text| text.contains(&key_search))) + }) + .collect(); + + capture(app, ui); + egui::ScrollArea::vertical().auto_shrink([false, false]).show_rows(ui, ROW_HEIGHT, entries.len(), |ui, rows| { + for entry in &entries[rows] { + ui.horizontal(|ui| { + ui.set_height(ROW_HEIGHT); + let picture = match &entry.item { + LibraryItem::Node { def } if def != "dot" => app.thumbs.library(ui.ctx(), def), + _ => None, + }; + match picture { + Some(texture) => { + ui.add(egui::Image::new((texture, egui::vec2(ICON_SIDE, ICON_SIDE))).corner_radius(3)); + } + None => { + ui.add_sized([ICON_SIDE, ICON_SIDE], egui::Label::new(RichText::new(icon::FLOW_ARROW).color(tokens.text_dim))); + } + } + let left = egui::Layout::left_to_right(egui::Align::Center); + ui.allocate_ui_with_layout(egui::vec2(LABEL_WIDTH, ROW_HEIGHT), left, |ui| { + ui.set_min_width(LABEL_WIDTH); + ui.add(egui::Label::new(tr(&entry.label)).truncate()); + }); + field(app, ui, &entry.id, &entry.label); + }); + } + }); +} + +/// The button that shows an entry's shortcut and, clicked, waits for new keys +fn field(app: &mut MaterialCraftApp, ui: &mut Ui, entry: &str, label: &str) { + let waiting = app.ui.preferences.capturing.as_deref() == Some(entry); + let text = if waiting { + tr("Press keys, Backspace to clear, Esc to cancel").to_string() + } else { + app.ui.prefs.node_shortcuts.get(entry).map(|text| crate::menus::shortcut_label(ui.ctx(), text)).unwrap_or_default() + }; + + // A field-like button, framed even while empty, so every row shows where its keys go + let tokens = Tokens::get(ui.ctx()); + let fill = if waiting { tokens.tool_active } else { tokens.field }; + let field = egui::Button::new(text).fill(fill).stroke(egui::Stroke::new(1.0, tokens.field_border)); + let button = ui.add_sized([FIELD_WIDTH, ROW_HEIGHT - 6.0], field); + crate::widgets::name(&button, egui::Role::Button, &format!("Shortcut for {label}")); + if button.clicked() { + app.ui.preferences.capturing = Some(entry.to_string()); + } +} + +/// While a field waits, the next key press with its modifiers becomes that entry's shortcut +fn capture(app: &mut MaterialCraftApp, ui: &mut Ui) { + let Some(entry) = app.ui.preferences.capturing.clone() else { return }; + + let pressed = ui.input(|input| { + input.events.iter().find_map(|event| match event { + egui::Event::Key { key, pressed: true, modifiers, .. } => Some((*modifiers, *key)), + _ => None, + }) + }); + let Some((modifiers, key)) = pressed else { return }; + + app.ui.preferences.capturing = None; + if modifiers.is_none() && key == Key::Escape { + return; + } + if modifiers.is_none() && matches!(key, Key::Backspace | Key::Delete) { + app.ui.prefs.node_shortcuts.remove(&entry); + return; + } + + let Some(text) = crate::node_shortcuts::text(modifiers, key) else { return }; + + if let Some(command) = crate::node_shortcuts::taken_by(&text) { + app.toast(format!("{text} {} {command}", tr("is already the shortcut of")), true); + return; + } + + // A shortcut adds one entry: giving it to this one takes it from any other + app.ui.prefs.node_shortcuts.retain(|_, assigned| *assigned != text); + app.ui.prefs.node_shortcuts.insert(entry, text); +} diff --git a/crates/ui-egui/src/preferences/view3d_page.rs b/crates/ui-egui/src/preferences/view3d_page.rs new file mode 100644 index 00000000..bc973d18 --- /dev/null +++ b/crates/ui-egui/src/preferences/view3d_page.rs @@ -0,0 +1,37 @@ +//! Preferences ▸ 3D View: what a new 3D view shows and how its camera moves + +use egui::Ui; +use materialcraft_engine::geom::view::Background; + +use super::heading; +use crate::MaterialCraftApp; +use crate::i18n::tr; + +/// The renderer's rays per pixel side, with the names the sample count list shows +const SAMPLE_COUNTS: [(u32, &str); 3] = [(1, "Low (1 spp)"), (2, "Medium (4 spp)"), (4, "High (16 spp)")]; +/// The furthest the 3D camera's target may move from the mesh, in mesh radii +const MAX_PAN_LIMIT: f32 = 20.0; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let prefs = &mut app.ui.prefs; + let mut view = prefs.default_view3d.clone().unwrap_or_default(); + + heading(ui, "Misc"); + let mut environment_shown = view.background == Background::Environment; + if ui.checkbox(&mut environment_shown, tr("Environment shown behind the mesh by default")).changed() { + view.background = if environment_shown { Background::Environment } else { Background::default() }; + } + let current = SAMPLE_COUNTS.iter().find(|(samples, _)| *samples == view.samples).map_or("", |(_, label)| label); + crate::widgets::combo(ui, tr("Sample count"), tr(current), |ui| { + for (samples, label) in SAMPLE_COUNTS { + ui.selectable_value(&mut view.samples, samples, tr(label)); + } + }); + if view != prefs.default_view3d.clone().unwrap_or_default() { + prefs.default_view3d = Some(view); + } + + heading(ui, "Camera"); + crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut prefs.camera.pan_limit, 0.0..=MAX_PAN_LIMIT, 1); + crate::widgets::slider(ui, tr("3D pan speed"), &mut prefs.camera.pan_speed, 0.1..=4.0, 2); +} diff --git a/crates/ui-egui/src/shell/modality.rs b/crates/ui-egui/src/shell/modality.rs index 4cac47d1..0ce3e974 100644 --- a/crates/ui-egui/src/shell/modality.rs +++ b/crates/ui-egui/src/shell/modality.rs @@ -96,8 +96,14 @@ fn open_blocker(app: &MaterialCraftApp) -> Option { if windows.package_save.is_some() { return Some(Blocker::Dialog); } - (app.expose_parameter_dialog.is_some() || windows.new_graph || windows.export || windows.preferences || windows.about || app.ui.explorer.rename.is_some()) - .then_some(Blocker::Dialog) + (app.expose_parameter_dialog.is_some() + || windows.new_graph + || windows.export + || windows.preferences + || windows.about + || windows.plugin_manager + || app.ui.explorer.rename.is_some()) + .then_some(Blocker::Dialog) } #[cfg(test)] diff --git a/crates/ui-egui/src/state/prefs.rs b/crates/ui-egui/src/state/prefs.rs index fbcfc6f4..a1fc1824 100644 --- a/crates/ui-egui/src/state/prefs.rs +++ b/crates/ui-egui/src/state/prefs.rs @@ -29,6 +29,34 @@ pub struct Prefs { pub camera: CameraPrefs, /// The 3D view a reset and a new document start from (3D view ▸ Scene ▸ Save Current State As Default) pub default_view3d: Option, + /// How many packages File ▸ Recent packages lists + pub recent_limit: usize, + /// Scrolling up zooms out in the graph, the 2D view and the 3D view + pub invert_zoom: bool, + /// Autosaved copies kept for each package, newest first + pub autosave_versions: u32, + /// Tab over the graph opens the node search + pub tab_opens_node_search: bool, + /// A wire dropped on empty canvas opens the node search to connect a new node + pub wire_drop_opens_node_search: bool, + /// Opening a material graph shows its outputs in the 3D view + pub view_outputs_on_open: bool, + /// Node creation shortcuts: library entry id to shortcut text ("Ctrl+Shift+B") + pub node_shortcuts: std::collections::BTreeMap, + /// Windows ▸ Main toolbar + pub show_toolbar: bool, +} + +impl Prefs { + /// What a wheel step up does to the zoom: 1 zooms in, -1 zooms out when the zoom is inverted + pub fn zoom_direction(&self) -> f32 { + if self.invert_zoom { -1.0 } else { 1.0 } + } + + /// Most packages the recent list can hold + pub const MAX_RECENT: usize = 30; + /// Most autosaved copies kept for a package + pub const MAX_AUTOSAVE_VERSIONS: u32 = 50; } impl Default for Prefs { @@ -48,6 +76,14 @@ impl Default for Prefs { show_home: true, camera: CameraPrefs::default(), default_view3d: None, + recent_limit: 10, + invert_zoom: false, + autosave_versions: 6, + tab_opens_node_search: true, + wire_drop_opens_node_search: true, + view_outputs_on_open: true, + node_shortcuts: Default::default(), + show_toolbar: true, } } } @@ -66,11 +102,17 @@ mod tests { assert!(old.snap_to_grid); assert_eq!(old.history, HistoryPrefs::default()); assert_eq!(old.library_cache, LibraryCachePrefs::default()); + assert_eq!((old.recent_limit, old.autosave_versions, old.invert_zoom), (10, 6, false)); + assert!(old.tab_opens_node_search && old.wire_drop_opens_node_search && old.view_outputs_on_open && old.show_toolbar); + assert!(old.node_shortcuts.is_empty()); let p = Prefs { camera: CameraPrefs { pan_limit: 8.0, pan_speed: 0.5 }, history: HistoryPrefs { undo_limit: 500 }, library_cache: LibraryCachePrefs { disk_mib: 512, max_previews: 12000 }, + recent_limit: 4, + invert_zoom: true, + node_shortcuts: [("blur".to_string(), "Ctrl+Shift+B".to_string())].into(), ..Prefs::default() }; @@ -79,6 +121,8 @@ mod tests { assert_eq!(v["camera"], serde_json::json!({"panLimit": 8.0, "panSpeed": 0.5})); assert_eq!(v["history"]["undoLimit"], 500); assert_eq!(v["libraryCache"], serde_json::json!({"diskMib": 512, "maxPreviews": 12000})); + assert_eq!((v["recentLimit"].clone(), v["invertZoom"].clone()), (serde_json::json!(4), serde_json::json!(true))); + assert_eq!(v["nodeShortcuts"], serde_json::json!({"blur": "Ctrl+Shift+B"})); assert_eq!(serde_json::from_value::(v).unwrap(), p); } diff --git a/crates/ui-egui/src/state/ui_state.rs b/crates/ui-egui/src/state/ui_state.rs index f07467b7..c1cf4a85 100644 --- a/crates/ui-egui/src/state/ui_state.rs +++ b/crates/ui-egui/src/state/ui_state.rs @@ -35,11 +35,29 @@ pub struct UiState { pub new_graph_template: String, pub new_graph_name: String, pub new_graph_size: u32, + pub new_graph_height: u32, + /// The width and height of a new graph change together + pub new_graph_linked: bool, + /// The category of templates shown; `None` lists them all + #[serde(skip)] + pub new_graph_category: Option, + /// The package a new graph goes in; `None` is a new package + #[serde(skip)] + pub new_graph_package: Option, + /// A card was double-clicked: create on this frame + #[serde(skip)] + pub new_graph_create_now: bool, /// Export window: the saved settings, the open tab and the copy the open window edits pub export: crate::export::ExportSettings, pub export_tab: crate::export::ExportTab, #[serde(skip)] pub export_draft: Option, + /// The open Preferences window's page, the preferences Cancel returns to, and the Shortcuts page's search + #[serde(skip)] + pub preferences: crate::preferences::PreferencesState, + /// The Plugin Manager's filter text + #[serde(skip)] + pub plugin_filter: String, /// Frame the whole graph on the next frame #[serde(skip)] pub frame_all: bool, @@ -67,19 +85,26 @@ impl Default for UiState { new_graph_template: "pbr".into(), new_graph_name: "New_graph".into(), new_graph_size: 1024, + new_graph_height: 1024, + new_graph_linked: true, + new_graph_category: None, + new_graph_package: None, + new_graph_create_now: false, export: crate::export::ExportSettings::default(), export_tab: crate::export::ExportTab::default(), export_draft: None, + preferences: Default::default(), + plugin_filter: String::new(), frame_all: true, } } } impl UiState { - /// Remember `path` at the top of the recent list + /// Remember `path` at the top of the recent list, keeping as many as the preferences ask for pub fn add_recent(&mut self, path: &str) { - self.recent.retain(|p| p != path); + self.recent.retain(|recent| recent != path); self.recent.insert(0, path.to_string()); - self.recent.truncate(12); + self.recent.truncate(self.prefs.recent_limit.clamp(1, Prefs::MAX_RECENT)); } } diff --git a/crates/ui-egui/src/state/windows.rs b/crates/ui-egui/src/state/windows.rs index 4bc9931e..c7010f76 100644 --- a/crates/ui-egui/src/state/windows.rs +++ b/crates/ui-egui/src/state/windows.rs @@ -10,6 +10,7 @@ pub struct Windows { pub preferences: bool, pub shortcuts: bool, pub home: bool, + pub plugin_manager: bool, #[cfg(any(test, target_arch = "wasm32"))] #[serde(skip)] pub package_save: Option, diff --git a/crates/ui-egui/src/template_card.rs b/crates/ui-egui/src/template_card.rs new file mode 100644 index 00000000..e5ebf6d9 --- /dev/null +++ b/crates/ui-egui/src/template_card.rs @@ -0,0 +1,90 @@ +//! The template cards of the New graph dialog and the home screen: a rendered preview, a name, +//! the kind of graph, and an information button that says what the template holds + +use egui::{Color32, RichText, Sense, Ui, vec2}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::GraphKind; + +use crate::i18n::tr; +use crate::theme::Tokens; + +pub(crate) const CARD_SIZE: egui::Vec2 = vec2(140.0, 196.0); +const PREVIEW_SIDE: f32 = 96.0; + +/// A template a new graph can start from +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct TemplateCard { + /// The `file.new` template id; function graphs have one template + pub id: &'static str, + pub label: &'static str, + pub kind: GraphKind, + pub description: &'static str, +} + +/// The id the function graph card goes by +pub(crate) const FUNCTION_TEMPLATE: &str = "function"; + +/// Every card: the material templates the engine has, then the function graph +pub(crate) fn cards() -> Vec { + let material = + materialcraft_engine::samples::TEMPLATES.iter().map(|(id, label)| TemplateCard { id, label, kind: GraphKind::Material, description: description(id) }); + let function = TemplateCard { id: FUNCTION_TEMPLATE, label: "Function graph", kind: GraphKind::Function, description: description(FUNCTION_TEMPLATE) }; + material.chain(std::iter::once(function)).collect() +} + +/// What a template holds, in a sentence +fn description(id: &str) -> &'static str { + match id { + "empty" => "An empty material graph", + "pbr" => "Base color, normal, roughness, metallic, height and ambient occlusion outputs, ready to connect", + "atomics" => "A small graph of atomic nodes working together", + FUNCTION_TEMPLATE => "An empty function graph: a value computed from function nodes", + _ => "", + } +} + +impl TemplateCard { + /// The name the kind of graph goes by under the card's title + pub fn kind_label(&self) -> &'static str { + if self.kind == GraphKind::Function { "Function" } else { "Material" } + } +} + +/// Draw a card; `preview` is its rendered picture once ready. Returns the card's response +pub(crate) fn show(ui: &mut Ui, card: &TemplateCard, chosen: bool, preview: Option) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(CARD_SIZE, Sense::click()); + crate::widgets::name(&response, egui::Role::ListItem, card.label); + + let fill = if chosen || response.hovered() { tokens.row_hover } else { tokens.row }; + ui.painter().rect_filled(rect, 6.0, fill); + if chosen { + ui.painter().rect_stroke(rect, 6.0, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Inside); + } + + let picture = egui::Rect::from_center_size(egui::pos2(rect.center().x, rect.top() + 18.0 + PREVIEW_SIDE * 0.5), vec2(PREVIEW_SIDE, PREVIEW_SIDE)); + match (preview, card.kind) { + (Some(texture), _) => { + ui.painter().image(texture, picture, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); + } + (None, GraphKind::Function) => { + ui.painter().text(picture.center(), egui::Align2::CENTER_CENTER, icon::FUNCTION, egui::FontId::proportional(48.0), tokens.text_dim); + } + (None, _) => { + ui.painter().circle_filled(picture.center(), PREVIEW_SIDE * 0.45, tokens.separator); + } + } + + let title = ui.painter().layout(tr(card.label).to_string(), egui::FontId::proportional(13.0), tokens.text_strong, CARD_SIZE.x - 12.0); + ui.painter().galley(egui::pos2(rect.center().x - title.size().x * 0.5, picture.bottom() + 14.0), title, tokens.text_strong); + let kind = tr(card.kind_label()); + ui.painter().text(egui::pos2(rect.center().x, rect.bottom() - 18.0), egui::Align2::CENTER_CENTER, kind, egui::FontId::proportional(11.0), tokens.text_dim); + + // The information button tells what the template holds + let info = egui::Rect::from_center_size(rect.right_top() + vec2(-16.0, 16.0), vec2(18.0, 18.0)); + let info_response = ui.interact(info, response.id.with("info"), Sense::hover()); + ui.painter().text(info.center(), egui::Align2::CENTER_CENTER, icon::INFO, egui::FontId::proportional(16.0), tokens.text_dim); + info_response.on_hover_text(RichText::new(tr(card.description))); + + response +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 569a87b3..ab1f9d9b 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -41,7 +41,11 @@ pub fn status_bar(app: &mut MaterialCraftApp, ui: &mut Ui) { egui::Panel::bottom("status_bar").exact_size(22.0).frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(8, 0))).show(ui, |ui| { ui.horizontal_centered(|ui| { let busy = app.cooker.busy(); - if busy { + if app.cooker.suspended { + ui.label( + RichText::new(tr("Engine suspended: choose Suspend engine in the Tools menu again (Shift+Escape) to resume")).size(11.0).color(tk.warning), + ); + } else if busy { ui.add(egui::Spinner::new().size(12.0)); ui.label(RichText::new(tr("Computing...")).size(11.0).color(tk.text_dim)); } else if !app.status.is_empty() { diff --git a/crates/ui-egui/src/view2d/viewport.rs b/crates/ui-egui/src/view2d/viewport.rs index 4b835074..3c4079a2 100644 --- a/crates/ui-egui/src/view2d/viewport.rs +++ b/crates/ui-egui/src/view2d/viewport.rs @@ -156,7 +156,7 @@ fn place(app: &mut MaterialCraftApp, ui: &Ui, response: &Response, rect: Rect, s } if response.hovered() { - let scroll = ui.input(|input| input.smooth_scroll_delta.y); + let scroll = app.ui.prefs.zoom_direction() * ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { // One notch of a mouse wheel scrolls one line, and zooms one step let points_per_notch = ui.ctx().options(|options| options.input_options.line_scroll_speed).max(1.0); diff --git a/crates/ui-egui/src/view3d/navigation.rs b/crates/ui-egui/src/view3d/navigation.rs index b4e2e575..ad0b0bc1 100644 --- a/crates/ui-egui/src/view3d/navigation.rs +++ b/crates/ui-egui/src/view3d/navigation.rs @@ -56,7 +56,7 @@ pub(super) fn handle(app: &mut MaterialCraftApp, ui: &Ui, response: &Response, a } if response.hovered() { - let scroll = ui.input(|input| input.smooth_scroll_delta.y); + let scroll = app.ui.prefs.zoom_direction() * ui.input(|input| input.smooth_scroll_delta.y); if scroll.abs() > 0.0 { // One notch of a mouse wheel scrolls one line let points_per_notch = ui.ctx().options(|options| options.input_options.line_scroll_speed).max(1.0); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 3b8b2033..6ca81c6b 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -11,8 +11,7 @@ use serde_json::{Value, json}; use crate::MaterialCraftApp; use crate::i18n::tr; -use crate::shell::modality::Modality; -use crate::theme::{Accent, Brightness, Tokens}; +use crate::theme::Tokens; /// Template previews for the New graph dialog (rendered in the background on first open) #[derive(Default)] @@ -75,19 +74,24 @@ thread_local! { static TEMPLATES: std::cell::RefCell = std::cell::RefCell::new(TemplatePreviews::default()); } +/// A template's rendered preview, once the background render has finished +pub(crate) fn template_preview(ctx: &egui::Context, id: &str) -> Option { + TEMPLATES.with(|previews| previews.borrow_mut().get(ctx, id)) +} + pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { if let Some(error) = app.thumbs.tick(ctx, &app.session.library, app.cooker.busy() || app.session.dirty) { app.toast(error, true); } if app.ui.windows.new_graph { - new_graph(app, ctx); + crate::new_graph_dialog::show(app, ctx); } if app.ui.windows.export { crate::export::show(app, ctx); } if app.ui.windows.preferences { - preferences(app, ctx); + crate::preferences::show(app, ctx); } if app.ui.windows.about { about(app, ctx); @@ -96,7 +100,10 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { shortcuts(app, ctx); } if app.ui.windows.home { - home(app, ctx); + crate::home_screen::show(app, ctx); + } + if app.ui.windows.plugin_manager { + crate::plugin_manager::show(app, ctx); } crate::unsaved::show(app, ctx); @@ -120,129 +127,6 @@ pub(crate) fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, .show(ctx, body); } -fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) { - use materialcraft_engine::core::GraphKind; - - let mut open = true; - let mut create = false; - modal(ctx, "new-graph", tr("New graph"), &mut open, vec2(440.0, 290.0), |ui| { - ui.horizontal(|ui| { - ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Material, tr("Graph")); - ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Function, tr("Function Graph")); - }); - ui.add_space(12.0); - ui.label(tr("Graph name")); - let name = ui.text_edit_singleline(&mut app.ui.new_graph_name); - crate::widgets::name(&name, egui::Role::TextInput, "Graph name"); - - if app.ui.new_graph_kind == GraphKind::Material { - ui.add_space(8.0); - crate::widgets::combo(ui, tr("Template"), app.ui.new_graph_template.clone(), |ui| { - for (id, label) in materialcraft_engine::samples::TEMPLATES { - ui.selectable_value(&mut app.ui.new_graph_template, id.to_string(), tr(label)); - } - }); - let size = egui::ComboBox::from_label(tr("Size")).selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| { - for size in [256u32, 512, 1024, 2048, 4096] { - ui.selectable_value(&mut app.ui.new_graph_size, size, format!("{size} px")); - } - }); - crate::widgets::name(&size.response, egui::Role::ComboBox, "Size"); - } - - ui.add_space(12.0); - ui.label(format!("{}: {}", tr("Package"), app.session.pkg.name)); - ui.add_space(16.0); - ui.horizontal(|ui| { - if ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked() { - create = true; - } - if ui.button(tr("Cancel")).clicked() { - app.ui.windows.new_graph = false; - } - }); - }); - - if create { - let parameters = - json!({"kind": app.ui.new_graph_kind, "template": app.ui.new_graph_template, "name": app.ui.new_graph_name, "size": app.ui.new_graph_size}); - if app.run("file.new", parameters).is_some() { - app.ui.frame_all = true; - open = false; - } - } - if !open { - app.ui.windows.new_graph = false; - } -} - -fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let mut open = true; - let mut clear_cache = false; - modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(400.0, 500.0), |ui| { - let p = &mut app.ui.prefs; - let current_lang = crate::i18n::current(); - crate::widgets::combo(ui, tr("Language"), current_lang.name, |ui| { - for l in &crate::i18n::LANGUAGES { - if ui.selectable_label(p.language == l.code, l.name).clicked() { - p.language = l.code.to_owned(); - crate::i18n::set_language(&p.language); - } - } - }); - crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| { - for b in Brightness::ALL { - ui.selectable_value(&mut p.brightness, b, tr(b.label())); - } - }); - crate::widgets::combo(ui, tr("Accent color"), tr(p.accent.label()), |ui| { - for a in Accent::ALL { - ui.selectable_value(&mut p.accent, a, tr(a.label())); - } - }); - crate::widgets::slider(ui, tr("Interface scale"), &mut p.ui_scale, 0.75..=2.0, 2); - let mut auto = p.autosave_minutes as f32; - if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut auto, 0.0..=60.0, 0).changed() { - p.autosave_minutes = auto.round() as u32; - } - let mut undo_limit = p.history.undo_limit as f32; - if crate::widgets::slider(ui, tr("Undo history (steps)"), &mut undo_limit, 1.0..=10_000.0, 0).changed() { - p.history.undo_limit = undo_limit.round() as u32; - } - crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(p.preview_size), |ui| { - crate::preview_resolution::choices(ui, &mut p.preview_size); - }); - ui.checkbox(&mut p.thumbnails, tr("Show node thumbnails")); - ui.separator(); - ui.label(tr("Library preview cache")); - #[cfg(not(target_arch = "wasm32"))] - { - use materialcraft_engine::LibraryCachePrefs; - ui.horizontal(|ui| { - let label = ui.label(tr("Disk limit (MiB, 0 = off)")); - ui.add(egui::DragValue::new(&mut p.library_cache.disk_mib).range(0..=LibraryCachePrefs::MAX_DISK_MIB)).labelled_by(label.id); - }); - ui.horizontal(|ui| { - let label = ui.label(tr("Maximum stored previews")); - ui.add(egui::DragValue::new(&mut p.library_cache.max_previews).range(1..=LibraryCachePrefs::MAX_PREVIEWS)).labelled_by(label.id); - }); - } - clear_cache = ui.button(tr("Clear cache")).clicked(); - ui.label(tr("Previews rebuild as they come into view.")); - ui.separator(); - crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut p.camera.pan_limit, 0.0..=20.0, 1); - crate::widgets::slider(ui, tr("3D pan speed"), &mut p.camera.pan_speed, 0.1..=4.0, 2); - }); - if clear_cache { - app.run("library.cache.clear", serde_json::json!({})); - app.apply_prefs(); - } - - if !open { - app.ui.windows.preferences = false; - } -} - fn about(app: &mut MaterialCraftApp, ctx: &egui::Context) { let mut open = true; modal(ctx, "about", tr("About MaterialCraft"), &mut open, vec2(400.0, 260.0), |ui| { @@ -297,96 +181,6 @@ fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { } } -fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let mut open = true; - let mut create: Option<(&str, &str)> = None; - let modality = Modality::capture(app, ctx); - let free = !modality.is_blocked(); - modal(ctx, "home", tr("Home"), &mut open, vec2(760.0, 470.0), |ui| { - let tk = Tokens::get(ui.ctx()); - ui.horizontal_top(|ui| { - // Left rail: actions and links - ui.vertical(|ui| { - ui.set_width(150.0); - if ui.add_enabled(free, crate::widgets::primary_button(ui, tr("New graph"))).clicked() { - app.ui.windows.home = false; - app.ui.windows.new_graph = true; - } - ui.add_space(4.0); - if ui.add_enabled(modality.allows("file.open"), egui::Button::new(format!("{} {}", icon::FOLDER_OPEN, tr("Open package...")))).clicked() { - app.ui.windows.home = false; - crate::menus::invoke(app, ui.ctx(), "file.open"); - } - ui.add_space(16.0); - ui.hyperlink_to(tr("Documentation"), "https://github.com/storytold/materialcraft#readme"); - ui.hyperlink_to(tr("Community (Discord)"), "https://discord.gg/artcraft"); - ui.hyperlink_to("getartcraft.com", "https://getartcraft.com/apps/materialcraft"); - ui.add_space(16.0); - ui.checkbox(&mut app.ui.prefs.show_home, tr("Show at startup")); - }); - ui.separator(); - ui.vertical(|ui| { - ui.label(RichText::new(tr("Welcome to MaterialCraft")).size(18.0).strong().color(tk.text_strong)); - ui.label( - RichText::new(tr( - "Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.", - )) - .color(tk.text_dim), - ); - ui.add_space(8.0); - ui.label(RichText::new(tr("Samples")).strong()); - ui.horizontal_wrapped(|ui| { - if !free { - ui.disable(); - } - for (id, label) in materialcraft_engine::samples::TEMPLATES.iter().filter(|(id, _)| !matches!(*id, "empty" | "pbr")) { - let (r, resp) = ui.allocate_exact_size(vec2(92.0, 116.0), egui::Sense::click()); - crate::widgets::name(&resp, egui::Role::ListItem, label); - if free && resp.hovered() { - ui.painter().rect_filled(r, 6.0, tk.row_hover); - } - let img = egui::Rect::from_min_size(r.min + vec2(6.0, 4.0), vec2(80.0, 80.0)); - match TEMPLATES.with(|t| t.borrow_mut().get(ui.ctx(), id)) { - Some(t) => { - ui.painter().image(t, img, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); - } - None => { - ui.painter().circle_filled(img.center(), 36.0, tk.row); - } - } - let g = ui.painter().layout(tr(label).to_string(), egui::FontId::proportional(11.0), tk.text, 90.0); - ui.painter().galley(egui::pos2(r.center().x - g.size().x * 0.5, img.bottom() + 6.0), g, tk.text); - if free && resp.clicked() { - create = Some((id, label)); - } - } - }); - ui.add_space(8.0); - ui.label(RichText::new(tr("Recent")).strong()); - if app.ui.recent.is_empty() { - ui.label(RichText::new(tr("No recent packages")).color(tk.text_dim)); - } - #[cfg(not(target_arch = "wasm32"))] - for p in app.ui.recent.clone().into_iter().take(6) { - if ui.add_enabled(free, egui::Link::new(&p)).clicked() { - open_path(app, &p); - app.ui.windows.home = false; - } - } - }); - }); - }); - if let Some((id, label)) = create { - if app.run("file.new", json!({"template": id, "name": label.replace(' ', "_"), "size": 1024})).is_some() { - app.ui.frame_all = true; - } - open = false; - } - if !open { - app.ui.windows.home = false; - } -} - pub fn console(app: &mut MaterialCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); let console_line = |text: String, color: Color32| RichText::new(text).monospace().size(11.0).color(color); @@ -564,6 +358,10 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> crate::export::open(app, crate::export::ExportTab::Mcmat); true } + "file.saveAll" => { + save_all(app); + true + } "file.sendToTextureCraft" => { if app.run("file.sendToTextureCraft", json!({})).is_some() { app.toast(tr("Sent to TextureCraft: find it on the shelf under My smart materials"), false); @@ -598,6 +396,33 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> } } +/// File ▸ Save all: save every modified package with a file and say which still need Save as +#[cfg(not(target_arch = "wasm32"))] +fn save_all(app: &mut MaterialCraftApp) { + let Some(reply) = app.run("file.saveAll", json!({})) else { return }; + + let saved: Vec = reply["saved"].as_array().into_iter().flatten().filter_map(|path| path.as_str().map(str::to_string)).collect(); + for path in &saved { + app.ui.add_recent(path); + } + + let names = |key: &str| reply[key].as_array().into_iter().flatten().filter_map(|name| name.as_str()).collect::>().join(", "); + let without_file = names("withoutFile"); + let failed: Vec = reply["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failure| format!("{}: {}", failure["package"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default())) + .collect(); + if !failed.is_empty() { + app.toast(format!("{} {}", tr("Not saved:"), failed.join("; ")), true); + } else if !without_file.is_empty() { + app.toast(format!("{} {} ({without_file})", saved.len(), tr("saved; use Save as for packages without a file")), false); + } else { + app.toast(format!("{} {}", saved.len(), tr("packages saved")), false); + } +} + /// Whether File ▸ Save writes straight to the package's path (a package opened from a URL has none to write to) #[cfg(not(target_arch = "wasm32"))] pub(crate) fn has_local_path(app: &MaterialCraftApp) -> bool { diff --git a/crates/ui-egui/src/windows.test.rs b/crates/ui-egui/src/windows.test.rs index 28379f80..a30223fd 100644 --- a/crates/ui-egui/src/windows.test.rs +++ b/crates/ui-egui/src/windows.test.rs @@ -38,14 +38,14 @@ mod home_modality_tests { fn home_actions_are_live_when_nothing_blocks_them() { let harness = harness(|_| {}); assert!(open_package(&harness)); - assert!(!harness.get(By::new().role(egui::accesskit::Role::Button).label("New graph")).accesskit_node().is_disabled()); + assert!(!harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("New graph")).accesskit_node().is_disabled()); } #[test] fn open_package_is_off_behind_a_dialog_and_home_stays_open() { let harness = harness(|app| app.ui.windows.about = true); assert!(!open_package(&harness)); - assert!(harness.get(By::new().role(egui::accesskit::Role::Button).label("New graph")).accesskit_node().is_disabled()); + assert!(harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("New graph")).accesskit_node().is_disabled()); assert!(harness.state().ui.windows.home); } @@ -62,7 +62,7 @@ mod home_modality_tests { #[test] fn a_sample_tile_and_a_recent_link_wait_behind_a_file_dialog() { let mut harness = harness(file_dialog); - assert!(harness.get(By::new().role(egui::accesskit::Role::Link).label("recent.sbs")).accesskit_node().is_disabled()); + assert!(harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("recent.sbs")).accesskit_node().is_disabled()); let graphs = harness.state().session.pkg.graphs.len(); let (_, sample) = materialcraft_engine::samples::TEMPLATES.iter().find(|(id, _)| !matches!(*id, "empty" | "pbr")).unwrap(); harness.get(By::new().role(egui::accesskit::Role::ListItem).label(sample)).click(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 241c7247..24b52ae8 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -7,9 +7,12 @@ mod dialogs; mod export_window; mod graph_properties; mod interface_scale; +mod menu_bar; +mod new_graph_dialog; mod node_look; mod normal_maps; mod numeric_input; +mod preferences_window; mod preview_resolution; mod resolution; mod search; diff --git a/crates/ui-egui/tests/it/menu_bar.rs b/crates/ui-egui/tests/it/menu_bar.rs new file mode 100644 index 00000000..8d6b8440 --- /dev/null +++ b/crates/ui-egui/tests/it/menu_bar.rs @@ -0,0 +1,72 @@ +//! The menu bar's own items: suspending and resuming the engine, the toolbar switch and the Plugin Manager + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{By, Queryable}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState, menus}; + +fn harness() -> Harness<'static, MaterialCraftApp> { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.ui.windows.home = false; + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + harness.run_steps(6); + harness +} + +fn choose(harness: &mut Harness<'static, MaterialCraftApp>, menu: &str, item: &str) { + harness.get(By::new().role(Role::Button).label(menu)).click(); + harness.run_steps(3); + harness.get(By::new().role(Role::Button).label_contains(item)).click(); + harness.run_steps(3); +} + +#[test] +fn a_suspended_engine_cooks_nothing_until_it_is_resumed() { + let mut harness = harness(); + for _ in 0..200 { + harness.step(); + if !harness.state().cooker.busy() && !harness.state().session.dirty { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + + choose(&mut harness, "Tools", "Suspend engine"); + assert!(harness.state().cooker.suspended); + + harness.state_mut().session.dirty = true; + harness.run_steps(5); + assert!(!harness.state().cooker.busy() && harness.state().session.dirty, "the edit waits"); + + harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Escape); + harness.run_steps(2); + assert!(!harness.state().cooker.suspended, "Shift+Esc resumes the engine"); + assert!(harness.state().cooker.busy() || !harness.state().session.dirty, "and what changed cooks"); +} + +#[test] +fn cancel_rendering_is_only_offered_while_a_cook_runs() { + let harness = harness(); + assert_eq!(menus::enabled(harness.state(), "ui.cook.cancel"), harness.state().cooker.busy()); +} + +#[test] +fn the_main_toolbar_and_the_plugin_manager_open_from_the_menus() { + let mut harness = harness(); + assert!(harness.query_by_label("Open package... (Ctrl+O)").is_some()); + + choose(&mut harness, "Windows", "Main toolbar"); + assert!(!harness.state().ui.prefs.show_toolbar); + assert!(harness.query_by_label("Open package... (Ctrl+O)").is_none(), "the toolbar is hidden"); + + choose(&mut harness, "Tools", "Plugin Manager..."); + assert!(harness.state().ui.windows.plugin_manager); + assert!(harness.query_by_label_contains("MaterialCraft does not load plugins yet").is_some()); +} diff --git a/crates/ui-egui/tests/it/new_graph_dialog.rs b/crates/ui-egui/tests/it/new_graph_dialog.rs new file mode 100644 index 00000000..8365f86a --- /dev/null +++ b/crates/ui-egui/tests/it/new_graph_dialog.rs @@ -0,0 +1,65 @@ +//! File ▸ New ▸ Graph: template cards, the size of the graph and the package it goes in + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{By, Queryable}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState, menus}; + +fn harness() -> Harness<'static, MaterialCraftApp> { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.ui.windows.home = false; + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + harness.run_steps(6); + harness +} + +fn open(harness: &mut Harness<'static, MaterialCraftApp>, id: &str) { + let context = harness.ctx.clone(); + menus::invoke(harness.state_mut(), &context, id); + harness.run_steps(4); +} + +#[test] +fn a_card_and_an_unlinked_size_make_the_graph_in_the_active_package() { + let mut harness = harness(); + let packages = harness.state().session.open_packages().len(); + open(&mut harness, "ui.newGraph"); + + harness.get(By::new().role(Role::ListItem).label("Atomic sample")).click(); + harness.run_steps(2); + harness.get(By::new().role(Role::Button).label("Keep the width and height the same")).click(); + harness.run_steps(2); + harness.state_mut().ui.new_graph_size = 512; + harness.state_mut().ui.new_graph_height = 2048; + harness.get(By::new().role(Role::Button).label("Create")).click(); + harness.run_steps(6); + + let session = &harness.state().session; + assert!(!harness.state().ui.windows.new_graph); + assert_eq!(session.open_packages().len(), packages); + assert_eq!(session.graph().unwrap().size, [9, 11]); + assert!(!session.graph().unwrap().nodes.is_empty(), "the atomic sample's nodes"); +} + +#[test] +fn a_function_graph_can_go_in_a_new_package() { + let mut harness = harness(); + let packages = harness.state().session.open_packages().len(); + open(&mut harness, "ui.newFunctionGraph"); + assert!(harness.query_by_label("Size").is_none(), "a function graph has no size"); + + harness.state_mut().ui.new_graph_package = None; + harness.get(By::new().role(Role::Button).label("Create")).click(); + harness.run_steps(6); + + let session = &harness.state().session; + assert_eq!(session.open_packages().len(), packages + 1); + assert!(session.graph().unwrap().function.is_some()); +} diff --git a/crates/ui-egui/tests/it/preferences_window.rs b/crates/ui-egui/tests/it/preferences_window.rs new file mode 100644 index 00000000..c196e6a0 --- /dev/null +++ b/crates/ui-egui/tests/it/preferences_window.rs @@ -0,0 +1,96 @@ +//! Edit ▸ Preferences: pages, OK, Cancel and Apply, and the node creation shortcuts they set + +use egui::accesskit::Role; +use egui::{Key, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{By, Queryable}; +use materialcraft_ui_egui::preferences::PreferencesPage; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; + +fn harness() -> Harness<'static, MaterialCraftApp> { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.ui.windows.home = false; + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + harness.run_steps(6); + harness +} + +fn open(harness: &mut Harness<'static, MaterialCraftApp>) { + harness.state_mut().ui.windows.preferences = true; + harness.run_steps(4); +} + +fn click(harness: &mut Harness<'static, MaterialCraftApp>, role: Role, label: &str) { + harness.get(By::new().role(role).label(label)).click(); + harness.run_steps(4); +} + +#[test] +fn cancel_returns_to_the_preferences_of_the_last_apply() { + let mut harness = harness(); + open(&mut harness); + + click(&mut harness, Role::CheckBox, "Invert zoom in views"); + assert!(harness.state().ui.prefs.invert_zoom, "a change shows at once"); + click(&mut harness, Role::Button, "Apply"); + + click(&mut harness, Role::Tab, "Graph"); + assert_eq!(harness.state().ui.preferences.page, PreferencesPage::Graph); + click(&mut harness, Role::CheckBox, "Tab key shows the node search"); + assert!(!harness.state().ui.prefs.tab_opens_node_search); + + click(&mut harness, Role::Button, "Cancel"); + let prefs = &harness.state().ui.prefs; + assert!(prefs.invert_zoom, "the applied change stays"); + assert!(prefs.tab_opens_node_search, "the change after Apply is undone"); + assert!(!harness.state().ui.windows.preferences); + + open(&mut harness); + click(&mut harness, Role::CheckBox, "View outputs in 3D view when opening a graph"); + click(&mut harness, Role::Button, "OK"); + assert!(!harness.state().ui.prefs.view_outputs_on_open && !harness.state().session.view_outputs_on_open, "OK keeps the change and the session follows it"); + assert!(!harness.state().ui.windows.preferences); +} + +#[test] +fn a_shortcut_is_captured_refused_when_taken_and_adds_its_node_over_the_graph() { + let mut harness = harness(); + open(&mut harness); + click(&mut harness, Role::Tab, "Shortcuts"); + + click(&mut harness, Role::Button, "Shortcut for Blur"); + harness.key_press_modifiers(Modifiers::COMMAND, Key::S); + harness.run_steps(3); + assert!(harness.state().ui.prefs.node_shortcuts.is_empty(), "Ctrl+S already saves"); + + click(&mut harness, Role::Button, "Shortcut for Blur"); + harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::B); + harness.run_steps(3); + assert_eq!(harness.state().ui.prefs.node_shortcuts.get("node:blur").map(String::as_str), Some("Ctrl+Shift+B")); + + // The same keys on another entry move the shortcut there; the search brings it into view + harness.state_mut().ui.preferences.shortcut_search = "levels".into(); + harness.run_steps(2); + click(&mut harness, Role::Button, "Shortcut for Levels"); + harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::B); + harness.run_steps(3); + assert_eq!(harness.state().ui.prefs.node_shortcuts.len(), 1); + assert!(harness.state().ui.prefs.node_shortcuts.contains_key("node:levels")); + click(&mut harness, Role::Button, "OK"); + + let nodes = harness.state().session.graph().unwrap().nodes.len(); + let canvas = harness.state().graph.view; + harness.hover_at(canvas.center()); + harness.run_steps(2); + harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::B); + harness.run_steps(3); + let graph = harness.state().session.graph().unwrap(); + assert_eq!(graph.nodes.len(), nodes + 1); + assert_eq!(graph.nodes.last().unwrap().def, "levels"); +} diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 1d8f7495..be68e07b 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -31,6 +31,9 @@ mod library; #[path = "snapshot/menu.rs"] mod menu; +#[path = "snapshot/menus_and_preferences.rs"] +mod menus_and_preferences; + #[path = "snapshot/node_search.rs"] mod node_search; @@ -766,11 +769,9 @@ fn empty_startup_can_create_a_template() { } harness.get_by_label("New graph...").click(); settle(&mut harness, 4); - harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Template")).click(); - settle(&mut harness, 2); - harness.get_by_label("Atomic sample").click(); + harness.get(By::new().role(egui::accesskit::Role::ListItem).label("Atomic sample")).click(); settle(&mut harness, 4); - harness.get_by_label("Create").click(); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Create")).click(); settle(&mut harness, 40); assert_eq!(harness.state().session.pkg.graphs.len(), 2); assert!(!harness.state().session.graph().unwrap().nodes.is_empty()); @@ -1166,10 +1167,10 @@ fn annotations_and_function_graph_creation() { harness.state_mut().ui.windows.new_graph = true; settle(&mut harness, 3); - harness.get_by_label("Function Graph").click(); + harness.get(By::new().role(egui::accesskit::Role::ListItem).label("Function graph")).click(); settle(&mut harness, 3); save(&mut harness, &directory, "new-function-graph"); - harness.get_by_label("Create").click(); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Create")).click(); settle(&mut harness, 3); assert_eq!(harness.state().session.graph().unwrap().kind(), GraphKind::Function); @@ -1696,11 +1697,14 @@ fn library_cache_preferences() { settle(&mut h, 4); h.state_mut().ui.windows.preferences = true; settle(&mut h, 4); + // The dock has a Library tab too, so the page is chosen directly + h.state_mut().ui.preferences.page = materialcraft_ui_egui::preferences::PreferencesPage::Library; + settle(&mut h, 4); assert!(h.query_all(By::new().label("Disk limit (MiB, 0 = off)")).next().is_some()); assert!(h.query_all(By::new().label("Maximum stored previews")).next().is_some()); - h.get_by_label("Clear cache").click(); + h.get_by_label("Rebuild thumbnails").click(); settle(&mut h, 4); assert_eq!(h.state().session.library_cache_clear_epoch, 1); diff --git a/crates/ui-egui/tests/snapshot/menus_and_preferences.rs b/crates/ui-egui/tests/snapshot/menus_and_preferences.rs new file mode 100644 index 00000000..90fa17e2 --- /dev/null +++ b/crates/ui-egui/tests/snapshot/menus_and_preferences.rs @@ -0,0 +1,48 @@ +//! Renders of the menu bar's menus, the Preferences pages, the New graph dialog, the home screen +//! and the Plugin Manager + +use egui_kittest::kittest::Queryable; +use materialcraft_ui_egui::preferences::PreferencesPage; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn the_menus_and_their_windows() { + let Some(directory) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&directory).unwrap(); + let app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + let mut harness = super::harness(app, 1600.0, 960.0); + super::settle(&mut harness, 8); + + for menu in ["File", "Edit", "Tools", "Windows", "Help"] { + harness.get_by_label(menu).click(); + super::settle(&mut harness, 4); + super::save(&mut harness, &directory, &format!("menu-{}", menu.to_lowercase())); + harness.key_press(egui::Key::Escape); + super::settle(&mut harness, 2); + } + + harness.state_mut().ui.windows.preferences = true; + for page in PreferencesPage::ALL { + harness.state_mut().ui.preferences.page = page; + super::settle(&mut harness, 6); + super::save(&mut harness, &directory, &format!("preferences-{}", page.label().to_lowercase().replace(' ', "-"))); + } + harness.state_mut().ui.windows.preferences = false; + + // The template previews render in the background + harness.state_mut().ui.windows.new_graph = true; + super::settle(&mut harness, 200); + super::save(&mut harness, &directory, "new-graph"); + harness.state_mut().ui.windows.new_graph = false; + + harness.state_mut().ui.windows.home = true; + super::settle(&mut harness, 10); + super::save(&mut harness, &directory, "home-screen"); + harness.state_mut().ui.windows.home = false; + + harness.state_mut().ui.windows.plugin_manager = true; + super::settle(&mut harness, 6); + super::save(&mut harness, &directory, "plugin-manager"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f1b39372..cfc2a748 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -89,7 +89,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `graph.function.variables` | `{id, target?: FunctionGraphTarget}` returns ordered suggestions matching a Get node's type and caller scope; typed custom names remain supported | | `session.environment` | `{timeSeconds?, uvTile?: [int, int], normalFormat?: int}` updates host evaluation values without modifying the package; `{}` reads them; defaults are zero and the normal-format code is passed through | | `graph.context` | `{physicalSize?: [x, y, z], pixelRatio?: 0\|1, tiling?: [horizontal, vertical]}` edits material-graph metadata with undo; `{}` reads it; reusable functions receive their caller's context | -| `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) | +| `file.new` | `{template?, name?, folder?, kind?, size?, height?, newPackage?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`). `size` is the width in pixels and `height` defaults to it (powers of two, 16 to 8192); `newPackage: true` creates the graph in a new untitled package | | `graph.node.edit` | `{}` resolves the selected FX-Map, processor or graph instance to `{kind, node, parameter?, graph?, document?, path?}`; use `ui.menu.invoke` to open its reference in the graph panel | | `graph.node.info` | `{id}` returns `{text}` describing a main-graph node without changing the document or node clipboard | | `graph.instance.add` | `{document, graph, function?: FunctionGraphTarget, at?, snapToGrid?}` adds a linked graph instance from an open package; requires a source output and rejects dependency cycles | @@ -386,6 +386,7 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k | `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?, linear?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package | | `file.open` | `{path}` opens `.sbs` XML or an independent `.mcraft` ZIP. Also opens a `.mcmat`'s source without a save path. Returns `warnings` for unsupported content; also in `session.inspect` as `package.warnings` | | `file.save` / `file.saveAs` / `file.saveCopyAs` | `{path?}` / `{path}` / `{path}`: `.sbs` writes XML and adjacent `resources/`; `.mcraft` writes a ZIP containing `package.sbs` and `resources/`. Unrecognized extensions get `.sbs` appended. Save Copy preserves the active path and modified state | +| `file.saveAll` | `{}` saves every modified package that has a file and returns `{saved, withoutFile, failed}`; packages without a file need `file.saveAs` | | `file.importBitmap` / `file.importVector` | `{path, name?, folder?}` imports a supported bitmap / SVG into Resources or a subfolder without adding a node. Unsaved imports and their original bytes participate in undo. `session.inspect` reports resource name, folder, file, byte count and missing status | | `graph.resource.add` | `{resource, document?, at?}` places a resource from the source document on the active material graph. Cross-document drops copy the asset; resource and node creation undo together | | `folder.properties` / `folder.attributes` | `{folder, document?}` reads Identifier/Description; add `identifier?` and/or `description?` to edit. Folder attributes persist as native SBS group identifiers and descriptions. The reserved root Resources identifier cannot change | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 570893de..1d37f85a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -23,7 +23,7 @@ Explorer now preserves native SBS folder hierarchies and provides package, folde menus for creation, copying, pasting, renaming, removal and package file actions. Moving items within a package and removing folder subtrees support undo; empty folders survive saves. -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-15 · **Change:** major (3D view 55% → 75%: the reference menus, tool strip, properties, shaders and lights) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later) +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-18 · **Change:** minor (UI and UX 70% → 75%: the reference application menus, Preferences pages, New graph dialog and home screen) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later) **Overall: ≈ 69%** of a material artist's daily workflow works end to end (engine + UI + automation + tests), weighted by how much of the day each area carries. **Remaining: ≈ 83 Opus @@ -39,7 +39,7 @@ automation + tests), weighted by how much of the day each area carries. **Remain | 2D view | 5 | 90% | The reference layout: a toolbar above the image (background image, save, copy to the clipboard, output choice, UV overlay, Information and Histogram panels) and one below (channel menu with C/R/G/B/A keys, checkerboard, premultiplied alpha, sRGB or linear display, tiling across the whole view, physical size, exact fit, 1:1, stepped zoom with a zoom field, zoom lock); an Information panel with the pixel under the pointer and a color sampler (values at the image's bit depth and as floats, HSV, position); a Histogram panel with channel choice, bit depth, square-root scale, used range and a selectable range; size/format line | Color picker to parameters, floating the two panels, UV sets beyond the first | | 3D view | 10 | 75% | The reference layout: menus (Scene, Materials, Lights, Camera, Environment, Display, Renderer), a tool strip (scene browser, Select, Camera and Light tools, environment background, shadows, a displacement pop-up, the display helpers) and a bar with the channels, the color space and the scene; the material, lights, camera, environment and renderer in the Properties panel. Thirteen built-in meshes and OBJ, glTF and GLB meshes; nine shaders (the OpenPBR Surface model with coat, fuzz, thin film, transmission and subsurface, metallic/roughness with coated and subsurface variants, specular/glossiness, Blinn, Lambert, unlit and mesh information) with every parameter editable, switchable and replaced by a graph output; height by tessellation and displacement or parallax occlusion; an ambient light and two point lights with shadows; 4 procedural environments with rotation, exposure and an on/off switch; focal length, perspective or orthographic projection, viewpoints, framing, clip planes, a studio backdrop, a background color or the environment behind the mesh, and a render resolution of its own; wireframe, backface culling, grid, axes with a scale, bounding box, light helpers, vertex tangent space, scene statistics, resolution and frame rate; tiling, UV scale and physical size; alpha transparency and an alpha channel view; save and copy the render, export the tessellated mesh as OBJ, state files and a saved default state | A GPU renderer and a path tracer, a ground plane that catches shadows, several materials on one mesh, loading shader definitions, anisotropy, dispersion and thin-walled transmission in the renderer | | Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; an Export window (From graph, Batch at a chosen output size, and MaterialX and MCMAT tabs holding the #190 publishing options) writing the checked outputs (PNG, JPEG, TGA, BMP, WEBP, EXR, HDR; DDS listed for later; 8/16/32 bits; name pattern; sRGB, linear or raw per output); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources | -| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave, 3D pan limit and speed), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs | +| UI and UX | 8 | 75% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, the reference File, Tools, Windows and Help menus (Save all, Cancel rendering, Suspend engine, main toolbar toggle, help and community links), New graph dialog with template cards, a category filter, width and height and a target package, export dialog, a paged Preferences window (General, Projects, Graph, 3D View, Library and Shortcuts pages with OK, Cancel and Apply; recent list length, invert zoom, numbered autosave copies, node search on Tab and on wire drop, outputs in the 3D view on open, node creation shortcuts), a Plugin Manager window (no plugin loading yet), shortcuts list, a home screen at startup (templates, recent packages, learn and community links), visual function editor, presets bar, accessible names on every widget, status bar | A plugin system, bakers, keymap editor for application commands, minimap, multi-graph tabs | | Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run | | **Total** | **100** | **≈ 69%** | | | @@ -58,6 +58,7 @@ and is tested. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | UI and UX 70% → 75%: the reference File, Tools, Windows and Help menus, a paged Preferences window keeping every earlier setting, node creation shortcuts, the New graph dialog with sizes and a target package, a Plugin Manager window and a new home screen (#269); overall ≈ 69% → ≈ 69% | | 2026-11-15 | major | 3D view 55% → 75%: the reference menus, tool strip and properties; shaders with editable parameters, lights with shadows, camera lens and projection, render resolution, display helpers, state files (#221); overall ≈ 67% → ≈ 69% | | 2026-11-14 | minor | 2D view 80% → 90%: the reference toolbars, the Information and Histogram panels, display settings and stepped zoom (#221); overall unchanged at ≈ 67% | | 2026-11-02 | minor | ≈ 66% → ≈ 67%: `.mcmat` portable materials and TextureCraft interop (Files 70%) | From 25ed4f7e2d777c4c029822b752b2a350254a2de4 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 19:26:06 +0000 Subject: [PATCH 2/4] Auto: Stream archive saves and preserve recovery and preference state Give each document an exclusive recovery history, skip occupied version names, and stream native archive saves. Publish pending linked edits before Save All selects packages, and preserve each document's result on partial failure. Commit destructive preference changes on Apply or OK. Respect the 3D preview preference on open and reload, discard cancelled cooks, and validate graph destinations before switching documents. Reuse the Library catalog and borrow its keys on cache hits. Keep template textures with their app, correct shortcut handling and help links, and omit personal document details from exported diagnostics. --- Cargo.lock | 1 + crates/engine/src/file_cmds.rs | 94 ++++++---- crates/engine/src/open_document.rs | 4 +- crates/engine/src/package_commands.rs | 2 +- crates/engine/src/save_all_commands.rs | 25 ++- crates/engine/tests/it/linked_instances.rs | 25 +++ crates/engine/tests/it/material_preview.rs | 38 +++++ crates/engine/tests/it/open_documents.rs | 24 ++- crates/formats/Cargo.toml | 3 + crates/formats/src/project/project_files.rs | 25 ++- crates/ui-egui/src/autosave_versions.rs | 160 ++++++++++++++---- crates/ui-egui/src/control.rs | 12 +- crates/ui-egui/src/cook.rs | 24 ++- crates/ui-egui/src/cook_cancellation.test.rs | 25 +++ crates/ui-egui/src/function/input.rs | 1 + crates/ui-egui/src/graph/graph_camera.rs | 11 +- crates/ui-egui/src/graph/graph_view.rs | 5 + crates/ui-egui/src/graph/input.rs | 32 ++-- crates/ui-egui/src/help_links.rs | 4 +- crates/ui-egui/src/home_screen.rs | 50 +++--- crates/ui-egui/src/i18n/ar.rs | 11 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/library.rs | 16 +- crates/ui-egui/src/library.test.rs | 25 +++ crates/ui-egui/src/material_craft_app.rs | 143 ++++++++++------ crates/ui-egui/src/material_craft_app.test.rs | 20 +++ crates/ui-egui/src/menus.rs | 32 ++-- crates/ui-egui/src/native_dialogs.rs | 33 +++- crates/ui-egui/src/native_dialogs.test.rs | 15 ++ crates/ui-egui/src/new_graph_dialog.rs | 81 +++++---- crates/ui-egui/src/node_shortcuts.rs | 115 +++++++------ .../general_page.rs | 33 ++-- .../{preferences => preference}/graph_page.rs | 0 .../library_page.rs | 0 .../src/{preferences.rs => preference/mod.rs} | 36 ++-- .../src/preference/preference_action.rs | 7 + .../preferences_page.rs | 0 .../preferences_state.rs | 0 .../projects_page.rs | 14 +- .../shortcuts_page.rs | 49 +++--- .../view3d_page.rs | 8 +- crates/ui-egui/src/shell/modality.rs | 3 + crates/ui-egui/src/state/ui_state.rs | 7 +- crates/ui-egui/src/template_card.rs | 16 +- crates/ui-egui/src/windows.rs | 60 ++++--- crates/ui-egui/src/windows.test.rs | 23 +++ crates/ui-egui/tests/it/graph_properties.rs | 6 + crates/ui-egui/tests/it/menu_bar.rs | 6 +- crates/ui-egui/tests/it/new_graph_dialog.rs | 3 +- crates/ui-egui/tests/it/preferences_window.rs | 28 +++ crates/ui-egui/tests/snapshot.rs | 18 +- docs/control-protocol.md | 4 +- docs/target-app-parity.md | 6 +- 53 files changed, 965 insertions(+), 419 deletions(-) rename crates/ui-egui/src/{preferences => preference}/general_page.rs (73%) rename crates/ui-egui/src/{preferences => preference}/graph_page.rs (100%) rename crates/ui-egui/src/{preferences => preference}/library_page.rs (100%) rename crates/ui-egui/src/{preferences.rs => preference/mod.rs} (81%) create mode 100644 crates/ui-egui/src/preference/preference_action.rs rename crates/ui-egui/src/{preferences => preference}/preferences_page.rs (100%) rename crates/ui-egui/src/{preferences => preference}/preferences_state.rs (100%) rename crates/ui-egui/src/{preferences => preference}/projects_page.rs (73%) rename crates/ui-egui/src/{preferences => preference}/shortcuts_page.rs (81%) rename crates/ui-egui/src/{preferences => preference}/view3d_page.rs (78%) diff --git a/Cargo.lock b/Cargo.lock index 82395802..f2fdfa6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2881,6 +2881,7 @@ name = "materialcraft-formats" version = "0.4.1" dependencies = [ "base64 0.22.1", + "craft-atomic", "craft-fonts-build", "craft-mcmat", "craft-mesh", diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 2ae6f4e1..d6768923 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -17,7 +17,7 @@ pub(crate) fn specs() -> Vec { "Graph...", ["File", "New"], Some("Ctrl+N"), - "{name?, folder?, kind? (material|function), template? (see graph.templates), size? (px, power of two), height? (px, power of two; default size), newPackage? (create the graph in a new package)} adds a new graph to the package and opens it", + "{name?, folder?, kind? (material|function), template? (see graph.templates), size? (px, power of two), height? (px, power of two; default size), document? (open package id), newPackage?} adds a graph and opens it", always, new_graph ), @@ -63,6 +63,7 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result { "function" => materialcraft_core::GraphKind::Function, _ => return Err(bad("file.new", "kind must be material or function")), }; + let template_id = strp(parameters, "template").unwrap_or("pbr"); let label = if kind == materialcraft_core::GraphKind::Function { "Function Graph" @@ -75,32 +76,46 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result { let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_")); let folder = strp(parameters, "folder").unwrap_or(""); let in_new_package = boolp(parameters, "newPackage").unwrap_or(false); - if in_new_package && !folder.is_empty() { - return Err(bad("file.new", "a new package has no folders yet: leave `folder` out")); + let target_document = parameters + .get("document") + .filter(|document| !document.is_null()) + .map(|document| document.as_u64().ok_or_else(|| bad("file.new", "`document` must be an open package id"))) + .transpose()?; + if in_new_package && target_document.is_some() { + return Err(bad("file.new", "`document` and `newPackage` cannot be used together")); } - if !in_new_package { - crate::folder_path::require(&session.pkg, folder)?; + + let target = target_document.map(|document| session.package(document)).transpose()?; + let target = target.or_else(|| (!in_new_package && session.has_package()).then_some(&session.pkg)); + if let Some(package) = target { + crate::folder_path::require(package, folder)?; + } else if !folder.is_empty() { + return Err(bad("file.new", "a new package has no folders yet")); } + crate::folder_path::require_graph_folder(folder)?; let base = crate::folder_path::name(&base)?; + let name = target.map_or_else(|| base.to_owned(), |package| crate::folder_path::unique(package, folder, base)); let mut graph = if kind == materialcraft_core::GraphKind::Function { - let mut graph = materialcraft_core::Graph::new(base); + let mut graph = materialcraft_core::Graph::new(&name); graph.function = Some(materialcraft_core::FunctionGraph::default()); graph } else { - template(template_id, base, width_log2)? + template(template_id, &name, width_log2)? }; + if kind == materialcraft_core::GraphKind::Material { + graph.size = [width_log2, height_log2]; + } + graph.folder = folder.into(); - // Everything is checked before a package opens, so a refused request leaves the workspace as it was - if in_new_package || !session.has_package() { + // Validate the graph before changing the active package + if let Some(document) = target_document { + session.activate_document(document)?; + } else if in_new_package || !session.has_package() { session.open_package(Package::new("Untitled package"), None)?; } - let name = crate::folder_path::unique(&session.pkg, folder, base); - graph.name = name.clone(); - graph.size = [width_log2, height_log2]; - graph.folder = folder.into(); session.edit("New graph", |session| { session.pkg.graphs.push(graph); session.graph = session.pkg.graphs.len() - 1; @@ -120,25 +135,28 @@ fn new_package(s: &mut Session, p: &J) -> Result { } /// Replace the active document explicitly, resetting its history and views -pub fn replace_package(s: &mut Session, pkg: Package, path: Option) { +pub fn replace_package(session: &mut Session, package: Package, path: Option) { // Reloaded archive dependencies must replace cached snapshots before links are refreshed - s.linked_sources.extend(pkg.dependencies.clone()); - s.pkg = pkg; - s.document_open = true; - s.clipboard = None; - s.embedded_clipboard = None; - s.clear_decoded(); - s.path = path; - s.graph = 0; - s.material_preview = crate::MaterialPreview::for_graph(&s.pkg, 0); - s.clear_preview_results(); - s.selection.clear(); - s.annotation_selection = None; - s.view2d.node = None; - s.reset_history(); - s.modified = false; - s.dirty = true; - s.load_warnings.clear(); + session.linked_sources.extend(package.dependencies.clone()); + session.pkg = package; + session.document_open = true; + session.path = path; + session.graph = 0; + + session.clipboard = None; + session.embedded_clipboard = None; + session.clear_decoded(); + session.material_preview = Default::default(); + session.open_material_preview(); + session.clear_preview_results(); + session.selection.clear(); + session.annotation_selection = None; + session.view2d.node = None; + + session.reset_history(); + session.modified = false; + session.dirty = true; + session.load_warnings.clear(); } fn has_extension(path: &str, ext: &str) -> bool { @@ -250,9 +268,7 @@ pub fn save_files_at(session: &Session, path: &str) -> Result Result { let files = save_files_at(session, path)?; if is_mcraft(path) { - let bytes = files.zip()?; - materialcraft_formats::write_atomic(std::path::Path::new(path), &bytes)?; - Ok(bytes.len()) + Ok(files.write_archive(std::path::Path::new(path))?) } else { materialcraft_formats::project::write_files(std::path::Path::new(path), &files)?; Ok(files.xml()?.len()) @@ -297,7 +313,14 @@ fn save(s: &mut Session, p: &J) -> Result { None => s.path.clone().ok_or_else(|| bad("file.save", "the package has no file yet (new, or opened from another program): give a `path`"))?, }; - let path = crate::document_path::normalize(&path); + let reply = save_to_path(s, &path)?; + s.log(format!("Saved {}", reply["path"].as_str().unwrap_or_default())); + Ok(reply) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn save_to_path(s: &mut Session, path: &str) -> Result { + let path = crate::document_path::normalize(path); if path.contains("://") { return Err(bad("file.save", "library aliases cannot be overwritten; save to a local .sbs path")); } @@ -310,7 +333,6 @@ fn save(s: &mut Session, p: &J) -> Result { s.path = Some(path.clone()); s.refresh_links(); s.modified = false; - s.log(format!("Saved {path}")); Ok(json!({"path": path, "bytes": bytes})) } diff --git a/crates/engine/src/open_document.rs b/crates/engine/src/open_document.rs index 59cff11c..868ca824 100644 --- a/crates/engine/src/open_document.rs +++ b/crates/engine/src/open_document.rs @@ -84,10 +84,10 @@ impl OpenDocument { } /// A document that was just opened, with the 3D view a new document starts from - pub(crate) fn new(id: u64, pkg: Package, path: Option, view3d: View3d) -> Self { + pub(crate) fn new(id: u64, pkg: Package, path: Option, view3d: View3d, show_outputs: bool) -> Self { Self { id, - material_preview: MaterialPreview::for_graph(&pkg, 0), + material_preview: if show_outputs { MaterialPreview::for_graph(&pkg, 0) } else { MaterialPreview::default() }, pkg, path, graph: 0, diff --git a/crates/engine/src/package_commands.rs b/crates/engine/src/package_commands.rs index 4f778488..89ed4684 100644 --- a/crates/engine/src/package_commands.rs +++ b/crates/engine/src/package_commands.rs @@ -144,7 +144,7 @@ impl Session { self.next_document_id = id.checked_add(1).ok_or_else(|| bad("file.open", "document identifiers exhausted"))?; self.linked_sources.extend(package.dependencies.clone()); let had_document = self.document_open; - let mut document = OpenDocument::new(id, package, path, self.default_view3d.clone().unwrap_or_default()); + let mut document = OpenDocument::new(id, package, path, self.default_view3d.clone().unwrap_or_default(), self.view_outputs_on_open); document.exchange(self); self.document_open = true; if had_document { diff --git a/crates/engine/src/save_all_commands.rs b/crates/engine/src/save_all_commands.rs index cb9aa562..cea0d533 100644 --- a/crates/engine/src/save_all_commands.rs +++ b/crates/engine/src/save_all_commands.rs @@ -1,10 +1,16 @@ //! File ▸ Save all: write every open package that has unsaved edits to its own file -use crate::commands::{CommandSpec, has_package}; +use crate::commands::CommandSpec; + +#[cfg(not(target_arch = "wasm32"))] +use crate::commands::has_package; +#[cfg(not(target_arch = "wasm32"))] use crate::{Result, Session, cmd}; +#[cfg(not(target_arch = "wasm32"))] use serde_json::{Value, json}; /// Register the command that saves every modified package +#[cfg(not(target_arch = "wasm32"))] pub(crate) fn specs() -> Vec { vec![cmd!( "file.saveAll", @@ -17,8 +23,16 @@ pub(crate) fn specs() -> Vec { )] } +#[cfg(target_arch = "wasm32")] +pub(crate) fn specs() -> Vec { + Vec::new() +} + /// Save each modified package in turn, then make the package that was active the active one again +#[cfg(not(target_arch = "wasm32"))] fn save_all(session: &mut Session, _parameters: &Value) -> Result { + // Publishing the active edit can mark linked packages modified + session.end_group(); let active = session.document_id; let modified: Vec<(u64, String, Option)> = session .open_packages() @@ -28,14 +42,14 @@ fn save_all(session: &mut Session, _parameters: &Value) -> Result { .collect(); let (mut saved, mut without_file, mut failed) = (Vec::new(), Vec::new(), Vec::new()); - for (id, name, path) in modified { + for (document, name, path) in modified { // A package from a library alias or with no file yet needs a name chosen in Save as - if path.as_deref().is_none_or(|path| path.contains("://")) { + let Some(path) = path.filter(|path| !path.contains("://")) else { without_file.push(name); continue; - } + }; - let result = session.activate_document(id).and_then(|()| crate::execute(session, "file.save", &json!({}))); + let result = session.activate_document(document).and_then(|()| crate::file_cmds::save_to_path(session, &path)); match result { Ok(reply) => saved.push(reply["path"].clone()), Err(error) => failed.push(json!({"package": name, "error": error.to_string()})), @@ -45,5 +59,6 @@ fn save_all(session: &mut Session, _parameters: &Value) -> Result { if session.document_id != active { session.activate_document(active)?; } + Ok(json!({"saved": saved, "withoutFile": without_file, "failed": failed})) } diff --git a/crates/engine/tests/it/linked_instances.rs b/crates/engine/tests/it/linked_instances.rs index 58f6c19b..b5068c03 100644 --- a/crates/engine/tests/it/linked_instances.rs +++ b/crates/engine/tests/it/linked_instances.rs @@ -126,6 +126,31 @@ fn failed_edit_groups_do_not_publish_source_changes() { assert_eq!(session.cooked.image(instance, 0).unwrap().get(0, 0, false), [1.0, 0.0, 0.0, 1.0]); } +#[test] +fn save_all_includes_dependents_changed_by_the_pending_group() { + let directory = std::env::temp_dir().join(format!("materialcraft-save-all-linked-{}", std::process::id())); + std::fs::create_dir(&directory).unwrap(); + let (source, value) = source(); + let mut session = Session::new(source); + execute(&mut session, "file.save", &json!({"path": directory.join("source.sbs")})).unwrap(); + execute(&mut session, "file.newPackage", &json!({"name": "Target"})).unwrap(); + execute(&mut session, "file.new", &json!({"name": "Target", "template": "empty"})).unwrap(); + execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Source"})).unwrap(); + execute(&mut session, "file.save", &json!({"path": directory.join("target.sbs")})).unwrap(); + execute(&mut session, "package.activate", &json!({"document": 0})).unwrap(); + session.begin_group("Pending source edit"); + execute(&mut session, "graph.node.param", &json!({"id": value.0, "param": "color", "value": [1.0, 0.0, 0.0, 1.0]})).unwrap(); + assert_eq!(session.open_packages().iter().filter(|entry| entry.3).count(), 1); + + let result = execute(&mut session, "file.saveAll", &json!({})).unwrap(); + std::fs::remove_dir_all(directory).unwrap(); + + assert_eq!(result["failed"], json!([])); + assert_eq!(result["saved"].as_array().unwrap().len(), 2); + assert!(session.open_packages().iter().all(|entry| !entry.3)); + assert_eq!(session.document_id, 0); +} + #[test] fn instance_info_is_read_only_and_describes_the_source_reference() { let (source, _) = source(); diff --git a/crates/engine/tests/it/material_preview.rs b/crates/engine/tests/it/material_preview.rs index c23e6e9a..72e0df0f 100644 --- a/crates/engine/tests/it/material_preview.rs +++ b/crates/engine/tests/it/material_preview.rs @@ -283,3 +283,41 @@ fn opening_a_graph_shows_its_outputs_only_while_the_preference_is_on() { execute(&mut session, "file.new", &json!({"template": "pbr", "name": "Shown"})).unwrap(); assert_eq!(session.material_preview.graph, Some(session.graph)); } + +#[test] +fn opening_a_package_respects_the_output_preview_preference() { + let mut source = new_session(); + execute(&mut source, "file.new", &json!({"template": "pbr"})).unwrap(); + execute(&mut source, "graph.delete", &json!({"graph": 0})).unwrap(); + let bytes = materialcraft_engine::file_cmds::save_bytes(&source).unwrap(); + let mut destination = new_session(); + destination.view_outputs_on_open = false; + + materialcraft_engine::file_cmds::open_bytes(&mut destination, &bytes, None).unwrap(); + + assert_eq!(destination.material_preview.graph, None); + + destination.view_outputs_on_open = true; + materialcraft_engine::file_cmds::open_bytes(&mut destination, &bytes, None).unwrap(); + + assert_eq!(destination.material_preview.graph, Some(0)); +} + +#[test] +fn reloading_a_package_respects_the_output_preview_preference() { + let directory = std::env::temp_dir().join(format!("materialcraft-reload-preview-{}", std::process::id())); + std::fs::create_dir(&directory).unwrap(); + let mut session = new_session(); + let path = directory.join("preview.sbs"); + execute(&mut session, "file.saveAs", &json!({"path": path})).unwrap(); + + session.view_outputs_on_open = false; + execute(&mut session, "file.reload", &json!({})).unwrap(); + let disabled = session.material_preview.clone(); + session.view_outputs_on_open = true; + execute(&mut session, "file.reload", &json!({})).unwrap(); + std::fs::remove_dir_all(directory).unwrap(); + + assert_eq!(disabled, MaterialPreview::default()); + assert_eq!(session.material_preview.graph, Some(0)); +} diff --git a/crates/engine/tests/it/open_documents.rs b/crates/engine/tests/it/open_documents.rs index e61b9660..e6ed353e 100644 --- a/crates/engine/tests/it/open_documents.rs +++ b/crates/engine/tests/it/open_documents.rs @@ -138,8 +138,9 @@ fn saving_a_new_file_preserves_its_identity_across_path_aliases() { #[test] fn save_all_writes_every_modified_package_with_a_file_and_lists_the_rest() { let folder = std::env::temp_dir().join(format!("materialcraft-save-all-{}", std::process::id())); - std::fs::create_dir_all(&folder).unwrap(); + std::fs::create_dir(&folder).unwrap(); let first_path = folder.join("first.sbs"); + let saved_path = folder.canonicalize().unwrap().join("first.sbs"); let second_path = folder.join("second.sbs"); let mut session = Session::new(Package::new("First")); @@ -157,7 +158,7 @@ fn save_all_writes_every_modified_package_with_a_file_and_lists_the_rest() { let reply = execute(&mut session, "file.saveAll", &json!({})).unwrap(); - assert_eq!(reply["saved"], json!([first_path.to_str().unwrap()])); + assert_eq!(reply["saved"], json!([saved_path.to_str().unwrap()])); assert_eq!(reply["withoutFile"], json!(["Unsaved"])); assert_eq!(reply["failed"], json!([])); assert_eq!(session.document_id, active, "the package that was active stays active"); @@ -185,3 +186,22 @@ fn a_new_graph_can_start_its_own_package_and_take_any_size() { assert!(execute(&mut session, "file.new", &json!({"folder": "Missing", "newPackage": true})).is_err()); assert_eq!(session.open_packages().len(), 2); } + +#[test] +fn a_refused_graph_leaves_the_active_package_unchanged() { + let mut session = Session::new(Package::new("First")); + let destination = session.document_id; + execute(&mut session, "file.newPackage", &json!({"name": "Second"})).unwrap(); + let original = session.document_id; + + let refused = execute(&mut session, "file.new", &json!({"document": destination, "template": "invalid"})); + + assert!(refused.is_err()); + assert_eq!(session.document_id, original); + assert!(session.package(destination).unwrap().graphs.is_empty()); + + execute(&mut session, "file.new", &json!({"document": destination, "template": "empty", "name": "New graph"})).unwrap(); + + assert_eq!(session.document_id, destination); + assert_eq!(session.graph().unwrap().name, "New graph"); +} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 31e468ba..3bba0a59 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -27,6 +27,9 @@ flate2 = { workspace = true } base64 = { workspace = true } craft-svg = { workspace = true } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +craft-atomic = { workspace = true } + [build-dependencies] flate2 = { workspace = true } craft-fonts-build = { workspace = true } diff --git a/crates/formats/src/project/project_files.rs b/crates/formats/src/project/project_files.rs index 0508247f..e9cfa402 100644 --- a/crates/formats/src/project/project_files.rs +++ b/crates/formats/src/project/project_files.rs @@ -3,7 +3,7 @@ use crate::{Result, sbs}; use materialcraft_core::{Package, ResourceBytes}; use std::collections::{BTreeMap, BTreeSet}; use std::hash::{Hash, Hasher}; -use std::io::{Cursor, Write}; +use std::io::{Cursor, Seek, Write}; const MAX_RESOURCE_STEM_CHARS: usize = 40; const MAX_RESOURCE_EXTENSION_CHARS: usize = 16; @@ -124,7 +124,26 @@ impl ProjectFiles { } pub fn zip(&self) -> Result> { - let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + Ok(self.write_zip(Cursor::new(Vec::new()))?.into_inner()) + } + + /// Replace a native archive atomically and report its saved byte length. + #[cfg(not(target_arch = "wasm32"))] + pub fn write_archive(&self, path: &std::path::Path) -> Result { + let mut length = 0; + craft_atomic::atomic_write_with(path, |file| { + self.write_zip(std::io::BufWriter::new(&mut *file)).map_err(std::io::Error::other)?.flush()?; + length = usize::try_from(file.metadata()?.len()).map_err(std::io::Error::other)?; + Ok(()) + }) + .map_err(|error| crate::FormatError::Io(format!("{}: {error}", path.display())))?; + + Ok(length) + } + + /// Write an archive to a seekable destination without buffering the whole archive + pub fn write_zip(&self, destination: W) -> Result { + let mut writer = zip::ZipWriter::new(destination); writer.add_directory("resources/", zip::write::SimpleFileOptions::default()).map_err(|error| bad(error.to_string()))?; for (name, bytes) in &self.files { let is_text = name.ends_with(".sbs") || name.ends_with(".svg"); @@ -136,7 +155,7 @@ impl ProjectFiles { writer.write_all(bytes.as_slice()).map_err(|error| bad(error.to_string()))?; } - Ok(writer.finish().map_err(|error| bad(error.to_string()))?.into_inner()) + writer.finish().map_err(|error| bad(error.to_string())) } pub fn xml(&self) -> Result<&[u8]> { diff --git a/crates/ui-egui/src/autosave_versions.rs b/crates/ui-egui/src/autosave_versions.rs index 26ec52d3..9c0c4c58 100644 --- a/crates/ui-egui/src/autosave_versions.rs +++ b/crates/ui-egui/src/autosave_versions.rs @@ -1,39 +1,77 @@ -//! The autosaved copies of a package: numbered files in the autosave folder, the newest kept +//! Write numbered recovery copies and retain the newest copies for each document +use std::io::{self, ErrorKind}; use std::path::{Path, PathBuf}; -const EXTENSION: &str = "mcraft"; +use craft_atomic::{NewFilePermissions, WriteOptions}; +use materialcraft_engine::core::Package; +use materialcraft_engine::formats::project::ProjectFiles; +use sha2::{Digest, Sha256}; -/// The file name stem of `package`'s copies, before the copy's number -fn prefix(package: &str) -> String { - format!("{}-autosave-", materialcraft_engine::formats::safe_file_name(package)) +const EXTENSION: &str = ".mcraft"; +const MAX_WRITE_ATTEMPTS: usize = 8; + +/// Saved documents share history by normalized path; untitled documents use workspace-local IDs +pub(crate) fn folder(root: &Path, path: Option<&str>, workspace: u64, document: u64) -> PathBuf { + let key = match path.filter(|path| !path.contains("://")) { + Some(path) => format!("file-{:x}", Sha256::digest(path.as_bytes())), + None => format!("untitled-{workspace:016x}-{document}"), + }; + root.join(key) } -/// The numbers of `package`'s copies in `folder`, lowest first -fn numbers(folder: &Path, package: &str) -> Vec { - let prefix = prefix(package); - let Ok(entries) = std::fs::read_dir(folder) else { return Vec::new() }; - - let mut numbers: Vec = entries - .filter_map(|entry| entry.ok()?.file_name().into_string().ok()) - .filter_map(|name| name.strip_prefix(&prefix)?.strip_suffix(&format!(".{EXTENSION}"))?.parse().ok()) - .collect(); - numbers.sort_unstable(); - numbers +fn copies(folder: &Path) -> io::Result> { + Ok(std::fs::read_dir(folder)?.filter_map(|entry| { + let entry = entry.ok()?; + let filename = entry.file_name(); + let number = filename.to_str()?.strip_suffix(EXTENSION)?.parse().ok()?; + entry.file_type().ok()?.is_file().then_some((number, entry)) + })) } -/// Where the next copy of `package` goes: one number past the newest -pub(crate) fn next_path(folder: &Path, package: &str) -> PathBuf { - let next = numbers(folder, package).last().map_or(1, |newest| newest.saturating_add(1)); - folder.join(format!("{}{next}.{EXTENSION}", prefix(package))) +fn next_path(folder: &Path) -> io::Result { + let mut version = copies(folder)?.map(|(number, _)| number).max().unwrap_or(0); + loop { + version = version.checked_add(1).ok_or_else(|| io::Error::other("autosave versions exhausted"))?; + let path = folder.join(format!("{version}{EXTENSION}")); + + // A directory or link can occupy a name without counting toward retention + match path.symlink_metadata() { + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(path), + Err(error) => return Err(error), + Ok(_) => continue, + } + } } -/// Delete all but the newest `keep` copies of `package`; returns how many were deleted -pub(crate) fn prune(folder: &Path, package: &str, keep: u32) -> usize { - let numbers = numbers(folder, package); - let surplus = numbers.len().saturating_sub(keep.max(1) as usize); +fn prune(folder: &Path, keep: u32) -> io::Result<()> { + let mut copies: Vec<_> = copies(folder)?.collect(); + copies.sort_unstable_by_key(|(number, _)| *number); + let surplus = copies.len().saturating_sub(keep.max(1) as usize); - numbers.iter().take(surplus).filter(|number| std::fs::remove_file(folder.join(format!("{}{number}.{EXTENSION}", prefix(package)))).is_ok()).count() + for (_, entry) in copies.into_iter().take(surplus) { + match std::fs::remove_file(entry.path()) { + Err(error) if error.kind() == ErrorKind::NotFound => {} + result => result?, + } + } + Ok(()) +} + +pub(crate) fn save(folder: &Path, package: &Package, keep: u32) -> io::Result<()> { + std::fs::create_dir_all(folder)?; + let files = ProjectFiles::build(package, "autosave.mcraft", true).map_err(io::Error::other)?; + let options = WriteOptions::default().with_new_file_permissions(NewFilePermissions::Private); + + for _ in 0..MAX_WRITE_ATTEMPTS { + let path = next_path(folder)?; + match options.write_new_with(&path, |file| files.write_zip(file).map(|_| ()).map_err(io::Error::other)) { + Ok(()) => return prune(folder, keep), + Err(error) if error.kind() == ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + Err(io::Error::other("autosave version could not be reserved")) } #[cfg(test)] @@ -41,21 +79,71 @@ mod tests { use super::*; #[test] - fn copies_are_numbered_and_only_the_newest_are_kept() { - let folder = std::env::temp_dir().join(format!("materialcraft-autosave-versions-{}", std::process::id())); - std::fs::create_dir_all(&folder).unwrap(); + fn retention_keeps_distinct_packages_and_ignores_directories() { + let root = tempfile::tempdir().unwrap(); + let wood = Package::new("Wood"); + let first = folder(root.path(), Some("/first/wood.sbs"), 1, 0); + let second = folder(root.path(), Some("/second/wood.sbs"), 1, 1); + let untitled = folder(root.path(), None, 1, 0); + assert_ne!(untitled, folder(root.path(), None, 2, 0)); + assert_ne!(untitled, folder(root.path(), None, 1, 1)); + assert_eq!(first, folder(root.path(), Some("/first/wood.sbs"), 2, 1)); for _ in 0..5 { - std::fs::write(next_path(&folder, "Wood"), b"copy").unwrap(); + save(&first, &wood, 2).unwrap(); } - std::fs::write(next_path(&folder, "Metal"), b"copy").unwrap(); - assert_eq!(next_path(&folder, "Wood"), folder.join("Wood-autosave-6.mcraft")); + save(&second, &wood, 1).unwrap(); + std::fs::create_dir(first.join("99.mcraft")).unwrap(); + std::fs::rename(first.join("4.mcraft"), first.join("04.mcraft")).unwrap(); + save(&first, &wood, 2).unwrap(); - assert_eq!(prune(&folder, "Wood", 2), 3); - assert_eq!(numbers(&folder, "Wood"), vec![4, 5]); - assert_eq!(numbers(&folder, "Metal"), vec![1], "another package's copies stay"); - assert_eq!(prune(&folder, "Wood", 0), 1, "at least one copy is always kept"); + assert!(!first.join("04.mcraft").exists()); + assert!(first.join("5.mcraft").is_file()); + assert!(first.join("6.mcraft").is_file()); + assert!(first.join("99.mcraft").is_dir()); + assert!(second.join("1.mcraft").is_file()); + let archive = std::fs::read(first.join("6.mcraft")).unwrap(); + assert!(materialcraft_engine::formats::project::read(&archive, "autosave.mcraft").is_ok()); + } - std::fs::remove_dir_all(&folder).unwrap(); + #[test] + fn an_occupied_version_name_does_not_block_recovery() { + let root = tempfile::tempdir().unwrap(); + let occupied = root.path().join("1.mcraft"); + std::fs::create_dir(&occupied).unwrap(); + + save(root.path(), &Package::new("Wood"), 1).unwrap(); + + assert!(occupied.is_dir()); + let bytes = std::fs::read(root.path().join("2.mcraft")).unwrap(); + assert!(materialcraft_engine::formats::project::read(&bytes, "autosave.mcraft").is_ok()); + } + + #[test] + fn simultaneous_writes_publish_distinct_versions() { + let root = tempfile::tempdir().unwrap(); + let folder = root.path(); + let barrier = std::sync::Barrier::new(4); + + std::thread::scope(|scope| { + for number in 0..4 { + let barrier = &barrier; + scope.spawn(move || { + barrier.wait(); + let mut package = Package::new("Same filename"); + package.graphs.push(materialcraft_engine::core::Graph::new(&format!("Graph {number}"))); + save(folder, &package, 4).unwrap(); + }); + } + }); + + let mut names = Vec::new(); + for (_, entry) in copies(folder).unwrap() { + let archive = std::fs::read(entry.path()).unwrap(); + names.push(materialcraft_engine::formats::project::read(&archive, "autosave.mcraft").unwrap().pkg.graphs[0].name.clone()); + } + + names.sort_unstable(); + assert_eq!(names, ["Graph 0", "Graph 1", "Graph 2", "Graph 3"]); } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 5e8f0ca1..c42ff15d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -264,20 +264,12 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p if matches!(id, "view.3d.saveRender" | "view.3d.exportGeometry" | "view.2d.copyImage") { return displayed_command(app, ctx, id, ¶ms); } + match crate::cook::guard("command request", || { Ok(materialcraft_engine::commands::execute_request(&mut app.session, id, ¶ms).map_err(|error| error.to_string())) }) { Ok(Ok(v)) => { - if id == "view.previewSize" { - app.ui.prefs.preview_size = app.session.preview_size.unwrap_or(0); - } - if id == "library.cache.configure" { - app.ui.prefs.library_cache = app.session.library_cache_prefs; - } - if id == "session.history" { - app.ui.prefs.history = app.session.history_prefs; - } - + app.sync_preferences_after_command(id); app.close_subgraph_after(id); ok(v) } diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index d61fee04..852a3fd6 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -83,10 +83,12 @@ impl Cooker { /// Tools ▸ Cancel rendering: stop the running cook; the next edit cooks again pub fn cancel(app: &mut MaterialCraftApp) { - if app.cooker.busy() { - app.cooker.stop(); - app.cooker.stopped_by_user = true; + if !app.cooker.busy() { + return; } + + app.cooker.stop(); + app.cooker.stopped_by_user = true; app.session.dirty = false; } @@ -105,6 +107,7 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { if let Some(rx) = &app.cooker.rx { match rx.try_recv() { Ok(result) => { + let stopped_by_user = std::mem::take(&mut app.cooker.stopped_by_user); app.cooker.rx = None; app.cooker.started = None; #[cfg(not(target_arch = "wasm32"))] @@ -112,19 +115,20 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { app.cooker.cancel = None; } match result { - // A stopped cook is partial: keep the previous results and cook again, unless the user stopped it + _ if stopped_by_user => {} + + // Partial results are discarded so the previous preview stays visible Ok(c) if c.cancelled() => { - if app.cooker.epoch == app.session.cook_epoch && !app.cooker.stopped_by_user { + if app.cooker.epoch == app.session.cook_epoch { app.session.dirty = true; } - app.cooker.stopped_by_user = false; } Ok(c) => { - if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch { + if !app.cooker.suspended && !app.session.dirty && app.cooker.epoch == app.session.cook_epoch { app.session.accept_preview(c); } } - Err(msg) if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch => report_failure(app, msg), + Err(msg) if !app.cooker.suspended && !app.session.dirty && app.cooker.epoch == app.session.cook_epoch => report_failure(app, msg), Err(_) => {} } ctx.request_repaint(); @@ -140,9 +144,10 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { return; } Err(TryRecvError::Disconnected) => { + let stopped_by_user = std::mem::take(&mut app.cooker.stopped_by_user); app.cooker.rx = None; app.cooker.started = None; - if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch { + if !stopped_by_user && !app.cooker.suspended && !app.session.dirty && app.cooker.epoch == app.session.cook_epoch { report_failure(app, "the cook worker stopped unexpectedly".into()); } #[cfg(not(target_arch = "wasm32"))] @@ -152,6 +157,7 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { } } } + if app.session.dirty && !app.cooker.suspended { start(app, ctx.input(|i| i.time)); ctx.request_repaint(); diff --git a/crates/ui-egui/src/cook_cancellation.test.rs b/crates/ui-egui/src/cook_cancellation.test.rs index 3887ebb8..906c5ed4 100644 --- a/crates/ui-egui/src/cook_cancellation.test.rs +++ b/crates/ui-egui/src/cook_cancellation.test.rs @@ -43,3 +43,28 @@ fn ready_results_are_discarded_when_an_edit_is_pending() { assert_eq!(app.session.cooked.ms, 123.0); assert!(!app.session.dirty); } + +#[test] +fn cancelling_a_finished_worker_keeps_the_displayed_preview() { + let (mut app, tx, flag) = waiting(); + tx.send(Ok(PreviewCook { cooked: Cooked { ms: 7.0, ..Default::default() }, ..Default::default() })).unwrap(); + + cancel(&mut app); + drive(&mut app, &egui::Context::default()); + + assert!(flag.load(Ordering::Relaxed)); + assert_eq!(Arc::strong_count(&flag), 1, "the settled cooker releases the cancellation flag"); + assert_eq!(app.session.cooked.ms, 123.0); + assert!(!app.cooker.busy()); + assert!(!app.session.dirty); +} + +#[test] +fn cancelling_without_a_worker_keeps_pending_work() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); + app.session.dirty = true; + + cancel(&mut app); + + assert!(app.session.dirty); +} diff --git a/crates/ui-egui/src/function/input.rs b/crates/ui-egui/src/function/input.rs index 1be76454..56fc4361 100644 --- a/crates/ui-egui/src/function/input.rs +++ b/crates/ui-egui/src/function/input.rs @@ -186,6 +186,7 @@ pub(super) fn handle( { editor.menu_at = camera.to_graph(pointer_position); } + // Space or Tab over the canvas, or a double-click on empty canvas, searches for a node to add // Tab moves focus between widgets, so it waits only for text fields and focus held before this frame let space = !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::Space)); diff --git a/crates/ui-egui/src/graph/graph_camera.rs b/crates/ui-egui/src/graph/graph_camera.rs index 9b3bbdcc..36caaa62 100644 --- a/crates/ui-egui/src/graph/graph_camera.rs +++ b/crates/ui-egui/src/graph/graph_camera.rs @@ -31,8 +31,11 @@ impl GraphCamera { Self { origin: view.min, pan, zoom } } - /// Zoom around the pointer by the wheel or a pinch; `direction` is -1 when the preferences invert the zoom - pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect, direction: f32) { + /// Zoom around the pointer by the wheel or a pinch. `zoom_direction` is -1 for inverted zoom. + pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect, zoom_direction: f32) { + const PINCH_TO_SCROLL_POINTS: f32 = 200.0; + const ZOOM_PER_SCROLL_POINT: f32 = 0.0025; + self.zoom = self.zoom.clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); if !ui.rect_contains_pointer(view) { return; @@ -40,10 +43,10 @@ impl GraphCamera { let Some(pointer) = ui.input(|input| input.pointer.hover_pos()).filter(|pointer| view.contains(*pointer)) else { return }; - let scroll = direction * ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0); + let scroll = zoom_direction * ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * PINCH_TO_SCROLL_POINTS); if scroll.is_finite() && scroll != 0.0 { let before = self.to_graph(pointer); - self.zoom = (self.zoom * (scroll * 0.0025).exp()).clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); + self.zoom = (self.zoom * (scroll * ZOOM_PER_SCROLL_POINT).exp()).clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); self.pan = before.to_vec2() - (pointer - self.origin) / self.zoom; } } diff --git a/crates/ui-egui/src/graph/graph_view.rs b/crates/ui-egui/src/graph/graph_view.rs index f032e462..e390694b 100644 --- a/crates/ui-egui/src/graph/graph_view.rs +++ b/crates/ui-egui/src/graph/graph_view.rs @@ -41,9 +41,14 @@ impl GraphView { self.cancel_drag(); self.framed_graph = None; } + pub(crate) fn is_dragging(&self) -> bool { self.drag.is_some() } + + pub(crate) fn search_is_open(&self) -> bool { + self.search.is_some() + } } impl Default for GraphView { diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs index e536bbc5..6c077ae8 100644 --- a/crates/ui-egui/src/graph/input.rs +++ b/crates/ui-egui/src/graph/input.rs @@ -273,30 +273,28 @@ pub(super) fn handle( app.run("library.add", json!({"entry": payload.0, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid})); } - // Keys over the canvas - let hovered = pointer.is_some_and(|position| rect.contains(position)); - if hovered && app.graph.search.is_none() && !crate::shell::modality::Modality::capture(app, &context).is_blocked() { - let space = !context.egui_wants_keyboard_input() && context.input(|input| input.key_pressed(egui::Key::Space)); + if let Some(position) = pointer.filter(|position| rect.contains(*position)) + && app.graph.search.is_none() + && !crate::shell::modality::Modality::capture(app, &context).is_blocked() + { + let typing = context.egui_wants_keyboard_input(); + let platform = craft_keymap::egui::platform(&context); + if !typing && let Some(entry) = context.input(|input| crate::node_shortcuts::pressed(&app.ui.prefs.node_shortcuts, input, platform)) { + let under_pointer = camera.to_graph(position); + let at = [under_pointer.x - NODE_W * 0.5, under_pointer.y - 20.0]; + app.run("library.add", json!({"entry": entry, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid})); + return; + } + + let space = !typing && context.input(|input| input.key_pressed(egui::Key::Space)); let tab = app.ui.prefs.tab_opens_node_search && !app.graph.keyboard_was_focused && !context.text_edit_focused() && context.input(|input| input.key_pressed(egui::Key::Tab)); - if (space || tab) - && let Some(position) = pointer - { + if space || tab { open_search(app, &context, camera.to_graph(position), None); } - // A node creation shortcut adds its entry under the pointer - let typing = context.egui_wants_keyboard_input(); - if !typing - && let Some(position) = pointer - && let Some(entry) = context.input(|input| crate::node_shortcuts::pressed(&app.ui.prefs.node_shortcuts, input)) - { - let under_pointer = camera.to_graph(position); - let at = [under_pointer.x - NODE_W * 0.5, under_pointer.y - 20.0]; - app.run("library.add", json!({"entry": entry, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid})); - } if GraphCamera::frame_key(ui, rect) { let selected = !app.session.selection.is_empty(); frame(app, rect, selected); diff --git a/crates/ui-egui/src/help_links.rs b/crates/ui-egui/src/help_links.rs index d9302735..b286e960 100644 --- a/crates/ui-egui/src/help_links.rs +++ b/crates/ui-egui/src/help_links.rs @@ -2,7 +2,7 @@ /// Help menu ids and the pages they open pub(crate) const HELP_LINKS: &[(&str, &str)] = &[ - ("ui.help.tutorials", "https://getartcraft.com/tutorials"), + ("ui.help.tutorials", "https://craft.wiki/apps/materialcraft/getting-started/"), ("ui.help.releaseNotes", "https://github.com/storytold/materialcraft/releases"), ("ui.help.requirements", "https://craft.wiki/apps/materialcraft/install-update/"), ("ui.help.docs", "https://craft.wiki/apps/materialcraft/overview/"), @@ -13,7 +13,7 @@ pub(crate) const HELP_LINKS: &[(&str, &str)] = &[ ("ui.help.feedback", "https://getartcraft.com/support"), ("ui.help.apps", "https://getartcraft.com/apps"), ("ui.help.website", "https://getartcraft.com/apps/materialcraft"), - ("ui.help.news", "https://getartcraft.com/news"), + ("ui.help.news", "https://github.com/storytold/materialcraft/releases"), ]; /// The page a Help menu id opens diff --git a/crates/ui-egui/src/home_screen.rs b/crates/ui-egui/src/home_screen.rs index a56889fb..1ac58314 100644 --- a/crates/ui-egui/src/home_screen.rs +++ b/crates/ui-egui/src/home_screen.rs @@ -13,6 +13,8 @@ use crate::theme::Tokens; const WINDOW_SIZE: egui::Vec2 = vec2(1000.0, 620.0); const RAIL_WIDTH: f32 = 220.0; const CARD_GAP: f32 = 14.0; +const RAIL_PADDING: f32 = 12.0; +const STARTUP_BAR_HEIGHT: f32 = 32.0; /// The links down the left side, under their headings: (heading, [(label, Help menu id)]) const LINKS: [(&str, &[(&str, &str)]); 2] = [ ("Learn", &[("Tutorials", "ui.help.tutorials"), ("Documentation", "ui.help.docs"), ("What's new", "ui.help.news")]), @@ -20,15 +22,22 @@ const LINKS: [(&str, &[(&str, &str)]); 2] = [ ]; pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { + let size = crate::windows::dialog_size(ctx, WINDOW_SIZE); let mut open = true; - crate::windows::modal(ctx, "home", tr("Home"), &mut open, WINDOW_SIZE, |ui| { - ui.set_min_size(WINDOW_SIZE); + crate::windows::modal(ctx, "home", tr("Home"), &mut open, size, |ui| { + ui.set_min_size(size); let whole = ui.available_rect_before_wrap(); - let rail = egui::Rect::from_min_max(whole.min, egui::pos2(whole.left() + RAIL_WIDTH, whole.bottom())); + let rail = egui::Rect::from_min_max(whole.min, egui::pos2(whole.left() + RAIL_WIDTH.min(size.x * 0.4), whole.bottom())); let content = egui::Rect::from_min_max(egui::pos2(rail.right() + 24.0, whole.top()), whole.max); - left_rail(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(rail))); - start(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(content))); + let mut rail_ui = ui.new_child(egui::UiBuilder::new().max_rect(rail.with_max_y(rail.bottom() - STARTUP_BAR_HEIGHT))); + egui::ScrollArea::vertical().id_salt("home-links").auto_shrink([false, false]).show(&mut rail_ui, |ui| left_rail(app, ui)); + let checkbox = rail.with_min_y(rail.bottom() - STARTUP_BAR_HEIGHT).with_min_x(rail.left() + RAIL_PADDING); + ui.new_child(egui::UiBuilder::new().max_rect(checkbox)).checkbox(&mut app.ui.prefs.show_home, tr("Show at startup")); + + let mut content_ui = ui.new_child(egui::UiBuilder::new().max_rect(content)); + egui::ScrollArea::vertical().id_salt("home-content").auto_shrink([false, false]).show(&mut content_ui, |ui| start(app, ui)); + ui.advance_cursor_after_rect(whole); }); if !open { @@ -41,16 +50,16 @@ fn left_rail(app: &mut MaterialCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let modality = Modality::capture(app, ui.ctx()); ui.painter().rect_filled(ui.max_rect(), 6.0, tokens.row); - ui.add_space(12.0); + ui.add_space(RAIL_PADDING); ui.horizontal(|ui| { - ui.add_space(12.0); + ui.add_space(RAIL_PADDING); ui.vertical(|ui| { ui.label(RichText::new("MaterialCraft").size(22.0).strong().color(tokens.accent)); ui.label(RichText::new(format!("{} {}", tr("Version"), materialcraft_engine::VERSION)).small().color(tokens.text_dim)); ui.add_space(16.0); - let width = RAIL_WIDTH - 24.0; + let width = (ui.available_width() - RAIL_PADDING).max(0.0); let new_graph = crate::widgets::primary_button(ui, &format!("{} {}", icon::FILE_PLUS, tr("New graph..."))); if ui.add_enabled_ui(!modality.is_blocked(), |ui| ui.add_sized([width, 30.0], new_graph)).inner.clicked() { app.ui.windows.home = false; @@ -73,9 +82,6 @@ fn left_rail(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); }); - - let bottom = egui::Rect::from_min_max(egui::pos2(ui.max_rect().left() + 12.0, ui.max_rect().bottom() - 32.0), ui.max_rect().right_bottom()); - ui.new_child(egui::UiBuilder::new().max_rect(bottom)).checkbox(&mut app.ui.prefs.show_home, tr("Show at startup")); } /// The welcome, the template cards and the recent packages @@ -100,7 +106,7 @@ fn start(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.disable(); } for card in row { - let preview = crate::windows::template_preview(ui.ctx(), card.id); + let preview = crate::windows::template_preview(app, ui.ctx(), card.id); if crate::template_card::show(ui, card, false, preview).clicked() && free { begin_with(app, card); } @@ -130,17 +136,21 @@ fn recent(app: &mut MaterialCraftApp, ui: &mut Ui) { } #[cfg(not(target_arch = "wasm32"))] - egui::ScrollArea::vertical().id_salt("home-recent").show(ui, |ui| { + { let free = !Modality::capture(app, ui.ctx()).is_blocked(); - for path in app.ui.recent.clone() { - let file = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |name| name.to_string_lossy().into_owned()); + let mut selected = None; + for path in &app.ui.recent { + let file = std::path::Path::new(path).file_name().map_or_else(|| std::borrow::Cow::Borrowed(path.as_str()), |name| name.to_string_lossy()); let text = egui::text::LayoutJob::simple_singleline(format!("{} {file}", icon::PACKAGE), egui::FontId::proportional(13.0), tokens.text); - let row = ui.add_enabled(free, egui::Button::new(text).frame_when_inactive(false)).on_hover_text(&path); - ui.label(RichText::new(&path).small().color(tokens.text_dim)); + let row = ui.add_enabled(free, egui::Button::new(text).frame_when_inactive(false)).on_hover_text(path.as_str()); + ui.label(RichText::new(path.as_str()).small().color(tokens.text_dim)); if row.clicked() { - crate::windows::open_path(app, &path); - app.ui.windows.home = false; + selected = Some(path.clone()); } } - }); + if let Some(path) = selected { + crate::windows::open_path(app, &path); + app.ui.windows.home = false; + } + } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index d8d796ed..435389f4 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -21,6 +21,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("512 px", "512 بكسل"), ("8 bits", "8 بت"), ("8 bits per channel", "8 بت لكل قناة"), + ("9 spp", "9 عينات لكل بكسل"), ("A folder: material.mtlx, material.json, resources/ and the optional preview.png", "مجلد: material.mtlx وmaterial.json وresources/ وpreview.png الاختياري"), ("A graph's name is unique in its package; a taken name gets a number", "اسم المخطط فريد في حزمته؛ يُضاف رقم إلى الاسم المستخدم"), ("A saved default is in use", "إعداد افتراضي محفوظ قيد الاستخدام"), @@ -89,8 +90,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bake every control", "خَبز كل عناصر التحكم في الخامات"), ("Base", "الأساس"), ( - "Base color, normal, roughness, metallic, height and ambient occlusion outputs, ready to connect", - "مخرجات اللون الأساسي والناظم والخشونة والمعدنية والارتفاع والإطباق المحيط، جاهزة للتوصيل", + "Base color, normal, roughness, metallic, height and ambient occlusion outputs with inputs already connected", + "مخرجات اللون الأساسي والناظم والخشونة والمعدنية والارتفاع والإطباق المحيط موصولة بمدخلاتها مسبقاً", ), ("Base parameters", "المعلمات الأساسية"), ("Batch", "دفعة"), @@ -119,6 +120,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Category", "الفئة"), ("Ceil", "الحد الأعلى (Ceil)"), ("Channels shown", "القنوات المعروضة"), + ("Choose a package", "اختر حزمة"), ("Check at least one output to export", "حدّد مخرجًا واحدًا على الأقل للتصدير"), ("Check for updates...", "التحقق من وجود تحديثات..."), ("Choose a folder to export to", "اختر مجلداً للتصدير إليه"), @@ -131,6 +133,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Click a node to show it here", "انقر على عقدة لعرضها هنا"), ("Clip planes", "مستويات القطع"), ("Close", "إغلاق"), + ("Close or confirm", "إغلاق أو تأكيد"), ("Close all", "إغلاق الكل"), ("Close the Histogram panel", "إغلاق لوحة المخطط البياني"), ("Close the Information panel", "إغلاق لوحة المعلومات"), @@ -266,6 +269,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Format", "الصيغة"), ("Fractional part", "الجزء الكسري"), + ("Frame graph", "تأطير المخطط"), ("Frame", "تأطير"), ("Frame all", "تأطير الكل"), ("Frame all (F)", "تأطير الكل (F)"), @@ -431,6 +435,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Opacity", "العتامة"), ("Open", "فتح"), ("Open graph", "فتح المخطط"), + ("Open node search", "فتح البحث عن العقد"), ("Open package...", "فتح حزمة..."), ("Open package... (Ctrl+O)", "فتح حزمة... (Ctrl+O)"), ("Open...", "فتح..."), @@ -581,7 +586,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save settings", "حفظ الإعدادات"), ("Saved", "تم الحفظ"), ("Saved as the default 3D view", "حُفظ كعرض ثلاثي الأبعاد افتراضي"), - ("saved; use Save as for packages without a file", "حُفظت؛ استخدم «حفظ باسم» للحزم التي ليس لها ملف"), ("Saving a render needs the desktop app; copy it to the clipboard instead", "حفظ التصيير يتطلب تطبيق سطح المكتب؛ انسخه إلى الحافظة بدلاً من ذلك"), ("Scene", "المشهد"), ("Scene browser", "متصفح المشهد"), @@ -689,6 +693,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Uniform Color", "لون موحّد"), ("Unlit", "غير مضاء"), ("Use as result", "استخدام كنتيجة"), + ("Use Save as for:", "استخدم «حفظ باسم» لـ:"), ("Use the built-in default", "استخدام الإعداد الافتراضي المدمج"), ("Use this parameter; off reads as if the material had none", "استخدام هذا المعامل؛ عند الإيقاف يُقرأ كأن المادة لا تحتويه"), ("Use viewport resolution", "استخدام دقة منفذ العرض"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5f722e38..83b0b057 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -45,6 +45,7 @@ mod material_craft_app; mod native_dialogs; pub mod pattern; mod plugin_manager; +#[path = "preference/mod.rs"] pub mod preferences; mod template_card; mod toast; diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index 40dc9bb0..0bb6bbc0 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -73,19 +73,21 @@ fn category_icon(category: &str) -> &'static str { } /// The library's entries for the open session, rebuilt when its packages change -fn entries(app: &MaterialCraftApp, ctx: &egui::Context) -> Arc> { +pub(crate) fn entries(app: &MaterialCraftApp, ctx: &egui::Context) -> Arc> { type Cached = (Vec<(String, usize)>, Arc>); - let mut key: Vec<(String, usize)> = vec![(String::new(), Arc::as_ptr(&app.session.library) as usize)]; - key.extend( - app.session.pkg.dependencies.iter().filter(|(path, _)| path.starts_with("sbs://")).map(|(path, package)| (path.clone(), Arc::as_ptr(package) as usize)), - ); + let library = ("", Arc::as_ptr(&app.session.library) as usize); + let packages = app.session.pkg.dependencies.iter().filter(|(path, _)| path.starts_with("sbs://")); + let key = std::iter::once(library).chain(packages.map(|(path, package)| (path.as_str(), Arc::as_ptr(package) as usize))); + let id = egui::Id::unique("library-entries"); - if let Some((cached, list)) = ctx.data(|data| data.get_temp::>(id)).as_deref() - && *cached == key + let previous = ctx.data(|data| data.get_temp::>(id)); + if let Some((cached, list)) = previous.as_deref() + && cached.iter().map(|(path, address)| (path.as_str(), *address)).eq(key.clone()) { return list.clone(); } + let key: Vec<_> = key.map(|(path, address)| (path.to_owned(), address)).collect(); let list = Arc::new(app.session.library_entries()); ctx.data_mut(|data| data.insert_temp(id, Arc::new((key, list.clone())))); list diff --git a/crates/ui-egui/src/library.test.rs b/crates/ui-egui/src/library.test.rs index ca661dde..f2ae8e85 100644 --- a/crates/ui-egui/src/library.test.rs +++ b/crates/ui-egui/src/library.test.rs @@ -13,6 +13,31 @@ fn labels(app: &MaterialCraftApp) -> Vec { visible(app, &entries, &LibraryTarget::of(app)).into_iter().map(|entry| entry.label.clone()).collect() } +#[test] +fn catalog_hits_share_entries_and_replaced_packages_release_them() { + let mut app = app(); + let context = egui::Context::default(); + let path = "sbs://test/replaced.sbs"; + + for name in ["First", "Second", "Third"] { + let catalog = entries(&app, &context); + assert!(Arc::ptr_eq(&catalog, &entries(&app, &context))); + let previous = Arc::downgrade(&catalog); + drop(catalog); + + app.session.pkg.dependencies.insert(path.into(), Arc::new(materialcraft_engine::core::Package::new(name))); + let replacement = entries(&app, &context); + + assert!(previous.upgrade().is_none()); + assert!(!replacement.is_empty()); + } + + let last = Arc::downgrade(&entries(&app, &context)); + drop(context); + + assert!(last.upgrade().is_none()); +} + /// Open project graphs remain separate from reusable library entries. #[test] fn open_package_graphs_are_explorer_resources_not_library_entries() { diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 8f780a2e..28bba14c 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -15,6 +15,7 @@ pub struct MaterialCraftApp { pub cooker: cook::Cooker, /// Node output thumbnails and library previews pub thumbs: thumbs::Thumbs, + pub(crate) template_previews: windows::TemplatePreviews, /// The graph editor's gesture state pub graph: graph::GraphView, pub view3d: view3d::View3dState, @@ -42,6 +43,10 @@ pub struct MaterialCraftApp { last_time: f64, #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, + #[cfg(not(target_arch = "wasm32"))] + autosave_workspace: u64, + #[cfg(not(target_arch = "wasm32"))] + autosave_worker: Option>, styled: Option<(theme::Brightness, theme::Accent)>, /// Release checks and the update prompt (desktop only) #[cfg(not(target_arch = "wasm32"))] @@ -95,6 +100,7 @@ impl MaterialCraftApp { toasts: Vec::new(), cooker: cook::Cooker::default(), thumbs: thumbs::Thumbs::default(), + template_previews: windows::TemplatePreviews::default(), graph: graph::GraphView::default(), view3d: view3d::View3dState::default(), view2d: view2d::View2dState::default(), @@ -115,6 +121,10 @@ impl MaterialCraftApp { quit_confirmed: false, last_time: 0.0, next_autosave, + #[cfg(not(target_arch = "wasm32"))] + autosave_workspace: std::hash::BuildHasher::hash_one(&std::hash::RandomState::new(), ()), + #[cfg(not(target_arch = "wasm32"))] + autosave_worker: None, styled: None, #[cfg(not(target_arch = "wasm32"))] updates_rt: crate::updates_ui::Runtime::default(), @@ -146,24 +156,28 @@ impl MaterialCraftApp { /// Push application preferences into the session pub fn apply_prefs(&mut self) { self.ui.prefs.library_cache = self.ui.prefs.library_cache.sanitized(); - if self.session.library_cache_prefs != self.ui.prefs.library_cache { - let _ = materialcraft_engine::execute(&mut self.session, "library.cache.configure", &serde_json::json!(self.ui.prefs.library_cache)); + let library_cache = self.ui.committed_prefs().library_cache.sanitized(); + if self.session.library_cache_prefs != library_cache { + let _ = materialcraft_engine::execute(&mut self.session, "library.cache.configure", &serde_json::json!(library_cache)); } - self.thumbs.configure_cache(self.ui.prefs.library_cache, self.session.library_cache_clear_epoch); + self.thumbs.configure_cache(library_cache, self.session.library_cache_clear_epoch); + self.ui.prefs.history = self.ui.prefs.history.sanitized(); - if self.session.history_prefs != self.ui.prefs.history { - let _ = materialcraft_engine::execute(&mut self.session, "session.history", &serde_json::json!(self.ui.prefs.history)); + let history = self.ui.committed_prefs().history.sanitized(); + if self.session.history_prefs != history { + let _ = materialcraft_engine::execute(&mut self.session, "session.history", &serde_json::json!(history)); } - self.ui.recent.truncate(self.ui.prefs.recent_limit.clamp(1, crate::state::Prefs::MAX_RECENT)); - self.session.view_outputs_on_open = self.ui.prefs.view_outputs_on_open; + self.ui.recent.truncate(self.ui.committed_prefs().recent_limit.clamp(1, crate::state::Prefs::MAX_RECENT)); + self.session.view_outputs_on_open = self.ui.committed_prefs().view_outputs_on_open; - if self.session.camera != self.ui.prefs.camera.sanitized() { - self.session.set_camera_prefs(self.ui.prefs.camera); + let camera = self.ui.committed_prefs().camera.sanitized(); + if self.session.camera != camera { + self.session.set_camera_prefs(camera); } - // A saved default is a file like any other: its numbers are put in range before use - let default_view = self.ui.prefs.default_view3d.clone().map(|view| { + // Bound saved camera values before applying them + let default_view = self.ui.committed_prefs().default_view3d.clone().map(|view| { let mut view = view.sanitized(); view.target = self.session.camera.clamp_target(view.target); view @@ -171,9 +185,10 @@ impl MaterialCraftApp { if self.session.default_view3d != default_view { self.session.default_view3d = default_view; } - let p = if self.ui.prefs.preview_size == 0 { None } else { Some(self.ui.prefs.preview_size.clamp(64, 8192)) }; - if self.session.preview_size != p { - let _ = materialcraft_engine::execute(&mut self.session, "view.previewSize", &serde_json::json!({"size": p.unwrap_or(0)})); + + let preview_size = if self.ui.prefs.preview_size == 0 { None } else { Some(self.ui.prefs.preview_size.clamp(64, 8192)) }; + if self.session.preview_size != preview_size { + let _ = materialcraft_engine::execute(&mut self.session, "view.previewSize", &serde_json::json!({"size": preview_size.unwrap_or(0)})); } } @@ -263,19 +278,7 @@ impl MaterialCraftApp { self.ui.dock.focus(docking::Panel::Properties); } - if id == "view.previewSize" { - self.ui.prefs.preview_size = self.session.preview_size.unwrap_or(0); - } - if id == "view.3d.saveDefault" { - self.ui.prefs.default_view3d = self.session.default_view3d.clone(); - } - if id == "library.cache.configure" { - self.ui.prefs.library_cache = self.session.library_cache_prefs; - } - if id == "session.history" { - self.ui.prefs.history = self.session.history_prefs; - } - + self.sync_preferences_after_command(id); self.close_subgraph_after(id); if id == "graph.node.function.edit" && let Ok(target) = serde_json::from_value::(v["target"].clone()) @@ -303,6 +306,39 @@ impl MaterialCraftApp { } } + /// Commands commit explicit preferences even while the window presents a draft + pub(crate) fn sync_preferences_after_command(&mut self, id: &str) { + let prefs = &mut self.ui.prefs; + let applied = self.ui.preferences.applied.as_mut(); + match id { + "view.previewSize" => { + prefs.preview_size = self.session.preview_size.unwrap_or(0); + if let Some(applied) = applied { + applied.preview_size = prefs.preview_size; + } + } + "view.3d.saveDefault" => { + prefs.default_view3d.clone_from(&self.session.default_view3d); + if let Some(applied) = applied { + applied.default_view3d.clone_from(&prefs.default_view3d); + } + } + "library.cache.configure" => { + prefs.library_cache = self.session.library_cache_prefs; + if let Some(applied) = applied { + applied.library_cache = prefs.library_cache; + } + } + "session.history" => { + prefs.history = self.session.history_prefs; + if let Some(applied) = applied { + applied.history = prefs.history; + } + } + _ => {} + } + } + pub(crate) fn close_subgraph_after(&mut self, command: &str) { if command.starts_with("file.new") || command.starts_with("package.") @@ -351,49 +387,42 @@ impl MaterialCraftApp { pub fn toast(&mut self, text: impl Into, error: bool) { let text = text.into(); - self.status = text.clone(); self.session.log(text.clone()); + self.toast_only(text, error); + } + + pub(crate) fn toast_only(&mut self, text: String, error: bool) { + self.status = text.clone(); self.toasts.push(Toast { text, error, until: self.last_time + if error { 6.0 } else { 3.0 } }); } /// Every `prefs.autosave_minutes`, write a modified package to the autosave folder #[cfg(not(target_arch = "wasm32"))] fn autosave(&mut self, now: f64) { - let period = self.ui.prefs.autosave_minutes as f64 * 60.0; + let preferences = self.ui.committed_prefs(); + let period = f64::from(preferences.autosave_minutes) * 60.0; if period <= 0.0 || !self.session.modified { self.next_autosave = now + period; return; } - if now < self.next_autosave { + // A slow disk must not accumulate multiple package snapshots + if now < self.next_autosave || self.autosave_worker.as_ref().is_some_and(|worker| !worker.is_finished()) { return; } self.next_autosave = now + period; - let folder = user_dir("autosave"); - let pkg = self.session.pkg.clone(); - let keep = self.ui.prefs.autosave_versions.clamp(1, crate::state::Prefs::MAX_AUTOSAVE_VERSIONS); - let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || { - let path = crate::autosave_versions::next_path(&folder, &pkg.name); - let result = std::fs::create_dir_all(&folder) - .map_err(|error| error.to_string()) - .and_then(|_| { - materialcraft_engine::formats::project::ProjectFiles::build(&pkg, "autosave.mcraft", true) - .and_then(|files| files.zip()) - .map_err(|error| error.to_string()) - }) - .and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|error| error.to_string())); - - match result { - Ok(()) => { - crate::autosave_versions::prune(&folder, &pkg.name, keep); - log::info!("autosaved {}", path.display()); - } - Err(error) => log::warn!("autosave to {} failed: {error}", path.display()), - } - }); - if let Err(e) = spawned { - log::warn!("could not start autosave: {e}"); + let folder = crate::autosave_versions::folder(&user_dir("autosave"), self.session.path.as_deref(), self.autosave_workspace, self.session.document_id); + let package = self.session.pkg.clone(); + let keep = preferences.autosave_versions.clamp(1, crate::state::Prefs::MAX_AUTOSAVE_VERSIONS); + let worker = + std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || match crate::autosave_versions::save(&folder, &package, keep) { + Ok(()) => log::info!("Saved a recovery copy"), + Err(error) => log::warn!("Could not save a recovery copy ({:?})", error.kind()), + }); + match worker { + Ok(worker) => self.autosave_worker = Some(worker), + Err(error) => log::warn!("Could not start autosave ({:?})", error.kind()), } } } @@ -404,7 +433,13 @@ impl eframe::App for MaterialCraftApp { } fn save(&mut self, storage: &mut dyn eframe::Storage) { + if let Some(applied) = self.ui.preferences.applied.as_mut() { + std::mem::swap(applied, &mut self.ui.prefs); + } eframe::set_value(storage, "ui", &self.ui); + if let Some(applied) = self.ui.preferences.applied.as_mut() { + std::mem::swap(applied, &mut self.ui.prefs); + } } fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { diff --git a/crates/ui-egui/src/material_craft_app.test.rs b/crates/ui-egui/src/material_craft_app.test.rs index 3add740b..df5940a0 100644 --- a/crates/ui-egui/src/material_craft_app.test.rs +++ b/crates/ui-egui/src/material_craft_app.test.rs @@ -5,6 +5,26 @@ mod lib_tests { use materialcraft_engine::sample_session; use serde_json::json; + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn autosave_leaves_one_snapshot_worker_in_flight() { + let mut app = MaterialCraftApp::headless(sample_session(), UiState::default()); + app.session.modified = true; + let (sender, receiver) = std::sync::mpsc::channel(); + let worker = std::thread::spawn(move || receiver.recv().unwrap()); + let initial_worker = worker.thread().id(); + app.autosave_worker = Some(worker); + + for interval in 1..=3 { + let now = app.next_autosave + f64::from(interval) * 600.0; + app.autosave(now); + assert_eq!(app.autosave_worker.as_ref().unwrap().thread().id(), initial_worker); + } + + sender.send(()).unwrap(); + app.autosave_worker.take().unwrap().join().unwrap(); + } + #[test] fn copy_and_cut_fill_the_system_clipboard_in_material_and_function_canvases() { use crate::function::{FunctionEditor, FunctionTarget}; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b18c05db..915ceee6 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -93,6 +93,7 @@ pub const CATALOG: &[MenuItem] = &[ sep("File"), it("File", "Save", "file.save", Some("Ctrl+S")), it("File", "Save as...", "file.saveAs", Some("Ctrl+Shift+S")), + #[cfg(not(target_arch = "wasm32"))] it("File", "Save all", "file.saveAll", None), it("File", "Close all", "ui.closeAll", None), sep("File"), @@ -198,6 +199,10 @@ pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool { return app.cooker.busy(); } + if id == "graph.cook" && app.cooker.suspended { + return false; + } + if matches!(id, "edit.paste" | "edit.pasteWithoutLinks") { return app.session.graph().is_ok() && app.session.clipboard.as_ref().is_some_and(|clip| !clip.nodes.is_empty()); } @@ -205,6 +210,7 @@ pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool { if is_ui(id) { return true; } + materialcraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok()) } @@ -231,11 +237,13 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { app.ui.dock.toggle(panel); return; } + if let Some(size) = id.strip_prefix("ui.preview.").and_then(|s| s.parse::().ok()) { app.ui.prefs.preview_size = size; app.apply_prefs(); return; } + match id { "ui.newGraph" => crate::new_graph_dialog::open(app, materialcraft_engine::core::GraphKind::Material), "ui.newFunctionGraph" => crate::new_graph_dialog::open(app, materialcraft_engine::core::GraphKind::Function), @@ -261,19 +269,21 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { "ui.help.checkForUpdates" => crate::updates_ui::check(app), "ui.cook.cancel" => crate::cook::cancel(app), "ui.cook.suspend" => crate::cook::toggle_suspended(app), + "graph.cook" if app.cooker.suspended => {} "ui.pluginManager" => app.ui.windows.plugin_manager = true, "ui.view.toolbar" => app.ui.prefs.show_toolbar = !app.ui.prefs.show_toolbar, #[cfg(not(target_arch = "wasm32"))] "ui.help.exportLog" => crate::native_dialogs::export_log(app), - id if crate::help_links::url(id).is_some() => { + _ => { if let Some(url) = crate::help_links::url(id) { ctx.open_url(egui::OpenUrl::new_tab(url)); + return; } - } - _ => { + if crate::windows::file_action(app, ctx, id) { return; } + app.run(id, Value::Null); } } @@ -449,6 +459,7 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { if ctx.egui_wants_keyboard_input() || egui::Popup::is_any_open(ctx) { return; } + // The desktop sends Copy, Cut and Paste events in place of their key presses if !ctx .input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. } | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_)))) @@ -460,6 +471,7 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { if !modality.is_blocked() && crate::explorer::shortcuts(app, ctx) { return; } + if !modality.is_blocked() { crate::graph::wire_actions::shortcuts(app, ctx); } @@ -468,21 +480,21 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { if app.keymap.platform() != platform { app.keymap = keymap(platform); } - // Selected label text copies through egui's Copy and Cut events, which a hit would remove + + // Keep egui's copy, cut, and Escape events while label text is selected let label_selected = label_text_selected(ctx); + // A clipboard chord with nothing to copy or paste leaves its event to egui instead of reporting an error let unavailable_clipboard_commands: Vec<&str> = ["edit.copy", "edit.cut", "edit.paste"].into_iter().filter(|id| !enabled(app, id)).collect(); + // A drag in progress keeps Escape so the gesture can cancel itself let gesture_in_progress = ctx.input(|i| i.pointer.any_down()); + let node_search_open = app.graph.search_is_open() || app.function_editor.as_ref().is_some_and(|editor| editor.search.is_some()); let hits = ctx.input_mut(|i| { app.dispatcher.dispatch_filtered(i, &app.keymap, &Active::NONE, |hit| { let id = hit.command.id.as_str(); - // Escape cancels a cook only while one runs and no drag is held, so it keeps closing and clearing everything else - let cancels_nothing = id == "ui.cook.cancel" && (!app.cooker.busy() || gesture_in_progress); - modality.allows(id) - && !(label_selected && matches!(id, "edit.copy" | "edit.cut")) - && !unavailable_clipboard_commands.contains(&id) - && !cancels_nothing + let keeps_escape = id == "ui.cook.cancel" && (!app.cooker.busy() || gesture_in_progress || node_search_open || label_selected); + modality.allows(id) && !(label_selected && matches!(id, "edit.copy" | "edit.cut")) && !unavailable_clipboard_commands.contains(&id) && !keeps_escape }) }); for hit in hits { diff --git a/crates/ui-egui/src/native_dialogs.rs b/crates/ui-egui/src/native_dialogs.rs index 577fa2e1..83d80743 100644 --- a/crates/ui-egui/src/native_dialogs.rs +++ b/crates/ui-egui/src/native_dialogs.rs @@ -41,7 +41,7 @@ pub(crate) enum Then { }, /// The image file the 2D view draws behind transparent pixels BackgroundImage, - /// Help ▸ Export log: the Console's messages, one per line + /// Help ▸ Export log: diagnostic events without message details ExportLog(String), /// The parameters `graph.input.bind` runs with, before the path BindInput(Value, GraphRef), @@ -96,13 +96,36 @@ pub(crate) fn save_package(app: &mut MaterialCraftApp, copy: bool) { ask(app, dialog, then); } -/// Help ▸ Export log: ask where to write the Console's messages as a text file +/// Help ▸ Export log: ask where to write a diagnostic event log pub(crate) fn export_log(app: &mut MaterialCraftApp) { - let text = app.session.log.join("\n"); + let text = log_for_export(&app.session); let dialog = craft_dialogs::FileDialog::save().file_name("materialcraft-log.txt").filter(tr("Text"), &["txt"]); ask(app, dialog, Then::ExportLog(text)); } +fn log_for_export(session: &materialcraft_engine::Session) -> String { + use std::fmt::Write as _; + + let mut text = format!("MaterialCraft {}\nMessage details omitted to protect document names and paths.\n", materialcraft_engine::VERSION); + + // Raw Console messages can contain names and paths in platform-specific error formats + for message in &session.log { + let event = match message.as_str() { + message if message.starts_with(materialcraft_engine::WARNING_PREFIX) => "Package warning", + message if message.starts_with("Opened ") => "Opened package", + message if message.starts_with("Saved ") => "Saved file", + message if message.starts_with("Save all: ") => "Saved multiple packages", + message if message.starts_with("Exported ") => "Exported file", + _ => "Session message", + }; + let _ = writeln!(text, "{event}"); + } + + let (failures, unsupported) = session.cook_failures(); + let _ = writeln!(text, "Node errors in the active graph: {}\nUnsupported nodes: {unsupported}", failures.len()); + text +} + /// Save in the unsaved-changes prompt, for a package without a path: waits behind any open dialog pub(crate) fn save_before_action(app: &mut MaterialCraftApp) { let then = Then::SavePackage { document: app.session.document_id, copy: false, before_action: true }; @@ -189,8 +212,8 @@ fn chosen(app: &mut MaterialCraftApp, then: Then, path: &std::path::Path) { } } Then::ExportLog(text) => match materialcraft_engine::formats::write_atomic(path, text.as_bytes()) { - Ok(()) => app.toast(format!("{} {picked}", tr("Saved")), false), - Err(error) => app.toast(format!("{}: {error}", tr("The log could not be saved")), true), + Ok(()) => app.toast_only(format!("{} {picked}", tr("Saved")), false), + Err(error) => app.toast_only(format!("{}: {error}", tr("The log could not be saved")), true), }, Then::SaveViewState => { if app.run("view.3d.saveState", json!({"path": picked})).is_some() { diff --git a/crates/ui-egui/src/native_dialogs.test.rs b/crates/ui-egui/src/native_dialogs.test.rs index 4fea63f8..d35abecf 100644 --- a/crates/ui-egui/src/native_dialogs.test.rs +++ b/crates/ui-egui/src/native_dialogs.test.rs @@ -7,6 +7,21 @@ fn app() -> MaterialCraftApp { MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()) } +#[test] +fn exported_log_keeps_events_and_strips_raw_document_details() { + let mut app = app(); + app.session.log("Opened C:\\My projects\\Client sample.sbs"); + app.session.warn("Invalid resource at /home/person/private textures/input.png"); + + let report = log_for_export(&app.session); + + assert!(report.contains("Opened package")); + assert!(report.contains("Package warning")); + assert!(report.contains("Node errors in the active graph: 0")); + assert!(!report.contains("Client sample")); + assert!(!report.contains("/home/person")); +} + /// Answer every queued dialog with `answer` and collect what was asked fn answer_all(app: &mut MaterialCraftApp, answer: impl Fn() -> Answer + 'static) -> Vec { let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); diff --git a/crates/ui-egui/src/new_graph_dialog.rs b/crates/ui-egui/src/new_graph_dialog.rs index 32fc6c51..e2aac9cf 100644 --- a/crates/ui-egui/src/new_graph_dialog.rs +++ b/crates/ui-egui/src/new_graph_dialog.rs @@ -15,6 +15,8 @@ const WINDOW_SIZE: egui::Vec2 = vec2(1000.0, 640.0); const SETTINGS_WIDTH: f32 = 340.0; const CARD_GAP: f32 = 14.0; const BUTTON_WIDTH: f32 = 120.0; +const ACTION_BAR_HEIGHT: f32 = 36.0; +const COLUMN_GAP: f32 = 24.0; /// The sides a new graph can have, in pixels const SIDES: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192]; /// The categories the dialog lists: every template, or the templates of one kind of graph @@ -41,17 +43,24 @@ fn choose(app: &mut MaterialCraftApp, card: &TemplateCard) { } pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { + let size = crate::windows::dialog_size(ctx, WINDOW_SIZE); let mut open = true; let mut create = false; let title = if app.ui.new_graph_kind == GraphKind::Function { tr("New function graph") } else { tr("New graph") }; - crate::windows::modal(ctx, "new-graph", title, &mut open, WINDOW_SIZE, |ui| { - ui.set_min_size(WINDOW_SIZE); + crate::windows::modal(ctx, "new-graph", title, &mut open, size, |ui| { + ui.set_min_size(size); let whole = ui.available_rect_before_wrap(); - let cards = egui::Rect::from_min_max(whole.min, egui::pos2(whole.right() - SETTINGS_WIDTH - 24.0, whole.bottom())); - let settings = egui::Rect::from_min_max(egui::pos2(whole.right() - SETTINGS_WIDTH, whole.top()), whole.max); + let settings_left = whole.right() - SETTINGS_WIDTH.min(size.x * 0.52); + let cards = egui::Rect::from_min_max(whole.min, egui::pos2(settings_left - COLUMN_GAP, whole.bottom())); + let settings = egui::Rect::from_min_max(egui::pos2(settings_left, whole.top()), whole.max); card_grid(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(cards))); - create = graph_settings(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(settings))); + let bar = settings.with_min_y(settings.bottom() - ACTION_BAR_HEIGHT); + let form = settings.with_max_y(bar.top()); + let mut form_ui = ui.new_child(egui::UiBuilder::new().max_rect(form)); + let destination_available = egui::ScrollArea::vertical().auto_shrink([false, false]).show(&mut form_ui, |ui| graph_settings(app, ui)).inner; + create = graph_actions(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(bar)), destination_available); + ui.advance_cursor_after_rect(whole); }); @@ -66,13 +75,6 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { /// Create the graph. Returns true when it was created fn run(app: &mut MaterialCraftApp) -> bool { let target = app.ui.new_graph_package; - if let Some(document) = target - && document != app.session.document_id - && app.run("package.activate", json!({"document": document})).is_none() - { - return false; - } - let kind = if app.ui.new_graph_kind == GraphKind::Function { "function" } else { "material" }; let height = if app.ui.new_graph_linked { app.ui.new_graph_size } else { app.ui.new_graph_height }; let parameters = json!({ @@ -81,6 +83,7 @@ fn run(app: &mut MaterialCraftApp) -> bool { "name": app.ui.new_graph_name, "size": app.ui.new_graph_size, "height": height, + "document": target, "newPackage": target.is_none(), }); let created = app.run("file.new", parameters).is_some(); @@ -96,7 +99,7 @@ fn card_grid(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.horizontal(|ui| { ui.label(RichText::new(tr("Category")).strong()); let current = CATEGORIES.iter().find(|(kind, _)| *kind == app.ui.new_graph_category).map_or("", |(_, label)| label); - let combo = egui::ComboBox::from_id_salt("new-graph-category").width(220.0).selected_text(tr(current)).show_ui(ui, |ui| { + let combo = egui::ComboBox::from_id_salt("new-graph-category").width(ui.available_width().min(220.0)).selected_text(tr(current)).show_ui(ui, |ui| { for (kind, label) in CATEGORIES { ui.selectable_value(&mut app.ui.new_graph_category, kind, tr(label)); } @@ -124,7 +127,7 @@ fn card_grid(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.spacing_mut().item_spacing.x = CARD_GAP; for card in row { let chosen = app.ui.new_graph_kind == card.kind && app.ui.new_graph_template == card.id; - let preview = crate::windows::template_preview(ui.ctx(), card.id); + let preview = crate::windows::template_preview(app, ui.ctx(), card.id); let response = crate::template_card::show(ui, card, chosen, preview); if response.clicked() { choose(app, card); @@ -141,7 +144,7 @@ fn card_grid(app: &mut MaterialCraftApp, ui: &mut Ui) { }); } -/// The graph's name, size and package, and the Create and Cancel buttons. Returns true for Create +/// The graph's name, size and package. Returns whether the chosen package is available. fn graph_settings(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { let tokens = Tokens::get(ui.ctx()); ui.horizontal(|ui| { @@ -173,29 +176,45 @@ fn graph_settings(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { } ui.label(RichText::new(tr("Create graph in")).strong()); - let packages: Vec<(u64, String)> = app.session.open_packages().into_iter().map(|(id, package, _, _)| (id, package.name.clone())).collect(); - let current = app - .ui - .new_graph_package - .and_then(|id| packages.iter().find(|(package, _)| *package == id)) - .map_or_else(|| tr("New package").to_string(), |(_, name)| name.clone()); + let packages = app.session.open_packages(); + let package_label = |id, name: &str, path: Option<&str>| match path { + Some(path) => format!("{name} — {path}"), + None => format!("{name} (#{id})"), + }; + let destination_available = app.ui.new_graph_package.is_none_or(|target| packages.iter().any(|(id, ..)| *id == target)); + let current = app.ui.new_graph_package.map_or_else( + || tr("New package").to_string(), + |target| { + packages + .iter() + .find(|(id, ..)| *id == target) + .map_or_else(|| tr("Choose a package").to_string(), |(id, package, path, _)| package_label(*id, &package.name, *path)) + }, + ); let combo = egui::ComboBox::from_id_salt("new-graph-package").width(ui.available_width()).selected_text(current).show_ui(ui, |ui| { ui.selectable_value(&mut app.ui.new_graph_package, None, tr("New package")); - for (id, name) in &packages { - ui.selectable_value(&mut app.ui.new_graph_package, Some(*id), name); + for (id, package, path, _) in &packages { + ui.selectable_value(&mut app.ui.new_graph_package, Some(*id), package_label(*id, &package.name, *path)); } }); crate::widgets::name(&combo.response, egui::Role::ComboBox, "Create graph in"); + destination_available +} + +fn graph_actions(app: &mut MaterialCraftApp, ui: &mut Ui, destination_available: bool) -> bool { let mut create = std::mem::take(&mut app.ui.new_graph_create_now); - let bottom = ui.max_rect().bottom(); - let bar = egui::Rect::from_min_max(egui::pos2(ui.max_rect().left(), bottom - 32.0), ui.max_rect().right_bottom()); - let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); - if bar_ui.add_sized([BUTTON_WIDTH, 28.0], egui::Button::new(tr("Cancel"))).clicked() { - app.ui.windows.new_graph = false; - } - create |= bar_ui.add_sized([BUTTON_WIDTH, 28.0], crate::widgets::primary_button(&bar_ui, tr("Create"))).clicked(); - create + let button_width = BUTTON_WIDTH.min((ui.available_width() * 0.5 - ui.spacing().item_spacing.x).max(0.0)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add_sized([button_width, 28.0], egui::Button::new(tr("Cancel"))).clicked() { + app.ui.windows.new_graph = false; + } + + let create_button = crate::widgets::primary_button(ui, tr("Create")); + create |= ui.add_enabled_ui(destination_available, |ui| ui.add_sized([button_width, 28.0], create_button)).inner.clicked(); + }); + + create && destination_available && app.ui.windows.new_graph } /// A list of the sides a graph can have diff --git a/crates/ui-egui/src/node_shortcuts.rs b/crates/ui-egui/src/node_shortcuts.rs index aab3e489..6ee6bff6 100644 --- a/crates/ui-egui/src/node_shortcuts.rs +++ b/crates/ui-egui/src/node_shortcuts.rs @@ -1,61 +1,54 @@ -//! Node creation shortcuts (Preferences ▸ Shortcuts): a key with modifiers that adds a library -//! entry under the pointer in the graph. The text of a shortcut is the menus' form, "Ctrl+Shift+B", -//! where Ctrl is Command on macOS +//! Node creation shortcuts add a library entry under the pointer in the material graph -use egui::{Key, Modifiers}; +use craft_keymap::{Chord, Key, Mods, Platform}; +use egui::{Event, InputState}; -/// The library categories whose entries can have a creation shortcut: the atomic nodes and the graph items +/// The library categories whose entries can have a creation shortcut pub(crate) const CATEGORIES: [&str; 2] = ["Atomic nodes", "Graph items"]; -/// The text of a key pressed with `modifiers`, or `None` for a key that cannot start a shortcut -pub(crate) fn text(modifiers: Modifiers, key: Key) -> Option { - // Plain Escape, Tab and Enter keep their usual work: closing, moving focus and confirming - if modifiers.is_none() && matches!(key, Key::Escape | Key::Tab | Key::Enter) { - return None; - } +/// The chord on a fresh key press, using the event's own modifiers +pub(crate) fn event_chord(event: &Event, platform: Platform) -> Option { + let Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { return None }; - let mut parts = Vec::new(); - if modifiers.command { - parts.push("Ctrl"); - } - if modifiers.alt { - parts.push("Alt"); - } - if modifiers.shift { - parts.push("Shift"); - } - parts.push(key.name()); - Some(parts.join("+")) + Some(Chord::new(Mods::from_egui(modifiers, platform), Key::from_egui(*key)?)) } -/// The modifiers and key a shortcut text names -pub(crate) fn parse(text: &str) -> Option<(Modifiers, Key)> { - let mut modifiers = Modifiers::NONE; - let mut key = None; - for part in text.split('+') { - match part { - "Ctrl" | "Cmd" => modifiers.command = true, - "Alt" => modifiers.alt = true, - "Shift" => modifiers.shift = true, - name if key.is_none() => key = Some(Key::from_name(name)?), - _ => return None, - } - } - key.map(|key| (modifiers, key)) +/// Preserve the stored syntax where Ctrl means Command on macOS +pub(crate) fn text(chord: Chord) -> String { + chord.portable().replace("Ctrl+", "Control+").replace("Cmd+", "Ctrl+") } /// The entry whose shortcut was pressed this frame, if any -pub(crate) fn pressed(shortcuts: &std::collections::BTreeMap, input: &egui::InputState) -> Option { - shortcuts.iter().find_map(|(entry, text)| { - let (modifiers, key) = parse(text)?; - (input.modifiers.matches_logically(modifiers) && input.modifiers.shift == modifiers.shift && input.key_pressed(key)).then(|| entry.clone()) +pub(crate) fn pressed<'a>(shortcuts: &'a std::collections::BTreeMap, input: &InputState, platform: Platform) -> Option<&'a str> { + if shortcuts.is_empty() { + return None; + } + + input.events.iter().filter_map(|event| event_chord(event, platform)).find_map(|pressed| { + shortcuts.iter().find_map(|(entry, text)| { + let mut assigned = crate::menus::parse_shortcut(text)?; + assigned.mods = assigned.mods.effective(platform); + (assigned == pressed).then_some(entry.as_str()) + }) }) } -/// The app command a shortcut text already starts, if any -pub(crate) fn taken_by(text: &str) -> Option<&'static str> { - let wanted = parse(text)?; - crate::menus::shortcut_table().into_iter().find(|(_, shortcut)| parse(shortcut) == Some(wanted)).map(|(id, _)| id) +/// The app command or canvas action already bound to the chord +pub(crate) fn taken_by(chord: Chord, platform: Platform) -> Option<&'static str> { + if chord.mods.is_none() { + match chord.key { + Key::Space | Key::Tab => return Some("Open node search"), + Key::F => return Some("Frame graph"), + Key::Escape | Key::Enter => return Some("Close or confirm"), + _ => {} + } + } + + crate::menus::shortcut_table().into_iter().find_map(|(id, text)| { + let mut assigned = crate::menus::parse_shortcut(text)?; + assigned.mods = assigned.mods.effective(platform); + (assigned == chord).then_some(id) + }) } #[cfg(test)] @@ -64,19 +57,33 @@ mod tests { #[test] fn a_shortcut_reads_back_as_the_keys_that_made_it() { - let both = Modifiers { command: true, shift: true, ..Modifiers::NONE }; - assert_eq!(text(both, Key::B).as_deref(), Some("Ctrl+Shift+B")); - assert_eq!(parse("Ctrl+Shift+B"), Some((both, Key::B))); - assert_eq!(text(Modifiers::ALT, Key::Num1).and_then(|text| parse(&text)), Some((Modifiers::ALT, Key::Num1))); + let plain = Chord::new(Mods::CMD, Key::B); + let both = Chord::new(Mods { cmd: true, ctrl: true, shift: true, ..Mods::NONE }, Key::B); - assert_eq!(text(Modifiers::NONE, Key::Escape), None); - assert_eq!(parse("Ctrl+Nope"), None); - assert_eq!(parse("Ctrl+B+C"), None); + assert_eq!(text(plain), "Ctrl+B"); + assert_eq!(crate::menus::parse_shortcut(&text(both)), Some(both)); + assert_eq!(crate::menus::parse_shortcut("Cmd+B"), Some(plain)); } #[test] fn a_shortcut_the_app_already_uses_is_named() { - assert_eq!(taken_by("Ctrl+S"), Some("file.save")); - assert_eq!(taken_by("Ctrl+Shift+B"), None); + assert_eq!(taken_by(Chord::new(Mods::CMD, Key::S), Platform::Windows), Some("file.save")); + assert_eq!(taken_by(Chord::plain(Key::F), Platform::Windows), Some("Frame graph")); + assert_eq!(taken_by(Chord::new(Mods::CTRL, Key::S), Platform::Mac), None); + } + + #[test] + fn key_events_keep_their_own_modifiers_and_ignore_repeat() { + let key = egui::Key::B; + let event = |modifiers, repeat| Event::Key { key, physical_key: None, pressed: true, repeat, modifiers }; + let plain = event(egui::Modifiers::NONE, false); + let alt = event(egui::Modifiers::ALT, false); + let raw = egui::RawInput { events: vec![plain, alt], ..Default::default() }; + let shortcuts = [("node:blur".to_owned(), "Alt+B".to_owned()), ("node:levels".to_owned(), "B".to_owned())].into(); + + let _ = egui::Context::default().run_ui(raw, |ui| { + assert_eq!(ui.input(|input| pressed(&shortcuts, input, Platform::Windows)), Some("node:levels")); + }); + assert!(event_chord(&event(egui::Modifiers::ALT, true), Platform::Windows).is_none()); } } diff --git a/crates/ui-egui/src/preferences/general_page.rs b/crates/ui-egui/src/preference/general_page.rs similarity index 73% rename from crates/ui-egui/src/preferences/general_page.rs rename to crates/ui-egui/src/preference/general_page.rs index c9e53562..4118990a 100644 --- a/crates/ui-egui/src/preferences/general_page.rs +++ b/crates/ui-egui/src/preference/general_page.rs @@ -10,6 +10,7 @@ use crate::theme::{Accent, Brightness}; /// The most undo steps the history slider reaches const MAX_UNDO_STEPS: f32 = 10_000.0; +#[cfg(not(target_arch = "wasm32"))] /// The longest autosave interval the slider reaches, in minutes const MAX_AUTOSAVE_MINUTES: f32 = 60.0; @@ -51,21 +52,25 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { heading(ui, "Views"); ui.checkbox(&mut prefs.invert_zoom, tr("Invert zoom in views")); - heading(ui, "Auto backup"); - let mut minutes = prefs.autosave_minutes as f32; - if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut minutes, 0.0..=MAX_AUTOSAVE_MINUTES, 0).changed() { - prefs.autosave_minutes = minutes.round() as u32; - } - let mut versions = prefs.autosave_versions as usize; - if number_row(ui, "Keep up to", &mut versions, 1..=Prefs::MAX_AUTOSAVE_VERSIONS as usize, "versions") { - prefs.autosave_versions = versions as u32; - } #[cfg(not(target_arch = "wasm32"))] - ui.label( - egui::RichText::new(format!("{} {}", tr("The copies are numbered files in"), crate::user_dir("autosave").display())) - .small() - .color(crate::theme::Tokens::get(ui.ctx()).text_dim), - ); + { + heading(ui, "Auto backup"); + let mut minutes = prefs.autosave_minutes as f32; + if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut minutes, 0.0..=MAX_AUTOSAVE_MINUTES, 0).changed() { + prefs.autosave_minutes = minutes.round() as u32; + } + + let mut versions = prefs.autosave_versions as usize; + if number_row(ui, "Keep up to", &mut versions, 1..=Prefs::MAX_AUTOSAVE_VERSIONS as usize, "versions") { + prefs.autosave_versions = versions as u32; + } + + ui.label( + egui::RichText::new(format!("{} {}", tr("The copies are numbered files in"), crate::user_dir("autosave").display())) + .small() + .color(crate::theme::Tokens::get(ui.ctx()).text_dim), + ); + } heading(ui, "Cooker"); crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(prefs.preview_size), |ui| { diff --git a/crates/ui-egui/src/preferences/graph_page.rs b/crates/ui-egui/src/preference/graph_page.rs similarity index 100% rename from crates/ui-egui/src/preferences/graph_page.rs rename to crates/ui-egui/src/preference/graph_page.rs diff --git a/crates/ui-egui/src/preferences/library_page.rs b/crates/ui-egui/src/preference/library_page.rs similarity index 100% rename from crates/ui-egui/src/preferences/library_page.rs rename to crates/ui-egui/src/preference/library_page.rs diff --git a/crates/ui-egui/src/preferences.rs b/crates/ui-egui/src/preference/mod.rs similarity index 81% rename from crates/ui-egui/src/preferences.rs rename to crates/ui-egui/src/preference/mod.rs index ce737f10..01a2f88f 100644 --- a/crates/ui-egui/src/preferences.rs +++ b/crates/ui-egui/src/preference/mod.rs @@ -5,6 +5,7 @@ mod general_page; mod graph_page; mod library_page; +mod preference_action; mod preferences_page; mod preferences_state; mod projects_page; @@ -12,6 +13,7 @@ mod shortcuts_page; mod view3d_page; use egui::{RichText, Ui, vec2}; +use preference_action::PreferenceAction; pub use preferences_page::PreferencesPage; pub use preferences_state::PreferencesState; @@ -26,14 +28,6 @@ const PAGE_ROW_HEIGHT: f32 = 36.0; const BUTTON_WIDTH: f32 = 110.0; const BUTTON_BAR_HEIGHT: f32 = 40.0; -/// What the buttons at the bottom of the window asked for -#[derive(Clone, Copy, PartialEq, Eq)] -enum Choice { - Ok, - Cancel, - Apply, -} - /// A section heading of a page, in capitals like the reference layout pub(super) fn heading(ui: &mut Ui, title: &str) { ui.add_space(10.0); @@ -57,21 +51,22 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { app.ui.preferences.applied = Some(app.ui.prefs.clone()); } + let size = crate::windows::dialog_size(ctx, WINDOW_SIZE); let mut open = true; let mut choice = None; let mut rebuild_previews = false; - crate::windows::modal(ctx, "prefs", tr("Preferences"), &mut open, WINDOW_SIZE, |ui| { - ui.set_min_size(WINDOW_SIZE); + crate::windows::modal(ctx, "prefs", tr("Preferences"), &mut open, size, |ui| { + ui.set_min_size(size); let whole = ui.available_rect_before_wrap(); let bar_top = whole.bottom() - BUTTON_BAR_HEIGHT; - let list = egui::Rect::from_min_max(whole.min, egui::pos2(whole.left() + PAGE_LIST_WIDTH, bar_top)); + let list = egui::Rect::from_min_max(whole.min, egui::pos2(whole.left() + PAGE_LIST_WIDTH.min(size.x * 0.35), bar_top)); let page = egui::Rect::from_min_max(egui::pos2(list.right() + 16.0, whole.top()), egui::pos2(whole.right(), bar_top)); page_list(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(list))); let mut page_ui = ui.new_child(egui::UiBuilder::new().max_rect(page)); - egui::ScrollArea::vertical().id_salt("preferences-page").auto_shrink([false, false]).show(&mut page_ui, |ui| { - ui.set_width(page.width() - 12.0); + egui::ScrollArea::both().id_salt("preferences-page").auto_shrink([false, false]).show(&mut page_ui, |ui| { + ui.set_min_width((page.width() - 12.0).max(0.0)); match app.ui.preferences.page { PreferencesPage::General => general_page::show(app, ui), PreferencesPage::Projects => projects_page::show(app, ui), @@ -84,12 +79,13 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { let bar = egui::Rect::from_min_max(egui::pos2(whole.left(), bar_top), whole.max); let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); - for (label, pressed) in [("Apply", Choice::Apply), ("Cancel", Choice::Cancel), ("OK", Choice::Ok)] { - let button = if pressed == Choice::Ok { crate::widgets::primary_button(&bar_ui, tr(label)) } else { egui::Button::new(tr(label)) }; - if bar_ui.add_sized([BUTTON_WIDTH, 28.0], button).clicked() { + for (label, pressed) in [("Apply", PreferenceAction::Apply), ("Cancel", PreferenceAction::Cancel), ("OK", PreferenceAction::Ok)] { + let button = if pressed == PreferenceAction::Ok { crate::widgets::primary_button(&bar_ui, tr(label)) } else { egui::Button::new(tr(label)) }; + if bar_ui.add_sized([BUTTON_WIDTH.min(bar.width() / 3.0 - 4.0), 28.0], button).clicked() { choice = Some(pressed); } } + ui.advance_cursor_after_rect(whole); }); @@ -98,16 +94,16 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { } // Closing the window is Cancel - let choice = if open { choice } else { Some(Choice::Cancel) }; + let choice = if open { choice } else { Some(PreferenceAction::Cancel) }; match choice { - Some(Choice::Apply) => app.ui.preferences.applied = Some(app.ui.prefs.clone()), - Some(Choice::Cancel) => { + Some(PreferenceAction::Apply) => app.ui.preferences.applied = Some(app.ui.prefs.clone()), + Some(PreferenceAction::Cancel) => { if let Some(applied) = app.ui.preferences.applied.take() { app.ui.prefs = applied; } close(app); } - Some(Choice::Ok) => close(app), + Some(PreferenceAction::Ok) => close(app), None => {} } app.apply_prefs(); diff --git a/crates/ui-egui/src/preference/preference_action.rs b/crates/ui-egui/src/preference/preference_action.rs new file mode 100644 index 00000000..212dffff --- /dev/null +++ b/crates/ui-egui/src/preference/preference_action.rs @@ -0,0 +1,7 @@ +/// A Preferences window action +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum PreferenceAction { + Ok, + Cancel, + Apply, +} diff --git a/crates/ui-egui/src/preferences/preferences_page.rs b/crates/ui-egui/src/preference/preferences_page.rs similarity index 100% rename from crates/ui-egui/src/preferences/preferences_page.rs rename to crates/ui-egui/src/preference/preferences_page.rs diff --git a/crates/ui-egui/src/preferences/preferences_state.rs b/crates/ui-egui/src/preference/preferences_state.rs similarity index 100% rename from crates/ui-egui/src/preferences/preferences_state.rs rename to crates/ui-egui/src/preference/preferences_state.rs diff --git a/crates/ui-egui/src/preferences/projects_page.rs b/crates/ui-egui/src/preference/projects_page.rs similarity index 73% rename from crates/ui-egui/src/preferences/projects_page.rs rename to crates/ui-egui/src/preference/projects_page.rs index 2c24a46d..d0818a31 100644 --- a/crates/ui-egui/src/preferences/projects_page.rs +++ b/crates/ui-egui/src/preference/projects_page.rs @@ -18,19 +18,23 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.label(egui::RichText::new(tr("Save Current State As Default, in the 3D view's Scene menu, saves the whole view here")).small().color(tokens.text_dim)); let current = ENVIRONMENTS.iter().find(|(id, _)| *id == view.environment).map_or(view.environment.clone(), |(_, label)| tr(label).to_string()); + let mut changed = false; crate::widgets::combo(ui, tr("Default environment"), current, |ui| { for (id, label) in ENVIRONMENTS { - ui.selectable_value(&mut view.environment, (*id).to_string(), tr(label)); + if ui.selectable_label(view.environment == *id, tr(label)).clicked() && view.environment != *id { + view.environment = (*id).to_owned(); + changed = true; + } } }); heading(ui, "Default lighting state"); - ui.checkbox(&mut view.ambient.enabled, tr("Ambient Light")); - ui.checkbox(&mut view.lights[0].enabled, tr("Point Light 1")); - ui.checkbox(&mut view.lights[1].enabled, tr("Point Light 2")); + changed |= ui.checkbox(&mut view.ambient.enabled, tr("Ambient Light")).changed(); + changed |= ui.checkbox(&mut view.lights[0].enabled, tr("Point Light 1")).changed(); + changed |= ui.checkbox(&mut view.lights[1].enabled, tr("Point Light 2")).changed(); // Only an actual change makes a saved default out of the built-in one - if view != prefs.default_view3d.clone().unwrap_or_default() { + if changed { prefs.default_view3d = Some(view); } diff --git a/crates/ui-egui/src/preferences/shortcuts_page.rs b/crates/ui-egui/src/preference/shortcuts_page.rs similarity index 81% rename from crates/ui-egui/src/preferences/shortcuts_page.rs rename to crates/ui-egui/src/preference/shortcuts_page.rs index fa244d01..5cb393a9 100644 --- a/crates/ui-egui/src/preferences/shortcuts_page.rs +++ b/crates/ui-egui/src/preference/shortcuts_page.rs @@ -1,6 +1,7 @@ //! Preferences ▸ Shortcuts: keys that add an atomic node or a graph item under the pointer -use egui::{Key, RichText, Ui}; +use craft_keymap::Key; +use egui::{RichText, Ui}; use egui_phosphor::regular as icon; use materialcraft_engine::node_library::LibraryItem; @@ -22,7 +23,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let any = !app.ui.prefs.node_shortcuts.is_empty(); if ui .add_enabled_ui(any, |ui| { - crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Remove every node creation shortcut"), false, 22.0) + crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Remove every node creation shortcut"), false, ICON_SIDE) }) .inner .clicked() @@ -44,21 +45,20 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.add_space(4.0); let (search, key_search, only_assigned) = (state.shortcut_search.to_lowercase(), state.shortcut_key_search.to_lowercase(), state.only_assigned); - let entries: Vec<_> = app - .session - .library_entries() - .into_iter() + let catalog = crate::library::entries(app, ui.ctx()); + let entries: Vec<_> = catalog + .iter() .filter(|entry| entry.missing.is_none() && crate::node_shortcuts::CATEGORIES.contains(&entry.category.as_str())) .filter(|entry| search.is_empty() || entry.label.to_lowercase().contains(&search)) .filter(|entry| { - let shortcut = app.ui.prefs.node_shortcuts.get(&entry.id).map(|text| text.to_lowercase()); - (!only_assigned || shortcut.is_some()) && (key_search.is_empty() || shortcut.is_some_and(|text| text.contains(&key_search))) + let shortcut = app.ui.prefs.node_shortcuts.get(&entry.id); + (!only_assigned || shortcut.is_some()) && (key_search.is_empty() || shortcut.is_some_and(|text| text.to_lowercase().contains(&key_search))) }) .collect(); capture(app, ui); egui::ScrollArea::vertical().auto_shrink([false, false]).show_rows(ui, ROW_HEIGHT, entries.len(), |ui, rows| { - for entry in &entries[rows] { + for entry in entries.get(rows).unwrap_or_default() { ui.horizontal(|ui| { ui.set_height(ROW_HEIGHT); let picture = match &entry.item { @@ -108,31 +108,32 @@ fn field(app: &mut MaterialCraftApp, ui: &mut Ui, entry: &str, label: &str) { fn capture(app: &mut MaterialCraftApp, ui: &mut Ui) { let Some(entry) = app.ui.preferences.capturing.clone() else { return }; - let pressed = ui.input(|input| { - input.events.iter().find_map(|event| match event { - egui::Event::Key { key, pressed: true, modifiers, .. } => Some((*modifiers, *key)), - _ => None, - }) - }); - let Some((modifiers, key)) = pressed else { return }; + let platform = craft_keymap::egui::platform(ui.ctx()); + let chord = ui.input(|input| input.events.iter().find_map(|event| crate::node_shortcuts::event_chord(event, platform))); + let Some(chord) = chord else { return }; app.ui.preferences.capturing = None; - if modifiers.is_none() && key == Key::Escape { + if chord.mods.is_none() && chord.key == Key::Escape { return; } - if modifiers.is_none() && matches!(key, Key::Backspace | Key::Delete) { + + if chord.mods.is_none() && matches!(chord.key, Key::Backspace | Key::Delete) { app.ui.prefs.node_shortcuts.remove(&entry); return; } - let Some(text) = crate::node_shortcuts::text(modifiers, key) else { return }; - - if let Some(command) = crate::node_shortcuts::taken_by(&text) { - app.toast(format!("{text} {} {command}", tr("is already the shortcut of")), true); + let text = crate::node_shortcuts::text(chord); + if let Some(command) = crate::node_shortcuts::taken_by(chord, platform) { + app.toast(format!("{text} {} {}", tr("is already the shortcut of"), tr(command)), true); return; } - // A shortcut adds one entry: giving it to this one takes it from any other - app.ui.prefs.node_shortcuts.retain(|_, assigned| *assigned != text); + // A shortcut belongs to at most one entry + app.ui.prefs.node_shortcuts.retain(|_, assigned| { + crate::menus::parse_shortcut(assigned).is_none_or(|mut assigned| { + assigned.mods = assigned.mods.effective(platform); + assigned != chord + }) + }); app.ui.prefs.node_shortcuts.insert(entry, text); } diff --git a/crates/ui-egui/src/preferences/view3d_page.rs b/crates/ui-egui/src/preference/view3d_page.rs similarity index 78% rename from crates/ui-egui/src/preferences/view3d_page.rs rename to crates/ui-egui/src/preference/view3d_page.rs index bc973d18..ba53e76d 100644 --- a/crates/ui-egui/src/preferences/view3d_page.rs +++ b/crates/ui-egui/src/preference/view3d_page.rs @@ -8,7 +8,7 @@ use crate::MaterialCraftApp; use crate::i18n::tr; /// The renderer's rays per pixel side, with the names the sample count list shows -const SAMPLE_COUNTS: [(u32, &str); 3] = [(1, "Low (1 spp)"), (2, "Medium (4 spp)"), (4, "High (16 spp)")]; +const SAMPLE_COUNTS: [(u32, &str); 4] = [(1, "Low (1 spp)"), (2, "Medium (4 spp)"), (3, "9 spp"), (4, "High (16 spp)")]; /// The furthest the 3D camera's target may move from the mesh, in mesh radii const MAX_PAN_LIMIT: f32 = 20.0; @@ -18,16 +18,18 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { heading(ui, "Misc"); let mut environment_shown = view.background == Background::Environment; - if ui.checkbox(&mut environment_shown, tr("Environment shown behind the mesh by default")).changed() { + let background_changed = ui.checkbox(&mut environment_shown, tr("Environment shown behind the mesh by default")).changed(); + if background_changed { view.background = if environment_shown { Background::Environment } else { Background::default() }; } let current = SAMPLE_COUNTS.iter().find(|(samples, _)| *samples == view.samples).map_or("", |(_, label)| label); + let original_samples = view.samples; crate::widgets::combo(ui, tr("Sample count"), tr(current), |ui| { for (samples, label) in SAMPLE_COUNTS { ui.selectable_value(&mut view.samples, samples, tr(label)); } }); - if view != prefs.default_view3d.clone().unwrap_or_default() { + if background_changed || view.samples != original_samples { prefs.default_view3d = Some(view); } diff --git a/crates/ui-egui/src/shell/modality.rs b/crates/ui-egui/src/shell/modality.rs index 0ce3e974..763293ed 100644 --- a/crates/ui-egui/src/shell/modality.rs +++ b/crates/ui-egui/src/shell/modality.rs @@ -88,14 +88,17 @@ fn open_blocker(app: &MaterialCraftApp) -> Option { if windows.unsaved.is_some() || app.awaiting_save.is_some() { return Some(Blocker::UnsavedPrompt); } + #[cfg(not(target_arch = "wasm32"))] if crate::updates_ui::blocks_input(app) { return Some(Blocker::Update); } + #[cfg(any(test, target_arch = "wasm32"))] if windows.package_save.is_some() { return Some(Blocker::Dialog); } + (app.expose_parameter_dialog.is_some() || windows.new_graph || windows.export diff --git a/crates/ui-egui/src/state/ui_state.rs b/crates/ui-egui/src/state/ui_state.rs index c1cf4a85..1a604b7b 100644 --- a/crates/ui-egui/src/state/ui_state.rs +++ b/crates/ui-egui/src/state/ui_state.rs @@ -101,10 +101,15 @@ impl Default for UiState { } impl UiState { + /// Preferences committed by Apply or OK, including while the window shows a draft + pub(crate) fn committed_prefs(&self) -> &Prefs { + self.preferences.applied.as_ref().unwrap_or(&self.prefs) + } + /// Remember `path` at the top of the recent list, keeping as many as the preferences ask for pub fn add_recent(&mut self, path: &str) { self.recent.retain(|recent| recent != path); self.recent.insert(0, path.to_string()); - self.recent.truncate(self.prefs.recent_limit.clamp(1, Prefs::MAX_RECENT)); + self.recent.truncate(self.committed_prefs().recent_limit.clamp(1, Prefs::MAX_RECENT)); } } diff --git a/crates/ui-egui/src/template_card.rs b/crates/ui-egui/src/template_card.rs index e5ebf6d9..008da410 100644 --- a/crates/ui-egui/src/template_card.rs +++ b/crates/ui-egui/src/template_card.rs @@ -1,7 +1,7 @@ //! The template cards of the New graph dialog and the home screen: a rendered preview, a name, //! the kind of graph, and an information button that says what the template holds -use egui::{Color32, RichText, Sense, Ui, vec2}; +use egui::{Color32, Sense, Ui, vec2}; use egui_phosphor::regular as icon; use materialcraft_engine::core::GraphKind; @@ -36,7 +36,7 @@ pub(crate) fn cards() -> Vec { fn description(id: &str) -> &'static str { match id { "empty" => "An empty material graph", - "pbr" => "Base color, normal, roughness, metallic, height and ambient occlusion outputs, ready to connect", + "pbr" => "Base color, normal, roughness, metallic, height and ambient occlusion outputs with inputs already connected", "atomics" => "A small graph of atomic nodes working together", FUNCTION_TEMPLATE => "An empty function graph: a value computed from function nodes", _ => "", @@ -58,7 +58,7 @@ pub(crate) fn show(ui: &mut Ui, card: &TemplateCard, chosen: bool, preview: Opti let fill = if chosen || response.hovered() { tokens.row_hover } else { tokens.row }; ui.painter().rect_filled(rect, 6.0, fill); - if chosen { + if chosen || response.has_focus() { ui.painter().rect_stroke(rect, 6.0, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Inside); } @@ -80,11 +80,15 @@ pub(crate) fn show(ui: &mut Ui, card: &TemplateCard, chosen: bool, preview: Opti let kind = tr(card.kind_label()); ui.painter().text(egui::pos2(rect.center().x, rect.bottom() - 18.0), egui::Align2::CENTER_CENTER, kind, egui::FontId::proportional(11.0), tokens.text_dim); - // The information button tells what the template holds let info = egui::Rect::from_center_size(rect.right_top() + vec2(-16.0, 16.0), vec2(18.0, 18.0)); - let info_response = ui.interact(info, response.id.with("info"), Sense::hover()); + let info_response = ui.interact(info, response.id.with("info"), Sense::click()); + crate::widgets::name(&info_response, egui::Role::Button, tr(card.description)); ui.painter().text(info.center(), egui::Align2::CENTER_CENTER, icon::INFO, egui::FontId::proportional(16.0), tokens.text_dim); - info_response.on_hover_text(RichText::new(tr(card.description))); + if info_response.has_focus() { + ui.painter().rect_stroke(info, 3.0, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + info_response.show_tooltip_text(tr(card.description)); + } + info_response.on_hover_text(tr(card.description)); response } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 6ca81c6b..a2505f35 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -32,6 +32,7 @@ fn render_templates() -> crate::thumbs::Previews { .filter_map(|(id, _)| { let mut s = materialcraft_engine::Session::new(materialcraft_engine::core::Package::new("t")); s.pkg.graphs.push(materialcraft_engine::samples::template(id, "t", 8).ok()?); + s.material_preview = materialcraft_engine::MaterialPreview::for_graph(&s.pkg, 0); s.preview_size = Some(256); s.cook(); let maps = materialcraft_render::Maps::from_usages(s.material_maps()); @@ -57,26 +58,28 @@ impl TemplatePreviews { let _ = tx.send(render_templates()); self.rx = Some(rx); } - if let Some(rx) = &self.rx - && let Ok(list) = rx.try_recv() - { - for (k, px) in list { - let img = egui::ColorImage::from_rgba_unmultiplied([PREVIEW as usize, PREVIEW as usize], &px); - self.tex.insert(k.clone(), ctx.load_texture(format!("tpl-{k}"), img, egui::TextureOptions::LINEAR)); + if let Some(rx) = &self.rx { + match rx.try_recv() { + Ok(previews) => { + for (template, pixels) in previews { + let image = egui::ColorImage::from_rgba_unmultiplied([PREVIEW as usize, PREVIEW as usize], &pixels); + let texture = ctx.load_texture(format!("tpl-{template}"), image, egui::TextureOptions::LINEAR); + self.tex.insert(template, texture); + } + self.rx = None; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => self.rx = None, + Err(std::sync::mpsc::TryRecvError::Empty) => {} } - self.rx = None; } + self.tex.get(id).map(TextureHandle::id) } } -thread_local! { - static TEMPLATES: std::cell::RefCell = std::cell::RefCell::new(TemplatePreviews::default()); -} - /// A template's rendered preview, once the background render has finished -pub(crate) fn template_preview(ctx: &egui::Context, id: &str) -> Option { - TEMPLATES.with(|previews| previews.borrow_mut().get(ctx, id)) +pub(crate) fn template_preview(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> Option { + (id != crate::template_card::FUNCTION_TEMPLATE).then(|| app.template_previews.get(ctx, id)).flatten() } pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { @@ -127,6 +130,12 @@ pub(crate) fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, .show(ctx, body); } +pub(crate) fn dialog_size(ctx: &egui::Context, preferred: egui::Vec2) -> egui::Vec2 { + // Leave room for the title bar and window margins inside the viewport + const FRAME_SPACE: egui::Vec2 = vec2(32.0, 72.0); + preferred.min((ctx.content_rect().size() - FRAME_SPACE).max(vec2(20.0, 40.0))) +} + fn about(app: &mut MaterialCraftApp, ctx: &egui::Context) { let mut open = true; modal(ctx, "about", tr("About MaterialCraft"), &mut open, vec2(400.0, 260.0), |ui| { @@ -401,26 +410,29 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> fn save_all(app: &mut MaterialCraftApp) { let Some(reply) = app.run("file.saveAll", json!({})) else { return }; - let saved: Vec = reply["saved"].as_array().into_iter().flatten().filter_map(|path| path.as_str().map(str::to_string)).collect(); - for path in &saved { + let saved = reply["saved"].as_array().into_iter().flatten(); + let saved_count = saved.clone().count(); + for path in saved.filter_map(Value::as_str) { app.ui.add_recent(path); } - let names = |key: &str| reply[key].as_array().into_iter().flatten().filter_map(|name| name.as_str()).collect::>().join(", "); - let without_file = names("withoutFile"); - let failed: Vec = reply["failed"] + let without_file: Vec<&str> = reply["withoutFile"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let failures: Vec = reply["failed"] .as_array() .into_iter() .flatten() .map(|failure| format!("{}: {}", failure["package"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default())) .collect(); - if !failed.is_empty() { - app.toast(format!("{} {}", tr("Not saved:"), failed.join("; ")), true); - } else if !without_file.is_empty() { - app.toast(format!("{} {} ({without_file})", saved.len(), tr("saved; use Save as for packages without a file")), false); - } else { - app.toast(format!("{} {}", saved.len(), tr("packages saved")), false); + let mut message = format!("{saved_count} {}", tr("packages saved")); + if !without_file.is_empty() { + message.push_str(&format!("\n{} {}", tr("Use Save as for:"), without_file.join(", "))); } + if !failures.is_empty() { + message.push_str(&format!("\n{} {}", tr("Not saved:"), failures.join("; "))); + } + + app.session.log(format!("Save all: {saved_count} saved, {} need Save as, {} failed", without_file.len(), failures.len())); + app.toast_only(message, !failures.is_empty()); } /// Whether File ▸ Save writes straight to the package's path (a package opened from a URL has none to write to) diff --git a/crates/ui-egui/src/windows.test.rs b/crates/ui-egui/src/windows.test.rs index a30223fd..61b3027e 100644 --- a/crates/ui-egui/src/windows.test.rs +++ b/crates/ui-egui/src/windows.test.rs @@ -150,3 +150,26 @@ fn project_dialogs_offer_separate_formats_and_import_filters_show_full_names() { assert!(bitmap.iter().any(|(label, _)| label == "JPEG - JFIF Compliant (*.jpg *.jif *.jpeg *.jpe)")); assert_eq!(resource_filters(true)[1].0, "Scalable Vector Graphics (*.svg)"); } + +#[test] +fn template_texture_handles_drop_with_their_application() { + let context = egui::Context::default(); + let manager = context.tex_manager(); + let initial_count = manager.read().num_allocated(); + + for name in ["empty", "pbr", "atomics"] { + let mut app = crate::MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); + let (sender, receiver) = std::sync::mpsc::channel(); + sender.send(vec![(name.to_string(), vec![255; (super::PREVIEW * super::PREVIEW * 4) as usize])]).unwrap(); + app.template_previews.rx = Some(receiver); + app.template_previews.started = true; + + let texture = super::template_preview(&mut app, &context, name).unwrap(); + + assert!(manager.read().meta(texture).is_some()); + assert_eq!(manager.read().num_allocated(), initial_count + 1); + drop(app); + assert!(manager.read().meta(texture).is_none()); + assert_eq!(manager.read().num_allocated(), initial_count); + } +} diff --git a/crates/ui-egui/tests/it/graph_properties.rs b/crates/ui-egui/tests/it/graph_properties.rs index ae07a745..61903aaf 100644 --- a/crates/ui-egui/tests/it/graph_properties.rs +++ b/crates/ui-egui/tests/it/graph_properties.rs @@ -184,6 +184,7 @@ fn opening_package_bytes_preserves_focused_graph_text() { #[test] fn undo_limit_is_editable_in_preferences_and_through_commands() { let mut harness = harness(false); + let initial_limit = harness.state().session.history_prefs.undo_limit; harness.state_mut().ui.windows.preferences = true; harness.run_steps(5); @@ -192,6 +193,11 @@ fn undo_limit_is_editable_in_preferences_and_through_commands() { harness.run_steps(4); assert_eq!(harness.state().ui.prefs.history.undo_limit, 500); + assert_eq!(harness.state().session.history_prefs.undo_limit, initial_limit); + + harness.get(By::new().role(egui::Role::Button).label("Apply")).click(); + harness.run_steps(4); + assert_eq!(harness.state().session.history_prefs.undo_limit, 500); let saved = serde_json::to_value(&harness.state().ui).unwrap(); let restored: UiState = serde_json::from_value(saved).unwrap(); diff --git a/crates/ui-egui/tests/it/menu_bar.rs b/crates/ui-egui/tests/it/menu_bar.rs index 8d6b8440..51dcd57a 100644 --- a/crates/ui-egui/tests/it/menu_bar.rs +++ b/crates/ui-egui/tests/it/menu_bar.rs @@ -30,16 +30,20 @@ fn choose(harness: &mut Harness<'static, MaterialCraftApp>, menu: &str, item: &s #[test] fn a_suspended_engine_cooks_nothing_until_it_is_resumed() { let mut harness = harness(); - for _ in 0..200 { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while std::time::Instant::now() < deadline { harness.step(); if !harness.state().cooker.busy() && !harness.state().session.dirty { break; } + std::thread::sleep(std::time::Duration::from_millis(5)); } + assert!(!harness.state().cooker.busy() && !harness.state().session.dirty, "the initial cook must settle"); choose(&mut harness, "Tools", "Suspend engine"); assert!(harness.state().cooker.suspended); + assert!(!menus::enabled(harness.state(), "graph.cook")); harness.state_mut().session.dirty = true; harness.run_steps(5); diff --git a/crates/ui-egui/tests/it/new_graph_dialog.rs b/crates/ui-egui/tests/it/new_graph_dialog.rs index 8365f86a..0d2a3a66 100644 --- a/crates/ui-egui/tests/it/new_graph_dialog.rs +++ b/crates/ui-egui/tests/it/new_graph_dialog.rs @@ -45,7 +45,8 @@ fn a_card_and_an_unlinked_size_make_the_graph_in_the_active_package() { assert!(!harness.state().ui.windows.new_graph); assert_eq!(session.open_packages().len(), packages); assert_eq!(session.graph().unwrap().size, [9, 11]); - assert!(!session.graph().unwrap().nodes.is_empty(), "the atomic sample's nodes"); + let sample = materialcraft_engine::samples::template("atomics", "Fixture", 9).unwrap(); + assert_eq!(session.graph().unwrap().nodes, sample.nodes); } #[test] diff --git a/crates/ui-egui/tests/it/preferences_window.rs b/crates/ui-egui/tests/it/preferences_window.rs index c196e6a0..2510f34b 100644 --- a/crates/ui-egui/tests/it/preferences_window.rs +++ b/crates/ui-egui/tests/it/preferences_window.rs @@ -58,6 +58,34 @@ fn cancel_returns_to_the_preferences_of_the_last_apply() { assert!(!harness.state().ui.windows.preferences); } +#[test] +fn draft_limits_preserve_recents_and_undo_until_applied() { + let mut harness = harness(); + for _ in 0..3 { + harness.state_mut().run("graph.node.add", serde_json::json!({"def": "uniform"})).unwrap(); + } + for path in ["first.sbs", "second.sbs", "third.sbs"] { + harness.state_mut().ui.add_recent(path); + } + let history = harness.state().session.history(); + open(&mut harness); + harness.state_mut().ui.prefs.history.undo_limit = 1; + harness.state_mut().ui.prefs.recent_limit = 1; + harness.run_steps(2); + click(&mut harness, Role::Button, "Cancel"); + + assert_eq!(harness.state().session.history(), history); + assert_eq!(harness.state().ui.recent.len(), 3); + + open(&mut harness); + harness.state_mut().ui.prefs.history.undo_limit = 1; + harness.state_mut().ui.prefs.recent_limit = 1; + click(&mut harness, Role::Button, "Apply"); + + assert_eq!(harness.state().session.history_prefs.undo_limit, 1); + assert_eq!(harness.state().ui.recent, ["third.sbs"]); +} + #[test] fn a_shortcut_is_captured_refused_when_taken_and_adds_its_node_over_the_graph() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index be68e07b..9a408883 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1672,7 +1672,18 @@ fn explorer_inputs_and_graph_drop_share_labels_and_material_assignment() { save(&mut harness, &directory, "graph-drop-target"); harness.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - settle(&mut harness, 45); + let has_expected_material = |harness: &Harness<'static, MaterialCraftApp>| { + harness + .state() + .view3d + .shown + .as_ref() + .is_some_and(|(_, _, frame)| frame.as_chunks::<4>().0.iter().filter(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 30).nth(100).is_some()) + }; + let deadline = std::time::Instant::now() + Duration::from_secs(6); + while !has_expected_material(&harness) && std::time::Instant::now() < deadline { + settle(&mut harness, 1); + } assert_eq!(harness.state().session.graph, graph, "dropping a graph must not open it"); assert_eq!(harness.state().session.view3d, camera, "dropping must not orbit the camera"); @@ -1682,9 +1693,7 @@ fn explorer_inputs_and_graph_drop_share_labels_and_material_assignment() { assert_eq!((binding.graph, binding.node), (0, NodeId(output))); - let frame = &harness.state().view3d.shown.as_ref().unwrap().2; - - assert!(frame.as_chunks::<4>().0.iter().filter(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 30).count() > 100); + assert!(has_expected_material(&harness), "the assigned material appears in the rendered frame"); save(&mut harness, &directory, "graph-dropped-on-material"); } @@ -1697,6 +1706,7 @@ fn library_cache_preferences() { settle(&mut h, 4); h.state_mut().ui.windows.preferences = true; settle(&mut h, 4); + // The dock has a Library tab too, so the page is chosen directly h.state_mut().ui.preferences.page = materialcraft_ui_egui::preferences::PreferencesPage::Library; settle(&mut h, 4); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cfc2a748..bb807ce2 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -89,7 +89,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `graph.function.variables` | `{id, target?: FunctionGraphTarget}` returns ordered suggestions matching a Get node's type and caller scope; typed custom names remain supported | | `session.environment` | `{timeSeconds?, uvTile?: [int, int], normalFormat?: int}` updates host evaluation values without modifying the package; `{}` reads them; defaults are zero and the normal-format code is passed through | | `graph.context` | `{physicalSize?: [x, y, z], pixelRatio?: 0\|1, tiling?: [horizontal, vertical]}` edits material-graph metadata with undo; `{}` reads it; reusable functions receive their caller's context | -| `file.new` | `{template?, name?, folder?, kind?, size?, height?, newPackage?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`). `size` is the width in pixels and `height` defaults to it (powers of two, 16 to 8192); `newPackage: true` creates the graph in a new untitled package | +| `file.new` | `{template?, name?, folder?, kind?, size?, height?, document?, newPackage?}`. Use `graph.templates` for the supported material templates. `size` is the width in pixels and `height` defaults to it (powers of two, 16 to 8192). `document` selects an open package. `newPackage: true` creates a new untitled package and cannot be combined with `document` or a nonempty `folder` | | `graph.node.edit` | `{}` resolves the selected FX-Map, processor or graph instance to `{kind, node, parameter?, graph?, document?, path?}`; use `ui.menu.invoke` to open its reference in the graph panel | | `graph.node.info` | `{id}` returns `{text}` describing a main-graph node without changing the document or node clipboard | | `graph.instance.add` | `{document, graph, function?: FunctionGraphTarget, at?, snapToGrid?}` adds a linked graph instance from an open package; requires a source output and rejects dependency cycles | @@ -386,7 +386,7 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k | `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?, linear?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package | | `file.open` | `{path}` opens `.sbs` XML or an independent `.mcraft` ZIP. Also opens a `.mcmat`'s source without a save path. Returns `warnings` for unsupported content; also in `session.inspect` as `package.warnings` | | `file.save` / `file.saveAs` / `file.saveCopyAs` | `{path?}` / `{path}` / `{path}`: `.sbs` writes XML and adjacent `resources/`; `.mcraft` writes a ZIP containing `package.sbs` and `resources/`. Unrecognized extensions get `.sbs` appended. Save Copy preserves the active path and modified state | -| `file.saveAll` | `{}` saves every modified package that has a file and returns `{saved, withoutFile, failed}`; packages without a file need `file.saveAs` | +| `file.saveAll` | Native only. `{}` saves every modified package that has a local file and returns `{saved, withoutFile, failed}`. `saved` lists paths, `withoutFile` lists packages that need `file.saveAs`, and `failed` lists `{package, error}` entries. The original package stays active | | `file.importBitmap` / `file.importVector` | `{path, name?, folder?}` imports a supported bitmap / SVG into Resources or a subfolder without adding a node. Unsaved imports and their original bytes participate in undo. `session.inspect` reports resource name, folder, file, byte count and missing status | | `graph.resource.add` | `{resource, document?, at?}` places a resource from the source document on the active material graph. Cross-document drops copy the asset; resource and node creation undo together | | `folder.properties` / `folder.attributes` | `{folder, document?}` reads Identifier/Description; add `identifier?` and/or `description?` to edit. Folder attributes persist as native SBS group identifiers and descriptions. The reserved root Resources identifier cannot change | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1d37f85a..b89fffcb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -23,7 +23,7 @@ Explorer now preserves native SBS folder hierarchies and provides package, folde menus for creation, copying, pasting, renaming, removal and package file actions. Moving items within a package and removing folder subtrees support undo; empty folders survive saves. -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-18 · **Change:** minor (UI and UX 70% → 75%: the reference application menus, Preferences pages, New graph dialog and home screen) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later) +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-18 · **Change:** minor (UI workflow update: menus, Preferences, New graph and Home) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later) **Overall: ≈ 69%** of a material artist's daily workflow works end to end (engine + UI + automation + tests), weighted by how much of the day each area carries. **Remaining: ≈ 83 Opus @@ -39,7 +39,7 @@ automation + tests), weighted by how much of the day each area carries. **Remain | 2D view | 5 | 90% | The reference layout: a toolbar above the image (background image, save, copy to the clipboard, output choice, UV overlay, Information and Histogram panels) and one below (channel menu with C/R/G/B/A keys, checkerboard, premultiplied alpha, sRGB or linear display, tiling across the whole view, physical size, exact fit, 1:1, stepped zoom with a zoom field, zoom lock); an Information panel with the pixel under the pointer and a color sampler (values at the image's bit depth and as floats, HSV, position); a Histogram panel with channel choice, bit depth, square-root scale, used range and a selectable range; size/format line | Color picker to parameters, floating the two panels, UV sets beyond the first | | 3D view | 10 | 75% | The reference layout: menus (Scene, Materials, Lights, Camera, Environment, Display, Renderer), a tool strip (scene browser, Select, Camera and Light tools, environment background, shadows, a displacement pop-up, the display helpers) and a bar with the channels, the color space and the scene; the material, lights, camera, environment and renderer in the Properties panel. Thirteen built-in meshes and OBJ, glTF and GLB meshes; nine shaders (the OpenPBR Surface model with coat, fuzz, thin film, transmission and subsurface, metallic/roughness with coated and subsurface variants, specular/glossiness, Blinn, Lambert, unlit and mesh information) with every parameter editable, switchable and replaced by a graph output; height by tessellation and displacement or parallax occlusion; an ambient light and two point lights with shadows; 4 procedural environments with rotation, exposure and an on/off switch; focal length, perspective or orthographic projection, viewpoints, framing, clip planes, a studio backdrop, a background color or the environment behind the mesh, and a render resolution of its own; wireframe, backface culling, grid, axes with a scale, bounding box, light helpers, vertex tangent space, scene statistics, resolution and frame rate; tiling, UV scale and physical size; alpha transparency and an alpha channel view; save and copy the render, export the tessellated mesh as OBJ, state files and a saved default state | A GPU renderer and a path tracer, a ground plane that catches shadows, several materials on one mesh, loading shader definitions, anisotropy, dispersion and thin-walled transmission in the renderer | | Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; an Export window (From graph, Batch at a chosen output size, and MaterialX and MCMAT tabs holding the #190 publishing options) writing the checked outputs (PNG, JPEG, TGA, BMP, WEBP, EXR, HDR; DDS listed for later; 8/16/32 bits; name pattern; sRGB, linear or raw per output); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources | -| UI and UX | 8 | 75% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, the reference File, Tools, Windows and Help menus (Save all, Cancel rendering, Suspend engine, main toolbar toggle, help and community links), New graph dialog with template cards, a category filter, width and height and a target package, export dialog, a paged Preferences window (General, Projects, Graph, 3D View, Library and Shortcuts pages with OK, Cancel and Apply; recent list length, invert zoom, numbered autosave copies, node search on Tab and on wire drop, outputs in the 3D view on open, node creation shortcuts), a Plugin Manager window (no plugin loading yet), shortcuts list, a home screen at startup (templates, recent packages, learn and community links), visual function editor, presets bar, accessible names on every widget, status bar | A plugin system, bakers, keymap editor for application commands, minimap, multi-graph tabs | +| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, the reference File, Tools, Windows and Help menus (Save all, Cancel rendering, Suspend engine, main toolbar toggle, help and community links), New graph dialog with template cards, a category filter, width and height and a target package, export dialog, a paged Preferences window (General, Projects, Graph, 3D View, Library and Shortcuts pages with OK, Cancel and Apply; recent list length, invert zoom, numbered autosave copies, node search on Tab and on wire drop, outputs in the 3D view on open, node creation shortcuts), a Plugin Manager window (no plugin loading yet), shortcuts list, a home screen at startup (templates, recent packages, learn and community links), visual function editor, presets bar, accessible names on every widget, status bar | A plugin system, bakers, keymap editor for application commands, minimap, multi-graph tabs | | Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run | | **Total** | **100** | **≈ 69%** | | | @@ -58,7 +58,7 @@ and is tested. | Date | Change | Summary | |---|---|---| -| 2026-11-18 | minor | UI and UX 70% → 75%: the reference File, Tools, Windows and Help menus, a paged Preferences window keeping every earlier setting, node creation shortcuts, the New graph dialog with sizes and a target package, a Plugin Manager window and a new home screen (#269); overall ≈ 69% → ≈ 69% | +| 2026-11-18 | minor | Updated File, Tools, Windows and Help menus, paged Preferences, node creation shortcuts, New graph with independent sizes and a target package, a Plugin Manager window and Home (#269). The historical scores remain as recorded | | 2026-11-15 | major | 3D view 55% → 75%: the reference menus, tool strip and properties; shaders with editable parameters, lights with shadows, camera lens and projection, render resolution, display helpers, state files (#221); overall ≈ 67% → ≈ 69% | | 2026-11-14 | minor | 2D view 80% → 90%: the reference toolbars, the Information and Histogram panels, display settings and stepped zoom (#221); overall unchanged at ≈ 67% | | 2026-11-02 | minor | ≈ 66% → ≈ 67%: `.mcmat` portable materials and TextureCraft interop (Files 70%) | From dea0b0f6e2304426932d0381ceeb6dfd2e5ecbd5 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 20:00:54 +0000 Subject: [PATCH 3/4] Auto: Protect recovery copies and honor committed UI state Apply preview size only after confirmation, and keep canceled preview values out of parameter capture. Resolve reserved graph names in fresh packages. Publish recovery archives atomically under a folder lock and prune complete copies with bounded memory. --- crates/engine/src/file_cmds.rs | 8 +- crates/engine/tests/it/open_documents.rs | 24 ++ crates/ui-egui/src/autosave_versions.rs | 272 ++++++++++++++++-- crates/ui-egui/src/cook.rs | 10 +- crates/ui-egui/src/cook_cancellation.test.rs | 48 ++++ crates/ui-egui/src/material_craft_app.rs | 5 +- .../ui-egui/src/property/parameter_control.rs | 2 +- crates/ui-egui/tests/it/preferences_window.rs | 24 ++ 8 files changed, 359 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d6768923..836b1ce2 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -95,7 +95,9 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result { crate::folder_path::require_graph_folder(folder)?; let base = crate::folder_path::name(&base)?; - let name = target.map_or_else(|| base.to_owned(), |package| crate::folder_path::unique(package, folder, base)); + let mut new_package = None; + let destination = target.unwrap_or_else(|| new_package.insert(Package::new("Untitled package"))); + let name = crate::folder_path::unique(destination, folder, base); let mut graph = if kind == materialcraft_core::GraphKind::Function { let mut graph = materialcraft_core::Graph::new(&name); @@ -112,8 +114,8 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result { // Validate the graph before changing the active package if let Some(document) = target_document { session.activate_document(document)?; - } else if in_new_package || !session.has_package() { - session.open_package(Package::new("Untitled package"), None)?; + } else if let Some(package) = new_package { + session.open_package(package, None)?; } session.edit("New graph", |session| { diff --git a/crates/engine/tests/it/open_documents.rs b/crates/engine/tests/it/open_documents.rs index e6ed353e..83438238 100644 --- a/crates/engine/tests/it/open_documents.rs +++ b/crates/engine/tests/it/open_documents.rs @@ -205,3 +205,27 @@ fn a_refused_graph_leaves_the_active_package_unchanged() { assert_eq!(session.document_id, destination); assert_eq!(session.graph().unwrap().name, "New graph"); } + +#[test] +fn a_new_package_resolves_reserved_graph_names() { + for new_package in [true, false] { + let mut session = Session::new(Package::new("Existing")); + let original = session.document_id; + if !new_package { + execute(&mut session, "package.close", &json!({})).unwrap(); + assert!(session.open_packages().is_empty()); + } + + let mut parameters = json!({"template": "empty", "name": "Resources"}); + if new_package { + parameters["newPackage"] = json!(true); + } + let reply = execute(&mut session, "file.new", ¶meters).unwrap(); + + assert_eq!(reply["name"], "Resources_1", "newPackage: {new_package}"); + assert_eq!(session.graph().unwrap().name, "Resources_1"); + assert!(session.pkg.folder_paths().contains("Resources")); + assert_ne!(session.document_id, original); + assert_eq!(session.open_packages().len(), if new_package { 2 } else { 1 }); + } +} diff --git a/crates/ui-egui/src/autosave_versions.rs b/crates/ui-egui/src/autosave_versions.rs index 9c0c4c58..54f20a31 100644 --- a/crates/ui-egui/src/autosave_versions.rs +++ b/crates/ui-egui/src/autosave_versions.rs @@ -1,6 +1,9 @@ //! Write numbered recovery copies and retain the newest copies for each document -use std::io::{self, ErrorKind}; +use std::collections::BTreeSet; +use std::ffi::OsString; +use std::fs::{File, OpenOptions}; +use std::io::{self, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use craft_atomic::{NewFilePermissions, WriteOptions}; @@ -9,7 +12,7 @@ use materialcraft_engine::formats::project::ProjectFiles; use sha2::{Digest, Sha256}; const EXTENSION: &str = ".mcraft"; -const MAX_WRITE_ATTEMPTS: usize = 8; +const LOCK_FILE: &str = ".recovery.lock"; /// Saved documents share history by normalized path; untitled documents use workspace-local IDs pub(crate) fn folder(root: &Path, path: Option<&str>, workspace: u64, document: u64) -> PathBuf { @@ -20,17 +23,25 @@ pub(crate) fn folder(root: &Path, path: Option<&str>, workspace: u64, document: root.join(key) } -fn copies(folder: &Path) -> io::Result> { +fn copies(folder: &Path) -> io::Result>> { Ok(std::fs::read_dir(folder)?.filter_map(|entry| { - let entry = entry.ok()?; + let entry = match entry { + Ok(entry) => entry, + Err(error) => return Some(Err(error)), + }; + let filename = entry.file_name(); let number = filename.to_str()?.strip_suffix(EXTENSION)?.parse().ok()?; - entry.file_type().ok()?.is_file().then_some((number, entry)) + match entry.file_type() { + Ok(kind) if kind.is_file() => Some(Ok((number, filename))), + Ok(_) => None, + Err(error) => Some(Err(error)), + } })) } fn next_path(folder: &Path) -> io::Result { - let mut version = copies(folder)?.map(|(number, _)| number).max().unwrap_or(0); + let mut version = copies(folder)?.try_fold(0, |latest, copy| copy.map(|(number, _)| latest.max(number)))?; loop { version = version.checked_add(1).ok_or_else(|| io::Error::other("autosave versions exhausted"))?; let path = folder.join(format!("{version}{EXTENSION}")); @@ -44,39 +55,135 @@ fn next_path(folder: &Path) -> io::Result { } } -fn prune(folder: &Path, keep: u32) -> io::Result<()> { - let mut copies: Vec<_> = copies(folder)?.collect(); - copies.sort_unstable_by_key(|(number, _)| *number); - let surplus = copies.len().saturating_sub(keep.max(1) as usize); +fn has_recovery_footer(path: &Path) -> io::Result { + // The recovery writer emits uncommented ZIP32 and ZIP64 end records + const ZIP_FOOTER_BYTES: usize = 22; + const ZIP64_FOOTER_BYTES: usize = 56; + const ZIP64_LOCATOR_BYTES: usize = 20; + let mut footer = [0; ZIP_FOOTER_BYTES]; + let mut file = File::open(path)?; + if file.metadata()?.len() < ZIP_FOOTER_BYTES as u64 { + return Ok(false); + } - for (_, entry) in copies.into_iter().take(surplus) { - match std::fs::remove_file(entry.path()) { - Err(error) if error.kind() == ErrorKind::NotFound => {} - result => result?, + let footer_offset = file.seek(SeekFrom::End(-(ZIP_FOOTER_BYTES as i64)))?; + file.read_exact(&mut footer)?; + if !footer.starts_with(b"PK\x05\x06") || !footer.ends_with(&[0, 0]) { + return Ok(false); + } + + let directory_size = u64::from(u32::from_le_bytes(footer[12..16].try_into().unwrap_or_default())); + let directory_offset = u64::from(u32::from_le_bytes(footer[16..20].try_into().unwrap_or_default())); + if directory_matches(&mut file, directory_offset, directory_size, footer_offset)? { + return Ok(true); + } + + let Some(zip64_offset) = footer_offset.checked_sub((ZIP64_FOOTER_BYTES + ZIP64_LOCATOR_BYTES) as u64) else { + return Ok(false); + }; + + let mut zip64_footer = [0; ZIP64_FOOTER_BYTES]; + let mut locator = [0; ZIP64_LOCATOR_BYTES]; + file.seek(SeekFrom::Start(zip64_offset))?; + file.read_exact(&mut zip64_footer)?; + file.read_exact(&mut locator)?; + if !zip64_footer.starts_with(b"PK\x06\x06") || !locator.starts_with(b"PK\x06\x07") || locator[8..16] != zip64_offset.to_le_bytes() { + return Ok(false); + } + + let directory_size = u64::from_le_bytes(zip64_footer[40..48].try_into().unwrap_or_default()); + let directory_offset = u64::from_le_bytes(zip64_footer[48..56].try_into().unwrap_or_default()); + directory_matches(&mut file, directory_offset, directory_size, zip64_offset) +} + +fn directory_matches(file: &mut File, offset: u64, size: u64, end: u64) -> io::Result { + // A nested ZIP in a torn copy can have a footer without pointing at the outer directory + let mut signature = [0; 4]; + if size < signature.len() as u64 || offset.checked_add(size) != Some(end) { + return Ok(false); + } + + file.seek(SeekFrom::Start(offset))?; + file.read_exact(&mut signature)?; + Ok(&signature == b"PK\x01\x02") +} + +fn prune(folder: &Path, keep: u32, mut remove: impl FnMut(&Path) -> io::Result<()>) -> io::Result<()> { + let keep = keep.clamp(1, crate::state::Prefs::MAX_AUTOSAVE_VERSIONS) as usize; + let mut newest = BTreeSet::new(); + + // Retain only the newest candidates before deleting anything + for copy in copies(folder)? { + let copy = copy?; + if newest.len() == keep && newest.first().is_some_and(|oldest| © < oldest) { + continue; + } + + if has_recovery_footer(&folder.join(©.1))? { + newest.insert(copy); + if newest.len() > keep { + newest.pop_first(); + } } } - Ok(()) + + if newest.len() < keep { + return Ok(()); + } + + let Some(oldest) = newest.into_iter().next() else { + return Ok(()); + }; + + // A second scan lets even an oversized folder be pruned with bounded storage + let mut first_error = None; + for copy in copies(folder)? { + let result = copy.and_then(|copy| { + if copy < oldest { + let path = folder.join(copy.1); + if has_recovery_footer(&path)? { + return remove(&path); + } + } + + Ok(()) + }); + if let Err(error) = result + && error.kind() != ErrorKind::NotFound + { + first_error.get_or_insert(error); + } + } + + first_error.map_or(Ok(()), Err) } pub(crate) fn save(folder: &Path, package: &Package, keep: u32) -> io::Result<()> { - std::fs::create_dir_all(folder)?; let files = ProjectFiles::build(package, "autosave.mcraft", true).map_err(io::Error::other)?; - let options = WriteOptions::default().with_new_file_permissions(NewFilePermissions::Private); + save_with(folder, keep, |file| files.write_zip(file).map(|_| ()).map_err(io::Error::other)) +} - for _ in 0..MAX_WRITE_ATTEMPTS { - let path = next_path(folder)?; - match options.write_new_with(&path, |file| files.write_zip(file).map(|_| ()).map_err(io::Error::other)) { - Ok(()) => return prune(folder, keep), - Err(error) if error.kind() == ErrorKind::AlreadyExists => continue, - Err(error) => return Err(error), - } - } - Err(io::Error::other("autosave version could not be reserved")) +fn save_with(folder: &Path, keep: u32, write: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { + std::fs::create_dir_all(folder)?; + + // Keep the lock file in place so concurrent processes lock the same file + let lock = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(folder.join(LOCK_FILE))?; + lock.lock()?; + + let path = next_path(folder)?; + + // Publish by rename so the numbered file is never visible during copying + let options = WriteOptions::default().with_new_file_permissions(NewFilePermissions::Private); + options.atomic_write_with(&path, write)?; + prune(folder, keep, |path| std::fs::remove_file(path)) } #[cfg(test)] mod tests { use super::*; + use std::io::Write; + use std::process::Command; + use std::time::{Duration, Instant}; #[test] fn retention_keeps_distinct_packages_and_ignores_directories() { @@ -138,12 +245,121 @@ mod tests { }); let mut names = Vec::new(); - for (_, entry) in copies(folder).unwrap() { - let archive = std::fs::read(entry.path()).unwrap(); + for copy in copies(folder).unwrap() { + let (_, filename) = copy.unwrap(); + let archive = std::fs::read(folder.join(filename)).unwrap(); names.push(materialcraft_engine::formats::project::read(&archive, "autosave.mcraft").unwrap().pkg.graphs[0].name.clone()); } names.sort_unstable(); assert_eq!(names, ["Graph 0", "Graph 1", "Graph 2", "Graph 3"]); } + + #[test] + fn a_truncated_legacy_copy_does_not_displace_a_complete_version() { + let root = tempfile::tempdir().unwrap(); + let package = Package::new("Wood"); + save(root.path(), &package, 2).unwrap(); + let first = root.path().join("1.mcraft"); + let archive = std::fs::read(&first).unwrap(); + let incomplete = root.path().join("2.mcraft"); + std::fs::write(&incomplete, &archive[..archive.len() / 2]).unwrap(); + let embedded = root.path().join("3.mcraft"); + std::fs::write(&embedded, [&archive[..archive.len() / 2], &archive].concat()).unwrap(); + + save(root.path(), &package, 2).unwrap(); + + assert_eq!(std::fs::read(first).unwrap(), archive); + assert!(incomplete.is_file()); + assert!(embedded.is_file()); + let latest = std::fs::read(root.path().join("4.mcraft")).unwrap(); + assert!(materialcraft_engine::formats::project::read(&latest, "autosave.mcraft").is_ok()); + } + + #[test] + fn zip64_end_records_are_accepted() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("1.mcraft"); + let mut writer = zip::ZipWriter::new(File::create(&path).unwrap()); + writer.set_zip64_comment(Some("")); + writer.start_file("package.sbs", zip::write::SimpleFileOptions::default()).unwrap(); + writer.finish().unwrap(); + + assert!(has_recovery_footer(&path).unwrap()); + } + + #[test] + fn pruning_continues_after_a_deletion_error() { + let root = tempfile::tempdir().unwrap(); + let package = Package::new("Wood"); + for _ in 0..4 { + save(root.path(), &package, 4).unwrap(); + } + + let error = prune(root.path(), 1, |path| { + if path.ends_with("1.mcraft") { + return Err(io::Error::new(ErrorKind::PermissionDenied, "injected deletion denial")); + } + + std::fs::remove_file(path) + }) + .unwrap_err(); + + assert_eq!(error.kind(), ErrorKind::PermissionDenied); + assert!(root.path().join("1.mcraft").is_file()); + assert!(!root.path().join("2.mcraft").exists()); + assert!(!root.path().join("3.mcraft").exists()); + assert!(root.path().join("4.mcraft").is_file()); + } + + #[test] + fn overlapping_processes_keep_one_complete_copy_when_a_write_fails() { + const CHILD_FOLDER: &str = "MATERIALCRAFT_AUTOSAVE_TEST_CHILD_FOLDER"; + const LOCK_CHECKED: &str = "lock-checked"; + const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5); + if let Some(folder) = std::env::var_os(CHILD_FOLDER) { + let folder = PathBuf::from(folder); + let lock = OpenOptions::new().read(true).write(true).open(folder.join(LOCK_FILE)).unwrap(); + assert!(matches!(lock.try_lock(), Err(std::fs::TryLockError::WouldBlock))); + std::fs::write(folder.join(LOCK_CHECKED), []).unwrap(); + save(&folder, &Package::new("New"), 1).unwrap(); + return; + } + + let root = tempfile::tempdir().unwrap(); + let folder = root.path(); + save(folder, &Package::new("Original"), 1).unwrap(); + let first = folder.join("1.mcraft"); + let second = folder.join("2.mcraft"); + let mut child = None; + + let result = save_with(folder, 1, |file| { + file.write_all(b"partial archive")?; + let process = child.insert( + Command::new(std::env::current_exe()?) + .args(["--exact", "autosave_versions::tests::overlapping_processes_keep_one_complete_copy_when_a_write_fails"]) + .env(CHILD_FOLDER, folder) + .spawn()?, + ); + let deadline = Instant::now() + HANDSHAKE_TIMEOUT; + while !folder.join(LOCK_CHECKED).exists() { + if process.try_wait()?.is_some() || Instant::now() >= deadline { + return Err(io::Error::other("overlapping writer did not confirm lock contention")); + } + + std::thread::sleep(Duration::from_millis(5)); + } + + assert!(first.is_file()); + assert!(!second.exists()); + Err(io::Error::new(ErrorKind::WriteZero, "injected interrupted write")) + }); + + let child_status = child.unwrap().wait().unwrap(); + assert_eq!(result.unwrap_err().kind(), ErrorKind::WriteZero); + assert!(child_status.success()); + assert!(!first.exists()); + let archive = std::fs::read(second).unwrap(); + assert_eq!(materialcraft_engine::formats::project::read(&archive, "autosave.mcraft").unwrap().pkg.name, "New"); + } } diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index 852a3fd6..edea4311 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -65,6 +65,8 @@ pub struct Cooker { pub suspended: bool, /// Tools ▸ Cancel rendering stopped the running cook: it does not start again until the next edit stopped_by_user: bool, + /// The retained preview cannot supply parameter values at this epoch + cancelled_preview_epoch: Option, } impl Cooker { @@ -81,6 +83,10 @@ impl Cooker { } } +pub(crate) fn preview_ready(app: &MaterialCraftApp) -> bool { + !app.session.dirty && !app.cooker.busy() && app.cooker.cancelled_preview_epoch != Some(app.session.cook_epoch) +} + /// Tools ▸ Cancel rendering: stop the running cook; the next edit cooks again pub fn cancel(app: &mut MaterialCraftApp) { if !app.cooker.busy() { @@ -89,6 +95,7 @@ pub fn cancel(app: &mut MaterialCraftApp) { app.cooker.stop(); app.cooker.stopped_by_user = true; + app.cooker.cancelled_preview_epoch = Some(app.session.cook_epoch); app.session.dirty = false; } @@ -124,8 +131,9 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { } } Ok(c) => { - if !app.cooker.suspended && !app.session.dirty && app.cooker.epoch == app.session.cook_epoch { + if !app.cooker.suspended && !app.session.dirty && app.cooker.epoch == app.session.cook_epoch && c.graph == app.session.graph { app.session.accept_preview(c); + app.cooker.cancelled_preview_epoch = None; } } Err(msg) if !app.cooker.suspended && !app.session.dirty && app.cooker.epoch == app.session.cook_epoch => report_failure(app, msg), diff --git a/crates/ui-egui/src/cook_cancellation.test.rs b/crates/ui-egui/src/cook_cancellation.test.rs index 906c5ed4..736655cc 100644 --- a/crates/ui-egui/src/cook_cancellation.test.rs +++ b/crates/ui-egui/src/cook_cancellation.test.rs @@ -68,3 +68,51 @@ fn cancelling_without_a_worker_keeps_pending_work() { assert!(app.session.dirty); } + +#[test] +fn cancelled_preview_is_unavailable_for_parameter_capture_until_recooked() { + use materialcraft_engine::core::{FunctionGraph, NodeId, Value}; + use serde_json::json; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); + app.session.preview_size = Some(64); + let owner = NodeId(app.run("graph.node.add", json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap()); + let set_intensity = |app: &mut MaterialCraftApp, value| { + let function = FunctionGraph::constant(Value::Float(value)); + app.run("graph.node.function", json!({"id": owner, "param": "intensity", "function": function})).unwrap(); + }; + let intensity = |app: &MaterialCraftApp| app.session.cooked.nodes[&owner].parameters["intensity"].clone(); + let ctx = egui::Context::default(); + set_intensity(&mut app, 0.2); + app.session.cook(); + assert!(preview_ready(&app)); + assert_eq!(intensity(&app), Value::Float(0.2)); + + set_intensity(&mut app, 0.8); + let (sender, receiver) = mpsc::channel(); + app.cooker.rx = Some(receiver); + app.cooker.epoch = app.session.cook_epoch; + app.session.dirty = false; + cancel(&mut app); + drop(sender); + drive(&mut app, &ctx); + + assert_eq!(intensity(&app), Value::Float(0.2)); + assert!(!app.session.dirty && !app.cooker.busy()); + assert!(!preview_ready(&app), "the retained value must not be offered for capture"); + + drive(&mut app, &ctx); + assert!(!app.cooker.busy()); + app.session.dirty = true; + drive(&mut app, &ctx); + for _ in 0..2000 { + if !app.cooker.busy() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + drive(&mut app, &ctx); + } + + assert!(preview_ready(&app)); + assert_eq!(intensity(&app), Value::Float(0.8)); +} diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 28bba14c..5c83ab6a 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -186,7 +186,10 @@ impl MaterialCraftApp { self.session.default_view3d = default_view; } - let preview_size = if self.ui.prefs.preview_size == 0 { None } else { Some(self.ui.prefs.preview_size.clamp(64, 8192)) }; + let preview_size = match self.ui.committed_prefs().preview_size { + 0 => None, + size => Some(size.clamp(64, 8192)), + }; if self.session.preview_size != preview_size { let _ = materialcraft_engine::execute(&mut self.session, "view.previewSize", &serde_json::json!({"size": preview_size.unwrap_or(0)})); } diff --git a/crates/ui-egui/src/property/parameter_control.rs b/crates/ui-egui/src/property/parameter_control.rs index a31ddc45..2efbb658 100644 --- a/crates/ui-egui/src/property/parameter_control.rs +++ b/crates/ui-egui/src/property/parameter_control.rs @@ -25,7 +25,7 @@ pub(super) fn show( .filter(|identifier| app.session.graph().is_ok_and(|graph| graph.exposed.iter().any(|input| input.id == *identifier))) .or_else(|| base.is_none().then(|| node.bindings.get(&descriptor.id).map(String::as_str)).flatten()); let driven = function.is_some() || bound.is_some(); - let evaluated = (!app.session.dirty && !app.cooker.busy()) + let evaluated = crate::cook::preview_ready(app) .then(|| app.session.cooked.nodes.get(&node.id)) .flatten() .filter(|result| result.error.is_none()) diff --git a/crates/ui-egui/tests/it/preferences_window.rs b/crates/ui-egui/tests/it/preferences_window.rs index 2510f34b..96362811 100644 --- a/crates/ui-egui/tests/it/preferences_window.rs +++ b/crates/ui-egui/tests/it/preferences_window.rs @@ -86,6 +86,30 @@ fn draft_limits_preserve_recents_and_undo_until_applied() { assert_eq!(harness.state().ui.recent, ["third.sbs"]); } +#[test] +fn draft_preview_size_reaches_the_session_only_on_apply_or_ok() { + let mut harness = harness(); + let initial = harness.state().session.preview_size; + open(&mut harness); + harness.state_mut().ui.prefs.preview_size = 64; + harness.run_steps(2); + + assert_eq!(harness.state().session.preview_size, initial); + click(&mut harness, Role::Button, "Cancel"); + assert_eq!(harness.state().session.preview_size, initial); + + open(&mut harness); + harness.state_mut().ui.prefs.preview_size = 1; + click(&mut harness, Role::Button, "Apply"); + assert_eq!(harness.state().session.preview_size, Some(64)); + + harness.state_mut().ui.prefs.preview_size = 0; + harness.run_steps(2); + assert_eq!(harness.state().session.preview_size, Some(64)); + click(&mut harness, Role::Button, "OK"); + assert_eq!(harness.state().session.preview_size, None); +} + #[test] fn a_shortcut_is_captured_refused_when_taken_and_adds_its_node_over_the_graph() { let mut harness = harness(); From 0a2a2e294ea65d1804591e3aa09132fd4f2d037d Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 20:52:59 +0000 Subject: [PATCH 4/4] Auto: Dispose of shortcut test output and exercise modifier changes Consume the headless egui frame with drop_without_applying_deltas so its initial font texture can be discarded safely in debug builds. Send an explicit Alt transition between key events so the existing Levels assertion detects a matcher that uses the frame's final modifiers. Preserve the repeat assertion. --- crates/ui-egui/src/node_shortcuts.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/node_shortcuts.rs b/crates/ui-egui/src/node_shortcuts.rs index 6ee6bff6..f597ac83 100644 --- a/crates/ui-egui/src/node_shortcuts.rs +++ b/crates/ui-egui/src/node_shortcuts.rs @@ -78,12 +78,15 @@ mod tests { let event = |modifiers, repeat| Event::Key { key, physical_key: None, pressed: true, repeat, modifiers }; let plain = event(egui::Modifiers::NONE, false); let alt = event(egui::Modifiers::ALT, false); - let raw = egui::RawInput { events: vec![plain, alt], ..Default::default() }; + let raw = egui::RawInput { events: vec![plain, Event::ModifiersChanged(egui::Modifiers::ALT), alt], ..Default::default() }; let shortcuts = [("node:blur".to_owned(), "Alt+B".to_owned()), ("node:levels".to_owned(), "B".to_owned())].into(); - let _ = egui::Context::default().run_ui(raw, |ui| { - assert_eq!(ui.input(|input| pressed(&shortcuts, input, Platform::Windows)), Some("node:levels")); - }); + egui::Context::default() + .run_ui(raw, |ui| { + assert_eq!(ui.input(|input| pressed(&shortcuts, input, Platform::Windows)), Some("node:levels")); + }) + .drop_without_applying_deltas(); + assert!(event_chord(&event(egui::Modifiers::ALT, true), Platform::Windows).is_none()); } }