Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/openecraft-i18n/src/catalog/extra.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,12 @@ connection failed: {} Verbindung fehlgeschlagen: {} échec de la connexion : {}
value set… Wertesatz … jeu de valeurs… conjunto de valores…
Shown in title blocks with {prop:Name} Wird in Schriftfeldern mit {prop:Name} angezeigt Affiché dans les cartouches avec {prop:Name} Se muestra en los cajetines con {prop:Name}
e.g. W z. B. W p. ex. W p. ej. W
(all) (alle) (tous) (todos)
Reset filter Filter zurücksetzen Réinitialiser le filtre Restablecer el filtro
Filter criteria Filterkriterien Critères de filtre Criterios de filtro
Top group Hauptgruppe Groupe principal Grupo principal
Group by Gruppieren nach Grouper par Agrupar por
{} of {} parts {} von {} Artikeln {} sur {} articles {} de {} artículos
(no product group) (keine Produktgruppe) (aucun groupe de produits) (sin grupo de productos)
(no manufacturer) (kein Hersteller) (aucun fabricant) (sin fabricante)
(no supplier) (kein Lieferant) (aucun fournisseur) (sin proveedor)
69 changes: 69 additions & 0 deletions crates/openecraft-parts/src/filter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//! Part filter of the part trees: free text plus manufacturer, supplier and product
//! group, and the criterion the tree is grouped by.

use crate::{natural_cmp, Part, TopGroup};

/// Criterion of the first tree level.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Grouping {
/// Top group › product group › subgroup.
#[default]
ProductGroup,
Manufacturer,
Supplier,
}

impl Grouping {
pub const ALL: [Grouping; 3] = [Grouping::ProductGroup, Grouping::Manufacturer, Grouping::Supplier];

pub fn title(self) -> &'static str {
match self {
Grouping::ProductGroup => "Product group",
Grouping::Manufacturer => "Manufacturer",
Grouping::Supplier => "Supplier",
}
}
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct PartFilter {
/// Searched in number, type, order number, manufacturer, description and groups.
pub text: String,
pub manufacturer: Option<String>,
pub supplier: Option<String>,
pub top_group: Option<TopGroup>,
pub group: Option<String>,
pub grouping: Grouping,
}

impl PartFilter {
pub fn matches(&self, p: &Part) -> bool {
let eq = |want: &Option<String>, have: &str| want.as_deref().is_none_or(|w| w == have);
p.matches_text(&self.text)
&& eq(&self.manufacturer, &p.manufacturer)
&& eq(&self.supplier, &p.supplier)
&& self.top_group.is_none_or(|t| t == p.top_group)
&& eq(&self.group, &p.group)
}

/// True if any criterion restricts the parts (the grouping does not).
pub fn is_active(&self) -> bool {
!self.text.is_empty() || self.manufacturer.is_some() || self.supplier.is_some() || self.top_group.is_some() || self.group.is_some()
}

/// Clears all criteria, keeps the grouping.
pub fn reset(&mut self) {
*self = PartFilter { grouping: self.grouping, ..Default::default() };
}
}

/// Distinct non-empty values of a part field, naturally sorted.
pub fn distinct_values<'a>(parts: impl IntoIterator<Item = &'a Part>, field: impl Fn(&Part) -> &str) -> Vec<String> {
let mut values: Vec<String> = parts.into_iter().map(&field).filter(|v| !v.is_empty()).map(String::from).collect();
values.sort_by(|a, b| natural_cmp(a, b));
values.dedup();
values
}

#[cfg(test)]
mod tests;
58 changes: 58 additions & 0 deletions crates/openecraft-parts/src/filter/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use super::*;

fn part(number: &str, manufacturer: &str, supplier: &str, top_group: TopGroup, group: &str) -> Part {
Part { number: number.into(), manufacturer: manufacturer.into(), supplier: supplier.into(), top_group, group: group.into(), ..Default::default() }
}

