diff --git a/assets/locales/pending/frame-member-groups.json b/assets/locales/pending/frame-member-groups.json new file mode 100644 index 00000000000..4970925d212 --- /dev/null +++ b/assets/locales/pending/frame-member-groups.json @@ -0,0 +1,50 @@ +{ + "ar": { + "ui.frame_member.group": "المجموعة {number}", + "ui.frame_member.groups": "المجموعات", + "ui.frame_member.new_group": "مجموعة جديدة", + "ui.frame_member.remove_group": "إزالة المجموعة" + }, + "de": { + "ui.frame_member.group": "Gruppe {number}", + "ui.frame_member.groups": "Gruppen", + "ui.frame_member.new_group": "Neue Gruppe", + "ui.frame_member.remove_group": "Gruppe entfernen" + }, + "en": { + "ui.frame_member.group": "Group {number}", + "ui.frame_member.groups": "Groups", + "ui.frame_member.new_group": "New Group", + "ui.frame_member.remove_group": "Remove Group" + }, + "he": { + "ui.frame_member.group": "קבוצה {number}", + "ui.frame_member.groups": "קבוצות", + "ui.frame_member.new_group": "קבוצה חדשה", + "ui.frame_member.remove_group": "הסרת קבוצה" + }, + "ja": { + "ui.frame_member.group": "グループ {number}", + "ui.frame_member.groups": "グループ", + "ui.frame_member.new_group": "新しいグループ", + "ui.frame_member.remove_group": "グループを削除" + }, + "ko": { + "ui.frame_member.group": "그룹 {number}", + "ui.frame_member.groups": "그룹", + "ui.frame_member.new_group": "새 그룹", + "ui.frame_member.remove_group": "그룹 제거" + }, + "vi": { + "ui.frame_member.group": "Nhóm {number}", + "ui.frame_member.groups": "Nhóm", + "ui.frame_member.new_group": "Tạo nhóm mới", + "ui.frame_member.remove_group": "Xóa nhóm" + }, + "zh": { + "ui.frame_member.group": "组 {number}", + "ui.frame_member.groups": "组", + "ui.frame_member.new_group": "新建组", + "ui.frame_member.remove_group": "删除组" + } +} diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index bd30616659d..7104d333199 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1017,6 +1017,11 @@ pub enum FeatureKind { /// come and go (`frame::member_names`). #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] names: std::collections::BTreeMap, + /// Two or more groups of lines, each placed its own way (`frame::MemberGroup`); then they + /// stand in for `lines`, `anchor`, `angle`, `mirror` and `body_name`, which stay unset. + /// None: those fields are the feature's one group (`frame::member_groups`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + groups: Vec, }, /// Raise or sink profiles on a planar face, or wrap them on a selected cylindrical wall. Emboss { diff --git a/crates/doc/src/eval_frame.rs b/crates/doc/src/eval_frame.rs index 35ab2b0fcce..0e2105677d3 100644 --- a/crates/doc/src/eval_frame.rs +++ b/crates/doc/src/eval_frame.rs @@ -2,7 +2,7 @@ //! profile laid square to the line (`frame::member_axes`) and run from one end to the other. use std::borrow::Cow; -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use solidcraft_geom::{Aabb2, Plane, Region2, Ring, Vec2, Vec3}; use solidcraft_kernel as kernel; @@ -10,7 +10,7 @@ use solidcraft_sketch::CurveKind; use super::{ModelBody, ModelState, SolvedSketch, new_name, path_in_frame, select_profiles, sketch_in_feature_frame, val}; use crate::expr::{Kind, Value}; -use crate::frame::{self, MAX_MEMBERS, MemberProfile}; +use crate::frame::{self, MAX_MEMBERS, MemberGroup, MemberProfile}; use crate::{DocError, Document, Feature, FeatureKind, ProfileSel, Result}; /// Most profiles a profile sketch may have for its material to be worked out. @@ -20,36 +20,42 @@ const MIN_LENGTH: f64 = 1e-6; /// How far (mm) a 3D sketch curve may stray from the line between its ends and still be a line. const STRAIGHT_TOL: f64 = 1e-3; -/// Evaluate a `FrameMember` feature: one new body per line, each named -/// ([`member_names`], or by position for a copy whose `body_names` were set). +/// Evaluate a `FrameMember` feature: one new body per line, group by group, each placed as its +/// group says and named ([`member_names`], or by position for a copy whose `body_names` were set). pub(super) fn evaluate(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState) -> Result<()> { - let FeatureKind::FrameMember { path_sketch, lines, profile, anchor, angle, mirror, body_name, names } = &f.kind else { + let FeatureKind::FrameMember { path_sketch, profile, names, .. } = &f.kind else { return Err(DocError::Invalid("not a frame member feature".into())); }; let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; // The frame sketch in this feature's component frame: its plane, and its 3D lines. let mapped = if ps.sketch.wires.is_empty() { Cow::Owned(sketch_in_feature_frame(doc, ps, f.component)?) } else { path_in_frame(doc, ps, f.component)? }; - let segments = member_lines(mapped.as_ref(), lines)?; - let (mut regions, description) = profile_regions(vals, st, profile)?; - if *mirror { - regions = regions.iter().map(frame::mirrored).collect(); - } - let at = frame::anchor_point(®ions, *anchor); - let turn = match angle { - Some(e) => val(vals, e, Kind::Angle)?, - None => 0.0, - }; - let mut made = Vec::with_capacity(segments.len()); - for (id, a, b) in &segments { - let (x, y) = frame::member_axes(*b - *a, turn).ok_or_else(|| DocError::Invalid(format!("line `{id}` has no length")))?; - let plane = Plane::new(*a - x * at.x - y * at.y, x, y).ok_or_else(|| DocError::Invalid(format!("line `{id}`: no plane square to it")))?; - let mut bodies = kernel::extrude(&plane, ®ions, 0.0, a.dist(*b))?; - let body = match (bodies.pop(), bodies.is_empty()) { - (Some(body), true) => body, - _ => return Err(DocError::Invalid(format!("the member on line `{id}` is not one solid"))), + let groups = frame::member_groups(&f.kind); + let lines = group_lines(mapped.as_ref(), &groups)?; + let (section, description) = profile_regions(vals, st, profile)?; + let mut made = Vec::new(); + let mut ids = Vec::new(); + let mut bases = Vec::new(); + for (group, segments) in groups.iter().zip(lines) { + let regions: Cow<[Region2]> = if group.mirror { Cow::Owned(section.iter().map(frame::mirrored).collect()) } else { Cow::Borrowed(§ion) }; + let at = frame::anchor_point(®ions, group.anchor); + let turn = match &group.angle { + Some(e) => val(vals, e, Kind::Angle)?, + None => 0.0, }; - made.push(crate::lineage::numbered_tool(body)); + let base = group.body_name.as_deref().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&description); + for (id, a, b) in segments { + let (x, y) = frame::member_axes(b - a, turn).ok_or_else(|| DocError::Invalid(format!("line `{id}` has no length")))?; + let plane = Plane::new(a - x * at.x - y * at.y, x, y).ok_or_else(|| DocError::Invalid(format!("line `{id}`: no plane square to it")))?; + let mut bodies = kernel::extrude(&plane, ®ions, 0.0, a.dist(b))?; + let body = match (bodies.pop(), bodies.is_empty()) { + (Some(body), true) => body, + _ => return Err(DocError::Invalid(format!("the member on line `{id}` is not one solid"))), + }; + made.push(crate::lineage::numbered_tool(body)); + ids.push(id); + bases.push(base.to_string()); + } } if !f.body_names.is_empty() { // A copy (pasted, or in a copied component) names its members by position, as any @@ -60,9 +66,7 @@ pub(super) fn evaluate(doc: &Document, vals: &BTreeMap, f: &Featu } return Ok(()); } - let base = body_name.as_deref().map(str::trim).filter(|n| !n.is_empty()).map_or(description, str::to_string); - let ids: Vec = segments.into_iter().map(|(id, _, _)| id).collect(); - for (name, t) in member_names(st, &ids, names, &base).into_iter().zip(made) { + for (name, t) in group_member_names(st, &ids, &bases, names).into_iter().zip(made) { st.bodies.push(ModelBody::traced_new(name, t, f.id)); } Ok(()) @@ -72,6 +76,12 @@ pub(super) fn evaluate(doc: &Document, vals: &BTreeMap, f: &Featu /// other body has it, else the first free one of `base`, `base (2)`, `base (3)`… that no line has /// pinned. A member therefore keeps its name when other lines are added, deleted or reordered. pub fn member_names(st: &ModelState, lines: &[String], pinned: &BTreeMap, base: &str) -> Vec { + group_member_names(st, lines, &vec![base.to_string(); lines.len()], pinned) +} + +/// [`member_names`] with a base of its own for each line (its group's), the numbers counting on +/// per base across the groups. +pub fn group_member_names(st: &ModelState, lines: &[String], bases: &[String], pinned: &BTreeMap) -> Vec { let reserved: HashSet<&str> = pinned.values().map(String::as_str).collect(); let mut used: HashSet = HashSet::new(); let mut out: Vec> = lines @@ -81,15 +91,18 @@ pub fn member_names(st: &ModelState, lines: &[String], pinned: &BTreeMap = HashMap::new(); + for (slot, base) in out.iter_mut().zip(bases.iter().map(|b| if b.trim().is_empty() { "Member" } else { b.trim() })) { + if slot.is_some() { + continue; + } + let next = next.entry(base).or_insert(1); + while *next <= limit { + let candidate = if *next == 1 { base.to_string() } else { format!("{base} ({next})") }; + *next += 1; if st.body(&candidate).is_none() && !used.contains(&candidate) && !reserved.contains(candidate.as_str()) { used.insert(candidate.clone()); *slot = Some(candidate); @@ -97,16 +110,40 @@ pub fn member_names(st: &ModelState, lines: &[String], pinned: &BTreeMap Result> { - let FeatureKind::FrameMember { path_sketch, lines, .. } = kind else { + let FeatureKind::FrameMember { path_sketch, .. } = kind else { return Err(DocError::Invalid("not a frame member feature".into())); }; let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch}")))?; - Ok(member_lines(ps, lines)?.into_iter().map(|(id, _, _)| id).collect()) + Ok(group_lines(ps, &frame::member_groups(kind))?.into_iter().flatten().map(|(id, _, _)| id).collect()) +} + +/// Each group's member lines ([`member_lines`]). A feature's single group may leave its lines out +/// (every line); of several, each lists its own, no line in two of them. +fn group_lines(ss: &SolvedSketch, groups: &[MemberGroup]) -> Result>> { + if let [only] = groups { + return Ok(vec![member_lines(ss, &only.lines)?]); + } + if groups.iter().map(|g| g.lines.len()).sum::() > MAX_MEMBERS { + return Err(DocError::Invalid(format!("at most {MAX_MEMBERS} members in one feature"))); + } + let mut seen = HashSet::new(); + let mut out = Vec::with_capacity(groups.len()); + for (k, g) in groups.iter().enumerate() { + if g.lines.is_empty() { + return Err(DocError::Invalid(format!("group {} has no lines", k + 1))); + } + if let Some(twice) = g.lines.iter().find(|l| !seen.insert(l.as_str())) { + return Err(DocError::Invalid(format!("line `{twice}` is listed twice"))); + } + out.push(member_lines(ss, &g.lines)?); + } + Ok(out) } /// The member lines of the frame sketch, each as (curve id, start, end) in its frame: the lines diff --git a/crates/doc/src/format/pending/frame-member-groups.rs b/crates/doc/src/format/pending/frame-member-groups.rs new file mode 100644 index 00000000000..2a22c3e4a12 --- /dev/null +++ b/crates/doc/src/format/pending/frame-member-groups.rs @@ -0,0 +1,6 @@ +//! A `frame_member` feature can hold `groups` (#4003): two or more groups of its frame sketch's +//! lines, each with its own `lines`, `anchor`, `angle`, `mirror` and `body_name`, all made of the +//! feature's one profile. Then the feature's own `lines`, `anchor`, `angle`, `mirror` and +//! `body_name` stay unset. Older designs need no transformation: without `groups` those fields +//! are the feature's one group, as before. The last release refuses a design saved with this +//! (the newer format number) rather than dropping all but one group's settings. diff --git a/crates/doc/src/frame.rs b/crates/doc/src/frame.rs index 60404781778..f45013a85ca 100644 --- a/crates/doc/src/frame.rs +++ b/crates/doc/src/frame.rs @@ -259,7 +259,7 @@ impl crate::walk::Walk for ProfileSpec { } } -pub use crate::eval::frame_member::{member_line_ids, member_names}; +pub use crate::eval::frame_member::{group_member_names, member_line_ids, member_names}; /// Where a frame member's cross-section comes from. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] @@ -279,6 +279,42 @@ pub enum MemberProfile { }, } +/// One group of a frame member feature: lines whose members share a placement on the profile +/// (#4003). Per-group finishing, such as how the group's corners are treated, belongs here too. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +pub struct MemberGroup { + /// The lines, by curve id; none (only in a feature's single group): every straight line drawn + /// in the frame sketch. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub lines: Vec, + /// The profile point that sits on each line. + #[serde(default, skip_serializing_if = "Anchor::is_origin")] + pub anchor: Anchor, + /// How far the profile turns about each line (see [`member_axes`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(angle = "Rotation")] + pub angle: Option, + /// The profile mirrored across its y axis (before it turns). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub mirror: bool, + /// What the group's members are named after when they have no name of their own; none: the + /// profile's description or the profile sketch's name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body_name: Option, +} + +/// The groups of a frame member feature, in the order their members are made: its `groups`, or, +/// without them, the one group its own `lines`, `anchor`, `angle`, `mirror` and `body_name` make. +pub fn member_groups(kind: &crate::FeatureKind) -> Vec { + match kind { + crate::FeatureKind::FrameMember { groups, .. } if !groups.is_empty() => groups.clone(), + crate::FeatureKind::FrameMember { lines, anchor, angle, mirror, body_name, .. } => { + vec![MemberGroup { lines: lines.clone(), anchor: *anchor, angle: angle.clone(), mirror: *mirror, body_name: body_name.clone() }] + } + _ => Vec::new(), + } +} + impl Anchor { pub fn is_origin(&self) -> bool { *self == Anchor::Origin diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 08736550d30..5ce4080bb9f 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1520,6 +1520,26 @@ fn input_keys(kind: &FeatureKind) -> Vec<(String, solidcraft_doc::expr::Kind)> { keys } +/// The name a frame member feature gives the member on `line` (its group's `body_name`); none: +/// named after the profile. +fn member_group_name(kind: &FeatureKind, line: &str) -> Option { + let groups = solidcraft_doc::frame::member_groups(kind); + let group = groups.iter().find(|g| g.lines.is_empty() || g.lines.iter().any(|l| l == line))?; + group.body_name.as_deref().map(str::trim).filter(|n| !n.is_empty()).map(str::to_string) +} + +/// The name `frame.member` parameters give the member on `line`, as [`member_group_name`]. +fn given_group_name(p: &serde_json::Map, line: &str) -> Option { + let named = match p.get("groups").and_then(Value::as_array) { + Some(groups) => groups + .iter() + .find(|g| g.get("lines").and_then(Value::as_array).is_some_and(|ls| ls.iter().any(|l| l.as_str() == Some(line))))? + .get("body_name"), + None => p.get("body_name"), + }; + named.and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string) +} + fn redefine(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.redefine"; let id = feature_id(s, p.get("feature"), cmd)?; @@ -1574,12 +1594,16 @@ fn redefine(s: &mut Session, p: &Value) -> Result { parameters.entry("convention").or_insert_with(|| json!(convention)); } // Members keep their names through an edit, unless it gives them another name. - if let FeatureKind::FrameMember { names, body_name, .. } = &old.kind + // With groups, a member keeps its name while its group's name stays the same. + if let FeatureKind::FrameMember { names, .. } = &old.kind && cid == "frame.member" && let Some(parameters) = params.as_object_mut() - && parameters.get("body_name").and_then(Value::as_str) == body_name.as_deref() { - parameters.entry("names").or_insert_with(|| json!(names)); + let kept: BTreeMap<&String, &String> = + names.iter().filter(|(line, _)| member_group_name(&old.kind, line) == given_group_name(parameters, line)).collect(); + if !kept.is_empty() { + parameters.entry("names").or_insert_with(|| json!(kept)); + } } if !old.participants.is_empty() && let Some(parameters) = params.as_object_mut() diff --git a/crates/engine/src/cmd/frame.rs b/crates/engine/src/cmd/frame.rs index d0fec7a264c..20235466a30 100644 --- a/crates/engine/src/cmd/frame.rs +++ b/crates/engine/src/cmd/frame.rs @@ -7,7 +7,7 @@ use std::collections::BTreeMap; use serde_json::{Value, json}; use solidcraft_doc::expr::Kind; -use solidcraft_doc::frame::{self, Anchor, MemberProfile, Profile, ProfileSpec}; +use solidcraft_doc::frame::{self, Anchor, MemberGroup, MemberProfile, Profile, ProfileSpec}; use solidcraft_doc::{FeatureKind, SketchId}; use solidcraft_geom::{Loop2, Seg2, Vec2}; use solidcraft_sketch::Sketch; @@ -33,7 +33,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("frame.member", "Frame Member", member).at("WELDMENTS", "CREATE").icon("frame_member").enabled(not_in_sketch).params(concat!( "sketch: the frame sketch (id or name; 2D or 3D); lines?: [curve ids] (one member each; default: every straight line drawn in the sketch: not construction, not projected or otherwise linked, not of no length); ", profile_doc!(), - " | profile_sketch: a sketch whose profile is the section, in its own x and y around its origin, with profiles?: picks as solid.extrude takes them (default: its material, nested loops alternating, so two circles make a tube); anchor?: origin|center|centroid|top_left|top|top_right|left|right|bottom_left|bottom|bottom_right (the profile point that sits on each line, default origin); angle?: angle expr (the profile turned about the line; default 0: its y as near world up as the line allows, a vertical member's x along world X); mirror?: bool (the profile mirrored across its y axis); name?; body_name? (what the members are named after, then numbered: `Rail`, `Rail (2)`…; default the profile's description, `Rect Tube 40x40x3`, or the profile sketch's name); names?: {line id: name} (names to keep, as Edit Feature keeps them). One body per line, from its start to its end; each member keeps its name when other lines are added or deleted. Returns the feature and the bodies it made" + " | profile_sketch: a sketch whose profile is the section, in its own x and y around its origin, with profiles?: picks as solid.extrude takes them (default: its material, nested loops alternating, so two circles make a tube); anchor?: origin|center|centroid|top_left|top|top_right|left|right|bottom_left|bottom|bottom_right (the profile point that sits on each line, default origin); angle?: angle expr (the profile turned about the line; default 0: its y as near world up as the line allows, a vertical member's x along world X); mirror?: bool (the profile mirrored across its y axis); name?; body_name? (what the members are named after, then numbered: `Rail`, `Rail (2)`…; default the profile's description, `Rect Tube 40x40x3`, or the profile sketch's name); names?: {line id: name} (names to keep, as Edit Feature keeps them); groups?: [{lines, anchor?, angle?, mirror?, body_name?}] (instead of those keys beside the profile: several groups of lines of one profile, each placed and named its own way, no line in two groups). One body per line, from its start to its end; each member keeps its name when other lines are added or deleted. Returns the feature and the bodies it made" )), CommandSpec::new("frame.profile.list", "Profile Library", list).icon("library") .noundo() @@ -182,20 +182,24 @@ fn add_loop(sk: &mut Sketch, l: &Loop2, fixed: bool, cmd: &str) -> Result<()> { Ok(()) } -fn member(s: &mut Session, p: &Value) -> Result { - let cmd = "frame.member"; - let path_sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?; +/// The keys of one group of members, given beside `profile` for a feature's single group or in +/// each of its `groups`. +const GROUP_KEYS: [&str; 5] = ["lines", "anchor", "angle", "mirror", "body_name"]; + +/// One group of members as `p` (the command's parameters, or one of its `groups`) gives it; `at` +/// names the group in errors, and a group of several must list its lines. +fn member_group(s: &Session, cmd: &str, p: &Value, at: &str, several: bool) -> Result { let lines = match p.get("lines") { - None | Some(Value::Null) => Vec::new(), + None | Some(Value::Null) if !several => Vec::new(), Some(Value::Array(a)) if !a.is_empty() && a.len() <= frame::MAX_MEMBERS && a.iter().all(Value::is_string) => { let lines = string_list(cmd, p, "lines")?; let mut seen = std::collections::HashSet::new(); if let Some(twice) = lines.iter().find(|l| !seen.insert(l.as_str())) { - return Err(bad(cmd, format!("line `{twice}` is listed twice"))); + return Err(bad(cmd, format!("{at}line `{twice}` is listed twice"))); } lines } - Some(_) => Err(bad(cmd, format!("`lines` must list 1…{} curve ids", frame::MAX_MEMBERS)))?, + _ => Err(bad(cmd, format!("{at}`lines` must list 1…{} curve ids", frame::MAX_MEMBERS)))?, }; let body_name = match p.get("body_name") { None | Some(Value::Null) => None, @@ -203,10 +207,64 @@ fn member(s: &mut Session, p: &Value) -> Result { str_(p, "body_name") .map(str::trim) .filter(|n| !n.is_empty() && n.len() <= 128) - .ok_or_else(|| bad(cmd, "`body_name` must be 1…128 characters"))? + .ok_or_else(|| bad(cmd, format!("{at}`body_name` must be 1…128 characters")))? .to_string(), ), }; + let anchor: Anchor = match p.get("anchor") { + None | Some(Value::Null) => Anchor::default(), + Some(v) => serde_json::from_value(v.clone()).map_err(|_| { + bad( + cmd, + format!("{at}`anchor` must be origin, center, centroid, top_left, top, top_right, left, right, bottom_left, bottom or bottom_right"), + ) + })?, + }; + let angle = match p.get("angle") { + None | Some(Value::Null) => None, + Some(_) => { + let e = expr(p, "angle").ok_or_else(|| bad(cmd, format!("{at}`angle` must be an angle expression")))?; + check_expr(s, &e, solidcraft_doc::expr::Kind::Angle, cmd, "angle")?; + Some(e) + } + }; + let mirror = match p.get("mirror") { + None | Some(Value::Null) => false, + Some(_) => bool_(p, "mirror").ok_or_else(|| bad(cmd, format!("{at}`mirror` must be true or false")))?, + }; + Ok(MemberGroup { lines, anchor, angle, mirror, body_name }) +} + +/// The groups of members `p` asks for: its `groups`, or the one group its own keys make. +fn member_groups(s: &Session, cmd: &str, p: &Value) -> Result> { + let list = match p.get("groups") { + None | Some(Value::Null) => return Ok(vec![member_group(s, cmd, p, "", false)?]), + Some(Value::Array(a)) if !a.is_empty() && a.len() <= frame::MAX_MEMBERS && a.iter().all(Value::is_object) => a, + Some(_) => { + return Err(bad( + cmd, + format!("`groups` must list 1…{} groups, each {{lines, anchor?, angle?, mirror?, body_name?}}", frame::MAX_MEMBERS), + )); + } + }; + if let Some(key) = GROUP_KEYS.iter().find(|k| p.get(**k).is_some_and(|v| !v.is_null())) { + return Err(bad(cmd, format!("give `{key}` in each of `groups`, not beside them"))); + } + let groups = list.iter().enumerate().map(|(k, g)| member_group(s, cmd, g, &format!("group {}: ", k + 1), true)).collect::>>()?; + if groups.iter().map(|g| g.lines.len()).sum::() > frame::MAX_MEMBERS { + return Err(bad(cmd, format!("at most {} members in one feature", frame::MAX_MEMBERS))); + } + let mut seen = std::collections::HashSet::new(); + if let Some(twice) = groups.iter().flat_map(|g| &g.lines).find(|l| !seen.insert(l.as_str())) { + return Err(bad(cmd, format!("line `{twice}` is in two groups"))); + } + Ok(groups) +} + +fn member(s: &mut Session, p: &Value) -> Result { + let cmd = "frame.member"; + let path_sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?; + let mut groups = member_groups(s, cmd, p)?; let (profile, default_name) = match (p.get("profile"), p.get("profile_sketch")) { (Some(_), None) => { let spec = profile_spec(cmd, p)?; @@ -224,24 +282,6 @@ fn member(s: &mut Session, p: &Value) -> Result { } _ => return Err(bad(cmd, "give `profile` (a built-in profile) or `profile_sketch` (a sketch), one of them")), }; - let anchor: Anchor = match p.get("anchor") { - None | Some(Value::Null) => Anchor::default(), - Some(v) => serde_json::from_value(v.clone()).map_err(|_| { - bad(cmd, "`anchor` must be origin, center, centroid, top_left, top, top_right, left, right, bottom_left, bottom or bottom_right") - })?, - }; - let angle = match p.get("angle") { - None | Some(Value::Null) => None, - Some(_) => { - let e = expr(p, "angle").ok_or_else(|| bad(cmd, "`angle` must be an angle expression"))?; - check_expr(s, &e, solidcraft_doc::expr::Kind::Angle, cmd, "angle")?; - Some(e) - } - }; - let mirror = match p.get("mirror") { - None | Some(Value::Null) => false, - Some(_) => bool_(p, "mirror").ok_or_else(|| bad(cmd, "`mirror` must be true or false"))?, - }; let kept: BTreeMap = match p.get("names") { None | Some(Value::Null) => BTreeMap::new(), Some(Value::Object(m)) if m.len() <= frame::MAX_MEMBERS => m @@ -254,14 +294,44 @@ fn member(s: &mut Session, p: &Value) -> Result { .collect::>()?, Some(_) => return Err(bad(cmd, format!("`names` must map up to {} line ids to names", frame::MAX_MEMBERS))), }; - let base = body_name.clone().unwrap_or(default_name); - let mut kind = - FeatureKind::FrameMember { path_sketch: SketchId(path_sketch), lines, profile, anchor, angle, mirror, body_name, names: BTreeMap::new() }; + let base = |g: &MemberGroup| g.body_name.clone().unwrap_or_else(|| default_name.clone()); + // One group is saved as the feature's own lines and placement, as before groups existed. + let mut kind = match groups.as_mut_slice() { + [one] => { + let MemberGroup { lines, anchor, angle, mirror, body_name } = std::mem::take(one); + FeatureKind::FrameMember { + path_sketch: SketchId(path_sketch), + lines, + profile, + anchor, + angle, + mirror, + body_name, + names: BTreeMap::new(), + groups: Vec::new(), + } + } + _ => FeatureKind::FrameMember { + path_sketch: SketchId(path_sketch), + lines: Vec::new(), + profile, + anchor: Anchor::default(), + angle: None, + mirror: false, + body_name: None, + names: BTreeMap::new(), + groups, + }, + }; // Each member's name is pinned to its line as the feature is made, so deleting or adding a // line later leaves the other members' names alone. let st = s.model.state(); let ids = frame::member_line_ids(&st, &kind).map_err(|e| bad(cmd, e.to_string()))?; - let pinned: BTreeMap = ids.iter().cloned().zip(frame::member_names(&st, &ids, &kept, &base)).collect(); + let bases: Vec = match frame::member_groups(&kind).as_slice() { + [one] => vec![base(one); ids.len()], + several => several.iter().flat_map(|g| std::iter::repeat_n(base(g), g.lines.len())).collect(), + }; + let pinned: BTreeMap = ids.iter().cloned().zip(frame::group_member_names(&st, &ids, &bases, &kept)).collect(); if let FeatureKind::FrameMember { names, .. } = &mut kind { *names = pinned; } diff --git a/crates/engine/src/cmd/frame_tests.rs b/crates/engine/src/cmd/frame_tests.rs index 5559b909351..7c1660fcdd7 100644 --- a/crates/engine/src/cmd/frame_tests.rs +++ b/crates/engine/src/cmd/frame_tests.rs @@ -638,3 +638,124 @@ fn editing_the_feature_keeps_member_names_until_it_names_them() { run(&mut s, "edit.undo", json!({})); assert_eq!(boxes(&mut s).into_keys().collect::>(), names); } + +// --------------------------------------------------------------------------------------------- +// Groups: several groups of lines of one profile, each placed and named its own way + +/// The rectangle frame's rails (bottom and top) and posts (left and right), by line id. +fn rails_and_posts(s: &Session) -> (Vec, Vec) { + let rails = vec![line_at_y(s, "Frame", 0.0), line_at_y(s, "Frame", 400.0)]; + let posts = vec![line_at_x(s, "Frame", 0.0), line_at_x(s, "Frame", 600.0)]; + (rails, posts) +} + +fn grouped(rails: &[String], posts: &[String]) -> Value { + json!({"sketch": "Frame", "profile": {"kind": "angle", "width": 60, "height": 40, "thickness": 5}, "groups": [ + {"lines": rails, "anchor": "bottom_left", "body_name": "Rail"}, + {"lines": posts, "anchor": "bottom_left", "angle": "90 deg", "body_name": "Post"}, + ]}) +} + +#[test] +fn groups_place_and_name_their_members_their_own_way() { + let mut s = Session::default(); + rectangle_frame(&mut s); + let (rails, posts) = rails_and_posts(&s); + run(&mut s, "frame.member", grouped(&rails, &posts)); + let bs = boxes(&mut s); + assert_eq!(bs.keys().collect::>(), ["Post", "Post (2)", "Rail", "Rail (2)"], "{bs:?}"); + // Where each group puts its members is graded in tests/kernel-cases/frames + // (cov-frame-member-groups-turned-their-own-way). +} + +#[test] +fn one_group_is_saved_as_the_flat_form() { + let mut s = Session::default(); + rectangle_frame(&mut s); + let (rails, _) = rails_and_posts(&s); + run(&mut s, "frame.member", json!({"sketch": "Frame", "profile": tube(), "groups": [{"lines": rails, "mirror": true, "body_name": "Rail"}]})); + let saved = serde_json::to_value(&s.doc.features.last().unwrap().kind).unwrap(); + assert!(saved.get("groups").is_none(), "{saved}"); + assert_eq!((&saved["lines"], &saved["mirror"], &saved["body_name"]), (&json!(rails), &json!(true), &json!("Rail"))); + assert_eq!(boxes(&mut s).keys().collect::>(), ["Rail", "Rail (2)"]); +} + +#[test] +fn bad_groups_are_refused() { + let mut s = Session::default(); + rectangle_frame(&mut s); + let (rails, posts) = rails_and_posts(&s); + let with = |groups: Value| json!({"sketch": "Frame", "profile": tube(), "groups": groups}); + for (p, why) in [ + (with(json!([])), "`groups`"), + (with(json!("all")), "`groups`"), + (with(json!([1, 2])), "`groups`"), + (with(json!([{"lines": rails}, {}])), "group 2: `lines`"), + (with(json!([{"lines": rails}, {"lines": []}])), "group 2: `lines`"), + (with(json!([{"lines": rails}, {"lines": [&posts[0], &posts[0]]}])), "listed twice"), + (with(json!([{"lines": rails}, {"lines": [&rails[0]]}])), "in two groups"), + (with(json!([{"lines": rails}, {"lines": posts, "anchor": "middle"}])), "group 2: `anchor`"), + (with(json!([{"lines": rails}, {"lines": posts, "angle": "a lot"}])), "angle"), + (with(json!([{"lines": rails}, {"lines": posts, "mirror": "yes"}])), "group 2: `mirror`"), + (with(json!([{"lines": rails}, {"lines": posts, "body_name": ""}])), "group 2: `body_name`"), + (with(json!([{"lines": rails}, {"lines": ["nope"]}])), "nope"), + (json!({"sketch": "Frame", "profile": tube(), "lines": rails, "groups": [{"lines": posts}]}), "not beside"), + (json!({"sketch": "Frame", "profile": tube(), "mirror": true, "groups": [{"lines": posts}]}), "not beside"), + ] { + let err = s.execute("frame.member", &p).unwrap_err().to_string(); + assert!(err.contains(why), "{p}: {err}"); + } + assert!(bodies(&mut s).is_empty(), "nothing was made"); +} + +/// A design's groups survive saving and reopening; an edit keeps every member's name but those of +/// a group given another name, and a member renamed by hand keeps its new name. +#[test] +fn groups_survive_reopening_and_edits_keep_their_names() { + let mut s = Session::default(); + rectangle_frame(&mut s); + let (rails, posts) = rails_and_posts(&s); + run(&mut s, "frame.member", grouped(&rails, &posts)); + let fid = s.doc.features.last().unwrap().id; + let before = boxes(&mut s); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert_eq!(boxes(&mut reopened), before); + run(&mut s, "body.rename", json!({"body": "Post (2)", "name": "Right post"})); + // Turn the posts back: same names, the rails untouched. + let mut p = grouped(&rails, &posts); + p["groups"][1]["angle"] = json!("0 deg"); + run(&mut s, "timeline.redefine", json!({"feature": fid, "command": "frame.member", "params": p.clone()})); + let after = boxes(&mut s); + assert_eq!(after.keys().collect::>(), ["Post", "Rail", "Rail (2)", "Right post"], "{after:?}"); + assert_eq!((after["Rail"], after["Rail (2)"]), (before["Rail"], before["Rail (2)"])); + assert_ne!(after["Post"], before["Post"], "the post turned"); + // The rails' group renamed: its members take the new name, the posts keep theirs. + p["groups"][0]["body_name"] = json!("Beam"); + run(&mut s, "timeline.redefine", json!({"feature": fid, "command": "frame.member", "params": p})); + assert_eq!(boxes(&mut s).keys().collect::>(), ["Beam", "Beam (2)", "Post", "Right post"]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(boxes(&mut s).keys().collect::>(), ["Post", "Rail", "Rail (2)", "Right post"]); +} + +/// A flat feature turned into groups keeps its members' names (no group renamed them). +#[test] +fn a_flat_feature_split_into_groups_keeps_its_names() { + let mut s = Session::default(); + rectangle_frame(&mut s); + let (rails, posts) = rails_and_posts(&s); + run(&mut s, "frame.member", json!({"sketch": "Frame", "profile": tube()})); + let fid = s.doc.features.last().unwrap().id; + let before = boxes(&mut s); + let p = json!({"sketch": "Frame", "profile": tube(), "groups": [{"lines": rails}, {"lines": posts, "anchor": "bottom"}]}); + run(&mut s, "timeline.redefine", json!({"feature": fid, "command": "frame.member", "params": p})); + let after = boxes(&mut s); + assert_eq!(after.keys().collect::>(), before.keys().collect::>()); + for line in &rails { + let name = &s.doc.feature(fid).map(|f| f.kind.clone()).and_then(|k| match k { + solidcraft_doc::FeatureKind::FrameMember { names, .. } => names.get(line).cloned(), + _ => None, + }); + let name = name.as_ref().unwrap(); + assert_eq!(after[name], before[name], "the rail {name} stayed put"); + } +} diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index d77d28ef535..6cf20f0e95d 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -854,7 +854,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo Kind::Surface(k) => enter |= crate::dialogs_surface::rows(ui, k), Kind::Sheet(k) => enter |= crate::dialogs_sheet::rows(app, ui, k, &mut d.inputs), Kind::Plastic(k) => enter |= crate::dialogs_plastic::rows(app, ui, k, &d.inputs), - Kind::Frame(k) => enter |= crate::dialogs_frame::rows(app, ui, k, &d.inputs), + Kind::Frame(k) => enter |= crate::dialogs_frame::rows(app, ui, k, &mut d.inputs), Kind::Assembly(k) => enter |= crate::dialogs_assembly::rows(app, ui, k, &mut d.inputs, &mut d.active), Kind::Measure { result, show, .. } => measure_rows(app, ui, result.as_ref(), show), Kind::Section { offset, flip, hatch } => { diff --git a/crates/ui-egui/src/dialogs_frame.rs b/crates/ui-egui/src/dialogs_frame.rs index a45b27d3456..d1247f24f0f 100644 --- a/crates/ui-egui/src/dialogs_frame.rs +++ b/crates/ui-egui/src/dialogs_frame.rs @@ -1,6 +1,8 @@ //! Frame Member (`frame.member`): structural members along the lines of a frame sketch. The lines //! are picked in the view; the section is a built-in profile with its dimensions, or the profiles -//! picked in another sketch. Anchor, angle and mirror place the section on each line. +//! picked in another sketch. Anchor, angle and mirror place the section on each line. The lines +//! may come in groups, each with its own anchor, angle, mirror and name: the Lines input and those +//! rows show the group chosen in the group list. use serde_json::{Map, Value, json}; use solidcraft_engine::Sel; @@ -11,7 +13,7 @@ use solidcraft_engine::doc::{FeatureKind, ProfileSel}; use crate::SolveApp; use crate::dialogs::{Kind, check, curves_sketch, form_row, profile_indices, put, shown_expr}; use crate::selection::{PROFILES, SKETCH_LINES, SelInput, SelectionExt as _}; -use crate::ui_kit::{choice_row, expr_row, hint_row, text_row}; +use crate::ui_kit::{Button, button, choice_row, expr_row, hint_row, text_row}; /// The anchors as `frame.member` names them, and their labels. const ANCHORS: &[(&str, &str)] = &[ @@ -28,10 +30,21 @@ const ANCHORS: &[(&str, &str)] = &[ ("bottom_right", "Bottom Right"), ]; +/// A group of lines and how its members sit on them, while another group is shown. +#[derive(Clone, Debug, Default)] +pub struct Group { + pub lines: Vec, + pub anchor: usize, + pub angle: String, + pub mirror: bool, + pub name: String, +} + /// The Frame Member dialog's values (the picks are its selection inputs). #[derive(Clone, Debug)] pub struct Member { - /// Every line of the frame sketch, now and as lines are added, not only the lines picked. + /// Every line of the frame sketch, now and as lines are added, not only the lines picked + /// (with one group only). pub all: bool, /// The built-in profile (an index into `frame::profile_kinds`), used when no section is picked. pub kind: usize, @@ -41,10 +54,15 @@ pub struct Member { /// A profile sketch whose whole drawn section is the member's (nested loops alternating), as /// a feature made that way keeps it while no section is picked. pub whole: Option, + /// The shown group's anchor, angle, mirror and name (its lines are the Lines input). pub anchor: usize, pub angle: String, pub mirror: bool, pub name: String, + /// Every group; the shown one's entry is brought up to date when another is shown. + pub groups: Vec, + /// The shown group, an index into `groups`. + pub current: usize, } impl Member { @@ -59,7 +77,70 @@ impl Member { .collect(); // A rectangular tube is the most common member. let kind = frame::profile_kinds().iter().position(|k| k.kind == "rect_tube").unwrap_or(0); - Member { all: false, kind, dims, whole: None, anchor: 0, angle: String::new(), mirror: false, name: String::new() } + Member { + all: false, + kind, + dims, + whole: None, + anchor: 0, + angle: String::new(), + mirror: false, + name: String::new(), + groups: vec![Group::default()], + current: 0, + } + } + + /// The shown group as it stands, its lines from the Lines input. + fn shown(&self, inputs: &[SelInput]) -> Group { + let lines = crate::selection::items(inputs, 0).to_vec(); + Group { lines, anchor: self.anchor, angle: self.angle.clone(), mirror: self.mirror, name: self.name.clone() } + } + + /// Every group as it stands, the shown one included (none is while `current` is past the end). + pub fn all_groups(&self, inputs: &[SelInput]) -> Vec { + let mut groups = self.groups.clone(); + if let Some(g) = groups.get_mut(self.current) { + *g = self.shown(inputs); + } + groups + } + + /// Show group `k`: the shown one is kept, `k`'s lines go into the Lines input. + pub fn show(&mut self, k: usize, inputs: &mut [SelInput]) { + let groups = self.all_groups(inputs); + let Some(g) = groups.get(k).cloned() else { return }; + self.groups = groups; + self.current = k; + self.anchor = g.anchor; + self.angle = g.angle; + self.mirror = g.mirror; + self.name = g.name; + if let Some(i) = inputs.first_mut() { + i.items = g.lines; + } + } + + /// A new, empty group after the others, shown. + pub fn add_group(&mut self, inputs: &mut [SelInput]) { + self.groups = self.all_groups(inputs); + self.groups.push(Group::default()); + self.all = false; + self.show(self.groups.len() - 1, inputs); + } + + /// The shown group taken out (never the last one), its neighbour shown. + pub fn remove_group(&mut self, inputs: &mut [SelInput]) { + let mut groups = self.all_groups(inputs); + if groups.len() < 2 || self.current >= groups.len() { + return; + } + groups.remove(self.current); + let k = self.current.min(groups.len() - 1); + self.groups = groups; + // The removed group must not be written back over its neighbour. + self.current = usize::MAX; + self.show(k, inputs); } } @@ -73,10 +154,42 @@ fn tr(text: &str) -> &str { crate::i18n::tr_label(text) } +/// The group list: a button per group (the shown one marked), then New Group and Remove Group. +fn group_rows(ui: &mut egui::Ui, m: &mut Member, inputs: &mut [SelInput]) { + let count = m.groups.len().max(1); + let mut show = None; + let (mut add, mut remove) = (false, false); + form_row(ui, crate::i18n::tr("ui.frame_member.groups"), |ui| { + ui.horizontal_wrapped(|ui| { + for k in 0..count { + let label = crate::i18n::format("ui.frame_member.group", &[("number", &(k + 1).to_string())]); + let style = if k == m.current { Button::SmallSelected } else { Button::Small }; + if button(ui, label, style).clicked() && k != m.current { + show = Some(k); + } + } + add = button(ui, crate::i18n::tr("ui.frame_member.new_group"), Button::Small).clicked(); + if count > 1 { + remove = button(ui, crate::i18n::tr("ui.frame_member.remove_group"), Button::Small).clicked(); + } + }); + }); + if let Some(k) = show { + m.show(k, inputs); + } else if add { + m.add_group(inputs); + } else if remove { + m.remove_group(inputs); + } +} + /// The dialog's own rows (after the selection inputs); true when Enter was pressed in a value. -pub fn rows(app: &SolveApp, ui: &mut egui::Ui, m: &mut Member, inputs: &[SelInput]) -> bool { +pub fn rows(app: &SolveApp, ui: &mut egui::Ui, m: &mut Member, inputs: &mut [SelInput]) -> bool { let mut enter = false; - form_row(ui, "All Lines", |ui| check(ui, &mut m.all)); + group_rows(ui, m, inputs); + if m.groups.len() <= 1 { + form_row(ui, "All Lines", |ui| check(ui, &mut m.all)); + } let picked = !crate::selection::items(inputs, 1).is_empty(); if let Some(sketch) = m.whole.filter(|_| !picked) { let name = app.session.doc.feature(sketch).map(|f| f.name.clone()).unwrap_or_default(); @@ -104,39 +217,73 @@ pub fn rows(app: &SolveApp, ui: &mut egui::Ui, m: &mut Member, inputs: &[SelInpu enter } -/// The command the dialog's OK runs (`extra`: parameters kept from the feature being edited). -pub fn commands(app: &SolveApp, m: &Member, inputs: &[SelInput], extra: &Map) -> Result, String> { - let section = crate::selection::items(inputs, 1).profiles(); - let section_sketch = section.first().map(|x| x.0).or(m.whole); - if section.iter().any(|x| Some(x.0) != section_sketch) { - return Err("the section's profiles must be in one sketch".into()); - } - // A line picked in the view comes with its sketch (line ids are a sketch's own); a line - // selected before the dialog opened is looked for in the newest sketch with it, not the - // section's. - let picks = crate::selection::items(inputs, 0); +/// The ids of the lines picked, `sketch` the frame sketch they are in once one names it (line ids +/// are a sketch's own). +fn picked_lines(picks: &[Sel], sketch: &mut Option) -> Result, String> { let mut lines = Vec::new(); - let mut known = None; for pick in picks { match pick { - Sel::ExternalSketchCurve { sketch, id } | Sel::SketchCurve { id, sketch: Some(sketch) } => { - if known.is_some_and(|k| k != *sketch) { + Sel::ExternalSketchCurve { sketch: s, id } | Sel::SketchCurve { id, sketch: Some(s) } => { + if sketch.is_some_and(|k| k != *s) { return Err("the lines must be in one sketch".into()); } - known = Some(*sketch); + *sketch = Some(*s); lines.push(id.clone()); } Sel::SketchCurve { id, sketch: None } => lines.push(id.clone()), _ => {} } } - if lines.is_empty() { + Ok(lines) +} + +/// A group's anchor, angle, mirror and name in `p`. +fn put_placement(p: &mut Value, g: &Group) { + if g.anchor != 0 + && let Some((anchor, _)) = ANCHORS.get(g.anchor) + { + p["anchor"] = json!(anchor); + } + put(p, &[("angle", &g.angle), ("body_name", g.name.trim())]); + if g.mirror { + p["mirror"] = json!(true); + } +} + +/// The command the dialog's OK runs (`extra`: parameters kept from the feature being edited). +pub fn commands(app: &SolveApp, m: &Member, inputs: &[SelInput], extra: &Map) -> Result, String> { + let section = crate::selection::items(inputs, 1).profiles(); + let section_sketch = section.first().map(|x| x.0).or(m.whole); + if section.iter().any(|x| Some(x.0) != section_sketch) { + return Err("the section's profiles must be in one sketch".into()); + } + // A line picked in the view comes with its sketch; a line selected before the dialog opened + // is looked for in the newest sketch with it, not the section's. + let groups = m.all_groups(inputs); + let mut known = None; + let lines = groups.iter().map(|g| picked_lines(&g.lines, &mut known)).collect::, _>>()?; + if lines.iter().all(Vec::is_empty) { return Err("select the frame sketch's lines first".into()); } - let sketch = known.or_else(|| curves_sketch(app, &lines, section_sketch)).ok_or("the lines must be in one sketch, not the section's")?; + let every: Vec = lines.concat(); + let sketch = known.or_else(|| curves_sketch(app, &every, section_sketch)).ok_or("the lines must be in one sketch, not the section's")?; let mut p = json!({"sketch": sketch}); - if !m.all { - p["lines"] = json!(lines); + if let ([g], [lines]) = (groups.as_slice(), lines.as_slice()) { + if !m.all { + p["lines"] = json!(lines); + } + put_placement(&mut p, g); + } else { + let mut list = Vec::with_capacity(groups.len()); + for (k, (g, lines)) in groups.iter().zip(&lines).enumerate() { + if lines.is_empty() { + return Err(format!("group {} has no lines", k + 1)); + } + let mut group = json!({"lines": lines}); + put_placement(&mut group, g); + list.push(group); + } + p["groups"] = json!(list); } if let Some(ps) = section_sketch { p["profile_sketch"] = json!(ps); @@ -154,15 +301,6 @@ pub fn commands(app: &SolveApp, m: &Member, inputs: &[SelInput], extra: &Map Option<(Kind, Vec, Map)> { - let FeatureKind::FrameMember { path_sketch, lines, profile, anchor, angle, mirror, body_name, .. } = kind else { return None }; + let FeatureKind::FrameMember { path_sketch, lines, profile, .. } = kind else { return None }; let (_, mut inputs) = start(app, "frame.member")?; let st = app.session.model.state(); let mut m = Member::new(); - m.all = lines.is_empty(); - let ids = if m.all { frame::member_line_ids(&st, kind).unwrap_or_default() } else { lines.clone() }; - if let Some(i) = inputs.get_mut(0) { - i.items = ids.into_iter().map(|id| Sel::ExternalSketchCurve { sketch: path_sketch.0, id }).collect(); + m.all = lines.is_empty() && frame::member_groups(kind).len() == 1; + let picks = |ids: Vec| ids.into_iter().map(|id| Sel::ExternalSketchCurve { sketch: path_sketch.0, id }).collect(); + m.groups = frame::member_groups(kind) + .into_iter() + .map(|g| { + let ids = if g.lines.is_empty() { frame::member_line_ids(&st, kind).unwrap_or_default() } else { g.lines }; + let anchor = serde_json::to_value(g.anchor).ok(); + Group { + lines: picks(ids), + anchor: ANCHORS.iter().position(|(a, _)| anchor.as_ref().and_then(Value::as_str) == Some(*a)).unwrap_or(0), + angle: g.angle.as_deref().map(|a| shown_expr(a, ValueKind::Angle)).unwrap_or_default(), + mirror: g.mirror, + name: g.body_name.unwrap_or_default(), + } + }) + .collect(); + if m.groups.is_empty() { + m.groups.push(Group::default()); } + m.current = usize::MAX; + m.show(0, &mut inputs); match profile { MemberProfile::Library { profile } => { let kinds = frame::profile_kinds(); @@ -202,11 +356,6 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec