From 6f2c739f5bfccadcbd2a339299ad5daea35bc3a9 Mon Sep 17 00:00:00 2001 From: Ben Chan Date: Wed, 25 Nov 2026 01:14:12 +0800 Subject: [PATCH] Link a whole selection to one object at once, and unlink it at once. --- src/app.rs | 2 +- src/editor.rs | 141 ++++++++++++++++++++++++++++++++++++++++++++++--- src/ui_edit.rs | 98 ++++++++++++++++++++++++++++++++++ 3 files changed, 233 insertions(+), 8 deletions(-) diff --git a/src/app.rs b/src/app.rs index cb938ee6..76175dd4 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2269,7 +2269,7 @@ impl App { self.ed.cancel_edge_snap(); } else if std::mem::take(&mut self.ed.cutting) { // (only the knife goes, the selection stays) - } else if self.ed.link_pick.take().is_some() { + } else if self.ed.link_pick.take().is_some() | self.ed.link_pick_many.take().is_some() { // (only the linking is called off, the object stays selected) } else if self.ed.take_path_connect() { // (only the path connect is called off, the point stays picked) diff --git a/src/editor.rs b/src/editor.rs index 2dbc3379..3a4ed479 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -755,6 +755,9 @@ pub struct Editor { pub picked: Option<(Option, Option)>, /// An object waiting for the one it takes its state from (`[varparent]`) to be clicked. pub link_pick: Option<(TileKey, i64)>, + /// Every object of a selection waiting for the one they all take their state from: the + /// same click as `link_pick`, once for the whole selection. + pub link_pick_many: Option>, /// The next click reads an asset off the map, or puts an object onto the spline clicked. pub sample: Option, /// Free objects waiting for the spline they should stand on (`Sample::Attach`). @@ -948,6 +951,7 @@ impl Default for Editor { pick_mode: false, picked: None, link_pick: None, + link_pick_many: None, sample: None, attach_to: Vec::new(), sample_browser: false, @@ -1500,6 +1504,7 @@ impl Editor { self.ramp_start = None; self.water_pts.clear(); self.link_pick = None; + self.link_pick_many = None; self.sample = None; self.attach_to.clear(); self.sample_browser = false; @@ -2630,6 +2635,14 @@ impl Editor { } return; } + // (several at once: the same click, and every one of them takes its state from it) + if let (Some(many), Tool::Select) = (self.link_pick_many.take(), self.tool) { + match self.hover { + Some(Sel::Object(_, p) | Sel::Attached(_, p)) => self.link_many_to(&many, p), + _ => self.toast(tr("No object clicked: nothing linked", "Объект не выбран: ничего не связано")), + } + return; + } if self.pick_mode && self.tool == Tool::Select { self.picked = Some((self.hover, self.cursor)); return; @@ -9891,20 +9904,80 @@ impl Editor { /// The object clicked while linking: `id` takes its state from it, unless that would /// close a ring (it takes its own state, through others, from `id`). fn link_to(&mut self, k: TileKey, id: i64, parent: i64) { - let Some(doc) = self.doc.as_ref() else { return }; + if self.link_rings(id, parent) { + self.toast(tr("That object already takes its state from this one", "Тот объект сам берёт состояние от этого")); + return; + } + self.set_var_parent(k, id, Some(parent)); + self.toast(tr("Linked", "Связано")); + } + + /// Whether `id` taking its state from `parent` would close a ring: `parent` already takes + /// its state, through others, from `id`. + fn link_rings(&self, id: i64, parent: i64) -> bool { + let Some(doc) = self.doc.as_ref() else { return false }; let mut at = Some(parent); for _ in 0..64 { match at { - Some(p) if p == id => { - self.toast(tr("That object already takes its state from this one", "Тот объект сам берёт состояние от этого")); - return; - } + Some(p) if p == id => return true, Some(p) => at = selection::var_parent_of(doc, p), None => break, } } - self.set_var_parent(k, id, Some(parent)); - self.toast(tr("Linked", "Связано")); + false + } + + /// Every one of these takes its state from `parent` (`[varparent]`), as one step: a + /// selection of signal heads on one crossing, of stop displays on one stop. The ones the + /// link would close a ring on, and `parent` itself, are left as they are. + pub fn link_many_to(&mut self, many: &[(TileKey, i64)], parent: i64) { + let take: Vec<(TileKey, i64)> = many.iter().copied().filter(|(_, id)| *id != parent && !self.link_rings(*id, parent)).collect(); + if take.is_empty() { + self.toast(tr("That object already takes its state from this one", "Тот объект сам берёт состояние от этого")); + return; + } + let Some(doc) = self.doc.as_mut() else { return }; + let n = take.len(); + self.history.begin(tr("Link to an object", "Связать с объектом")); + for (k, id) in take { + self.history.touch_tile(doc, k); + if let Some(o) = selection::any_object_mut(doc, k, id) { + o.var_parent = Some(parent); + } else if let Some(a) = doc.attachment_mut(k, id) { + a.var_parent = Some(parent); + } + if let Some(t) = doc.tiles.get_mut(&k) { + t.touch_content(); + } + } + self.history.commit(); + self.toast(format!("{} {n}", tr("Linked", "Связано"))); + } + + /// Every one of these forgets the object it takes its state from (`[varparent]`), as one + /// step. + pub fn unlink_many(&mut self, many: &[(TileKey, i64)]) { + let linked: Vec<(TileKey, i64)> = match self.doc.as_ref() { + Some(doc) => many.iter().copied().filter(|(k, id)| crate::selection::state_holder(doc, *k, *id).and_then(|(_, p, _)| p).is_some()).collect(), + None => return, + }; + if linked.is_empty() { + return; + } + let Some(doc) = self.doc.as_mut() else { return }; + self.history.begin(tr("Unlink", "Отвязать")); + for (k, id) in linked { + self.history.touch_tile(doc, k); + if let Some(o) = selection::any_object_mut(doc, k, id) { + o.var_parent = None; + } else if let Some(a) = doc.attachment_mut(k, id) { + a.var_parent = None; + } + if let Some(t) = doc.tiles.get_mut(&k) { + t.touch_content(); + } + } + self.history.commit(); } /// Which light of its parent's program a signal head shows (its first label). @@ -14727,6 +14800,60 @@ mod tests { assert_eq!(d.attachment((0, 0), 3).unwrap().strings, vec!["5".to_string()]); } + /// Several objects take their state from one object at once, in one step; a link that + /// would close a ring, and the parent itself, are left out; unlinking them is one step too. + #[test] + fn a_whole_selection_takes_its_state_from_one_object() { + let mut doc = flat_map(1); + for (id, x) in [(1, 100.0), (2, 110.0), (3, 120.0), (4, 130.0)] { + add_object(&mut doc, (0, 0), id, x, 100.0); + } + let mut ed = Editor::default(); + ed.open(doc); + let sels = [((0, 0), 2), ((0, 0), 3), ((0, 0), 4)]; + ed.set_selection(sels.iter().map(|(k, id)| Sel::Object(*k, *id)).collect()); + ed.link_many_to(&sels, 1); + { + let d = ed.doc.as_ref().unwrap(); + for (_, id) in sels { + assert_eq!(crate::selection::var_parent_of(d, id), Some(1), "object {id}"); + } + assert_eq!(crate::selection::var_parent_of(d, 1), None, "the parent takes its state from nothing"); + } + // (the whole lot is one step) + ed.undo(); + { + let d = ed.doc.as_ref().unwrap(); + for (_, id) in sels { + assert_eq!(crate::selection::var_parent_of(d, id), None, "object {id} undone"); + } + } + // (the parent among the picked ones is not linked to itself) + ed.link_many_to(&[((0, 0), 1), ((0, 0), 2)], 1); + { + let d = ed.doc.as_ref().unwrap(); + assert_eq!(crate::selection::var_parent_of(d, 1), None); + assert_eq!(crate::selection::var_parent_of(d, 2), Some(1)); + } + // (3 takes its state from 1: 1 taking it from 3 would close a ring, and is left out) + ed.link_many_to(&[((0, 0), 3)], 1); + ed.link_many_to(&[((0, 0), 1)], 3); + { + let d = ed.doc.as_ref().unwrap(); + assert_eq!(crate::selection::var_parent_of(d, 3), Some(1)); + assert_eq!(crate::selection::var_parent_of(d, 1), None, "no ring"); + } + // (and forgetting it, for several at once) + ed.unlink_many(&[((0, 0), 2), ((0, 0), 3)]); + { + let d = ed.doc.as_ref().unwrap(); + assert_eq!(crate::selection::var_parent_of(d, 2), None); + assert_eq!(crate::selection::var_parent_of(d, 3), None); + } + ed.undo(); + assert_eq!(ed.doc.as_ref().and_then(|d| crate::selection::var_parent_of(d, 3)), Some(1), "one step back"); + } + #[test] fn omsis_n_puts_the_chosen_object_at_the_cursor_and_takes_it() { let lib = Library::default(); diff --git a/src/ui_edit.rs b/src/ui_edit.rs index 71bb5f47..6e3e88a6 100644 --- a/src/ui_edit.rs +++ b/src/ui_edit.rs @@ -538,6 +538,7 @@ pub fn group_properties(ui: &mut egui::Ui, ed: &mut Editor, lib: &Library, paren } }); }); + link_group_section(ui, ed, lib); array_section(ui, ed, lib); parallel_section(ui, ed, lib); rows_section(ui, ed, lib); @@ -1351,6 +1352,103 @@ pub fn link_section(ui: &mut egui::Ui, ed: &mut Editor, lib: &Library, k: TileKe } } +/// The same link (`[varparent]`) for a whole selection: every object in it takes its state +/// from the object clicked next, or forgets the one it takes it from, as one step. A row of +/// signal heads on one crossing, or of stop displays on one stop, is set at once. +pub fn link_group_section(ui: &mut egui::Ui, ed: &mut Editor, lib: &Library) { + let records: Vec<(TileKey, i64)> = ed + .selection() + .iter() + .filter_map(|s| match s { + Sel::Object(k, id) | Sel::Attached(k, id) => Some((*k, *id)), + Sel::Spline(..) => None, + }) + .collect(); + if records.is_empty() { + return; + } + let parents: Vec> = { + let Some(doc) = ed.doc.as_ref() else { return }; + records.iter().map(|(k, id)| crate::selection::state_holder(doc, *k, *id).and_then(|(_, p, _)| p)).collect() + }; + let linked = parents.iter().filter(|p| p.is_some()).count(); + // (what they all take their state from, when it is the same one: else the row is blank) + let first = parents.first().copied().flatten(); + let common = first.filter(|p| parents.iter().all(|q| *q == Some(*p))); + let parent = common.map(|pid| { + let at = ed.links_of(records[0].1, Some(pid)).0.map(|(k, _)| k); + let name = ed + .doc + .as_ref() + .and_then(|d| crate::selection::file_by_id(d, pid)) + .map(|f| lib.find(&f).map(|a| a.name.clone()).unwrap_or_else(|| f.rsplit('\\').next().unwrap_or(&f).to_string())) + .unwrap_or_default(); + (pid, at, name) + }); + let picking = ed.link_pick_many.is_some(); + let mut go: Option = None; + let mut start = false; + let mut stop = false; + let mut unlink = false; + section(ui, Icon::Link, &format!("{} ({linked})", tr("Linked objects", "Связанные объекты"))); + egui::Frame::new().inner_margin(Margin::same(8)).show(ui, |ui| { + ui.label(RichText::new(tr("An object can take its state from another ([varparent]): a signal head shows a light of its crossing's program, a stop's display its stop.", "Объект может брать состояние от другого ([varparent]): светофор показывает сигнал программы своего перекрёстка, табло остановки — свою остановку.")).small().color(pal().text_dim)); + match (&parent, linked) { + (Some((pid, at, name)), _) => { + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(tr("Takes its state from", "Берёт состояние от")).color(pal().text_dim)); + let r = ui.link(name).on_hover_text(format!("{} {pid}", tr("Select it: IDCode", "Выбрать его: IDCode"))); + if r.clicked() { + if let (Some(doc), Some(k)) = (ed.doc.as_ref(), *at) { + go = Some(crate::selection::as_sel(doc, k, *pid)); + } + } + }); + } + (None, 0) => { + ui.label(RichText::new(tr("Takes its state from nothing", "Ни от чего не берёт состояние")).color(pal().text_dim)); + } + (None, _) => { + // (from different ones: each object's own panel names its own) + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(tr("Takes its state from", "Берёт состояние от")).color(pal().text_dim)); + ui.label(RichText::new("—").color(pal().text_dim)); + }); + } + } + ui.horizontal_wrapped(|ui| { + let label = if picking { + tr("Click the object in the view… (Esc)", "Щёлкните объект в виде… (Esc)") + } else if linked > 0 { + tr("Link to another…", "Связать с другим…") + } else { + tr("Link to an object…", "Связать с объектом…") + }; + if ui.add(egui::Button::new(icons::labelled(Icon::Traffic, label)).selected(picking)).on_hover_text(tr("Then click the object it is to take its state from (a crossing for a signal head)", "Затем щёлкните объект, от которого брать состояние (перекрёсток для светофора)")).clicked() { + if picking { + stop = true; + } else { + start = true; + } + } + if linked > 0 && ui.button(icons::labelled(Icon::LinkOff, tr("Unlink", "Отвязать"))).clicked() { + unlink = true; + } + }); + }); + if let Some(s) = go { + ed.select(Some(s)); + } else if unlink { + ed.unlink_many(&records); + } else if stop { + ed.link_pick_many = None; + } else if start { + ed.link_pick = None; + ed.link_pick_many = Some(records); + ed.toast(tr("Click the object it takes its state from", "Щёлкните объект, от которого брать состояние")); + } +} + /// A road's free ends: put a junction piece onto one (its helper made for this road type meets /// the end), the piece picked from those that fit, the road type's preferred one first. pub fn end_junction_section(ui: &mut egui::Ui, ed: &mut Editor, lib: &Library, actions: &mut Vec) {