diff --git a/src/app_mesh.rs b/src/app_mesh.rs index f526b47..0ca9fec 100644 --- a/src/app_mesh.rs +++ b/src/app_mesh.rs @@ -48,9 +48,7 @@ impl App { _ => false, }; if !keep { - if let Some(mut m) = self.ed.mesh.take() { - self.write_mesh(&mut m, true); - } + self.drop_mesh_session(false); if let Some((rel, s)) = want { self.ed.mesh = Session::open(&roots, &rel, s); } @@ -142,6 +140,15 @@ impl App { /// Write the session's object if it changed (at once with `now`), and have its model read /// and drawn again. pub(super) fn write_mesh(&mut self, m: &mut Session, now: bool) { + // (the first change is what hands the map object the copy of its own: until then a Tab + // and a Tab back leaves neither a copy nor a changed map, see `toggle_edit_mode`) + if m.dirty { + if let Some(rel) = m.made.take() { + crate::meshops::point_at(&mut self.ed, m.inst, &rel); + self.mesh_known = Some((rel, true)); + self.ed.toast(tr("A copy of its own was made: the original type is unchanged", "Создана собственная копия: исходный тип не изменён")); + } + } let Some(roots) = self.roots.clone() else { return }; // (what follows the ground follows it where this object stands) let place = m.place; @@ -178,17 +185,36 @@ impl App { } } - /// Into the edit mode of the selected object (made an openMapper object of its own first - /// if it is not one), or out of it. + /// Let the edit session go: what was changed is written, and if nothing was changed the + /// copy of its own made only to read the mesh is taken away again. (Leaving is not itself a + /// change: marking it dirty rewrote the object and dropped its model, so the mesh vanished + /// until the files were read again.) + /// `stay`: the session is kept (out of the edit mode) when it was written, as a Tab out of + /// the edit mode keeps the object's mesh at hand; else it is let go. + fn drop_mesh_session(&mut self, stay: bool) { + let Some(mut m) = self.ed.mesh.take() else { return }; + if let (Some(rel), false) = (m.made.clone(), m.dirty) { + // (the map object never pointed at that copy, so there is nothing to undo either) + if let Some(roots) = self.roots.clone() { + crate::meshops::discard_copy(&roots, &rel); + } + self.mesh_known = None; + return; + } + self.write_mesh(&mut m, true); + if stay { + self.ed.mesh = Some(m); + } + } + + /// Into the edit mode of the selected object (reading a copy of its own if it is not one of + /// openMapper's yet), or out of it. A Tab pressed by mistake leaves nothing behind: the map + /// object is handed the copy at the first change, and the copy goes if there was none. pub(super) fn toggle_edit_mode(&mut self) { if let Some(m) = self.ed.mesh.as_mut().filter(|m| m.editing) { m.cancel(); m.editing = false; - // (leaving is not itself a change: marking it dirty rewrote the object and dropped - // its model, so the mesh vanished until the files were read again) - let mut m = self.ed.mesh.take().unwrap(); - self.write_mesh(&mut m, true); - self.ed.mesh = Some(m); + self.drop_mesh_session(true); return; } let Some(sel @ Sel::Object(..)) = self.ed.selected else { @@ -197,11 +223,18 @@ impl App { }; if self.ed.mesh.is_none() { let Some(roots) = self.roots.clone() else { return }; - match crate::meshops::make_editable(&mut self.ed, &roots, &self.lib, sel) { + let was = self.ed.doc.as_ref().and_then(|d| match sel { + Sel::Object(k, id) => d.object(k, id).map(|o| o.file.clone()), + _ => None, + }); + match crate::meshops::copy_for_edit(&mut self.ed, &roots, &self.lib, sel) { Ok(rel) => { self.mesh_known = Some((rel.clone(), true)); - self.ed.mesh = Session::open(&roots, &rel, sel); - self.ed.toast(tr("A copy of its own was made: the original type is unchanged", "Создана собственная копия: исходный тип не изменён")); + let Some(mut m) = Session::open(&roots, &rel, sel) else { return }; + if !was.as_deref().map(|w| w.eq_ignore_ascii_case(&rel)).unwrap_or(false) { + m.made = Some(rel.clone()); + } + self.ed.mesh = Some(m); } Err(e) => { self.ed.error(format!("{}: {e}", tr("Cannot edit this object", "Этот объект нельзя редактировать"))); diff --git a/src/meshedit.rs b/src/meshedit.rs index 8211dcd..9757d56 100644 --- a/src/meshedit.rs +++ b/src/meshedit.rs @@ -67,6 +67,10 @@ pub struct Session { /// The object's file, and the map object it is edited on. pub rel: String, pub inst: Sel, + /// A copy of its own made only so that the mesh could be read, which the map object does + /// not point at yet: it is handed the copy at the first change, and the copy goes when the + /// edit mode is left before anything was changed. + pub made: Option, pub src: Source, /// The part being edited. pub part: usize, @@ -106,6 +110,7 @@ impl Session { Some(Session { rel: rel.to_string(), inst, + made: None, src, part: 0, mode: SelectMode::Vertex, diff --git a/src/meshops.rs b/src/meshops.rs index a725858..8212d8a 100644 --- a/src/meshops.rs +++ b/src/meshops.rs @@ -119,9 +119,11 @@ fn delete_object(ed: &mut Editor, k: TileKey, id: i64) { doc.delete_object(k, id); } -/// The selected object made an openMapper object of its own (a copy of its type): what its -/// mesh, materials and lamps are can then be edited. Its file, or the new one. -pub fn make_editable(ed: &mut Editor, roots: &Roots, lib: &Library, sel: Sel) -> anyhow::Result { +/// The selected object's editable source: the file it has when it is an openMapper object +/// already, or a copy of its type made beside the map's own objects. The map object keeps the +/// file it had: [`point_at`] is what hands it the copy, so a Tab pressed by mistake can be +/// taken back with [`discard_copy`] and leave neither a copy nor a changed map. +pub fn copy_for_edit(ed: &mut Editor, roots: &Roots, lib: &Library, sel: Sel) -> anyhow::Result { let p = placed(ed, lib, sel).ok_or_else(|| anyhow::anyhow!("{}", tr("select an object first", "сначала выделите объект")))?; if editable::is_editable(roots, &p.obj.file) { return Ok(p.obj.file); @@ -129,9 +131,37 @@ pub fn make_editable(ed: &mut Editor, roots: &Roots, lib: &Library, sel: Sel) -> let (rel, dir) = new_for(roots, ed, &p.obj.file, ""); let src = editable::source_of(roots, &p.obj.file, &dir)?; editable::save(roots, &rel, &src)?; + // (the catalogue need not be read again, and the models need not be dropped, for a copy + // made only to be edited: a Tab pressed by mistake should cost nothing at all) + crate::hot::own_change(); + Ok(rel) +} + +/// The map object pointed at `rel`, one of openMapper's own (one undo step). +pub fn point_at(ed: &mut Editor, sel: Sel, rel: &str) { + let Sel::Object(k, id) = sel else { return }; ed.history.begin(tr("Make editable", "Сделать редактируемым")); - set_file(ed, p.k, p.obj.id, &rel); + set_file(ed, k, id, rel); ed.history.commit(); +} + +/// A copy made only to read an object's mesh, and left as it was: its folder goes. Nothing +/// points at it, so nothing else changes. +pub fn discard_copy(roots: &Roots, rel: &str) { + let (dir, _) = editable::folder_of(roots, rel); + let _ = std::fs::remove_dir_all(dir); + // (its going is not the catalogue's news either) + crate::hot::own_change(); +} + +/// The selected object made an openMapper object of its own (a copy of its type): what its +/// mesh, materials and lamps are can then be edited. Its file, or the new one. +pub fn make_editable(ed: &mut Editor, roots: &Roots, lib: &Library, sel: Sel) -> anyhow::Result { + let was = placed(ed, lib, sel).map(|p| p.obj.file); + let rel = copy_for_edit(ed, roots, lib, sel)?; + if !was.as_deref().map(|w| w.eq_ignore_ascii_case(&rel)).unwrap_or(false) { + point_at(ed, sel, &rel); + } Ok(rel) } @@ -365,3 +395,78 @@ pub fn boolean(ed: &mut Editor, roots: &Roots, lib: &Library, op: Bool, keep: bo ed.set_selection(out.clone()); Ok(out) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::selection::tests::{add_object, flat_map}; + + fn roots(tag: &str) -> (std::path::PathBuf, Roots) { + let dir = std::env::temp_dir().join(format!("om-meshops-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("content")).unwrap(); + std::fs::create_dir_all(dir.join("omsi")).unwrap(); + (dir.clone(), Roots { omsi: dir.join("omsi"), content: dir.join("content") }) + } + + /// An object of the installation: its `.sco` and its meshes, and no openMapper source + /// beside it. + fn an_installed_object(roots: &Roots) -> String { + let rel = "Sceneryobjects\\Test\\Lamp\\Lamp.sco".to_string(); + let src = crate::editable::primitive_source(openmapper_mesh::primitives::Primitive::Cube { size: Vec3::splat(1.0) }); + crate::editable::save(roots, &rel, &src).unwrap(); + let (dir, _) = crate::editable::folder_of(roots, &rel); + for e in std::fs::read_dir(&dir).unwrap().flatten() { + if e.path().extension().map(|x| x == "json").unwrap_or(false) { + let _ = std::fs::remove_file(e.path()); + } + } + assert!(!crate::editable::is_editable(roots, &rel)); + rel + } + + /// A Tab on an object that is not openMapper's reads a copy of its own, but the map object + /// keeps the file it had: taken back, nothing is left and nothing has to be undone. + #[test] + fn a_copy_for_reading_a_mesh_leaves_the_map_alone_until_it_is_wanted() { + let (dir, roots) = roots("stray"); + let rel = an_installed_object(&roots); + let mut doc = flat_map(1); + add_object(&mut doc, (0, 0), 1, 100.0, 100.0); + doc.tiles.get_mut(&(0, 0)).unwrap().tile.objects[0].file = rel.clone(); + let mut ed = Editor::default(); + ed.open(doc); + let lib = Library::default(); + let sel = Sel::Object((0, 0), 1); + let copy = copy_for_edit(&mut ed, &roots, &lib, sel).unwrap(); + assert!(!copy.eq_ignore_ascii_case(&rel), "a copy of its own: {copy}"); + assert!(crate::editable::is_editable(&roots, ©)); + assert_eq!(ed.doc.as_ref().unwrap().object((0, 0), 1).unwrap().file, rel, "the map still names the object it had"); + assert!(!ed.history.can_undo(), "reading the mesh is not a change of the map"); + // (a Tab and a Tab back: the copy goes, and nothing else does) + discard_copy(&roots, ©); + assert!(!crate::editable::folder_of(&roots, ©).0.exists(), "no folder left behind"); + assert_eq!(ed.doc.as_ref().unwrap().object((0, 0), 1).unwrap().file, rel); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The first change hands the map object the copy, in one step that can be undone. + #[test] + fn pointing_at_the_copy_is_one_step_of_the_map() { + let (dir, roots) = roots("point"); + let rel = an_installed_object(&roots); + let mut doc = flat_map(1); + add_object(&mut doc, (0, 0), 1, 100.0, 100.0); + doc.tiles.get_mut(&(0, 0)).unwrap().tile.objects[0].file = rel.clone(); + let mut ed = Editor::default(); + ed.open(doc); + let lib = Library::default(); + let sel = Sel::Object((0, 0), 1); + let copy = copy_for_edit(&mut ed, &roots, &lib, sel).unwrap(); + point_at(&mut ed, sel, ©); + assert_eq!(ed.doc.as_ref().unwrap().object((0, 0), 1).unwrap().file, copy); + ed.undo(); + assert_eq!(ed.doc.as_ref().unwrap().object((0, 0), 1).unwrap().file, rel, "one step back"); + let _ = std::fs::remove_dir_all(&dir); + } +}