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 crate::icon_text::IconTextUi as _;
34use eframe::egui;
35use std::collections::HashMap;
36
37/// The pickable kinds, in the order the filter row draws them: the geometry
38/// kinds coarsest-first, then the CONSTRUCTION kind last. SKETCH sits beside
39/// SOLID because a committed sketch is drawn as a sheet solid and picks as one;
40/// the two lanes split that single pick kind so a sketch can be made pickable
41/// (or not) independently of real bodies. It governs WHOLE sketches — a sketch's
42/// face and its drawn segments stay under Face and Edge.
43/// `(key, label)`: the `key` is the engine kind name + the `hits` map key
44/// suffix; the `label` is the checkbox caption. COMPONENT is the promotion
45/// kind: on, a pick landing on assembly-component geometry selects the WHOLE
46/// component; off, the click reaches the sub-entity kinds. PLANE is the
47/// construction kind: the drawn datum/plane cards, pickable like any face (they
48/// rank right after faces in the pick list, so a plane under geometry is
49/// reachable through the pick-list popup).
50const KINDS: [(&str, &str); 7] = [
51 ("COMPONENT", "Component"),
52 ("SOLID", "Solid"),
53 ("SKETCH", "Sketch"),
54 ("FACE", "Face"),
55 ("EDGE", "Edge"),
56 ("VERTEX", "Vertex"),
57 ("PLANE", "Plane"),
58];
59
60/// The selection panel's own state: the per-frame map of egui widget screen
61/// rects, published to JS for the headed verifier to drive real clicks. Rebuilt
62/// each frame (there is no DOM — egui is drawn on the canvas).
63#[derive(Default)]
64pub struct SelectionPanel {
65 hits: HashMap<String, egui::Rect>,
66 inspection: super::selection_inspection::Cache,
67 /// The compact filter button's caption as last drawn, `None` while the
68 /// full row is drawn instead (published as `__brepFilterButton`).
69 button: Option<String>,
70}
71
72impl SelectionPanel {
73 pub fn new() -> Self {
74 Self::default()
75 }
76
77 /// Draw the selection filter as a row or compact popup in the shell's
78 /// bottom STATUS BAR: a leading "All" tristate checkbox + one CHECKBOX per
79 /// pickable kind (all reflecting the LIVE engine `selection_filter`). Rebuilds
80 /// `hits` as it draws. Called by the bottom bar in modeling mode.
81 pub fn show_status_bar(&mut self, ui: &mut egui::Ui, state: &mut EngineState, document: u64) {
82 let inspection = self.inspection.read(state, document);
83 ui.horizontal_wrapped(|ui| {
84 if let Some(text) = inspection["text"].as_str().filter(|s| !s.is_empty()) {
85 ui.label(text);
86 ui.separator();
87 }
88 // Share the existing row; the filter becomes a popup when the
89 // measurements leave too little room for all its checkboxes.
90 self.show_filter_bar(ui, state);
91 });
92 }
93
94 pub fn show_filter_bar(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
95 self.hits.clear();
96 self.button = None;
97 // A loading label can leave only a sliver of the status bar. Never
98 // wrap the filter into that sliver: a popup does not consume viewport
99 // height and remains usable with touch-sized controls. The whole
100 // filter is then ONE button whose caption says what is pickable.
101 if crate::viewport::touch::enabled(ui.ctx()) || ui.available_width() < crate::viewport::touch::NARROW_WIDTH {
102 let caption = button_caption(&state.selection_filter(), state.ref_select_active());
103 self.button = Some(caption.clone());
104 let menu = egui::containers::menu::MenuButton::new(caption)
105 .config(egui::containers::menu::MenuConfig::new()
106 .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside))
107 .ui(ui, |ui| {
108 ui.set_width(240.0_f32.min(ui.ctx().content_rect().width() - 24.0));
109 egui::ScrollArea::vertical()
110 .max_height((ui.ctx().content_rect().height() - 100.0).max(88.0))
111 .show(ui, |ui| self.show_filters(ui, state));
112 });
113 self.hits.insert("filters:toggle".into(), menu.0.rect);
114 } else {
115 ui.horizontal_wrapped(|ui| self.show_filters(ui, state));
116 }
117 }
118
119 pub fn inspection_json(&mut self, state: &mut EngineState, document: u64) -> String {
120 self.inspection.read(state, document).to_string()
121 }
122
123 fn show_filters(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
124 // While the reference-selection picker is active the engine
125 // temporarily CONSTRAINS the filter to the active field's allowed
126 // kinds (see `begin_ref_select`). Letting a bottom-bar click edit it
127 // then would clobber that constraint, so LOCK the row: it still shows
128 // the constrained kinds (greyed) but is non-interactive until the
129 // picker finishes/cancels and the filter is restored.
130 let locked = state.ref_select_active();
131 if locked {
132 ui.icon_label(egui::RichText::new("\u{1f512} Reference selection — filter locked").weak())
133 .on_hover_text(
134 "The pick filter is set by the field being referenced. \
135 Finish the pick (Done on its field, or Escape) to change it.",
136 );
137 } else {
138 ui.label("Pickable:");
139 }
140
141 // `add_enabled_ui(false, …)` greys the widgets AND makes them
142 // non-interactive, so no `.changed()`/`.clicked()` fires while locked
143 // — the constrained filter cannot be overwritten. Rects are still laid
144 // out and published so the verifier and layout stay consistent.
145 ui.add_enabled_ui(!locked, |ui| {
146 let mut filter = state.selection_filter();
147 let before = filter;
148
149 // Leading "All" TRISTATE CHECKBOX (mirrors the Scene tree's group
150 // checkbox idiom): checked when EVERY kind is on, the indeterminate
151 // dash when some-but-not-all are on, unchecked when none are.
152 // Toggling it applies the toggle-all semantic — all-on → clear all;
153 // partial or none → set all on — which is exactly the checkbox's
154 // post-click value. Published under `filter:ALL` for the verifier.
155 let all_on = KINDS.iter().all(|(k, _)| filter.get(k));
156 let any_on = KINDS.iter().any(|(k, _)| filter.get(k));
157 let mut all_checked = all_on;
158 let resp = ui.add(
159 egui::Checkbox::new(&mut all_checked, "All").indeterminate(any_on && !all_on),
160 );
161 self.hits.insert("filter:ALL".into(), resp.rect);
162 if resp.changed() {
163 let target = toggle_all_target(&filter);
164 for (kind, _) in KINDS {
165 filter.set(kind, target);
166 }
167 }
168
169 // One CHECKBOX per kind, reflecting the live filter. A `.changed()`
170 // checkbox updates the working copy; it is written back once below.
171 for (kind, label) in KINDS {
172 let mut on = filter.get(kind);
173 let resp = ui.checkbox(&mut on, label);
174 self.hits.insert(format!("filter:{kind}"), resp.rect);
175 if resp.changed() {
176 filter.set(kind, on);
177 }
178 }
179
180 if filter != before {
181 state.set_selection_filter(filter);
182 }
183 });
184 }
185
186 /// Drop the published widget rects. The bottom bar calls this in sketch mode
187 /// (when the filter row is NOT drawn) so the verifier never sees stale
188 /// last-modeling-frame rects for widgets that are no longer on screen.
189 pub fn clear_hits(&mut self) {
190 self.hits.clear();
191 self.button = None;
192 }
193
194 /// The `__brepFilterButton` verifier global: `{shown, label}` — whether
195 /// the filter is collapsed to its one button, and the button's caption.
196 pub fn button_json(&self) -> String {
197 serde_json::json!({ "shown": self.button.is_some(), "label": self.button }).to_string()
198 }
199
200 /// The published widget hit-rects (egui points) for the headed verifier —
201 /// `filter:COMPONENT|SOLID|FACE|EDGE|VERTEX|PLANE` (the per-kind checkboxes)
202 /// + `filter:ALL` (the leading "All" tristate checkbox).
203 pub fn hits_json(&self) -> String {
204 crate::automation::hit_rects::hits_json(&self.hits)
205 }
206}
207
208/// The compact filter button's caption: what a click may pick, so the state
209/// shows without opening the popup. "All" and "None" for the two ends, the
210/// kind names for one or two, a count beyond that; a reference pick's
211/// constraint is marked locked (the popup cannot change it).
212fn button_caption(filter: &SelectionFilter, locked: bool) -> String {
213 let on: Vec<&str> = KINDS.iter().filter(|(k, _)| filter.get(k)).map(|(_, label)| *label).collect();
214 let what = match on.len() {
215 0 => "None".to_string(),
216 n if n == KINDS.len() => "All".to_string(),
217 1 | 2 => on.join(", "),
218 n => format!("{n} of {}", KINDS.len()),
219 };
220 if locked { format!("Filter (locked): {what}") } else { format!("Filter: {what}") }
221}
222
223/// The "toggle all" target value: if EVERY pickable kind is currently on, the
224/// "All" checkbox turns them all OFF; otherwise (some-but-not-all on, or none on)
225/// it turns them all ON. Returns the value to write to every kind.
226fn toggle_all_target(filter: &SelectionFilter) -> bool {
227 !KINDS.iter().all(|(k, _)| filter.get(k))
228}
229
230
231/// The hit keys this panel publishes (see `automation::hit_keys`).
232pub static HIT_KEYS: &[HitKeyDoc] = &[
233 HitKeyDoc { panel: "selection", prefix: "filters:toggle", meaning: "show or hide pickable filters when the status bar is compact", command: None },
234 HitKeyDoc { panel: "selection", prefix: "filter:", meaning: "toggle which entity kinds a click may pick (filter:ALL, filter:kind)", command: None },
235];