diff --git a/crates/engine/src/project_cmds.rs b/crates/engine/src/project_cmds.rs index 33432cda..a9018f4f 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -1,4 +1,4 @@ -//! Project-level commands: new project, sample project, smart materials, inspection. +//! Project-level commands: new project, rename, sample project, smart materials, inspection. use serde_json::{Value, json}; use texturecraft_compose::BakedMaps; @@ -9,6 +9,9 @@ use crate::commands::{CommandSpec, always, bad, boolp, strp, u64p}; use crate::materials::Place; use crate::{Result, Session, cmd}; +/// Longest project name, in characters; it goes into export file names. +pub const MAX_PROJECT_NAME_CHARS: usize = 128; + pub fn specs() -> Vec { vec![ cmd!( @@ -22,6 +25,15 @@ pub fn specs() -> Vec { ), cmd!("project.sample", "Open sample project", ["File"], None, "{}", always, sample), cmd!("project.inspect", "Inspect project", [], None, "{}", always, |s, _| Ok(crate::inspect::session(s))), + cmd!( + "project.rename", + "Rename project", + [], + None, + "{name: 1-128 characters without control characters} — the name `$project` stands for in export file names; the project file keeps its own name", + always, + rename + ), cmd!( "material.apply", "Add smart material", @@ -51,6 +63,30 @@ fn new(s: &mut Session, p: &Value) -> Result { Ok(crate::inspect::session(s)) } +/// Trim and validate a proposed name without changing the project. +pub fn validate_project_name(name: &str) -> Result<&str> { + let name = name.trim(); + if name.is_empty() || name.chars().nth(MAX_PROJECT_NAME_CHARS).is_some() || name.chars().any(char::is_control) { + return Err(bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters"))); + } + + Ok(name) +} + +fn rename(session: &mut Session, params: &Value) -> Result { + let name = validate_project_name(strp(params, "name").unwrap_or_default())?; + + // The same name is not an undo step and leaves a saved project unmodified + if name != session.doc.project.name { + session.edit("Rename project", |session| { + session.doc.project.name = name.to_owned(); + Ok(()) + })?; + } + + Ok(json!({ "name": name })) +} + fn material(s: &mut Session, p: &Value) -> Result { let id = strp(p, "material").ok_or_else(|| bad("material.apply", "`material` is required"))?; let l = crate::materials::apply_at(s, id, Place::from_params(p))?; diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3dbfd83c..01f63de0 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -67,6 +67,7 @@ mod perf; mod polygon_fill; mod project_recovery; mod rebuilt_uv_layout; +mod rename_project; mod resource_updater; mod resources_used; mod sample; diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index c6ee8dfe..8d95bb01 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -523,19 +523,29 @@ fn sets_with_the_same_file_name_warn_instead_of_overwriting() { fn a_material_never_points_at_a_texture_kept_for_another_set() { let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); - // The first set's name expands to the same base-colour filename as the second - execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "$channel"})).unwrap(); - execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "baseColor"})).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "body"})).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "trim"})).unwrap(); let directory = temp("shared-map"); - let result = export(&mut session, &directory, OPENPBR, true); + // Give the first set a map with the same filename as the second set's canonical base colour + let mut preset = texturecraft_engine::formats::builtin_preset(OPENPBR).unwrap(); + let mut conflicting_map = preset.maps.iter().find(|map| map.file.ends_with("_base_color")).unwrap().clone(); + let conflicting_stem = "material_ball_trim_base_color"; + conflicting_map.file = conflicting_stem.into(); + preset.maps.push(conflicting_map); - let materials: Vec<_> = files(&result).into_iter().filter(|path| path.ends_with(".mtlx")).collect(); - assert!(materials.len() >= 2, "{result}"); - assert!(std::fs::read_to_string(&materials[0]).unwrap().contains("material_ball_baseColor_base_color.png")); - for material in materials.iter().skip(1) { - assert!(!std::fs::read_to_string(material).unwrap().contains("material_ball_baseColor_base_color.png"), "{material}"); - } + let result = + execute(&mut session, "file.exportTextures", &json!({"dir": directory.display().to_string(), "preset": preset, "ts": [0, 1], "materialX": true})) + .unwrap(); + + let conflicting_file = format!("{conflicting_stem}.png"); + assert!(names(&result).contains(&conflicting_file), "{result}"); + assert!(warned(&result, &format!("\"{conflicting_file}\" was not written")), "{result}"); + let body = referenced(&std::fs::read_to_string(directory.join("material_ball_body.mtlx")).unwrap()); + let trim = referenced(&std::fs::read_to_string(directory.join("material_ball_trim.mtlx")).unwrap()); + assert!(body.iter().any(|file| file == "material_ball_body_base_color.png"), "{body:?}"); + assert!(trim.iter().any(|file| file.starts_with("material_ball_trim_")), "{trim:?}"); + assert!(!trim.contains(&conflicting_file), "{trim:?}"); } #[test] diff --git a/crates/engine/tests/it/rename_project.rs b/crates/engine/tests/it/rename_project.rs new file mode 100644 index 00000000..2bcca1a6 --- /dev/null +++ b/crates/engine/tests/it/rename_project.rs @@ -0,0 +1,63 @@ +//! `project.rename`: the name `$project` stands for in export file names. + +use serde_json::json; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +#[test] +fn a_renamed_project_exports_under_its_new_name_until_undone() { + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut preset = execute(&mut session, "export.preset.get", &json!({"name": "Document channels + Normal + AO (No Alpha)"})).unwrap(); + preset["maps"][0]["file"] = json!("$project_$textureSet"); + + execute(&mut session, "project.rename", &json!({"name": " Knight final "})).unwrap(); + + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + let renamed_file = plan[0]["file"].as_str().unwrap(); + assert!(renamed_file.starts_with("Knight_final_"), "{renamed_file}"); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.name, "Knight final"); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + + assert_eq!(session.doc.project.name, "hero"); + let restored_file = plan[0]["file"].as_str().unwrap(); + assert!(restored_file.starts_with("hero_"), "{restored_file}"); +} + +#[test] +fn an_unusable_or_unchanged_project_name_edits_nothing() { + use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS; + + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + + for name in [json!(null), json!(7), json!(" "), json!("a\nb"), json!("界".repeat(MAX_PROJECT_NAME_CHARS + 1))] { + assert!(execute(&mut session, "project.rename", &json!({"name": name})).is_err(), "{name}"); + } + + execute(&mut session, "project.rename", &json!({"name": "hero"})).unwrap(); + + assert_eq!(session.doc.project.name, "hero"); + assert!(!session.modified, "nothing changed"); + assert!(!session.can_undo()); + + let at_limit = "界".repeat(MAX_PROJECT_NAME_CHARS); + let result = execute(&mut session, "project.rename", &json!({"name": format!(" {at_limit} ")})).unwrap(); + + assert_eq!(result["name"], at_limit); +} + +#[test] +fn a_renamed_project_is_inserted_into_the_template_as_literal_text() { + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut preset = execute(&mut session, "export.preset.get", &json!({"name": "Document channels + Normal + AO (No Alpha)"})).unwrap(); + preset["maps"][0]["file"] = json!("$project/$mesh"); + + execute(&mut session, "project.rename", &json!({"name": "Knight/$mesh"})).unwrap(); + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + + let file = plan[0]["file"].as_str().unwrap(); + assert!(file.starts_with("Knight__mesh/cube."), "{file}"); +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 8ca37c57..824a37ea 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -717,8 +717,32 @@ fn disambiguated_psd_stem(stem: &str, set_index: usize, limit: usize, taken: imp } /// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. -pub fn sanitize_file_path(s: &str) -> String { - s.split('/').map(sanitize_file_stem).collect::>().join("/") +pub fn sanitize_file_path(path: &str) -> String { + if !path.contains('/') { + return sanitize_file_stem(path); + } + + path.split('/').map(sanitize_file_stem).collect::>().join("/") +} + +/// Expand tokens in the template while keeping the substituted values literal. +fn expand_file_template(template: &str, variables: &[(&str, &str)]) -> String { + let mut expanded = String::with_capacity(template.len()); + let mut remaining = template; + while let Some(index) = remaining.find('$') { + let (literal, variable) = remaining.split_at(index); + expanded.push_str(literal); + if let Some((value, tail)) = variables.iter().find_map(|&(token, value)| variable.strip_prefix(token).map(|tail| (value, tail))) { + expanded.push_str(value); + remaining = tail; + } else { + expanded.push('$'); + remaining = &variable[1..]; + } + } + + expanded.push_str(remaining); + expanded } /// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file @@ -773,14 +797,19 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti } else { std::borrow::Cow::Borrowed(map.file.as_str()) }; + let channel = channel_label(map); let expand_stem = |udim: &str| { - let expanded = template - .replace("$udim", udim) - .replace("$project", &project_stem) - .replace("$mesh", &mesh_stem) - .replace("$textureSet", &set_stem) - .replace("$channel", channel_label(map)) - .replace("$colorSpace", color_space); + let expanded = expand_file_template( + &template, + &[ + ("$udim", udim), + ("$project", &project_stem), + ("$mesh", &mesh_stem), + ("$textureSet", &set_stem), + ("$channel", channel), + ("$colorSpace", color_space), + ], + ); sanitize_file_path(&expanded) }; diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs index 53f9cb4a..8d954593 100644 --- a/crates/ui-egui/src/autosave_name.rs +++ b/crates/ui-egui/src/autosave_name.rs @@ -1,5 +1,5 @@ -//! Where a project's autosave copy goes. Each project has a file of its own, `-copy-.tcraft`: a project's -//! name comes from its mesh file, so the name alone would let projects made from one mesh overwrite each other's copy +//! Where a project's autosave copy goes. Each project has a file of its own, `-copy-.tcraft`, +//! even if several projects share a name or a project is renamed. use std::path::{Path, PathBuf}; @@ -45,19 +45,20 @@ impl TextureCraftApp { } /// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the - /// same across restarts; an unsaved project gets one that no other open project or running instance shares + /// same across restarts; an unsaved project's copy keeps its first autosave name until the project is saved pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf { let Some(saved) = self.session.path.as_deref() else { let project = self.session.project_id; - let suffix = match self.unsaved_autosave_suffix { - Some((owner, suffix)) if owner == project => suffix, - _ => { - let suffix = new_suffix(project); - self.unsaved_autosave_suffix = Some((project, suffix)); - suffix - } - }; - return folder.join(file_name(&self.session.doc.project.name, suffix)); + if let Some((owner, name)) = &self.unsaved_autosave_file + && *owner == project + { + return folder.join(name); + } + + let name = file_name(&self.session.doc.project.name, new_suffix(project)); + let path = folder.join(&name); + self.unsaved_autosave_file = Some((project, name)); + return path; }; let saved = absolute(Path::new(saved)); @@ -178,6 +179,23 @@ mod tests { assert_ne!(first.autosave_path(folder), one, "a new project of the same name starts its own copy"); } + #[test] + fn renaming_an_unsaved_project_keeps_its_autosave_copy() { + let folder = Path::new("autosave"); + let mut app = app(project("hero")); + let copy = app.autosave_path(folder); + + for name in ["Knight", "Knight final"] { + texturecraft_engine::execute(&mut app.session, "project.rename", &serde_json::json!({"name": name})).unwrap(); + + assert_eq!(app.autosave_path(folder), copy); + } + + app.session.switch_to(project("Knight")); + + assert_ne!(app.autosave_path(folder), copy); + } + #[test] fn a_saved_project_names_its_copy_after_its_file_and_keeps_it_across_restarts() { let folder = Path::new("autosave"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dee90c4e..ebb68f4e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -383,9 +383,12 @@ pub struct TextureCraftApp { /// When the next autosave is due (seconds of app time; desktop only). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, - /// The unsaved project (its id) and the suffix of its autosave copy. + /// The unsaved project (its id) and the stable filename of its autosave copy. #[cfg(not(target_arch = "wasm32"))] - unsaved_autosave_suffix: Option<(u64, u64)>, + unsaved_autosave_file: Option<(u64, String)>, + /// The dialog opening that owns the Project name widget's undo state. + #[cfg(not(target_arch = "wasm32"))] + project_name_editor_opening: Option, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. @@ -537,7 +540,9 @@ impl TextureCraftApp { last_time: 0.0, next_autosave, #[cfg(not(target_arch = "wasm32"))] - unsaved_autosave_suffix: None, + unsaved_autosave_file: None, + #[cfg(not(target_arch = "wasm32"))] + project_name_editor_opening: None, styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs index 23316b2b..2ad606b1 100644 --- a/crates/ui-egui/src/parity.rs +++ b/crates/ui-egui/src/parity.rs @@ -18,7 +18,7 @@ pub const HEADLESS: &[(&str, &str, &str, &str)] = &[ ("ui.saveAsTemplate", "partial", "window", "the dialog is desktop-only; `project.template.save` saves it"), ("ui.export", "partial", "window", "the dialog is desktop-only; `file.exportTextures` exports"), ("ui.saveReduced", "no", "engine-gap", "a smaller save could be a command"), - ("ui.projectConfig", "no", "engine-gap", "project settings could be set by a command"), + ("ui.projectConfig", "partial", "window", "the dialog is desktop-only; `project.rename` sets the project name"), ("ui.recent.clear", "no", "window", "the desktop recent-projects list"), ("ui.quit", "no", "window", "quits the desktop app"), ("ui.settings", "no", "window", "the desktop settings window"), diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index a399aa4e..e88413f2 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -1,13 +1,15 @@ //! Edit > Project Configuration...: the project's settings in sections. 3D MESH picks another mesh -//! file for the project or reads the current one again; PROJECT SETTINGS sets the normal map format -//! and shows the UV tiles. Settings TextureCraft does not have yet (tangent space per fragment, -//! physical size, OpenColorIO, import options other than stroke preservation) are shown disabled. +//! file for the project or reads the current one again; PROJECT SETTINGS sets the project name and +//! normal map format and shows the UV tiles. Unsupported options such as tangent space per fragment, +//! physical size and OpenColorIO are shown disabled. +use std::borrow::Cow; use std::sync::atomic::{AtomicU64, Ordering}; use egui::{Key, Modifiers}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; +use texturecraft_engine::project_cmds::{MAX_PROJECT_NAME_CHARS, validate_project_name}; use crate::TextureCraftApp; use crate::dock::info_icon; @@ -33,6 +35,7 @@ const MIN_FIELD_WIDTH_POINTS: f32 = 60.0; const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 560.0; /// Leave space around the centered dialog on short viewports. const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0; +const PROJECT_NAME_FIELD_ID: &str = "project_config_name"; /// Opens the window on the current project, with nothing chosen yet. pub(crate) fn open(app: &mut TextureCraftApp) { @@ -44,6 +47,7 @@ pub(crate) fn open(app: &mut TextureCraftApp) { mesh: None, reimport: false, preserve: true, + draft_name: None, normal_format: None, color_management: crate::project_form::ColorManagement::Legacy, confirm: false, @@ -115,14 +119,23 @@ fn format_name(format: NormalFormat) -> &'static str { } } -pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - let Some(mut config) = app.ui.windows.project_config.take() else { return }; - - // Choices for another project cannot be applied here - if config.project != app.session.project_id { +fn sync_name_editor(app: &mut TextureCraftApp, ctx: &egui::Context, opening: Option) { + if app.project_name_editor_opening == opening { return; } + // Egui keeps widget undo data after the dialog closes + app.project_name_editor_opening = opening; + ctx.data_mut(|data| data.remove::(egui::Id::unique(PROJECT_NAME_FIELD_ID))); +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + // Choices for another project cannot be applied here + let config = app.ui.windows.project_config.take().filter(|config| config.project == app.session.project_id); + sync_name_editor(app, ctx, config.as_ref().map(|config| config.opening_id)); + + let Some(mut config) = config else { return }; + let project = &app.session.doc.project; let current_mesh_path = &project.mesh_path; @@ -137,7 +150,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); - // Start with a form that fits the viewport; subsequent sizes follow the user's resize + // Fit the first frame to the viewport and follow the user's resize after that let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); let dialog = crate::windows::dialog(ctx, "project_config", tr("Project Configuration"), &mut open) @@ -211,6 +224,20 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add_space(12.0); ui.label(caption(tr("PROJECT SETTINGS"))); ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + let label = ui.label(tr("Project name")).id; + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, tr("The name $project stands for in export file names. The project file keeps its own name.")); + let was_edited = config.draft_name.is_some(); + let mut name = config.draft_name.take().map_or(Cow::Borrowed(project.name.as_str()), Cow::Owned); + let field = egui::TextEdit::singleline(&mut name).id(egui::Id::unique(PROJECT_NAME_FIELD_ID)).desired_width(FIELD_WIDTH_POINTS); + if ui.add(field).labelled_by(label).changed() || was_edited { + config.draft_name = Some(name.into_owned()); + } + }); + }); + let shown_format = config.normal_format.unwrap_or(current_normal_format); row( ui, @@ -284,7 +311,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { physical_size(ui, "project_config_physical_size", false); color_management(ui, "project_config_color_management", &mut config.color_management); }); - }); }); }); @@ -303,9 +329,19 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); } - // Apply the mesh first so a failed mesh change leaves the format untouched + let confirming = ok && !cancel && open; + + // Reject invalid drafts before applying mesh or format changes + if confirming && config.draft_name.as_deref().is_some_and(|name| validate_project_name(name).is_err()) { + app.toast(trf("Project name must be 1 to {max} characters after trimming, without control characters.", &[("max", &MAX_PROJECT_NAME_CHARS)]), true); + app.announce_latest_toast(); + app.ui.windows.project_config = Some(config); + return; + } + + // Apply the mesh first so a failed mesh change leaves the remaining settings untouched let mut mesh_applied = false; - let done = ok && !cancel && open && { + let done = confirming && { let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten(); mesh_applied = if config.reimport && chosen_mesh.is_none() && reimport.is_none() { // Drop a stale reimport tick so the user can retry the remaining settings @@ -328,15 +364,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } None => true, } + && match config.draft_name.as_deref() { + Some(name) => app.run("project.rename", json!({"name": name})).is_some(), + None => true, + } }; if !done && !cancel && open { - // A format retry must not reimport an already changed mesh + // A retry must not reimport an already changed mesh if ok && mesh_applied { (config.mesh, config.reimport) = (None, false); } app.ui.windows.project_config = Some(config); + } else { + sync_name_editor(app, ctx, None); } } diff --git a/crates/ui-egui/src/state/project_config.rs b/crates/ui-egui/src/state/project_config.rs index 174b0987..0d848f6e 100644 --- a/crates/ui-egui/src/state/project_config.rs +++ b/crates/ui-egui/src/state/project_config.rs @@ -7,6 +7,8 @@ pub struct ProjectConfig { pub reimport: bool, /// Whether painted strokes follow the surface of a newly imported mesh pub preserve: bool, + /// The name as typed, or None to leave the current name unvalidated and unchanged + pub draft_name: Option, /// The selected normal map format when it differs from the project's pub normal_format: Option, /// Color management as chosen in the window; nothing is applied (the project stays Legacy) diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index a44c4640..88723d9a 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -765,3 +765,99 @@ fn project_config_snapshots() { h.run_steps(6); h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap(); } + +fn type_project_name(h: &mut Harness<'_, TextureCraftApp>, name: &str) { + in_window(h, Role::TextInput, "Project name").focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + in_window(h, Role::TextInput, "Project name").type_text(name); + h.run_steps(2); +} + +#[test] +fn a_typed_project_name_applies_only_with_ok() { + let dir = temp_dir("project-name"); + let mut h = app_on_a_quad(&dir); + let before = h.state().session.doc.project.name.clone(); + + for button in ["Cancel", "OK"] { + open_window(&mut h); + type_project_name(&mut h, "Knight"); + click_in_window(&mut h, Role::Button, button); + + let expected = if button == "OK" { "Knight" } else { before.as_str() }; + assert_eq!(h.state().session.doc.project.name, expected, "after {button}"); + assert!(!window_is_open(&h), "{button} closes the window"); + } +} + +#[test] +fn an_invalid_project_name_leaves_other_configuration_changes_pending() { + use texturecraft_engine::core::NormalFormat; + + let dir = temp_dir("invalid-project-name"); + let mut h = app_on_a_quad(&dir); + let triangle = dir.join("tri.obj"); + std::fs::write(&triangle, TRIANGLE).unwrap(); + + open_window(&mut h); + select(&mut h, &triangle); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + type_project_name(&mut h, " "); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, "quad"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl); + let message = h.get_by_label("Project name must be 1 to 128 characters after trimming, without control characters."); + assert_eq!(message.accesskit_node().live(), egui::accesskit::Live::Polite); + + type_project_name(&mut h, "Knight"); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, "Knight"); + assert_eq!(h.state().session.mesh.triangle_count(), 1); + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); +} + +#[test] +fn the_project_name_limit_applies_after_trimming_in_the_dialog() { + use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS; + + let dir = temp_dir("project-name-limit"); + let mut h = app_on_a_quad(&dir); + let name = format!("{}Z", "x".repeat(MAX_PROJECT_NAME_CHARS - 1)); + + open_window(&mut h); + type_project_name(&mut h, &format!(" {name} ")); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, name); +} + +#[test] +fn a_reopened_name_field_cannot_undo_to_a_discarded_draft() { + let dir = temp_dir("project-name-history"); + let mut h = app_on_a_quad(&dir); + let original = h.state().session.doc.project.name.clone(); + + open_window(&mut h); + type_project_name(&mut h, "Discard this name"); + + // Drive enough virtual frames for the text edit to record an undo point + h.run_steps(90); + click_in_window(&mut h, Role::Button, "Cancel"); + + open_window(&mut h); + in_window(&h, Role::TextInput, "Project name").focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + h.run_steps(2); + + let field = in_window(&h, Role::TextInput, "Project name"); + assert_eq!(field.accesskit_node().value().as_deref(), Some(original.as_str())); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 49070f1b..8233c5a7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -13,6 +13,12 @@ Everything TextureCraft does is an engine command with a stable id (`layer.add.f Programmatic calls never open dialogs: a command runs with its defaults. Only `ui.menu.invoke` behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and painted tile count, so an agent can verify its work without a screenshot. + +`project.rename {name}` sets the internal project name used by `$project` in export +templates and returns `{name}` with the trimmed value. The name must contain 1–128 +characters after trimming and contain no control characters. Renaming is undoable. +Submitting the current name leaves history unchanged. The project file keeps its own name. + `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. `effect.move {effect, index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies diff --git a/docs/parity.md b/docs/parity.md index 46707737..bf1345ae 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -4,7 +4,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac **63 of 64 menu items live (98%).** -**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 21 yes, 40 no (window 33, os 5, engine-gap 2), 3 partial, 0 unknown.** An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`). +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 21 yes, 39 no (window 33, os 5, engine-gap 1), 4 partial, 0 unknown.** An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`). ## File @@ -32,7 +32,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac |---|---|---|---|---| | Undo | `edit.undo` | Ctrl+Z | live | yes | | Redo | `edit.redo` | Ctrl+Y | live | yes | -| Project Configuration | `ui.projectConfig` | | live | no, reach: engine-gap (project settings could be set by a command) | +| Project Configuration | `ui.projectConfig` | | live | partial, reach: window (the dialog is desktop-only; `project.rename` sets the project name) | | Reimport Mesh | `file.reimportMesh` | Ctrl+Shift+R | live | yes | | Settings | `ui.settings` | | live | no, reach: window (the desktop settings window) |