diff --git a/README.md b/README.md index 69cd720c..f714f68d 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ The full list of what's in it is in [`docs/features.md`](docs/features.md). git clone https://github.com/storytold/texturecraft cd texturecraft -cargo run --release -p texturecraft # desktop app (opens a sample project) +cargo run --release -p texturecraft # desktop app (starts with no project) cargo run --release -p texturecraft -- model.glb # a new project from a mesh cargo run --release -p texturecraft -- --control 7878 # + JSON control channel cargo run --release -p texturecraft-cli -- mcp # MCP server (stdio) @@ -157,7 +157,7 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.95 or newer. The app opens with a baked sample project and a start window (new project, open, recent projects); **File ▸ New project** starts +You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one; **File ▸ Close** returns to this empty state); **File ▸ New project** starts from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none). Japanese, Chinese, Korean and Arabic interface text uses the fonts of diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index bc1372a5..7740db12 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -40,9 +40,11 @@ pub fn start() { } async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { - // The WebAssembly has downloaded and compiled when this runs. - step(0.5, "Preparing the sample project…").await; - let session = initial_session()?; + // The WebAssembly has downloaded and compiled when this runs + step(0.5, "Preparing the app…").await; + + // The app starts with no project, like File > Close + let session = Session::closed().map_err(|e| e.to_string())?; step(0.8, "Starting the renderer…").await; let mut options = eframe::WebOptions::default(); if query().contains("webgl") @@ -50,13 +52,13 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { { create.instance_descriptor.backends = eframe::wgpu::Backends::GL; } + eframe::WebRunner::new() .start( canvas, options, Box::new(|cc| { let mut app = TextureCraftApp::new(cc, session); - app.ui.windows.start = app.ui.prefs.start_window; if let Some(rs) = &cc.wgpu_render_state { let backend = rs.adapter.get_info().backend; log::info!("TextureCraft: wgpu backend {backend:?}"); @@ -137,18 +139,6 @@ fn guard_unsaved_changes() { on_unload.forget(); } -/// The baked sample project, or an empty material ball if that fails. Texture and bake sizes are -/// kept small: the web build composites and bakes on one thread (bake 256 took ~12 s to start on a -/// fast desktop CPU, 128 ~7.5 s). -fn initial_session() -> Result { - texturecraft_engine::sample_session(1024, 128) - .or_else(|e| { - log::warn!("sample project failed: {e}"); - Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 1024) - }) - .map_err(|e| e.to_string()) -} - fn query() -> String { web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default() } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 2deac956..d05b6cad 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -38,6 +38,7 @@ fn version() -> String { struct Args { file: Option, control: Option, + /// With `--control`: start with an empty material ball instead of the sample project empty: bool, gpu: Option, power_pref: Option, @@ -84,21 +85,34 @@ fn parse_args_from>(it: I) -> Result } fn initial_session(args: &Args) -> Session { - if let Some(f) = &args.file { - match texturecraft_engine::file_cmds::open_path(f) { - Ok(s) => return s, - Err(e) => eprintln!("texturecraft: could not open {f}: {e}"), + if let Some(path) = &args.file { + match texturecraft_engine::file_cmds::open_path(path) { + Ok(session) => return session, + Err(error) => eprintln!("texturecraft: could not open {path}: {error}"), } } - if !args.empty - && let Ok(s) = texturecraft_engine::sample_session(2048, 512) - { - return s; + + // Control runs retain their sample project; interactive runs start empty + if args.control.is_some() { + if !args.empty + && let Ok(session) = texturecraft_engine::sample_session(2048, 512) + { + return session; + } + + return match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) { + Ok(session) => session, + Err(error) => { + eprintln!("texturecraft: {error}"); + std::process::exit(1); + } + }; } - match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) { - Ok(s) => s, - Err(e) => { - eprintln!("texturecraft: {e}"); + + match Session::closed() { + Ok(session) => session, + Err(error) => { + eprintln!("texturecraft: {error}"); std::process::exit(1); } } @@ -176,7 +190,7 @@ fn checks_for_updates_at_start(control: Option) -> bool { } fn main() { - // Windows: the update helper is a copy of this program started with `--finish-update`. + // Windows: the update helper is a copy of this program started with `--finish-update` #[cfg(windows)] if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); @@ -189,14 +203,16 @@ fn main() { std::process::exit(2); } }; + // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); - let prev = std::panic::take_hook(); + let previous_hook = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { // A message box needs the main thread on macOS; other threads' panics are only logged fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); - prev(info); + previous_hook(info); })); + // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); @@ -220,9 +236,7 @@ fn main() { std::process::exit(2); } let control = args.control; - // The start window offers new, open and recent projects, unless a file was given or a script drives the app - let start = args.file.is_none() && control.is_none(); - let r = eframe::run_native( + let result = eframe::run_native( APP_NAME, options, Box::new(move |cc| { @@ -230,7 +244,8 @@ fn main() { if let Some(w) = cc.winit_window() { set_taskbar_icon(w); } - // winit's Quit ends the process without asking; this menu's asks like the close button. + + // winit's Quit ends the process without asking; this menu's asks like the close button #[cfg(target_os = "macos")] if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) { log::warn!("the app menu could not be installed: {e}"); @@ -238,7 +253,6 @@ fn main() { let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; - app.ui.windows.start = start && app.ui.prefs.start_window; app.set_startup_update_check(checks_for_updates_at_start(control)); if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); @@ -251,7 +265,7 @@ fn main() { })) }), ); - if let Err(e) = r { + if let Err(e) = result { fatal(&e.to_string(), true); std::process::exit(1); } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 438a4f25..a5b3c761 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -101,6 +101,11 @@ impl Headless { matches!(self.fs, Filesystem::TrustedLocal) } + /// Commands that act on the project refuse after `file.close`, as in the app + fn require_project(&self) -> Result<(), AutomationError> { + if self.session.project_open { Ok(()) } else { Err(bad("no project is open")) } + } + fn read(&self, path: &str) -> Result, AutomationError> { match &self.fs { Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root ")), @@ -205,12 +210,15 @@ impl Headless { /// Add a high-definition mesh for baking from `path` (or, with `cage`, set the bake cage). pub fn add_bake_mesh(&mut self, path: &str, cage: bool) -> Result { + self.require_project()?; + let f = self.read_mesh(path)?; Ok(self.session.add_bake_mesh(f, cage)?) } /// Reimport the mesh from `path`, or from the project's own copy, keeping the project. pub fn reimport_mesh(&mut self, path: Option<&str>, preserve_strokes: bool) -> Result { + self.require_project()?; let file = path.map(|p| self.read_mesh(p)).transpose()?; Ok(self.session.reimport_mesh(file, preserve_strokes)?) } @@ -218,6 +226,7 @@ impl Headless { /// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the /// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it. pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result { + self.require_project()?; let out = self.session.mesh_export(path, format)?; let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or("."); self.create_dir_all(dir)?; @@ -233,12 +242,14 @@ impl Headless { /// Import an image file as a project resource (for `layer.add.image`, `tool.stencil`). pub fn import_resource(&mut self, path: &str) -> Result { + self.require_project()?; let bytes = self.read(path)?; Ok(json!({ "name": self.session.import_resource_bytes(path, bytes)? })) } /// Save a layer (default: the selected one) as a smart material file (`.tcmat`). pub fn material_save(&mut self, p: &Value) -> Result { + self.require_project()?; let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?; let s = &self.session; let id = match p.get("layer").and_then(Value::as_u64) { @@ -258,12 +269,14 @@ impl Headless { /// Add a smart material from a `.tcmat` file above the selection. pub fn material_load(&mut self, path: &str) -> Result { + self.require_project()?; let bytes = self.read(path)?; Ok(json!({ "layer": self.session.add_smart_material_bytes(&bytes)?.0 })) } /// Save as `.tcraft` to `path`, or to the project's own file. pub fn save(&mut self, path: Option<&str>) -> Result { + self.require_project()?; let target = match path.or(self.session.path.as_deref()) { Some(p) if ext_of(p) == PROJECT_EXT => p.to_string(), Some(p) => format!("{p}.{PROJECT_EXT}"), @@ -277,6 +290,7 @@ impl Headless { /// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…). pub fn export(&mut self, p: &Value) -> Result { + self.require_project()?; let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?; let opts = file_cmds::export_options(&self.session, p, "textures.export")?; let n = self.session.set_count(); @@ -299,39 +313,43 @@ impl Headless { /// Render the session to PNG. The viewport needs a GPU adapter; path tracing (`samples`) /// runs on the GPU when it has compute shaders and falls back to the CPU. - pub fn render_png(&mut self, o: &RenderOptions) -> Result { - let s = &self.session; - let kind = match o.view.as_deref().unwrap_or("3d") { + pub fn render_png(&mut self, options: &RenderOptions) -> Result { + self.require_project()?; + + let session = &self.session; + let kind = match options.view.as_deref().unwrap_or("3d") { "3d" => ViewKind::Scene, - "2d" | "uv" => ViewKind::Uv { ts: s.ts(), zoom: 1.0, pan: [0.0, 0.0] }, + "2d" | "uv" => ViewKind::Uv { ts: session.ts(), zoom: 1.0, pan: [0.0, 0.0] }, other => return Err(bad(format!("unknown view `{other}` (3d, 2d or uv)"))), }; - let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE }; - let side = |v: Option, d: f32| { + let max_side = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE }; + let checked_side = |v: Option, d: f32| { let v = v.unwrap_or(d.round() as u32); - if (16..=max).contains(&v) { Ok(v) } else { Err(bad(format!("render size {v} must be 16 to {max} pixels"))) } + if (16..=max_side).contains(&v) { Ok(v) } else { Err(bad(format!("render size {v} must be 16 to {max_side} pixels"))) } }; - let size = [side(o.width, s.viewport.x)?, side(o.height, s.viewport.y)?]; - let mut camera = s.camera; - for (v, slot, lim) in [(o.yaw, &mut camera.yaw, 1e6), (o.pitch, &mut camera.pitch, 89.0)] { + let size = [checked_side(options.width, session.viewport.x)?, checked_side(options.height, session.viewport.y)?]; + let mut camera = session.camera; + for (v, slot, max_degrees) in [(options.yaw, &mut camera.yaw, 1e6), (options.pitch, &mut camera.pitch, 89.0)] { if let Some(v) = v { if !v.is_finite() { return Err(bad("camera angles must be finite")); } - *slot = v.clamp(-lim, lim).to_radians(); + + *slot = v.clamp(-max_degrees, max_degrees).to_radians(); } } - if let Some(samples) = o.samples { - if !(1..=MAX_TRACE_SAMPLES).contains(&samples) || o.view.as_deref().is_some_and(|v| v != "3d") { + if let Some(samples) = options.samples { + if !(1..=MAX_TRACE_SAMPLES).contains(&samples) || options.view.as_deref().is_some_and(|v| v != "3d") { return Err(bad(format!("path tracing renders the 3D view with 1 to {MAX_TRACE_SAMPLES} samples"))); } - let settings = texturecraft_render::trace::TraceSettings { bounces: o.bounces.unwrap_or(6).clamp(1, 32) }; + + let settings = texturecraft_render::trace::TraceSettings { bounces: options.bounces.unwrap_or(6).clamp(1, 32) }; let mut traced = None; let mut by = "CPU path tracer".to_string(); - if !o.cpu + if !options.cpu && let Ok(gpu) = self.gpu.get_or_insert_with(Gpu::new) { - // Last-resort guard, as for viewport renders below. + // Last-resort guard, as for viewport renders below let session = &mut self.session; match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.path_trace(session, size, camera, samples, &settings))) { Ok(Ok(px)) => { @@ -355,11 +373,13 @@ impl Headless { } return Ok(Rendered { width: w, height: h, png, by }); } + let gpu = match self.gpu.get_or_insert_with(Gpu::new) { Ok(g) => g, Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))), }; - // Last-resort guard: wgpu panics on device errors; drop the device and report instead. + + // Last-resort guard: wgpu panics on device errors; drop the device and report instead let session = &mut self.session; let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.render(session, kind, size, camera))); let (w, h, rgba) = match out { @@ -396,6 +416,25 @@ pub fn batch_reply(results: Vec, failed: Option<(usize, &str, String)>) - mod tests { use super::*; + #[test] + fn closed_session_rejects_bake_mesh_before_reading_it() { + let mut client = Headless::new(Session::closed().unwrap(), Filesystem::Denied); + + let error = client.add_bake_mesh("missing.obj", false).unwrap_err(); + + assert!(error.to_string().contains("no project is open"), "{error}"); + } + + #[test] + fn closed_session_rejects_render_before_view_validation() { + let mut client = Headless::new(Session::closed().unwrap(), Filesystem::Denied); + let options = RenderOptions { view: Some("unknown".into()), ..RenderOptions::default() }; + + let error = client.render_png(&options).err().unwrap(); + + assert!(error.to_string().contains("no project is open"), "{error}"); + } + #[test] fn fresh_headless_session_loads_saved_brushes() { let brush_dir = std::env::temp_dir().join(format!("tc-headless-brush-{}", std::process::id())); diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 53b33f61..8214b3b0 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -147,6 +147,40 @@ pub fn command_specs() -> &'static [CommandSpec] { }) } +/// Commands that run in the empty state (no project open): they open or create a project, or +/// only read the libraries and the user's presets, or only move the camera (`viewport.frame`, enabled on the reference app's blank screen). +fn works_without_project(id: &str) -> bool { + matches!( + id, + "file.open" + | "file.new" + | "project.new" + | "project.sample" + | "project.inspect" + | "viewport.frame" + | "project.templates" + | "export.presets" + | "export.preset.get" + | "export.preset.save" + | "export.preset.remove" + | "brush.preset.list" + | "alpha.list" + | "filter.list" + | "material.list" + | "mask.smart.list" + | "text.fonts" + ) +} + +/// Whether `spec` can run on `s`: no project open refuses everything but [`works_without_project`] +pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), String> { + if !s.project_open && !works_without_project(spec.id) { + return Err("no project is open".into()); + } + + (spec.enabled)(s) +} + pub fn find(id: &str) -> Option<&'static CommandSpec> { command_specs().iter().find(|c| c.id == id) } @@ -155,7 +189,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> { /// `merge: true` its edits continue the previous undo step of the same label (drags). pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result { let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - (spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; + check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false)); let result = (spec.run)(s, params); s.merge_edits = outer; @@ -175,7 +209,7 @@ pub fn list(s: &Session, filter: Option<&str>) -> Value { "menu": c.menu, "shortcut": c.shortcut, "params": c.params, - "enabled": (c.enabled)(s).is_ok(), + "enabled": check_enabled(c, s).is_ok(), }) }) .collect(); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 331e9c26..ad339dca 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -685,8 +685,7 @@ use unsupported as export_textures; use unsupported as export_mesh; fn close(s: &mut Session, _: &Value) -> Result { - let next = Session::new_project("Untitled", primitives::material_ball(), "builtin:material_ball", None, 2048)?; - s.switch_to(next); + s.switch_to(Session::closed()?); Ok(Value::Null) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index b045bb4a..8fb0a3d8 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -202,28 +202,29 @@ pub fn texture_set(session: &Session, index: usize) -> Value { } /// The whole session. -pub fn session(s: &Session) -> Value { - let ts = s.ts(); +pub fn session(session: &Session) -> Value { + let texture_set = session.ts(); json!({ - "project": s.doc.project.name, - "mesh": { "source": s.doc.project.mesh, "triangles": s.mesh.triangle_count(), "vertices": s.mesh.vertex_count(), "materials": s.mesh.materials }, - "path": s.path, - "modified": s.modified, - "textureSets": texture_sets(s), - "bakeMeshes": crate::bake::meshes_json(s), - "activeTextureSet": ts, - "selectedLayer": s.selected_layer().map(|l| l.0), - "selectedLayers": crate::layer_selection::ids_json(&s.selected_layers()), - "target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) }, - "layers": stack(s, ts), - "tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) }, - "view": s.view.label(), - "solo": s.solo.map(|solo| json!({ "layer": solo.layer.0, "ignoreMask": solo.ignore_mask })), - "bakePreview": crate::bake_preview::preview_json(s), - "camera": crate::view_cmds::camera_json(s), - "display": s.doc.project.display, - "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, - "memoryBytes": s.memory().total(), - "pendingTiles": s.pending_tiles(), + "projectOpen": session.project_open, + "project": session.doc.project.name, + "mesh": { "source": session.doc.project.mesh, "triangles": session.mesh.triangle_count(), "vertices": session.mesh.vertex_count(), "materials": session.mesh.materials }, + "path": session.path, + "modified": session.modified, + "textureSets": texture_sets(session), + "bakeMeshes": crate::bake::meshes_json(session), + "activeTextureSet": texture_set, + "selectedLayer": session.selected_layer().map(|layer| layer.0), + "selectedLayers": crate::layer_selection::ids_json(&session.selected_layers()), + "target": match session.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(effect) => json!(effect.0) }, + "layers": stack(session, texture_set), + "tool": { "tool": session.tool.tool.id(), "brush": crate::tool_cmds::brush_json(session) }, + "view": session.view.label(), + "solo": session.solo.map(|solo| json!({ "layer": solo.layer.0, "ignoreMask": solo.ignore_mask })), + "bakePreview": crate::bake_preview::preview_json(session), + "camera": crate::view_cmds::camera_json(session), + "display": session.doc.project.display, + "history": { "undo": session.undo_label(), "redo": session.redo_label(), "depth": session.history_labels().len() }, + "memoryBytes": session.memory().total(), + "pendingTiles": session.pending_tiles(), }) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ced2014f..6f89804a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -75,7 +75,7 @@ pub mod view_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap}; pub use bake_preview::{BakePreview, PreviewShow}; -pub use commands::{CommandSpec, command_specs, execute, find}; +pub use commands::{CommandSpec, check_enabled, command_specs, execute, find}; pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use path_tool::PathState; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index cffeb713..f8ce6c32 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -448,6 +448,10 @@ pub struct Session { /// Point changes of the path being edited: (earlier states for undo, undone states for redo) pub(crate) path_steps: (Vec, Vec), pub path: Option, + /// False in the empty state (the app at start, or after File > Close): the document is a + /// tiny placeholder that panels do not show. Project-independent commands remain available + /// (see [`crate::commands::check_enabled`]). + pub project_open: bool, pub modified: bool, /// Bumps on every document change. pub revision: u64, @@ -512,6 +516,7 @@ impl Session { path_draft: None, path_steps: Default::default(), path: None, + project_open: true, modified: false, revision: 1, log: Vec::new(), @@ -523,6 +528,16 @@ impl Session { }) } + /// The empty state: no project is open. Holds a tiny placeholder document that the UI never + /// shows; project-dependent commands are refused. + pub fn closed() -> Result { + // The hidden placeholder uses the minimum supported texture resolution + let mut session = Session::new_project("", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, texturecraft_core::MIN_RESOLUTION)?; + session.project_open = false; + + Ok(session) + } + /// Replace this session with `next` (another project), keeping the viewport size, the /// user's brush presets, export presets and project templates and the tool settings. pub fn switch_to(&mut self, mut next: Session) { diff --git a/crates/engine/src/tool_availability.rs b/crates/engine/src/tool_availability.rs index 7002f37b..9dd93859 100644 --- a/crates/engine/src/tool_availability.rs +++ b/crates/engine/src/tool_availability.rs @@ -7,6 +7,10 @@ use crate::{Session, StackTarget, Tool}; impl Session { /// Whether `tool` can act on the selection (or on the quick mask while it is being edited) pub fn tool_usable(&self, tool: Tool) -> bool { + if !self.project_open { + return false; + } + match tool { // The picker reads the composite under the cursor, whatever is selected Tool::ColorPicker => return true, diff --git a/crates/engine/tests/it/closed_session.rs b/crates/engine/tests/it/closed_session.rs new file mode 100644 index 00000000..2c19e089 --- /dev/null +++ b/crates/engine/tests/it/closed_session.rs @@ -0,0 +1,79 @@ +//! The empty state (no project open): project-dependent commands are refused, and +//! File > Close returns to it. + +use serde_json::json; +use texturecraft_engine::{EngineError, Session, Tool, check_enabled, command_specs, execute, find}; + +fn open_project() -> Session { + Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap() +} + +#[test] +fn a_closed_session_refuses_commands_that_need_a_project() { + let mut session = Session::closed().unwrap(); + + assert!(!session.project_open); + for id in ["layer.add.paint", "file.save", "file.close", "edit.undo", "tool.paint", "bake.run", "file.exportTextures", "viewport.view", "camera.add"] { + let error = execute(&mut session, id, &json!({})).unwrap_err(); + + assert!(matches!(error, EngineError::Disabled { .. }), "{id}: {error}"); + } + assert!(!session.can_undo(), "nothing was changed"); + assert!(!session.tool_usable(Tool::Paint), "no tool can act without a project"); +} + +#[test] +fn a_closed_session_lists_project_independent_commands_as_enabled() { + let session = Session::closed().unwrap(); + for id in ["file.open", "file.new", "project.new", "project.sample"] { + assert!(check_enabled(find(id).unwrap(), &session).is_ok(), "{id} runs with no project"); + } + let enabled: Vec<&str> = command_specs().iter().filter(|spec| check_enabled(spec, &session).is_ok()).map(|spec| spec.id).collect(); + + assert!(!enabled.iter().any(|id| id.starts_with("layer.") || id.starts_with("tool.") || id.starts_with("bake.")), "{enabled:?}"); +} + +#[test] +fn creating_a_project_from_the_closed_state_opens_it() { + let mut session = Session::closed().unwrap(); + + execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); + + assert!(session.project_open); + + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); +} + +#[test] +fn close_returns_to_the_empty_state_and_allows_reopening() { + let mut session = open_project(); + session.modified = true; + + execute(&mut session, "file.close", &json!({})).unwrap(); + + assert!(!session.project_open && !session.modified && session.path.is_none()); + assert!(execute(&mut session, "file.close", &json!({})).is_err(), "closing again has nothing to close"); + + execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); + + assert!(session.project_open, "a project can be created again"); +} + +#[test] +fn the_libraries_and_presets_still_answer_without_a_project() { + let mut session = Session::closed().unwrap(); + for id in [ + "export.presets", + "brush.preset.list", + "alpha.list", + "filter.list", + "material.list", + "mask.smart.list", + "text.fonts", + "project.templates", + "project.inspect", + ] { + execute(&mut session, id, &json!({})).unwrap_or_else(|error| panic!("{id}: {error}")); + } + assert_eq!(texturecraft_engine::inspect::session(&session)["projectOpen"], json!(false)); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 20d1c773..17e217b4 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -7,6 +7,7 @@ mod bake_resolution; mod bake_settings; mod bake_tiles; mod brush_material; +mod closed_session; mod color_selection; mod content_effects; mod export_colour_space; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 136fd373..c5dc53bf 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -76,6 +76,12 @@ pub(crate) fn encode_png(w: u32, h: u32, rgba: Vec) -> Option<(u32, u32, Vec pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, params: &Value) -> Value { app.ui.prefs.apply_resource_limits(); + + // These direct control jobs bypass the engine command availability check + if !app.session.project_open && matches!(method, "ui.bake.start" | "debug.paintTest") { + return err("no project is open"); + } + match method { "ping" => ok(json!("pong")), "ui.resize" => { @@ -104,6 +110,18 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para app.thumbs.forget_saved_files(); } + // Work from the old project must not reach its replacement + if matches!(id, "file.open" | "file.new" | "file.close" | "project.new" | "project.sample") { + app.resize = None; + app.pbr_import = None; + app.layer_panel = Default::default(); + } + + // The Export dialog cannot operate after Close + if id == "file.close" { + app.ui.windows.export = false; + } + // A command that moved the camera takes over from a glide in progress; a projection switch joins it app.settle_camera_glide(id, before); @@ -223,6 +241,10 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para /// Encode a rendered view as PNG. pub fn screenshot(app: &TextureCraftApp, view: u64) -> Option<(u32, u32, Vec)> { + if !app.session.project_open { + return None; + } + let rs = app.render_state.as_ref()?; let renderer = rs.renderer.read(); let gpu = renderer.callback_resources.get::()?; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ffa81798..d831213d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -43,6 +43,11 @@ const TAG_COLORS: [Color32; 8] = [ ]; pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { + // The empty state lists nothing + if !app.session.project_open { + return; + } + let tk = Tokens::get(ui.ctx()); let sets: Vec<(String, String, bool)> = app .session @@ -95,7 +100,8 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text); - // Narrow panels drop the shader label, then the resolution, before cutting the name. + + // Narrow panels drop the shader label, then the resolution, before cutting the name let cy = rect.center().y; let mut right = rect.right() - 6.0; if rect.width() >= 260.0 { @@ -142,48 +148,62 @@ fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { } pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); // Wrap in a narrow column so rows stay within the panel - ui.horizontal_wrapped(|ui| { - // Keep menu buttons as compact as the adjacent icon buttons - ui.spacing_mut().button_padding.x = 4.0; - ui.spacing_mut().item_spacing.x = TOOLBAR_SPACING; - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let project_open = app.session.project_open; + ui.add_enabled_ui(project_open, |ui| { + ui.horizontal_wrapped(|ui| { + // Keep menu buttons as compact as the adjacent icon buttons + ui.spacing_mut().button_padding.x = 4.0; + ui.spacing_mut().item_spacing.x = TOOLBAR_SPACING; + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); - // The channel box takes what the six buttons leave, so the toolbar stays on one row in a narrow column - let buttons = 2.0 * (MENU_BUTTON_WIDTH + TOOLBAR_SPACING) + 4.0 * (TOOLBAR_ICON_SIZE + TOOLBAR_SPACING); - let channel_width = (ui.available_width() - buttons).clamp(CHANNEL_BOX_MIN_WIDTH, CHANNEL_BOX_WIDTH); - ui.allocate_ui(vec2(channel_width, ICON_BUTTON_SIZE), |ui| { - egui::ComboBox::from_id_salt("layer_channel").width(channel_width).truncate().selected_text(tr(app.ui.layer_channel.label())).show_ui(ui, |ui| { - for c in chans { - ui.selectable_value(&mut app.ui.layer_channel, c, tr(c.label())); - } + // The channel box takes what the six buttons leave, so the toolbar stays on one row in a narrow column + let buttons = 2.0 * (MENU_BUTTON_WIDTH + TOOLBAR_SPACING) + 4.0 * (TOOLBAR_ICON_SIZE + TOOLBAR_SPACING); + let channel_width = (ui.available_width() - buttons).clamp(CHANNEL_BOX_MIN_WIDTH, CHANNEL_BOX_WIDTH); + ui.allocate_ui(vec2(channel_width, ICON_BUTTON_SIZE), |ui| { + egui::ComboBox::from_id_salt("layer_channel").width(channel_width).truncate().selected_text(tr(app.ui.layer_channel.label())).show_ui( + ui, + |ui| { + for channel in channels { + ui.selectable_value(&mut app.ui.layer_channel, channel, tr(channel.label())); + } + }, + ); }); - }); - let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); - ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| match &selected { - Some(l) => effect_menu(app, ui, l), - None => { - ui.label(RichText::new(tr("Select a layer")).color(tk.text_dim)); + ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| { + let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); + match &selected { + Some(layer) => effect_menu(app, ui, layer), + None => { + ui.label(RichText::new(tr("Select a layer")).color(tokens.text_dim)); + } + } + }) + .response + .on_hover_text(tr("Add effect")); + ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| add_mask_menu(app, ui, None)).response.on_hover_text(tr("Add mask")); + if icon_button(ui, ic::PAINT_BRUSH, tr("Add paint layer"), false, TOOLBAR_ICON_SIZE).clicked() { + app.run("layer.add.paint", Value::Null); + } + if icon_button(ui, ic::PAINT_BUCKET, tr("Add fill layer"), false, TOOLBAR_ICON_SIZE).clicked() { + app.run("layer.add.fill", Value::Null); + } + if icon_button(ui, ic::FOLDER_SIMPLE, tr("Add folder"), false, TOOLBAR_ICON_SIZE).clicked() { + app.run("layer.add.group", Value::Null); + } + if icon_button(ui, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), false, TOOLBAR_ICON_SIZE).clicked() { + app.run("layer.remove", Value::Null); } }) - .response - .on_hover_text(tr("Add effect")); - ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| add_mask_menu(app, ui, None)).response.on_hover_text(tr("Add mask")); - if icon_button(ui, ic::PAINT_BRUSH, tr("Add paint layer"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.paint", Value::Null); - } - if icon_button(ui, ic::PAINT_BUCKET, tr("Add fill layer"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.fill", Value::Null); - } - if icon_button(ui, ic::FOLDER_SIMPLE, tr("Add folder"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.group", Value::Null); - } - if icon_button(ui, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.remove", Value::Null); - } }); + + // The empty state has no layers: the toolbar stays, greyed + if !project_open { + return; + } + ui.add_space(2.0); let ts = app.session.ts(); let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default(); @@ -217,7 +237,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { } let material = resp.dnd_hover_payload::().is_some_and(|d| d.asset.is_material()); if resp.dnd_hover_payload::().is_some() || material { - ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); + ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tokens.accent)); } }); select_all_layers(app, ui); @@ -1768,6 +1788,10 @@ pub(crate) fn mesh_map_color(map: BakedMap) -> Color32 { /// The Properties tab title: what the panel edits pub(crate) fn properties_title(app: &TextureCraftApp) -> String { + if !app.session.project_open { + return tr("Properties").to_string(); + } + let project = &app.session.doc.project; let tool = app.session.tool.tool; let tool_usable = app.session.tool_usable(tool); @@ -1794,6 +1818,11 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { /// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder, instance or mask, else the tool (or a hint to select a layer when it can't act) pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); + if !app.session.project_open { + ui.label(RichText::new(tr("No properties found")).color(tokens.text_dim)); + return; + } + let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); let tool = app.session.tool.tool; let tool_usable = app.session.tool_usable(tool); diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 62bfa427..13d39465 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -480,6 +480,12 @@ const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); /// The body of every panel except the viewport, in the dock or on the rail pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { + // No project open: the library and the log work, the other panels about a project stay empty + let works_empty = matches!(panel, Panel::Assets | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties); + if !app.session.project_open && !works_empty { + return; + } + egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel { Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), @@ -490,6 +496,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { Panel::Layers => crate::dock::layers(app, ui), Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), Panel::Properties => crate::dock::properties(app, ui), + // Display and Shader Settings scroll here, as tall as their contents; History and Log scroll their own lists Panel::Display => egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, true]).show(ui, |ui| crate::windows::display(app, ui)).inner, Panel::Shader => egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, true]).show(ui, |ui| crate::windows::shader(app, ui)).inner, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9c4224d1..94643a0e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -256,7 +256,13 @@ impl TextureCraftApp { // The first run speaks the OS (or browser) language let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned()); - let ui = start_ui(ui_store.load(cc.storage), &mut session); + let mut ui = start_ui(ui_store.load(cc.storage), &mut session); + + // No window opens by itself with no project (a saved layout may have left Export open) + if !session.project_open { + ui.windows.export = false; + } + let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; ui.prefs.apply_resource_limits(); @@ -348,9 +354,17 @@ impl TextureCraftApp { self.thumbs.forget_saved_files(); } - // A pending dialog must not import its old source into the replacement project - if matches!(id, "file.open" | "file.close" | "project.new" | "project.sample") { + // Pending work and thumbnail snapshots belong to the old project + if matches!(id, "file.open" | "file.new" | "file.close" | "project.new" | "project.sample") { self.pbr_import = None; + self.resize = None; + self.layer_panel = Default::default(); + } + + // The empty state has no baking or rendering to show + if id == "file.close" { + self.ui.mode = state::Mode::Painting; + self.ui.windows.export = false; } match glide_from { @@ -585,6 +599,7 @@ impl TextureCraftApp { if self.resize.is_some() { return; } + match self.session.resize_task(ts, resolution) { Ok(task) => { let progress = Arc::new(Progress::new()); @@ -598,10 +613,18 @@ impl TextureCraftApp { /// Apply a finished resize (after any stroke in progress ends). fn poll_resize(&mut self, ctx: &egui::Context) { let Some(job) = &self.resize else { return }; + + // Nothing to resize without a project (a result that arrives after Close is dropped) + if !self.session.project_open { + self.resize = None; + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(30)); if self.session.stroke_active() { return; } + let result = match job.rx.try_recv() { Ok(r) => r, Err(std::sync::mpsc::TryRecvError::Empty) => return, @@ -843,7 +866,13 @@ impl eframe::App for TextureCraftApp { #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); - let t0 = now_ms(); + let started_ms = now_ms(); + + // Baking and rendering need a project (a saved layout may start in one of them) + if !self.session.project_open { + self.ui.mode = state::Mode::Painting; + } + if !self.ui.hide_ui { titlebar::show(self, ui); banner(self, ui); @@ -854,25 +883,28 @@ impl eframe::App for TextureCraftApp { toolbar::rail(self, ui); } } - let hide = self.ui.hide_ui; - let tk = theme::Tokens::get(&ctx); + + let hide_ui = self.ui.hide_ui; + let tokens = theme::Tokens::get(&ctx); // The dock keeps the cards' gutter from the bars and rails around it - let panel_frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; - egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); + let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) }; + egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); - // The Layers panel and the source slots have asked for their pictures by now + // Finish after the dock and windows have requested their thumbnails self.layer_panel.end(&ctx, &self.session); + #[cfg(not(target_arch = "wasm32"))] updates_ui::show(self, &ctx); toasts(self, &ctx); #[cfg(not(target_arch = "wasm32"))] self.file_dialogs.show_pending(frame); - let end = now_ms(); - let dt = (end - t0) as f32; - self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 }; - self.profiler.end_frame(end, dt); + + let ended_ms = now_ms(); + let elapsed_ms = (ended_ms - started_ms) as f32; + self.ui_ms = if self.ui_ms == 0.0 { elapsed_ms } else { self.ui_ms * 0.9 + elapsed_ms * 0.1 }; + self.profiler.end_frame(ended_ms, elapsed_ms); } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index c999d494..16755672 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -38,12 +38,14 @@ pub const TOP: [&str; 6] = ["File", "Edit", "Mode", "Window", "Viewport", "Help" pub const CATALOG: &[Item] = &[ it("File", "New project...", "ui.newProject", Some("Ctrl+N")), it("File", "Open...", "file.open", Some("Ctrl+O")), + sep("File"), it("File", "Open sample project...", "project.sample", None), + sep("File"), it("File", "Close", "file.close", Some("Ctrl+F4")), sep("File"), it("File", "Save", "file.save", Some("Ctrl+S")), it("File", "Save as...", "file.saveAs", Some("Ctrl+Shift+S")), - it("File", "Save a copy...", "file.saveCopy", None), + sub("File", "More save options", "Save a copy...", "file.saveCopy", None), it("File", "Remove unused resources...", "file.removeUnused", None), sep("File"), it("File", "Import resources...", "resource.import", None), @@ -57,7 +59,6 @@ pub const CATALOG: &[Item] = &[ it("File", "Quit", "ui.quit", Some("Ctrl+Q")), it("Edit", "Undo", "edit.undo", Some("Ctrl+Z")), it("Edit", "Redo", "edit.redo", Some("Ctrl+Y")), - sep("Edit"), it("Edit", "Project Configuration...", "ui.projectConfig", None), it("Edit", "Reimport mesh", "file.reimportMesh", Some("Ctrl+Shift+R")), it("Edit", "Settings...", "ui.settings", None), @@ -76,10 +77,12 @@ pub const CATALOG: &[Item] = &[ sub("Window", "Views", "Shader Settings", "ui.view.shader", None), sub("Window", "Views", "Texture Sets", "ui.view.textureSetList", None), sub("Window", "Views", "Texture Set Settings", "ui.view.textureSetSettings", None), + sep("Window"), sub("Window", "Save UI Layout", "Save current layout...", "ui.layout.save", None), it("Window", "Load UI Layout", "ui.layout.load", None), sub("Window", "Layouts", "Save current layout as...", "ui.layout.saveAs", None), sub("Window", "Layouts", "Manage layouts...", "ui.layout.manage", None), + sep("Window"), it("Window", "Hide UI", "ui.hideUi", Some("Tab")), it("Window", "Reset panel layout", "ui.resetPanelLayout", None), it("Window", "Reset UI", "ui.resetUi", None), @@ -113,11 +116,12 @@ pub const CATALOG: &[Item] = &[ it("Viewport", "Invert quick mask", "viewport.quickMask.invert", Some("Ctrl+Shift+I")), it("Help", "Documentation...", "ui.help.docs", 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", "Report a bug...", "ui.help.bug", None), - sep("Help"), it("Help", "Show log...", "ui.view.log", None), + sep("Help"), #[cfg(not(target_arch = "wasm32"))] it("Help", "Check for Updates...", "ui.help.checkForUpdates", None), it("Help", "About TextureCraft...", "ui.about", None), @@ -128,6 +132,11 @@ fn is_ui(id: &str) -> bool { id.starts_with("ui.") } +/// Shell items that act on the open project: greyed while none is open +fn ui_needs_project(id: &str) -> bool { + matches!(id, "ui.export" | "ui.projectConfig" | "ui.uvChecker" | "ui.mode.bake" | "ui.mode.paint" | "ui.mode.render") +} + /// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { if let Some(panel) = crate::docking::view_panel(id) { @@ -143,7 +152,7 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { } if is_ui(id) { - return true; + return app.session.project_open || !ui_needs_project(id); } // Scripts may pick any tool, but the shelf and its shortcuts offer only those that can act @@ -152,7 +161,7 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { return false; } - texturecraft_engine::find(id).is_some_and(|command| (command.enabled)(&app.session).is_ok()) + texturecraft_engine::find(id).is_some_and(|command| texturecraft_engine::check_enabled(command, &app.session).is_ok()) } /// Whether an id is implemented at all (parity report). diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index 6826c1a0..506d20d7 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -12,11 +12,11 @@ use crate::widgets::icon_button; /// The rail's panels, top to bottom, with their icons and Window ▸ Views ids pub(crate) const RAIL_PANELS: [(Panel, &str, &str); 5] = [ - (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), + (Panel::Log, ic::FILE_TEXT, "ui.view.log"), (Panel::Display, ic::MONITOR, "ui.view.display"), (Panel::Shader, ic::SLIDERS_HORIZONTAL, "ui.view.shader"), (Panel::History, ic::CLOCK_COUNTER_CLOCKWISE, "ui.view.history"), - (Panel::Log, ic::FILE_TEXT, "ui.view.log"), + (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), ]; /// The popup reaches this far into the viewport, so it covers the panels between the viewport and the rail diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 9945a2d9..005699be 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -79,9 +79,6 @@ pub struct Windows { /// Browser File › Export Mesh: the download format choice. #[serde(default)] pub export_mesh: bool, - /// The start window: new, open, recent projects (the app opens it at launch). - #[serde(skip)] - pub start: bool, /// Edit > Project Configuration: what is chosen so far, applied by OK. #[serde(skip)] pub project_config: Option, @@ -125,8 +122,6 @@ pub struct Prefs { pub accent: crate::theme::Accent, /// The system draws the window's title bar instead of TextureCraft (desktop; read at startup). pub system_title_bar: bool, - /// Show the start window at launch. - pub start_window: bool, /// Where autosaves, smart materials, presets, templates and layouts go (desktop; read at /// startup). Empty or relative: `Documents/TextureCraft`. pub data_folder: String, @@ -149,7 +144,6 @@ impl Default for Prefs { brightness: crate::theme::Brightness::default(), accent: crate::theme::Accent::default(), system_title_bar: false, - start_window: true, data_folder: String::new(), reserved_cores: 1, project_open_limit_gib: texturecraft_engine::formats::DEFAULT_PROJECT_OPEN_LIMIT_GIB, diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index f9dbf810..76a5c742 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -76,27 +76,31 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { /// Width of `view_buttons`, so the bar knows when to move them into the scrolling strip fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { - // Two icons, two dropdowns, two separators and the five gaps between them - 2.0 * button_size + 2.0 * icon_dropdown_button_width(button_size) + 2.0 * BAR_SEPARATOR_WIDTH + 5.0 * spacing + // Two icons, two dropdowns, one separator and the four gaps between them + 2.0 * button_size + 2.0 * icon_dropdown_button_width(button_size) + BAR_SEPARATOR_WIDTH + 4.0 * spacing } -/// View buttons in a right-to-left layout, with the screenshot button at the end +/// View buttons in a right-to-left layout: the layout, then the camera type, then the screenshot and UV checker fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let button_size = ui.spacing().interact_size.y; - if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, button_size).clicked() { - app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); - } + // Only the layout works without a project: the others act on it + let project_open = app.session.project_open; + + // Right-to-left: the UV checker is added first and sits rightmost + ui.add_enabled_ui(project_open, |ui| { + let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; + if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, button_size).clicked() { + let mode = if checker { "material" } else { "uvChecker" }; + app.run("viewport.view", json!({"mode": mode})); + } + if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, button_size).clicked() { + app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); + } + }); ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - projection_dropdown(app, ui); + ui.add_enabled_ui(project_open, |ui| projection_dropdown(app, ui)); layout_dropdown(app, ui); - - ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; - if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, button_size).clicked() { - let mode = if checker { "material" } else { "uvChecker" }; - app.run("viewport.view", json!({"mode": mode})); - } } /// The 3D/2D, 3D-only and 2D-only layouts, showing the current one's icon @@ -315,7 +319,10 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, button_size).clicked() { + // Greyed (Painting stays shown as the current mode) while no project is open + let on = crate::menus::enabled(app, command); + let button = ui.add_enabled_ui(on, |ui| icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, button_size)).inner; + if button.clicked() { crate::menus::invoke(app, &ui.ctx().clone(), command); } } @@ -525,23 +532,6 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { .size(11.0) .color(tk.text_dim), ); - ui.separator(); - let m = app.session.memory(); - let mb = |b: usize| b as f64 / (1024.0 * 1024.0); - let total = mb(m.total()); - let decimals = if total < 10.0 { 1 } else { 0 }; - let mb1 = |b: usize| format!("{:.1}", mb(b)); - ui.label(RichText::new(trf("Layer memory: {mb} MB", &[("mb", &format!("{total:.decimals$}"))])).size(11.0).color(tk.text_dim)).on_hover_ui( - |ui| { - ui.label(trf( - "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", - &[("pixels", &mb1(m.pixels)), ("composites", &mb1(m.composites)), ("cache", &mb1(m.cache))], - )); - }, - ); - ui.separator(); - ui.label(RichText::new(trf("UI {ms} ms", &[("ms", &format!("{:.1}", app.ui_ms))])).size(11.0).color(tk.text_dim)); - ui.add_space(vec2(0.0, 0.0).x); }); }); }); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 20736bdd..072977e2 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -126,7 +126,6 @@ mod tests { let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().updates_rt.updater = Updater::new(&crate::UPDATE_APP, "0.0.1").with_source(ask).with_paths(Paths::under(&root)).with_pins_path(root.join("pins.json")); - h.state_mut().ui.windows.start = false; h.run_steps(2); h } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 9c7822c9..4c453f04 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -65,6 +65,23 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { crate::toolbar::paint_bar(app, ui); } + // No project open: empty views with only their view-mode picker + if !app.session.project_open { + if app.render.is_active() { + crate::render_mode::stop(app); + } + + // The closed project's last frames must not stay readable (`viewport.screenshot`) + if let Some(render_state) = app.render_state.as_ref() + && let Some(gpu) = render_state.renderer.write().callback_resources.get_mut::() + { + gpu.renderer.drop_view(VIEW_3D); + gpu.renderer.drop_view(VIEW_2D); + } + empty_views(app, ui); + return; + } + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); // A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture @@ -139,6 +156,28 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// The views while no project is open: no mesh, no texture, each with its view-mode picker +fn empty_views(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let full = ui.available_rect_before_wrap(); + let regions: Vec<(Rect, &str)> = match app.ui.layout { + ViewLayout::Only3D => vec![(full, "v3d")], + ViewLayout::Only2D => vec![(full, "v2d")], + ViewLayout::Split => { + let middle = (full.left() + full.width() * 0.5).round(); + vec![ + (Rect::from_min_max(full.min, pos2(middle - SPLIT_LINE_HALF_WIDTH, full.max.y)), "v3d"), + (Rect::from_min_max(pos2(middle + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max), "v2d"), + ] + } + }; + + for (rect, id) in regions { + ui.painter().rect_filled(rect, 0.0, tokens.viewport); + view_header(app, ui, rect, id); + } +} + /// Half the split divider's line width: each view starts this far from the line's centre const SPLIT_LINE_HALF_WIDTH: f32 = 1.0; @@ -450,23 +489,27 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { let Some(header) = view_header_rect(rect) else { return }; let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center))); + // With no project open there is no camera to pick: the view keeps only its view-mode picker + let project_open = app.session.project_open; let current = texturecraft_engine::camera_cmds::current(&app.session); let names: Vec = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect(); let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str); - egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { - if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { - app.run("camera.select", json!({})); - } - for (index, name) in names.iter().enumerate() { - if ui.selectable_label(current == Some(index), name).clicked() { - app.run("camera.select", json!({"index": index})); + if project_open { + egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { + if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { + app.run("camera.select", json!({})); } - } - ui.separator(); - if ui.selectable_label(false, tr("Save view as camera")).clicked() { - app.run("camera.add", json!({})); - } - }); + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(current == Some(index), name).clicked() { + app.run("camera.select", json!({"index": index})); + } + } + ui.separator(); + if ui.selectable_label(false, tr("Save view as camera")).clicked() { + app.run("camera.add", json!({})); + } + }); + } // Bake mode lights the project mesh with the neutral material unless the painted one is asked for let baking = app.ui.mode == crate::state::Mode::Baking; @@ -477,33 +520,43 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { _ => app.session.view.label(), }; let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); - egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(&mut child, |ui| { - if baking && ui.selectable_label(neutral, tr("Neutral Material")).clicked() { - app.ui.bake_visualization.neutral_shown = true; - app.run("viewport.view", json!({"mode": "material"})); - } - if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() { - // Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone - app.ui.bake_visualization.neutral_shown &= !baking; - app.run("viewport.view", json!({"mode": "material"})); - } - ui.separator(); - if baking { - mesh_map_entries(app, ui); - return; - } - for channel in channels { - if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { - app.run("viewport.view", json!({"mode": channel.id()})); + // The picker stays greyed without project maps + child.add_enabled_ui(project_open, |child| { + egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(child, |ui| { + if baking && ui.selectable_label(neutral, tr("Neutral Material")).clicked() { + app.ui.bake_visualization.neutral_shown = true; + app.run("viewport.view", json!({"mode": "material"})); } - } - ui.separator(); - mesh_map_entries(app, ui); - ui.separator(); - if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() { - app.run("viewport.view", json!({"mode": "uvChecker"})); - } + if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() && project_open { + // Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone + app.ui.bake_visualization.neutral_shown &= !baking; + app.run("viewport.view", json!({"mode": "material"})); + } + + // Nothing else to show without a project + if !project_open { + return; + } + + ui.separator(); + if baking { + mesh_map_entries(app, ui); + return; + } + + for channel in channels { + if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { + app.run("viewport.view", json!({"mode": channel.id()})); + } + } + ui.separator(); + mesh_map_entries(app, ui); + ui.separator(); + if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() { + app.run("viewport.view", json!({"mode": "uvChecker"})); + } + }) }); } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index a436cd01..fe4bcd83 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -32,18 +32,18 @@ pub const MATERIAL_EXTS: &[&str] = &["tcmat", "mcmat", "mcraft"]; /// Texture size of a project made from an opened mesh (smaller on the single-threaded web). const MESH_RESOLUTION: u32 = if cfg!(target_arch = "wasm32") { 1024 } else { 2048 }; -/// What a picked file is for. +/// What a picked file is for; project-bound picks carry their originating project id. #[derive(Clone, Copy, PartialEq)] #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] enum Pick { /// File > Open / a dropped file: a project, a mesh or an image resource. Open, /// Display settings > Import HDR. - Environment, + Environment(u64), /// Bake mode: a high-definition mesh. - HighPoly, + HighPoly(u64), /// Bake mode: the cage mesh. - Cage, + Cage(u64), /// Export dialog › Output templates: an export template (`.json`). ExportPreset, } @@ -54,15 +54,29 @@ static INBOX: Mutex, Pick)>> = Mutex::new(Vec::new()); /// Load files that arrived since the last frame. Call once per frame. pub fn poll(app: &mut TextureCraftApp) { let picked = std::mem::take(&mut *INBOX.lock().unwrap_or_else(PoisonError::into_inner)); + apply_picked(app, picked); +} + +fn apply_picked(app: &mut TextureCraftApp, picked: Vec<(String, Vec, Pick)>) { for (name, bytes, pick) in picked { let done = match pick { Pick::Open => { load(app, &name, bytes); continue; } - Pick::Environment => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)), - Pick::HighPoly => app.session.add_high_poly_bytes(&name, bytes).map(|n| app.toast(trf("High poly: {name}", &[("name", &n)]), false)), - Pick::Cage => app.session.set_cage_bytes(&name, bytes).map(|n| app.toast(trf("Cage: {name}", &[("name", &n)]), false)), + + // A late project-bound pick must not modify the placeholder or a replacement project + Pick::Environment(_) | Pick::HighPoly(_) | Pick::Cage(_) if !app.session.project_open => { + app.toast(tr("No project is open"), true); + continue; + } + Pick::Environment(project_id) | Pick::HighPoly(project_id) | Pick::Cage(project_id) if project_id != app.session.project_id => { + app.toast(tr("The project changed while the dialog was open, so nothing was done"), true); + continue; + } + Pick::Environment(_) => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)), + Pick::HighPoly(_) => app.session.add_high_poly_bytes(&name, bytes).map(|n| app.toast(trf("High poly: {name}", &[("name", &n)]), false)), + Pick::Cage(_) => app.session.set_cage_bytes(&name, bytes).map(|n| app.toast(trf("Cage: {name}", &[("name", &n)]), false)), Pick::ExportPreset => { match texturecraft_engine::formats::preset_from_json(&String::from_utf8_lossy(&bytes)) { Ok(p) => crate::export_templates::import(app, &p), @@ -119,6 +133,11 @@ fn use_environment(app: &mut TextureCraftApp, name: &str) { pub fn load(app: &mut TextureCraftApp, name: &str, bytes: Vec) { let path = std::path::Path::new(name); let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + if (IMAGE_EXTS.contains(&ext.as_str()) || MATERIAL_EXTS.contains(&ext.as_str())) && !app.session.project_open { + app.toast(tr("No project is open"), true); + return; + } + if IMAGE_EXTS.contains(&ext.as_str()) { match app.session.import_resource_bytes(name, bytes) { Ok(res) => { @@ -129,22 +148,27 @@ pub fn load(app: &mut TextureCraftApp, name: &str, bytes: Vec) { } return; } + if MATERIAL_EXTS.contains(&ext.as_str()) { if let Err(e) = app.session.add_smart_material_bytes(&bytes) { app.toast(trf("Couldn't import {name}: {error}", &[("name", &name), ("error", &e)]), true); } return; } + let bytes = std::sync::Arc::new(bytes); if crate::windows::ask_to_save(app, crate::state::Unsaved::Load(name.into(), bytes.clone())) { return; } + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled"); let next = if ext == PROJECT_EXT { Session::from_project_bytes(&bytes) } else { Session::from_mesh_bytes(name, &bytes, MESH_RESOLUTION, stem) }; match next { Ok(next) => { app.session.switch_to(next); app.pbr_import = None; + app.resize = None; + app.layer_panel = Default::default(); app.toast(trf("Opened {name}", &[("name", &name)]), false); } Err(e) => app.toast(trf("Couldn't open {name}: {error}", &[("name", &name), ("error", &e)]), true), @@ -246,13 +270,13 @@ mod web { /// Display settings › Import HDR: pick an equirect image; it becomes the environment on a /// later frame. - pub fn import_environment(_app: &mut TextureCraftApp, ctx: &egui::Context) { - pick(ctx, tr("HDR environments"), ENV_EXTS, false, Pick::Environment); + pub fn import_environment(app: &mut TextureCraftApp, ctx: &egui::Context) { + pick(ctx, tr("HDR environments"), ENV_EXTS, false, Pick::Environment(app.session.project_id)); } /// Bake mode: pick high-definition meshes (or the cage); they load on a later frame. - pub fn import_bake_mesh(_app: &mut TextureCraftApp, ctx: &egui::Context, cage: bool) { - pick(ctx, tr("Meshes"), &MESH_EXTENSIONS, !cage, if cage { Pick::Cage } else { Pick::HighPoly }); + pub fn import_bake_mesh(app: &mut TextureCraftApp, ctx: &egui::Context, cage: bool) { + pick(ctx, tr("Meshes"), &MESH_EXTENSIONS, !cage, if cage { Pick::Cage(app.session.project_id) } else { Pick::HighPoly(app.session.project_id) }); } /// Export dialog › Output templates › Import: pick a template; it is added on a later frame. @@ -360,6 +384,79 @@ mod web { mod tests { use super::*; + use egui_kittest::Harness; + + #[test] + fn environment_pick_after_close_does_not_edit_the_placeholder() { + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let old_project_id = harness.state().session.project_id; + + assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); + + apply_picked(harness.state_mut(), vec![("environment.png".into(), png.clone(), Pick::Environment(old_project_id))]); + + assert!(!harness.state().session.can_undo()); + assert!(!harness.state().session.doc.resources.contains_key("environment.png")); + + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + let project_id = harness.state().session.project_id; + + apply_picked(harness.state_mut(), vec![("environment.png".into(), png, Pick::Environment(project_id))]); + + assert!(harness.state().session.doc.resources.contains_key("environment.png")); + } + + #[test] + fn environment_pick_from_replaced_project_does_not_edit_the_new_project() { + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let old_project_id = harness.state().session.project_id; + + assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + + apply_picked(harness.state_mut(), vec![("old-environment.png".into(), png, Pick::Environment(old_project_id))]); + + assert!(!harness.state().session.doc.resources.contains_key("old-environment.png")); + assert!(!harness.state().session.modified); + assert!(!harness.state().session.can_undo()); + assert!(harness.state().toasts.iter().any(|toast| toast.error)); + } + + #[test] + fn bake_mesh_picks_after_close_do_not_edit_the_placeholder() { + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let old_project_id = harness.state().session.project_id; + assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); + let cage = harness.state().session.mesh_obj_bytes(); + + apply_picked( + harness.state_mut(), + vec![("high.obj".into(), cage.clone(), Pick::HighPoly(old_project_id)), ("cage.obj".into(), cage, Pick::Cage(old_project_id))], + ); + + assert!(harness.state().session.bake_meshes.high.is_empty()); + assert!(harness.state().session.bake_meshes.cage.is_none()); + assert!(!harness.state().session.modified); + assert_eq!(harness.state().toasts.iter().filter(|toast| toast.error).count(), 2); + + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + let project_id = harness.state().session.project_id; + let mesh = harness.state().session.mesh_obj_bytes(); + + apply_picked( + harness.state_mut(), + vec![("high.obj".into(), mesh.clone(), Pick::HighPoly(project_id)), ("cage.obj".into(), mesh, Pick::Cage(project_id))], + ); + + assert_eq!(harness.state().session.bake_meshes.high.len(), 1); + assert!(harness.state().session.bake_meshes.cage.is_some()); + } + #[test] fn zip_round_trips_every_export_file() { let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0199bbe0..3c507dc3 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -19,7 +19,6 @@ use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, section_with_reset, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - start(app, ctx); new_project(app, ctx); about(app, ctx); settings(app, ctx); @@ -446,78 +445,6 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// What the start window was asked for. -enum Start { - Menu(&'static str), - #[cfg(not(target_arch = "wasm32"))] - Recent(String), - Close, -} - -/// The start window: a new project, a project file or a recent one, or the sample that is open. -fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { - if !app.ui.windows.start { - return; - } - - #[cfg(not(target_arch = "wasm32"))] - let tokens = Tokens::get(ctx); - let mut open = true; - let mut action = None; - dialog("start", "TextureCraft", &mut open).min_width(380.0).show(ctx, |ui| { - ui.horizontal(|ui| { - if ui.add(primary_button(ui, tr("New project..."))).clicked() { - action = Some(Start::Menu("ui.newProject")); - } - if ui.button(tr("Open...")).clicked() { - action = Some(Start::Menu("file.open")); - } - }); - #[cfg(not(target_arch = "wasm32"))] - if file_dialogs_available() { - ui.add_space(8.0); - ui.label(caption(tr("Recent projects"))); - if app.ui.recent.is_empty() { - ui.label(RichText::new(tr("No recent projects yet")).color(tokens.text_dim)); - } - for path in &app.ui.recent { - let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path); - if ui - .add(egui::Button::selectable(false, format!("{} {name}", ic::FILE)).min_size(vec2(ui.available_width(), 0.0))) - .on_hover_text(path) - .clicked() - { - action = Some(Start::Recent(path.clone())); - } - } - } - ui.add_space(8.0); - ui.separator(); - ui.horizontal(|ui| { - ui.checkbox(&mut app.ui.prefs.start_window, tr("Show at startup")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Continue with the sample project")).clicked() { - action = Some(Start::Close); - } - }); - }); - }); - - if let Some(action) = action { - app.ui.windows.start = false; - match action { - Start::Menu(id) => crate::menus::invoke(app, ctx, id), - #[cfg(not(target_arch = "wasm32"))] - Start::Recent(path) => open_path(app, &path), - Start::Close => {} - } - } - - if !open { - app.ui.windows.start = false; - } -} - fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.new_project { return; @@ -573,7 +500,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { ui.add(egui::TextEdit::singleline(&mut app.ui.new_project.template_name).hint_text(tr("Template name")).desired_width(120.0)); let name = app.ui.new_project.template_name.trim().to_string(); - if ui.add_enabled(!name.is_empty(), egui::Button::new(tr("Save current project as template"))).clicked() + if ui.add_enabled(!name.is_empty() && app.session.project_open, egui::Button::new(tr("Save current project as template"))).clicked() && app.run("project.template.save", json!({"name": name})).is_some() { app.ui.new_project.template = name; @@ -658,13 +585,15 @@ fn settings_resources(ctx: &egui::Context) -> (u32, u64) { fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); let mut open = app.ui.windows.settings; - // A language whose script no font draws is listed by its English name and disabled. + + // A language whose script no font draws is listed by its English name and disabled let drawable = LANGUAGES.each_ref().map(|l| crate::fonts::Script::of_language(l.code).is_none_or(|s| app.fonts.covers(s))); #[cfg(not(target_arch = "wasm32"))] let mut pick_data_folder = false; window("settings", tr("Settings"), &mut open).default_width(360.0).show(ctx, |ui| { let p = &mut app.ui.prefs; - // Every section is a two-column form: labels on the left, controls aligned beside them. + + // Every section is a two-column form: labels on the left, controls aligned beside them let form = |id: &str| egui::Grid::new(id).num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(120.0); ui.label(caption(tr("Interface"))); form("settings_interface").show(ui, |ui| { @@ -716,9 +645,6 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar")); ui.end_row(); } - ui.label(tr("Start window")); - ui.checkbox(&mut p.start_window, tr("Show at startup")); - ui.end_row(); }); ui.add_space(8.0); ui.label(caption(tr("Viewport"))); @@ -1287,6 +1213,12 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let presets = texturecraft_engine::formats::builtin_presets(); dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(820.0, 430.0)).show(ctx, |ui| { + // Nothing to export without a project + if !app.session.project_open { + ui.label(tr("No project is open")); + return; + } + ui.horizontal(|ui| { for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { if ui.selectable_label(app.ui.export.tab == i as u8, caption(t)).clicked() { diff --git a/crates/ui-egui/tests/it/close_unsaved.rs b/crates/ui-egui/tests/it/close_unsaved.rs index 47996530..e1b74688 100644 --- a/crates/ui-egui/tests/it/close_unsaved.rs +++ b/crates/ui-egui/tests/it/close_unsaved.rs @@ -102,7 +102,7 @@ fn closing_the_project_with_changes_asks_first() { assert_eq!(name(&h), "Edited", "the project stays until answered"); h.get_by_label("Don't save").click(); h.run_steps(2); - assert_ne!(name(&h), "Edited", "Don't save closes the project"); + assert!(!h.state().session.project_open, "Don't save closes the project"); assert!(h.state().ui.windows.unsaved.is_none() && !h.state().session.modified); } diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs new file mode 100644 index 00000000..54f4e925 --- /dev/null +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -0,0 +1,395 @@ +//! The app starts with no project and no popup; File > Close goes back to that empty state. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_ui_egui::{TextureCraftApp, menus}; + +fn harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The exact-text checks below need English, whatever the OS language is + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness +} + +fn empty() -> Harness<'static, TextureCraftApp> { + harness(Session::closed().unwrap()) +} + +fn open_project() -> Harness<'static, TextureCraftApp> { + harness(texturecraft_engine::sample_session(256, 64).unwrap()) +} + +/// Texts painted this frame as (text, left edge) +fn painted(harness: &Harness<'static, TextureCraftApp>) -> Vec<(String, f32)> { + harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) => Some((text.galley.text().to_string(), text.pos.x)), + _ => None, + }) + .collect() +} + +fn has_camera_picker(harness: &Harness<'static, TextureCraftApp>) -> bool { + painted(harness).iter().any(|(text, _)| text == "Default camera") +} + +fn invoke(harness: &mut Harness<'static, TextureCraftApp>, id: &str) { + let ctx = harness.ctx.clone(); + menus::invoke(harness.state_mut(), &ctx, id); + harness.run_steps(3); +} + +#[test] +fn starts_with_no_project_and_no_popup() { + let harness = empty(); + let ui = &harness.state().ui; + + assert!(!harness.state().session.project_open); + assert!(!ui.windows.new_project && !ui.windows.about && !ui.windows.settings && !ui.windows.export, "no window opens by itself"); + assert!(harness.query_by_label("Continue with the sample project").is_none() && harness.query_by_label("Recent projects").is_none(), "no start window"); + assert!(harness.query_by_label("No properties found").is_some(), "Properties says it has nothing"); +} + +#[test] +fn project_items_are_disabled_without_a_project() { + let harness = empty(); + let app = harness.state(); + for id in [ + "file.save", + "file.saveAs", + "file.saveCopy", + "file.close", + "ui.export", + "file.exportMesh", + "ui.projectConfig", + "edit.undo", + "edit.redo", + "file.reimportMesh", + "ui.mode.bake", + "ui.mode.render", + "ui.uvChecker", + "viewport.displayMaterial", + "tool.paint", + "tool.eraser", + "viewport.quickMask", + "layer.add.paint", + "layer.add.fill", + "layer.remove", + "bake.run", + "resource.import", + "material.load", + ] { + assert!(!menus::enabled(app, id), "{id} needs a project"); + } + for id in + ["ui.newProject", "file.open", "project.sample", "ui.settings", "ui.about", "ui.quit", "ui.hideUi", "ui.resetUi", "viewport.frame", "ui.layout.split"] + { + assert!(menus::enabled(app, id), "{id} works without a project"); + } + let open = open_project(); + for id in ["file.save", "file.close", "ui.export", "layer.add.paint", "ui.mode.bake"] { + assert!(menus::enabled(open.state(), id), "{id} is on with a project"); + } +} + +#[test] +fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { + let empty = empty(); + + assert!(!has_camera_picker(&empty), "no camera picker"); + + // The picker shows "Material" right of the tool shelf and the Assets panel: one per view in the split layout + let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && *x > 400.0).count(); + + assert_eq!(pickers, 2, "each of the two views keeps its view picker"); + + let open = open_project(); + + assert!(has_camera_picker(&open), "with a project the camera picker is there"); +} + +#[test] +fn the_status_bar_has_the_version_but_no_frame_time_or_layer_memory() { + for harness in [empty(), open_project()] { + assert!(harness.query_by_label_contains("Version:").is_some()); + assert!(harness.query_by_label_contains("Layer memory").is_none()); + assert!(harness.query_by_label_contains(" ms").is_none(), "no frame time"); + } +} + +#[test] +fn close_unloads_the_project_back_to_the_empty_state() { + let mut harness = open_project(); + + assert!(harness.state().session.project_open && harness.state().session.set_count() == 2); + + invoke(&mut harness, "file.close"); + + assert!(!harness.state().session.project_open, "Close leaves no project open"); + assert!(harness.state().session.path.is_none() && !harness.state().session.modified); + assert!(harness.query_by_label("No properties found").is_some()); + assert!(!has_camera_picker(&harness)); + assert!(!menus::enabled(harness.state(), "file.save")); +} + +#[test] +fn creating_or_opening_a_project_from_the_empty_state_works() { + let mut harness = empty(); + + assert!(harness.state_mut().run("project.new", json!({"mesh": "cube", "resolution": 128})).is_some()); + harness.run_steps(3); + + assert!(harness.state().session.project_open); + assert!(menus::enabled(harness.state(), "file.save") && has_camera_picker(&harness)); + + invoke(&mut harness, "file.close"); + invoke(&mut harness, "ui.newProject"); + + assert!(harness.state().ui.windows.new_project, "New project opens its dialog from the empty state"); + + let mut harness = empty(); + + invoke(&mut harness, "project.sample"); + + assert!(harness.state().session.project_open && harness.state().session.set_count() == 2, "the sample is still one menu click away"); +} + +#[test] +fn using_every_panel_and_menu_item_in_the_empty_state_does_not_panic() { + let mut harness = empty(); + for item in menus::CATALOG + .iter() + .filter(|item| item.label != "-" && !matches!(item.id, "ui.quit" | "file.open" | "project.sample" | "ui.layout.load" | "ui.help.checkForUpdates")) + { + invoke(&mut harness, item.id); + } + for mode in ["ui.mode.bake", "ui.mode.render", "ui.mode.paint"] { + invoke(&mut harness, mode); + } + for id in ["ui.layout.2d", "ui.layout.3d", "ui.layout.split"] { + invoke(&mut harness, id); + } + assert!(!harness.state().session.project_open, "none of these opened a project"); + assert!(!harness.state().session.can_undo(), "and none changed it"); +} + +#[test] +fn close_drops_the_pending_resize_and_the_viewport_images() { + let mut harness = open_project(); + harness.state_mut().start_resize(0, 128); + + assert!(harness.state().resize.is_some(), "a resize is running"); + + let had_image = texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_some(); + + invoke(&mut harness, "file.close"); + + assert!(harness.state().resize.is_none(), "Close drops the resize of the closed project"); + assert!(!harness.state().session.modified, "a late resize result does not mark the empty project modified"); + if had_image { + assert!( + texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_none(), + "no image of the closed project" + ); + } +} + +fn assert_eventually_released(reference: &std::sync::Weak) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while reference.strong_count() > 0 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + + assert_eq!(reference.strong_count(), 0, "the old project must be released after background work finishes"); +} + +#[test] +fn control_project_replacement_discards_the_old_resize() { + let mut harness = open_project(); + let resource = std::sync::Arc::new(vec![0; 1_048_576]); + let old_resource = std::sync::Arc::downgrade(&resource); + harness.state_mut().session.doc.resources.insert("lifetime-probe.bin".into(), resource); + let old_mesh = std::sync::Arc::downgrade(&harness.state().session.mesh); + harness.state_mut().start_resize(0, 128); + + assert!(harness.state().resize.is_some()); + + let resize_progress = std::sync::Arc::downgrade(&harness.state().resize.as_ref().unwrap().progress); + let owners_before = resize_progress.strong_count(); + + let ctx = harness.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle( + harness.state_mut(), + &ctx, + "command.run", + &json!({"id": "project.new", "params": {"mesh": "cube", "resolution": 128}}), + ); + + assert_eq!(reply["ok"], true); + assert!(harness.state().session.project_open); + assert!(harness.state().resize.is_none(), "the previous project's resize must be discarded"); + + let owners_after = resize_progress.strong_count(); + eprintln!("control resize progress owners: {owners_before} before, {owners_after} after replacement"); + + assert!(owners_after < owners_before && owners_after <= 1); + + assert_eventually_released(&resize_progress); + assert_eventually_released(&old_mesh); + assert_eventually_released(&old_resource); + eprintln!( + "released old mesh and 1_048_576-byte resource after replacement: mesh={}, resource={}, progress={}", + old_mesh.strong_count(), + old_resource.strong_count(), + resize_progress.strong_count() + ); + + harness.run_steps(3); + + assert!(!harness.state().session.modified && !harness.state().session.can_undo(), "the old resize must not change the new project"); +} + +#[test] +fn control_close_rejects_a_viewport_capture_before_the_next_frame() { + let mut harness = open_project(); + let ctx = harness.ctx.clone(); + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &ctx, "command.run", &json!({"id": "file.close"})); + + assert_eq!(reply["ok"], true); + assert!(!harness.state().session.project_open); + assert!(texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_none()); +} + +#[test] +fn control_close_dismisses_the_export_dialog() { + let mut harness = open_project(); + harness.state_mut().ui.windows.export = true; + let ctx = harness.ctx.clone(); + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &ctx, "command.run", &json!({"id": "file.close"})); + + assert_eq!(reply["ok"], true); + assert!(!harness.state().session.project_open); + assert!(!harness.state().ui.windows.export, "Close dismisses the dialog before the next frame"); +} + +#[test] +fn uploaded_project_replacement_discards_the_old_resize() { + let mut harness = open_project(); + let bytes = harness.state().session.to_project_bytes().unwrap(); + let resource = std::sync::Arc::new(vec![0; 2_097_152]); + let old_resource = std::sync::Arc::downgrade(&resource); + harness.state_mut().session.doc.resources.insert("lifetime-probe.bin".into(), resource); + let old_mesh = std::sync::Arc::downgrade(&harness.state().session.mesh); + harness.state_mut().start_resize(0, 128); + + assert!(harness.state().resize.is_some()); + + let resize_progress = std::sync::Arc::downgrade(&harness.state().resize.as_ref().unwrap().progress); + let owners_before = resize_progress.strong_count(); + + texturecraft_ui_egui::web_files::load(harness.state_mut(), "replacement.tcraft", bytes); + + assert!(harness.state().session.project_open); + assert!(harness.state().resize.is_none(), "the previous project's resize must be discarded"); + + let owners_after = resize_progress.strong_count(); + eprintln!("upload resize progress owners: {owners_before} before, {owners_after} after replacement"); + + assert!(owners_after < owners_before && owners_after <= 1); + + assert_eventually_released(&resize_progress); + assert_eventually_released(&old_mesh); + assert_eventually_released(&old_resource); + eprintln!( + "released old mesh and 2_097_152-byte resource after replacement: mesh={}, resource={}, progress={}", + old_mesh.strong_count(), + old_resource.strong_count(), + resize_progress.strong_count() + ); + + harness.run_steps(3); + + assert!(!harness.state().session.modified && !harness.state().session.can_undo(), "the old resize must not change the uploaded project"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn file_new_discards_the_old_resize() { + let path = std::env::temp_dir().join(format!("texturecraft-file-new-resize-{}.obj", std::process::id())); + std::fs::write(&path, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut harness = open_project(); + harness.state_mut().start_resize(0, 128); + + assert!(harness.state().resize.is_some()); + + let result = harness.state_mut().run("file.new", json!({"mesh": path.display().to_string(), "resolution": 128})); + let _ = std::fs::remove_file(&path); + + assert!(result.is_some()); + assert!(harness.state().session.project_open); + assert!(harness.state().resize.is_none(), "the previous project's resize must be discarded"); + + harness.run_steps(3); + + assert!(!harness.state().session.modified && !harness.state().session.can_undo(), "the old resize must not change the mesh project"); +} + +#[test] +fn closed_session_rejects_project_control_operations() { + for (method, params) in [("ui.bake.start", json!({"ts": 0})), ("debug.paintTest", json!({"from": [640, 400], "to": [650, 400], "frames": 2}))] { + let mut harness = empty(); + let ctx = harness.ctx.clone(); + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &ctx, method, ¶ms); + + assert_eq!(reply["ok"], false, "{method}: {reply}"); + assert!(reply["error"].as_str().unwrap().contains("no project is open")); + assert!(harness.state().bake.is_none()); + assert!(harness.state().session.bake_preview.is_none()); + + harness.run_steps(3); + + assert!(!harness.state().session.modified && !harness.state().session.can_undo()); + } +} + +#[test] +fn close_releases_the_layer_thumbnail_snapshot() { + for _ in 0..2 { + let mut harness = open_project(); + let old_mesh = std::sync::Arc::downgrade(&harness.state().session.mesh); + let old_maps: Vec<_> = harness + .state() + .session + .doc + .baked + .values() + .flat_map(|maps| maps.maps.values()) + .map(|pixels| (std::sync::Arc::downgrade(pixels), std::mem::size_of_val(pixels.as_slice()))) + .collect(); + let tracked_bytes: usize = old_maps.iter().map(|(_, bytes)| bytes).sum(); + + invoke(&mut harness, "file.close"); + + assert!(!harness.state().session.project_open); + assert_eventually_released(&old_mesh); + for (pixels, _) in &old_maps { + assert_eventually_released(pixels); + } + eprintln!( + "closed thumbnail snapshot: mesh owners={}, {} baked-map allocations ({} bytes) released", + old_mesh.strong_count(), + old_maps.len(), + tracked_bytes + ); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 4d5626dd..d58f564b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -18,6 +18,7 @@ mod display_post_effects; mod effect_decal; mod effect_rows; mod effect_sliders; +mod empty_start; mod export_template_guards; mod file_dialogs; mod fill_channel_image; @@ -46,6 +47,7 @@ mod polygon_fill; mod project_config; mod properties_popup; mod rail; +mod reference_order; mod rename_anchor; mod reset_ui; mod shelf_click; @@ -60,7 +62,6 @@ mod skew_paint; mod smudge_channels; mod snapped_lines; mod split_divider; -mod start_window; mod template_invert; mod tool_availability; mod tool_settings_saved; diff --git a/crates/ui-egui/tests/it/reference_order.rs b/crates/ui-egui/tests/it/reference_order.rs new file mode 100644 index 00000000..2afce36d --- /dev/null +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -0,0 +1,194 @@ +//! The order of the menus, the tool shelf and the right bar, and what is enabled with no project open, +//! follow the reference app's measured layout. Items TextureCraft has no equivalent of are absent. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::Session; +use texturecraft_ui_egui::{TextureCraftApp, menus}; + +fn harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness +} + +fn buttons_in(harness: &Harness<'static, TextureCraftApp>, x: std::ops::Range) -> Vec<(f32, String, bool)> { + let mut found: Vec<(f32, String, bool)> = harness + .get_all_by_role(Role::Button) + .filter(|button| x.contains(&button.rect().min.x)) + .filter_map(|button| { + let node = button.accesskit_node(); + node.label().map(|label| (button.rect().min.y, label.to_string(), node.is_disabled())) + }) + .collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + found +} + +fn named<'a>(found: &'a [(f32, String, bool)], name: &str) -> Option<&'a (f32, String, bool)> { + found.iter().find(|(_, label, _)| label == name || label.starts_with(&format!("{name} ("))) +} + +#[test] +fn every_menu_lists_its_items_in_the_reference_order() { + // Items the reference has and TextureCraft lacks are absent; TextureCraft's own sit where they fit + let expected = [ + "File: New project... | Open... | - | Open sample project... | - | Close | - | Save | Save as... | More save options > Save a copy... | Remove unused resources... | - | Import resources... | Import MaterialX material... | Import PBR texture folder... | Import material... | Export Textures... | Export Mesh... | - | Quit", + "Edit: Undo | Redo | Project Configuration... | Reimport mesh | Settings...", + "Mode: Bake Mesh Maps | Painting | Rendering (path traced)", + "Window: Views > Assets | Views > Common Settings | Views > Display Settings | Views > History | Views > Layers | Views > Log | Views > Mesh Map Bakers | Views > Mesh Map Settings | Views > Properties | Views > Shader Settings | Views > Texture Sets | Views > Texture Set Settings | - | Save UI Layout > Save current layout... | Load UI Layout | Layouts > Save current layout as... | Layouts > Manage layouts... | - | Hide UI | Reset panel layout | Reset UI", + "Viewport: Display material | Display next channel | Display previous channel | Display next mesh map | Display previous mesh map | UV checker | - | Frame texture set | Show entire mesh | Front view | Back view | Left view | Right view | Top view | Bottom view | - | Perspective | Orthographic | - | 3D/2D views | 3D view only | 2D view only | - | Navigation buttons | - | Enable quick mask | Edit quick mask | Invert quick mask", + "Help: Documentation... | Shortcuts list... | - | Join the community (Discord)... | ArtCraft website... | Report a bug... | Show log... | - | Check for Updates... | About TextureCraft...", + ]; + let actual: Vec = menus::TOP + .iter() + .map(|top| { + let items: Vec = menus::CATALOG + .iter() + .filter(|item| item.menu == *top) + .map(|item| match item.sub { + Some(sub) => format!("{sub} > {}", item.label), + None => item.label.to_string(), + }) + .collect(); + format!("{top}: {}", items.join(" | ")) + }) + .collect(); + for (expected, actual) in expected.iter().zip(&actual) { + assert_eq!(expected, actual); + } + assert_eq!(menus::TOP, ["File", "Edit", "Mode", "Window", "Viewport", "Help"], "the reference's top menus, minus the scripting ones"); +} + +#[test] +fn the_tool_shelf_keeps_the_reference_order() { + let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let shelf = buttons_in(&harness, 0.0..60.0); + let order = ["Paint", "Eraser", "Path", "Projection", "Polygon fill", "Smudge", "Clone", "Material picker", "Geometry mask"]; + let row_positions: Vec = order.iter().map(|name| named(&shelf, name).unwrap_or_else(|| panic!("{name} on the shelf: {shelf:?}")).0).collect(); + + assert!(row_positions.windows(2).all(|pair| pair[0] < pair[1]), "{row_positions:?}"); +} + +#[test] +fn the_right_bar_keeps_the_reference_order() { + let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let bar = buttons_in(&harness, 1562.0..1600.0); + let order = ["Export textures", "Log", "Display Settings", "Shader Settings", "History"]; + let row_positions: Vec = order.iter().map(|name| named(&bar, name).unwrap_or_else(|| panic!("{name} on the bar: {bar:?}")).0).collect(); + + assert!(row_positions.windows(2).all(|pair| pair[0] < pair[1]), "{row_positions:?}"); +} + +#[test] +fn the_blank_screen_enables_what_the_reference_enables() { + let harness = harness(Session::closed().unwrap()); + let shelf = buttons_in(&harness, 0.0..60.0); + for name in ["Paint", "Eraser", "Path", "Projection", "Polygon fill", "Smudge", "Clone", "Material picker", "Geometry mask"] { + assert!(named(&shelf, name).unwrap().2, "{name} should be disabled with no project"); + } + let bar = buttons_in(&harness, 1562.0..1600.0); + for name in ["Export textures", "Log", "Display Settings", "Shader Settings", "History"] { + assert!(!named(&bar, name).unwrap().2, "{name} on the right bar stays enabled"); + } + + // Top bar: layout stays on; camera type and the three modes are greyed, Painting shown as the current mode + let top = buttons_in(&harness, 600.0..1562.0); + let on = |name: &str| !named(&top, name).unwrap_or_else(|| panic!("{name}: {top:?}")).2; + + assert!(on("3D/2D views"), "the layout selector works without a project"); + assert!(!on("Perspective") && !on("Painting") && !on("Bake Mesh Maps") && !on("Rendering (path traced)")); + + let painting = + harness.get_all_by_role(Role::Button).find(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("Painting"))).unwrap(); + + assert_eq!(painting.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "Painting is the shown mode"); +} + +#[test] +fn the_blank_screen_menus_match_the_measured_enabled_states() { + let harness = harness(Session::closed().unwrap()); + let app = harness.state(); + let disabled = [ + "file.close", + "file.save", + "file.saveAs", + "file.saveCopy", + "file.removeUnused", + "ui.export", + "file.exportMesh", + "edit.undo", + "edit.redo", + "ui.projectConfig", + "file.reimportMesh", + "ui.mode.bake", + "ui.mode.paint", + "ui.mode.render", + "viewport.displayMaterial", + "viewport.nextChannel", + "viewport.previousChannel", + "viewport.nextMeshMap", + "viewport.previousMeshMap", + "viewport.quickMask", + "viewport.quickMask.edit", + "viewport.quickMask.invert", + ]; + for id in disabled { + assert!(!menus::enabled(app, id), "{id} is disabled on the blank screen"); + } + let enabled = [ + "ui.newProject", + "file.open", + "project.sample", + "ui.quit", + "ui.settings", + "ui.view.assets", + "ui.view.layers", + "ui.view.properties", + "ui.view.textureSetList", + "ui.view.textureSetSettings", + "ui.view.display", + "ui.view.history", + "ui.view.log", + "ui.view.shader", + "ui.hideUi", + "ui.resetUi", + "ui.layout.save", + "ui.layout.load", + "viewport.frame", + "ui.help.docs", + "ui.help.shortcuts", + "ui.help.bug", + "ui.about", + ]; + for id in enabled { + assert!(menus::enabled(app, id), "{id} is enabled on the blank screen"); + } + for id in ["ui.view.bakeSettings", "ui.view.bakeMaps", "ui.view.meshMapBakers"] { + assert!(!menus::enabled(app, id), "{id} belongs to Baking mode"); + } +} + +#[test] +fn opening_a_project_enables_the_same_items() { + let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let app = harness.state(); + for id in [ + "file.close", + "file.save", + "file.saveAs", + "file.saveCopy", + "ui.export", + "file.exportMesh", + "ui.projectConfig", + "ui.mode.bake", + "ui.mode.paint", + "ui.mode.render", + "viewport.displayMaterial", + "viewport.quickMask", + ] { + assert!(menus::enabled(app, id), "{id} is enabled with a project"); + } +} diff --git a/crates/ui-egui/tests/it/start_window.rs b/crates/ui-egui/tests/it/start_window.rs deleted file mode 100644 index 9c5415b4..00000000 --- a/crates/ui-egui/tests/it/start_window.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! The start window: New project opens its dialog, Continue keeps the open project, and the -//! startup choice is a setting. - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use texturecraft_ui_egui::TextureCraftApp; - -fn harness() -> Harness<'static, TextureCraftApp> { - let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.state_mut().ui.windows.start = true; - h.run_steps(3); - h -} - -#[test] -fn start_window_choices() { - let mut h = harness(); - h.get_by_label("New project...").click(); - h.run_steps(3); - assert!(!h.state().ui.windows.start && h.state().ui.windows.new_project, "New project opens its dialog"); - - let mut h = harness(); - h.get_by_label("Show at startup").click(); - h.get_by_label("Continue with the sample project").click(); - h.run_steps(3); - assert!(!h.state().ui.windows.start && !h.state().ui.windows.new_project); - assert!(!h.state().ui.prefs.start_window, "unticked: not shown next time"); - assert_eq!(h.state().session.doc.project.texture_sets.len(), 2, "the sample stays open"); -} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index d3b6481f..eab48e4e 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -23,14 +23,85 @@ fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { harness.run_steps(3); } -fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { - h.run_steps(6); - let img = h.render().unwrap_or_else(|e| panic!("{name}: {e}")); +fn save(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { + harness.run_steps(6); + let img = harness.render().unwrap_or_else(|e| panic!("{name}: {e}")); let path = dir.join(format!("{name}.png")); img.save(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); eprintln!("wrote {}", path.display()); } +#[test] +#[ignore] +fn empty_start_snapshot() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::Session::closed().unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + + save(&mut harness, &output_dir, "empty-start"); +} + +/// Closing rejects a same-frame capture, then releases both rendered view targets. +#[test] +#[ignore] +fn close_releases_view_targets_and_rejects_immediate_capture() { + let session = texturecraft_engine::Session::closed().unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(960.0, 640.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + + for mesh in ["cube", "plane"] { + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": mesh, "resolution": 128})).is_some()); + harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Split; + harness.run_steps(4); + harness.render().unwrap(); + let render_state = harness.state().render_state.as_ref().unwrap().clone(); + let report = |stage: &str| { + render_state.device.poll(eframe::wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap(); + if let Some(report) = render_state.device.generate_allocator_report() { + eprintln!( + "{mesh} {stage}: {} live GPU allocations, {} allocated bytes, {} reserved bytes", + report.allocations.len(), + report.total_allocated_bytes, + report.total_reserved_bytes + ); + } else { + eprintln!("{mesh} {stage}: allocator report unavailable on this backend"); + } + }; + assert!(texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_some()); + assert!(texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_2D).is_some()); + report("before close"); + let ctx = harness.ctx.clone(); + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &ctx, "command.run", &serde_json::json!({"id": "file.close"})); + + assert_eq!(reply["ok"], true); + assert!(texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_none()); + { + let renderer = render_state.renderer.read(); + let gpu = renderer.callback_resources.get::().unwrap(); + assert!( + gpu.renderer.read_view(&render_state.device, &render_state.queue, texturecraft_ui_egui::viewport::VIEW_3D).is_some(), + "the stale target still exists before the next UI frame" + ); + } + + harness.run_steps(2); + harness.render().unwrap(); + + { + let renderer = render_state.renderer.read(); + let gpu = renderer.callback_resources.get::().unwrap(); + for view in [texturecraft_ui_egui::viewport::VIEW_3D, texturecraft_ui_egui::viewport::VIEW_2D] { + assert!(gpu.renderer.read_view(&render_state.device, &render_state.queue, view).is_none()); + } + } + report("after close"); + } +} + /// Check the saved-brush controls without a GPU adapter #[test] #[ignore] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d1adcc13..54a30b48 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -256,6 +256,8 @@ Through `command_run`, every `file.*` command but `file.close` and `file.removeU a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. +`file.close` leaves no project open: `session.inspect` then reports `projectOpen: false`, `command.list` marks every command but the project-independent ones as not enabled: the ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`), `project.inspect`, `viewport.frame`, `project.templates`, the `export.preset*` commands (`export.presets`, `export.preset.get`, `export.preset.save`, `export.preset.remove`) and the library and preset listings (`brush.preset.list`, `alpha.list`, `filter.list`, `material.list`, `mask.smart.list`, `text.fonts`), each still subject to its own enabled check. The rest are refused with "no project is open" until a project is opened or created. A `texturecraft --control` run starts with the sample project (an empty material ball with `--empty`); the app without `--control` starts with no project. + | Tool | Params | Notes | |---|---|---| | `session_inspect` | | The whole session as JSON | diff --git a/docs/features.md b/docs/features.md index 70088b2d..57f28206 100644 --- a/docs/features.md +++ b/docs/features.md @@ -179,8 +179,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA strip, and Settings › Interface › System title bar for the system's frame instead. - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed them. -- A **start window** at launch: a new project, a project file, a recent project or the sample - (Settings › Interface › Start window). +- **No project at launch**: empty views, panels and toolbars until you create or open one (File › + New project, Open, Recent projects, Open sample project); File › Close returns to that state. - A **data folder** of your choice for autosaves, smart materials, presets, templates and UI layouts, on any drive (Settings › Folders; `Documents/TextureCraft` by default). - A **shortcut editor** with conflict detection, listing every menu item and every command a key can run (commands that need a path, name or similar are left out), and every shortcut shown in its tooltip. diff --git a/docs/parity.md b/docs/parity.md index 581369f6..70d417f8 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -14,7 +14,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Close | `file.close` | Ctrl+F4 | live | | Save | `file.save` | Ctrl+S | live | | Save as... | `file.saveAs` | Ctrl+Shift+S | live | -| Save a copy... | `file.saveCopy` | | live | +| More save options ▸ Save a copy... | `file.saveCopy` | | live | | Remove unused resources... | `file.removeUnused` | | live | | Import resources... | `resource.import` | | live | | Import MaterialX material... | `file.importMaterialX` | | live |