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