diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 5e29d054..6e9d006f 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1686,7 +1686,7 @@ fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut } /// A dim info icon explaining a setting on hover -fn info_icon(ui: &mut Ui, text: &str) { +pub(crate) fn info_icon(ui: &mut Ui, text: &str) { ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1196947d..2ded5072 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -44,6 +44,8 @@ mod preview_image; mod preview_request; mod preview_worker; pub mod profile; +#[cfg(not(target_arch = "wasm32"))] +mod project_config; pub mod properties_popup; mod rail_popup; pub mod render_mode; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b5bafea5..9a4d3208 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -164,6 +164,11 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.newProject" => app.ui.windows.new_project = true, "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), + #[cfg(not(target_arch = "wasm32"))] + "ui.projectConfig" => crate::project_config::open(app), + + // The browser cannot change the mesh file, so open Display instead + #[cfg(target_arch = "wasm32")] "ui.projectConfig" => crate::rail_popup::open(app, crate::docking::Panel::Display), "ui.settings" => app.ui.windows.settings = true, "ui.mode.bake" => app.ui.mode = Mode::Baking, @@ -191,6 +196,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { if crate::windows::file_action(app, ctx, id) { return; } + app.run(id, Value::Null); } } @@ -352,6 +358,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Escape closes a dropdown before Properties, the rail popup, color picking or the stroke let popup_open = egui::Popup::is_any_open(ctx); + #[cfg(not(target_arch = "wasm32"))] + let nothing_focused = ctx.memory(|memory| memory.focused().is_none()); let commands_to_invoke = ctx.input_mut(|input| { // egui's label selection copies on these events at the end of the frame let copies: Vec<_> = input.events.iter().filter(|event| matches!(event, egui::Event::Copy | egui::Event::Cut)).cloned().collect(); @@ -371,7 +379,11 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + if app.ui.windows.project_config.is_some() { + // Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched + #[cfg(not(target_arch = "wasm32"))] + crate::project_config::keys_in(app, input, nothing_focused, popup_open); + } else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; @@ -381,6 +393,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.cancel_stroke(); app.session.cancel_path(); } + commands }); @@ -391,6 +404,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Ctrl+V reaches the app only while the system clipboard holds text or an image ctx.copy_text(layer.name.clone()); } + invoke(app, ctx, effect_command(app, id)); } } diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs new file mode 100644 index 00000000..80942b1b --- /dev/null +++ b/crates/ui-egui/src/project_config.rs @@ -0,0 +1,342 @@ +//! Edit > Project Configuration...: the project's settings in sections. Today it has one, the +//! 3D mesh: pick another mesh file for the project, or read the current one again. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use egui::{Key, Modifiers}; +use serde_json::{Value, json}; +use texturecraft_engine::core::NormalFormat; + +use crate::TextureCraftApp; +use crate::dock::info_icon; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{tr, trf}; +use crate::state::ProjectConfig; +use crate::theme::caption; +use crate::widgets::primary_button; + +/// Room for the Select... button and its info icon beside the path. +const SELECT_BUTTON_WIDTH_POINTS: f32 = 150.0; +/// Room for an info icon at the end of a row. +const INFO_WIDTH_POINTS: f32 = 28.0; +/// Keep a usable field when the dialog is narrowed. +const MIN_FIELD_WIDTH_POINTS: f32 = 60.0; +/// Initial width of the configuration dialog. +const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 460.0; +/// Leave space around the centered dialog on short viewports. +const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0; + +/// Opens the window on the current project, with nothing chosen yet. +pub(crate) fn open(app: &mut TextureCraftApp) { + // Layout resets must not reuse an identity held by a pending file picker + static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1); + + app.ui.windows.project_config = Some(ProjectConfig { + mesh: None, + reimport: false, + preserve: true, + normal_format: None, + confirm: false, + project: app.session.project_id, + opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed), + }); +} + +/// `text` with its beginning replaced by an ellipsis until `fits` accepts it (the end of a path +/// is the part that tells files apart). +fn elide_start(text: &str, fits: impl Fn(&str) -> bool) -> String { + if fits(text) { + return text.to_string(); + } + + let chars: Vec = text.chars().collect(); + let shown = |from: usize| format!("…{}", chars[from..].iter().collect::()); + + // Bisection finds the longest tail that fits because each shorter tail also fits + let (mut low, mut high) = (1, chars.len()); + while low < high { + let mid = low + (high - low) / 2; + if fits(&shown(mid)) { + high = mid; + } else { + low = mid + 1; + } + } + + shown(low) +} + +/// The keys of the open window, read in `menus::shortcuts` before any panel draws: Escape closes +/// it (and goes no further, so it doesn't cancel a stroke), Enter confirms it unless a text field +/// or button had the keyboard (`nothing_focused`), whose Enter belongs to it. An open dropdown +/// (`popup_open`) takes both keys first: Escape closes only it, Enter doesn't press OK behind it. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool, popup_open: bool) { + if popup_open { + return; + } + + let escape = input.consume_key(Modifiers::NONE, Key::Escape); + let enter = input.consume_key(Modifiers::NONE, Key::Enter); + + if escape { + app.ui.windows.project_config = None; + } else if enter + && nothing_focused + && let Some(config) = app.ui.windows.project_config.as_mut() + { + config.confirm = true; + } +} + +/// The command OK runs for the mesh: the project moves to `chosen`, or `reimport` (the project's +/// own file, when Reimport mesh is ticked) is read again. `preserve` is the Import settings box. +fn mesh_command(chosen: Option<&str>, reimport: Option<&str>, preserve: bool) -> Option<(&'static str, Value)> { + match (chosen, reimport) { + (Some(path), _) => Some(("file.changeMesh", json!({"path": path, "preserveStrokes": preserve}))), + (None, Some(path)) => Some(("file.reimportMesh", json!({"path": path, "preserveStrokes": preserve}))), + (None, None) => None, + } +} + +fn format_name(format: NormalFormat) -> &'static str { + match format { + NormalFormat::OpenGl => "OpenGL", + NormalFormat::DirectX => "DirectX", + } +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut config) = app.ui.windows.project_config.clone() else { return }; + + // Choices for another project cannot be applied here + if config.project != app.session.project_id { + app.ui.windows.project_config = None; + return; + } + + let project = &app.session.doc.project; + let current_mesh_path = project.mesh_path.clone(); + + // Show the imported name when there is no file path + let mesh_label = if current_mesh_path.is_empty() { project.mesh_file.clone() } else { current_mesh_path.clone() }; + let source_file_available = app.session.remembered_mesh_path().is_some(); + let current_normal_format = project.normal_format; + + // Keep each texture set's tiles together for the read-only list + let texture_set_tiles: Vec<(String, Option)> = project + .texture_sets + .iter() + .map(|set| (set.name.clone(), (!set.uv_tiles.is_empty()).then(|| set.uv_tiles.iter().map(u32::to_string).collect::>().join(", ")))) + .collect(); + + // Re-selecting the current path cancels an earlier choice + let chosen_mesh = config.mesh.as_ref().filter(|chosen| **chosen != current_mesh_path).cloned(); + + let mut open = true; + let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); + + let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open) + .default_width(DEFAULT_DIALOG_WIDTH_POINTS) + .max_height((ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS).max(0.0)) + .vscroll(true); + + dialog.show(ctx, |ui| { + // Keep the project sections in the order users expect + ui.label(caption(tr("3D MESH"))); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.label(tr("3D mesh")); + info_icon(ui, tr("The mesh file the project is built on. Hover the path to see it in full.")); + + let display_path = chosen_mesh.clone().unwrap_or_else(|| mesh_label.clone()); + let font = egui::TextStyle::Body.resolve(ui.style()); + let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS); + let measure = |text: &str| ui.painter().layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points; + + if display_path.is_empty() { + ui.weak(tr("Built-in mesh")); + } else { + ui.label(elide_start(&display_path, measure)).on_hover_text(&display_path); + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, tr("Choose another mesh file for the project. It is read when you press OK.")); + select = ui.button(tr("Select...")).clicked(); + }); + }); + if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available { + ui.colored_label(ui.visuals().error_fg_color, tr("File not found")); + } + + ui.add_space(4.0); + + // A selected replacement always reads the mesh again + // A missing source file cannot be reimported + let mut reimport = config.reimport || chosen_mesh.is_some(); + let can_reimport_source = chosen_mesh.is_none() && source_file_available; + let reimport_checkbox = ui + .horizontal(|ui| { + let checkbox = ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))); + info_icon(ui, tr("Read the mesh file again, keeping the layers and painted strokes")); + checkbox + }) + .inner; + + if can_reimport_source { + config.reimport = reimport; + } else if chosen_mesh.is_none() { + reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); + } + + ui.add_space(8.0); + ui.label(caption(tr("Import settings"))); + + // Import settings matter only when a mesh will be read + let importing = chosen_mesh.is_some() || (config.reimport && source_file_available); + ui.horizontal(|ui| { + ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))); + info_icon(ui, tr("Painted strokes follow the surface when the new mesh's UVs differ")); + }); + + ui.add_space(12.0); + ui.label(caption(tr("PROJECT SETTINGS"))); + ui.add_space(4.0); + let shown_format = config.normal_format.unwrap_or(current_normal_format); + ui.horizontal(|ui| { + ui.label(tr("Normal map format")); + egui::ComboBox::from_id_salt(tr("Normal map format")) + .width((ui.available_width() - INFO_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS)) + .wrap_mode(egui::TextWrapMode::Truncate) + .selected_text(format_name(shown_format)) + .show_ui(ui, |ui| { + for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { + if ui.selectable_label(format == shown_format, format_name(format)).clicked() { + config.normal_format = (format != current_normal_format).then_some(format); + } + } + }) + .response + .on_hover_text(tr( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + )); + info_icon(ui, tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")); + }); + ui.add_space(4.0); + + // Texture Set Settings owns UV tile changes + ui.horizontal(|ui| { + ui.label(tr("UV Tile settings (UDIMs)")); + info_icon(ui, tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings.")); + }); + if texture_set_tiles.iter().all(|(_, tile_text)| tile_text.is_none()) { + ui.label(egui::RichText::new(tr("No UV tiles")).weak()); + } + for (name, tile_text) in texture_set_tiles.iter().filter(|(_, tile_text)| tile_text.is_some()) { + let tile_list = tile_text.as_deref().unwrap_or_default(); + ui.label( + egui::RichText::new(if texture_set_tiles.len() > 1 { + trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)]) + } else { + tile_list.to_string() + }) + .weak(), + ); + } + ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak()); + + ui.add_space(12.0); + ui.label(egui::RichText::new(tr("Choosing or reimporting a mesh recomputes all channels.")).small().weak()); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ok |= ui.add(primary_button(ui, tr("OK"))).clicked(); + cancel = ui.button(tr("Cancel")).clicked(); + }); + }); + }); + + if select { + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + let opening_id = config.opening_id; + app.ask_file(dialog, Bound::Project, move |app, paths| { + let Some(path) = paths.first().map(|p| p.display().to_string()) else { return }; + + let current_mesh_path = app.session.doc.project.mesh_path.clone(); + if let Some(config) = app.ui.windows.project_config.as_mut().filter(|config| config.opening_id == opening_id) { + // Re-selecting the source file drops an earlier choice + config.mesh = (path != current_mesh_path).then_some(path); + } + }); + } + + // Apply the mesh first so a failed mesh change leaves the format untouched + let mut mesh_applied = false; + let done = ok && { + 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 + app.toast(tr("File not found"), true); + config.reimport = false; + false + } else { + match mesh_command(chosen_mesh.as_deref(), reimport.as_deref(), config.preserve) { + Some((command, params)) => app.run(command, params).is_some(), + None => true, + } + }; + + // Another panel may have set the same format while this dialog was open + let format = config.normal_format.filter(|format| *format != app.session.doc.project.normal_format); + mesh_applied + && match format { + Some(format) => { + app.run("textureSet.settings", json!({"normalFormat": if format == NormalFormat::DirectX { "directX" } else { "openGl" }})).is_some() + } + None => true, + } + }; + + if done || cancel || !open { + app.ui.windows.project_config = None; + } else if let Some(stored) = app.ui.windows.project_config.as_mut() { + // A file answer arrives later through the stored state + (stored.reimport, stored.preserve, stored.normal_format, stored.confirm) = (config.reimport, config.preserve, config.normal_format, false); + + // A format retry must not reimport an already changed mesh + if ok && mesh_applied { + (stored.mesh, stored.reimport) = (None, false); + } + } +} + +#[cfg(test)] +mod tests { + use super::{elide_start, mesh_command}; + + #[test] + fn a_path_that_fits_is_unchanged() { + assert_eq!(elide_start("/a/b.obj", |s| s.chars().count() <= 20), "/a/b.obj"); + } + + #[test] + fn a_long_path_loses_its_beginning() { + let shown = elide_start("/home/me/projects/models/hero.obj", |s| s.chars().count() <= 12); + + assert_eq!(shown, "…ls/hero.obj", "the longest tail that fits, not a shorter one"); + } + + #[test] + fn the_import_setting_goes_to_the_command() { + for preserve in [true, false] { + let (command, params) = mesh_command(Some("/a/b.obj"), None, preserve).unwrap(); + + assert_eq!((command, params["preserveStrokes"].as_bool()), ("file.changeMesh", Some(preserve))); + + let (command, params) = mesh_command(None, Some("/a/c.obj"), preserve).unwrap(); + + assert_eq!((command, params["preserveStrokes"].as_bool(), params["path"].as_str()), ("file.reimportMesh", Some(preserve), Some("/a/c.obj"))); + } + + assert!(mesh_command(None, None, true).is_none(), "nothing to read"); + } +} diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index afe85f1a..6826c1a0 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -102,6 +102,7 @@ pub(crate) fn toggle(app: &mut TextureCraftApp, panel: Panel) { } /// Open `panel` from the rail: in its popup, or where it is in the dock (bake mode has no rail) +#[cfg(target_arch = "wasm32")] pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) { if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { app.ui.dock.focus(panel); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 4b0c321d..3b7d7a83 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -9,6 +9,9 @@ use crate::saved_search::SavedSearch; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; +mod project_config; +pub use project_config::ProjectConfig; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { #[default] @@ -79,6 +82,9 @@ pub struct Windows { /// 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, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, diff --git a/crates/ui-egui/src/state/project_config.rs b/crates/ui-egui/src/state/project_config.rs new file mode 100644 index 00000000..33992ec4 --- /dev/null +++ b/crates/ui-egui/src/state/project_config.rs @@ -0,0 +1,18 @@ +/// Edit > Project Configuration: choices waiting for OK +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ProjectConfig { + /// A mesh file picked with Select..., waiting for OK + pub mesh: Option, + /// The user's Reimport mesh selection + pub reimport: bool, + /// Whether painted strokes follow the surface of a newly imported mesh + pub preserve: bool, + /// The selected normal map format when it differs from the project's + pub normal_format: Option, + /// Whether Enter requested confirmation in the next frame + pub confirm: bool, + /// The project that was open when this window opened + pub project: u64, + /// This opening's identity, used to reject late file picker answers + pub(crate) opening_id: u64, +} diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8d573899..0416b022 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -23,6 +23,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { new_project(app, ctx); about(app, ctx); settings(app, ctx); + #[cfg(not(target_arch = "wasm32"))] + crate::project_config::show(app, ctx); crate::keymap::window(app, ctx); crate::windows::export(app, ctx); #[cfg(target_arch = "wasm32")] @@ -152,7 +154,7 @@ pub(crate) fn window<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Win } /// A centered dialog; `id` keeps its place across UI languages. -fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> { +pub(crate) fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> { egui::Window::new(title.to_owned()) .id(egui::Id::unique(id)) .open(open) diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 41b4c8cc..4f454304 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -27,6 +27,7 @@ mod path_in_view; mod path_list; mod pen_pressure; mod polygon_fill; +mod project_config; mod properties_popup; mod rail; mod shelf_drop; diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs new file mode 100644 index 00000000..969c5e5c --- /dev/null +++ b/crates/ui-egui/tests/it/project_config.rs @@ -0,0 +1,719 @@ +//! Edit > Project Configuration...: the 3D mesh section. File pickers are answered by the +//! override, never shown. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; + +mod temp_dir; +use temp_dir::TempDir; + +const QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; +const TRIANGLE: &str = "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"; +/// The format combo's tooltip, which is its accessible label. +const FORMAT_HINT: &str = "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export"; +const TITLE: &str = "Project configuration"; + +fn temp_dir(test: &str) -> TempDir { + TempDir::new(test) +} + +/// An app whose project is the quad in `dir/quad.obj` with a fill layer on it. +fn app_on_a_quad(dir: &std::path::Path) -> Harness<'static, TextureCraftApp> { + let file = dir.join("quad.obj"); + std::fs::write(&file, QUAD).unwrap(); + let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap(); + texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + session.doc.project.mesh_path = file.display().to_string(); + 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 +} + +/// The widget of `role` and `label` inside the window, which sits at the middle of the screen +/// (a panel of the dock may show the same text). +fn in_window<'h>(h: &'h Harness<'_, TextureCraftApp>, role: Role, label: &'h str) -> egui_kittest::Node<'h> { + let middle = egui::pos2(800.0, 480.0); + + h.get_all_by_role_and_label(role, label) + .min_by(|a, b| a.rect().center().distance(middle).total_cmp(&b.rect().center().distance(middle))) + .expect("the widget in the window") +} + +fn click_in_window(h: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + in_window(h, role, label).click(); + h.run_steps(3); +} + +fn open_window(h: &mut Harness<'_, TextureCraftApp>) { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.projectConfig"); + h.run_steps(3); +} + +fn window_is_open(h: &Harness<'_, TextureCraftApp>) -> bool { + h.query_by_label(TITLE).is_some() +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + h.get_by_role_and_label(role, label).click(); + h.run_steps(3); +} + +/// Select... answered with `file`. +fn select(h: &mut Harness<'_, TextureCraftApp>, file: &std::path::Path) { + let file = file.to_path_buf(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![file.clone()])))); + click(h, Role::Button, "Select..."); +} + +/// The Reimport mesh box as the window shows it. +fn reimport_ticked(h: &Harness<'_, TextureCraftApp>) -> bool { + h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +/// The tick the user made themselves, as stored. +fn own_tick(h: &Harness<'_, TextureCraftApp>) -> bool { + h.state().ui.windows.project_config.as_ref().is_some_and(|c| c.reimport) +} + +#[test] +fn the_menu_opens_the_window() { + let dir = temp_dir("menu"); + let mut h = app_on_a_quad(&dir); + + assert!(!window_is_open(&h)); + + open_window(&mut h); + + assert!(window_is_open(&h)); + assert!(h.query_by_label("3D MESH").is_some(), "the 3D mesh section"); + assert!(!reimport_ticked(&h), "nothing is ticked at first"); + assert!(h.state().ui.rail_panel.is_none(), "the Display panel stays where it was"); +} + +#[test] +fn many_texture_sets_keep_dialog_actions_reachable_in_a_short_viewport() { + let dir = temp_dir("many-tiles"); + let mut h = app_on_a_quad(&dir); + let template = h.state().session.doc.project.texture_sets[0].clone(); + h.state_mut().session.doc.project.texture_sets = (0..30) + .map(|index| { + let mut set = template.clone(); + set.name = format!("Set {index}"); + set.uv_tiles = vec![1001]; + set + }) + .collect(); + h.set_size(egui::vec2(800.0, 480.0)); + + open_window(&mut h); + h.get_by_role_and_label(Role::Button, "Cancel").scroll_to_me(); + h.run_steps(3); + + let ok = h.get_by_role_and_label(Role::Button, "OK"); + assert!(ok.rect().top() >= 0.0 && ok.rect().bottom() <= 480.0, "OK must be inside the viewport after scrolling: {:?}", ok.rect()); + let cancel = h.get_by_role_and_label(Role::Button, "Cancel"); + assert!(cancel.rect().top() >= 0.0 && cancel.rect().bottom() <= 480.0, "Cancel must be inside the viewport after scrolling: {:?}", cancel.rect()); + cancel.click(); + h.run_steps(3); + assert!(!window_is_open(&h)); +} + +#[test] +fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() { + let dir = temp_dir("info"); + let mut h = app_on_a_quad(&dir); + + open_window(&mut h); + + let icons: Vec<_> = h.get_all_by_label(egui_phosphor::regular::INFO).collect(); + let tip = "Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it."; + + assert!(h.query_by_label("Choosing or reimporting a mesh recomputes all channels.").is_some(), "the note above the buttons"); + assert_eq!(icons.len(), 6, "mesh path, Select, Reimport mesh, Preserve strokes, Normal map format, UV tiles"); + assert!(h.query_by_label(tip).is_none(), "no tooltip before hovering"); + + // The format icon is fifth in the window's rows + let mut centers: Vec<_> = icons.iter().map(|n| n.rect().center()).collect(); + centers.sort_by(|a, b| a.y.total_cmp(&b.y)); + let format_center = centers[4]; + h.hover_at(format_center); + h.run_steps(30); + + assert!(h.query_by_label(tip).is_some(), "hovering the normal map format icon explains it"); +} + +#[test] +fn another_file_shows_its_path_and_ticks_reimport() { + let dir = temp_dir("select"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + + open_window(&mut h); + select(&mut h, &tri); + + assert!(h.query_by_label_contains("tri.obj").is_some(), "the chosen file is shown"); + assert!(reimport_ticked(&h)); + assert!(!own_tick(&h), "shown ticked, not stored as the user's tick"); + assert_eq!(h.state().session.mesh.triangle_count(), 2, "nothing changes before OK"); +} + +#[test] +fn a_delayed_selection_does_not_change_a_reopened_window() { + let dir = temp_dir("stale-selection"); + let mut harness = app_on_a_quad(&dir); + let triangle = dir.join("tri.obj"); + std::fs::write(&triangle, TRIANGLE).unwrap(); + open_window(&mut harness); + + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![triangle.clone()])))); + harness.get_by_role_and_label(Role::Button, "Select...").click(); + harness.run_steps(1); + + assert_eq!(harness.state().file_dialogs.pending(), 1, "the answer has not been applied yet"); + + harness.state_mut().ui.windows.project_config = None; + open_window(&mut harness); + + assert!(harness.state().ui.windows.project_config.as_ref().is_some_and(|config| config.mesh.is_none())); + assert_eq!(harness.state().file_dialogs.pending(), 0, "the old answer was released"); + + let replacement = dir.join("other.obj"); + std::fs::write(&replacement, TRIANGLE).unwrap(); + select(&mut harness, &replacement); + + assert_eq!(harness.state().ui.windows.project_config.as_ref().and_then(|config| config.mesh.as_deref()), replacement.to_str()); +} + +#[test] +fn a_delayed_selection_does_not_change_a_window_reopened_after_layout_reset() { + let dir = temp_dir("reset-layout-selection"); + let mut harness = app_on_a_quad(&dir); + let triangle = dir.join("tri.obj"); + std::fs::write(&triangle, TRIANGLE).unwrap(); + open_window(&mut harness); + + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![triangle.clone()])))); + harness.get_by_role_and_label(Role::Button, "Select...").click(); + harness.run_steps(1); + + assert_eq!(harness.state().file_dialogs.pending(), 1); + + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.resetUi"); + open_window(&mut harness); + + assert!(harness.state().ui.windows.project_config.as_ref().is_some_and(|config| config.mesh.is_none())); + assert_eq!(harness.state().file_dialogs.pending(), 0); +} + +#[test] +fn ok_moves_the_project_to_the_chosen_mesh_and_keeps_the_layers() { + let dir = temp_dir("ok"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + let layers = h.state().session.doc.project.layers.len(); + + open_window(&mut h); + select(&mut h, &tri); + click(&mut h, Role::Button, "OK"); + let session = &h.state().session; + + assert_eq!(session.mesh.triangle_count(), 1, "the new mesh is in use"); + assert_eq!(session.doc.project.mesh_file, "tri.obj"); + assert!(session.doc.project.mesh_path.ends_with("tri.obj"), "Reimport mesh now follows the new file"); + assert_eq!(session.doc.project.layers.len(), layers, "the layers stay"); + assert!(!window_is_open(&h)); +} + +#[test] +fn ticking_reimport_alone_reads_the_same_file_again() { + let dir = temp_dir("reimport"); + let mut h = app_on_a_quad(&dir); + let project = h.state().session.project_id; + let layers = h.state().session.doc.project.layers.len(); + + // The file changed on disk since it was imported + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + + open_window(&mut h); + click(&mut h, Role::CheckBox, "Reimport mesh"); + + assert!(reimport_ticked(&h) && own_tick(&h)); + + click(&mut h, Role::Button, "OK"); + let session = &h.state().session; + + assert_eq!(session.mesh.triangle_count(), 1, "the edited file was read again"); + assert_eq!(session.project_id, project); + assert_eq!(session.doc.project.layers.len(), layers); + assert!(!window_is_open(&h)); +} + +#[test] +fn ok_with_nothing_chosen_changes_nothing() { + let dir = temp_dir("nothing"); + let mut h = app_on_a_quad(&dir); + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + let mesh = h.state().session.mesh_id; + + open_window(&mut h); + click(&mut h, Role::Button, "OK"); + + assert_eq!(h.state().session.mesh_id, mesh); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + assert!(!window_is_open(&h)); +} + +#[test] +fn cancel_changes_nothing() { + let dir = temp_dir("cancel"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + let mesh = h.state().session.mesh_id; + + open_window(&mut h); + select(&mut h, &tri); + click(&mut h, Role::Button, "Cancel"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.mesh_id, mesh); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + + // Opened again, the old choice is gone + open_window(&mut h); + + assert!(!reimport_ticked(&h)); + assert!(h.state().ui.windows.project_config.as_ref().is_some_and(|c| c.mesh.is_none())); +} + +#[test] +fn escape_closes_the_window_and_leaves_a_stroke_alone() { + let dir = temp_dir("escape"); + let mut h = app_on_a_quad(&dir); + + assert_eq!(h.state().ui.mode, texturecraft_ui_egui::state::Mode::Painting, "Painting is where Escape cancels strokes"); + + texturecraft_engine::execute(&mut h.state_mut().session, "layer.add.paint", &json!({})).unwrap(); + h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + + open_window(&mut h); + h.key_press(egui::Key::Escape); + h.run_steps(3); + + assert!(!window_is_open(&h)); + assert!(h.state().session.stroke_active(), "Escape went to the window, not to the stroke"); +} + +#[test] +fn escape_with_the_dropdown_open_closes_only_the_dropdown() { + let dir = temp_dir("escape-dropdown"); + let mut h = app_on_a_quad(&dir); + + open_window(&mut h); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + + assert!(egui::Popup::is_any_open(&h.ctx), "the dropdown is open"); + + h.key_press(egui::Key::Escape); + h.run_steps(3); + + assert!(!egui::Popup::is_any_open(&h.ctx), "Escape closed the dropdown"); + assert!(window_is_open(&h), "and left the window"); + + h.key_press(egui::Key::Escape); + h.run_steps(3); + + assert!(!window_is_open(&h), "the next Escape closes the window"); +} + +#[test] +fn enter_with_the_dropdown_open_does_not_press_ok() { + let dir = temp_dir("enter-dropdown"); + let mut h = app_on_a_quad(&dir); + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + + open_window(&mut h); + h.state_mut().ui.windows.project_config.as_mut().unwrap().reimport = true; + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + + // Nothing focused, as the shortcut handler needs for Enter to mean OK + h.ctx.memory_mut(|m| { + if let Some(id) = m.focused() { + m.surrender_focus(id); + } + }); + h.run_steps(1); + + assert!(h.ctx.memory(|m| m.focused().is_none()), "nothing has the keyboard"); + assert!(egui::Popup::is_any_open(&h.ctx), "the dropdown is still open"); + + h.key_press(egui::Key::Enter); + h.run_steps(3); + + assert!(window_is_open(&h), "Enter did not press OK behind the dropdown"); + assert_eq!(h.state().session.mesh.triangle_count(), 2, "nothing was applied"); +} + +#[test] +fn ok_after_the_ticked_file_went_missing_reports_it_and_stays_open() { + let dir = temp_dir("ticked-then-missing"); + let mut h = app_on_a_quad(&dir); + + open_window(&mut h); + click_in_window(&mut h, Role::CheckBox, "Reimport mesh"); + + assert!(own_tick(&h)); + + std::fs::remove_file(dir.join("quad.obj")).unwrap(); + h.run_steps(2); + click(&mut h, Role::Button, "OK"); + + assert!(window_is_open(&h), "the window stays open"); + assert!(h.state().toasts.iter().any(|t| t.error && t.text == "File not found"), "the error shows as a toast"); + assert!(!own_tick(&h), "the tick that can't be applied is dropped"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + + click(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h), "a second OK has nothing left to read"); +} + +#[test] +fn enter_confirms_but_not_a_text_fields_enter() { + let dir = temp_dir("enter"); + let mut h = app_on_a_quad(&dir); + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + + open_window(&mut h); + + // Ticked without a click, which would leave the box focused + h.state_mut().ui.windows.project_config.as_mut().unwrap().reimport = true; + + // Renaming a layer: Enter belongs to the text field + let layer = h.state().session.selected_layer().unwrap().0; + let name = h.state().session.doc.project.layers.values().find(|l| l.id.0 == layer).unwrap().name.clone(); + h.state_mut().ui.rename = Some((layer, name)); + h.run_steps(3); + h.key_press(egui::Key::Enter); + h.run_steps(3); + + assert!(h.state().ui.rename.is_none(), "Enter ended the rename"); + assert!(window_is_open(&h), "and did not press OK"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + + // With nothing focused, Enter is OK + h.key_press(egui::Key::Enter); + h.run_steps(3); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.mesh.triangle_count(), 1, "the tick was applied"); +} + +#[test] +fn picking_the_projects_own_file_again_drops_the_choice_and_its_tick() { + let dir = temp_dir("own"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + let mesh = h.state().session.mesh_id; + + open_window(&mut h); + select(&mut h, &tri); + let own = h.state().session.doc.project.mesh_path.clone(); + select(&mut h, std::path::Path::new(&own)); + + assert!(!reimport_ticked(&h), "the tick was only ever the file's"); + + click(&mut h, Role::Button, "OK"); + + assert_eq!(h.state().session.mesh_id, mesh, "OK does nothing"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); +} + +#[test] +fn a_missing_file_cannot_be_reimported() { + let dir = temp_dir("missing"); + let mut h = app_on_a_quad(&dir); + std::fs::remove_file(dir.join("quad.obj")).unwrap(); + + open_window(&mut h); + + assert!(h.query_by_label("File not found").is_some()); + assert!(h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().is_disabled()); + + click(&mut h, Role::Button, "OK"); + + assert_eq!(h.state().file_dialogs.pending(), 0, "no second dialog"); + assert!(!window_is_open(&h)); + assert!(h.state().toasts.is_empty()); +} + +#[test] +fn a_built_in_mesh_shows_its_name_and_has_nothing_to_reimport() { + let dir = temp_dir("builtin"); + let mut h = app_on_a_quad(&dir); + h.state_mut().session.doc.project.mesh_path.clear(); + + open_window(&mut h); + + assert!(h.query_by_label("quad.obj").is_some(), "the name it was imported under"); + assert!(h.query_by_label("File not found").is_none()); + assert!(h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().is_disabled()); + + h.state_mut().session.doc.project.mesh_file.clear(); + h.run_steps(2); + + assert!(h.query_by_label("Built-in mesh").is_some()); +} + +#[test] +fn a_failing_change_is_reported_as_a_toast() { + let dir = temp_dir("error"); + let mut h = app_on_a_quad(&dir); + let missing = dir.join("missing.obj"); + + open_window(&mut h); + select(&mut h, &missing); + click(&mut h, Role::Button, "OK"); + + assert!(h.state().toasts.iter().any(|t| t.error), "the error shows as a toast"); + assert!(window_is_open(&h), "the window stays open"); + assert_eq!(h.state().ui.windows.project_config.as_ref().and_then(|c| c.mesh.clone()), Some(missing.display().to_string()), "with the choice kept"); + assert_eq!(h.state().session.mesh.triangle_count(), 2, "the project keeps its mesh"); +} + +fn project_normal_format(h: &Harness<'_, TextureCraftApp>) -> texturecraft_engine::core::NormalFormat { + h.state().session.doc.project.normal_format +} + +#[test] +fn the_normal_map_format_changes_on_ok_and_shows_in_the_texture_set_panel() { + use texturecraft_engine::core::NormalFormat; + + let dir = temp_dir("normal-format"); + let mut h = app_on_a_quad(&dir); + + open_window(&mut h); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl, "nothing changes before OK"); + + click(&mut h, Role::Button, "OK"); + + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); + + h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::TextureSetSettings); + h.run_steps(3); + + assert!(h.query_all_by_value("DirectX").next().is_some(), "the Texture Set Settings panel shows the project's format"); + + // One undo step puts it back + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + h.run_steps(3); + + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl); +} + +#[test] +fn cancel_discards_a_normal_map_format() { + use texturecraft_engine::core::NormalFormat; + + let dir = temp_dir("normal-format-cancel"); + let mut h = app_on_a_quad(&dir); + + open_window(&mut h); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + click(&mut h, Role::Button, "Cancel"); + + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl); +} + +#[test] +fn uv_tiles_are_shown_read_only() { + let dir = temp_dir("udim"); + let mut h = app_on_a_quad(&dir); + + open_window(&mut h); + + assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some()); + assert!(h.query_by_label("No UV tiles").is_some(), "a project without UV tiles"); + assert!(h.query_by_label("Change them in Texture Set Settings").is_some()); + + click(&mut h, Role::Button, "Cancel"); + + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.uvTiles", &json!({"ts": 0, "enabled": true})).unwrap(); + + open_window(&mut h); + + assert!(h.query_by_label("No UV tiles").is_none()); + assert!(h.query_by_label("1001").is_some(), "the tile list of a UDIM project"); +} + +#[test] +fn preserving_strokes_is_an_import_setting_of_a_mesh_that_is_read() { + let dir = temp_dir("preserve"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + let preserve_is_disabled = + |h: &Harness<'_, TextureCraftApp>| h.get_by_role_and_label(Role::CheckBox, "Preserve stroke positions on mesh").accesskit_node().is_disabled(); + + open_window(&mut h); + + assert!(preserve_is_disabled(&h), "greyed while no mesh is going to be read"); + assert!(h.state().ui.windows.project_config.as_ref().unwrap().preserve, "on by default"); + + select(&mut h, &tri); + + assert!(!preserve_is_disabled(&h)); + + click(&mut h, Role::CheckBox, "Preserve stroke positions on mesh"); + + assert!(!h.state().ui.windows.project_config.as_ref().unwrap().preserve); + + click(&mut h, Role::Button, "OK"); + + assert_eq!(h.state().session.mesh.triangle_count(), 1, "the mesh changed without reprojecting strokes"); +} + +/// The same quad with its UVs mirrored in u. +const MIRRORED_QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 1 0\nvt 0 0\nvt 0 1\nvt 1 1\nf 1/1 2/2 3/3 4/4\n"; + +/// Paints the half of the quad with the larger x on its first layer. +fn paint_the_right_half(h: &mut Harness<'_, TextureCraftApp>) -> texturecraft_engine::core::LayerId { + use texturecraft_engine::core::Channel; + + let session = &mut h.state_mut().session; + let id = session.doc.project.texture_sets[0].stack[0]; + let (size, cells) = { + let cache = &session.caches[0]; + let xs: Vec<(usize, f32)> = + (0..cache.size.0 as usize * cache.size.1 as usize).filter_map(|i| cache.gbuf.surface(&session.mesh, i).map(|p| (i, p.pos.x))).collect(); + let (low, high) = xs.iter().fold((f32::MAX, f32::MIN), |(l, h), (_, x)| (l.min(*x), h.max(*x))); + (cache.size, xs.into_iter().filter(|(_, x)| *x > (low + high) / 2.0).map(|(i, _)| i).collect::>()) + }; + + let image = session.doc.pixels.layer_mut(id, Channel::BaseColor, size); + for i in cells { + image.set(i as u32 % size.0, i as u32 / size.0, &[65535, 0, 0, 65535]); + } + + id +} + +/// Painted texels on the right and on the left half of the quad's surface, away from the middle. +fn painted_halves(h: &Harness<'_, TextureCraftApp>, id: texturecraft_engine::core::LayerId) -> (usize, usize) { + use texturecraft_engine::core::Channel; + + let session = &h.state().session; + let cache = &session.caches[0]; + let image = session.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + let texels: Vec<(u32, u32, f32)> = (0..cache.size.0 * cache.size.1) + .filter_map(|i| cache.gbuf.surface(&session.mesh, i as usize).map(|p| (i % cache.size.0, i / cache.size.0, p.pos.x))) + .collect(); + let (low, high) = texels.iter().fold((f32::MAX, f32::MIN), |(l, h), t| (l.min(t.2), h.max(t.2))); + + // Ignore the center seam where rasterization may place texels on either side + let (middle, margin) = ((low + high) / 2.0, (high - low) * 0.05); + let painted = |x: u32, y: u32| image.get(x, y)[3] > 32768; + let right = texels.iter().filter(|t| t.2 > middle + margin && painted(t.0, t.1)).count(); + let left = texels.iter().filter(|t| t.2 < middle - margin && painted(t.0, t.1)).count(); + + (right, left) +} + +/// OK on a mirrored-UV mesh with the Preserve box as given; returns the painted (right, left) texels afterwards. +fn painted_after_changing_to_mirrored_uvs(test: &str, preserve: bool) -> ((usize, usize), (usize, usize)) { + let dir = temp_dir(test); + let mut h = app_on_a_quad(&dir); + let mirrored = dir.join("mirrored.obj"); + std::fs::write(&mirrored, MIRRORED_QUAD).unwrap(); + let id = paint_the_right_half(&mut h); + let before = painted_halves(&h, id); + + open_window(&mut h); + select(&mut h, &mirrored); + if !preserve { + click(&mut h, Role::CheckBox, "Preserve stroke positions on mesh"); + } + click(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + + (before, painted_halves(&h, id)) +} + +#[test] +fn preserve_on_moves_the_strokes_with_the_surface() { + let (before, after) = painted_after_changing_to_mirrored_uvs("preserve-on", true); + + assert!(before.0 > 2000 && before.1 == 0, "painted on the right half: {before:?}"); + assert!(after.0 > 2000 && after.1 < 200, "still on the right half of the surface: {after:?}"); +} + +#[test] +fn preserve_off_leaves_the_strokes_in_the_uv_layout() { + let (_, after) = painted_after_changing_to_mirrored_uvs("preserve-off", false); + + assert!(after.1 > 2000 && after.0 < 200, "the paint stayed where it was in UV space, now on the left half: {after:?}"); +} + +#[test] +fn a_mesh_and_a_format_change_in_one_ok() { + use texturecraft_engine::core::NormalFormat; + + let dir = temp_dir("both"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + + open_window(&mut h); + select(&mut h, &tri); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + click(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.mesh.triangle_count(), 1); + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); + + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + h.run_steps(3); + + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl, "the format is one undo step"); + assert_eq!(h.state().session.mesh.triangle_count(), 1, "and the mesh stays"); +} + +#[test] +fn a_format_the_project_already_has_is_not_set_again() { + use texturecraft_engine::core::NormalFormat; + + let dir = temp_dir("same-format"); + let mut h = app_on_a_quad(&dir); + + open_window(&mut h); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + + // The Texture Set Settings panel sets it meanwhile + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.settings", &json!({"normalFormat": "directX"})).unwrap(); + let steps = h.state().session.history_labels().len(); + click(&mut h, Role::Button, "OK"); + + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); + assert_eq!(h.state().session.history_labels().len(), steps, "no extra undo step"); +} diff --git a/crates/ui-egui/tests/it/project_config/temp_dir.rs b/crates/ui-egui/tests/it/project_config/temp_dir.rs new file mode 100644 index 00000000..1c3ab71d --- /dev/null +++ b/crates/ui-egui/tests/it/project_config/temp_dir.rs @@ -0,0 +1,27 @@ +use std::path::{Path, PathBuf}; + +/// A test folder removed when its owner drops +pub(super) struct TempDir(PathBuf); + +impl TempDir { + pub(super) fn new(test: &str) -> Self { + let path = std::env::temp_dir().join(format!("texturecraft-project-config-{test}-{}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + + Self(path) + } +} + +impl std::ops::Deref for TempDir { + type Target = Path; + + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index db4046f6..0016e8e9 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -226,9 +226,8 @@ fn window_views_open_the_rail_panels_popup() { assert!(popup_shows(&harness, "Shader Settings")); assert!(!harness.state().ui.dock.is_open(Panel::Shader)); - // Project configuration opens Display Settings, in its popup too - texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.projectConfig"); - harness.run_steps(SETTLE_FRAMES); + // Display Settings still opens from its rail icon + click_rail(&mut harness, "Display Settings"); assert!(popup_shows(&harness, "Display Settings")); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index f57b9070..bb4e036b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -179,6 +179,11 @@ fn window_snapshots() { save(&mut harness, &output_dir, "window-settings"); harness.state_mut().ui.windows.settings = false; + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.projectConfig"); + save(&mut harness, &output_dir, "window-project-configuration"); + harness.state_mut().ui.windows.project_config = None; + // A taller window exposes every mesh-map slot harness.state_mut().ui.dock.focus(Panel::TextureSetSettings); harness.set_size(egui::vec2(1600.0, 1800.0)); @@ -196,6 +201,7 @@ fn window_snapshots() { texturecraft_engine::execute(session, id, ¶ms).unwrap(); } save(&mut harness, &output_dir, "properties-levels"); + // Show the Layers panel thumbnails with a hidden content effect, a folder and a mask let session = &mut harness.state_mut().session; for (id, params) in [ @@ -230,6 +236,7 @@ fn window_snapshots() { } save(&mut harness, &output_dir, "panel-layers"); harness.set_size(egui::vec2(1600.0, 960.0)); + // Show the second path selected in Properties let session = &mut harness.state_mut().session; for (id, params) in [ diff --git a/docs/features.md b/docs/features.md index 925476c9..139d6a27 100644 --- a/docs/features.md +++ b/docs/features.md @@ -84,6 +84,10 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and images and a loose USD layer's textures are read from its folder and kept in the project. Reimport a changed mesh and your painted strokes stay on the surface. The `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. + **Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the + file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. *Import settings* decides whether painted + strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and + lists its UV tiles (read only; Texture Set Settings changes them). - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`).