1use crate::automation::hit_keys::HitKeyDoc;
73use crate::column_tree::{self, CellKind, ColumnLayout, ColumnSpec, ColumnTreeSpec, RowAction, RowNode};
74use crate::form_view::{form_view, FormViewSpec};
75use brep_render::engine_state::{EngineState, RefSelectTarget};
76use brep_render::features::form_fields_from_schema;
77use brep_render::sheets::SheetState;
78use eframe::egui;
79use serde_json::Value;
80use std::collections::{HashMap, HashSet};
81
82const NAME: &str = "name";
83const KIND: &str = "kind";
84const VALUE: &str = "value";
85const STATUS: &str = "status";
86const ON: &str = "on";
87const ACTIONS: &str = "actions";
88
89const OK_COLOR: &str = "#3fb950";
90const ERROR_COLOR: &str = "#f85149";
91const ACTIVE_COLOR: &str = "#58a6ff";
92const MUTED_COLOR: &str = "#8b949e";
93
94const ACT_OPEN: &str = "open";
96const ACT_CLOSE: &str = "close";
97const ACT_EDIT: &str = "edit";
98const ACT_DELETE_SHEET: &str = "delete-sheet";
99const ACT_DELETE_VIEW: &str = "delete-view";
100const ACT_DELETE_DIM: &str = "delete-dimension";
101const ACT_DELETE_ORD: &str = "delete-ordinate";
102
103enum Action {
105 AddSheet,
106 PlaceView(String),
107 Rename(String, String),
108 Open(Option<String>),
109 Edit(Option<String>),
110 Select(String),
112 DeleteSheet(String),
113 DeleteView(String),
114 DeleteDimension(String),
115 UpdateSheet(String, Value),
116 UpdateView(String, Value),
117 UpdateDimension(String, Value),
118 DeleteOrdinate(String),
119 UpdateOrdinate(String, Value),
120 BeginRefSelect {
125 id: String,
126 path: Vec<String>,
127 label: String,
128 filter: Vec<String>,
129 multiple: bool,
130 seed: Vec<String>,
131 },
132 FinishRefSelect,
134 RefSelectRemove(usize),
136 AddRevision(String),
138 UpdateRevision(String, usize, Value),
140 RemoveRevision(String, usize),
142}
143
144enum RevisionIntent {
148 Add,
149 Update(usize, &'static str, String),
150 Remove(usize),
151}
152
153fn apply(state: &mut EngineState, action: Action) -> Result<(), String> {
156 match action {
157 Action::AddSheet => {
158 state.sheet_add(None);
159 Ok(())
160 }
161 Action::PlaceView(view) => state.sheet_place_view(None, &view, None, None).map(|_| ()),
162 Action::Rename(id, name) => {
163 state.sheet_update(&id, &serde_json::json!({ "name": name }).to_string())
164 }
165 Action::Open(id) => state.sheet_set_open(id.as_deref()),
166 Action::Edit(id) => {
167 state.sheet_set_object_open(id.as_deref());
168 Ok(())
169 }
170 Action::Select(id) => {
171 state.sheet_select_object(Some(&id));
172 Ok(())
173 }
174 Action::DeleteSheet(id) => state.sheet_delete(&id),
175 Action::DeleteView(id) => state.sheet_remove_view(&id),
176 Action::DeleteDimension(id) => state.sheet_remove_dimension(&id),
177 Action::UpdateSheet(id, params) => state.sheet_update(&id, ¶ms.to_string()),
178 Action::UpdateView(id, params) => state.sheet_update_view(&id, ¶ms.to_string()),
179 Action::UpdateDimension(id, params) => {
180 state.sheet_update_dimension(&id, ¶ms.to_string())
181 }
182 Action::DeleteOrdinate(id) => state.sheet_remove_ordinate(&id),
183 Action::UpdateOrdinate(id, params) => {
184 state.sheet_update_ordinate(&id, ¶ms.to_string())
185 }
186 Action::BeginRefSelect { id, path, label, filter, multiple, seed } => {
187 if state.ref_select_active() {
190 state.finish_ref_select();
191 }
192 state.begin_ref_select_for_sheet(&id, path, label, filter, multiple, seed)
193 }
194 Action::FinishRefSelect => {
195 state.finish_ref_select();
196 Ok(())
197 }
198 Action::RefSelectRemove(index) => {
199 state.ref_select_remove(index);
200 Ok(())
201 }
202 Action::AddRevision(id) => state.sheet_add_revision(&id, None, None, None).map(|_| ()),
203 Action::UpdateRevision(id, index, params) => {
204 state.sheet_update_revision(&id, index, ¶ms.to_string())
205 }
206 Action::RemoveRevision(id, index) => state.sheet_remove_revision(&id, index),
207 }
208}
209
210fn sheet_actions(is_open: bool) -> Vec<RowAction> {
213 vec![
214 if is_open {
215 RowAction::new(ACT_CLOSE, "Close sheet").tooltip("Return the viewport to the 3D model")
216 } else {
217 RowAction::new(ACT_OPEN, "Open sheet").tooltip("Draw this sheet in the viewport")
218 },
219 RowAction::new(ACT_EDIT, "Edit sheet").tooltip("Name and paper size"),
220 RowAction::new(ACT_DELETE_SHEET, "Delete sheet").separator_above().destructive(),
221 ]
222}
223
224fn placement_actions() -> Vec<RowAction> {
226 vec![
227 RowAction::new(ACT_EDIT, "Edit placement").tooltip("Which view, where, at what scale, whether its text lies flat on the sheet, and — on a section or a detail — its letter"),
228 RowAction::new(ACT_DELETE_VIEW, "Remove from sheet").separator_above().destructive(),
229 ]
230}
231
232fn dimension_actions() -> Vec<RowAction> {
234 vec![
235 RowAction::new(ACT_EDIT, "Edit dimension").tooltip("Kind, anchors, offset, precision and tolerance"),
236 RowAction::new(ACT_DELETE_DIM, "Remove dimension").separator_above().destructive(),
237 ]
238}
239
240fn ordinate_actions() -> Vec<RowAction> {
242 vec![
243 RowAction::new(ACT_EDIT, "Edit ordinate set").tooltip("Axis, datum, members, baseline offset and precision"),
244 RowAction::new(ACT_DELETE_ORD, "Remove ordinate set").separator_above().destructive(),
245 ]
246}
247
248pub(crate) fn object_actions(sheets: &SheetState, open_sheet: Option<&str>, id: &str) -> Vec<RowAction> {
255 if sheets.find_sheet(id).is_some() {
256 sheet_actions(open_sheet == Some(id))
257 } else if sheets.locate_view(id).is_some() {
258 placement_actions()
259 } else if sheets.locate_dimension(id).is_some() {
260 dimension_actions()
261 } else if sheets.locate_ordinate(id).is_some() {
262 ordinate_actions()
263 } else {
264 Vec::new()
265 }
266}
267
268fn menu_action(id: String, action: &str) -> Option<Action> {
271 match action {
272 ACT_OPEN => Some(Action::Open(Some(id))),
273 ACT_CLOSE => Some(Action::Open(None)),
274 ACT_EDIT => Some(Action::Edit(Some(id))),
275 ACT_DELETE_SHEET => Some(Action::DeleteSheet(id)),
276 ACT_DELETE_VIEW => Some(Action::DeleteView(id)),
277 ACT_DELETE_DIM => Some(Action::DeleteDimension(id)),
278 ACT_DELETE_ORD => Some(Action::DeleteOrdinate(id)),
279 _ => None,
280 }
281}
282
283pub(crate) fn run_row_action(state: &mut EngineState, id: &str, action: &str) -> Result<(), String> {
287 menu_action(id.to_string(), action).map_or(Ok(()), |action| apply(state, action))
288}
289
290pub(crate) fn delete_held_object(state: &mut EngineState, id: &str) -> Result<(), String> {
295 let sheets = state.sheet_state();
296 let entry = if sheets.locate_view(id).is_some() {
297 ACT_DELETE_VIEW
298 } else if sheets.locate_dimension(id).is_some() {
299 ACT_DELETE_DIM
300 } else if sheets.locate_ordinate(id).is_some() {
301 ACT_DELETE_ORD
302 } else {
303 return Err(format!("no placed view, dimension or ordinate set '{id}'"));
304 };
305 run_row_action(state, id, entry)
306}
307
308pub struct SheetsPanel {
310 hits: HashMap<String, egui::Rect>,
311 layout: ColumnLayout,
312 columns: Vec<ColumnSpec>,
313 collapsed: HashSet<String>,
315}
316
317impl Default for SheetsPanel {
318 fn default() -> Self {
319 Self::new()
320 }
321}
322
323impl SheetsPanel {
324 pub fn new() -> Self {
325 Self {
326 hits: HashMap::new(),
327 layout: ColumnLayout::default(),
328 columns: vec![
329 ColumnSpec::new(NAME, "Sheet / view", CellKind::Text).width(140.0),
330 ColumnSpec::new(KIND, "", CellKind::Badges).width(28.0),
331 ColumnSpec::new(VALUE, "Paper / placement", CellKind::ReadOnly).width(170.0),
332 ColumnSpec::new(STATUS, "", CellKind::Badges).width(28.0),
333 ColumnSpec::new(ON, "Open", CellKind::Toggle).width(36.0),
334 ColumnSpec::new(ACTIONS, "", CellKind::Actions { label: "\u{22EF}".into() }).width(30.0),
335 ],
336 collapsed: HashSet::new(),
337 }
338 }
339
340 pub fn show(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
342 self.hits.clear();
343 self.hits.insert("sheets:panel:clip".into(), ui.clip_rect());
344 let sheets = state.sheet_state();
345 let open_sheet = state.sheet_open().map(String::from);
346 let open_object = state.sheet_open_object().map(String::from);
347 let selected = state.sheet_selected_object().map(String::from);
348 let view_ids = state.sheet_pmi_view_ids();
349
350 let mut action: Option<Action> = None;
351 let mut close = false;
352 match open_object.as_deref() {
353 Some(id) if sheets.find_sheet(id).is_some() => {
354 let sheet = sheets.find_sheet(id).expect("just matched").clone();
355 self.show_form(ui, state, &sheet.id, "Sheet", &sheet.params(), 0, None, &mut action, &mut close);
356 }
357 Some(id) if sheets.locate_view(id).is_some() => {
358 let placed = sheets
359 .sheets
360 .iter()
361 .find_map(|sheet| sheet.find_view(id))
362 .expect("just located")
363 .clone();
364 let (label, index) = match placed.schema_type() {
368 "sectionView" => ("Section view", 4),
369 "detailView" => ("Detail view", 5),
370 _ => ("Placed view", 1),
371 };
372 self.show_form(ui, state, &placed.id, label, &placed.params(), index, None, &mut action, &mut close);
373 }
374 Some(id) if sheets.locate_dimension(id).is_some() => {
375 let dimension = sheets.find_dimension(id).expect("just located").clone();
376 let inherited = sheets
380 .locate_dimension(id)
381 .and_then(|(sheet, _)| state.sheet_drawing_cached(&sheet))
382 .and_then(|drawing| drawing.dimensions.iter().find(|drawn| drawn.id == dimension.id))
383 .filter(|drawn| !drawn.tolerance_from.is_empty())
384 .map(|drawn| {
385 format!(
386 "Tolerance from PMI dimension {}: {} \u{2014} set one here to override it",
387 drawn.tolerance_from, drawn.text
388 )
389 });
390 self.show_form(ui, state, &dimension.id, "Sheet dimension", &dimension.params(), 2, inherited.as_deref(), &mut action, &mut close);
391 }
392 Some(id) if sheets.locate_ordinate(id).is_some() => {
393 let set = sheets.find_ordinate(id).expect("just located").clone();
394 self.show_form(ui, state, &set.id, "Ordinate set", &set.params(), 3, None, &mut action, &mut close);
395 }
396 _ => self.show_tree(ui, state, &sheets, open_sheet.as_deref(), selected.as_deref(), &view_ids, &mut action),
399 }
400
401 let result = action.map_or(Ok(()), |action| apply(state, action));
402 if let Err(error) = result {
403 state.push_notice(format!("Sheets: {error}"));
404 }
405 if close {
406 if state.ref_select_is_sheet() {
408 state.finish_ref_select();
409 }
410 state.sheet_set_object_open(None);
411 }
412 if let Some(field) = state.ref_select_field() {
415 if field.target == RefSelectTarget::Sheet && state.sheet_open_object() == Some(field.subject.as_str()) {
416 state.ref_select_claim();
417 }
418 }
419 }
420
421 #[allow(clippy::too_many_arguments)]
422 fn show_tree(
423 &mut self,
424 ui: &mut egui::Ui,
425 state: &mut EngineState,
426 sheets: &SheetState,
427 open_sheet: Option<&str>,
428 selected: Option<&str>,
429 view_ids: &[String],
430 action: &mut Option<Action>,
431 ) {
432 ui.horizontal_wrapped(|ui| {
434 let add = ui
435 .add(crate::icon_text::icon_button(ui, "\u{1F5CB} Add sheet"))
436 .on_hover_text("Add an A3 sheet and open it in the sheet viewport");
437 self.hits.insert("sheets:add".into(), add.rect);
438 if add.clicked() {
439 *action = Some(Action::AddSheet);
440 }
441 let can_place = !sheets.sheets.is_empty() && !view_ids.is_empty();
442 let mut place: Option<String> = None;
443 ui.add_enabled_ui(can_place, |ui| {
444 let combo = egui::ComboBox::from_id_salt("sheets-place")
445 .selected_text("+ Place view")
446 .show_ui(ui, |ui| {
447 for id in view_ids {
448 let item = crate::icon_text::selectable_icon_label(ui, false, id);
449 self.hits.insert(format!("sheets:place:{id}"), item.rect);
450 if item.clicked() {
451 place = Some(id.clone());
452 }
453 }
454 });
455 let response = if can_place {
456 combo.response
457 } else if sheets.sheets.is_empty() {
458 combo.response.on_disabled_hover_text("Add a sheet first")
459 } else {
460 combo.response.on_disabled_hover_text("Capture a PMI view first")
461 };
462 self.hits.insert("sheets:place".into(), response.rect);
463 });
464 if let Some(view) = place {
465 *action = Some(Action::PlaceView(view));
466 }
467 });
468 let placed: usize = sheets.sheets.iter().map(|sheet| sheet.views.len()).sum();
469 let dimensions: usize = sheets.sheets.iter().map(|sheet| sheet.dimensions.len()).sum();
470 ui.label(
471 egui::RichText::new(format!(
472 "{} sheet{} | {placed} placed view{} | {dimensions} dimension{} | {}",
473 sheets.sheets.len(),
474 if sheets.sheets.len() == 1 { "" } else { "s" },
475 if placed == 1 { "" } else { "s" },
476 if dimensions == 1 { "" } else { "s" },
477 match open_sheet.and_then(|id| sheets.find_sheet(id)) {
478 Some(sheet) => format!("open: {}", sheet.name),
479 None => "no sheet open".to_string(),
480 }
481 ))
482 .weak(),
483 );
484 if sheets.sheets.is_empty() {
485 ui.label(egui::RichText::new("Add a sheet to place PMI views on paper").weak().italics());
486 }
487 ui.add_space(2.0);
488
489 let drawing = open_sheet.and_then(|id| state.sheet_drawing(id));
495 let rows: Vec<RowNode> = sheets
496 .sheets
497 .iter()
498 .map(|sheet| {
499 let is_open = open_sheet == Some(sheet.id.as_str());
500 let (w, h) = sheet.millimetres();
501 let count = sheet.views.len();
502 let mut row = RowNode::new(&sheet.id)
503 .cell(NAME, Value::String(sheet.name.clone()))
504 .cell(KIND, serde_json::json!([{ "glyph": "\u{1F5CB}", "color": if is_open { ACTIVE_COLOR } else { MUTED_COLOR }, "tooltip": "drawing sheet" }]))
505 .cell(
506 VALUE,
507 Value::String(format!(
508 "{} · {w:.0} × {h:.0} mm · {count} view{}",
509 sheet.size,
510 if count == 1 { "" } else { "s" }
511 )),
512 )
513 .cell(
514 STATUS,
515 if is_open {
516 serde_json::json!([{ "glyph": "\u{25CF}", "color": ACTIVE_COLOR, "tooltip": "shown in the sheet viewport" }])
517 } else {
518 serde_json::json!([])
519 },
520 )
521 .cell(ON, Value::Bool(is_open))
522 .actions(sheet_actions(is_open));
523 row.expanded = !self.collapsed.contains(&sheet.id);
524 row.selected = is_open;
525 row.children = sheet
526 .views
527 .iter()
528 .map(|placed| {
529 let projected = drawing.and_then(|d| d.views.iter().find(|v| v.id == placed.id));
530 let is_section = placed.section.as_ref();
531 let is_detail = placed.detail.as_ref();
532 let (glyph, color, tooltip, status) = match projected {
533 Some(view) if view.error.is_empty() => (
534 "\u{2713}",
535 OK_COLOR,
536 format!("{} edges, {} annotations", view.edges.len(), view.annotations.len()),
537 format!("{} edges", view.edges.len()),
538 ),
539 Some(view) => ("\u{2715}", ERROR_COLOR, view.error.clone(), view.error.clone()),
540 None => ("\u{2013}", MUTED_COLOR, "open the sheet to draw it".into(), String::new()),
541 };
542 let _ = status;
543 let mut child = RowNode::new(&placed.id)
546 .cell(NAME, Value::String(placed.id.clone()))
547 .cell(KIND, match (is_section, is_detail) {
548 (Some(cut), _) => serde_json::json!([{ "glyph": "\u{25E7}", "color": ACTIVE_COLOR, "tooltip": format!("section {}—{} of {}", cut.label, cut.label, cut.source) }]),
549 (_, Some(circle)) => serde_json::json!([{ "glyph": "\u{25CE}", "color": ACTIVE_COLOR, "tooltip": format!("detail {} of {}", circle.label, circle.source) }]),
550 _ => serde_json::json!([{ "glyph": "\u{1F5CE}", "color": ACTIVE_COLOR, "tooltip": "placed PMI view" }]),
551 })
552 .cell(
553 VALUE,
554 Value::String(match (is_section, is_detail) {
555 (Some(cut), _) => format!(
559 "SECTION {}—{} of {} · {}:1 · ({:.0}, {:.0}) mm",
560 cut.label,
561 cut.label,
562 cut.source,
563 trim(placed.scale),
564 placed.position[0],
565 placed.position[1]
566 ),
567 (_, Some(circle)) => format!(
570 "DETAIL {} of {} · {}:1 · ({:.0}, {:.0}) mm",
571 circle.label,
572 circle.source,
573 trim(placed.scale),
574 placed.position[0],
575 placed.position[1]
576 ),
577 _ => format!(
578 "{} · {}:1 · ({:.0}, {:.0}) mm · {}",
579 placed.view,
580 trim(placed.scale),
581 placed.position[0],
582 placed.position[1],
583 if placed.flatten_text { "flat" } else { "projected" }
584 ),
585 }),
586 )
587 .cell(STATUS, serde_json::json!([{ "glyph": glyph, "color": color, "tooltip": tooltip }]))
588 .cell(ON, Value::Null)
589 .actions(placement_actions());
590 child.editable = false;
591 child.selected = selected == Some(placed.id.as_str());
592 child
593 })
594 .collect();
595 row.children.extend(sheet.dimensions.iter().map(|dimension| {
600 let drawn = drawing.and_then(|d| d.dimensions.iter().find(|x| x.id == dimension.id));
601 let (glyph, color, tooltip) = match drawn {
602 Some(d) if d.error.is_empty() => (
603 "\u{2713}",
604 OK_COLOR,
605 if d.tolerance_from.is_empty() {
606 format!("{} \u{2014} {} mm off its anchors", d.text, trim(d.offset_mm))
607 } else {
608 format!(
609 "{} \u{2014} {} mm off its anchors; the tolerance is PMI dimension {}'s",
610 d.text,
611 trim(d.offset_mm),
612 d.tolerance_from
613 )
614 },
615 ),
616 Some(d) => ("\u{2715}", ERROR_COLOR, d.error.clone()),
617 None => ("\u{2013}", MUTED_COLOR, "open the sheet to draw it".into()),
618 };
619 let measured = drawn
620 .filter(|d| d.error.is_empty())
621 .map(|d| match d.tolerance_from.as_str() {
622 "" => d.text.clone(),
623 from => format!("{} (from {from})", d.text),
624 })
625 .unwrap_or_else(|| "\u{2014}".into());
626 let mut child = RowNode::new(&dimension.id)
627 .cell(NAME, Value::String(dimension.id.clone()))
628 .cell(KIND, serde_json::json!([{ "glyph": "\u{2194}", "color": ACTIVE_COLOR, "tooltip": "sheet dimension" }]))
629 .cell(
630 VALUE,
631 Value::String(format!(
632 "{} \u{00B7} {} \u{00B7} {measured}",
633 if dimension.kind == "linear" {
634 dimension.alignment.clone()
635 } else {
636 dimension.kind.clone()
637 },
638 match dimension.anchors.len() {
639 1 => "1 anchor".to_string(),
640 n => format!("{n} anchors"),
641 }
642 )),
643 )
644 .cell(STATUS, serde_json::json!([{ "glyph": glyph, "color": color, "tooltip": tooltip }]))
645 .cell(ON, Value::Null)
646 .actions(dimension_actions());
647 child.editable = false;
648 child.selected = selected == Some(dimension.id.as_str());
649 child
650 }));
651 row.children.extend(sheet.ordinates.iter().map(|set| {
655 let drawn = drawing.and_then(|d| d.ordinates.iter().find(|x| x.id == set.id));
656 let (glyph, color, tooltip) = match drawn {
657 Some(d) if !d.error.is_empty() => ("\u{2715}", ERROR_COLOR, d.error.clone()),
658 Some(d) if d.lost() > 0 => (
659 "\u{2715}",
660 ERROR_COLOR,
661 d.stations
662 .iter()
663 .filter(|station| !station.error.is_empty())
664 .map(|station| station.error.clone())
665 .collect::<Vec<_>>()
666 .join("; "),
667 ),
668 Some(d) => (
669 "\u{2713}",
670 OK_COLOR,
671 format!(
672 "{} stations \u{2014} baseline {} mm from the datum",
673 d.stations.len(),
674 trim(d.offset_mm)
675 ),
676 ),
677 None => ("\u{2013}", MUTED_COLOR, "open the sheet to draw it".into()),
678 };
679 let mut child = RowNode::new(&set.id)
680 .cell(NAME, Value::String(set.id.clone()))
681 .cell(KIND, serde_json::json!([{ "glyph": "\u{22EE}", "color": ACTIVE_COLOR, "tooltip": "ordinate set" }]))
682 .cell(
683 VALUE,
684 Value::String(format!(
685 "{} \u{00B7} {}",
686 set.axis,
687 match set.members.len() {
688 1 => "1 member".to_string(),
689 n => format!("{n} members"),
690 }
691 )),
692 )
693 .cell(STATUS, serde_json::json!([{ "glyph": glyph, "color": color, "tooltip": tooltip }]))
694 .cell(ON, Value::Null)
695 .actions(ordinate_actions());
696 child.editable = false;
697 child.selected = selected == Some(set.id.as_str());
698 child
699 }));
700 row
701 })
702 .collect();
703 let spec = ColumnTreeSpec {
704 id: "sheets",
705 columns: &self.columns,
706 root_label: Some("Sheets"),
707 root_cells: None,
708 empty_hint: Some("(no sheets — Add sheet to start a drawing)"),
709 hits_prefix: "sheets:",
710 };
711 let out = column_tree::column_tree(ui, &spec, &mut self.layout, &rows, Some(&mut self.hits));
712
713 if let Some(id) = &out.toggled {
715 if sheets.find_sheet(id).is_some() && !self.collapsed.remove(id) {
716 self.collapsed.insert(id.clone());
717 }
718 }
719 if let Some(click) = out.actions.first() {
720 *action = menu_action(click.row_id.clone(), &click.action);
721 return;
722 }
723 if let Some(edit) = out.edits.first() {
724 let id = edit.row_id.clone();
725 match edit.column.as_str() {
726 NAME if sheets.find_sheet(&id).is_some() => {
727 *action = Some(Action::Rename(id, edit.value.as_str().unwrap_or("").to_string()));
728 }
729 ON if sheets.find_sheet(&id).is_some() => {
730 *action = Some(Action::Open(edit.value.as_bool().unwrap_or(false).then_some(id)));
731 }
732 _ => {}
733 }
734 return;
735 }
736 let held_by_a_sheet = |id: &str| {
737 sheets.locate_view(id).is_some()
738 || sheets.locate_dimension(id).is_some()
739 || sheets.locate_ordinate(id).is_some()
740 };
741 if let Some(id) = &out.double_clicked {
744 if held_by_a_sheet(id) || sheets.find_sheet(id).is_some() {
745 *action = Some(Action::Edit(Some(id.clone())));
746 }
747 return;
748 }
749 if let Some(id) = &out.clicked {
753 if held_by_a_sheet(id) {
754 *action = Some(Action::Select(id.clone()));
755 } else if sheets.find_sheet(id).is_some() && open_sheet != Some(id.as_str()) {
756 *action = Some(Action::Open(Some(id.clone())));
757 }
758 }
759 }
760
761 #[allow(clippy::too_many_arguments)]
765 fn show_form(
766 &mut self,
767 ui: &mut egui::Ui,
768 state: &EngineState,
769 id: &str,
770 label: &str,
771 seed: &Value,
772 catalogue_index: usize,
773 note: Option<&str>,
774 action: &mut Option<Action>,
775 close: &mut bool,
776 ) {
777 let catalogue = state.sheet_catalogue();
778 let Some(schema) = catalogue
779 .get("objects")
780 .and_then(Value::as_array)
781 .and_then(|objects| objects.get(catalogue_index))
782 .cloned()
783 else {
784 *close = true;
785 return;
786 };
787 let fields = form_fields_from_schema(&schema);
788 let mut params = seed.clone();
789 let title = format!("{label} {id}");
790 let is_sheet = catalogue_index == 0;
794 let revisions: Vec<brep_render::sheets::Revision> = if is_sheet {
795 serde_json::from_value(seed.get("revisions").cloned().unwrap_or(Value::Null)).unwrap_or_default()
796 } else {
797 Vec::new()
798 };
799 let revision_rows = std::cell::RefCell::new(revisions);
800 let revision_intents: std::cell::RefCell<Vec<RevisionIntent>> = std::cell::RefCell::new(Vec::new());
801 let revision_hits: std::cell::RefCell<Vec<(String, egui::Rect)>> = std::cell::RefCell::new(Vec::new());
802 let bom = std::cell::RefCell::new(serde_json::from_value::<Option<brep_render::sheets::BomTable>>(seed.get("bomTable").cloned().unwrap_or(Value::Null)).unwrap_or_default());
803 let bom_changed = std::cell::Cell::new(false);
804 let mut columns = if is_sheet { state.sheet_bom_columns() } else { Vec::new() };
805 let config = if state.settings.bom_columns.is_empty() { crate::panels::bom_columns::default_text() } else { state.settings.bom_columns.clone() };
806 for column in crate::panels::bom_columns::parse(&config).columns { let key = column.key(); if !columns.contains(&key) { columns.push(key); } }
807 if let Some(table) = bom.borrow().as_ref() { for column in &table.columns { if !columns.contains(column) { columns.push(column.clone()); } } }
808 columns.sort_by_key(|column| !bom.borrow().as_ref().is_some_and(|table| table.columns.contains(column)));
809 let draw_revisions = |ui: &mut egui::Ui| {
810 ui.label("BOM table");
811 let mut table = bom.borrow_mut();
812 let mut enabled = table.is_some();
813 let response = ui.checkbox(&mut enabled, "Show BOM table");
814 revision_hits.borrow_mut().push(("sheets:bom:enabled".into(), response.rect));
815 if response.changed() {
816 *table = enabled.then(brep_render::sheets::BomTable::default); bom_changed.set(true);
817 }
818 if let Some(table) = table.as_mut() {
819 ui.horizontal(|ui| {
820 ui.label("Position (mm)");
821 for coordinate in &mut table.position { if ui.add(egui::DragValue::new(coordinate).speed(1.)).changed() { bom_changed.set(true); } }
822 });
823 ui.horizontal(|ui| { ui.label("Column width (mm)"); if ui.add(egui::DragValue::new(&mut table.column_width_mm).range(8.0..=200.0)).changed() { bom_changed.set(true); } });
824 ui.label("Columns");
825 egui::ScrollArea::vertical().id_salt(("bom-columns", id)).max_height(180.0).show(ui, |ui| {
826 for column in &columns {
827 let mut selected = table.columns.contains(column);
828 let response = ui.checkbox(&mut selected, column.replace('_', " "));
829 revision_hits.borrow_mut().push((format!("sheets:bom:column:{column}"), response.rect));
830 if response.changed() {
831 if selected { table.columns.push(column.clone()); } else { table.columns.retain(|c| c != column); }
832 bom_changed.set(true);
833 }
834 }
835 });
836 }
837 ui.separator();
838 ui.label("Revisions");
839 draw_revision_rows(ui, id, &revision_rows, &revision_intents, &revision_hits);
840 };
841 let picking = state
844 .ref_select_field()
845 .filter(|f| f.target == RefSelectTarget::Sheet && f.subject == id);
846 let spec = FormViewSpec {
847 title: &title,
848 subtitle: None,
849 fields: &fields,
850 banner: note.map(|note| (note, egui::Color32::from_rgb(0x58, 0xa6, 0xff))),
851 trailing: None,
852 exit_label: "Return to tree",
853 extra: is_sheet.then_some(("Tables", &draw_revisions as &dyn Fn(&mut egui::Ui))),
854 rollback: false,
855 hidden: None,
856 hits_prefix: "sheets:",
857 read_only: state.history.locked(),
858 picking: picking.as_ref().map(|f| crate::form::ActivePick { path: &f.path, names: &f.names }),
859 };
860 let mut out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
861 if is_sheet && bom_changed.get() { params["bomTable"] = serde_json::to_value(bom.into_inner()).unwrap_or(Value::Null); out.changed = true; }
862 for (key, rect) in revision_hits.into_inner() {
863 self.hits.insert(key, rect);
864 }
865 if !out.changed {
868 if let Some(intent) = revision_intents.into_inner().into_iter().next() {
869 *action = Some(match intent {
870 RevisionIntent::Add => Action::AddRevision(id.to_string()),
871 RevisionIntent::Update(index, field, value) => {
872 Action::UpdateRevision(id.to_string(), index, serde_json::json!({ field: value }))
873 }
874 RevisionIntent::Remove(index) => Action::RemoveRevision(id.to_string(), index),
875 });
876 }
877 }
878 let anchor = self.hits.get("sheets:form:feature").map(|rect| rect.min).unwrap_or(egui::Pos2::ZERO);
879 self.hits.insert(format!("sheets:form:object:{id}"), egui::Rect::from_min_size(anchor, egui::Vec2::ZERO));
880 if out.changed {
881 *action = Some(match catalogue_index {
882 0 => Action::UpdateSheet(id.to_string(), params),
883 2 => Action::UpdateDimension(id.to_string(), params),
884 3 => Action::UpdateOrdinate(id.to_string(), params),
885 _ => Action::UpdateView(id.to_string(), params),
887 });
888 }
889 if let Some(activate) = out.ref_activate {
893 *action = Some(Action::BeginRefSelect {
894 id: id.to_string(),
895 path: activate.path,
896 label: activate.label,
897 filter: activate.filter,
898 multiple: activate.multiple,
899 seed: activate.seed,
900 });
901 }
902 if let Some(index) = out.pick_remove {
904 *action = Some(Action::RefSelectRemove(index));
905 }
906 if out.pick_done {
907 *action = Some(Action::FinishRefSelect);
908 }
909 if out.exit_clicked {
910 *close = true;
911 }
912 }
913
914 pub fn hits_json(&self) -> String {
916 crate::automation::hit_rects::hits_json(&self.hits)
917 }
918
919 pub fn clear_hits(&mut self) {
922 self.hits.clear();
923 }
924}
925
926fn draw_revision_rows(
931 ui: &mut egui::Ui,
932 sheet_id: &str,
933 rows: &std::cell::RefCell<Vec<brep_render::sheets::Revision>>,
934 intents: &std::cell::RefCell<Vec<RevisionIntent>>,
935 hits: &std::cell::RefCell<Vec<(String, egui::Rect)>>,
936) {
937 let mut rows = rows.borrow_mut();
938 if rows.is_empty() {
939 ui.label(egui::RichText::new("No revisions \u{2014} the sheet draws no revision table").weak().italics());
940 }
941 for (index, row) in rows.iter_mut().enumerate() {
945 let mut edit = |ui: &mut egui::Ui, field: &'static str, value: &mut String, width: f32, hint: &str| {
946 let response = ui.add(
947 egui::TextEdit::singleline(value)
948 .id(egui::Id::new(("sheet-revision", sheet_id, index, field)))
949 .hint_text(hint)
950 .desired_width(width),
951 );
952 hits.borrow_mut().push((format!("sheets:rev:{index}:{field}"), response.rect));
953 if response.changed() {
954 intents.borrow_mut().push(RevisionIntent::Update(index, field, value.clone()));
955 }
956 };
957 ui.horizontal(|ui| {
958 ui.label(egui::RichText::new("Rev").weak());
959 edit(ui, "rev", &mut row.rev, 36.0, "A");
960 ui.label(egui::RichText::new("Date").weak());
961 edit(ui, "date", &mut row.date, 88.0, "YYYY-MM-DD");
962 let remove = ui
963 .add(crate::icon_text::icon_button(ui, "\u{2715}"))
964 .on_hover_text("Remove this revision row");
965 hits.borrow_mut().push((format!("sheets:rev:{index}:remove"), remove.rect));
966 if remove.clicked() {
967 intents.borrow_mut().push(RevisionIntent::Remove(index));
968 }
969 });
970 let width = ui.available_width().min(240.0);
973 edit(ui, "description", &mut row.description, width, "Description");
974 ui.add_space(4.0);
975 }
976 let add = ui
977 .add(crate::icon_text::icon_button(ui, "+ Add revision"))
978 .on_hover_text("Append a revision row: the next letter, today's date, no description");
979 hits.borrow_mut().push(("sheets:rev:add".into(), add.rect));
980 if add.clicked() {
981 intents.borrow_mut().push(RevisionIntent::Add);
982 }
983}
984
985fn trim(value: f64) -> String {
987 let text = format!("{value:.3}");
988 let text = text.trim_end_matches('0').trim_end_matches('.');
989 if text.is_empty() { "0".into() } else { text.to_string() }
990}
991
992pub static HIT_KEYS: &[HitKeyDoc] = &[
994 HitKeyDoc { panel: "sheets", prefix: "sheets:panel:clip", meaning: "the pane's clip rect \u{2014} a row scrolled outside it publishes a rect egui will not accept a click on", command: None },
995 HitKeyDoc { panel: "sheets", prefix: "sheets:add", meaning: "add a sheet at the default paper size and open it", command: Some("sheet_add") },
996 HitKeyDoc { panel: "sheets", prefix: "sheets:place", meaning: "open the place-view menu", command: None },
997 HitKeyDoc { panel: "sheets", prefix: "sheets:place:", meaning: "place that saved PMI view on the open sheet (sheets:place:<view id>)", command: Some("sheet_place_view") },
998 HitKeyDoc { panel: "sheets", prefix: "sheets:row:", meaning: "a sheet, placement, dimension or ordinate-set row (sheets:row:<id>) \u{2014} a click opens a sheet in the sheet viewport or SELECTS what it holds, a double click opens that row's dialog", command: None },
999 HitKeyDoc { panel: "sheets", prefix: "sheets:cell:", meaning: "a row cell (sheets:cell:<id>:<column>) \u{2014} `sheets:cell:<sheet id>:on` is the toggle that OPENS a sheet in the sheet viewport", command: Some("sheet_open") },
1000 HitKeyDoc { panel: "sheets", prefix: "sheets:box:", meaning: "a row's collapse box (sheets:box:<row id>) \u{2014} a sheet's box folds its placed views away", command: None },
1001 HitKeyDoc { panel: "sheets", prefix: "sheets:col:", meaning: "a table column header (sheets:col:<field>) \u{2014} click to sort", command: None },
1002 HitKeyDoc { panel: "sheets", prefix: "sheets:grip:", meaning: "a column's resize grip (sheets:grip:<field>)", command: None },
1003 HitKeyDoc { panel: "sheets", prefix: "sheets:menu:", meaning: "a row's action-menu trigger cell (sheets:menu:<row id>); a right-click on the row opens the same menu", command: None },
1004 HitKeyDoc { panel: "sheets", prefix: "sheets:menuitem:", meaning: "one entry of the OPEN row action menu (sheets:menuitem:<row id>:<action>) \u{2014} published only while the menu is up", command: None },
1005 HitKeyDoc { panel: "sheets", prefix: "sheets:form:", meaning: "the open sheet / placement form (sheets:form:object:<id>, sheets:form:feature, sheets:form:return)", command: Some("sheet_update") },
1006 HitKeyDoc { panel: "sheets", prefix: "sheets:field:", meaning: "one schema field of the open form (sheets:field:<path>) \u{2014} the paper size, the placed view, its position and scale, `sheets:field:flattenText`, the checkbox that lays that view's annotation text flat on the sheet, and a sheet dimension's kind, alignment, offset and precision and its tolerance block — `sheets:field:tolMode` (none / symmetric / deviation / limits), `sheets:field:tolUpper`, `sheets:field:tolLower` and the `sheets:field:isReference` checkbox, which an ordinate set's form carries too. `sheets:field:anchors#activate` focuses the field and opens the anchor pick on the paper (anchors are clicked as `sheet/anchor:<ref>`; the same key, now Done, commits a list, and a single field commits on its pick), `sheets:field:anchors#line<n>` is one anchor row and `sheets:field:anchors#x<n>` drops it. An ORDINATE SET's form adds `sheets:field:axis` and its two reference fields `sheets:field:datum` and `sheets:field:members`; a SECTION's form its `sheets:field:cut` (the cutting line), `sheets:field:sectionLabel` and `sheets:field:sectionFlip`; a DETAIL's form its `sheets:field:centre`, `sheets:field:rim` and `sheets:field:detailLabel` \u{2014} each reference field with the same `#activate`, `#line<n>` and `#x<n>` keys", command: Some("sheet_update_dimension") },
1007 HitKeyDoc { panel: "sheets", prefix: "sheets:group:", meaning: "a collapsible group header of the open form (sheets:group:<name>)", command: None },
1008 HitKeyDoc { panel: "sheets", prefix: "sheets:bom:", meaning: "the sheet BOM table toggle and column choices: sheets:bom:enabled, sheets:bom:column:<attribute>", command: Some("sheet_update") },
1009 HitKeyDoc { panel: "sheets", prefix: "sheets:rev:", meaning: "the SHEET dialog's Revisions section: `sheets:rev:add` appends a row (the next letter, today's date), and per row `sheets:rev:<n>:rev`, `sheets:rev:<n>:date` and `sheets:rev:<n>:description` are its three text edits and `sheets:rev:<n>:remove` removes it. Rows keep their order; the sheet draws them as the revision table beside its title block", command: Some("sheet_add_revision") },
1010];
1011
1012
1013
1014