use crate::automation::hit_keys::HitKeyDoc;
use brep_render::engine_state::{EngineState, SelectionFilter};
use brep_render::engine_state::rename_ops::RenameKind;
use crate::icon_text::IconTextUi as _;
use eframe::egui;
use std::collections::HashMap;
const KINDS: [(&str, &str); 7] = [
("COMPONENT", "Component"),
("SOLID", "Solid"),
("SKETCH", "Sketch"),
("FACE", "Face"),
("EDGE", "Edge"),
("VERTEX", "Vertex"),
("PLANE", "Plane"),
];
#[derive(Default)]
pub struct SelectionPanel {
hits: HashMap<String, egui::Rect>,
inspection: super::selection_inspection::Cache,
button: Option<String>,
rename: Option<RenameEdit>,
rename_note: Option<serde_json::Value>,
}
struct RenameEdit {
kind: RenameKind,
id: String,
text: String,
error: Option<String>,
focus: bool,
}
impl SelectionPanel {
pub fn new() -> Self {
Self::default()
}
pub fn show_status_bar(&mut self, ui: &mut egui::Ui, state: &mut EngineState, document: u64) {
let inspection = self.inspection.read(state, document);
let mut rename_hits = Vec::new();
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
if let Some(text) = inspection["text"].as_str().filter(|s| !s.is_empty()) {
let width = (ui.available_width() - 100.0).max(0.0);
ui.scope(|ui| {
ui.set_max_width(width);
ui.add(egui::Label::new(text).truncate());
});
}
self.show_rename(ui, state, &mut rename_hits);
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
ui.horizontal_wrapped(|ui| self.show_filter_bar(ui, state));
});
});
self.hits.extend(rename_hits);
}
fn show_rename(&mut self, ui: &mut egui::Ui, state: &mut EngineState, hits: &mut Vec<(String, egui::Rect)>) {
let candidate = if state.any_sketch_mode() || state.ref_select_active() { None } else { state.rename_candidate() };
let Some((kind, id)) = candidate else {
self.rename = None;
return;
};
if self.rename.as_ref().is_some_and(|edit| edit.id != id || edit.kind != kind) {
self.rename = None;
}
if self.rename.is_none() && rename_key_pressed(ui.ctx(), state.selected_feature().is_some()) {
self.start_rename(kind, &id);
}
let Some(edit) = self.rename.as_mut() else {
let button = ui.add(egui::Button::new(format!("\u{270E} {id}")).small())
.on_hover_text(format!("Rename this {} (F2)", kind.as_str()));
hits.push(("selection:rename".into(), button.rect));
if button.clicked() {
self.start_rename(kind, &id);
}
return;
};
if let Some(error) = &edit.error {
ui.colored_label(ui.visuals().error_fg_color, error).on_hover_text(error);
}
let field = ui.add(egui::TextEdit::singleline(&mut edit.text).desired_width(140.0).id_salt("selection:rename:field"));
hits.push(("selection:rename:field".into(), field.rect));
if edit.focus {
field.request_focus();
edit.focus = false;
}
let (enter, escape) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)));
if field.lost_focus() && enter {
let new = edit.text.trim().to_string();
if new == id {
self.rename = None;
return;
}
match state.rename_entity(kind, &id, &new) {
Ok((rename, _)) => {
self.rename_note = Some(serde_json::json!({"ok": true, "old": rename["old"], "new": rename["new"], "error": null}));
self.rename = None;
}
Err(error) => {
self.rename_note = Some(serde_json::json!({"ok": false, "old": id, "new": new, "error": error}));
edit.error = Some(error);
edit.focus = true;
}
}
} else if escape || field.lost_focus() {
self.rename = None;
}
}
fn start_rename(&mut self, kind: RenameKind, id: &str) {
self.rename = Some(RenameEdit { kind, id: id.to_string(), text: id.to_string(), error: None, focus: true });
}
pub fn rename_json(&self, state: &EngineState) -> String {
let candidate = if state.any_sketch_mode() || state.ref_select_active() { None } else { state.rename_candidate() };
serde_json::json!({
"target": candidate.map(|(kind, id)| serde_json::json!({"kind": kind.as_str(), "id": id})),
"open": self.rename.is_some(),
"text": self.rename.as_ref().map(|e| e.text.clone()),
"error": self.rename.as_ref().and_then(|e| e.error.clone()),
"last": self.rename_note,
})
.to_string()
}
pub fn show_filter_bar(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
self.hits.clear();
self.button = None;
if crate::viewport::touch::enabled(ui.ctx()) || ui.available_width() < crate::viewport::touch::NARROW_WIDTH {
let caption = button_caption(&state.selection_filter(), state.ref_select_active());
self.button = Some(caption.clone());
let menu = egui::containers::menu::MenuButton::new(caption)
.config(egui::containers::menu::MenuConfig::new()
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside))
.ui(ui, |ui| {
ui.set_width(240.0_f32.min(ui.ctx().content_rect().width() - 24.0));
egui::ScrollArea::vertical()
.max_height((ui.ctx().content_rect().height() - 100.0).max(88.0))
.show(ui, |ui| self.show_filters(ui, state));
});
self.hits.insert("filters:toggle".into(), menu.0.rect);
} else {
ui.horizontal_wrapped(|ui| self.show_filters(ui, state));
}
}
pub fn inspection_json(&mut self, state: &mut EngineState, document: u64) -> String {
self.inspection.read(state, document).to_string()
}
fn show_filters(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
let held = state.filter_override();
let locked = state.ref_select_active() || held.is_some();
if let (Some(kind), false) = (held, state.ref_select_active()) {
let resp = ui.label(
egui::RichText::new(format!("\u{2328} Key held: only {} pickable", held_kind_label(kind)))
.strong()
.color(ui.visuals().warn_fg_color),
);
self.hits.insert("filter:override".into(), resp.rect);
resp.on_hover_text("Release the key and this filter is back.");
} else if locked {
ui.icon_label(egui::RichText::new("\u{1f512} Reference selection — filter locked").weak())
.on_hover_text(
"The pick filter is set by the field being referenced. \
Finish the pick (Done on its field, or Escape) to change it.",
);
} else {
ui.label("Pickable:");
}
ui.add_enabled_ui(!locked, |ui| {
let mut filter = state.bottom_selection_filter();
let before = filter;
let all_on = KINDS.iter().all(|(k, _)| filter.get(k));
let any_on = KINDS.iter().any(|(k, _)| filter.get(k));
let mut all_checked = all_on;
let resp = ui.add(
egui::Checkbox::new(&mut all_checked, "All").indeterminate(any_on && !all_on),
);
self.hits.insert("filter:ALL".into(), resp.rect);
if resp.changed() {
let target = toggle_all_target(&filter);
for (kind, _) in KINDS {
filter.set(kind, target);
}
}
for (kind, label) in KINDS {
let mut on = filter.get(kind);
let resp = ui.checkbox(&mut on, label);
self.hits.insert(format!("filter:{kind}"), resp.rect);
if resp.changed() {
filter.set(kind, on);
}
}
if filter != before {
state.set_selection_filter(filter);
}
});
}
pub fn clear_hits(&mut self) {
self.hits.clear();
self.button = None;
}
pub fn button_json(&self) -> String {
serde_json::json!({ "shown": self.button.is_some(), "label": self.button }).to_string()
}
pub fn hits_json(&self) -> String {
crate::automation::hit_rects::hits_json(&self.hits)
}
}
fn rename_key_pressed(ctx: &egui::Context, tree_feature: bool) -> bool {
if ctx.egui_wants_keyboard_input() {
return false;
}
let mac = ctx.os() == egui::os::OperatingSystem::Mac;
ctx.input(|i| {
let plain = !i.modifiers.any();
plain && (i.key_pressed(egui::Key::F2) || (mac && tree_feature && i.key_pressed(egui::Key::Enter)))
})
}
fn button_caption(filter: &SelectionFilter, locked: bool) -> String {
let on: Vec<&str> = KINDS.iter().filter(|(k, _)| filter.get(k)).map(|(_, label)| *label).collect();
let what = match on.len() {
0 => "None".to_string(),
n if n == KINDS.len() => "All".to_string(),
1 | 2 => on.join(", "),
n => format!("{n} of {}", KINDS.len()),
};
if locked { format!("Filter (locked): {what}") } else { format!("Filter: {what}") }
}
fn toggle_all_target(filter: &SelectionFilter) -> bool {
!KINDS.iter().all(|(k, _)| filter.get(k))
}
pub static HIT_KEYS: &[HitKeyDoc] = &[
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") },
HitKeyDoc { panel: "selection", prefix: "filters:toggle", meaning: "show or hide pickable filters when the status bar is compact", command: None },
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 },
];
fn held_kind_label(kind: &str) -> &'static str {
match kind {
"SOLID" => "solids",
"FACE" => "faces",
"EDGE" => "edges",
"VERTEX" => "vertices",
"COMPONENT" => "components",
"PLANE" => "planes",
_ => "?",
}
}