brep_app/panels/selection.rs
1//! Selection panel — the **selection filter** (which entity kinds a viewport
2//! click may pick), rendered as a row or compact popup in the shell's bottom
3//! STATUS BAR (not a side-panel section). Follows the panel pattern: a small
4//! state struct + a `show_status_bar(&mut self, ui, state)` the bottom bar calls
5//! once per frame in modeling mode; `EngineState` stays the single brain (it owns
6//! the filter + the selection), borrowed in.
7//!
8//! * **Filter** — a leading "All" tristate CHECKBOX followed by a real CHECKBOX
9//! per kind (COMPONENT / SOLID / FACE / EDGE / VERTEX / PLANE; COMPONENT =
10//! promote a pick on assembly-component geometry to the whole component;
11//! PLANE = the construction datum/plane cards, pickable like any face). The
12//! engine honors the filter in
13//! `select_top_at` (via the planes-aware `pick_top_at` with the enabled
14//! kinds), so a plain click grabs only an
15//! allowed kind — a FACE-only filter selects a face, a SOLID-only filter the
16//! owning solid, a PLANE-only filter the construction plane under the cursor. Defaults to ALL kinds enabled (everything under the cursor is
17//! pickable, highest-priority kind wins). Reference-selection mode temporarily
18//! constrains it to the active field's allowed kinds — while that picker is
19//! active the row is LOCKED (greyed + non-interactive) so a click can't
20//! overwrite the constraint. The model state is the engine's `selection_filter`;
21//! this panel just reads/writes it.
22//!
23//! The quick actions on the current selection (Clear / Hide / Edit-owning-feature
24//! + the feature-from-selection actions) live in the dedicated
25//! [`crate::panels::context_bar`] (the engine-native successor to the old app's
26//! floating selection action bar).
27//!
28//! The panel owns only the per-frame `hits` map (widget screen rects) the headed
29//! verifier reads to drive real clicks, exactly like the toolbar/history panels.
30
31use crate::automation::hit_keys::HitKeyDoc;
32use brep_render::engine_state::{EngineState, SelectionFilter};
33use brep_render::engine_state::rename_ops::RenameKind;
34use crate::icon_text::IconTextUi as _;
35use eframe::egui;
36use std::collections::HashMap;
37
38/// The pickable kinds, in the order the filter row draws them: the geometry
39/// kinds coarsest-first, then the CONSTRUCTION kind last. SKETCH sits beside
40/// SOLID because a committed sketch is drawn as a sheet solid and picks as one;
41/// the two lanes split that single pick kind so a sketch can be made pickable
42/// (or not) independently of real bodies. It governs WHOLE sketches — a sketch's
43/// face and its drawn segments stay under Face and Edge.
44/// `(key, label)`: the `key` is the engine kind name + the `hits` map key
45/// suffix; the `label` is the checkbox caption. COMPONENT is the promotion
46/// kind: on, a pick landing on assembly-component geometry selects the WHOLE
47/// component; off, the click reaches the sub-entity kinds. PLANE is the
48/// construction kind: the drawn datum/plane cards, pickable like any face (they
49/// rank right after faces in the pick list, so a plane under geometry is
50/// reachable through the pick-list popup).
51const KINDS: [(&str, &str); 7] = [
52 ("COMPONENT", "Component"),
53 ("SOLID", "Solid"),
54 ("SKETCH", "Sketch"),
55 ("FACE", "Face"),
56 ("EDGE", "Edge"),
57 ("VERTEX", "Vertex"),
58 ("PLANE", "Plane"),
59];
60
61/// The selection panel's own state: the per-frame map of egui widget screen
62/// rects, published to JS for the headed verifier to drive real clicks. Rebuilt
63/// each frame (there is no DOM — egui is drawn on the canvas).
64#[derive(Default)]
65pub struct SelectionPanel {
66 hits: HashMap<String, egui::Rect>,
67 inspection: super::selection_inspection::Cache,
68 /// The compact filter button's caption as last drawn, `None` while the
69 /// full row is drawn instead (published as `__brepFilterButton`).
70 button: Option<String>,
71 /// The in-place rename of the one selected entity, while it is open.
72 rename: Option<RenameEdit>,
73 /// The last rename's outcome (`{ok, old, new, error}`), for the status
74 /// line and the `__brepRename` blob.
75 rename_note: Option<serde_json::Value>,
76}
77
78/// An open in-place rename: what it renames and the text typed so far.
79struct RenameEdit {
80 kind: RenameKind,
81 id: String,
82 text: String,
83 error: Option<String>,
84 focus: bool,
85}
86
87impl SelectionPanel {
88 pub fn new() -> Self {
89 Self::default()
90 }
91
92 /// Draw the selection filter as a row or compact popup in the shell's
93 /// bottom STATUS BAR: a leading "All" tristate checkbox + one CHECKBOX per
94 /// pickable kind (all reflecting the LIVE engine `selection_filter`). Rebuilds
95 /// `hits` as it draws. Called by the bottom bar in modeling mode.
96 pub fn show_status_bar(&mut self, ui: &mut egui::Ui, state: &mut EngineState, document: u64) {
97 let inspection = self.inspection.read(state, document);
98 let mut rename_hits = Vec::new();
99 // `Align::Min` for the same reason as the bar's own row: centring
100 // against the unbounded height below would double the bar.
101 ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
102 // Measurements hold the right end, leaving the filter button room
103 // on a narrow bar; a clipped reading shows in full on hover.
104 if let Some(text) = inspection["text"].as_str().filter(|s| !s.is_empty()) {
105 let width = (ui.available_width() - 100.0).max(0.0);
106 ui.scope(|ui| {
107 ui.set_max_width(width);
108 ui.add(egui::Label::new(text).truncate());
109 });
110 }
111 self.show_rename(ui, state, &mut rename_hits);
112 // The filter becomes a popup when the measurements leave too
113 // little room for all its checkboxes.
114 ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
115 ui.horizontal_wrapped(|ui| self.show_filter_bar(ui, state));
116 });
117 });
118 self.hits.extend(rename_hits);
119 }
120
121 /// The one selected feature, solid, sketch or datum's name, renamed in
122 /// place: the name button (or F2, or Return on macOS with a feature
123 /// selected in the tree) opens a field, Enter renames through the engine
124 /// (one undo step, every reference followed), Esc or leaving the field
125 /// cancels. A refusal keeps the field open with the reason.
126 fn show_rename(&mut self, ui: &mut egui::Ui, state: &mut EngineState, hits: &mut Vec<(String, egui::Rect)>) {
127 let candidate = if state.any_sketch_mode() || state.ref_select_active() { None } else { state.rename_candidate() };
128 let Some((kind, id)) = candidate else {
129 self.rename = None;
130 return;
131 };
132 if self.rename.as_ref().is_some_and(|edit| edit.id != id || edit.kind != kind) {
133 self.rename = None;
134 }
135 if self.rename.is_none() && rename_key_pressed(ui.ctx(), state.selected_feature().is_some()) {
136 self.start_rename(kind, &id);
137 }
138 let Some(edit) = self.rename.as_mut() else {
139 let button = ui.add(egui::Button::new(format!("\u{270E} {id}")).small())
140 .on_hover_text(format!("Rename this {} (F2)", kind.as_str()));
141 hits.push(("selection:rename".into(), button.rect));
142 if button.clicked() {
143 self.start_rename(kind, &id);
144 }
145 return;
146 };
147 if let Some(error) = &edit.error {
148 ui.colored_label(ui.visuals().error_fg_color, error).on_hover_text(error);
149 }
150 let field = ui.add(egui::TextEdit::singleline(&mut edit.text).desired_width(140.0).id_salt("selection:rename:field"));
151 hits.push(("selection:rename:field".into(), field.rect));
152 if edit.focus {
153 field.request_focus();
154 edit.focus = false;
155 }
156 let (enter, escape) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)));
157 if field.lost_focus() && enter {
158 let new = edit.text.trim().to_string();
159 if new == id {
160 self.rename = None;
161 return;
162 }
163 match state.rename_entity(kind, &id, &new) {
164 Ok((rename, _)) => {
165 self.rename_note = Some(serde_json::json!({"ok": true, "old": rename["old"], "new": rename["new"], "error": null}));
166 self.rename = None;
167 }
168 Err(error) => {
169 self.rename_note = Some(serde_json::json!({"ok": false, "old": id, "new": new, "error": error}));
170 edit.error = Some(error);
171 edit.focus = true;
172 }
173 }
174 } else if escape || field.lost_focus() {
175 self.rename = None;
176 }
177 }
178
179 fn start_rename(&mut self, kind: RenameKind, id: &str) {
180 self.rename = Some(RenameEdit { kind, id: id.to_string(), text: id.to_string(), error: None, focus: true });
181 }
182
183 /// The `__brepRename` blob: the rename target the selection offers, whether
184 /// the field is open (its text and refusal), and the last outcome.
185 pub fn rename_json(&self, state: &EngineState) -> String {
186 let candidate = if state.any_sketch_mode() || state.ref_select_active() { None } else { state.rename_candidate() };
187 serde_json::json!({
188 "target": candidate.map(|(kind, id)| serde_json::json!({"kind": kind.as_str(), "id": id})),
189 "open": self.rename.is_some(),
190 "text": self.rename.as_ref().map(|e| e.text.clone()),
191 "error": self.rename.as_ref().and_then(|e| e.error.clone()),
192 "last": self.rename_note,
193 })
194 .to_string()
195 }
196
197 pub fn show_filter_bar(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
198 self.hits.clear();
199 self.button = None;
200 // A loading label can leave only a sliver of the status bar. Never
201 // wrap the filter into that sliver: a popup does not consume viewport
202 // height and remains usable with touch-sized controls. The whole
203 // filter is then ONE button whose caption says what is pickable.
204 if crate::viewport::touch::enabled(ui.ctx()) || ui.available_width() < crate::viewport::touch::NARROW_WIDTH {
205 let caption = button_caption(&state.selection_filter(), state.ref_select_active());
206 self.button = Some(caption.clone());
207 let menu = egui::containers::menu::MenuButton::new(caption)
208 .config(egui::containers::menu::MenuConfig::new()
209 .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside))
210 .ui(ui, |ui| {
211 ui.set_width(240.0_f32.min(ui.ctx().content_rect().width() - 24.0));
212 egui::ScrollArea::vertical()
213 .max_height((ui.ctx().content_rect().height() - 100.0).max(88.0))
214 .show(ui, |ui| self.show_filters(ui, state));
215 });
216 self.hits.insert("filters:toggle".into(), menu.0.rect);
217 } else {
218 ui.horizontal_wrapped(|ui| self.show_filters(ui, state));
219 }
220 }
221
222 pub fn inspection_json(&mut self, state: &mut EngineState, document: u64) -> String {
223 self.inspection.read(state, document).to_string()
224 }
225
226 fn show_filters(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
227 // While the reference-selection picker is active the engine
228 // temporarily CONSTRAINS the filter to the active field's allowed
229 // kinds (see `begin_ref_select`). Letting a bottom-bar click edit it
230 // then would clobber that constraint, so LOCK the row: it still shows
231 // the constrained kinds (greyed) but is non-interactive until the
232 // picker finishes/cancels and the filter is restored.
233 let held = state.filter_override();
234 let locked = state.ref_select_active() || held.is_some();
235 if let (Some(kind), false) = (held, state.ref_select_active()) {
236 // A HELD LETTER overrides this row for as long as it is held
237 // (the viewport's held-letter override): say so, the row greyed
238 // underneath, until the key is released.
239 let resp = ui.label(
240 egui::RichText::new(format!("\u{2328} Key held: only {} pickable", held_kind_label(kind)))
241 .strong()
242 .color(ui.visuals().warn_fg_color),
243 );
244 self.hits.insert("filter:override".into(), resp.rect);
245 resp.on_hover_text("Release the key and this filter is back.");
246 } else if locked {
247 ui.icon_label(egui::RichText::new("\u{1f512} Reference selection — filter locked").weak())
248 .on_hover_text(
249 "The pick filter is set by the field being referenced. \
250 Finish the pick (Done on its field, or Escape) to change it.",
251 );
252 } else {
253 ui.label("Pickable:");
254 }
255
256 // `add_enabled_ui(false, …)` greys the widgets AND makes them
257 // non-interactive, so no `.changed()`/`.clicked()` fires while locked
258 // — the constrained filter cannot be overwritten. Rects are still laid
259 // out and published so the verifier and layout stay consistent.
260 ui.add_enabled_ui(!locked, |ui| {
261 let mut filter = state.bottom_selection_filter();
262 let before = filter;
263
264 // Leading "All" TRISTATE CHECKBOX (mirrors the Scene tree's group
265 // checkbox idiom): checked when EVERY kind is on, the indeterminate
266 // dash when some-but-not-all are on, unchecked when none are.
267 // Toggling it applies the toggle-all semantic — all-on → clear all;
268 // partial or none → set all on — which is exactly the checkbox's
269 // post-click value. Published under `filter:ALL` for the verifier.
270 let all_on = KINDS.iter().all(|(k, _)| filter.get(k));
271 let any_on = KINDS.iter().any(|(k, _)| filter.get(k));
272 let mut all_checked = all_on;
273 let resp = ui.add(
274 egui::Checkbox::new(&mut all_checked, "All").indeterminate(any_on && !all_on),
275 );
276 self.hits.insert("filter:ALL".into(), resp.rect);
277 if resp.changed() {
278 let target = toggle_all_target(&filter);
279 for (kind, _) in KINDS {
280 filter.set(kind, target);
281 }
282 }
283
284 // One CHECKBOX per kind, reflecting the live filter. A `.changed()`
285 // checkbox updates the working copy; it is written back once below.
286 for (kind, label) in KINDS {
287 let mut on = filter.get(kind);
288 let resp = ui.checkbox(&mut on, label);
289 self.hits.insert(format!("filter:{kind}"), resp.rect);
290 if resp.changed() {
291 filter.set(kind, on);
292 }
293 }
294
295 if filter != before {
296 state.set_selection_filter(filter);
297 }
298 });
299 }
300
301 /// Drop the published widget rects. The bottom bar calls this in sketch mode
302 /// (when the filter row is NOT drawn) so the verifier never sees stale
303 /// last-modeling-frame rects for widgets that are no longer on screen.
304 pub fn clear_hits(&mut self) {
305 self.hits.clear();
306 self.button = None;
307 }
308
309 /// The `__brepFilterButton` verifier global: `{shown, label}` — whether
310 /// the filter is collapsed to its one button, and the button's caption.
311 pub fn button_json(&self) -> String {
312 serde_json::json!({ "shown": self.button.is_some(), "label": self.button }).to_string()
313 }
314
315 /// The published widget hit-rects (egui points) for the headed verifier —
316 /// `filter:COMPONENT|SOLID|FACE|EDGE|VERTEX|PLANE` (the per-kind checkboxes)
317 /// + `filter:ALL` (the leading "All" tristate checkbox).
318 pub fn hits_json(&self) -> String {
319 crate::automation::hit_rects::hits_json(&self.hits)
320 }
321}
322
323/// The compact filter button's caption: what a click may pick, so the state
324/// shows without opening the popup. "All" and "None" for the two ends, the
325/// kind names for one or two, a count beyond that; a reference pick's
326/// constraint is marked locked (the popup cannot change it).
327/// F2 starts a rename; on macOS so does Return while a feature is selected in
328/// the tree, as Finder does. Never while a text field has the keyboard.
329fn rename_key_pressed(ctx: &egui::Context, tree_feature: bool) -> bool {
330 if ctx.egui_wants_keyboard_input() {
331 return false;
332 }
333 let mac = ctx.os() == egui::os::OperatingSystem::Mac;
334 ctx.input(|i| {
335 let plain = !i.modifiers.any();
336 plain && (i.key_pressed(egui::Key::F2) || (mac && tree_feature && i.key_pressed(egui::Key::Enter)))
337 })
338}
339
340fn button_caption(filter: &SelectionFilter, locked: bool) -> String {
341 let on: Vec<&str> = KINDS.iter().filter(|(k, _)| filter.get(k)).map(|(_, label)| *label).collect();
342 let what = match on.len() {
343 0 => "None".to_string(),
344 n if n == KINDS.len() => "All".to_string(),
345 1 | 2 => on.join(", "),
346 n => format!("{n} of {}", KINDS.len()),
347 };
348 if locked { format!("Filter (locked): {what}") } else { format!("Filter: {what}") }
349}
350
351/// The "toggle all" target value: if EVERY pickable kind is currently on, the
352/// "All" checkbox turns them all OFF; otherwise (some-but-not-all on, or none on)
353/// it turns them all ON. Returns the value to write to every kind.
354fn toggle_all_target(filter: &SelectionFilter) -> bool {
355 !KINDS.iter().all(|(k, _)| filter.get(k))
356}
357
358
359/// The hit keys this panel publishes (see `automation::hit_keys`).
360pub static HIT_KEYS: &[HitKeyDoc] = &[
361 HitKeyDoc { panel: "selection", prefix: "selection:rename", meaning: "rename the one selected feature, solid, sketch or datum in place (F2; Return on macOS with a feature selected in the tree): selection:rename opens the field, selection:rename:field is the field (Enter renames everywhere, one undo step; Esc cancels)", command: Some("entity_rename") },
362 HitKeyDoc { panel: "selection", prefix: "filters:toggle", meaning: "show or hide pickable filters when the status bar is compact", command: None },
363 HitKeyDoc { panel: "selection", prefix: "filter:", meaning: "toggle which entity kinds a click may pick (filter:ALL, filter:kind); filter:override is the note shown while a held letter (S/F/E/V/C/P, D for faces in PCB) overrides the row", command: None },
364];
365
366/// How the held-letter override's kind reads in the filter row.
367fn held_kind_label(kind: &str) -> &'static str {
368 match kind {
369 "SOLID" => "solids",
370 "FACE" => "faces",
371 "EDGE" => "edges",
372 "VERTEX" => "vertices",
373 "COMPONENT" => "components",
374 "PLANE" => "planes",
375 _ => "?",
376 }
377}