mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-25 08:50:58 +01:00
Auto: Integrate main and reduce archive and export preview allocations
Preserve both branches’ Arabic translations and parity updates. Borrow the active package for .mcraft saves and enumerate export outputs lazily for the filename preview. Keep full row collections where selection or drawing needs multiple passes. Synchronize the linked-graph and material-drop snapshots with recooking and pointer release.
This commit is contained in:
commit
562a2c0fb8
71 files changed
+3093
-415
No files matched your search
Generated
+1
@@ -2905,6 +2905,7 @@ name = "materialcraft-formats"
|
||||
version = "0.4.1"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-atomic",
|
||||
"craft-fonts-build",
|
||||
"craft-mcmat",
|
||||
"craft-mesh",
|
||||
|
||||
@@ -90,6 +90,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
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"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), document? (open package id), newPackage?} adds a graph and opens it",
|
||||
always,
|
||||
new_graph
|
||||
),
|
||||
@@ -63,32 +63,61 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
"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"
|
||||
} 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);
|
||||
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"));
|
||||
}
|
||||
|
||||
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 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 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);
|
||||
graph.function = Some(materialcraft_core::FunctionGraph::default());
|
||||
graph
|
||||
} else {
|
||||
template(template_id, &name, log2)?
|
||||
template(template_id, &name, width_log2)?
|
||||
};
|
||||
graph.folder = folder.into();
|
||||
if !session.has_package() {
|
||||
session.open_package(Package::new("Untitled package"), None)?;
|
||||
if kind == materialcraft_core::GraphKind::Material {
|
||||
graph.size = [width_log2, height_log2];
|
||||
}
|
||||
graph.folder = folder.into();
|
||||
|
||||
// Validate the graph before changing the active package
|
||||
if let Some(document) = target_document {
|
||||
session.activate_document(document)?;
|
||||
} else if let Some(package) = new_package {
|
||||
session.open_package(package, None)?;
|
||||
}
|
||||
|
||||
session.edit("New graph", |session| {
|
||||
session.pkg.graphs.push(graph);
|
||||
session.graph = session.pkg.graphs.len() - 1;
|
||||
@@ -108,25 +137,28 @@ fn new_package(s: &mut Session, p: &J) -> Result<J> {
|
||||
}
|
||||
|
||||
/// Replace the active document explicitly, resetting its history and views
|
||||
pub fn replace_package(s: &mut Session, pkg: Package, path: Option<String>) {
|
||||
pub fn replace_package(session: &mut Session, package: Package, path: Option<String>) {
|
||||
// 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 {
|
||||
@@ -238,25 +270,26 @@ fn package_for_save(session: &Session, path: Option<&str>) -> Package {
|
||||
}
|
||||
|
||||
pub fn save_files_at(session: &Session, path: &str) -> Result<materialcraft_formats::project::ProjectFiles> {
|
||||
session.package(session.document_id)?;
|
||||
let archive = is_mcraft(path);
|
||||
let package = if archive { session.pkg.clone() } else { package_for_save(session, Some(path)) };
|
||||
let active_package = session.package(session.document_id)?;
|
||||
let filename = std::path::Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or("package.sbs");
|
||||
if is_mcraft(path) {
|
||||
return Ok(materialcraft_formats::project::ProjectFiles::build(active_package, filename, true)?);
|
||||
}
|
||||
|
||||
let package = package_for_save(session, Some(path));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if !archive && materialcraft_formats::sbs::library::contains_file(std::path::Path::new(path)) {
|
||||
if materialcraft_formats::sbs::library::contains_file(std::path::Path::new(path)) {
|
||||
return Ok(materialcraft_formats::project::ProjectFiles::build_linked(&package, filename)?);
|
||||
}
|
||||
|
||||
Ok(materialcraft_formats::project::ProjectFiles::build(&package, filename, archive)?)
|
||||
Ok(materialcraft_formats::project::ProjectFiles::build(&package, filename, false)?)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn write_package_at(session: &Session, path: &str) -> Result<usize> {
|
||||
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())
|
||||
@@ -301,7 +334,14 @@ fn save(s: &mut Session, p: &J) -> Result<J> {
|
||||
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<J> {
|
||||
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"));
|
||||
}
|
||||
@@ -314,7 +354,6 @@ fn save(s: &mut Session, p: &J) -> Result<J> {
|
||||
s.path = Some(path.clone());
|
||||
s.refresh_links();
|
||||
s.modified = false;
|
||||
s.log(format!("Saved {path}"));
|
||||
Ok(json!({"path": path, "bytes": bytes}))
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String>, view3d: View3d) -> Self {
|
||||
pub(crate) fn new(id: u64, pkg: Package, path: Option<String>, 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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! File ▸ Save all: write every open package that has unsaved edits to its own file
|
||||
|
||||
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<CommandSpec> {
|
||||
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
|
||||
)]
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
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<Value> {
|
||||
// Publishing the active edit can mark linked packages modified
|
||||
session.end_group();
|
||||
let active = session.document_id;
|
||||
let modified: Vec<(u64, String, Option<String>)> = 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 (document, name, path) in modified {
|
||||
// A package from a library alias or with no file yet needs a name chosen in Save as
|
||||
let Some(path) = path.filter(|path| !path.contains("://")) else {
|
||||
without_file.push(name);
|
||||
continue;
|
||||
};
|
||||
|
||||
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()})),
|
||||
}
|
||||
}
|
||||
|
||||
if session.document_id != active {
|
||||
session.activate_document(active)?;
|
||||
}
|
||||
|
||||
Ok(json!({"saved": saved, "withoutFile": without_file, "failed": failed}))
|
||||
}
|
||||
@@ -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<View3d>,
|
||||
/// 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<usize>,
|
||||
pub(crate) material_cooked: std::collections::BTreeMap<usize, Cooked>,
|
||||
@@ -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(),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -270,3 +270,54 @@ 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));
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
@@ -134,3 +134,98 @@ 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(&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"));
|
||||
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!([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");
|
||||
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);
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
|
||||
#[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 });
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
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<usize> {
|
||||
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<W: Write + Seek>(&self, destination: W) -> Result<W> {
|
||||
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]> {
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Write numbered recovery copies and retain the newest copies for each document
|
||||
|
||||
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};
|
||||
use materialcraft_engine::core::Package;
|
||||
use materialcraft_engine::formats::project::ProjectFiles;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const EXTENSION: &str = ".mcraft";
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
fn copies(folder: &Path) -> io::Result<impl Iterator<Item = io::Result<(u64, OsString)>>> {
|
||||
Ok(std::fs::read_dir(folder)?.filter_map(|entry| {
|
||||
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()?;
|
||||
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<PathBuf> {
|
||||
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}"));
|
||||
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_recovery_footer(path: &Path) -> io::Result<bool> {
|
||||
// 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);
|
||||
}
|
||||
|
||||
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<bool> {
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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<()> {
|
||||
let files = ProjectFiles::build(package, "autosave.mcraft", true).map_err(io::Error::other)?;
|
||||
save_with(folder, keep, |file| files.write_zip(file).map(|_| ()).map_err(io::Error::other))
|
||||
}
|
||||
|
||||
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() {
|
||||
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 {
|
||||
save(&first, &wood, 2).unwrap();
|
||||
}
|
||||
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!(!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());
|
||||
}
|
||||
|
||||
#[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 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");
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+53
-11
@@ -61,12 +61,52 @@ pub struct Cooker {
|
||||
pub started: Option<f64>,
|
||||
/// `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,
|
||||
/// The retained preview cannot supply parameter values at this epoch
|
||||
cancelled_preview_epoch: Option<u64>,
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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() {
|
||||
return;
|
||||
}
|
||||
|
||||
app.cooker.stop();
|
||||
app.cooker.stopped_by_user = true;
|
||||
app.cooker.cancelled_preview_epoch = Some(app.session.cook_epoch);
|
||||
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
|
||||
@@ -74,6 +114,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"))]
|
||||
@@ -81,29 +122,28 @@ 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
|
||||
_ 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.session.dirty = true;
|
||||
}
|
||||
}
|
||||
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 && c.graph == app.session.graph {
|
||||
app.session.accept_preview(c);
|
||||
app.cooker.cancelled_preview_epoch = None;
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -112,9 +152,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"))]
|
||||
@@ -124,7 +165,8 @@ 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();
|
||||
}
|
||||
|
||||
@@ -43,3 +43,76 @@ 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);
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
@@ -247,7 +247,7 @@ pub(super) fn path_field(ui: &mut Ui, path: &mut String, width: f32) -> bool {
|
||||
/// The file name the first checked output of `graph` is written to
|
||||
fn preview_file(settings: &ExportSettings, graph: &Graph) -> Option<String> {
|
||||
let graph_path = graph.sbs_path();
|
||||
let output = outputs::listed(graph).into_iter().find(|output| settings.includes(&graph_path, &output.identifier))?;
|
||||
let output = outputs::listed(graph).find(|output| settings.includes(&graph_path, &output.identifier))?;
|
||||
let name = materialcraft_engine::formats::output_name(&settings.pattern, &graph.name, &output.identifier, output.usage);
|
||||
Some(format!("{name}.{}", settings.format))
|
||||
}
|
||||
|
||||
@@ -20,13 +20,12 @@ pub struct ListedOutput {
|
||||
}
|
||||
|
||||
/// `graph`'s output nodes in node order
|
||||
pub fn listed(graph: &Graph) -> Vec<ListedOutput> {
|
||||
pub fn listed(graph: &Graph) -> impl Iterator<Item = ListedOutput> {
|
||||
graph
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|node| node.def == "output")
|
||||
.map(|node| ListedOutput { identifier: materialcraft_engine::eval::identifier(node), usage: materialcraft_engine::eval::output_usage(node) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl ExportSettings {
|
||||
@@ -55,7 +54,7 @@ impl ExportSettings {
|
||||
/// The `file.export` `outputs` and `colorSpaces` for `graph`; `None` when none of its outputs is checked
|
||||
pub fn selection(&self, graph: &Graph) -> Option<(Value, Value)> {
|
||||
let graph_path = graph.sbs_path();
|
||||
let outputs = listed(graph);
|
||||
let outputs: Vec<_> = listed(graph).collect();
|
||||
let included: Vec<&ListedOutput> = outputs.iter().filter(|output| self.includes(&graph_path, &output.identifier)).collect();
|
||||
if included.is_empty() {
|
||||
return None;
|
||||
@@ -85,7 +84,7 @@ pub fn tree(ui: &mut Ui, settings: &mut ExportSettings, graphs: &[&Graph]) {
|
||||
egui::ScrollArea::vertical().id_salt("export-outputs").max_height(240.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
for graph in graphs {
|
||||
let graph_path = graph.sbs_path();
|
||||
let outputs = listed(graph);
|
||||
let outputs: Vec<_> = listed(graph).collect();
|
||||
let included = outputs.iter().filter(|output| settings.includes(&graph_path, &output.identifier)).count();
|
||||
let id = ui.make_persistent_id(("export-graph", &graph_path));
|
||||
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true)
|
||||
|
||||
@@ -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))));
|
||||
}
|
||||
_ => {}
|
||||
@@ -186,10 +186,14 @@ 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));
|
||||
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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -31,7 +31,11 @@ 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. `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;
|
||||
@@ -39,10 +43,10 @@ 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 = 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
@@ -271,16 +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));
|
||||
let tab = !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 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 {
|
||||
open_search(app, &context, camera.to_graph(position), None);
|
||||
}
|
||||
|
||||
if GraphCamera::frame_key(ui, rect) {
|
||||
let selected = !app.session.selection.is_empty();
|
||||
frame(app, rect, selected);
|
||||
|
||||
@@ -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://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/"),
|
||||
("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://github.com/storytold/materialcraft/releases"),
|
||||
];
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//! 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;
|
||||
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")]),
|
||||
("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 size = crate::windows::dialog_size(ctx, WINDOW_SIZE);
|
||||
let mut open = true;
|
||||
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.min(size.x * 0.4), whole.bottom()));
|
||||
let content = egui::Rect::from_min_max(egui::pos2(rail.right() + 24.0, whole.top()), whole.max);
|
||||
|
||||
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 {
|
||||
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(RAIL_PADDING);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
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 = (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;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// 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(app, 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"))]
|
||||
{
|
||||
let free = !Modality::capture(app, ui.ctx()).is_blocked();
|
||||
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.as_str());
|
||||
ui.label(RichText::new(path.as_str()).small().color(tokens.text_dim));
|
||||
if row.clicked() {
|
||||
selected = Some(path.clone());
|
||||
}
|
||||
}
|
||||
if let Some(path) = selected {
|
||||
crate::windows::open_path(app, &path);
|
||||
app.ui.windows.home = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,11 @@ 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", "إعداد افتراضي محفوظ قيد الاستخدام"),
|
||||
("A small graph of atomic nodes working together", "مخطط صغير لعقد ذرية تعمل معاً"),
|
||||
("Abbe number", "عدد آبي"),
|
||||
("About MaterialCraft", "حول MaterialCraft"),
|
||||
("About MaterialCraft...", "حول MaterialCraft..."),
|
||||
@@ -44,28 +48,36 @@ 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", "تلقائي"),
|
||||
("Automatic (16-bit data, 8-bit color)", "تلقائي (16 بت للبيانات، 8 بت للألوان)"),
|
||||
("Automatic Clip Planes", "مستويات قطع تلقائية"),
|
||||
("Automatic export when outputs change", "تصدير تلقائي عند تغيّر المخرجات"),
|
||||
("Automation documentation...", "توثيق الأتمتة..."),
|
||||
("Autosave every (minutes, 0 = off)", "الحفظ التلقائي كل (دقائق، 0 = معطل)"),
|
||||
("Axis", "المحاور"),
|
||||
("Back", "الخلف"),
|
||||
@@ -77,6 +89,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Bad function", "دالة غير صالحة"),
|
||||
("Bake every control", "خَبز كل عناصر التحكم في الخامات"),
|
||||
("Base", "الأساس"),
|
||||
(
|
||||
"Base color, normal, roughness, metallic, height and ambient occlusion outputs with inputs already connected",
|
||||
"مخرجات اللون الأساسي والناظم والخشونة والمعدنية والارتفاع والإطباق المحيط موصولة بمدخلاتها مسبقاً",
|
||||
),
|
||||
("Base parameters", "المعلمات الأساسية"),
|
||||
("Batch", "دفعة"),
|
||||
("Bind to input", "ربط بالمدخل"),
|
||||
@@ -90,6 +106,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,9 +115,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Camera", "الكاميرا"),
|
||||
("Camera: drag to orbit, pan and zoom (C)", "الكاميرا: اسحب للدوران والتحريك والتكبير (C)"),
|
||||
("Cancel", "إلغاء"),
|
||||
("Cancel rendering", "إلغاء التصيير"),
|
||||
("Cast", "تحويل النوع"),
|
||||
("Category", "الفئة"),
|
||||
("Ceil", "الحد الأعلى (Ceil)"),
|
||||
("Channels shown", "القنوات المعروضة"),
|
||||
("Choose a package", "اختر حزمة"),
|
||||
("Check at least one output to export", "حدّد مخرجًا واحدًا على الأقل للتصدير"),
|
||||
("Check for updates...", "التحقق من وجود تحديثات..."),
|
||||
("Choose a folder to export to", "اختر مجلداً للتصدير إليه"),
|
||||
@@ -110,10 +130,12 @@ 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", "مستويات القطع"),
|
||||
("Close", "إغلاق"),
|
||||
("Close or confirm", "إغلاق أو تأكيد"),
|
||||
("Close all", "إغلاق الكل"),
|
||||
("Close the Histogram panel", "إغلاق لوحة المخطط البياني"),
|
||||
("Close the Information panel", "إغلاق لوحة المعلومات"),
|
||||
@@ -122,13 +144,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", "نسخ الصورة إلى الحافظة"),
|
||||
@@ -145,6 +172,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", "سماوي"),
|
||||
@@ -152,6 +180,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Dark", "داكن"),
|
||||
("Darkening", "التعتيم"),
|
||||
("Default", "افتراضي"),
|
||||
("Default 3D view", "العرض ثلاثي الأبعاد الافتراضي"),
|
||||
("Default environment", "البيئة الافتراضية"),
|
||||
("Default lighting state", "حالة الإضاءة الافتراضية"),
|
||||
("Delete", "حذف"),
|
||||
("Delete and relink", "حذف وإعادة ربط"),
|
||||
("Delete input", "حذف المدخل"),
|
||||
@@ -162,6 +193,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", "مقياس الإزاحة"),
|
||||
@@ -183,6 +215,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Duplicate selection without link", "تكرار التحديد بدون ربط"),
|
||||
("Edit", "تحرير"),
|
||||
("Edit function graph...", "تحرير مخطط الدوال..."),
|
||||
("Edit node graph", "تحرير مخطط العقدة"),
|
||||
("Edit properties", "تعديل الخصائص"),
|
||||
("Edit settings", "تعديل الإعدادات"),
|
||||
("Emission", "الانبعاث"),
|
||||
@@ -191,14 +224,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...", "تصدير المخرجات..."),
|
||||
@@ -217,6 +256,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("File", "ملف"),
|
||||
("File names", "أسماء الملفات"),
|
||||
("files", "ملفات"),
|
||||
("Filter", "تصفية"),
|
||||
("Filters", "مرشحات"),
|
||||
("Fit", "ملاءمة"),
|
||||
("Flip normal map Y (DirectX)", "قلب Y لخريطة النواظم (DirectX)"),
|
||||
@@ -228,8 +268,13 @@ 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 graph", "تأطير المخطط"),
|
||||
("Frame", "تأطير"),
|
||||
("Frame all", "تأطير الكل"),
|
||||
("Frame all (F)", "تأطير الكل (F)"),
|
||||
@@ -245,8 +290,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("function nodes", "عقد الدوال"),
|
||||
("Function of", "دالة لـ"),
|
||||
("Fuzz", "الزغب"),
|
||||
("General", "عام"),
|
||||
("Geometry", "الهندسة"),
|
||||
("Get variable", "جلب متغير"),
|
||||
("Give feedback...", "إرسال ملاحظات..."),
|
||||
("Glossiness", "اللمعان"),
|
||||
("Go to pin", "الانتقال إلى الدبوس"),
|
||||
("Graph", "مخطط"),
|
||||
@@ -268,6 +315,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Height scale", "مقياس الارتفاع"),
|
||||
("Height technique", "تقنية الارتفاع"),
|
||||
("Help", "مساعدة"),
|
||||
("High (16 spp)", "مرتفع (16 عينة/بكسل)"),
|
||||
("Histogram", "المخطط البياني (Histogram)"),
|
||||
("History", "السجل"),
|
||||
("Hollow box", "صندوق أجوف"),
|
||||
@@ -278,29 +326,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", "الأضواء"),
|
||||
@@ -310,17 +367,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 exported", "تم تصدير المادة"),
|
||||
("Material", "المادة"),
|
||||
("Material filters", "مرشحات المواد"),
|
||||
("Material graph", "مخطط مادة"),
|
||||
("Materials", "المواد"),
|
||||
("Maximum", "الحد الأقصى"),
|
||||
("Maximum stored previews", "أقصى عدد للمعاينات المخزنة"),
|
||||
("Medium (4 spp)", "متوسط (4 عينات/بكسل)"),
|
||||
("Medium dark", "داكن متوسط"),
|
||||
("Medium light", "فاتح متوسط"),
|
||||
("Mesh Info", "معلومات المجسم"),
|
||||
@@ -331,6 +394,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", "حرّك المؤشر فوق الصورة لقراءة بكسلاتها"),
|
||||
@@ -339,17 +403,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", "تشويشات"),
|
||||
@@ -358,9 +427,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 الاختياري",
|
||||
@@ -368,10 +440,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Opacity", "العتامة"),
|
||||
("Open", "فتح"),
|
||||
("Open graph", "فتح المخطط"),
|
||||
("Open node search", "فتح البحث عن العقد"),
|
||||
("Open package...", "فتح حزمة..."),
|
||||
("Open package... (Ctrl+O)", "فتح حزمة... (Ctrl+O)"),
|
||||
("Open...", "فتح..."),
|
||||
("Opened", "تم الفتح"),
|
||||
("Opened with", "فُتح مع"),
|
||||
("OpenGL (Y+)", "OpenGL (Y+)"),
|
||||
("Operator", "معامل حسابي"),
|
||||
("Ops", "عمليات"),
|
||||
@@ -383,10 +457,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", "النمط"),
|
||||
@@ -399,9 +476,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", "رخام مصقول"),
|
||||
@@ -411,11 +496,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", "الخصائص"),
|
||||
("Radius", "نصف القطر"),
|
||||
("Radius scale", "مقياس نصف القطر"),
|
||||
@@ -423,14 +512,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", "إزالة أداة التقاط اللون"),
|
||||
@@ -443,7 +538,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", "إعادة ضبط التخطيط"),
|
||||
@@ -472,14 +569,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", "حفظ الحزمة"),
|
||||
@@ -493,6 +596,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scene browser", "متصفح المشهد"),
|
||||
("Scene stats", "إحصاءات المشهد"),
|
||||
("Search", "بحث"),
|
||||
("Search by shortcut", "البحث بالاختصار"),
|
||||
("Search nodes...", "البحث في العقد..."),
|
||||
("Select all", "تحديد الكل"),
|
||||
("Select downstream nodes", "تحديد العقد اللاحقة"),
|
||||
@@ -511,16 +615,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", "المحاذاة إلى الشبكة"),
|
||||
("Source normals", "اتجاه نواظم المصدر"),
|
||||
("Specific parameters", "المعلمات المخصصة"),
|
||||
("Specular", "الانعكاس"),
|
||||
@@ -530,6 +637,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", "استوديو"),
|
||||
@@ -537,9 +645,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", "تقسيم + إزاحة"),
|
||||
@@ -547,8 +658,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", "الأضواء النقطية تلقي ظلالاً"),
|
||||
@@ -573,13 +688,19 @@ 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 Save as for:", "استخدم «حفظ باسم» لـ:"),
|
||||
("Use the built-in default", "استخدام الإعداد الافتراضي المدمج"),
|
||||
("Use this parameter; off reads as if the material had none", "استخدام هذا المعامل؛ عند الإيقاف يُقرأ كأن المادة لا تحتويه"),
|
||||
("Use viewport resolution", "استخدام دقة منفذ العرض"),
|
||||
("Used range", "النطاق المستخدم"),
|
||||
@@ -593,15 +714,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", "إطار سلكي"),
|
||||
|
||||
@@ -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,16 @@ 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;
|
||||
#[path = "preference/mod.rs"]
|
||||
pub mod preferences;
|
||||
mod template_card;
|
||||
mod toast;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod updates_ui;
|
||||
|
||||
@@ -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<Vec<LibraryEntry>> {
|
||||
pub(crate) fn entries(app: &MaterialCraftApp, ctx: &egui::Context) -> Arc<Vec<LibraryEntry>> {
|
||||
type Cached = (Vec<(String, usize)>, Arc<Vec<LibraryEntry>>);
|
||||
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::<Arc<Cached>>(id)).as_deref()
|
||||
&& *cached == key
|
||||
let previous = ctx.data(|data| data.get_temp::<Arc<Cached>>(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
|
||||
|
||||
@@ -13,6 +13,31 @@ fn labels(app: &MaterialCraftApp) -> Vec<String> {
|
||||
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() {
|
||||
|
||||
@@ -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<std::thread::JoinHandle<()>>,
|
||||
styled: Option<(theme::Brightness, theme::Accent)>,
|
||||
/// Release checks and the update prompt (desktop only)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -97,6 +102,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(),
|
||||
@@ -117,6 +123,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(),
|
||||
@@ -151,21 +161,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));
|
||||
}
|
||||
|
||||
if self.session.camera != self.ui.prefs.camera.sanitized() {
|
||||
self.session.set_camera_prefs(self.ui.prefs.camera);
|
||||
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;
|
||||
|
||||
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
|
||||
@@ -173,9 +190,13 @@ 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 = 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)}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,19 +286,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::<materialcraft_engine::FunctionGraphTarget>(v["target"].clone())
|
||||
@@ -305,6 +314,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.")
|
||||
@@ -353,44 +395,42 @@ impl MaterialCraftApp {
|
||||
|
||||
pub fn toast(&mut self, text: impl Into<String>, 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 dir = user_dir("autosave");
|
||||
let path = dir.join(format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name)));
|
||||
let pkg = self.session.pkg.clone();
|
||||
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())
|
||||
.and_then(|_| {
|
||||
materialcraft_engine::formats::project::ProjectFiles::build(&pkg, "autosave.mcraft", true)
|
||||
.and_then(|files| files.zip())
|
||||
.map_err(|e| e.to_string())
|
||||
})
|
||||
.and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|e| e.to_string()));
|
||||
match result {
|
||||
Ok(()) => log::info!("autosaved {}", path.display()),
|
||||
Err(e) => log::warn!("autosave to {} failed: {e}", 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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -401,7 +441,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) {
|
||||
@@ -512,7 +558,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));
|
||||
|
||||
@@ -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};
|
||||
|
||||
+66
-16
@@ -87,12 +87,14 @@ 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")),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
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 +102,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 +120,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 +138,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 +151,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 +195,14 @@ pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
if id == "ui.cook.cancel" {
|
||||
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());
|
||||
}
|
||||
@@ -180,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())
|
||||
}
|
||||
|
||||
@@ -206,17 +237,16 @@ 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::<u32>().ok()) {
|
||||
app.ui.prefs.preview_size = size;
|
||||
app.apply_prefs();
|
||||
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,14 +267,23 @@ 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),
|
||||
"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),
|
||||
_ => {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -363,6 +402,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::<u32>().ok()).map(|size| size == app.ui.prefs.preview_size)
|
||||
}
|
||||
@@ -418,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(_))))
|
||||
@@ -429,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);
|
||||
}
|
||||
@@ -437,14 +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();
|
||||
modality.allows(id) && !(label_selected && matches!(id, "edit.copy" | "edit.cut")) && !unavailable_clipboard_commands.contains(&id)
|
||||
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 {
|
||||
|
||||
@@ -41,6 +41,8 @@ pub(crate) enum Then {
|
||||
},
|
||||
/// The image file the 2D view draws behind transparent pixels
|
||||
BackgroundImage,
|
||||
/// Help ▸ Export log: diagnostic events without message details
|
||||
ExportLog(String),
|
||||
/// The parameters `graph.input.bind` runs with, before the path
|
||||
BindInput(Value, GraphRef),
|
||||
}
|
||||
@@ -94,6 +96,36 @@ pub(crate) fn save_package(app: &mut MaterialCraftApp, copy: bool) {
|
||||
ask(app, dialog, then);
|
||||
}
|
||||
|
||||
/// Help ▸ Export log: ask where to write a diagnostic event log
|
||||
pub(crate) fn export_log(app: &mut MaterialCraftApp) {
|
||||
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 };
|
||||
@@ -179,6 +211,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_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() {
|
||||
app.toast(format!("{} {picked}", tr("Saved")), false);
|
||||
|
||||
@@ -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<Request> {
|
||||
let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
//! 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;
|
||||
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
|
||||
const CATEGORIES: [(Option<GraphKind>, &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 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, size, |ui| {
|
||||
ui.set_min_size(size);
|
||||
let whole = ui.available_rect_before_wrap();
|
||||
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)));
|
||||
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);
|
||||
});
|
||||
|
||||
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;
|
||||
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,
|
||||
"document": target,
|
||||
"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(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));
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&combo.response, egui::Role::ComboBox, "Category");
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
|
||||
let cards: Vec<TemplateCard> =
|
||||
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(app, 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. 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| {
|
||||
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 = 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, 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 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
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Node creation shortcuts add a library entry under the pointer in the material graph
|
||||
|
||||
use craft_keymap::{Chord, Key, Mods, Platform};
|
||||
use egui::{Event, InputState};
|
||||
|
||||
/// The library categories whose entries can have a creation shortcut
|
||||
pub(crate) const CATEGORIES: [&str; 2] = ["Atomic nodes", "Graph items"];
|
||||
|
||||
/// The chord on a fresh key press, using the event's own modifiers
|
||||
pub(crate) fn event_chord(event: &Event, platform: Platform) -> Option<Chord> {
|
||||
let Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { return None };
|
||||
|
||||
Some(Chord::new(Mods::from_egui(modifiers, platform), Key::from_egui(*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<'a>(shortcuts: &'a std::collections::BTreeMap<String, String>, 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 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)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_shortcut_reads_back_as_the_keys_that_made_it() {
|
||||
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(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(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, 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();
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! 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;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// 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"));
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
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| {
|
||||
crate::preview_resolution::choices(ui, &mut prefs.preview_size);
|
||||
});
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! 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 preference_action;
|
||||
mod preferences_page;
|
||||
mod preferences_state;
|
||||
mod projects_page;
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
/// 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<T: egui::emath::Numeric>(ui: &mut Ui, label: &str, value: &mut T, range: std::ops::RangeInclusive<T>, 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 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, 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.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::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),
|
||||
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", 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);
|
||||
});
|
||||
|
||||
if rebuild_previews {
|
||||
app.run("library.cache.clear", serde_json::json!({}));
|
||||
}
|
||||
|
||||
// Closing the window is Cancel
|
||||
let choice = if open { choice } else { Some(PreferenceAction::Cancel) };
|
||||
match choice {
|
||||
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(PreferenceAction::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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/// A Preferences window action
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum PreferenceAction {
|
||||
Ok,
|
||||
Cancel,
|
||||
Apply,
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Prefs>,
|
||||
/// 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<String>,
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! 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());
|
||||
let mut changed = false;
|
||||
crate::widgets::combo(ui, tr("Default environment"), current, |ui| {
|
||||
for (id, label) in ENVIRONMENTS {
|
||||
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");
|
||||
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 changed {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Preferences ▸ Shortcuts: keys that add an atomic node or a graph item under the pointer
|
||||
|
||||
use craft_keymap::Key;
|
||||
use egui::{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, ICON_SIDE)
|
||||
})
|
||||
.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 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);
|
||||
(!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.get(rows).unwrap_or_default() {
|
||||
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 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 chord.mods.is_none() && chord.key == Key::Escape {
|
||||
return;
|
||||
}
|
||||
|
||||
if chord.mods.is_none() && matches!(chord.key, Key::Backspace | Key::Delete) {
|
||||
app.ui.prefs.node_shortcuts.remove(&entry);
|
||||
return;
|
||||
}
|
||||
|
||||
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 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);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! 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); 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;
|
||||
|
||||
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;
|
||||
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 background_changed || view.samples != original_samples {
|
||||
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);
|
||||
}
|
||||
@@ -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())
|
||||
|
||||
@@ -88,16 +88,25 @@ fn open_blocker(app: &MaterialCraftApp) -> Option<Blocker> {
|
||||
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 || 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)]
|
||||
|
||||
@@ -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<materialcraft_engine::View3d>,
|
||||
/// 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<String, String>,
|
||||
/// 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::<Prefs>(v).unwrap(), p);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<materialcraft_engine::core::GraphKind>,
|
||||
/// The package a new graph goes in; `None` is a new package
|
||||
#[serde(skip)]
|
||||
pub new_graph_package: Option<u64>,
|
||||
/// 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<crate::export::ExportSettings>,
|
||||
/// 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,31 @@ 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
|
||||
/// 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(|p| p != path);
|
||||
self.recent.retain(|recent| recent != path);
|
||||
self.recent.insert(0, path.to_string());
|
||||
self.recent.truncate(12);
|
||||
self.recent.truncate(self.committed_prefs().recent_limit.clamp(1, Prefs::MAX_RECENT));
|
||||
}
|
||||
}
|
||||
@@ -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<crate::web_files::PackageSave>,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! 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, 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<TemplateCard> {
|
||||
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 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",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
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::TextureId>) -> 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 || response.has_focus() {
|
||||
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);
|
||||
|
||||
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::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);
|
||||
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
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
+62
-225
@@ -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)]
|
||||
@@ -33,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());
|
||||
@@ -58,21 +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<TemplatePreviews> = std::cell::RefCell::new(TemplatePreviews::default());
|
||||
/// A template's rendered preview, once the background render has finished
|
||||
pub(crate) fn template_preview(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> Option<egui::TextureId> {
|
||||
(id != crate::template_card::FUNCTION_TEMPLATE).then(|| app.template_previews.get(ctx, id)).flatten()
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
@@ -81,13 +88,13 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
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 +103,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,127 +130,10 @@ 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;
|
||||
}
|
||||
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) {
|
||||
@@ -297,96 +190,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);
|
||||
@@ -565,6 +368,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);
|
||||
@@ -599,6 +406,36 @@ 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 = 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 without_file: Vec<&str> = reply["withoutFile"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
let failures: Vec<String> = 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();
|
||||
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)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn has_local_path(app: &MaterialCraftApp) -> bool {
|
||||
|
||||
@@ -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();
|
||||
@@ -152,3 +152,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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
//! 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();
|
||||
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);
|
||||
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());
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! 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]);
|
||||
let sample = materialcraft_engine::samples::template("atomics", "Fixture", 9).unwrap();
|
||||
assert_eq!(session.graph().unwrap().nodes, sample.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());
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! 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 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 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();
|
||||
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");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -177,14 +180,25 @@ fn explorer_drags_a_linked_graph_between_open_packages() {
|
||||
harness.state_mut().run("graph.node.param", json!({"id": color.0, "param": "color", "value": [0.9, 0.3, 0.1, 1.0]})).unwrap();
|
||||
let position = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Target canvas")).rect().center();
|
||||
double_click(&mut harness, position);
|
||||
settle(&mut harness, 8);
|
||||
|
||||
// Wait for the linked graph to be recooked after switching back to its document
|
||||
let expected_pixel = [0.9, 0.3, 0.1, 1.0];
|
||||
let linked_color_updated = |harness: &Harness<'static, MaterialCraftApp>| {
|
||||
harness
|
||||
.state()
|
||||
.session
|
||||
.cooked
|
||||
.image(instance, 0)
|
||||
.is_some_and(|image| image.get(0, 0, false).into_iter().zip(expected_pixel).all(|(actual, expected)| (actual - expected).abs() <= 1.0 / 255.0))
|
||||
};
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(6);
|
||||
while !linked_color_updated(&harness) && std::time::Instant::now() < deadline {
|
||||
settle(&mut harness, 1);
|
||||
}
|
||||
|
||||
assert_eq!(harness.state().session.document_id, target_document);
|
||||
assert_eq!(harness.state().session.history(), ["Add graph instance"]);
|
||||
|
||||
let value = harness.state().session.cooked.image(instance, 0).unwrap().get(0, 0, false);
|
||||
|
||||
assert!(value.into_iter().zip([0.9, 0.3, 0.1, 1.0]).all(|(actual, expected)| (actual - expected).abs() <= 1.0 / 255.0));
|
||||
assert!(linked_color_updated(&harness), "the linked instance uses the updated source pixel");
|
||||
assert!(harness.state().session.modified);
|
||||
|
||||
save(&mut harness, &directory, "linked-instance-source-edit");
|
||||
@@ -766,11 +780,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 +1178,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);
|
||||
|
||||
@@ -1671,7 +1683,22 @@ 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);
|
||||
|
||||
// Process the queued release before testing a frame that may already show the hover preview
|
||||
harness.step();
|
||||
|
||||
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");
|
||||
@@ -1681,9 +1708,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,10 +1722,14 @@ fn library_cache_preferences() {
|
||||
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);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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?, 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 |
|
||||
@@ -384,6 +384,7 @@ The named profiles choose their own file names and formats. Use `--format` and `
|
||||
| `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` | 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 |
|
||||
|
||||
@@ -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 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 (selected root graph, reachable helper graphs and source assets) 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 OpenPBR MaterialX baking and procedural MCMAT publishing) 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 | 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 | 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,6 +58,7 @@ and is tested.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 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%) |
|
||||
|
||||
Reference in new issue
Block a user