fn sample() -> Vec<Part> {
vec![
part("ABB.K1", "ABB", "Wholesale", TopGroup::Electrical, "Relays, contactors"),
part("SIE.K2", "Siemens", "Wholesale", TopGroup::Electrical, "Relays, contactors"),
part("SIE.Q1", "Siemens", "Direct", TopGroup::Electrical, "Safety devices"),
part("FES.V1", "Festo", "", TopGroup::Fluid, "Valves"),
]
}

fn numbers(parts: &[Part], f: &PartFilter) -> Vec<String> {
parts.iter().filter(|p| f.matches(p)).map(|p| p.number.clone()).collect()
}

#[test]
fn empty_filter_matches_everything() {
let parts = sample();
let f = PartFilter::default();
assert!(!f.is_active());
assert_eq!(numbers(&parts, &f).len(), parts.len());
}

#[test]
fn criteria_are_combined() {
let parts = sample();
let mut f = PartFilter { manufacturer: Some("Siemens".into()), ..Default::default() };
assert_eq!(numbers(&parts, &f), ["SIE.K2", "SIE.Q1"]);
f.group = Some("Safety devices".into());
assert_eq!(numbers(&parts, &f), ["SIE.Q1"]);
f.text = "k2".into();
assert!(numbers(&parts, &f).is_empty());

let f = PartFilter { supplier: Some("Wholesale".into()), text: "abb".into(), ..Default::default() };
assert_eq!(numbers(&parts, &f), ["ABB.K1"]);
let f = PartFilter { top_group: Some(TopGroup::Fluid), ..Default::default() };
assert_eq!(numbers(&parts, &f), ["FES.V1"]);
}

#[test]
fn reset_keeps_grouping() {
let mut f = PartFilter { text: "x".into(), manufacturer: Some("ABB".into()), grouping: Grouping::Manufacturer, ..Default::default() };
assert!(f.is_active());
f.reset();
assert!(!f.is_active());
assert_eq!(f.grouping, Grouping::Manufacturer);
}

#[test]
fn distinct_values_are_sorted_and_unique() {
let parts = sample();
assert_eq!(distinct_values(&parts, |p| &p.manufacturer), ["ABB", "Festo", "Siemens"]);
assert_eq!(distinct_values(&parts, |p| &p.supplier), ["Direct", "Wholesale"]);
}
3 changes: 3 additions & 0 deletions crates/openecraft-parts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//!
//! - [`Part`], [`FunctionTemplate`], [`PartsDb`] … – the part data (EPLAN style
//! product groups, commercial / technical / mounting data, function templates)
//! - part tree filter and grouping ([`PartFilter`])
//! - CSV / JSON import and export ([`to_csv`], [`from_csv`], [`import`])
//! - 2D / 3D models of parts with SVG, STL and OBJ import ([`Model2d`], [`Mesh3d`])
//! - the generic example catalog ([`default_catalog`])
Expand All @@ -10,13 +11,15 @@
pub mod api;
mod catalog;
mod csv;
mod filter;
mod graphics;
mod part;
mod text;
pub mod vec3;

pub use catalog::default_catalog;
pub use csv::{from_csv, import, to_csv};
pub use filter::{distinct_values, Grouping, PartFilter};
pub use graphics::{parse_mesh, parse_obj, parse_stl, parse_svg, Mesh3d, Model2d, Prim2d, MAX_TRIANGLES};
pub use part::*;
pub use text::natural_cmp;
92 changes: 79 additions & 13 deletions crates/openecraft-ui/src/part_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use openecraft_i18n::{tr, tr_fmt};
use crate::io::{short_name, FileKind};
use egui::{vec2, Color32, Pos2, RichText, Sense, Shape, Stroke};
use openecraft_parts::vec3::{cross, dot, norm, sub, Orbit};
use openecraft_parts::{parse_mesh, parse_svg, natural_cmp, FnKind, FunctionTemplate, Mesh3d, Model2d, Part, Prim2d, TopGroup, PRODUCT_GROUPS};
use openecraft_parts::{
distinct_values, parse_mesh, parse_svg, natural_cmp, FnKind, FunctionTemplate, Grouping, Mesh3d, Model2d, Part, PartFilter, Prim2d, TopGroup,
PRODUCT_GROUPS,
};
use std::collections::BTreeMap;

