From bac934d5a55ec57cb62dc2b2a8eb048dcf230f2f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 17 Nov 2026 22:00:22 +0100 Subject: [PATCH 1/8] Start with no project open; File > Close returns to the empty state Removes the start window and the startup sample project. With no project open the views are empty (view picker only), Layers and Properties are empty, project-only menu items and commands are disabled, and the status bar shows only the version. --- README.md | 4 +- apps/texturecraft-web/src/web.rs | 18 +--- apps/texturecraft/src/main.rs | 25 ++--- crates/engine/src/commands.rs | 36 ++++++- crates/engine/src/file_cmds.rs | 3 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/session.rs | 13 +++ crates/engine/src/tool_availability.rs | 3 + crates/engine/tests/it/closed_session.rs | 50 ++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/dock.rs | 20 +++- crates/ui-egui/src/docking.rs | 5 + crates/ui-egui/src/lib.rs | 8 ++ crates/ui-egui/src/menus.rs | 9 +- crates/ui-egui/src/state.rs | 6 -- crates/ui-egui/src/toolbar.rs | 23 +---- crates/ui-egui/src/updates_ui.rs | 1 - crates/ui-egui/src/viewport.rs | 44 ++++++++- crates/ui-egui/src/windows.rs | 80 +-------------- crates/ui-egui/tests/it/empty_start.rs | 119 +++++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 2 +- crates/ui-egui/tests/it/start_window.rs | 30 ------ docs/features.md | 4 +- 23 files changed, 324 insertions(+), 182 deletions(-) create mode 100644 crates/engine/tests/it/closed_session.rs create mode 100644 crates/ui-egui/tests/it/empty_start.rs delete mode 100644 crates/ui-egui/tests/it/start_window.rs 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..1bf59a17 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -41,8 +41,9 @@ 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()?; + step(0.5, "Preparing the app…").await; + // The app starts with no project, like File > Close + let session = Session::closed(); step(0.8, "Starting the renderer…").await; let mut options = eframe::WebOptions::default(); if query().contains("webgl") @@ -56,7 +57,6 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { 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 +137,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..d1b3d2d2 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -1,6 +1,6 @@ //! TextureCraft desktop app. //! -//! Usage: `texturecraft [project.tcraft | mesh.glb] [--control ] [--empty] [--version]` +//! Usage: `texturecraft [project.tcraft | mesh.glb] [--control ] [--version]` #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -38,7 +38,6 @@ fn version() -> String { struct Args { file: Option, control: Option, - empty: bool, gpu: Option, power_pref: Option, } @@ -48,7 +47,7 @@ fn parse_args() -> Result, String> { } fn parse_args_from>(it: I) -> Result, String> { - let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None }; + let mut args = Args { file: None, control: None, gpu: None, power_pref: None }; let mut it = it.into_iter(); while let Some(a) = it.next() { match a.as_str() { @@ -75,7 +74,8 @@ fn parse_args_from>(it: I) -> Result let p = it.next().ok_or("--power-pref needs high, low, or none")?; args.power_pref = Some(gpu::parse_power_preference(&p)?); } - "--empty" => args.empty = true, + // Kept so old command lines still work: the app starts without a project anyway + "--empty" => {} f if !f.starts_with('-') => args.file = Some(f.to_string()), other => return Err(format!("unknown option `{other}`")), } @@ -90,18 +90,8 @@ fn initial_session(args: &Args) -> Session { Err(e) => eprintln!("texturecraft: could not open {f}: {e}"), } } - if !args.empty - && let Ok(s) = texturecraft_engine::sample_session(2048, 512) - { - return s; - } - match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) { - Ok(s) => s, - Err(e) => { - eprintln!("texturecraft: {e}"); - std::process::exit(1); - } - } + // No file given (or it did not open): start with no project, like File > Close + Session::closed() } fn icon() -> Option { @@ -220,8 +210,6 @@ 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( APP_NAME, options, @@ -238,7 +226,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())); diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 06b74adb..a058fa84 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -88,6 +88,38 @@ 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. +fn works_without_project(id: &str) -> bool { + matches!( + id, + "file.open" + | "file.new" + | "project.new" + | "project.sample" + | "project.inspect" + | "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) } @@ -96,7 +128,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; @@ -116,7 +148,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 e4d17f53..f68848e5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -660,8 +660,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/lib.rs b/crates/engine/src/lib.rs index 34b6bf3a..33d67b9c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -65,7 +65,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 cb970042..db6f9a9b 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -363,6 +363,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, and only the commands that open or create a + /// project run (see [`crate::commands::check_enabled`]). + pub project_open: bool, pub modified: bool, /// Bumps on every document change. pub revision: u64, @@ -421,6 +425,7 @@ impl Session { path_draft: None, path_steps: Default::default(), path: None, + project_open: true, modified: false, revision: 1, log: Vec::new(), @@ -431,6 +436,14 @@ impl Session { }) } + /// The empty state: no project is open. Holds a tiny placeholder document that the UI never + /// shows; every command except opening or creating a project is refused. + pub fn closed() -> Session { + let mut session = Session::new_project("", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 128).expect("the placeholder project is valid"); + session.project_open = false; + session + } + /// Replace this session with `next` (another project), keeping the viewport size and the /// user's export presets and project templates. 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 392388e3..10478d94 100644 --- a/crates/engine/src/tool_availability.rs +++ b/crates/engine/src/tool_availability.rs @@ -7,6 +7,9 @@ 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..a40570c5 --- /dev/null +++ b/crates/engine/tests/it/closed_session.rs @@ -0,0 +1,50 @@ +//! The empty state (no project open): only commands that open or create a project run, 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 s = Session::closed(); + assert!(!s.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 s, id, &json!({})).unwrap_err(); + assert!(matches!(error, EngineError::Disabled { .. }), "{id}: {error}"); + } + assert!(!s.can_undo(), "nothing was changed"); + assert!(!s.tool_usable(Tool::Paint), "no tool can act without a project"); +} + +#[test] +fn a_closed_session_lists_only_the_opening_commands_as_enabled() { + let s = Session::closed(); + for id in ["file.open", "file.new", "project.new", "project.sample"] { + assert!(check_enabled(find(id).unwrap(), &s).is_ok(), "{id} runs with no project"); + } + let enabled: Vec<&str> = command_specs().iter().filter(|spec| check_enabled(spec, &s).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 s = Session::closed(); + execute(&mut s, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); + assert!(s.project_open); + execute(&mut s, "layer.add.paint", &json!({})).unwrap(); +} + +#[test] +fn close_returns_to_the_empty_state_and_keeps_the_user_presets() { + let mut s = open_project(); + s.modified = true; + execute(&mut s, "file.close", &json!({})).unwrap(); + assert!(!s.project_open && !s.modified && s.path.is_none()); + assert!(execute(&mut s, "file.close", &json!({})).is_err(), "closing again has nothing to close"); + execute(&mut s, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); + assert!(s.project_open, "a project can be created again"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 7c61e03b..17c62593 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -6,6 +6,7 @@ mod bake_checks; mod bake_resolution; mod bake_settings; mod bake_tiles; +mod closed_session; mod color_selection; mod content_effects; mod export_colour_space; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index b168194d..6ddc740e 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -41,6 +41,10 @@ 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 @@ -143,7 +147,8 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); // Wrap in a narrow column so rows stay within the panel - ui.horizontal_wrapped(|ui| { + 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 = 4.0; @@ -175,7 +180,11 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { if icon_button(ui, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), false, 22.0).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(); @@ -1481,6 +1490,9 @@ 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); @@ -1507,6 +1519,10 @@ 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..fee32f5d 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -480,6 +480,11 @@ 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), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 74d92580..e4a68fcd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -303,6 +303,10 @@ impl TextureCraftApp { if matches!(id, "file.open" | "file.close" | "project.new" | "project.sample") { self.pbr_import = None; } + // The empty state has no baking or rendering to show + if id == "file.close" { + self.ui.mode = state::Mode::Painting; + } if let Some(from) = glide_from.filter(|f| *f != self.session.camera) { self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); self.session.camera = from; @@ -760,6 +764,10 @@ impl eframe::App for TextureCraftApp { fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); let t0 = 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); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9c66fd45..c273e0b6 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -113,6 +113,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.render") +} + /// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { if let Some(panel) = crate::docking::view_panel(id) { @@ -124,7 +129,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 @@ -133,7 +138,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/state.rs b/crates/ui-egui/src/state.rs index 3b7d7a83..58fad475 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, @@ -122,8 +119,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, @@ -146,7 +141,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 ce998917..7627c272 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -466,7 +466,11 @@ pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { card(ui, &tokens, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, RAIL_CARD_PADDING, |ui| { ui.spacing_mut().item_spacing.y = RAIL_ICON_GAP; crate::rail_popup::begin_rail(ui.ctx(), ui.max_rect()); - if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE).clicked() { + let export_on = crate::menus::enabled(app, "ui.export"); + let export = ui.add_enabled_ui(export_on, |ui| { + icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE) + }); + if export.inner.clicked() { app.ui.windows.export = !app.ui.windows.export; } @@ -515,23 +519,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 d7030d9c..419ee64f 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -60,6 +60,15 @@ 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); + } + 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. let pending_2d_endpoint = if !app.session.stroke_active() || !tool_acts(app) { @@ -133,6 +142,27 @@ 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; @@ -425,10 +455,13 @@ 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 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!({})); } @@ -441,7 +474,8 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { 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; @@ -457,11 +491,15 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { 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() { + 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); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 5650c4de..a897761e 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, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - start(app, ctx); new_project(app, ctx); about(app, ctx); settings(app, ctx); @@ -389,78 +388,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; @@ -659,9 +586,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"))); @@ -1216,6 +1140,10 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); + // Nothing to export without a project (closed, or a saved layout that left it open) + if !app.session.project_open { + app.ui.windows.export = false; + } if !app.ui.windows.export { return; } 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..b4bddf88 --- /dev/null +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -0,0 +1,119 @@ +//! 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 h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn empty() -> Harness<'static, TextureCraftApp> { + harness(Session::closed()) +} + +fn open_project() -> Harness<'static, TextureCraftApp> { + harness(texturecraft_engine::sample_session(256, 64).unwrap()) +} + +fn invoke(h: &mut Harness<'static, TextureCraftApp>, id: &str) { + let ctx = h.ctx.clone(); + menus::invoke(h.state_mut(), &ctx, id); + h.run_steps(3); +} + +#[test] +fn starts_with_no_project_and_no_popup() { + let h = empty(); + let ui = &h.state().ui; + assert!(!h.state().session.project_open); + assert!(!ui.windows.new_project && !ui.windows.about && !ui.windows.settings && !ui.windows.export, "no window opens by itself"); + assert!(h.query_by_label("Continue with the sample project").is_none() && h.query_by_label("Recent projects").is_none(), "no start window"); + assert!(h.query_by_label("No properties found").is_some(), "Properties says it has nothing"); +} + +#[test] +fn project_items_are_disabled_without_a_project() { + let h = empty(); + let app = h.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.frame", "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.mode.paint", "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!(empty.query_by_label("Default camera").is_none(), "no camera picker"); + assert!(empty.query_all_by_label("Material").count() >= 1, "the view picker stays"); + let open = open_project(); + assert!(open.query_by_label("Default camera").is_some(), "with a project the camera picker is there"); +} + +#[test] +fn the_status_bar_has_the_version_but_no_frame_time_or_layer_memory() { + for h in [empty(), open_project()] { + assert!(h.query_by_label_contains("Version:").is_some()); + assert!(h.query_by_label_contains("Layer memory").is_none()); + assert!(h.query_by_label_contains(" ms").is_none(), "no frame time"); + } +} + +#[test] +fn close_unloads_the_project_back_to_the_empty_state() { + let mut h = open_project(); + assert!(h.state().session.project_open && h.state().session.set_count() == 2); + invoke(&mut h, "file.close"); + assert!(!h.state().session.project_open, "Close leaves no project open"); + assert!(h.state().session.path.is_none() && !h.state().session.modified); + assert!(h.query_by_label("No properties found").is_some()); + assert!(h.query_by_label("Default camera").is_none()); + assert!(!menus::enabled(h.state(), "file.save")); +} + +#[test] +fn creating_or_opening_a_project_from_the_empty_state_works() { + let mut h = empty(); + assert!(h.state_mut().run("project.new", json!({"mesh": "cube", "resolution": 128})).is_some()); + h.run_steps(3); + assert!(h.state().session.project_open); + assert!(menus::enabled(h.state(), "file.save") && h.query_by_label("Default camera").is_some()); + + invoke(&mut h, "file.close"); + invoke(&mut h, "ui.newProject"); + assert!(h.state().ui.windows.new_project, "New project opens its dialog from the empty state"); + let mut h = empty(); + invoke(&mut h, "project.sample"); + assert!(h.state().session.project_open && h.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 h = 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 h, item.id); + } + for mode in ["ui.mode.bake", "ui.mode.render", "ui.mode.paint"] { + invoke(&mut h, mode); + } + for id in ["ui.layout.2d", "ui.layout.3d", "ui.layout.split"] { + invoke(&mut h, id); + } + assert!(!h.state().session.project_open, "none of these opened a project"); + assert!(!h.state().session.can_undo(), "and none changed it"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 4f454304..5389562d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -37,7 +37,7 @@ mod shift_lines_2d; mod shortcut_keys; mod skew_paint; mod split_divider; -mod start_window; +mod empty_start; mod tool_availability; mod toolbar; 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/docs/features.md b/docs/features.md index 139d6a27..25f0d8fa 100644 --- a/docs/features.md +++ b/docs/features.md @@ -149,8 +149,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, and every shortcut shown in its tooltip. From 18c8538c3d0e14396130cbbe9e44f65a6b1d2fee Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 17 Nov 2026 22:11:00 +0100 Subject: [PATCH 2/8] Keep the control-run start, refuse project commands in headless close, grey view buttons without a project Review fixes: --control runs still start with the sample project, headless save/export/import refuse after file.close, session.inspect reports projectOpen, web drops need a project, the template button and view buttons are disabled without a project. --- apps/texturecraft-web/src/web.rs | 2 +- apps/texturecraft/src/main.rs | 34 ++++++++++--- crates/automation/src/headless.rs | 12 +++++ crates/engine/src/file_cmds.rs | 2 +- crates/engine/src/inspect.rs | 1 + crates/engine/src/session.rs | 6 +-- crates/engine/tests/it/closed_session.rs | 25 ++++++++-- crates/ui-egui/src/dock.rs | 62 ++++++++++++------------ crates/ui-egui/src/toolbar.rs | 6 +++ crates/ui-egui/src/viewport.rs | 22 ++++----- crates/ui-egui/src/web_files.rs | 4 ++ crates/ui-egui/src/windows.rs | 2 +- crates/ui-egui/tests/it/close_unsaved.rs | 2 +- crates/ui-egui/tests/it/empty_start.rs | 62 ++++++++++++++++++++---- crates/ui-egui/tests/it/main.rs | 2 +- docs/control-protocol.md | 2 + 16 files changed, 178 insertions(+), 68 deletions(-) diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index 1bf59a17..4c9640de 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -43,7 +43,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { // 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(); + 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") diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index d1b3d2d2..af950279 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -1,6 +1,6 @@ //! TextureCraft desktop app. //! -//! Usage: `texturecraft [project.tcraft | mesh.glb] [--control ] [--version]` +//! Usage: `texturecraft [project.tcraft | mesh.glb] [--control ] [--empty] [--version]` #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -38,6 +38,8 @@ 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, } @@ -47,7 +49,7 @@ fn parse_args() -> Result, String> { } fn parse_args_from>(it: I) -> Result, String> { - let mut args = Args { file: None, control: None, gpu: None, power_pref: None }; + let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None }; let mut it = it.into_iter(); while let Some(a) = it.next() { match a.as_str() { @@ -74,8 +76,7 @@ fn parse_args_from>(it: I) -> Result let p = it.next().ok_or("--power-pref needs high, low, or none")?; args.power_pref = Some(gpu::parse_power_preference(&p)?); } - // Kept so old command lines still work: the app starts without a project anyway - "--empty" => {} + "--empty" => args.empty = true, f if !f.starts_with('-') => args.file = Some(f.to_string()), other => return Err(format!("unknown option `{other}`")), } @@ -90,8 +91,29 @@ fn initial_session(args: &Args) -> Session { Err(e) => eprintln!("texturecraft: could not open {f}: {e}"), } } - // No file given (or it did not open): start with no project, like File > Close - Session::closed() + // A script-driven run (--control) starts with the sample project (or, with --empty, an empty + // material ball), as before; an interactive start has no project open, like File > Close + if args.control.is_some() { + if !args.empty + && let Ok(s) = texturecraft_engine::sample_session(2048, 512) + { + return s; + } + return match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) { + Ok(s) => s, + Err(e) => { + eprintln!("texturecraft: {e}"); + std::process::exit(1); + } + }; + } + match Session::closed() { + Ok(s) => s, + Err(e) => { + eprintln!("texturecraft: {e}"); + std::process::exit(1); + } + } } fn icon() -> Option { diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 0af8274d..0d34e24e 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -85,6 +85,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 ")), @@ -196,6 +201,7 @@ impl Headless { /// 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)?) } @@ -203,6 +209,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)?; @@ -218,12 +225,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) { @@ -243,12 +252,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}"), @@ -262,6 +273,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(); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f68848e5..ee7ff3bd 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -660,7 +660,7 @@ use unsupported as export_textures; use unsupported as export_mesh; fn close(s: &mut Session, _: &Value) -> Result { - s.switch_to(Session::closed()); + s.switch_to(Session::closed()?); Ok(Value::Null) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 3a2e348c..3b0b34e9 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -185,6 +185,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { pub fn session(s: &Session) -> Value { let ts = s.ts(); json!({ + "projectOpen": s.project_open, "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, diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index db6f9a9b..5b664756 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -438,10 +438,10 @@ impl Session { /// The empty state: no project is open. Holds a tiny placeholder document that the UI never /// shows; every command except opening or creating a project is refused. - pub fn closed() -> Session { - let mut session = Session::new_project("", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 128).expect("the placeholder project is valid"); + pub fn closed() -> Result { + let mut session = Session::new_project("", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 128)?; session.project_open = false; - session + Ok(session) } /// Replace this session with `next` (another project), keeping the viewport size and the diff --git a/crates/engine/tests/it/closed_session.rs b/crates/engine/tests/it/closed_session.rs index a40570c5..9c96a23e 100644 --- a/crates/engine/tests/it/closed_session.rs +++ b/crates/engine/tests/it/closed_session.rs @@ -10,7 +10,7 @@ fn open_project() -> Session { #[test] fn a_closed_session_refuses_commands_that_need_a_project() { - let mut s = Session::closed(); + let mut s = Session::closed().unwrap(); assert!(!s.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 s, id, &json!({})).unwrap_err(); @@ -22,7 +22,7 @@ fn a_closed_session_refuses_commands_that_need_a_project() { #[test] fn a_closed_session_lists_only_the_opening_commands_as_enabled() { - let s = Session::closed(); + let s = Session::closed().unwrap(); for id in ["file.open", "file.new", "project.new", "project.sample"] { assert!(check_enabled(find(id).unwrap(), &s).is_ok(), "{id} runs with no project"); } @@ -32,7 +32,7 @@ fn a_closed_session_lists_only_the_opening_commands_as_enabled() { #[test] fn creating_a_project_from_the_closed_state_opens_it() { - let mut s = Session::closed(); + let mut s = Session::closed().unwrap(); execute(&mut s, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); assert!(s.project_open); execute(&mut s, "layer.add.paint", &json!({})).unwrap(); @@ -48,3 +48,22 @@ fn close_returns_to_the_empty_state_and_keeps_the_user_presets() { execute(&mut s, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); assert!(s.project_open, "a project can be created again"); } + +#[test] +fn the_libraries_and_presets_still_answer_without_a_project() { + let mut s = 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 s, id, &json!({})).unwrap_or_else(|e| panic!("{id}: {e}")); + } + assert_eq!(texturecraft_engine::inspect::session(&s)["projectOpen"], json!(false)); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 6ddc740e..434d48ca 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -148,39 +148,41 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { // Wrap in a narrow column so rows stay within the panel 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 = 4.0; - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); - egui::ComboBox::from_id_salt("layer_channel").width(86.0).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())); + 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 = 4.0; + let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + egui::ComboBox::from_id_salt("layer_channel").width(86.0).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())); + } + }); + 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)); + } + }) + .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, 22.0).clicked() { + app.run("layer.add.paint", Value::Null); } - }); - 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)); + if icon_button(ui, ic::PAINT_BUCKET, tr("Add fill layer"), false, 22.0).clicked() { + app.run("layer.add.fill", Value::Null); + } + if icon_button(ui, ic::FOLDER_SIMPLE, tr("Add folder"), false, 22.0).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, 22.0).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, 22.0).clicked() { - app.run("layer.add.paint", Value::Null); - } - if icon_button(ui, ic::PAINT_BUCKET, tr("Add fill layer"), false, 22.0).clicked() { - app.run("layer.add.fill", Value::Null); - } - if icon_button(ui, ic::FOLDER_SIMPLE, tr("Add folder"), false, 22.0).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, 22.0).clicked() { - app.run("layer.remove", Value::Null); - } - })); + }); // The empty state has no layers: the toolbar stays, greyed if !project_open { return; diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 7627c272..9bbc64dd 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -82,6 +82,12 @@ fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { /// View buttons in a right-to-left layout, with the screenshot button at the end fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + // Screenshot, projection and UV checker act on the project: greyed while none is open + let project_open = app.session.project_open; + ui.add_enabled_ui(project_open, |ui| view_buttons_enabled(app, ui)); +} + +fn view_buttons_enabled(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); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 419ee64f..f85d033f 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -462,18 +462,18 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str); 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!({})); - } - for (index, name) in names.iter().enumerate() { - if ui.selectable_label(current == Some(index), name).clicked() { - app.run("camera.select", json!({"index": index})); + 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})); + } + } + ui.separator(); + if ui.selectable_label(false, tr("Save view as camera")).clicked() { + app.run("camera.add", json!({})); } - } - ui.separator(); - if ui.selectable_label(false, tr("Save view as camera")).clicked() { - app.run("camera.add", json!({})); - } }); } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index a436cd01..50fd24fb 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -119,6 +119,10 @@ 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) => { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index a897761e..ebe5b4a7 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -443,7 +443,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; 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 index b4bddf88..3cf32ef5 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -13,13 +13,29 @@ fn harness(session: Session) -> Harness<'static, TextureCraftApp> { } fn empty() -> Harness<'static, TextureCraftApp> { - harness(Session::closed()) + 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(h: &Harness<'static, TextureCraftApp>) -> Vec<(String, f32)> { + h.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(h: &Harness<'static, TextureCraftApp>) -> bool { + painted(h).iter().any(|(text, _)| text == "Default camera") +} + fn invoke(h: &mut Harness<'static, TextureCraftApp>, id: &str) { let ctx = h.ctx.clone(); menus::invoke(h.state_mut(), &ctx, id); @@ -41,9 +57,30 @@ fn project_items_are_disabled_without_a_project() { let h = empty(); let app = h.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.frame", "viewport.displayMaterial", "tool.paint", "tool.eraser", "viewport.quickMask", - "layer.add.paint", "layer.add.fill", "layer.remove", "bake.run", "resource.import", "material.load", + "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.frame", + "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"); } @@ -59,10 +96,12 @@ fn project_items_are_disabled_without_a_project() { #[test] fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { let empty = empty(); - assert!(empty.query_by_label("Default camera").is_none(), "no camera picker"); - assert!(empty.query_all_by_label("Material").count() >= 1, "the view picker stays"); + 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!(open.query_by_label("Default camera").is_some(), "with a project the camera picker is there"); + assert!(has_camera_picker(&open), "with a project the camera picker is there"); } #[test] @@ -82,7 +121,7 @@ fn close_unloads_the_project_back_to_the_empty_state() { assert!(!h.state().session.project_open, "Close leaves no project open"); assert!(h.state().session.path.is_none() && !h.state().session.modified); assert!(h.query_by_label("No properties found").is_some()); - assert!(h.query_by_label("Default camera").is_none()); + assert!(!has_camera_picker(&h)); assert!(!menus::enabled(h.state(), "file.save")); } @@ -92,7 +131,7 @@ fn creating_or_opening_a_project_from_the_empty_state_works() { assert!(h.state_mut().run("project.new", json!({"mesh": "cube", "resolution": 128})).is_some()); h.run_steps(3); assert!(h.state().session.project_open); - assert!(menus::enabled(h.state(), "file.save") && h.query_by_label("Default camera").is_some()); + assert!(menus::enabled(h.state(), "file.save") && has_camera_picker(&h)); invoke(&mut h, "file.close"); invoke(&mut h, "ui.newProject"); @@ -105,7 +144,10 @@ fn creating_or_opening_a_project_from_the_empty_state_works() { #[test] fn using_every_panel_and_menu_item_in_the_empty_state_does_not_panic() { let mut h = 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")) { + 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 h, item.id); } for mode in ["ui.mode.bake", "ui.mode.render", "ui.mode.paint"] { diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 5389562d..890bb1f3 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -11,6 +11,7 @@ mod color_selection_editor; mod curvature_generator; mod effect_rows; mod effect_sliders; +mod empty_start; mod file_dialogs; mod fill_channel_image; mod fill_projection_section; @@ -37,7 +38,6 @@ mod shift_lines_2d; mod shortcut_keys; mod skew_paint; mod split_divider; -mod empty_start; mod tool_availability; mod toolbar; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 98272ddc..2e712225 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -212,6 +212,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 ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`) and the library and preset listings as not enabled, and 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 | From ba26b11d85b18bcff6bad70cb04a4c7713db4ab7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 17 Nov 2026 22:23:06 +0100 Subject: [PATCH 3/8] Align menus, tool shelf, right bar and blank-screen states with the reference order --- crates/engine/src/commands.rs | 1 + crates/ui-egui/src/lib.rs | 7 +- crates/ui-egui/src/menus.rs | 12 +- crates/ui-egui/src/rail_popup.rs | 4 +- crates/ui-egui/src/toolbar.rs | 49 ++++---- crates/ui-egui/src/viewport.rs | 5 +- crates/ui-egui/src/windows.rs | 9 +- crates/ui-egui/tests/it/empty_start.rs | 2 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/reference_order.rs | 136 +++++++++++++++++++++ 10 files changed, 185 insertions(+), 41 deletions(-) create mode 100644 crates/ui-egui/tests/it/reference_order.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index a058fa84..b9e60651 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -98,6 +98,7 @@ fn works_without_project(id: &str) -> bool { | "project.new" | "project.sample" | "project.inspect" + | "viewport.frame" | "project.templates" | "export.presets" | "export.preset.get" diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e4a68fcd..5b174d3d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -215,11 +215,15 @@ 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 = ui_store.load(cc.storage).unwrap_or_else(|| { + let mut ui = ui_store.load(cc.storage).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui }); + // 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(); @@ -306,6 +310,7 @@ impl TextureCraftApp { // 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; } if let Some(from) = glide_from.filter(|f| *f != self.session.camera) { self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index c273e0b6..d7f0b4d1 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,8 +77,10 @@ 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), + sep("Window"), it("Window", "Hide UI", "ui.hideUi", Some("Tab")), it("Window", "Reset UI", "ui.resetUi", None), it("Viewport", "Display material", "viewport.displayMaterial", Some("M")), @@ -98,11 +101,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), @@ -115,7 +119,7 @@ fn is_ui(id: &str) -> bool { /// 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.render") + matches!(id, "ui.export" | "ui.projectConfig" | "ui.uvChecker" | "ui.mode.bake" | "ui.mode.paint" | "ui.mode.render") } /// Whether an item can run now 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/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 9bbc64dd..01c845d0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -76,33 +76,29 @@ 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) { - // Screenshot, projection and UV checker act on the project: greyed while none is open - let project_open = app.session.project_open; - ui.add_enabled_ui(project_open, |ui| view_buttons_enabled(app, ui)); -} - -fn view_buttons_enabled(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 @@ -317,7 +313,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); } } @@ -472,11 +471,7 @@ pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { card(ui, &tokens, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, RAIL_CARD_PADDING, |ui| { ui.spacing_mut().item_spacing.y = RAIL_ICON_GAP; crate::rail_popup::begin_rail(ui.ctx(), ui.max_rect()); - let export_on = crate::menus::enabled(app, "ui.export"); - let export = ui.add_enabled_ui(export_on, |ui| { - icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE) - }); - if export.inner.clicked() { + if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE).clicked() { app.ui.windows.export = !app.ui.windows.export; } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f85d033f..3477d2f5 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -486,7 +486,8 @@ 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| { + // The picker is greyed with no project: it has nothing to show a project's maps of + 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"})); @@ -517,7 +518,7 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() { app.run("viewport.view", json!({"mode": "uvChecker"})); } - }); + })); } /// The view picker's entries that show one baked mesh map diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index ebe5b4a7..ae86c5fc 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1140,10 +1140,6 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); - // Nothing to export without a project (closed, or a saved layout that left it open) - if !app.session.project_open { - app.ui.windows.export = false; - } if !app.ui.windows.export { return; } @@ -1151,6 +1147,11 @@ 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/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 3cf32ef5..27189130 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -84,7 +84,7 @@ fn project_items_are_disabled_without_a_project() { ] { 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.mode.paint", "ui.layout.split"] { + 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(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 890bb1f3..2ebb51bc 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -12,6 +12,7 @@ mod curvature_generator; mod effect_rows; mod effect_sliders; mod empty_start; +mod reference_order; mod file_dialogs; mod fill_channel_image; mod fill_projection_section; 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..d53053ff --- /dev/null +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -0,0 +1,136 @@ +//! 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::Queryable; +use texturecraft_engine::Session; +use texturecraft_ui_egui::{TextureCraftApp, menus}; + +fn harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + h +} + +fn buttons_in(h: &Harness<'static, TextureCraftApp>, x: std::ops::Range) -> Vec<(f32, String, bool)> { + let mut found: Vec<(f32, String, bool)> = h + .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 | - | Hide UI | Reset UI", + "Viewport: Display material | Display next channel | Display previous channel | Display next mesh map | Display previous mesh map | UV checker | - | Show entire mesh | - | 3D/2D views | 3D view only | 2D view only | - | 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 h = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let shelf = buttons_in(&h, 0.0..60.0); + let order = ["Paint", "Eraser", "Path", "Projection", "Polygon fill", "Smudge", "Clone", "Material picker", "Geometry mask"]; + let ys: Vec = order.iter().map(|name| named(&shelf, name).unwrap_or_else(|| panic!("{name} on the shelf: {shelf:?}")).0).collect(); + assert!(ys.windows(2).all(|pair| pair[0] < pair[1]), "{ys:?}"); +} + +#[test] +fn the_right_bar_keeps_the_reference_order() { + let h = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let bar = buttons_in(&h, 1562.0..1600.0); + let order = ["Export textures", "Log", "Display Settings", "Shader Settings", "History"]; + let ys: Vec = order.iter().map(|name| named(&bar, name).unwrap_or_else(|| panic!("{name} on the bar: {bar:?}")).0).collect(); + assert!(ys.windows(2).all(|pair| pair[0] < pair[1]), "{ys:?}"); +} + +#[test] +fn the_blank_screen_enables_what_the_reference_enables() { + let h = harness(Session::closed().unwrap()); + let shelf = buttons_in(&h, 0.0..60.0); + for name in ["Paint", "Eraser", "Path", "Projection", "Polygon fill", "Smudge", "Clone", "Geometry mask"] { + assert!(named(&shelf, name).unwrap().2, "{name} is disabled with no project"); + } + let bar = buttons_in(&h, 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(&h, 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 = h.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 h = harness(Session::closed().unwrap()); + let app = h.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 h = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let app = h.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"); + } +} From 7eba03f63ab3a86c727140adeab6704b46960e23 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 17 Nov 2026 22:28:25 +0100 Subject: [PATCH 4/8] Review fixes for the reference-order tests; regenerate parity doc --- crates/engine/src/commands.rs | 2 +- crates/ui-egui/src/viewport.rs | 64 +++++++++---------- crates/ui-egui/tests/it/empty_start.rs | 5 +- crates/ui-egui/tests/it/main.rs | 2 +- crates/ui-egui/tests/it/reference_order.rs | 72 +++++++++++++++++++--- docs/parity.md | 2 +- 6 files changed, 101 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index b9e60651..990ef852 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -89,7 +89,7 @@ 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. +/// 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, diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3477d2f5..5cad71e4 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -487,38 +487,40 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { }; let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); // The picker is greyed with no project: it has nothing to show a project's maps of - 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"})); - } - 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()})); + 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"})); + } + }) + }); } /// The view picker's entries that show one baked mesh map diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 27189130..96b0ad6d 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -70,7 +70,6 @@ fn project_items_are_disabled_without_a_project() { "ui.mode.bake", "ui.mode.render", "ui.uvChecker", - "viewport.frame", "viewport.displayMaterial", "tool.paint", "tool.eraser", @@ -84,7 +83,9 @@ fn project_items_are_disabled_without_a_project() { ] { 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"] { + 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(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 2ebb51bc..1b38cc7e 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -12,7 +12,6 @@ mod curvature_generator; mod effect_rows; mod effect_sliders; mod empty_start; -mod reference_order; mod file_dialogs; mod fill_channel_image; mod fill_projection_section; @@ -32,6 +31,7 @@ mod polygon_fill; mod project_config; mod properties_popup; mod rail; +mod reference_order; mod shelf_drop; mod shelf_hover_preview; mod shelf_panel; diff --git a/crates/ui-egui/tests/it/reference_order.rs b/crates/ui-egui/tests/it/reference_order.rs index d53053ff..20255633 100644 --- a/crates/ui-egui/tests/it/reference_order.rs +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -3,7 +3,7 @@ use egui::accesskit::Role; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::Session; use texturecraft_ui_egui::{TextureCraftApp, menus}; @@ -84,8 +84,8 @@ fn the_right_bar_keeps_the_reference_order() { fn the_blank_screen_enables_what_the_reference_enables() { let h = harness(Session::closed().unwrap()); let shelf = buttons_in(&h, 0.0..60.0); - for name in ["Paint", "Eraser", "Path", "Projection", "Polygon fill", "Smudge", "Clone", "Geometry mask"] { - assert!(named(&shelf, name).unwrap().2, "{name} is disabled with no project"); + 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(&h, 1562.0..1600.0); for name in ["Export textures", "Log", "Display Settings", "Shader Settings", "History"] { @@ -106,17 +106,56 @@ fn the_blank_screen_menus_match_the_measured_enabled_states() { let h = harness(Session::closed().unwrap()); let app = h.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", + "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", + "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"); @@ -130,7 +169,20 @@ fn the_blank_screen_menus_match_the_measured_enabled_states() { fn opening_a_project_enables_the_same_items() { let h = harness(texturecraft_engine::sample_session(256, 64).unwrap()); let app = h.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"] { + 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/docs/parity.md b/docs/parity.md index 8ef5389a..f206b066 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 | From df51327076b745485102142d3305d70f70c52b69 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 17 Nov 2026 22:48:16 +0100 Subject: [PATCH 5/8] Drop pending resize and viewport images on Close; pin test language; document project-independent commands --- crates/ui-egui/src/lib.rs | 7 +++++++ crates/ui-egui/src/viewport.rs | 7 +++++++ crates/ui-egui/tests/it/empty_start.rs | 16 ++++++++++++++++ docs/control-protocol.md | 2 +- 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1d5d14e3..71151dbf 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -310,6 +310,8 @@ impl TextureCraftApp { // A pending dialog must not import its old source into the replacement project if matches!(id, "file.open" | "file.close" | "project.new" | "project.sample") { self.pbr_import = None; + // A resize started on the old project must not be redone on its replacement + self.resize = None; } // The empty state has no baking or rendering to show @@ -542,6 +544,11 @@ 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; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 5cad71e4..dd2a63a1 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -65,6 +65,13 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { 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; } diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 96b0ad6d..d8163c1f 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -8,6 +8,8 @@ use texturecraft_ui_egui::{TextureCraftApp, menus}; fn harness(session: Session) -> Harness<'static, TextureCraftApp> { let mut h = 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 + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } @@ -160,3 +162,17 @@ fn using_every_panel_and_menu_item_in_the_empty_state_does_not_panic() { assert!(!h.state().session.project_open, "none of these opened a project"); assert!(!h.state().session.can_undo(), "and none changed it"); } + +#[test] +fn close_drops_the_pending_resize_and_the_viewport_images() { + let mut h = open_project(); + h.state_mut().start_resize(0, 128); + assert!(h.state().resize.is_some(), "a resize is running"); + let had_image = texturecraft_ui_egui::control::screenshot(h.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_some(); + invoke(&mut h, "file.close"); + assert!(h.state().resize.is_none(), "Close drops the resize of the closed project"); + assert!(!h.state().session.modified, "a late resize result does not mark the empty project modified"); + if had_image { + assert!(texturecraft_ui_egui::control::screenshot(h.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_none(), "no image of the closed project"); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 610dadaa..a6ea86c7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -212,7 +212,7 @@ 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 ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`) and the library and preset listings as not enabled, and 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. +`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 | |---|---|---| From 23ded4d481b3ae81bfea84b8a3c9e76a37e31271 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 00:16:38 +0000 Subject: [PATCH 6/8] Auto: Release stale project state and guard closed-session work Discard pending resize/import work and thumbnail snapshots on successful project replacement. Reject closed-project headless and direct control work, and prevent capture of the previous viewport immediately after Close. Clone selected-layer metadata only while the Add effect menu is open. Complete scoped naming, spacing, comments and regression coverage. Validated release tests for engine, automation, UI and desktop; formatting, workspace clippy, layering, wasm, panic tests, and offscreen/GPU regressions. --- apps/texturecraft-web/src/web.rs | 4 +- apps/texturecraft/src/main.rs | 45 +-- crates/automation/src/headless.rs | 61 ++-- crates/engine/src/commands.rs | 1 + crates/engine/src/inspect.rs | 42 +-- crates/engine/src/session.rs | 10 +- crates/engine/src/tool_availability.rs | 1 + crates/engine/tests/it/closed_session.rs | 60 ++-- crates/ui-egui/src/control.rs | 17 ++ crates/ui-egui/src/dock.rs | 30 +- crates/ui-egui/src/docking.rs | 2 + crates/ui-egui/src/lib.rs | 34 ++- crates/ui-egui/src/toolbar.rs | 2 + crates/ui-egui/src/viewport.rs | 10 +- crates/ui-egui/src/web_files.rs | 6 + crates/ui-egui/src/windows.rs | 9 +- crates/ui-egui/tests/it/empty_start.rs | 316 +++++++++++++++++---- crates/ui-egui/tests/it/reference_order.rs | 52 ++-- crates/ui-egui/tests/ui_snapshots.rs | 75 ++++- 19 files changed, 580 insertions(+), 197 deletions(-) diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index 4c9640de..7740db12 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -40,8 +40,9 @@ pub fn start() { } async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { - // The WebAssembly has downloaded and compiled when this runs. + // 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; @@ -51,6 +52,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { { create.instance_descriptor.backends = eframe::wgpu::Backends::GL; } + eframe::WebRunner::new() .start( canvas, diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index af950279..d05b6cad 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -85,32 +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}"), } } - // A script-driven run (--control) starts with the sample project (or, with --empty, an empty - // material ball), as before; an interactive start has no project open, like File > Close + + // Control runs retain their sample project; interactive runs start empty if args.control.is_some() { if !args.empty - && let Ok(s) = texturecraft_engine::sample_session(2048, 512) + && let Ok(session) = texturecraft_engine::sample_session(2048, 512) { - return s; + return session; } + return match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) { - Ok(s) => s, - Err(e) => { - eprintln!("texturecraft: {e}"); + Ok(session) => session, + Err(error) => { + eprintln!("texturecraft: {error}"); std::process::exit(1); } }; } + match Session::closed() { - Ok(s) => s, - Err(e) => { - eprintln!("texturecraft: {e}"); + Ok(session) => session, + Err(error) => { + eprintln!("texturecraft: {error}"); std::process::exit(1); } } @@ -188,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())); @@ -201,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()))); @@ -232,7 +236,7 @@ fn main() { std::process::exit(2); } let control = args.control; - let r = eframe::run_native( + let result = eframe::run_native( APP_NAME, options, Box::new(move |cc| { @@ -240,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}"); @@ -260,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 ffcb91bc..a5b3c761 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -210,6 +210,8 @@ 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)?) } @@ -311,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)) => { @@ -367,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 { @@ -408,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 990ef852..2821cba2 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -118,6 +118,7 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), if !s.project_open && !works_without_project(spec.id) { return Err("no project is open".into()); } + (spec.enabled)(s) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 3b0b34e9..cee9bb52 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -182,27 +182,27 @@ 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!({ - "projectOpen": s.project_open, - "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), - "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(), - "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), + "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(), + "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/session.rs b/crates/engine/src/session.rs index 4c34f161..d5437143 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -364,8 +364,8 @@ pub struct Session { 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, and only the commands that open or create a - /// project run (see [`crate::commands::check_enabled`]). + /// 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. @@ -442,10 +442,12 @@ impl Session { } /// The empty state: no project is open. Holds a tiny placeholder document that the UI never - /// shows; every command except opening or creating a project is refused. + /// shows; project-dependent commands are refused. pub fn closed() -> Result { - let mut session = Session::new_project("", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 128)?; + // 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) } diff --git a/crates/engine/src/tool_availability.rs b/crates/engine/src/tool_availability.rs index 10478d94..354ab10c 100644 --- a/crates/engine/src/tool_availability.rs +++ b/crates/engine/src/tool_availability.rs @@ -10,6 +10,7 @@ impl Session { 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 index 9c96a23e..2c19e089 100644 --- a/crates/engine/tests/it/closed_session.rs +++ b/crates/engine/tests/it/closed_session.rs @@ -1,4 +1,4 @@ -//! The empty state (no project open): only commands that open or create a project run, and +//! The empty state (no project open): project-dependent commands are refused, and //! File > Close returns to it. use serde_json::json; @@ -10,48 +10,58 @@ fn open_project() -> Session { #[test] fn a_closed_session_refuses_commands_that_need_a_project() { - let mut s = Session::closed().unwrap(); - assert!(!s.project_open); + 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 s, id, &json!({})).unwrap_err(); + let error = execute(&mut session, id, &json!({})).unwrap_err(); + assert!(matches!(error, EngineError::Disabled { .. }), "{id}: {error}"); } - assert!(!s.can_undo(), "nothing was changed"); - assert!(!s.tool_usable(Tool::Paint), "no tool can act without a project"); + 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_only_the_opening_commands_as_enabled() { - let s = Session::closed().unwrap(); +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(), &s).is_ok(), "{id} runs with no project"); + 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, &s).is_ok()).map(|spec| spec.id).collect(); + 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 s = Session::closed().unwrap(); - execute(&mut s, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); - assert!(s.project_open); - execute(&mut s, "layer.add.paint", &json!({})).unwrap(); + 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_keeps_the_user_presets() { - let mut s = open_project(); - s.modified = true; - execute(&mut s, "file.close", &json!({})).unwrap(); - assert!(!s.project_open && !s.modified && s.path.is_none()); - assert!(execute(&mut s, "file.close", &json!({})).is_err(), "closing again has nothing to close"); - execute(&mut s, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); - assert!(s.project_open, "a project can be created again"); +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 s = Session::closed().unwrap(); + let mut session = Session::closed().unwrap(); for id in [ "export.presets", "brush.preset.list", @@ -63,7 +73,7 @@ fn the_libraries_and_presets_still_answer_without_a_project() { "project.templates", "project.inspect", ] { - execute(&mut s, id, &json!({})).unwrap_or_else(|e| panic!("{id}: {e}")); + execute(&mut session, id, &json!({})).unwrap_or_else(|error| panic!("{id}: {error}")); } - assert_eq!(texturecraft_engine::inspect::session(&s)["projectOpen"], json!(false)); + assert_eq!(texturecraft_engine::inspect::session(&session)["projectOpen"], json!(false)); } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index bc44e107..d3ab0cde 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -74,6 +74,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" => { @@ -101,6 +107,13 @@ 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(); + } + ok(value) } Err(error) => err(error), @@ -206,6 +219,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 eb71c5be..a0e7d736 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -45,6 +45,7 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { if !app.session.project_open { return; } + let tk = Tokens::get(ui.ctx()); let sets: Vec<(String, String, bool)> = app .session @@ -97,7 +98,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 { @@ -144,7 +146,7 @@ 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 let project_open = app.session.project_open; @@ -153,17 +155,19 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut 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 = 4.0; - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); egui::ComboBox::from_id_salt("layer_channel").width(86.0).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())); + 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 @@ -183,10 +187,12 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { } }) }); + // 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(); @@ -218,7 +224,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)); } }); app.layer_panel.end(ui.ctx(), &app.session); @@ -1495,6 +1501,7 @@ 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); @@ -1525,6 +1532,7 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { 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 fee32f5d..13d39465 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -485,6 +485,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { 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), @@ -495,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 71151dbf..139fd754 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -216,10 +216,12 @@ impl TextureCraftApp { ui.prefs.language = i18n::os_language().into(); ui }); + // 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(); @@ -307,11 +309,11 @@ 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; - // A resize started on the old project must not be redone on its replacement self.resize = None; + self.layer_panel = Default::default(); } // The empty state has no baking or rendering to show @@ -531,6 +533,7 @@ impl TextureCraftApp { if self.resize.is_some() { return; } + match self.session.resize_task(ts, resolution) { Ok(task) => { let progress = Arc::new(Progress::new()); @@ -544,15 +547,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, @@ -782,11 +788,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); @@ -797,21 +805,23 @@ 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); #[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/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 01c845d0..54fc9e93 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -83,8 +83,10 @@ fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { /// 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; + // 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; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index dd2a63a1..e997ec11 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -65,6 +65,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { 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::() @@ -77,7 +78,8 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } 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. + + // A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture let pending_2d_endpoint = if !app.session.stroke_active() || !tool_acts(app) { ui.data_mut(|data| { let endpoint = data.get_temp(stroke_end); @@ -164,6 +166,7 @@ fn empty_views(app: &mut TextureCraftApp, ui: &mut Ui) { ] } }; + for (rect, id) in regions { ui.painter().rect_filled(rect, 0.0, tokens.viewport); view_header(app, ui, rect, id); @@ -493,7 +496,8 @@ 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(); - // The picker is greyed with no project: it has nothing to show a project's maps of + + // 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() { @@ -505,10 +509,12 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { 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); diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 50fd24fb..e8c56427 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -123,6 +123,7 @@ pub fn load(app: &mut TextureCraftApp, name: &str, bytes: Vec) { 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) => { @@ -133,22 +134,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), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index ae86c5fc..2e7a7a62 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -528,13 +528,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| { @@ -1143,6 +1145,7 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.export { return; } + let mut open = true; let mut do_export = false; let presets = texturecraft_engine::formats::builtin_presets(); @@ -1152,6 +1155,7 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { 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() { @@ -1166,6 +1170,7 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::export_templates::tab(app, ui, &presets); return; } + ui.vertical(|ui| { ui.set_width(180.0); ui.label(RichText::new(tr("Texture sets")).strong()); diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index d8163c1f..cb62c93a 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -7,11 +7,12 @@ use texturecraft_engine::Session; use texturecraft_ui_egui::{TextureCraftApp, menus}; fn harness(session: Session) -> Harness<'static, TextureCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + 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 - h.state_mut().ui.prefs.language = "en".into(); - h.run_steps(4); - h + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness } fn empty() -> Harness<'static, TextureCraftApp> { @@ -23,8 +24,9 @@ fn open_project() -> Harness<'static, TextureCraftApp> { } /// Texts painted this frame as (text, left edge) -fn painted(h: &Harness<'static, TextureCraftApp>) -> Vec<(String, f32)> { - h.output() +fn painted(harness: &Harness<'static, TextureCraftApp>) -> Vec<(String, f32)> { + harness + .output() .shapes .iter() .filter_map(|shape| match &shape.shape { @@ -34,30 +36,31 @@ fn painted(h: &Harness<'static, TextureCraftApp>) -> Vec<(String, f32)> { .collect() } -fn has_camera_picker(h: &Harness<'static, TextureCraftApp>) -> bool { - painted(h).iter().any(|(text, _)| text == "Default camera") +fn has_camera_picker(harness: &Harness<'static, TextureCraftApp>) -> bool { + painted(harness).iter().any(|(text, _)| text == "Default camera") } -fn invoke(h: &mut Harness<'static, TextureCraftApp>, id: &str) { - let ctx = h.ctx.clone(); - menus::invoke(h.state_mut(), &ctx, id); - h.run_steps(3); +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 h = empty(); - let ui = &h.state().ui; - assert!(!h.state().session.project_open); + 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!(h.query_by_label("Continue with the sample project").is_none() && h.query_by_label("Recent projects").is_none(), "no start window"); - assert!(h.query_by_label("No properties found").is_some(), "Properties says it has nothing"); + 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 h = empty(); - let app = h.state(); + let harness = empty(); + let app = harness.state(); for id in [ "file.save", "file.saveAs", @@ -99,80 +102,281 @@ fn project_items_are_disabled_without_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 h in [empty(), open_project()] { - assert!(h.query_by_label_contains("Version:").is_some()); - assert!(h.query_by_label_contains("Layer memory").is_none()); - assert!(h.query_by_label_contains(" ms").is_none(), "no frame time"); + 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 h = open_project(); - assert!(h.state().session.project_open && h.state().session.set_count() == 2); - invoke(&mut h, "file.close"); - assert!(!h.state().session.project_open, "Close leaves no project open"); - assert!(h.state().session.path.is_none() && !h.state().session.modified); - assert!(h.query_by_label("No properties found").is_some()); - assert!(!has_camera_picker(&h)); - assert!(!menus::enabled(h.state(), "file.save")); + 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 h = empty(); - assert!(h.state_mut().run("project.new", json!({"mesh": "cube", "resolution": 128})).is_some()); - h.run_steps(3); - assert!(h.state().session.project_open); - assert!(menus::enabled(h.state(), "file.save") && has_camera_picker(&h)); + let mut harness = empty(); - invoke(&mut h, "file.close"); - invoke(&mut h, "ui.newProject"); - assert!(h.state().ui.windows.new_project, "New project opens its dialog from the empty state"); - let mut h = empty(); - invoke(&mut h, "project.sample"); - assert!(h.state().session.project_open && h.state().session.set_count() == 2, "the sample is still one menu click away"); + 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 h = empty(); + 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 h, item.id); + invoke(&mut harness, item.id); } for mode in ["ui.mode.bake", "ui.mode.render", "ui.mode.paint"] { - invoke(&mut h, mode); + invoke(&mut harness, mode); } for id in ["ui.layout.2d", "ui.layout.3d", "ui.layout.split"] { - invoke(&mut h, id); + invoke(&mut harness, id); } - assert!(!h.state().session.project_open, "none of these opened a project"); - assert!(!h.state().session.can_undo(), "and none changed it"); + 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 h = open_project(); - h.state_mut().start_resize(0, 128); - assert!(h.state().resize.is_some(), "a resize is running"); - let had_image = texturecraft_ui_egui::control::screenshot(h.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_some(); - invoke(&mut h, "file.close"); - assert!(h.state().resize.is_none(), "Close drops the resize of the closed project"); - assert!(!h.state().session.modified, "a late resize result does not mark the empty project modified"); + 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(h.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_none(), "no image of the closed project"); + 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 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/reference_order.rs b/crates/ui-egui/tests/it/reference_order.rs index 20255633..95bb980f 100644 --- a/crates/ui-egui/tests/it/reference_order.rs +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -8,14 +8,14 @@ use texturecraft_engine::Session; use texturecraft_ui_egui::{TextureCraftApp, menus}; fn harness(session: Session) -> Harness<'static, TextureCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.state_mut().ui.prefs.language = "en".into(); - h.run_steps(4); - h + 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(h: &Harness<'static, TextureCraftApp>, x: std::ops::Range) -> Vec<(f32, String, bool)> { - let mut found: Vec<(f32, String, bool)> = h +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| { @@ -64,47 +64,53 @@ fn every_menu_lists_its_items_in_the_reference_order() { #[test] fn the_tool_shelf_keeps_the_reference_order() { - let h = harness(texturecraft_engine::sample_session(256, 64).unwrap()); - let shelf = buttons_in(&h, 0.0..60.0); + 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 ys: Vec = order.iter().map(|name| named(&shelf, name).unwrap_or_else(|| panic!("{name} on the shelf: {shelf:?}")).0).collect(); - assert!(ys.windows(2).all(|pair| pair[0] < pair[1]), "{ys:?}"); + 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 h = harness(texturecraft_engine::sample_session(256, 64).unwrap()); - let bar = buttons_in(&h, 1562.0..1600.0); + 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 ys: Vec = order.iter().map(|name| named(&bar, name).unwrap_or_else(|| panic!("{name} on the bar: {bar:?}")).0).collect(); - assert!(ys.windows(2).all(|pair| pair[0] < pair[1]), "{ys:?}"); + 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 h = harness(Session::closed().unwrap()); - let shelf = buttons_in(&h, 0.0..60.0); + 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(&h, 1562.0..1600.0); + 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(&h, 600.0..1562.0); + 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 = h.get_all_by_role(Role::Button).find(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("Painting"))).unwrap(); + + 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 h = harness(Session::closed().unwrap()); - let app = h.state(); + let harness = harness(Session::closed().unwrap()); + let app = harness.state(); let disabled = [ "file.close", "file.save", @@ -167,8 +173,8 @@ fn the_blank_screen_menus_match_the_measured_enabled_states() { #[test] fn opening_a_project_enables_the_same_items() { - let h = harness(texturecraft_engine::sample_session(256, 64).unwrap()); - let app = h.state(); + let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let app = harness.state(); for id in [ "file.close", "file.save", diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 4ab7803f..d50caf4e 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -23,14 +23,83 @@ 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.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()); + 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] From f783e69ba1a95e91a78eeeab184c4f58a1785538 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 00:46:39 +0000 Subject: [PATCH 7/8] Auto: Clear Export and reject late HDR imports after Close Dismiss Export on control-driven Close, discard environment picks that finish after Close, and establish both view targets before testing their removal. --- crates/ui-egui/src/control.rs | 5 +++++ crates/ui-egui/src/web_files.rs | 30 ++++++++++++++++++++++++++ crates/ui-egui/tests/it/empty_start.rs | 13 +++++++++++ crates/ui-egui/tests/ui_snapshots.rs | 2 ++ 4 files changed, 50 insertions(+) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d3ab0cde..f2915d7e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -114,6 +114,11 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para app.layer_panel = Default::default(); } + // The Export dialog cannot operate after Close + if id == "file.close" { + app.ui.windows.export = false; + } + ok(value) } Err(error) => err(error), diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index e8c56427..b878f44a 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -60,6 +60,12 @@ pub fn poll(app: &mut TextureCraftApp) { load(app, &name, bytes); continue; } + + // The picker may finish after Close; never import into the placeholder + Pick::Environment if !app.session.project_open => { + app.toast(tr("No project is open"), 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)), @@ -370,6 +376,30 @@ 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(); + INBOX.lock().unwrap().push(("environment.png".into(), png.clone(), Pick::Environment)); + + assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); + + poll(harness.state_mut()); + + 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()); + INBOX.lock().unwrap().push(("environment.png".into(), png, Pick::Environment)); + + poll(harness.state_mut()); + + assert!(harness.state().session.doc.resources.contains_key("environment.png")); + } + #[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/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index cb62c93a..54f4e925 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -268,6 +268,19 @@ fn control_close_rejects_a_viewport_capture_before_the_next_frame() { 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(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index d50caf4e..22a6b9b4 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -53,6 +53,7 @@ fn close_releases_view_targets_and_rejects_immediate_capture() { 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(); @@ -70,6 +71,7 @@ fn close_releases_view_targets_and_rejects_immediate_capture() { } }; 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(); From 7352fe307ed325109c724639ae9aa95653179406 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 01:24:58 +0000 Subject: [PATCH 8/8] Auto: Reject stale browser project picks Bind environment and bake-mesh picks to the project that opened them. Reject completions after Close or replacement while accepting picks in their original project. --- crates/ui-egui/src/web_files.rs | 91 +++++++++++++++++++++++++++------ 1 file changed, 74 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index b878f44a..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,6 +54,10 @@ 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 => { @@ -61,14 +65,18 @@ pub fn poll(app: &mut TextureCraftApp) { continue; } - // The picker may finish after Close; never import into the placeholder - Pick::Environment if !app.session.project_open => { + // 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 => 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::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), @@ -262,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. @@ -383,23 +391,72 @@ mod tests { 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(); - INBOX.lock().unwrap().push(("environment.png".into(), png.clone(), Pick::Environment)); + let old_project_id = harness.state().session.project_id; assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); - poll(harness.state_mut()); + 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()); - INBOX.lock().unwrap().push(("environment.png".into(), png, Pick::Environment)); + let project_id = harness.state().session.project_id; - poll(harness.state_mut()); + 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() };