/// Graphics file of a part.
Expand Down Expand Up @@ -50,14 +53,75 @@ impl Default for EditorState {
}
}

/// Product group tree. Returns the part number that was double clicked.
pub fn part_tree(ui: &mut egui::Ui, id: &str, parts: &[&Part], filter: &str, selected: &mut Option<String>) -> Option<String> {
let mut tree: BTreeMap<TopGroup, BTreeMap<&str, BTreeMap<&str, Vec<&Part>>>> = BTreeMap::new();
for p in parts.iter().filter(|p| p.matches_text(filter)) {
let group = if p.group.is_empty() { "(no product group)" } else { p.group.as_str() };
tree.entry(p.top_group).or_default().entry(group).or_default().entry(p.subgroup.as_str()).or_default().push(p);
fn choice_row(ui: &mut egui::Ui, id: (&str, &str), label: &str, value: &mut Option<String>, options: &[String]) {
ui.label(label);
egui::ComboBox::from_id_salt(id).selected_text(value.as_deref().unwrap_or(tr("(all)"))).width(180.0).show_ui(ui, |ui| {
ui.selectable_value(value, None, tr("(all)"));
for o in options {
ui.selectable_value(value, Some(o.clone()), o);
}
});
ui.end_row();
}

/// Filter of a part tree: text, manufacturer, supplier, product group and grouping,
/// followed by the number of shown parts.
pub fn part_filter(ui: &mut egui::Ui, id: &str, parts: &[&Part], f: &mut PartFilter) {
ui.horizontal(|ui| {
let reset = ui.add_enabled(f.is_active(), egui::Button::new("✖")).on_hover_text(tr("Reset filter"));
if reset.clicked() {
f.reset();
}
ui.add(egui::TextEdit::singleline(&mut f.text).hint_text(tr("Filter (number, type, manufacturer, text …)")).desired_width(f32::INFINITY));
});
egui::CollapsingHeader::new(tr("Filter criteria")).id_salt((id, "criteria")).show(ui, |ui| {
egui::Grid::new((id, "filter")).num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| {
choice_row(ui, (id, "manufacturer"), tr("Manufacturer"), &mut f.manufacturer, &distinct_values(parts.iter().copied(), |p| &p.manufacturer));
choice_row(ui, (id, "supplier"), tr("Supplier"), &mut f.supplier, &distinct_values(parts.iter().copied(), |p| &p.supplier));
ui.label(tr("Top group"));
let title = f.top_group.map_or(tr("(all)"), |t| t.title());
egui::ComboBox::from_id_salt((id, "top")).selected_text(title).width(180.0).show_ui(ui, |ui| {
ui.selectable_value(&mut f.top_group, None, tr("(all)"));
for t in TopGroup::ALL {
ui.selectable_value(&mut f.top_group, Some(t), t.title());
}
});
ui.end_row();
let top = f.top_group;
let groups = distinct_values(parts.iter().copied().filter(|p| top.is_none_or(|t| t == p.top_group)), |p| &p.group);
choice_row(ui, (id, "group"), tr("Product group"), &mut f.group, &groups);
ui.label(tr("Group by"));
egui::ComboBox::from_id_salt((id, "grouping")).selected_text(tr(f.grouping.title())).width(180.0).show_ui(ui, |ui| {
for g in Grouping::ALL {
ui.selectable_value(&mut f.grouping, g, tr(g.title()));
}
});
ui.end_row();
});
});
let shown = parts.iter().filter(|p| f.matches(p)).count();
let count = if f.is_active() { tr_fmt!("{} of {} parts", shown, parts.len()) } else { tr_fmt!("{} parts", parts.len()) };
ui.label(RichText::new(count).weak());
}

/// Part tree, grouped as the filter says (product group, manufacturer or supplier).
/// Returns the part number that was double clicked.
pub fn part_tree(ui: &mut egui::Ui, id: &str, parts: &[&Part], filter: &PartFilter, selected: &mut Option<String>) -> Option<String> {
let (no_group, no_manufacturer, no_supplier) = (tr("(no product group)"), tr("(no manufacturer)"), tr("(no supplier)"));
let or = |s: &str, empty: &str| if s.is_empty() { empty } else { s }.to_string();
// First level: (sort key, title); product groups keep the top group order.
type Groups<'a> = BTreeMap<String, BTreeMap<&'a str, Vec<&'a Part>>>;
let mut tree: BTreeMap<(usize, String), Groups> = BTreeMap::new();
for p in parts.iter().filter(|p| filter.matches(p)) {
let group = or(&p.group, no_group);
let (first, sub) = match filter.grouping {
Grouping::ProductGroup => ((p.top_group as usize, p.top_group.title().to_string()), p.subgroup.as_str()),
Grouping::Manufacturer => ((0, or(&p.manufacturer, no_manufacturer)), ""),
Grouping::Supplier => ((0, or(&p.supplier, no_supplier)), ""),
};
tree.entry(first).or_default().entry(group).or_default().entry(sub).or_default().push(p);
}
let open = if filter.is_empty() { None } else { Some(true) };
let open = if filter.is_active() { Some(true) } else { None };
let mut activated = None;
let mut leaf = |ui: &mut egui::Ui, list: &mut Vec<&Part>| {
list.sort_by(|a, b| natural_cmp(&a.number, &b.number));
Expand All @@ -72,20 +136,22 @@ pub fn part_tree(ui: &mut egui::Ui, id: &str, parts: &[&Part], filter: &str, sel
}
}
};
for (top, groups) in tree.iter_mut() {
egui::CollapsingHeader::new(RichText::new(top.title()).strong())
.id_salt((id, top.title()))
let grouping = filter.grouping.title();
for ((_, top), groups) in tree.iter_mut() {
let top = top.as_str();
egui::CollapsingHeader::new(RichText::new(top).strong())
.id_salt((id, grouping, top))
.default_open(true)
.open(open)
.show(ui, |ui| {
for (group, subs) in groups.iter_mut() {
egui::CollapsingHeader::new(*group).id_salt((id, top.title(), *group)).open(open).show(ui, |ui| {
egui::CollapsingHeader::new(group.as_str()).id_salt((id, grouping, top, group.as_str())).open(open).show(ui, |ui| {
for (sub, list) in subs.iter_mut() {
if sub.is_empty() {
leaf(ui, list);
} else {
egui::CollapsingHeader::new(*sub)
.id_salt((id, top.title(), *group, *sub))
.id_salt((id, grouping, top, group.as_str(), *sub))
.open(open)
.show(ui, |ui| leaf(ui, list));
}
Expand Down
10 changes: 5 additions & 5 deletions parts-manager/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use openecraft_i18n::{tr, tr_fmt};
use crate::session::{FollowUp, Session};
use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText};
use openecraft_parts::to_csv;
use openecraft_parts::{to_csv, PartFilter};
use openecraft_ui::client::ServerClient;
use openecraft_ui::io::{short_name, FileIo, FileKind, Loaded};
use openecraft_ui::part_editor::{self as pe, EditorState, ModelKind};
Expand Down Expand Up @@ -39,7 +39,7 @@ pub struct ManagerApp {
session: Session,
editor: EditorState,
io: FileIo<Purpose>,
filter: String,
filter: PartFilter,
confirm: Option<Confirm>,
/// Part number a model import was requested for.
model_target: Option<String>,
Expand All @@ -61,7 +61,7 @@ impl ManagerApp {
session: Session::default(),
editor: EditorState::default(),
io: FileIo::default(),
filter: String::new(),
filter: PartFilter::default(),
confirm: None,
model_target: None,
started: false,
Expand Down Expand Up @@ -232,8 +232,8 @@ impl ManagerApp {
}

fn part_list(&mut self, ui: &mut egui::Ui) {
ui.add(egui::TextEdit::singleline(&mut self.filter).hint_text(tr("Filter (number, type, manufacturer, text …)")));
ui.label(RichText::new(tr_fmt!("{} parts", self.session.parts.len())).weak());
let refs: Vec<_> = self.session.parts.iter().collect();
pe::part_filter(ui, "parts", &refs, &mut self.filter);
if let Some(d) = self.session.draft.as_ref().filter(|d| d.original.is_none()) {
ui.label(RichText::new(tr_fmt!("➕ {} (not saved)", d.part.number)).italics());
}
Expand Down
23 changes: 10 additions & 13 deletions src/parts_ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use openecraft_i18n::{tr, tr_fmt};
use crate::model::Project;
use crate::parts::{self, Part, PartRef, PartsDb};
use crate::parts::{self, Part, PartFilter, PartRef, PartsDb};
use crate::io::{Loaded, Purpose};
use egui::{vec2, Color32, RichText};
use openecraft_ui::client::{Reply, ServerClient};
Expand Down Expand Up @@ -31,11 +31,11 @@ struct SelectRequest {
pub struct PartsUi {
pub open: bool,
source: Source,
filter: String,
filter: PartFilter,
selected: Option<String>,
editor: EditorState,
select: Option<SelectRequest>,
sel_filter: String,
sel_filter: PartFilter,
sel_matching: bool,
sel_part: Option<String>,
/// Connection to the global parts server.
Expand All @@ -50,11 +50,11 @@ impl Default for PartsUi {
PartsUi {
open: false,
source: Source::Database,
filter: String::new(),
filter: PartFilter::default(),
selected: None,
editor: EditorState::default(),
select: None,
sel_filter: String::new(),
sel_filter: PartFilter::default(),
sel_matching: true,
sel_part: None,
server: ServerClient::default(),
Expand Down Expand Up @@ -263,10 +263,9 @@ impl PartsUi {
let h = ui.available_height();
ui.horizontal_top(|ui| {
ui.allocate_ui_with_layout(vec2(300.0, h), egui::Layout::top_down(egui::Align::Min), |ui| {
ui.add(egui::TextEdit::singleline(&mut self.filter).hint_text(tr("Filter (number, type, manufacturer, text …)")));
ui.label(RichText::new(tr_fmt!("{} parts", list.len())).weak());
let refs: Vec<&Part> = list.iter().collect();
pe::part_filter(ui, "mgr", &refs, &mut self.filter);
egui::ScrollArea::vertical().id_salt("ptree").auto_shrink([false, false]).show(ui, |ui| {
let refs: Vec<&Part> = list.iter().collect();
pe::part_tree(ui, "mgr", &refs, &self.filter, &mut self.selected);
});
});
Expand Down Expand Up @@ -317,11 +316,8 @@ impl PartsUi {
let placed = parts::placed_functions(prj, &tag);
let main = parts::main_kind(prj, &tag);
egui::Window::new(tr_fmt!("Part selection – {}", tag)).open(&mut open).default_size([760.0, 480.0]).collapsible(false).show(ctx, |ui| {
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.sel_filter).hint_text(tr("Filter…")).desired_width(220.0));
ui.checkbox(&mut self.sel_matching, tr("Device selection"))
.on_hover_text(tr("Only parts whose function template provides the device's main function"));
});
ui.checkbox(&mut self.sel_matching, tr("Device selection"))
.on_hover_text(tr("Only parts whose function template provides the device's main function"));
ui.separator();
let shown: Vec<&Part> = all
.iter()
Expand All @@ -330,6 +326,7 @@ impl PartsUi {
let h = ui.available_height() - 36.0;
ui.horizontal_top(|ui| {
ui.allocate_ui_with_layout(vec2(300.0, h), egui::Layout::top_down(egui::Align::Min), |ui| {
pe::part_filter(ui, "sel", &shown, &mut self.sel_filter);
egui::ScrollArea::vertical().id_salt("seltree").auto_shrink([false, false]).show(ui, |ui| {
if let Some(n) = pe::part_tree(ui, "sel", &shown, &self.sel_filter, &mut self.sel_part) {
chosen = Some(n);
Expand Down
Loading