Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

History: joints as one grouped button, and the History bar folded into groups, both off by default (#8884, #8885) (#8886)

JK3Ded30a5979536
diff --git a/assets/locales/pending/history-group-joints.json b/assets/locales/pending/history-group-joints.json
new file mode 100644
index 0000000000..22b16497d5
--- /dev/null
+++ b/assets/locales/pending/history-group-joints.json
@@ -0,0 +1,34 @@
+{
+ "en": {
+ "prefs.history_group_joints": "Group joints in the History",
+ "prefs.history_group_joints_note": "Two or more joints show as one button with their count, and a click shows each one. Off shows each joint."
+ },
+ "ja": {
+ "prefs.history_group_joints": "履歴でジョイントをまとめる",
+ "prefs.history_group_joints_note": "2つ以上のジョイントを、数を添えた1つのボタンにまとめます。クリックすると各ジョイントを表示します。オフにすると各ジョイントを個別に表示します。"
+ },
+ "zh": {
+ "prefs.history_group_joints": "在历史中将关节分组",
+ "prefs.history_group_joints_note": "两个或更多关节显示为一个带数量的按钮,单击即可显示每个关节。关闭后逐个显示每个关节。"
+ },
+ "de": {
+ "prefs.history_group_joints": "Gelenke im Verlauf gruppieren",
+ "prefs.history_group_joints_note": "Zwei oder mehr Gelenke erscheinen als eine Schaltfläche mit ihrer Anzahl; ein Klick zeigt jedes einzeln. Aus zeigt jedes Gelenk einzeln."
+ },
+ "ko": {
+ "prefs.history_group_joints": "이력에서 조인트 묶기",
+ "prefs.history_group_joints_note": "조인트가 두 개 이상이면 개수가 표시된 버튼 하나로 묶고, 클릭하면 각 조인트를 표시합니다. 끄면 각 조인트를 하나씩 표시합니다."
+ },
+ "ar": {
+ "prefs.history_group_joints": "تجميع المفاصل في السجل",
+ "prefs.history_group_joints_note": "يظهر مفصلان أو أكثر كزر واحد مع عددها، والنقر عليه يُظهر كل مفصل. عند الإيقاف يظهر كل مفصل على حدة."
+ },
+ "he": {
+ "prefs.history_group_joints": "קיבוץ מפרקים בציר הזמן",
+ "prefs.history_group_joints_note": "שני מפרקים או יותר מוצגים ככפתור אחד עם מספרם, ולחיצה מציגה כל אחד מהם. כשהאפשרות כבויה, כל מפרק מוצג בנפרד."
+ },
+ "vi": {
+ "prefs.history_group_joints": "Nhóm các khớp nối trong Lịch sử",
+ "prefs.history_group_joints_note": "Từ hai khớp nối trở lên hiện thành một nút kèm số lượng, nhấp vào để hiện từng khớp nối. Khi tắt, mỗi khớp nối hiện riêng."
+ }
+}
diff --git a/assets/locales/pending/history-groups.json b/assets/locales/pending/history-groups.json
new file mode 100644
index 0000000000..8f81457b60
--- /dev/null
+++ b/assets/locales/pending/history-groups.json
@@ -0,0 +1,93 @@
+{
+ "en": {
+ "ui.history_scope_all": "Show the whole design's features",
+ "ui.history_scope_all_shown": "The whole design's features",
+ "ui.history_scope_pick": "Edit a component, or pick one in the Browser, to show only its features",
+ "ui.history_scope_show": "Show only the features of {name} and the components inside it",
+ "ui.history_scope_shown": "The features of {name} and the components inside it",
+ "Fold Features": "Fold Features",
+ "Group Features": "Group Features",
+ "Select Features": "Select Features",
+ "Show Each Feature": "Show Each Feature",
+ "prefs.history_bar_groups": "Fold the History bar into groups",
+ "prefs.history_bar_groups_note": "In a long history, a run of one component's features folds into one chip, and feature folders start folded. An inserted STEP assembly goes into a Group folder. Off shows each feature, starts folders open and makes no folder."
+ },
+ "de": {
+ "ui.history_scope_all": "Features des ganzen Designs zeigen",
+ "ui.history_scope_all_shown": "Die Features des ganzen Designs",
+ "ui.history_scope_pick": "Eine Komponente bearbeiten oder im Browser wählen, um nur ihre Features zu zeigen",
+ "ui.history_scope_show": "Nur die Features von {name} und der Komponenten darin zeigen",
+ "ui.history_scope_shown": "Die Features von {name} und der Komponenten darin",
+ "prefs.history_bar_groups": "Verlaufsleiste in Gruppen falten",
+ "prefs.history_bar_groups_note": "In einem langen Verlauf wird eine Folge von Features einer Komponente zu einem Chip gefaltet, und Merkmalsordner beginnen gefaltet. Eine eingefügte STEP-Baugruppe kommt in einen Group-Ordner. Aus zeigt jedes Feature, öffnet Ordner und legt keinen Ordner an."
+ },
+ "ja": {
+ "ui.history_scope_all": "設計全体のフィーチャーを表示",
+ "ui.history_scope_all_shown": "設計全体のフィーチャー",
+ "ui.history_scope_pick": "コンポーネントを編集するかブラウザで選ぶと、そのフィーチャーだけを表示します",
+ "ui.history_scope_show": "{name} とその中のコンポーネントのフィーチャーだけを表示",
+ "ui.history_scope_shown": "{name} とその中のコンポーネントのフィーチャー",
+ "Fold Features": "フィーチャーを折りたたむ",
+ "Group Features": "フィーチャーをグループ化",
+ "Select Features": "フィーチャーを選択",
+ "Show Each Feature": "各フィーチャーを表示",
+ "prefs.history_bar_groups": "履歴バーをグループにまとめる",
+ "prefs.history_bar_groups_note": "長い履歴では、1つのコンポーネントの連続したフィーチャーを1つのチップにまとめ、フィーチャーフォルダは閉じた状態で始まります。挿入したSTEPアセンブリはGroupフォルダに入ります。オフにすると、各フィーチャーを表示し、フォルダは開いた状態で始まり、フォルダは作成されません。"
+ },
+ "zh": {
+ "ui.history_scope_all": "显示整个设计的特征",
+ "ui.history_scope_all_shown": "整个设计的特征",
+ "ui.history_scope_pick": "编辑一个零部件,或在浏览器中选中一个,即可只显示它的特征",
+ "ui.history_scope_show": "只显示 {name} 及其内部零部件的特征",
+ "ui.history_scope_shown": "{name} 及其内部零部件的特征",
+ "Fold Features": "折叠特征",
+ "Group Features": "将特征编组",
+ "Select Features": "选择特征",
+ "Show Each Feature": "显示每个特征",
+ "prefs.history_bar_groups": "将历史栏折叠为分组",
+ "prefs.history_bar_groups_note": "在较长的历史中,同一组件的连续特征折叠为一个标签,特征文件夹开始时为折叠状态。插入的 STEP 装配体放入 Group 文件夹。关闭后显示每个特征,文件夹开始时为展开状态,且不创建文件夹。"
+ },
+ "ar": {
+ "ui.history_scope_all": "إظهار ميزات التصميم كله",
+ "ui.history_scope_all_shown": "ميزات التصميم كله",
+ "ui.history_scope_pick": "حرّر مكوّنًا أو اختر واحدًا في المستعرض لإظهار ميزاته فقط",
+ "ui.history_scope_show": "إظهار ميزات {name} والمكوّنات التي بداخله فقط",
+ "ui.history_scope_shown": "ميزات {name} والمكوّنات التي بداخله",
+ "Fold Features": "طي الميزات",
+ "Group Features": "تجميع الميزات",
+ "Select Features": "تحديد الميزات",
+ "Show Each Feature": "إظهار كل ميزة",
+ "prefs.history_bar_groups": "طي شريط السجل في مجموعات",
+ "prefs.history_bar_groups_note": "في سجل طويل، تُطوى سلسلة ميزات المكوّن الواحد في شريحة واحدة، وتبدأ مجلدات الميزات مطوية. تدخل مجموعة STEP المُدرجة في مجلد Group. عند الإيقاف تظهر كل ميزة، وتبدأ المجلدات مفتوحة، ولا يُنشأ أي مجلد."
+ },
+ "he": {
+ "ui.history_scope_all": "הצגת הפיצ'רים של כל התכן",
+ "ui.history_scope_all_shown": "הפיצ'רים של כל התכן",
+ "ui.history_scope_pick": "יש לערוך רכיב, או לבחור אחד בעץ התכן, כדי להציג רק את הפיצ'רים שלו",
+ "ui.history_scope_show": "הצגת הפיצ'רים של {name} ושל הרכיבים שבתוכו בלבד",
+ "ui.history_scope_shown": "הפיצ'רים של {name} ושל הרכיבים שבתוכו",
+ "Fold Features": "קיפול פיצ'רים",
+ "Group Features": "קיבוץ פיצ'רים",
+ "Select Features": "בחירת פיצ'רים",
+ "Show Each Feature": "הצגת כל פיצ'ר",
+ "prefs.history_bar_groups": "קיפול סרגל ציר הזמן לקבוצות",
+ "prefs.history_bar_groups_note": "בציר זמן ארוך, רצף פיצ'רים של רכיב אחד מתקפל לשבב אחד, ותיקיות פיצ'רים מתחילות מקופלות. מכלול STEP שהוכנס נכנס לתיקיית Group. כשהאפשרות כבויה, כל פיצ'ר מוצג, התיקיות מתחילות פתוחות ולא נוצרת תיקייה."
+ },
+ "vi": {
+ "ui.history_scope_all": "Hiện các tính năng của toàn bộ thiết kế",
+ "ui.history_scope_all_shown": "Các tính năng của toàn bộ thiết kế",
+ "ui.history_scope_pick": "Sửa một cụm chi tiết, hoặc chọn một cụm trong Trình duyệt, để chỉ hiện các tính năng của nó",
+ "ui.history_scope_show": "Chỉ hiện các tính năng của {name} và các cụm chi tiết bên trong",
+ "ui.history_scope_shown": "Các tính năng của {name} và các cụm chi tiết bên trong",
+ "Fold Features": "Thu gọn tính năng",
+ "Group Features": "Nhóm tính năng",
+ "Select Features": "Chọn tính năng",
+ "Show Each Feature": "Hiện từng tính năng",
+ "prefs.history_bar_groups": "Thu gọn thanh Lịch sử thành nhóm",
+ "prefs.history_bar_groups_note": "Trong lịch sử dài, một chuỗi tính năng của cùng một thành phần được thu gọn thành một thẻ, và thư mục tính năng bắt đầu ở dạng thu gọn. Cụm lắp ráp STEP được chèn vào sẽ nằm trong thư mục Group. Khi tắt, mỗi tính năng đều hiện, thư mục bắt đầu ở dạng mở và không tạo thư mục nào."
+ },
+ "ko": {
+ "prefs.history_bar_groups": "이력 막대를 그룹으로 접기",
+ "prefs.history_bar_groups_note": "긴 이력에서는 한 컴포넌트의 연속된 특성을 하나의 칩으로 접고, 특성 폴더는 접힌 상태로 시작합니다. 삽입한 STEP 어셈블리는 Group 폴더에 들어갑니다. 끄면 각 특성을 표시하고, 폴더를 펼친 상태로 시작하며, 폴더를 만들지 않습니다."
+ }
+}
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index 7aaa154bc2..99b371c8c4 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -449,22 +449,96 @@ fn group_tree(doc: &solidcraft_doc::Document, roots: &[u64]) -> (std::collection
}
fn sort_group_features(doc: &mut solidcraft_doc::Document) {
- let positions: std::collections::BTreeMap<u64, usize> = doc.features.iter().enumerate().map(|(index, feature)| (feature.id, index)).collect();
- for group in &mut doc.timeline_groups {
+ sort_folder_features(&doc.features, &mut doc.timeline_groups);
+}
+
+fn sort_folder_features(features: &[Feature], folders: &mut [solidcraft_doc::TimelineGroup]) {
+ let positions: std::collections::BTreeMap<u64, usize> = features.iter().enumerate().map(|(index, feature)| (feature.id, index)).collect();
+ for group in folders {
group.features.sort_by_key(|feature| positions.get(feature).copied().unwrap_or(usize::MAX));
}
}
fn require_contiguous_groups(doc: &solidcraft_doc::Document, cmd: &str) -> Result<()> {
let Some(id) = solidcraft_doc::non_contiguous_timeline_group(&doc.features, &doc.timeline_groups) else { return Ok(()) };
- let name = doc.timeline_groups.iter().find(|group| group.id == id).map(|group| group.name.as_str()).unwrap_or("unknown");
- Err(bad(cmd, format!("timeline folder `{name}` must contain one contiguous run of features")))
+ Err(not_contiguous(&doc.timeline_groups, id, cmd))
+}
+
+fn not_contiguous(folders: &[solidcraft_doc::TimelineGroup], id: u64, cmd: &str) -> EngineError {
+ let name = folders.iter().find(|group| group.id == id).map(|group| group.name.as_str()).unwrap_or("unknown");
+ bad(cmd, format!("timeline folder `{name}` must contain one contiguous run of features"))
+}
+
+/// The design's folders once `folder` is added, taking its features and joints out of any other
+/// folder and becoming the parent of the folders `groups` (whose features and joints it then holds
+/// through them), and the first folder that would no longer be one run of features, if any.
+fn folders_with(
+ doc: &solidcraft_doc::Document,
+ mut folder: solidcraft_doc::TimelineGroup,
+ groups: &[u64],
+) -> (Vec<solidcraft_doc::TimelineGroup>, Option<u64>) {
+ let nested = group_feature_ids(doc, groups);
+ folder.features.retain(|feature| !nested.contains(feature));
+ let nested_joints = group_joint_ids(doc, groups);
+ folder.joints.retain(|joint| !nested_joints.contains(joint));
+ let mut next = doc.timeline_groups.clone();
+ for group in &mut next {
+ group.joints.retain(|joint| !folder.joints.contains(joint));
+ group.features.retain(|feature| !folder.features.contains(feature));
+ if groups.contains(&group.id) {
+ group.parent = Some(folder.id);
+ }
+ }
+ next.push(folder);
+ sort_folder_features(&doc.features, &mut next);
+ let broken = solidcraft_doc::non_contiguous_timeline_group(&doc.features, &next);
+ (next, broken)
+}
+
+/// A new folder named `name` holding `features` and `joints`, inside the folder `parent` (`None`:
+/// at the history's root), as `timeline.group` makes it. Returns its id.
+pub(crate) fn new_folder(s: &mut Session, name: &str, features: Vec<u64>, joints: Vec<u64>, parent: Option<u64>, cmd: &str) -> Result<u64> {
+ // Folder names are 1…128 bytes, as `timeline.rename_group` takes them.
+ let mut name = name.trim().to_string();
+ while name.len() > 128 {
+ name.pop();
+ }
+ let name = if name.is_empty() { format!("Folder{}", s.doc.timeline_groups.len() + 1) } else { name };
+ let id = s.doc_mut().allocate_id()?;
+ let (folders, broken) = folders_with(&s.doc, solidcraft_doc::TimelineGroup { id, name, parent, features, joints }, &[]);
+ if let Some(broken) = broken {
+ return Err(not_contiguous(&folders, broken, cmd));
+ }
+ s.doc_mut().timeline_groups = folders;
+ Ok(id)
+}
+
+/// The id a folder that is only being tried out goes by.
+const TRIAL_FOLDER: u64 = u64::MAX;
+
+impl Session {
+ /// Why `timeline.group` would refuse a new folder holding `features` inside the folder
+ /// `parent` (`None` at the history's root), in words for a menu's tooltip; `None` when it
+ /// would make it.
+ pub fn group_refusal(&self, features: &[u64], parent: Option<u64>) -> Option<String> {
+ if features.is_empty() {
+ return Some("No features are selected".into());
+ }
+ let trial = solidcraft_doc::TimelineGroup { id: TRIAL_FOLDER, name: String::new(), parent, features: features.to_vec(), joints: Vec::new() };
+ let (folders, broken) = folders_with(&self.doc, trial, &[]);
+ let broken = broken?;
+ if broken == TRIAL_FOLDER {
+ return Some("The features aren't next to each other in the history".into());
+ }
+ let name = folders.iter().find(|folder| folder.id == broken).map_or("", |folder| folder.name.as_str());
+ Some(format!("Folder {name} would no longer hold one run of features"))
+ }
}
fn group(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "timeline.group";
- let mut features = group_features(s, p, false, cmd)?;
- let mut joints = group_joints(s, p, cmd)?;
+ let features = group_features(s, p, false, cmd)?;
+ let joints = group_joints(s, p, cmd)?;
let groups = group_ids(s, p, false, cmd)?;
let name = match str_(p, "name").map(str::trim).filter(|name| !name.is_empty()) {
Some(name) if name.len() <= 128 => name.to_string(),
@@ -481,22 +555,12 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
{
return Err(bad(cmd, "a new folder cannot contain an ancestor of its parent"));
}
- let nested = group_feature_ids(&s.doc, &groups);
- features.retain(|feature| !nested.contains(feature));
- let nested_joints = group_joint_ids(&s.doc, &groups);
- joints.retain(|joint| !nested_joints.contains(joint));
- let mut next = (*s.doc).clone();
- for group in &mut next.timeline_groups {
- group.joints.retain(|joint| !joints.contains(joint));
- group.features.retain(|feature| !features.contains(feature));
- if groups.contains(&group.id) {
- group.parent = Some(id);
- }
+ let folder = solidcraft_doc::TimelineGroup { id, name: name.clone(), parent, features, joints };
+ let (folders, broken) = folders_with(&s.doc, folder, &groups);
+ if let Some(broken) = broken {
+ return Err(not_contiguous(&folders, broken, cmd));
}
- next.timeline_groups.push(solidcraft_doc::TimelineGroup { id, name: name.clone(), parent, features, joints });
- sort_group_features(&mut next);
- require_contiguous_groups(&next, cmd)?;
- *s.doc_mut() = next;
+ s.doc_mut().timeline_groups = folders;
Ok(json!({"group": id, "name": name, "parent": parent, "groups": groups}))
}
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 6a313dc778..ca79625463 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -31,11 +31,11 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("open")
.key("Ctrl+O")
.noundo()
- .params("path: .sc design (or a .solidcraft design from an earlier release), .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make), or a .ply/.xyz/.pts point cloud (opens as a new design holding it, as pointcloud.insert makes; its `units` and `max_points` as there); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); units?: for an STL or OBJ file (see file.insert_mesh); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh); newer_file: {format, reads_up_to, unknown_changes, not_understood, notice} and warnings when a newer SolidCraft saved it: it opens all the same, and what this version can't read is named there and kept by saving"),
+ .params("path: .sc design (or a .solidcraft design from an earlier release), .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make), or a .ply/.xyz/.pts point cloud (opens as a new design holding it, as pointcloud.insert makes; its `units` and `max_points` as there); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); units?: for an STL or OBJ file (see file.insert_mesh); folder?: bool for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh); newer_file: {format, reads_up_to, unknown_changes, not_understood, notice} and warnings when a newer SolidCraft saved it: it opens all the same, and what this version can't read is named there and kept by saving"),
CommandSpec::new("file.insert_step", "Insert STEP", insert_step)
.at("SOLID", "INSERT")
.icon("import")
- .params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: auto|solid|product|instance (default auto: keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"),
+ .params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?, group?: the folder); folder?: bool (default false; true: an import that brings more than one item into the history (its Import feature and the rigid joints holding its parts) goes into a new history folder named `Group #N`); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: auto|solid|product|instance (default auto: keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"),
CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh)
.at("SOLID", "INSERT")
.icon("import")
@@ -139,6 +139,9 @@ struct StepOptions {
/// (Y becomes Z), as the app's "Stand it up" offer does. `z` (the default) keeps the file's axes.
y_up: bool,
names: solidcraft_io::StepNames,
+ /// `folder: true`: an import that brings more than one item gets a `Group #N` history folder
+ /// (`import_folder`). `false` (the default) makes none, as before the option.
+ folder: bool,
}
fn step_options(p: &Value, cmd: &str) -> Result<StepOptions> {
@@ -157,7 +160,17 @@ fn step_options(p: &Value, cmd: &str) -> Result<StepOptions> {
.and_then(solidcraft_io::StepNames::parse)
.ok_or_else(|| bad(cmd, "`names` must be \"auto\", \"solid\", \"product\" or \"instance\""))?,
};
- Ok(StepOptions { y_up, names })
+ let folder = match p.get("folder") {
+ None | Some(Value::Null) => false,
+ Some(Value::Bool(folder)) => *folder,
+ Some(_) => {
+ return Err(bad(
+ cmd,
+ "`folder` must be true (an import that brings more than one item goes into a `Group #N` history folder) or false (no folder)",
+ ));
+ }
+ };
+ Ok(StepOptions { y_up, names, folder })
}
/// Read a STEP file as an Import feature.
@@ -200,6 +213,7 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio
// assembly's parts and instances turn together.
let turned = if options.y_up { turn_up(s, &placed)? } else { None };
let created = created_bodies(s, id);
+ let folder = if options.folder { import_folder(s, id, &placed)? } else { None };
let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
let mut out = json!({"path": path, "feature": id, "name": fname, "bodies": created, "created_bodies": created, "warnings": sf.warnings, "system": sf.import.system});
if let Some((up, exporter)) = exporter_up(&sf.import) {
@@ -210,6 +224,9 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio
if let Some(turned) = turned {
out["stand_up"] = json!(turned);
}
+ if let Some(folder) = folder {
+ out["group"] = json!(folder);
+ }
if let Some(mark) = profiled {
let report = crate::schema::diagnostics::ProfileReport::new(&mark.report(), 20);
out["profile"] = serde_json::to_value(report).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
@@ -217,6 +234,26 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio
Ok(out)
}
+/// An import that brings more than one item into the history (its Import feature and the rigid
+/// joints holding its parts together) goes into a history folder of its own, named `Group #N`,
+/// holding the feature and those joints, so it stands apart from the features before and after
+/// it and the History shows it as one chip. The folder sits in the folder the feature was put
+/// in, if any. Returns the folder.
+fn import_folder(s: &mut Session, feature: u64, placed: &import::Placed) -> Result<Option<u64>> {
+ if placed.joints.is_empty() {
+ return Ok(None);
+ }
+ let parent = s.doc.timeline_groups.iter().find(|folder| folder.features.contains(&feature)).map(|folder| folder.id);
+ let name = next_group_name(&s.doc);
+ super::edit::new_folder(s, &name, vec![feature], placed.joints.clone(), parent, "file.insert_step").map(Some)
+}
+
+/// The first `Group #N` no history folder is named yet.
+fn next_group_name(doc: &Document) -> String {
+ let taken = |name: &str| doc.timeline_groups.iter().any(|folder| folder.name == name);
+ (1..=doc.timeline_groups.len() + 1).map(|n| format!("Group #{n}")).find(|name| !taken(name)).unwrap_or_else(|| "Group".into())
+}
+
/// The bodies an import feature built, by name.
fn created_bodies(s: &Session, feature: u64) -> Vec<String> {
s.model.state().bodies.iter().filter(|b| b.feature == feature).map(|b| b.name.clone()).collect()
diff --git a/crates/engine/src/tests/import_component.rs b/crates/engine/src/tests/import_component.rs
index d35f6f61c8..257b233c7b 100644
--- a/crates/engine/src/tests/import_component.rs
+++ b/crates/engine/src/tests/import_component.rs
@@ -359,6 +359,108 @@ fn an_inserted_assembly_exports_its_nested_parts_where_they_are() {
let _ = std::fs::remove_dir_all(&dir);
}
+/// A file from the STEP corpus (`tests/step-conformance`).
+fn corpus(name: &str) -> String {
+ format!("{}/../../tests/step-conformance/{name}.step", env!("CARGO_MANIFEST_DIR"))
+}
+
+/// With `folder: true`, a file that brings more than one item into the history (its Import
+/// feature and the rigid joints holding its parts: one cylinder placed twice, an assembly) gets a
+/// history folder of its own, `Group #N` with the first free number, holding its Import feature and those joints,
+/// made by the same command and undone with it; a file with one object gets none. Inserted
+/// between the features of a folder, the import's folder nests in it.
+#[test]
+fn a_multi_object_step_insert_is_one_history_folder() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [100, 0, 0], "name": "Mine"}));
+ let r = run(&mut s, "file.insert_step", json!({"path": corpus("cylinder"), "folder": true}));
+ assert!(r.get("group").is_none() && s.doc.timeline_groups.is_empty(), "one object: no folder: {r}");
+
+ let undo = s.undo.len();
+ let r = run(&mut s, "file.insert_step", json!({"path": corpus("cylinder_twice"), "folder": true}));
+ assert_eq!(s.undo.len(), undo + 1, "one undo step");
+ let feature = r["feature"].as_u64().unwrap();
+ let [folder] = s.doc.timeline_groups.as_slice() else { panic!("one folder: {:?}", s.doc.timeline_groups) };
+ assert_eq!(
+ (json!(folder.id), folder.name.as_str(), folder.features.as_slice(), folder.parent),
+ (r["group"].clone(), "Group #1", &[feature][..], None),
+ "{r}"
+ );
+ let mut rigid: Vec<u64> = s.doc.assembly.joints.iter().map(|j| j.id).collect();
+ rigid.sort_unstable();
+ let mut held = folder.joints.clone();
+ held.sort_unstable();
+ assert!(!rigid.is_empty() && held == rigid, "the folder holds the import's joints: {held:?} of {rigid:?}");
+ run(&mut s, "edit.undo", json!({}));
+ assert!(s.doc.timeline_groups.is_empty() && s.doc.feature(feature).is_none(), "undo takes the folder with the import");
+
+ // An assembly, inserted with the marker inside a folder: its folder nests in that one.
+ let dir = temp_dir("folder");
+ let path = rig_file(&dir);
+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [200, 0, 0], "operation": "new_body", "name": "Later"}));
+ let all: Vec<u64> = s.doc.features.iter().map(|f| f.id).collect();
+ let outer = run(&mut s, "timeline.group", json!({"name": "Everything", "features": all}))["group"].as_u64().unwrap();
+ run(&mut s, "timeline.roll_to", json!({"feature": "Mine"}));
+ let r = run(&mut s, "file.insert_step", json!({"path": path, "folder": true}));
+ let folder = s.doc.timeline_groups.iter().find(|f| json!(f.id) == r["group"]).unwrap();
+ assert_eq!((folder.name.as_str(), folder.parent), ("Group #1", Some(outer)), "{r}");
+ assert_eq!(folder.features, [r["feature"].as_u64().unwrap()]);
+ // The next one takes the next free number.
+ let r = run(&mut s, "file.insert_step", json!({"path": path, "folder": true}));
+ let folder = s.doc.timeline_groups.iter().find(|f| json!(f.id) == r["group"]).unwrap();
+ assert_eq!(folder.name, "Group #2", "{r}");
+ assert!(solidcraft_doc::non_contiguous_timeline_group(&s.doc.features, &s.doc.timeline_groups).is_none());
+ // Opening a file as a design folds it the same way.
+ let r = run(&mut s, "doc.open", json!({"path": corpus("cylinder_twice"), "folder": true}));
+ assert_eq!(s.doc.timeline_groups.len(), 1, "{r}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// Without `folder`, as before the option, and with `folder: false` (the app's "Fold the History
+/// bar into groups" turned off), a multi-object import goes into no folder, inserted or opened as
+/// a design; a value that isn't true or false is refused.
+#[test]
+fn a_step_import_told_no_folder_makes_none() {
+ let mut s = Session::default();
+ let r = run(&mut s, "file.insert_step", json!({"path": corpus("cylinder_twice"), "folder": false}));
+ assert!(r.get("group").is_none() && s.doc.timeline_groups.is_empty(), "no folder: {r}");
+ assert_eq!(s.doc.assembly.joints.len(), 2, "its rigid joints are there all the same");
+ let r = run(&mut s, "doc.open", json!({"path": corpus("cylinder_twice"), "folder": false}));
+ assert!(s.doc.timeline_groups.is_empty(), "opened as a design, no folder either: {r}");
+ let e = s.execute("file.insert_step", &json!({"path": corpus("cylinder_twice"), "folder": "no"})).unwrap_err();
+ assert!(e.to_string().contains("`folder` must be true"), "{e}");
+ // Left out or null, as before the option: no folder either.
+ let r = run(&mut s, "doc.open", json!({"path": corpus("cylinder_twice")}));
+ assert!(s.doc.timeline_groups.is_empty(), "opened without `folder`, no folder: {r}");
+ let r = run(&mut s, "file.insert_step", json!({"path": corpus("cylinder_twice"), "folder": null}));
+ assert!(r.get("group").is_none() && s.doc.timeline_groups.is_empty(), "inserted with `folder: null`, no folder: {r}");
+}
+
+/// Grouping is refused, with a reason a menu can show, when the features aren't one run of the
+/// history or would split another folder; one or several neighbours group.
+#[test]
+fn group_refusal_says_why_a_selection_cannot_be_grouped() {
+ let mut s = Session::default();
+ for (i, name) in ["A", "B", "C", "D"].iter().enumerate() {
+ let corner = [20.0 * i as f64, 0.0, 0.0];
+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": corner, "operation": "new_body", "name": name}));
+ }
+ let id = |s: &Session, n: &str| s.doc.find_feature(n).unwrap().id;
+ let (a, b, c, d) = (id(&s, "A"), id(&s, "B"), id(&s, "C"), id(&s, "D"));
+ assert_eq!(s.group_refusal(&[b], None), None);
+ assert_eq!(s.group_refusal(&[b, c], None), None);
+ let apart = s.group_refusal(&[a, c], None).unwrap();
+ assert!(apart.contains("next to each other"), "{apart}");
+ assert!(s.execute("timeline.group", &json!({"features": [a, c]})).is_err(), "the command refuses it too");
+ run(&mut s, "timeline.group", json!({"name": "Run", "features": [a, b, c]}));
+ let split = s.group_refusal(&[b], None).unwrap();
+ assert!(split.contains("Run"), "taking the middle out splits the folder: {split}");
+ let run_id = s.doc.timeline_groups.first().unwrap().id;
+ assert_eq!(s.group_refusal(&[b], Some(run_id)), None, "inside the folder it nests");
+ assert_eq!(s.group_refusal(&[c, d], None), None, "a folder's last feature leaves it for the new folder");
+ assert!(s.group_refusal(&[], None).is_some());
+}
+
/// The parts of one STEP import share their face names, and each keeps its body where the file
/// has it, placed in its component by an offset. A joint on one part's hole takes that part's
/// hole, not the other part's hole of that name, though the pick (in the part's own coordinates)
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs
index 0cab46dc92..4dd11e8dea 100644
--- a/crates/ui-egui/src/browser.rs
+++ b/crates/ui-egui/src/browser.rs
@@ -205,15 +205,22 @@ pub struct TreeState {
pub picked_timeline_groups: Vec<u64>,
/// Last feature-history item clicked, for Shift ranges (`f:<id>` or `g:<id>`).
pub timeline_anchor: Option<String>,
- /// Find in Timeline: the feature the history scrolls to the next time it draws its items, in
- /// the bottom strip or in the history on the left (#5850).
+ /// Which part of the design the History bar shows (`timeline_scope`).
+ pub(crate) timeline_scope: crate::timeline_scope::Scope,
+ /// The component edited or picked when the History bar last followed it, once it has
+ /// (`timeline_scope`).
+ pub(crate) timeline_followed: Option<Option<u64>>,
+ /// A feature the History bar scrolls into view the next time it draws its items, in the
+ /// bottom strip or in the history on the left: the edited component's last, or the one Find
+ /// in Timeline found (#5850).
pub timeline_reveal: Option<u64>,
- /// Show components marked out of the History bar anyway (#10393). Held by the session, like
- /// the bar's Show All toggle; the History controls' menu carries the switch.
+ /// Show components marked out of the History bar anyway (#10393). Held by the session; the
+ /// History controls' menu carries the switch.
pub history_show_hidden: bool,
- /// The History bar's Show All toggle: every component's features, not only the active or
- /// picked one's (#2880).
- pub history_show_all: bool,
+ /// The runs and folders opened and folded in the active design's History (`history_folds`).
+ pub(crate) history_folds: crate::history_folds::Folds,
+ /// Those of designs with a file, by file, kept between runs (`history_folds`).
+ pub(crate) history_remembered: crate::history_folds::Remembered,
/// The feature of the face or edge last picked in the view, so a new pick scrolls the
/// history to it once.
pub view_pick: Option<u64>,
diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs
index bdce6c3b5a..14ffcc4fb7 100644
--- a/crates/ui-egui/src/context_menu.rs
+++ b/crates/ui-egui/src/context_menu.rs
@@ -11,7 +11,7 @@
//! state; [`items`] lists them and [`run_item`] runs one, so the control channel (`ui.menu`,
//! `ui.menuPick`) and tests reach everything a click does.
-use crate::ui_kit::{Container, Surface};
+use crate::ui_kit::{BackingTooltipExt as _, Container, Surface};
use egui::{Color32, Pos2, Rect, Sense, Vec2, pos2, vec2};
use serde::Serialize;
use serde_json::{Value, json};
@@ -135,6 +135,9 @@ pub struct Item {
pub children: Vec<Item>,
#[serde(skip_serializing_if = "Option::is_none")]
pub swatch: Option<[u8; 3]>,
+ /// Why the entry is off: shown on hover, and in the control channel's report.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tip: Option<String>,
}
impl Item {
@@ -152,6 +155,7 @@ impl Item {
params: None,
children: Vec::new(),
swatch: None,
+ tip: None,
}
}
pub(crate) fn heading(label: &str) -> Item {
@@ -164,6 +168,7 @@ impl Item {
params: None,
children: Vec::new(),
swatch: None,
+ tip: None,
}
}
fn is_sep(&self) -> bool {
@@ -183,6 +188,14 @@ impl Item {
self.enabled &= enabled;
self
}
+ /// Off, saying why, when there is a reason.
+ pub(crate) fn off_because(mut self, why: Option<String>) -> Item {
+ if let Some(why) = why {
+ self.enabled = false;
+ self.tip = Some(why);
+ }
+ self
+ }
pub fn key(mut self, k: &str) -> Item {
self.shortcut = k.into();
self
@@ -206,6 +219,7 @@ pub(crate) fn cmd(app: &SolveApp, id: &str, label: &str) -> Item {
params: None,
children: Vec::new(),
swatch: None,
+ tip: None,
}
}
@@ -220,6 +234,7 @@ pub(crate) fn act(id: &str, label: &str, icon: &str) -> Item {
params: None,
children: Vec::new(),
swatch: None,
+ tip: None,
}
}
@@ -1662,6 +1677,12 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {
crate::edit_clipboard::leave_text(app, text);
}
}
+ "ui.groupFeatures" => {
+ let ids: Vec<u64> = p.get("features").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect();
+ if !ids.is_empty() {
+ crate::timeline_folders::group(app, &ids, p.get("parent").and_then(Value::as_u64), at);
+ }
+ }
"ui.deleteFeatures" | "ui.deleteAfterMarker" => {
let ids: Vec<u64> = p.get("features").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect();
if !ids.is_empty() {
@@ -2777,6 +2798,10 @@ fn level_rows(
kit.id = &handle;
}
let row = kit.show(ui);
+ let row = match &item.tip {
+ Some(tip) => row.backing_on_hover_text(tip.as_str()),
+ None => row,
+ };
if item.children.is_empty() {
if row.clicked() && item.enabled {
*picked = Some(item.clone());
diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs
index f8f6ee05de..97a8495a59 100644
--- a/crates/ui-egui/src/dialogs_assembly.rs
+++ b/crates/ui-egui/src/dialogs_assembly.rs
@@ -5,6 +5,8 @@
//! before the click. Joints and drives preview on the placed (world) model: the moving
//! component shows where it goes, and with Animate the joint plays its motion.
+use std::collections::HashSet;
+
use crate::fonts::RichTextExt as _;
use crate::ui_kit::BackingTooltipExt as _;
use crate::ui_kit::{choice_row, expr_row, text_row};
@@ -1842,19 +1844,136 @@ fn timeline_joint_items(app: &SolveApp, ids: Option<&[u64]>) -> Vec<(u64, String
.collect()
}
-/// Joints after the features in the timeline: double-click edits, the menu drives, suppresses
-/// or deletes. Returns the x after them.
-pub fn timeline_joints(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, x: f32, r: egui::Rect) -> f32 {
- timeline_joint_tiles(app, ui, p, x, r, None)
+/// More joints than this (an imported assembly makes one per placed part) start grouped in the
+/// timeline as one button with their count, from the second joint on; clicking it shows each joint.
+const JOINT_GROUP_MIN: usize = 1;
+/// The browser-state key that remembers the timeline's joints were shown one by one.
+const JOINTS_KEY: &str = "timeline_joints";
+/// The History key that remembers a folder's joints were shown one by one, before its id.
+pub(crate) const FOLDER_JOINTS_KEY: &str = "timeline_joints:";
+
+/// Which joints a row of joint chips in the History bar shows: those no feature folder holds
+/// (after the features), or a folder's (an import's rigid group, see `timeline_folders`).
+#[derive(Clone, Copy)]
+pub(crate) enum JointRun<'a> {
+ Loose,
+ Folder { id: u64, name: &'a str },
+}
+
+impl JointRun<'_> {
+ /// The key that remembers the joints were shown one by one: in the browser's state for the
+ /// joints after the history, in the design's History choices for a folder's.
+ fn key(self) -> String {
+ match self {
+ Self::Loose => JOINTS_KEY.to_string(),
+ Self::Folder { id, .. } => format!("{FOLDER_JOINTS_KEY}{id}"),
+ }
+ }
+
+ /// The scenario handle of their grouped chip.
+ fn handle(self) -> String {
+ match self {
+ Self::Loose => "timeline:joints".to_string(),
+ Self::Folder { name, .. } => format!("timeline-folder-joints:{name}"),
+ }
+ }
+}
+
+/// Whether `count` joints group as one button: from the second joint, once the preference is on
+/// (Preferences > Layout, "Group joints in the History"; off by default, which shows each joint).
+fn grouped(app: &SolveApp, count: usize) -> bool {
+ count > JOINT_GROUP_MIN && app.preferences.history_group_joints
+}
+
+fn joints_open(app: &SolveApp, count: usize, run: JointRun) -> bool {
+ !grouped(app, count)
+ || match run {
+ JointRun::Loose => crate::browser::is_open(app, &run.key(), false),
+ // Folder ids are numbered in each design: its choice stays with the design, as the
+ // folder's own fold does.
+ JointRun::Folder { .. } => crate::history_folds::is_open(app, &run.key(), false),
+ }
+}
+
+fn toggle_joints(app: &mut SolveApp, run: JointRun) {
+ match run {
+ JointRun::Loose => crate::browser::toggle(app, &run.key(), false),
+ JointRun::Folder { .. } => {
+ let open = crate::history_folds::is_open(app, &run.key(), false);
+ crate::history_folds::set_open(app, &run.key(), !open);
+ }
+ }
}
-pub(crate) fn timeline_joint_tiles(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, mut x: f32, r: egui::Rect, ids: Option<&[u64]>) -> f32 {
+/// The button that stands for `count` grouped joints, its top left at `at` (see
+/// `HistoryGroupChip`). Returns its width and whether it was clicked.
+fn joint_group_button(
+ ui: &mut egui::Ui,
+ p: &egui::Painter,
+ at: egui::Pos2,
+ count: usize,
+ open: bool,
+ accent: crate::theme::TabAccent,
+ run: JointRun,
+) -> (f32, bool) {
+ let chip = crate::ui_kit::HistoryGroupChip {
+ icon: "joint",
+ name: "",
+ count,
+ open,
+ selected: false,
+ hovered: false,
+ dim: false,
+ error: false,
+ warning: false,
+ accent,
+ };
+ let br = egui::Rect::from_min_size(at, chip.size(p));
+ let resp = ui.interact(br, ui.scope_id().with(("joint_group", run.key())), egui::Sense::click());
+ let handle = run.handle();
+ crate::scenario::publish_handle(&handle, br.center());
+ crate::scenario::publish_target(&format!("{handle}_arrow"), crate::ui_kit::HistoryGroupChip::well(br));
+ let pointer = resp.hover_pos();
+ let on_arrow = crate::ui_kit::HistoryGroupChip::on_arrow(br, pointer);
+ crate::scenario::publish_count(&format!("{handle}_arrow_hot"), f64::from(u8::from(on_arrow)));
+ chip.paint(p, br, pointer);
+ let tip = if open { "click to group them" } else { "click to show each one" };
+ let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).backing_on_hover_text(format!("{count} joints: {tip}"));
+ (br.width(), resp.clicked())
+}
+
+/// Joints after the features in the timeline, except those a feature folder holds (`held`):
+/// double-click edits, the menu drives, suppresses or deletes. Returns the x after them.
+pub fn timeline_joints(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, x: f32, r: egui::Rect, held: &HashSet<u64>) -> f32 {
+ let loose: Vec<u64> = app.session.doc.assembly.joints.iter().map(|j| j.id).filter(|id| !held.contains(id)).collect();
+ if loose.is_empty() {
+ return x;
+ }
+ joint_chips(app, ui, p, x + 8.0, r, &loose, JointRun::Loose)
+}
+
+/// The joints `ids` as chips from `x` on, grouped into one chip (open to show each) when there
+/// are many. Returns the x after them.
+pub(crate) fn joint_chips(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, mut x: f32, r: egui::Rect, ids: &[u64], set: JointRun) -> f32 {
let t = Tokens::get();
- let joints = timeline_joint_items(app, ids);
+ let wanted: HashSet<u64> = ids.iter().copied().collect();
+ let joints: Vec<(u64, String, JointKind, bool)> =
+ app.session.doc.assembly.joints.iter().filter(|j| wanted.contains(&j.id)).map(|j| (j.id, j.name.clone(), j.kind, j.suppressed)).collect();
if joints.is_empty() {
return x;
}
- x += 8.0;
+ if grouped(app, joints.len()) {
+ let open = joints_open(app, joints.len(), set);
+ let accent = crate::theme::TabAccent::for_tab(&t, &app.ui.tab);
+ let (width, clicked) = joint_group_button(ui, p, egui::pos2(x, r.top() + 6.0), joints.len(), open, accent, set);
+ if clicked {
+ toggle_joints(app, set);
+ }
+ x += width + 4.0;
+ if !open {
+ return x;
+ }
+ }
let mut open: Option<Dialog> = None;
let mut run: Option<(&'static str, Value)> = None;
for (id, name, kind, suppressed) in joints {
@@ -1912,7 +2031,30 @@ pub(crate) fn timeline_joint_rows(app: &mut SolveApp, ui: &mut egui::Ui, ids: Op
}
if ids.is_none() {
ui.add_space(4.0);
- ui.label(egui::RichText::new("JOINTS").size(crate::theme::Tokens::get().font_micro).semibold().color(t.text_dim));
+ if grouped(app, joints.len()) {
+ let shown = joints_open(app, joints.len(), JointRun::Loose);
+ let header = format!("JOINTS ({})", joints.len());
+ let clicked = ui
+ .horizontal(|ui| {
+ let (rect, _) = ui.allocate_exact_size(vec2(t.form_section_icon_size, t.form_section_icon_size), egui::Sense::hover());
+ let fold = crate::ui_kit::disclosure_button_at(ui, rect, shown, &header);
+ let response = ui.add(
+ egui::Label::new(egui::RichText::new(&header).size(crate::theme::Tokens::get().font_micro).semibold().color(t.text_dim))
+ .sense(egui::Sense::click()),
+ );
+ crate::scenario::publish_handle("timeline:joints", response.rect.center());
+ fold.clicked() || response.clicked()
+ })
+ .inner;
+ if clicked {
+ toggle_joints(app, JointRun::Loose);
+ }
+ if !shown {
+ return;
+ }
+ } else {
+ ui.label(egui::RichText::new("JOINTS").size(crate::theme::Tokens::get().font_micro).semibold().color(t.text_dim));
+ }
}
let mut open = None;
let mut run = None;
diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs
index 66dab8453f..064179139e 100644
--- a/crates/ui-egui/src/dialogs_assembly_tests.rs
+++ b/crates/ui-egui/src/dialogs_assembly_tests.rs
@@ -1503,3 +1503,138 @@ fn joint_dialog_applies_custom_name_or_falls_back_to_type_default() {
assert_eq!(r["name"], "MyCustomJoint");
}
}
+
+/// An imported assembly makes a joint per placed part: with "Group joints in the History" on, from
+/// the second joint the timeline shows them as one grouped button with their count, and clicking
+/// it shows (and hides) each one.
+#[test]
+fn many_joints_start_grouped_in_the_timeline() {
+ let mut h = crate::scenario::Harness::new();
+ assert_eq!(h.call("ui.prefs", json!({"history_group_joints": true}))["ok"], true);
+ for (name, x) in [("A", 0), ("B", 30)] {
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.app.run("component.create", json!({ "name": name })).unwrap();
+ h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0]})).unwrap();
+ }
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ let at = |o: &str| json!({"occurrence": o, "point": [30, 10, 5], "z": [1, 0, 0]});
+ h.app.run("joint.create", json!({"type": "rigid", "a": at("A"), "b": at("B"), "name": "Held"})).unwrap();
+ h.frames(2);
+ assert!(crate::scenario::handle_at("timeline:joints").is_none(), "one joint shows on its own");
+ let first = h.app.session.doc.assembly.joints[0].clone();
+ for i in 1..=JOINT_GROUP_MIN as u64 {
+ let mut copy = first.clone();
+ copy.id = first.id + i;
+ copy.name = format!("Held {i}");
+ h.app.session.doc_mut().assembly.joints.push(copy);
+ }
+ h.frames(2);
+ assert_eq!(h.app.session.doc.assembly.joints.len(), 2);
+ assert!(!joints_open(&h.app, JOINT_GROUP_MIN + 1, JointRun::Loose), "a second joint starts them grouped");
+ let group = crate::scenario::handle_at("timeline:joints").expect("the grouped joints button");
+ assert_eq!(h.call("ui.click", json!({"x": group.x, "y": group.y}))["ok"], true);
+ assert!(joints_open(&h.app, JOINT_GROUP_MIN + 1, JointRun::Loose), "clicking the group shows each joint");
+ let group = crate::scenario::handle_at("timeline:joints").expect("the grouped joints button");
+ assert_eq!(h.call("ui.click", json!({"x": group.x, "y": group.y}))["ok"], true);
+ assert!(!joints_open(&h.app, JOINT_GROUP_MIN + 1, JointRun::Loose), "clicking it again groups them");
+}
+
+/// With "Group joints in the History" off, as it is by default, the History shows each joint as it
+/// always has: no grouped button, a tile for every joint, and the left History's JOINTS header
+/// without a count. Turned on, the joints group; turned off again, they show one by one.
+#[test]
+fn joints_show_one_by_one_when_their_grouping_is_off() {
+ let mut h = crate::scenario::Harness::new();
+ for (name, x) in [("A", 0), ("B", 30)] {
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.app.run("component.create", json!({ "name": name })).unwrap();
+ h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0]})).unwrap();
+ }
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ let at = |o: &str| json!({"occurrence": o, "point": [30, 10, 5], "z": [1, 0, 0]});
+ for name in ["Held", "Held again"] {
+ h.app.run("joint.create", json!({"type": "rigid", "a": at("A"), "b": at("B"), "name": name})).unwrap();
+ }
+ h.frames(2);
+ assert!(!h.app.preferences.history_group_joints, "grouping is off by default");
+ assert!(joints_open(&h.app, 2, JointRun::Loose), "each joint shows");
+ assert!(crate::scenario::handle_at("timeline:joints").is_none(), "no grouped button");
+ for name in ["Held", "Held again"] {
+ assert!(crate::scenario::handle_at(&format!("timeline-joint:{name}")).is_some(), "{name} has its own tile");
+ }
+ assert_eq!(h.call("ui.prefs", json!({"history_group_joints": true}))["ok"], true);
+ h.frames(2);
+ assert!(!joints_open(&h.app, 2, JointRun::Loose), "turned on, the two joints group");
+ assert!(crate::scenario::handle_at("timeline:joints").is_some(), "the grouped button appears");
+ assert!(crate::scenario::handle_at("timeline-joint:Held").is_none());
+ assert_eq!(h.call("ui.prefs", json!({"history_group_joints": false}))["ok"], true);
+ h.frames(2);
+ assert!(joints_open(&h.app, 2, JointRun::Loose), "turned off again, each joint shows");
+ assert!(crate::scenario::handle_at("timeline:joints").is_none(), "and the grouped button goes");
+ assert!(crate::scenario::handle_at("timeline-joint:Held").is_some());
+}
+
+/// The joints after the History bar's features belong to the whole design. Without the bar's
+/// groups, as by default, they stay while the bar shows only the edited component, as they always
+/// have; with the groups, a bar that shows one component leaves them out.
+#[test]
+fn joints_stay_in_the_history_bar_showing_one_component_without_its_groups() {
+ let mut h = crate::scenario::Harness::new();
+ for (name, x) in [("A", 0), ("B", 30)] {
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.app.run("component.create", json!({ "name": name })).unwrap();
+ h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0]})).unwrap();
+ }
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ let at = |o: &str| json!({"occurrence": o, "point": [30, 10, 5], "z": [1, 0, 0]});
+ h.app.run("joint.create", json!({"type": "rigid", "a": at("A"), "b": at("B"), "name": "Held"})).unwrap();
+ h.app.run("component.activate", json!({"component": "A"})).unwrap();
+ h.frames(2);
+ assert!(!h.app.preferences.history_bar_groups, "the bar's groups are off by default");
+ assert!(crate::timeline_scope::shown(&h.app).is_some(), "the bar shows the edited component");
+ assert!(crate::scenario::handle_at("timeline-joint:Held").is_some(), "the design's joint still shows");
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ h.frames(2);
+ assert!(crate::scenario::handle_at("timeline-joint:Held").is_none(), "with the groups, one component's bar leaves it out");
+}
+
+/// The grouped joints' arrow has a well of its own at the button's end: it lights up only under
+/// the pointer, and clicking it shows and hides the joints like the rest of the button.
+#[test]
+fn the_grouped_joints_arrow_lights_up_under_the_pointer() {
+ let mut h = crate::scenario::Harness::new();
+ assert_eq!(h.call("ui.prefs", json!({"history_group_joints": true}))["ok"], true);
+ for (name, x) in [("A", 0), ("B", 30)] {
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.app.run("component.create", json!({ "name": name })).unwrap();
+ h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0]})).unwrap();
+ }
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ let at = |o: &str| json!({"occurrence": o, "point": [30, 10, 5], "z": [1, 0, 0]});
+ h.app.run("joint.create", json!({"type": "rigid", "a": at("A"), "b": at("B"), "name": "Held"})).unwrap();
+ let first = h.app.session.doc.assembly.joints[0].clone();
+ // Thousands of joints, as an imported assembly makes: the count is four digits wide.
+ for i in 1..=1200u64 {
+ let mut copy = first.clone();
+ copy.id = first.id + i;
+ copy.name = format!("Held {i}");
+ h.app.session.doc_mut().assembly.joints.push(copy);
+ }
+ h.frames(2);
+ let arrow = crate::scenario::rect_of("timeline:joints_arrow").expect("the arrow's well");
+ let group = crate::scenario::handle_at("timeline:joints").expect("the grouped joints button");
+ assert!(arrow.left() > group.x, "the arrow sits at the button's right end");
+ let hot = |h: &mut crate::scenario::Harness, x: f32, y: f32| {
+ h.call("ui.move", json!({"x": x, "y": y}));
+ h.frames(1);
+ crate::scenario::count_of("timeline:joints_arrow_hot")
+ };
+ assert_eq!(hot(&mut h, arrow.center().x, arrow.center().y), Some(1.0), "the well lights up under the pointer");
+ let icon_x = arrow.left() - 2.0 * (arrow.left() - group.x) + 6.0;
+ assert_eq!(hot(&mut h, icon_x, arrow.center().y), Some(0.0), "not over the icon or the count");
+ assert_eq!(h.call("ui.click", json!({"x": arrow.center().x, "y": arrow.center().y}))["ok"], true);
+ assert!(joints_open(&h.app, 1201, JointRun::Loose), "clicking the arrow shows each joint");
+ let arrow = crate::scenario::rect_of("timeline:joints_arrow").expect("the arrow's well");
+ assert_eq!(h.call("ui.click", json!({"x": arrow.center().x, "y": arrow.center().y}))["ok"], true);
+ assert!(!joints_open(&h.app, 1201, JointRun::Loose), "and groups them again");
+}
diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs
index cbc67d7746..47407a784a 100644
--- a/crates/ui-egui/src/documents.rs
+++ b/crates/ui-egui/src/documents.rs
@@ -121,6 +121,11 @@ fn put_work(app: &mut SolveApp, mut work: DocWork, before: u64) {
#[derive(Clone, Debug, Default)]
struct DocView {
render: crate::render_workspace::ViewState,
+ /// The runs and folders opened and folded in its History, and which part of the design it
+ /// shows.
+ history_folds: crate::history_folds::Folds,
+ timeline_scope: crate::timeline_scope::Scope,
+ timeline_followed: Option<Option<u64>>,
/// Bodies, components and features copied or cut in this design: their names and paths mean nothing
/// in another one (copied features stay with the session the same way). Another design
/// pastes them from `SolveApp::foreign_copy`.
@@ -223,6 +228,9 @@ pub fn follow_file_rename(app: &mut SolveApp, old_path: &str, new_path: &str) {
fn take_view(app: &mut SolveApp) -> DocView {
DocView {
render: std::mem::take(&mut app.render_workspace.view),
+ history_folds: std::mem::take(&mut app.tree.history_folds),
+ timeline_scope: std::mem::take(&mut app.tree.timeline_scope),
+ timeline_followed: app.tree.timeline_followed.take(),
copied_bodies: std::mem::take(&mut app.copied_bodies),
copied_placements: std::mem::take(&mut app.copied_placements),
cut: std::mem::take(&mut app.cut),
@@ -235,6 +243,9 @@ fn put_view(app: &mut SolveApp, v: DocView) {
crate::render_workspace::invalidate_images(app);
crate::render_workspace::invalidate_scene(app);
crate::render_workspace::sync_backend(app);
+ app.tree.history_folds = v.history_folds;
+ app.tree.timeline_scope = v.timeline_scope;
+ app.tree.timeline_followed = v.timeline_followed;
app.copied_bodies = v.copied_bodies;
app.copied_placements = v.copied_placements;
app.cut = v.cut;
@@ -481,6 +492,7 @@ pub fn open_tab(app: &mut SolveApp, session: Session) -> Result<(), String> {
let at = app.docs.active + 1;
app.docs.slots.insert(at, Some(DocSlot::new(session)));
crate::agent_chat::follow_new_tab(app, |app| switch(app, at));
+ crate::history_folds::load(app);
app.fit_view();
Ok(())
}
@@ -506,6 +518,8 @@ pub fn adopt(app: &mut SolveApp, session: Session) -> bool {
reset_chat(app);
// The blank design's record of its links goes with it; the new one's start now.
app.docs.link_stamps.clear();
+ crate::history_folds::load(app);
+ crate::timeline_scope::reset(app);
crate::render_workspace::reset_document(app);
app.session.invalidate_view(rev);
app.cam = Camera::default();
diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs
index a8402ad79e..041e0dd007 100644
--- a/crates/ui-egui/src/file_load.rs
+++ b/crates/ui-egui/src/file_load.rs
@@ -277,8 +277,17 @@ pub fn begin(app: &mut SolveApp, path: &str, insert: bool) {
let _ = begin_request(app, Request::new(path, if insert { Kind::Insert } else { Kind::Open }));
}
+/// A STEP, IGES, FreeCAD or Rhino file the app opens or inserts gets a `Group #N` history folder
+/// while "Fold the History bar into groups" is on, and none while it is off (#8885), unless the
+/// caller chose (`folder`).
+pub(crate) fn step_folder_option(app: &SolveApp, path: &str, options: &mut serde_json::Map<String, Value>) {
+ if solidcraft_engine::io::is_step_path(path) {
+ options.entry("folder").or_insert(Value::Bool(app.preferences.history_bar_groups));
+ }
+}
+
/// Queue a file operation; on the web (no threads) it runs now.
-pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String> {
+pub fn begin_request(app: &mut SolveApp, mut request: Request) -> Result<(), String> {
if crate::control::chat_turn_cancelled(request.chat_turn.as_deref()) {
request.answer(Err("the agent chat turn ended".into()));
return Ok(());
@@ -286,6 +295,9 @@ pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String>
if app.file_load.idle() && reuse_open(app, &request) {
return Ok(());
}
+ if matches!(request.kind, Kind::Open | Kind::Insert) {
+ step_folder_option(app, &request.path, &mut request.options);
+ }
#[cfg(target_arch = "wasm32")]
{
if staged_kind(&request) {
@@ -2009,4 +2021,26 @@ mod tests {
}
assert!(read && after_read, "the import's progress showed while its file was read, then the open went on");
}
+
+ /// The app asks a STEP-family open or insert for a `Group #N` history folder only while "Fold
+ /// the History bar into groups" is on (#8885); a caller's own `folder` stays, and other files
+ /// are left alone.
+ #[test]
+ fn a_step_open_asks_for_a_history_folder_as_the_bar_groups() {
+ let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
+ let asked = |app: &SolveApp, path: &str, folder: Option<bool>| {
+ let mut options = serde_json::Map::new();
+ if let Some(folder) = folder {
+ options.insert("folder".into(), Value::Bool(folder));
+ }
+ step_folder_option(app, path, &mut options);
+ options.get("folder").cloned()
+ };
+ assert!(!app.preferences.history_bar_groups, "off by default");
+ assert_eq!(asked(&app, "a.step", None), Some(Value::Bool(false)), "no folder while the bar's groups are off");
+ app.preferences.history_bar_groups = true;
+ assert_eq!(asked(&app, "a.stp", None), Some(Value::Bool(true)), "a folder while they are on");
+ assert_eq!(asked(&app, "a.step", Some(false)), Some(Value::Bool(false)), "the caller's choice stays");
+ assert_eq!(asked(&app, "a.stl", None), None, "a mesh has no folders");
+ }
}
diff --git a/crates/ui-egui/src/history_folds.rs b/crates/ui-egui/src/history_folds.rs
new file mode 100644
index 0000000000..674302ace9
--- /dev/null
+++ b/crates/ui-egui/src/history_folds.rs
@@ -0,0 +1,295 @@
+//! The runs and folders opened and folded in the History (the bar and the History beside the
+//! browser) belong to the design they were chosen in, not to every design. A design keeps its
+//! choices in its tab while it is open and, once it has a file, between runs too: they are
+//! remembered by file in the preferences for the [`DESIGNS_MAX`] designs used most recently. A
+//! design opened, or made afresh, starts from the choices remembered for its file, or none.
+//!
+//! The choices are remembered as they are made, so a design replaced in its tab (opening another
+//! file there) has already left its own behind. A save gives the design's choices to the file it
+//! was saved as, so a new design or a copy saved under another name keeps what it showed.
+
+use std::collections::BTreeSet;
+
+use serde_json::{Value, json};
+
+use crate::SolveApp;
+
+/// Designs whose choices are remembered between runs; the least recently used is forgotten first.
+const DESIGNS_MAX: usize = 256;
+/// Choices of one design read from the preferences.
+const CHOICES_MAX: usize = 10_000;
+/// Keys the History once saved for all designs at once, with the browser's folders. Folders
+/// folded then stay folded in each design that makes no choice of its own for them
+/// ([`legacy_folded`]).
+const SHARED_ONCE: [&str; 3] = [crate::timeline_fold::KEY, crate::timeline_folders::KEY, crate::dialogs_assembly::FOLDER_JOINTS_KEY];
+
+/// One design's choices: the History keys of the runs and folders opened and folded.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Folds {
+ open: BTreeSet<String>,
+ folded: BTreeSet<String>,
+}
+
+impl Folds {
+ /// The choice made for `key`: opened (true), folded (false), or none.
+ fn get(&self, key: &str) -> Option<bool> {
+ if self.open.contains(key) {
+ Some(true)
+ } else if self.folded.contains(key) {
+ Some(false)
+ } else {
+ None
+ }
+ }
+
+ fn set(&mut self, key: &str, open: bool) {
+ self.open.remove(key);
+ self.folded.remove(key);
+ if open {
+ self.open.insert(key.to_string());
+ } else {
+ self.folded.insert(key.to_string());
+ }
+ }
+
+ fn is_empty(&self) -> bool {
+ self.open.is_empty() && self.folded.is_empty()
+ }
+
+ fn read(v: &Value) -> Self {
+ let keys = |k: &str| -> BTreeSet<String> {
+ v.get(k)
+ .and_then(Value::as_array)
+ .map(|a| a.iter().take(CHOICES_MAX).filter_map(|x| x.as_str().map(str::to_string)).collect())
+ .unwrap_or_default()
+ };
+ Folds { open: keys("open"), folded: keys("folded") }
+ }
+}
+
+/// The choices of designs with a file, by file, the most recently used last.
+#[derive(Debug, Default)]
+pub(crate) struct Remembered(Vec<(String, Folds)>);
+
+impl Remembered {
+ fn get(&self, path: &str) -> Option<&Folds> {
+ self.0.iter().find(|(p, _)| p == path).map(|(_, folds)| folds)
+ }
+
+ /// Remember `folds` for `path` as the most recently used (forget it when no choice is made).
+ fn put(&mut self, path: &str, folds: &Folds) {
+ self.0.retain(|(p, _)| p != path);
+ if !folds.is_empty() {
+ self.0.push((path.to_string(), folds.clone()));
+ }
+ let over = self.0.len().saturating_sub(DESIGNS_MAX);
+ self.0.drain(..over);
+ }
+}
+
+/// Whether `key` shows open in the active design: as last chosen there, else `unless_chosen`.
+pub(crate) fn is_open(app: &SolveApp, key: &str, unless_chosen: bool) -> bool {
+ app.tree.history_folds.get(key).or_else(|| legacy_folded(app, key).then_some(false)).unwrap_or(unless_chosen)
+}
+
+/// Whether `key` is a folder folded while the History kept its folders' folds for all designs at
+/// once, with the browser's folded folders (which keep it for every design, as then).
+fn legacy_folded(app: &SolveApp, key: &str) -> bool {
+ key.starts_with(crate::timeline_folders::KEY) && app.tree.collapsed.contains(key)
+}
+
+/// Open or fold `key` in the active design, remembered for its file when it has one.
+pub(crate) fn set_open(app: &mut SolveApp, key: &str, open: bool) {
+ app.tree.history_folds.set(key, open);
+ remember(app);
+}
+
+/// Remember the active design's choices for its file: as they change, and after a save gave it
+/// a file (or another one).
+pub(crate) fn remember(app: &mut SolveApp) {
+ if let Some(path) = app.session.path.as_deref() {
+ app.tree.history_remembered.put(path, &app.tree.history_folds);
+ }
+}
+
+/// Take up the choices remembered for the design just put in the active tab: its file's, or none.
+pub(crate) fn load(app: &mut SolveApp) {
+ app.tree.history_folds = app.session.path.as_deref().and_then(|p| app.tree.history_remembered.get(p)).cloned().unwrap_or_default();
+ remember(app);
+}
+
+/// The remembered choices, for the preferences.
+pub(crate) fn prefs(app: &SolveApp) -> Value {
+ app.tree.history_remembered.0.iter().map(|(path, folds)| json!({"path": path, "open": folds.open, "folded": folds.folded})).collect()
+}
+
+/// Restore the choices saved with [`prefs`] (`v`: the preferences), and drop the History's keys
+/// from the browser's folders, where they were once saved for all designs; folders folded then
+/// stay ([`legacy_folded`]).
+pub(crate) fn load_prefs(app: &mut SolveApp, v: &Value) {
+ let entries = v.get("history_folds").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
+ let mut remembered = Remembered::default();
+ for entry in entries.iter().skip(entries.len().saturating_sub(DESIGNS_MAX)) {
+ if let Some(path) = entry.get("path").and_then(Value::as_str) {
+ remembered.put(path, &Folds::read(entry));
+ }
+ }
+ app.tree.history_remembered = remembered;
+ let shared = |key: &String| SHARED_ONCE.iter().any(|k| key.starts_with(k));
+ app.tree.expanded.retain(|key| !shared(key));
+ app.tree.collapsed.retain(|key| !shared(key) || key.starts_with(crate::timeline_folders::KEY));
+ load(app);
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::{DESIGNS_MAX, Folds, Remembered};
+ use crate::SolveApp;
+
+ fn new_app() -> SolveApp {
+ SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default())
+ }
+
+ /// An empty folder of its own for one test's designs.
+ fn folder(test: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("solidcraft-history-folds-{test}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).expect("a folder");
+ dir
+ }
+
+ fn design(app: &mut SolveApp, dir: &std::path::Path, name: &str) -> String {
+ let path = dir.join(name).to_string_lossy().into_owned();
+ app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).expect("a box");
+ app.run("file.save_as", json!({"path": path})).expect("saved");
+ path
+ }
+
+ fn open(app: &mut SolveApp, path: &str) {
+ crate::documents::prepare_open(app);
+ app.run("doc.open", json!({"path": path})).expect("opened");
+ }
+
+ /// A choice made in one design stays with it: another design, open in its own tab or opened
+ /// later in the same tab, starts without it; going back to the first design shows it again.
+ #[test]
+ fn a_choice_stays_with_the_design_it_was_made_in() {
+ let dir = folder("stays");
+ let mut app = new_app();
+ let first = design(&mut app, &dir, "first.solidcraft");
+ super::set_open(&mut app, "timeline_group:7", true);
+ assert!(super::is_open(&app, "timeline_group:7", false));
+
+ crate::documents::new_design(&mut app);
+ assert!(!super::is_open(&app, "timeline_group:7", false), "a new design in its own tab");
+ let second = design(&mut app, &dir, "second.solidcraft");
+ super::set_open(&mut app, "timeline_group:7", false);
+ assert!(!super::is_open(&app, "timeline_group:7", true));
+
+ crate::documents::switch(&mut app, 0);
+ assert!(super::is_open(&app, "timeline_group:7", false), "back in the first design's tab");
+ app.run("doc.open", json!({"path": second})).expect("the second design, in this tab");
+ assert!(!super::is_open(&app, "timeline_group:7", true), "the second design's own choice");
+ app.run("doc.open", json!({"path": first})).expect("the first design again");
+ assert!(super::is_open(&app, "timeline_group:7", false), "remembered while it was replaced");
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// The choices of designs with a file outlast the run (in the preferences); the History's keys
+ /// once saved for all designs with the browser's folders no longer apply to any design.
+ #[test]
+ fn choices_are_remembered_by_file_between_runs() {
+ let dir = folder("between-runs");
+ let mut app = new_app();
+ let first = design(&mut app, &dir, "first.solidcraft");
+ super::set_open(&mut app, "timeline_component:3:9", true);
+ crate::documents::new_design(&mut app);
+ let second = design(&mut app, &dir, "second.solidcraft");
+ let mut prefs: serde_json::Value = serde_json::from_str(&app.prefs()).expect("preferences");
+ prefs["browser_expanded"] = json!(["c0/bodies", "timeline_group:8", "timeline_component:1:2", "timeline_joints:8"]);
+
+ let mut next = new_app();
+ next.load_prefs(&prefs.to_string());
+ assert_eq!(next.tree.expanded.iter().collect::<Vec<_>>(), ["c0/bodies"], "the browser's own folders stay");
+ assert!(!super::is_open(&next, "timeline_group:8", false));
+ assert!(!super::is_open(&next, "timeline_joints:8", false), "a folder's joints too");
+ open(&mut next, &second);
+ assert!(!super::is_open(&next, "timeline_component:3:9", false), "not chosen in the second design");
+ open(&mut next, &first);
+ assert!(super::is_open(&next, "timeline_component:3:9", false), "chosen in the first design");
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// A folder folded while the History kept its folders' folds for all designs at once stays
+ /// folded in each design that makes no choice of its own for it; opened in one design, it is
+ /// open there only.
+ #[test]
+ fn a_folder_folded_for_all_designs_before_stays_folded_until_chosen() {
+ let dir = folder("legacy-folded");
+ let mut app = new_app();
+ let first = design(&mut app, &dir, "first.solidcraft");
+ crate::documents::new_design(&mut app);
+ let second = design(&mut app, &dir, "second.solidcraft");
+ let mut prefs: serde_json::Value = serde_json::from_str(&app.prefs()).expect("preferences");
+ prefs["browser_collapsed"] = json!(["c0/bodies", "timeline_group:8", "timeline_component:1:2", "timeline_joints:8"]);
+
+ let mut next = new_app();
+ next.load_prefs(&prefs.to_string());
+ assert_eq!(next.tree.collapsed.iter().collect::<Vec<_>>(), ["c0/bodies", "timeline_group:8"], "the browser's and the folder's");
+ assert!(!crate::timeline_folders::is_open(&next, 8, true), "folded as before");
+ assert!(crate::timeline_folders::is_open(&next, 9, true), "another folder shows open");
+ assert!(super::is_open(&next, "timeline_joints:8", true), "a folder's joints no longer fold for all designs");
+ open(&mut next, &first);
+ assert!(!crate::timeline_folders::is_open(&next, 8, true), "in a design opened afterwards too");
+ crate::timeline_folders::set_open(&mut next, 8, true);
+ assert!(crate::timeline_folders::is_open(&next, 8, false), "opened in the first design");
+ open(&mut next, &second);
+ assert!(!crate::timeline_folders::is_open(&next, 8, true), "still folded in the second");
+ open(&mut next, &first);
+ assert!(crate::timeline_folders::is_open(&next, 8, false), "and open in the first again");
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// Saving gives the choices to the file saved as: a new design keeps what it showed once it
+ /// has a file, and so does a copy saved under another name, while the original keeps its own.
+ #[test]
+ fn a_save_keeps_the_choices_under_the_new_file() {
+ let dir = folder("save");
+ let mut app = new_app();
+ app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).expect("a box");
+ super::set_open(&mut app, "timeline_group:4", true);
+ let first = dir.join("first.solidcraft").to_string_lossy().into_owned();
+ crate::save_job::start(&mut app, "file.save_as", json!({"path": first}));
+ crate::save_job::tick(&mut app, true);
+ assert_eq!(app.session.path.as_deref(), Some(first.as_str()));
+ super::set_open(&mut app, "timeline_group:5", true);
+ let copy = dir.join("copy.solidcraft").to_string_lossy().into_owned();
+ app.run("file.save_as", json!({"path": copy})).expect("saved as a copy");
+ super::set_open(&mut app, "timeline_group:6", true);
+
+ let remembered = &app.tree.history_remembered;
+ let open = |path: &str, key: &str| remembered.get(path).and_then(|f| f.get(key)) == Some(true);
+ assert!(open(&first, "timeline_group:4") && open(&first, "timeline_group:5"));
+ assert!(!open(&first, "timeline_group:6"), "chosen after the copy was saved");
+ assert!(open(&copy, "timeline_group:4") && open(&copy, "timeline_group:6"));
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// Only the designs used most recently are remembered, and a design whose choices are all
+ /// gone is forgotten.
+ #[test]
+ fn the_least_recently_used_designs_are_forgotten() {
+ let mut remembered = Remembered::default();
+ let mut folds = Folds::default();
+ folds.set("timeline_group:1", true);
+ for i in 0..=DESIGNS_MAX {
+ remembered.put(&format!("{i}.solidcraft"), &folds);
+ }
+ assert_eq!(remembered.0.len(), DESIGNS_MAX);
+ assert!(remembered.get("0.solidcraft").is_none(), "the least recently used");
+ remembered.put("1.solidcraft", &Folds::default());
+ assert!(remembered.get("1.solidcraft").is_none(), "no choice left");
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 4f79de89c7..e50de1b8b5 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -72,6 +72,7 @@ pub mod frame_rate;
pub mod gizmo;
pub mod gpu;
pub mod help;
+mod history_folds;
pub(crate) mod history_rows;
#[cfg(test)]
mod hole_direction_ui_tests;
@@ -302,7 +303,10 @@ mod theme_options;
#[cfg(test)]
mod thin_extrude_tests;
pub mod timeline;
+mod timeline_fold;
+mod timeline_folders;
pub mod timeline_left;
+mod timeline_scope;
pub mod titlebar;
pub mod tool_cursor;
pub mod tool_modifiers;
@@ -1088,6 +1092,7 @@ impl SolveApp {
"visual_style": self.ui.visual_style,
"browser_collapsed": self.tree.collapsed,
"browser_expanded": self.tree.expanded,
+ "history_folds": history_folds::prefs(self),
"recent": self.home.recent,
"recent_opened_at": self.home.opened_at,
"recent_forgotten": self.home.forgotten,
@@ -1164,6 +1169,7 @@ impl SolveApp {
};
self.tree.collapsed = keys("browser_collapsed");
self.tree.expanded = keys("browser_expanded");
+ history_folds::load_prefs(self, &v);
self.home.recent = v
.get("recent")
.and_then(Value::as_array)
@@ -1574,6 +1580,11 @@ impl SolveApp {
self.preview.reset();
self.cam = Camera::default();
self.fit_view();
+ history_folds::load(self);
+ timeline_scope::reset(self);
+ }
+ if matches!(id, "file.save" | "file.save_as") {
+ history_folds::remember(self);
}
if matches!(id, "doc.open" | "file.save" | "file.save_as")
&& let Some(p) = self.session.path.clone()
@@ -2650,9 +2661,8 @@ impl SolveApp {
}
self.home.open = false;
documents::prepare_open(self);
- let mut params = options.clone();
- params.insert("path".into(), json!(path));
- if let Ok(r) = self.run("doc.open", Value::Object(params)) {
+ let params = self.load_params(path, options);
+ if let Ok(r) = self.run("doc.open", params) {
// An opened design comes up at the home view, not at the angle the design before it
// was left at: `prepare_open` keeps the camera when it reuses a blank design.
self.cam.set_view(StandardView::Iso);
@@ -2681,6 +2691,15 @@ impl SolveApp {
file_load::begin(self, path, true);
}
+ /// The parameters of opening or inserting `path` here: the path, and for a STEP file whether
+ /// it gets a history folder (`file_load::step_folder_option`).
+ fn load_params(&self, path: &str, options: &serde_json::Map<String, Value>) -> Value {
+ let mut params = options.clone();
+ params.insert("path".into(), json!(path));
+ file_load::step_folder_option(self, path, &mut params);
+ Value::Object(params)
+ }
+
/// Insert CAD bodies, meshes or sketch drawing geometry into the current design.
pub fn insert_path(&mut self, path: &str) {
self.insert_path_with(path, &Default::default(), false);
@@ -2697,9 +2716,8 @@ impl SolveApp {
file_load::insert_command(path)
};
let before: Vec<String> = crate::open_meshing::session_world(&self.session).bodies.iter().map(|b| b.name.clone()).collect();
- let mut params = options.clone();
- params.insert("path".into(), json!(path));
- if let Ok(r) = self.run(cmd, Value::Object(params)) {
+ let params = self.load_params(path, options);
+ if let Ok(r) = self.run(cmd, params) {
self.fit_view();
stand_up::offer(self, path, &before, Some(&r));
if let Some(summary) = timeline::import_status(self, &r) {
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 4e8b0f8c2b..23a4798aaa 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -1374,6 +1374,14 @@ preference_settings! {
/// A Play History button in the History controls, between Previous and Next (#3688). Off
/// gives the four controls History had before; right-clicking the controls toggles it too.
history_play_button: bool = true, PAGE_LAYOUT;
+ /// On, two or more joints show as one button with their count in the History, and a click
+ /// shows each one (#8884). Off, the default, shows each joint as the History always has.
+ history_group_joints: bool = false, PAGE_LAYOUT;
+ /// On, the History bar folds long runs of one component's features into chips and starts
+ /// feature folders folded, and a STEP insert that brings more than one item goes into a
+ /// `Group #N` folder (#8885). Off, the default, shows each feature, starts folders open and
+ /// makes no folder, as the bar always has.
+ history_bar_groups: bool = false, PAGE_LAYOUT;
/// The vertical history (left, or under the browser) starts with the active component's Bodies
/// folder and the Origin, as the browser shows them (#6490). The bottom strip is unchanged.
timeline_origin_bodies: bool = false, PAGE_LAYOUT;
@@ -6268,6 +6276,8 @@ mod tests {
("timeline_under_browser", json!(true), PAGE_LAYOUT),
("history_sketches", json!("under_feature"), PAGE_LAYOUT),
("history_play_button", json!(false), PAGE_LAYOUT),
+ ("history_group_joints", json!(true), PAGE_LAYOUT),
+ ("history_bar_groups", json!(true), PAGE_LAYOUT),
("browser_float", json!(true), PAGE_LAYOUT),
("browser_collapsed", json!(true), PAGE_LAYOUT),
("browser_show", json!("hover"), PAGE_LAYOUT),
diff --git a/crates/ui-egui/src/prefs/interface.rs b/crates/ui-egui/src/prefs/interface.rs
index dd8951b4aa..85c76d5aad 100644
--- a/crates/ui-egui/src/prefs/interface.rs
+++ b/crates/ui-egui/src/prefs/interface.rs
@@ -410,6 +410,22 @@ pub(super) fn layout(app: &mut SolveApp, ui: &mut egui::Ui) {
&mut app.preferences.history_play_button,
"history_play_button",
);
+ // A design's joints as one button in the History, from the second joint (#8884).
+ layout_check(
+ ui,
+ app.tr("prefs.history_group_joints"),
+ app.tr("prefs.history_group_joints_note"),
+ &mut app.preferences.history_group_joints,
+ "history_group_joints",
+ );
+ // Folds in the History bar, and a folder for a STEP insert's items (#8885).
+ layout_check(
+ ui,
+ app.tr("prefs.history_bar_groups"),
+ app.tr("prefs.history_bar_groups_note"),
+ &mut app.preferences.history_bar_groups,
+ "history_bar_groups",
+ );
ui.add_enabled_ui(app.preferences.timeline_left, |ui| {
layout_check(
ui,
diff --git a/crates/ui-egui/src/semantic_content.rs b/crates/ui-egui/src/semantic_content.rs
index cbfcca45a9..d8106cb926 100644
--- a/crates/ui-egui/src/semantic_content.rs
+++ b/crates/ui-egui/src/semantic_content.rs
@@ -392,7 +392,12 @@ pub(crate) fn release_eye(ctx: &egui::Context) -> Option<ContentSource> {
/// A reveal is acknowledged only after its row is presented in the scroll viewport. An
/// offscreen target requests scrolling again on the next frame until that happens.
pub(crate) fn scroll_acknowledged(ui: &Ui, rect: Rect) -> bool {
- ui.scroll_to_rect(rect, Some(egui::Align::Center));
+ scroll_acknowledged_at(ui, rect, egui::Align::Center)
+}
+
+/// [`scroll_acknowledged`] placing `rect` at `align` in the viewport.
+pub(crate) fn scroll_acknowledged_at(ui: &Ui, rect: Rect, align: egui::Align) -> bool {
+ ui.scroll_to_rect(rect, Some(align));
presented(ui) && ui.is_rect_visible(rect) && ui.clip_rect().contains(rect.center())
}
diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs
index 1a2101dba4..c696eafcdd 100644
--- a/crates/ui-egui/src/timeline.rs
+++ b/crates/ui-egui/src/timeline.rs
@@ -232,42 +232,15 @@ enum Drag {
Feature(u64),
}
-/// The component whose features the bottom timeline shows (#2880): the active component, else
-/// the one component picked in the browser. `None`: the whole design (nothing active or picked,
-/// or Show All turned on). A design with many parts lists every part's features otherwise.
-pub(crate) fn timeline_component(app: &SolveApp, show_all: bool) -> Option<u64> {
- if show_all {
- return None;
- }
- if app.session.active_component != 0 {
- return Some(app.session.active_component);
- }
- match app.tree.picked_components.as_slice() {
- [one] if *one != 0 => Some(*one),
- _ => None,
- }
-}
-
-/// Indices into the design's features that the timeline shows for `component` (all of them for
-/// `None`): the features of that component and of the components inside it, leaving out the
-/// components marked out of the History bar unless `show_hidden` asks for them (#10393).
-pub(crate) fn shown_feature_indices(doc: &solidcraft_engine::doc::Document, component: Option<u64>, show_hidden: bool) -> Vec<usize> {
- doc.features
- .iter()
- .enumerate()
- .filter(|(_, f)| component.is_none_or(|c| doc.component_within(f.component, c)))
- .filter(|(_, f)| show_hidden || !doc.component_history_hidden(f.component))
- .map(|(i, _)| i)
- .collect()
-}
-
-/// The design's feature position for a slot among the shown features: before the shown feature
-/// in that slot, or just after the last shown one (the end of the design when all are shown).
-fn design_position(shown: &[usize], slot: usize, n: usize) -> usize {
- match shown.get(slot) {
- Some(i) => *i,
- None => shown.last().map_or(n, |i| (i + 1).min(n)),
+/// Scrolls the History bar to `rect` when it `holds` the feature to reveal. The request is done
+/// only once the rect is presented in the viewport (an offscreen or hidden bar asks again on the
+/// next frame); then it returns true and the caller clears `timeline_reveal`.
+fn reveal_once(ui: &egui::Ui, reveal: &mut Option<usize>, holds: bool, rect: Rect, align: egui::Align) -> bool {
+ if holds && crate::semantic_content::scroll_acknowledged_at(ui, rect, align) {
+ *reveal = None;
+ return true;
}
+ false
}
/// Slot index (0..=n) nearest to screen x, given the left edges of the feature buttons.
@@ -402,8 +375,8 @@ pub(crate) fn delete_after_marker_button(app: &mut SolveApp, ui: &mut egui::Ui,
}
}
-/// A History bar feature's menu (`Target::Timeline`): edit, rename, suppress, roll back, find,
-/// the clipboard and delete.
+/// A History bar feature's menu (`Target::Timeline`): edit, rename, group, suppress, roll back,
+/// find, the clipboard and delete.
pub(crate) fn feature_items(app: &SolveApp, id: u64) -> Vec<Item> {
let doc = &app.session.doc;
let (Some(feature), Some(index)) = (doc.feature(id), doc.feature_index(id)) else { return Vec::new() };
@@ -419,8 +392,14 @@ pub(crate) fn feature_items(app: &SolveApp, id: u64) -> Vec<Item> {
// Its own message, not a literal: no catalog held the literal, so the item stayed English
// in every language (#8301).
let suppress = if feature.suppressed { "timeline.unsuppress_features" } else { "timeline.suppress_features" };
+ let targets = menu_targets(app, id);
+ let parent = crate::timeline_folders::group_parent(&doc.timeline_groups, &targets);
v.extend([
Item::action("ui.rename", "Rename", "rename").with(json!({ "feature": id, "dialog": true })),
+ // A new folder of the selected features, or of this one when it isn't selected.
+ Item::action("ui.groupFeatures", "Group Features", "feature_group")
+ .with(json!({ "features": targets, "parent": parent }))
+ .off_because(app.session.group_refusal(&targets, parent)),
Item::action("timeline.suppress", crate::i18n::tr(suppress), "suppress").with(json!({ "feature": id })),
Item::action("timeline.roll_to", "Roll History Marker Here", "rollback").with(json!({ "feature": id })),
Item::action("ui.findBrowser", "Find in Browser", "list").with(json!({ "feature": id })),
@@ -433,12 +412,13 @@ pub(crate) fn feature_items(app: &SolveApp, id: u64) -> Vec<Item> {
let label = if failed { "Copy Error Message" } else { "Copy Warning Message" };
v.push(Item::action("ui.copyMessage", label, "copy").with(json!({ "feature": id })));
}
- let targets = menu_targets(app, id);
v.push(Item::sep());
v.push(Item::action("ui.deleteFeatures", &delete_label(targets.len()), "delete").with(json!({ "features": targets })));
let marker = doc.marker.unwrap_or(doc.features.len());
- let shown = shown_feature_indices(doc, timeline_component(app, app.tree.history_show_all), app.tree.history_show_hidden);
- if let Some((label, ids)) = after_marker(app, id, index, marker, Some(&shown)) {
+ // The features the bar shows (`timeline_scope`), as it draws them.
+ let within = crate::timeline_scope::shown(app).map(|c| crate::timeline_scope::components_within(app, c));
+ let view = crate::timeline_fold::View::of(doc, within.as_ref(), app.tree.history_show_hidden);
+ if let Some((label, ids)) = after_marker(app, id, index, marker, view.shown()) {
// Its own id, so `ui.menuPick` can tell it from Delete.
v.push(Item::action("ui.deleteAfterMarker", &label, "delete").with(json!({ "features": ids })));
}
@@ -869,109 +849,6 @@ pub(crate) fn floating_rect(available: Rect) -> Rect {
Container::floating_card(Surface::Panel).bottom_strip_rect(available, 40.0)
}
-#[derive(Clone, Debug)]
-enum FolderTile {
- Feature(usize),
- Folder(u64),
- Joints(Vec<u64>),
-}
-
-/// Lay out each folder as a block, keeping feature order and placing its joints at its end.
-fn folder_tiles(app: &SolveApp, features: &[u64]) -> Vec<FolderTile> {
- if app.session.doc.timeline_groups.is_empty() {
- return (0..features.len()).map(FolderTile::Feature).collect();
- }
- fn entries(app: &SolveApp, features: &[u64], parent: Option<u64>) -> Vec<FolderTile> {
- let groups = &app.session.doc.timeline_groups;
- let mut entries: Vec<(usize, u64, FolderTile)> = features
- .iter()
- .enumerate()
- .filter(|(_, id)| groups.iter().find(|group| group.features.contains(id)).map(|group| group.id) == parent)
- .map(|(index, id)| (index, *id, FolderTile::Feature(index)))
- .collect();
- for group in groups.iter().filter(|group| group.parent == parent) {
- let mut pending = vec![group.id];
- let mut seen = std::collections::BTreeSet::new();
- let mut first = features.len();
- while let Some(id) = pending.pop() {
- if !seen.insert(id) {
- continue;
- }
- if let Some(group) = groups.iter().find(|group| group.id == id) {
- first = first.min(features.iter().position(|id| group.features.contains(id)).unwrap_or(features.len()));
- pending.extend(groups.iter().filter(|child| child.parent == Some(id)).map(|child| child.id));
- }
- }
- entries.push((first, group.id, FolderTile::Folder(group.id)));
- }
- entries.sort_by_key(|(index, id, _)| (*index, *id));
- entries.into_iter().map(|(_, _, tile)| tile).collect()
- }
-
- let mut out = Vec::new();
- let mut pending = entries(app, features, None);
- pending.reverse();
- let mut visited = std::collections::BTreeSet::new();
- while let Some(tile) = pending.pop() {
- if let FolderTile::Folder(id) = tile {
- if !visited.insert(id) {
- continue;
- }
- out.push(FolderTile::Folder(id));
- if !app.tree.collapsed.contains(&format!("timeline_group:{id}")) {
- if let Some(group) = app.session.doc.timeline_groups.iter().find(|group| group.id == id) {
- pending.push(FolderTile::Joints(group.joints.clone()));
- }
- pending.extend(entries(app, features, Some(id)).into_iter().rev());
- }
- } else {
- out.push(tile);
- }
- }
- out
-}
-
-fn folder_tile(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, x: f32, r: Rect, id: u64) -> f32 {
- let Some(group) = app.session.doc.timeline_groups.iter().find(|group| group.id == id).cloned() else { return x };
- let t = Tokens::get();
- let br = Rect::from_min_size(pos2(x, r.top() + 6.0), vec2(28.0, 28.0));
- let key = format!("timeline_group:{id}");
- let open = !app.tree.collapsed.contains(&key);
- let resp = ui.interact(br, ui.scope_id().with(("folder", id)), Sense::click());
- p.rect(
- br,
- t.radius_sm.saturating_sub(1),
- if resp.hovered() { t.hover } else { t.timeline_item },
- t.control_border_stroke(t.border),
- egui::StrokeKind::Inside,
- );
- crate::icons::paint_icon(p, br.shrink(4.0), "folder", f32::from(t.icon.a()) / 255.0);
- let mut pending = vec![id];
- let mut seen = std::collections::BTreeSet::new();
- let mut count = 0;
- while let Some(id) = pending.pop() {
- if !seen.insert(id) {
- continue;
- }
- if let Some(group) = app.session.doc.timeline_groups.iter().find(|group| group.id == id) {
- count += group.features.len() + group.joints.len();
- pending.extend(app.session.doc.timeline_groups.iter().filter(|child| child.parent == Some(id)).map(|child| child.id));
- }
- }
- p.text(br.right_bottom(), egui::Align2::RIGHT_BOTTOM, count.to_string(), egui::FontId::proportional(t.font_micro), t.text);
- crate::scenario::publish_handle(&format!("timeline-folder:{}", group.name), br.center());
- crate::scenario::publish_handle(&format!("timeline-folder-fold:{}", group.name), br.center());
- if resp.clicked() {
- if open {
- app.tree.collapsed.insert(key);
- } else {
- app.tree.collapsed.remove(&key);
- }
- }
- resp.backing_on_hover_text(format!("{} ({count})", group.name));
- x + 32.0
-}
-
fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
let t = Tokens::get();
let accent = crate::theme::TabAccent::for_tab(&t, &app.ui.tab);
@@ -1004,59 +881,46 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
x += t.space_24 + t.space_2;
}
x += 14.0;
+ // The feature that made what is under the cursor or picked in the viewport.
+ let from_view = [hovered_feature(app), picked_feature(app)];
+ // Long runs of one component's features show as one chip (`timeline_fold`). The bar shows the
+ // edited or picked component's features, after the path to it (`timeline_scope`).
+ let strip = crate::timeline_fold::Strip { marker, from_view, floating, accent };
+ crate::timeline_scope::follow(app);
+ let history = crate::timeline_fold::history(app, &strip);
+ // The edited component's last feature, scrolled into view once (`timeline_scope`): the
+ // folded chip holding it, its component's own chip, or the feature itself. Read before the
+ // path, whose click asks for it in what the next frame shows.
+ let reveal_at = app.tree.timeline_reveal.and_then(|id| app.session.doc.features.iter().position(|f| f.id == id));
+ let mut reveal = reveal_at.and_then(|i| history.view.find(i));
+ let x = crate::timeline_scope::header(app, ui, &p, x, r).min(r.right() - t.space_24);
+ // Below, slots and features count those the bar shows; the marker's slot among them.
+ let shown = history.view.len();
+ let marker_view = history.view.slot(marker);
// The features scroll horizontally in the space right of the playback controls.
- let strip = Rect::from_min_max(pos2(x, r.top()), r.right_bottom());
- ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| {
+ let strip_rect = Rect::from_min_max(pos2(x, r.top()), r.right_bottom());
+ ui.scope_builder(UiBuilder::new().max_rect(strip_rect), |ui| {
// A plain mouse wheel scrolls the strip sideways too (#3356).
ui.style_mut().always_scroll_the_only_direction = true;
- egui::ScrollArea::horizontal().auto_shrink([false, false]).show(ui, |ui| {
+ let scroll = egui::ScrollArea::horizontal().id_salt(("history_strip", history.within)).auto_shrink([false, false]);
+ scroll.show(ui, |ui| {
let p = ui.painter().clone();
let mut x = ui.max_rect().left();
let origin = x;
- // In an assembly, only the active (or picked) component's features (#2880).
- let show_all = app.tree.history_show_all;
- let only = timeline_component(app, show_all);
- let filtering = only.is_some() || show_all;
- let shown = shown_feature_indices(&app.session.doc, only, app.tree.history_show_hidden);
- if filtering || app.session.doc.features.iter().any(|f| f.component != 0) {
- // A toggle ahead of the features: this part only, or the whole design.
- let label = match only {
- Some(c) => app.session.doc.components.iter().find(|k| k.id == c).map_or_else(|| "Component".to_string(), |k| k.name.clone()),
- None => "All components".to_string(),
- };
- let galley = ui.painter().layout_no_wrap(label.clone(), egui::FontId::proportional(t.font_label), t.text);
- let br = Rect::from_min_size(pos2(x, r.top() + 9.0), vec2(galley.size().x + 12.0, 22.0));
- crate::scenario::publish_handle("timeline:components", br.center());
- let resp = ui.interact(br, ui.scope_id().with("tl_components"), Sense::click());
- p.rect(br, 3.0, if resp.hovered() { t.hover } else { t.timeline_item }, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
- p.galley(br.left_center() + vec2(6.0, -galley.size().y * 0.5), galley, t.text);
- let tip = if show_all {
- "Showing every component's features. Click to show only the active or picked component's"
- } else if only.is_some() {
- "Showing this component's features only. Click to show the whole design's"
- } else {
- "Activate or pick a component in the browser to show only its features"
- };
- if resp.backing_on_hover_text(tip).clicked() && (only.is_some() || show_all) {
- app.tree.history_show_all = !show_all;
- }
- x = br.right() + 8.0;
- }
- let marker = shown.iter().position(|i| *i >= marker).unwrap_or(shown.len());
- let feats: Vec<_> = shown
+ let feats: Vec<_> = app
+ .session
+ .doc
+ .features
.iter()
- .filter_map(|i| app.session.doc.features.get(*i))
.map(|f| (f.id, f.name.clone(), icon_of(&f.kind), f.suppressed, f.kind.type_name(), TimelineKind::of(&f.kind)))
.collect();
- let order: Vec<u64> = feats.iter().map(|f| f.0).collect();
- // Find in Timeline: scroll the found feature into the strip on this frame (#5850).
- let reveal = app.tree.timeline_reveal;
- // The feature that made what is under the cursor or picked in the viewport.
- let from_view = [hovered_feature(app), picked_feature(app)];
+ // The bar's features in the order it draws them, folded ones included: a Shift+click
+ // range runs over these.
+ let order: Vec<u64> = history.view.indices(0, shown).iter().filter_map(|i| feats.get(*i).map(|f| f.0)).collect();
let drag_id = ui.scope_id().with("tl_drag");
let mut drag: Option<Drag> = ui.data(|d| d.get_temp(drag_id));
let pointer = ui.input(|i| i.pointer.hover_pos());
- let mut xs: Vec<f32> = vec![x; feats.len()];
+ let mut xs: Vec<f32> = Vec::new();
let mut hovered: Option<u64> = None;
let mut edit: Option<u64> = None;
let mut marker_rect: Option<Rect> = None;
@@ -1078,49 +942,96 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
.filter_map(feature_of)
.chain(app.dialog.as_ref().map(|dialog| dialog.items()).unwrap_or_default().iter().filter_map(feature_of))
.collect();
- for tile in folder_tiles(app, &order) {
- let i = match tile {
- FolderTile::Folder(id) => {
- if marker_rect.is_none() && app.tree.collapsed.contains(&format!("timeline_group:{id}")) {
- let mut pending = vec![id];
- let mut seen = std::collections::BTreeSet::new();
- let mut contains_marker = false;
- while let Some(id) = pending.pop() {
- if !seen.insert(id) {
- continue;
- }
- if let Some(group) = app.session.doc.timeline_groups.iter().find(|group| group.id == id) {
- contains_marker |= order.get(marker).is_some_and(|feature| group.features.contains(feature));
- pending.extend(
- app.session.doc.timeline_groups.iter().filter(|child| child.parent == Some(id)).map(|child| child.id),
- );
- }
- }
- if contains_marker {
- marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0)));
- x += t.space_16;
- }
+ // Each open run or folder's tray: where it starts, its place under the chips, its depth.
+ let mut trays: Vec<(f32, egui::layers::ShapeIdx, usize)> = Vec::new();
+ let pad = crate::ui_kit::HISTORY_TRAY_PAD;
+ let marker_at = |x: f32| Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0));
+ let editing = crate::timeline_scope::focus(app).unwrap_or(0);
+ for entry in history.entries.iter().copied() {
+ let i = match entry {
+ crate::timeline_fold::Entry::Feature(i) => i,
+ crate::timeline_fold::Entry::Group(group) => {
+ if group.start == marker_view && marker_rect.is_none() {
+ marker_rect = Some(marker_at(x));
+ x += t.space_16;
+ }
+ if group.open {
+ trays.push((x, p.add(egui::Shape::Noop), group.depth));
+ x += pad;
+ }
+ let at = pos2(x, r.top() + 6.0);
+ let width = crate::timeline_fold::group_chip(app, ui, &p, at, &group, &history, &strip);
+ let holds = reveal.is_some_and(|k| group.start <= k && k < group.end && (!group.open || group.component == editing));
+ if reveal_once(ui, &mut reveal, holds, Rect::from_min_size(at, vec2(width, 28.0)), egui::Align::Min) {
+ app.tree.timeline_reveal = None;
+ }
+ if !group.open {
+ // Dropping on a folded run puts the feature before it.
+ xs.extend(std::iter::repeat_n(x, group.end - group.start));
+ }
+ x += width + 4.0;
+ if !group.open && group.start < marker_view && marker_view < group.end && marker_rect.is_none() {
+ marker_rect = Some(marker_at(x));
+ x += t.space_16;
+ }
+ continue;
+ }
+ crate::timeline_fold::Entry::Folder(folder) => {
+ let holds = folder.start < folder.end;
+ if holds && folder.start == marker_view && marker_rect.is_none() {
+ marker_rect = Some(marker_at(x));
+ x += t.space_16;
+ }
+ if folder.open {
+ trays.push((x, p.add(egui::Shape::Noop), folder.depth));
+ x += pad;
+ }
+ let at = pos2(x, r.top() + 6.0);
+ let width = crate::timeline_folders::folder_chip(app, ui, &p, at, &folder, &history, &strip);
+ let holds = reveal.is_some_and(|k| folder.start <= k && k < folder.end && !folder.open);
+ if reveal_once(ui, &mut reveal, holds, Rect::from_min_size(at, vec2(width, 28.0)), egui::Align::Min) {
+ app.tree.timeline_reveal = None;
+ }
+ if !folder.open {
+ // Dropping on a folded folder puts the feature before it.
+ xs.extend(std::iter::repeat_n(x, folder.end - folder.start));
+ }
+ x += width + 4.0;
+ if !folder.open && folder.start < marker_view && marker_view < folder.end && marker_rect.is_none() {
+ marker_rect = Some(marker_at(x));
+ x += t.space_16;
}
- x = folder_tile(app, ui, &p, x, r, id);
continue;
}
- FolderTile::Joints(ids) => {
- x = crate::dialogs_assembly::timeline_joint_tiles(app, ui, &p, x, r, Some(&ids));
+ crate::timeline_fold::Entry::Joints(folder) => {
+ let joints = history.folders.joints.get(&folder).cloned().unwrap_or_default();
+ let run = crate::dialogs_assembly::JointRun::Folder { id: folder, name: history.folders.name(folder) };
+ x = crate::dialogs_assembly::joint_chips(app, ui, &p, x, r, &joints, run);
+ continue;
+ }
+ crate::timeline_fold::Entry::End(_) => {
+ if let Some((left, tray, depth)) = trays.pop() {
+ let right = x - 4.0 + pad;
+ p.set(tray, crate::ui_kit::history_tray(left, right, r.top() + 6.0, depth, accent));
+ x = right + 4.0;
+ }
continue;
}
- FolderTile::Feature(index) => index,
};
- let Some((id, name, icon, suppressed, ty, kind)) = feats.get(i) else { continue };
+ // The feature's index in the design.
+ let at = history.view.index(i);
+ let Some((id, name, icon, suppressed, ty, kind)) = feats.get(at) else {
+ continue;
+ };
let sketch_state = matches!(kind, TimelineKind::Sketch).then(|| sketch_states.get(*id)).flatten();
- if i == marker {
- marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0)));
+ if i == marker_view && marker_rect.is_none() {
+ marker_rect = Some(marker_at(x));
x += t.space_16;
}
- if let Some(slot) = xs.get_mut(i) {
- *slot = x;
- }
+ xs.push(x);
let br = Rect::from_min_size(pos2(x, r.top() + 6.0), vec2(28.0, 28.0));
- if reveal == Some(*id) && crate::semantic_content::scroll_acknowledged(ui, br) {
+ let holds = reveal == Some(i);
+ if reveal_once(ui, &mut reveal, holds, br, egui::Align::Center) {
app.tree.timeline_reveal = None;
}
crate::scenario::publish_handle(&format!("timeline:{name}"), br.center());
@@ -1143,7 +1054,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
results.get(id).and_then(|k| app.session.model.results.get(*k).filter(|r| r.id == *id).or_else(|| app.session.model.result(*id)));
let err = res.and_then(|r| r.error.clone());
let warn = res.and_then(warning_text);
- let rolled = i >= marker;
+ let rolled = i >= marker_view;
let sel = picked.contains(id);
if resp.hovered() {
hovered = Some(*id);
@@ -1164,7 +1075,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
accent: if drag == Some(Drag::Feature(*id)) { crate::theme::TabAccent::for_tab(&t, "SKETCH") } else { accent },
}
.paint(&p, br, crate::ui_kit::HistoryStyle::Bottom);
- if floating && marker > 0 && i == marker - 1 {
+ if floating && at + 1 == marker {
p.circle_filled(pos2(br.center().x, br.bottom() + t.space_3), t.space_2, accent.color);
}
let ms = res.map(|r| r.ms);
@@ -1213,13 +1124,8 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
}
x += 32.0;
}
- let mut previous = origin;
- for slot in &mut xs {
- *slot = (*slot).max(previous);
- previous = *slot;
- }
let end = x;
- if marker >= feats.len() {
+ if marker_view >= shown && marker_rect.is_none() {
marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0)));
}
// The history marker: drag it to roll the model back or forward.
@@ -1235,32 +1141,47 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
crate::ui_kit::history_marker(&p, mr, false, accent);
resp.backing_on_hover_text(crate::i18n::tr("ui.history_marker_tip"));
}
- let content_end = crate::dialogs_assembly::timeline_joints(app, ui, &p, end + 10.0, r);
+ // The joints at the end belong to the whole design: a bar with its groups that shows one
+ // component leaves them out. Without the groups they stay, as they always have.
+ let content_end = if history.within.is_none() || !app.preferences.history_bar_groups {
+ crate::dialogs_assembly::timeline_joints(app, ui, &p, end + 10.0, r, &history.folders.held)
+ } else {
+ end
+ };
// The scroll range follows the drawn content (the buttons don't take layout space themselves).
ui.allocate_exact_size(vec2((content_end - origin).max(0.0), r.height()), Sense::hover());
// Drag feedback, and the drop.
if drag.is_some() {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
}
- let marker_slot = marker.min(n);
// At the marker's slot, which side of the marker the pointer is on: before it, a
// dropped feature stays in the model; after it, the feature is rolled back.
- let before_marker = |slot: usize, x: f32| slot < marker_slot || (slot == marker_slot && marker_rect.is_none_or(|mr| x < mr.center().x));
+ let before_marker = |slot: usize, x: f32| slot < marker_view || (slot == marker_view && marker_rect.is_none_or(|mr| x < mr.center().x));
+ // The design's position of a slot; at the marker's, on the side of the marker the
+ // pointer is on (features not shown may sit between it and the next one shown).
+ let position = |slot: usize, before: bool| {
+ let at = history.view.index(slot);
+ match (slot == marker_view, before) {
+ (true, true) => at.min(marker),
+ (true, false) => at.max(marker),
+ (false, _) => at,
+ }
+ };
// The marker dropped where it already is needs no bar: the marker shows the spot.
if let (Some(dg), Some(pp)) = (drag.as_ref(), pointer)
- && let slot = slot_at(&xs, end, pp.x)
- && !(matches!(dg, Drag::Marker) && slot == marker_slot)
+ && let local = slot_at(&xs, end, pp.x)
+ && !(matches!(dg, Drag::Marker) && local == marker_view)
{
// Centred in the gap between two chips, or beside the marker at its slot.
let sx = match marker_rect {
- Some(mr) if slot == marker_slot => {
- if before_marker(slot, pp.x) {
+ Some(mr) if local == marker_view => {
+ if before_marker(local, pp.x) {
mr.left() - 2.0
} else {
mr.right() + 2.0
}
}
- _ => xs.get(slot).copied().unwrap_or(end) - 2.0,
+ _ => xs.get(local).copied().unwrap_or(end) - 2.0,
};
// Kept inside the strip so the slot before the first feature stays visible.
let sx = sx.max(origin + t.space_2);
@@ -1277,21 +1198,15 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
&& let Some(dg) = drag.take()
&& let Some(pp) = pointer
{
- let slot = design_position(&shown, slot_at(&xs, end, pp.x), n);
+ let local = slot_at(&xs, end, pp.x);
+ let before = before_marker(local, pp.x);
+ let slot = position(local, before);
match dg {
Drag::Marker => {
let _ = app.run_heavy("timeline.roll_to", if slot >= n { json!({}) } else { json!({ "position": slot }) });
}
- Drag::Feature(id) => {
- let from = app.session.doc.feature_index(id).unwrap_or(0);
- // Dropping after itself means the slot shifts by one.
- let to = if slot > from { slot - 1 } else { slot };
- // Crossing the marker rolls the feature back or forward, in the same step.
- let active = before_marker(slot, pp.x);
- if to != from || active != (from < marker_slot) {
- let _ = app.run_heavy("timeline.reorder", json!({ "feature": id, "position": to, "active": active }));
- }
- }
+ // Crossing the marker rolls the feature back or forward, in the same step.
+ Drag::Feature(id) => crate::timeline_folders::drop_feature(app, &history.folders, id, slot, before, marker.min(n)),
}
}
ui.data_mut(|d| match drag {
@@ -1341,6 +1256,8 @@ mod tests {
let mut h = Harness::new();
h.app.home.open = false;
h.app.preferences.timeline_left = left;
+ h.app.preferences.history_group_joints = true;
+ h.app.preferences.history_bar_groups = true;
h.app.run("component.create", json!({"name":"Part"})).unwrap();
let mut joints = Vec::new();
for index in 0..50 {
@@ -1351,23 +1268,32 @@ mod tests {
);
}
let folder = h.app.run("timeline.group", json!({"name":"Joints", "joints":joints})).unwrap()["group"].as_u64().unwrap();
- h.app.tree.collapsed.insert(format!("timeline_group:{folder}"));
+ crate::timeline_folders::set_open(&mut h.app, folder, false);
h.frames(4);
- assert!(handle_at("timeline-folder:Joints").is_some());
- assert_eq!(crate::scenario::handles("timeline-folder:").len(), 1);
+ // The History bar shows a folder as a chip; the History beside the Browser as a row.
+ let (folders, fold) =
+ if left { ("timeline-folder:", "timeline-folder-fold:Joints") } else { ("timeline-folder-chip:", "timeline-folder-chip:Joints") };
+ assert!(handle_at(&format!("{folders}Joints")).is_some());
+ assert_eq!(crate::scenario::handles(folders).len(), 1);
assert!(crate::scenario::handles("timeline-joint:").is_empty());
for index in 0..50 {
assert!(handle_at(&format!("timeline-joint:Hinge{index}")).is_none());
}
- h.step(&json!({"click":{"handle":"timeline-folder-fold:Joints"}})).unwrap();
+ h.step(&json!({"click":{"handle":fold}})).unwrap();
h.frames(4);
+ if !left {
+ // In the History bar an open folder's joints are one button from the second on.
+ assert!(crate::scenario::handles("timeline-joint:").is_empty());
+ h.step(&json!({"click":{"handle":"timeline-folder-joints:Joints"}})).unwrap();
+ h.frames(4);
+ }
for index in 0..50 {
assert!(handle_at(&format!("timeline-joint:Hinge{index}")).is_some(), "joint {index} missing, left={left}");
}
assert_eq!(crate::scenario::handles("timeline-joint:").len(), 50, "no trailing duplicates");
h.step(&json!({"click":{"handle":"timeline-joint:Hinge0"}})).unwrap();
assert_eq!(h.app.tree.picked_joints, [joints[0]]);
- h.step(&json!({"click":{"handle":"timeline-folder-fold:Joints"}})).unwrap();
+ h.step(&json!({"click":{"handle":fold}})).unwrap();
h.frames(4);
assert!(handle_at("timeline-joint:Hinge0").is_none());
}
@@ -1414,7 +1340,7 @@ mod tests {
}
#[test]
- fn shown_feature_indices_leave_out_hidden_components_and_their_children() {
+ fn the_bar_leaves_out_hidden_components_and_their_children() {
let mut h = Harness::new();
h.app.run("component.create", json!({ "name": "Copy" })).unwrap();
h.app.run("solid.box", json!({ "length": 1, "width": 1, "height": 1, "name": "CopyBox" })).unwrap();
@@ -1425,15 +1351,16 @@ mod tests {
h.app.run("solid.box", json!({ "length": 1, "width": 1, "height": 1, "name": "PartBox" })).unwrap();
h.app.run("component.activate", json!({ "component": "root" })).unwrap();
h.app.run("component.hide_history", json!({ "component": "Copy" })).unwrap();
+ use crate::timeline_fold::View;
let doc = &h.app.session.doc;
- let shown = |show_hidden: bool| super::shown_feature_indices(doc, None, show_hidden);
- let names = |idx: Vec<usize>| idx.iter().map(|i| doc.features[*i].name.clone()).collect::<Vec<_>>();
- assert_eq!(names(shown(false)), ["PartBox"], "a hidden component takes its own and its children's rows out");
- assert_eq!(names(shown(true)), ["CopyBox", "InnerBox", "PartBox"], "show-hidden lists everything again");
- // The same filter applies when the bar narrows to one component.
+ let names = |view: View| view.indices(0, view.len()).iter().map(|i| doc.features[*i].name.clone()).collect::<Vec<_>>();
+ assert_eq!(names(View::of(doc, None, false)), ["PartBox"], "a hidden component takes its own and its children's rows out");
+ assert_eq!(names(View::of(doc, None, true)), ["CopyBox", "InnerBox", "PartBox"], "show-hidden lists everything again");
+ // The same filter applies when the bar shows one component.
let copy = doc.components.iter().find(|c| c.name == "Copy").unwrap().id;
- assert!(super::shown_feature_indices(doc, Some(copy), false).is_empty(), "the component filter shows nothing of a hidden component");
- assert_eq!(super::shown_feature_indices(doc, Some(copy), true).len(), 2, "Copy owns CopyBox and InnerBox");
+ let within = crate::timeline_scope::components_within(&h.app, copy);
+ assert!(names(View::of(doc, Some(&within), false)).is_empty(), "the component filter shows nothing of a hidden component");
+ assert_eq!(names(View::of(doc, Some(&within), true)), ["CopyBox", "InnerBox"], "Copy owns CopyBox and InnerBox");
}
#[test]
@@ -1991,6 +1918,292 @@ mod tests {
assert_eq!(super::selected_feature_ids(&h.app).len(), 200);
}
+ /// A long history folds a component's features into one chip with its name and count. A run
+ /// that holds the history marker shows each feature until its chip is clicked; folded by
+ /// hand, the marker waits after the chip. Clicking the chip again shows each feature.
+ #[test]
+ fn a_long_history_folds_a_components_features_into_one_chip() {
+ use crate::scenario::{handle_at, rect_of};
+ let mut h = Harness::new();
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ h.app.run("sketch.create", json!({"plane": "XY", "name": "Root sketch"})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("component.create", json!({"name": "Rig"})).unwrap();
+ for i in 0..crate::timeline_fold::FOLD_FROM {
+ h.app.run("sketch.create", json!({"plane": "XY", "name": format!("S{i}")})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ }
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.frames(4);
+ assert!(handle_at("timeline:Root sketch").is_some(), "a root feature stays on its own");
+ assert!(handle_at("timeline:S0").is_none(), "the component's features are folded");
+ assert!(handle_at("timeline-group:Rig").is_some(), "the folded run's chip");
+
+ h.app.run("timeline.roll_to", json!({"position": 20})).unwrap();
+ h.frames(2);
+ assert!(handle_at("timeline:S10").is_some(), "the run holding the marker shows each feature");
+ let chip = handle_at("timeline-group:Rig").unwrap();
+ h.call("ui.click", json!({"x": chip.x, "y": chip.y}));
+ h.frames(2);
+ assert!(handle_at("timeline:S10").is_none(), "clicking the chip folds them anyway");
+ let chip = handle_at("timeline-group:Rig").unwrap();
+ let marker = rect_of("history:marker").expect("the marker stays in view");
+ assert!(marker.left() > chip.x, "the marker waits after the folded chip: {marker:?} {chip:?}");
+
+ h.app.run("timeline.roll_to", json!({})).unwrap();
+ h.call("ui.click", json!({"x": chip.x, "y": chip.y}));
+ h.frames(2);
+ assert!(handle_at("timeline:S0").is_some() && handle_at("timeline:S49").is_some(), "clicking again shows each feature");
+ }
+
+ /// #10393 with the bar's groups on: a component marked out of the History bar leaves neither
+ /// its features nor a chip for them, and its features don't count towards folding. Showing
+ /// hidden components brings its long run back, folded like any other.
+ #[test]
+ fn a_component_hidden_from_the_bar_leaves_no_chip_and_comes_back_folded() {
+ use crate::scenario::handle_at;
+ let mut h = Harness::new();
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ h.app.run("sketch.create", json!({"plane": "XY", "name": "Root sketch"})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("component.create", json!({"name": "Copy"})).unwrap();
+ for i in 0..crate::timeline_fold::FOLD_FROM {
+ h.app.run("sketch.create", json!({"plane": "XY", "name": format!("C{i}")})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ }
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.app.run("component.hide_history", json!({"component": "Copy"})).unwrap();
+ h.frames(4);
+ assert!(handle_at("timeline:Root sketch").is_some(), "the rest of the design shows");
+ assert!(handle_at("timeline:C0").is_none() && handle_at("timeline-group:Copy").is_none(), "no feature or chip of the hidden component");
+ h.app.tree.history_show_hidden = true;
+ h.frames(4);
+ assert!(handle_at("timeline-group:Copy").is_some(), "shown again, its long run folds into a chip");
+ assert!(handle_at("timeline:C0").is_none(), "folded, not each feature");
+ }
+
+ /// A run that holds subassemblies folding in turn shows only its component's features when
+ /// clicked, after a path back to the whole design. A subassembly there opens in place, and the
+ /// marker dragged between its features rolls the whole history there. "All components" goes
+ /// back to the whole design, where such a run stays folded with the marker inside it.
+ #[test]
+ fn a_deep_run_shows_only_its_component_and_the_path_steps_back_out() {
+ use crate::scenario::{handle_at, rect_of};
+ let (mut h, _) = rig_with_arm_and_leg(30);
+ let rig_chip = handle_at("timeline-group:Rig").expect("the rig folds");
+ assert!(handle_at("timeline-group:Arm").is_none() && handle_at("timeline-path:Rig").is_none());
+ assert!(handle_at("timeline-path:All components").is_some(), "the path starts at the whole design");
+ h.call("ui.click", json!({"x": rig_chip.x, "y": rig_chip.y}));
+ h.frames(3);
+ assert!(handle_at("timeline-path:Rig").is_some(), "the path ends at the rig");
+ assert!(handle_at("timeline:Root sketch").is_none(), "the rest of the history is left out");
+ let arm = handle_at("timeline-group:Arm").expect("its subassemblies show folded");
+ assert!(handle_at("timeline-group:Leg").is_some());
+ h.call("ui.click", json!({"x": arm.x, "y": arm.y}));
+ h.frames(3);
+ assert!(handle_at("timeline:Arm0").is_some() && handle_at("timeline:Arm29").is_some(), "a subassembly opens in place");
+
+ let marker = rect_of("history:marker").expect("the marker sits at the end of the history");
+ let arm5 = handle_at("timeline:Arm5").unwrap();
+ h.step(&json!({"drag": [[marker.center().x, marker.center().y], [arm5.x - 14.0, arm5.y]]})).unwrap();
+ h.settle();
+ let index = h.app.session.doc.features.iter().position(|f| f.name == "Arm5").unwrap();
+ assert_eq!(h.app.session.doc.marker, Some(index), "the marker goes before Arm5 in the whole history");
+
+ let all = handle_at("timeline-path:All components").unwrap();
+ h.call("ui.click", json!({"x": all.x, "y": all.y}));
+ h.frames(3);
+ assert!(handle_at("timeline:Root sketch").is_some() && handle_at("timeline-path:Rig").is_none(), "back to the whole design");
+ assert!(handle_at("timeline-group:Rig").is_some() && handle_at("timeline-group:Arm").is_none(), "the rig stays folded around the marker");
+ }
+
+ /// A root sketch, then a component Rig holding Arm (`arm` sketches) and Leg (25): Rig's run is
+ /// deep. The bar's groups are on. Returns the harness, editing the root again, and the
+ /// components' ids by name.
+ fn rig_with_arm_and_leg(arm: usize) -> (Harness, std::collections::HashMap<&'static str, u64>) {
+ let mut h = Harness::new();
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ h.app.run("sketch.create", json!({"plane": "XY", "name": "Root sketch"})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ let rig = h.app.run("component.create", json!({"name": "Rig"})).unwrap()["component"].as_u64().unwrap();
+ let mut ids = std::collections::HashMap::from([("Rig", rig)]);
+ for (part, count) in [("Arm", arm), ("Leg", 25)] {
+ h.app.run("component.activate", json!({"component": rig})).unwrap();
+ let id = h.app.run("component.create", json!({"name": part})).unwrap()["component"].as_u64().unwrap();
+ ids.insert(part, id);
+ for i in 0..count {
+ h.app.run("sketch.create", json!({"plane": "XY", "name": format!("{part}{i}")})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ }
+ }
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.frames(4);
+ (h, ids)
+ }
+
+ /// Editing a component shows only its features, after the path to it. A click on a step
+ /// around it shows that component's features, with the way to the edited one open and
+ /// scrolled into view past an open subassembly wider than the window; the edited one's step
+ /// goes back in. Editing another component or picking one in the Browser follows it; editing
+ /// the root shows the whole design.
+ #[test]
+ fn editing_a_component_shows_only_its_features_and_the_path_steps_out() {
+ use crate::scenario::{handle_at, rect_of};
+ let (mut h, ids) = rig_with_arm_and_leg(60);
+ let rig = handle_at("timeline-group:Rig").unwrap();
+ h.call("ui.click", json!({"x": rig.x, "y": rig.y}));
+ h.frames(3);
+ let arm = handle_at("timeline-group:Arm").unwrap();
+ h.call("ui.click", json!({"x": arm.x, "y": arm.y}));
+ h.frames(3);
+ let all = handle_at("timeline-path:All components").unwrap();
+ h.call("ui.click", json!({"x": all.x, "y": all.y}));
+ h.frames(3);
+ assert!(handle_at("timeline-group:Rig").is_some() && handle_at("timeline:Leg0").is_none());
+
+ h.app.run("component.activate", json!({"component": ids["Leg"]})).unwrap();
+ h.frames(3);
+ assert!(handle_at("timeline:Leg0").is_some() && handle_at("timeline:Leg24").is_some(), "the leg's features show");
+ assert!(handle_at("timeline:Arm0").is_none() && handle_at("timeline:Root sketch").is_none(), "nothing else does");
+ assert!(handle_at("timeline-path:Rig").is_some() && handle_at("timeline-path:Leg").is_some(), "the path to the leg");
+
+ let rig = handle_at("timeline-path:Rig").unwrap();
+ h.call("ui.click", json!({"x": rig.x, "y": rig.y}));
+ h.frames(30);
+ assert!(handle_at("timeline:Arm0").is_some() && handle_at("timeline:Leg0").is_some(), "the rig's features: the open arm's and the leg's");
+ let strip = rect_of("history:strip").or_else(|| rect_of("history:card")).unwrap();
+ let leg = handle_at("timeline-group:Leg").unwrap();
+ assert!(strip.x_range().contains(leg.x), "the leg's chip scrolled into view: {leg:?} in {strip:?}");
+ let back_in = handle_at("timeline-path:Leg").expect("the leg's step stays on the path");
+ h.call("ui.click", json!({"x": back_in.x, "y": back_in.y}));
+ h.frames(3);
+ assert!(handle_at("timeline:Leg0").is_some() && handle_at("timeline:Arm0").is_none(), "back in to the leg");
+
+ h.app.run("component.activate", json!({"component": ids["Arm"]})).unwrap();
+ h.frames(3);
+ assert!(handle_at("timeline:Arm0").is_some() && handle_at("timeline:Leg0").is_none(), "switching to the arm follows it");
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.frames(3);
+ assert!(handle_at("timeline:Root sketch").is_some() && handle_at("timeline-path:Arm").is_none(), "the root shows the whole design");
+
+ h.app.tree.picked_components = vec![ids["Leg"]];
+ h.frames(3);
+ assert!(handle_at("timeline:Leg0").is_some() && handle_at("timeline:Root sketch").is_none(), "a component picked in the Browser");
+ h.app.tree.picked_components.clear();
+ h.frames(3);
+ assert!(handle_at("timeline:Root sketch").is_some(), "nothing picked shows the whole design again");
+ }
+
+ /// While a component is edited, its features keep their place in the design: the marker
+ /// dragged before one rolls back there, past another component's features in between, and a
+ /// feature dropped before another goes there in the design.
+ #[test]
+ fn a_components_history_rolls_and_reorders_in_the_whole_design() {
+ use crate::scenario::{handle_at, rect_of};
+ let mut h = Harness::new();
+ // The path to "All components" comes with the bar's groups (`timeline_scope`).
+ h.app.preferences.history_bar_groups = true;
+ let a = h.app.run("component.create", json!({"name": "A"})).unwrap()["component"].as_u64().unwrap();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "A1"})).unwrap();
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ let b = h.app.run("component.create", json!({"name": "B"})).unwrap()["component"].as_u64().unwrap();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "name": "B1"})).unwrap();
+ h.app.run("component.activate", json!({"component": a})).unwrap();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 20, 0], "name": "A2"})).unwrap();
+ h.frames(4);
+ let names = |h: &Harness| h.app.session.doc.features.iter().map(|f| f.name.clone()).collect::<Vec<_>>();
+ assert_eq!(names(&h), ["A1", "B1", "A2"]);
+ assert!(handle_at("timeline:A1").is_some() && handle_at("timeline:A2").is_some() && handle_at("timeline:B1").is_none());
+
+ let marker = rect_of("history:marker").unwrap();
+ let a2 = handle_at("timeline:A2").unwrap();
+ h.step(&json!({"drag": [[marker.center().x, marker.center().y], [a2.x - 14.0, a2.y]]})).unwrap();
+ h.settle();
+ assert_eq!(h.app.session.doc.marker, Some(2), "B1 stays built, A2 is rolled back");
+
+ h.app.run("timeline.roll_to", json!({})).unwrap();
+ h.frames(3);
+ let (a1, a2) = (handle_at("timeline:A1").unwrap(), handle_at("timeline:A2").unwrap());
+ h.step(&json!({"drag": [[a2.x, a2.y], [a1.x - 14.0, a1.y]]})).unwrap();
+ h.settle();
+ assert_eq!(names(&h), ["A2", "A1", "B1"], "A2 goes before A1 in the design");
+
+ h.app.run("component.activate", json!({"component": b})).unwrap();
+ h.frames(3);
+ assert!(handle_at("timeline:B1").is_some() && handle_at("timeline:A1").is_none());
+ let all = handle_at("timeline-path:All components").unwrap();
+ h.call("ui.click", json!({"x": all.x, "y": all.y}));
+ h.frames(3);
+ assert!(handle_at("timeline:A1").is_some() && handle_at("timeline:B1").is_some(), "All components shows both");
+ assert!(handle_at("timeline-path:B").is_some(), "the way back in to the edited component");
+ }
+
+ fn shown(h: &mut Harness) -> Vec<String> {
+ h.frames(4);
+ crate::scenario::handles("timeline:").into_iter().map(|(n, _)| n).filter(|n| n != "timeline:components").collect()
+ }
+
+ /// Two components with a box each: while one is active, the timeline shows only its
+ /// feature; the toggle ahead of the features shows the whole design again, and so does the
+ /// root (#2880). Without the bar's groups (the default) there is no path, and the whole
+ /// design stays shown while another component is edited or picked, until the toggle again.
+ #[test]
+ fn the_timeline_shows_only_the_active_components_features() {
+ let mut h = Harness::new();
+ h.app.run("component.create", json!({"name": "Left"})).unwrap();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "LeftBox"})).unwrap();
+ h.app.run("component.activate", json!({"component": 0})).unwrap();
+ h.app.run("component.create", json!({"name": "Right"})).unwrap();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "name": "RightBox"})).unwrap();
+ let names = shown(&mut h);
+ assert!(names.contains(&"timeline:RightBox".to_string()) && !names.contains(&"timeline:LeftBox".to_string()), "{names:?}");
+ h.step(&json!({"click": {"handle": "timeline:components"}})).unwrap();
+ let names = shown(&mut h);
+ assert!(names.contains(&"timeline:LeftBox".to_string()) && names.contains(&"timeline:RightBox".to_string()), "show all: {names:?}");
+ h.step(&json!({"click": {"handle": "timeline:components"}})).unwrap();
+ let names = shown(&mut h);
+ assert!(!names.contains(&"timeline:LeftBox".to_string()), "this part again: {names:?}");
+ h.app.run("component.activate", json!({"component": 0})).unwrap();
+ let names = shown(&mut h);
+ assert!(names.contains(&"timeline:LeftBox".to_string()) && names.contains(&"timeline:RightBox".to_string()), "root: {names:?}");
+ assert!(crate::scenario::handle_at("timeline-path:All components").is_none(), "no path without the bar's groups");
+
+ let id = |h: &Harness, name: &str| h.app.session.doc.components.iter().find(|c| c.name == name).map(|c| c.id).unwrap();
+ let (left, right) = (id(&h, "Left"), id(&h, "Right"));
+ h.app.run("component.activate", json!({"component": right})).unwrap();
+ shown(&mut h);
+ h.step(&json!({"click": {"handle": "timeline:components"}})).unwrap();
+ h.app.run("component.activate", json!({"component": left})).unwrap();
+ let names = shown(&mut h);
+ assert!(names.contains(&"timeline:RightBox".to_string()), "all still shown while another is edited: {names:?}");
+ h.app.run("component.activate", json!({"component": 0})).unwrap();
+ h.app.tree.picked_components = vec![right];
+ let names = shown(&mut h);
+ assert!(names.contains(&"timeline:LeftBox".to_string()), "and while one is picked: {names:?}");
+ h.step(&json!({"click": {"handle": "timeline:components"}})).unwrap();
+ let names = shown(&mut h);
+ assert!(
+ names.contains(&"timeline:RightBox".to_string()) && !names.contains(&"timeline:LeftBox".to_string()),
+ "the picked one only: {names:?}"
+ );
+ }
+
+ /// A design opened or made afresh in the tab shows the edited or picked component's
+ /// features again, not the whole design chosen for the one before.
+ #[test]
+ fn a_new_design_in_the_tab_starts_on_the_edited_component() {
+ let mut h = Harness::new();
+ h.app.run("component.create", json!({"name": "Part"})).unwrap();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "PartBox"})).unwrap();
+ shown(&mut h);
+ h.step(&json!({"click": {"handle": "timeline:components"}})).unwrap();
+ shown(&mut h);
+ assert_eq!(h.app.tree.timeline_scope, crate::timeline_scope::Scope::All);
+ h.app.run("file.new", json!({})).unwrap();
+ assert_eq!(h.app.tree.timeline_scope, crate::timeline_scope::Scope::Follow, "file.new");
+ assert_eq!(h.app.tree.timeline_followed, None, "it follows the new design's own component");
+ }
+
/// Find in Timeline on the last body of a history longer than the timeline scrolls its
/// feature into view, in the bottom strip and in the history on the left (#5850).
#[test]
@@ -2090,45 +2303,6 @@ mod tests {
}
}
- fn shown(h: &mut Harness) -> Vec<String> {
- h.frames(4);
- crate::scenario::handles("timeline:").into_iter().map(|(n, _)| n).filter(|n| n != "timeline:components").collect()
- }
-
- /// Two components with a box each: while one is active, the timeline shows only its
- /// feature; the toggle ahead of the features shows the whole design again, and so does the
- /// root (#2880).
- #[test]
- fn the_timeline_shows_only_the_active_components_features() {
- let mut h = Harness::new();
- h.app.run("component.create", json!({"name": "Left"})).unwrap();
- h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "LeftBox"})).unwrap();
- h.app.run("component.activate", json!({"component": 0})).unwrap();
- h.app.run("component.create", json!({"name": "Right"})).unwrap();
- h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "name": "RightBox"})).unwrap();
- let names = shown(&mut h);
- assert!(names.contains(&"timeline:RightBox".to_string()) && !names.contains(&"timeline:LeftBox".to_string()), "{names:?}");
- h.step(&json!({"click": {"handle": "timeline:components"}})).unwrap();
- let names = shown(&mut h);
- assert!(names.contains(&"timeline:LeftBox".to_string()) && names.contains(&"timeline:RightBox".to_string()), "show all: {names:?}");
- h.step(&json!({"click": {"handle": "timeline:components"}})).unwrap();
- let names = shown(&mut h);
- assert!(!names.contains(&"timeline:LeftBox".to_string()), "this part again: {names:?}");
- h.app.run("component.activate", json!({"component": 0})).unwrap();
- let names = shown(&mut h);
- assert!(names.contains(&"timeline:LeftBox".to_string()) && names.contains(&"timeline:RightBox".to_string()), "root: {names:?}");
- }
-
- /// The marker and a drop map from the shown features back to the design's positions.
- #[test]
- fn a_slot_among_the_shown_features_is_a_design_position() {
- let shown = [1, 4, 5];
- assert_eq!(super::design_position(&shown, 0, 7), 1);
- assert_eq!(super::design_position(&shown, 2, 7), 5);
- assert_eq!(super::design_position(&shown, 3, 7), 6);
- assert_eq!(super::design_position(&[], 0, 7), 7);
- }
-
fn copied(h: &Harness) -> Vec<String> {
h.app.session.clipboard.iter().map(|f| f.name.clone()).collect()
}
@@ -2273,6 +2447,39 @@ mod tests {
}
}
+ /// Shift+click selects every feature from the last one clicked to this one, folded chips in
+ /// between included, and keeps measuring from that feature; Ctrl+Shift+click adds the range.
+ #[test]
+ fn shift_click_selects_the_features_in_between() {
+ let mut h = Harness::new();
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ for (i, name) in ["A", "B", "C", "D", "E", "F"].into_iter().enumerate() {
+ let corner = [i as f64 * 15.0, 0.0, 0.0];
+ h.app
+ .run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": corner, "operation": "new_body", "name": name}))
+ .unwrap();
+ }
+ h.app.run("select.clear", json!({})).unwrap();
+ h.frames(4);
+ let ids =
+ |h: &Harness, names: &[&str]| -> Vec<u64> { names.iter().map(|n| h.app.session.doc.find_feature(n).map(|f| f.id).unwrap()).collect() };
+ h.step(&json!({"click": {"handle": "timeline:B"}})).unwrap();
+ h.step(&json!({"click": {"handle": "timeline:D"}, "shift": true})).unwrap();
+ assert_eq!(super::selected_feature_ids(&h.app), ids(&h, &["B", "C", "D"]));
+ h.step(&json!({"click": {"handle": "timeline:A"}, "shift": true})).unwrap();
+ assert_eq!(super::selected_feature_ids(&h.app), ids(&h, &["A", "B"]), "the range still starts at B");
+ h.step(&json!({"click": {"handle": "timeline:E"}, "shift": true, "ctrl": true})).unwrap();
+ assert_eq!(super::selected_feature_ids(&h.app), ids(&h, &["A", "B", "C", "D", "E"]), "Ctrl+Shift adds B to E");
+
+ // C and D folded into a folder chip: a range across it takes them too.
+ h.app.run("timeline.group", json!({"name": "Pair", "features": ["C", "D"]})).unwrap();
+ h.frames(2);
+ assert!(crate::scenario::handle_at("timeline:C").is_none(), "C and D are folded");
+ h.step(&json!({"click": {"handle": "timeline:B"}})).unwrap();
+ h.step(&json!({"click": {"handle": "timeline:F"}, "shift": true})).unwrap();
+ assert_eq!(super::selected_feature_ids(&h.app), ids(&h, &["B", "C", "D", "E", "F"]));
+ }
+
/// Copy on a feature outside the selection copies that feature alone.
#[test]
fn copy_on_an_unselected_feature_copies_only_it() {
@@ -2556,4 +2763,286 @@ mod tests {
}
}
}
+
+ /// Boxes named `names`, in that order, nothing selected.
+ fn boxes(names: &[&str]) -> Harness {
+ let mut h = Harness::new();
+ for (i, name) in names.iter().enumerate() {
+ let corner = [20.0 * i as f64, 0.0, 0.0];
+ h.app.run("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": corner, "operation": "new_body", "name": name})).unwrap();
+ }
+ h.app.run("select.clear", json!({})).unwrap();
+ h.frames(4);
+ h
+ }
+
+ /// Each folder's name and its features' names.
+ fn folders(h: &Harness) -> Vec<(String, Vec<String>)> {
+ let doc = &h.app.session.doc;
+ let name = |id: &u64| doc.feature(*id).map(|f| f.name.clone()).unwrap_or_default();
+ doc.timeline_groups.iter().map(|g| (g.name.clone(), g.features.iter().map(name).collect())).collect()
+ }
+
+ fn folder_names(h: &Harness, list: &[(&str, &[&str])]) -> bool {
+ folders(h) == list.iter().map(|(n, f)| (n.to_string(), f.iter().map(|x| x.to_string()).collect())).collect::<Vec<_>>()
+ }
+
+ /// Whether the menu item `label` on screen is shown off.
+ fn disabled(h: &Harness, label: &str) -> Option<bool> {
+ let tree = h.output.accesskit_update.as_ref()?;
+ tree.nodes
+ .iter()
+ .rev()
+ .find(|(_, n)| n.label().is_some_and(|l| l == label || l.starts_with(&format!("{label} "))))
+ .map(|(_, n)| n.is_disabled())
+ }
+
+ /// Group Features in a feature's menu folds the selected features, or the one right-clicked
+ /// when it isn't selected, into one folded chip whose name is typed next, in one undo step.
+ /// Features apart in the history can't be grouped: the item is shown off.
+ #[test]
+ fn group_features_in_the_feature_menu_makes_one_folded_chip() {
+ use crate::scenario::handle_at;
+ let mut h = boxes(&["A", "B", "C", "D", "E"]);
+ h.step(&json!({"click": {"handle": "timeline:A"}})).unwrap();
+ h.step(&json!({"click": {"handle": "timeline:C"}, "ctrl": true})).unwrap();
+ h.step(&json!({"click": {"handle": "timeline:C"}, "button": "right"})).unwrap();
+ assert_eq!(disabled(&h, "Group Features"), Some(true), "A and C are apart");
+ // The control channel's report of the menu says why too.
+ let group_item = |h: &mut Harness| {
+ let menu = h.call("ui.menu", json!({}))["result"].clone();
+ menu["items"].as_array().into_iter().flatten().find(|i| i["id"] == "ui.groupFeatures").cloned().unwrap_or_default()
+ };
+ let item = group_item(&mut h);
+ assert_eq!(item["enabled"], false, "{item}");
+ assert!(item["tip"].as_str().is_some_and(|t| !t.is_empty()), "{item}");
+ h.step(&json!({"widget": "Group Features"})).unwrap();
+ assert!(h.app.session.doc.timeline_groups.is_empty());
+ h.step(&json!({"key": "Escape"})).unwrap();
+
+ // One feature: the one right-clicked, not the selection.
+ h.step(&json!({"click": {"handle": "timeline:E"}, "button": "right"})).unwrap();
+ assert_eq!(disabled(&h, "Group Features"), Some(false));
+ assert!(group_item(&mut h)["tip"].is_null(), "on, it gives no reason");
+ let undo = h.app.session.undo.len();
+ h.step(&json!({"widget": "Group Features"})).unwrap();
+ assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step");
+ assert!(
+ matches!(h.app.menu.rename.as_ref().map(|r| &r.what), Some(crate::context_menu::RenameWhat::TimelineGroup(_))),
+ "its name is typed next"
+ );
+ h.step(&json!({"text": "Solo"})).unwrap();
+ h.step(&json!({"key": "Enter"})).unwrap();
+ assert!(folder_names(&h, &[("Solo", &["E"])]), "{:?}", folders(&h));
+ assert!(handle_at("timeline:E").is_none() && handle_at("timeline-folder-chip:Solo").is_some(), "folded into its chip");
+
+ // Several selected features.
+ h.step(&json!({"click": {"handle": "timeline:C"}})).unwrap();
+ h.step(&json!({"click": {"handle": "timeline:D"}, "ctrl": true})).unwrap();
+ h.step(&json!({"click": {"handle": "timeline:D"}, "button": "right"})).unwrap();
+ h.step(&json!({"widget": "Group Features"})).unwrap();
+ h.step(&json!({"text": "Pair"})).unwrap();
+ h.step(&json!({"key": "Enter"})).unwrap();
+ assert!(folder_names(&h, &[("Solo", &["E"]), ("Pair", &["C", "D"])]), "{:?}", folders(&h));
+ assert!(handle_at("timeline:C").is_none() && handle_at("timeline:D").is_none() && handle_at("timeline:B").is_some());
+ }
+
+ /// A folder's chip opens and folds with a click or its menu, which also renames it, selects
+ /// its features and ungroups it. Opened or folded in either History, both show it so.
+ #[test]
+ fn a_folder_chip_opens_renames_ungroups_and_both_histories_agree() {
+ use crate::scenario::handle_at;
+ let mut h = boxes(&["A", "B", "C"]);
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ h.app.run("timeline.group", json!({"name": "Pair", "features": ["A", "B"]})).unwrap();
+ h.frames(2);
+ assert!(handle_at("timeline:A").is_none(), "a folder starts folded");
+ h.step(&json!({"click": {"handle": "timeline-folder-chip:Pair"}})).unwrap();
+ assert!(handle_at("timeline:A").is_some() && handle_at("timeline:B").is_some(), "a click shows each feature");
+
+ // Folded in the History beside the browser, it is folded here too, and the other way.
+ h.app.preferences.timeline_left = true;
+ h.frames(4);
+ assert!(handle_at("timeline:A").is_some(), "open there too");
+ h.step(&json!({"click": {"handle": "timeline-folder-fold:Pair"}})).unwrap();
+ assert!(handle_at("timeline:A").is_none());
+ h.app.preferences.timeline_left = false;
+ h.frames(4);
+ assert!(handle_at("timeline:A").is_none() && handle_at("timeline-folder-chip:Pair").is_some(), "folded here too");
+ h.step(&json!({"click": {"handle": "timeline-folder-chip:Pair"}})).unwrap();
+ h.app.preferences.timeline_left = true;
+ h.frames(4);
+ assert!(handle_at("timeline:A").is_some(), "opened here, open there");
+ h.app.preferences.timeline_left = false;
+ h.frames(4);
+
+ let menu = |h: &mut Harness, name: &str, item: &str| {
+ h.step(&json!({"click": {"handle": format!("timeline-folder-chip:{name}")}, "button": "right"})).unwrap();
+ h.step(&json!({"widget": item})).unwrap();
+ };
+ menu(&mut h, "Pair", "Fold Features");
+ assert!(handle_at("timeline:A").is_none());
+ menu(&mut h, "Pair", "Show Each Feature");
+ assert!(handle_at("timeline:A").is_some());
+ menu(&mut h, "Pair", "Rename");
+ h.step(&json!({"text": "Renamed"})).unwrap();
+ h.step(&json!({"key": "Enter"})).unwrap();
+ assert!(folder_names(&h, &[("Renamed", &["A", "B"])]), "{:?}", folders(&h));
+ menu(&mut h, "Renamed", "Select Features");
+ let ids: Vec<u64> = ["A", "B"].iter().map(|n| h.app.session.doc.find_feature(n).unwrap().id).collect();
+ assert_eq!(super::selected_feature_ids(&h.app), ids);
+ menu(&mut h, "Renamed", "Ungroup");
+ assert!(h.app.session.doc.timeline_groups.is_empty());
+ assert!(handle_at("timeline:A").is_some() && handle_at("timeline-folder-chip:Renamed").is_none());
+ }
+
+ /// The marker rolled into a folded folder waits after its chip, and dragged onto the chip it
+ /// goes before it; a feature dropped on the folded chip goes before it too, and dropped
+ /// between an open folder's features it joins the folder.
+ #[test]
+ fn the_marker_and_a_dropped_feature_go_around_a_folded_folder() {
+ use crate::scenario::{handle_at, rect_of};
+ let mut h = boxes(&["A", "B", "C", "D"]);
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ h.app.run("timeline.group", json!({"name": "Mid", "features": ["B", "C"]})).unwrap();
+ h.app.run("timeline.roll_to", json!({"position": 2})).unwrap();
+ h.frames(2);
+ let chip = rect_of("timeline-folder-chip:Mid").unwrap();
+ let marker = rect_of("history:marker").unwrap();
+ assert!(marker.left() > chip.right(), "the marker waits after the folded chip: {marker:?} {chip:?}");
+ let y = chip.center().y;
+ h.step(&json!({"drag": [[marker.center().x, marker.center().y], [chip.left() + 2.0, y]]})).unwrap();
+ h.settle();
+ assert_eq!(h.app.session.doc.marker, Some(1), "dropped on the chip, the marker goes before the folder");
+
+ h.app.run("timeline.roll_to", json!({})).unwrap();
+ h.frames(2);
+ let d = handle_at("timeline:D").unwrap();
+ let chip = rect_of("timeline-folder-chip:Mid").unwrap();
+ h.step(&json!({"drag": [[d.x, d.y], [chip.left() + 2.0, y]]})).unwrap();
+ h.settle();
+ let order: Vec<&str> = h.app.session.doc.features.iter().map(|f| f.name.as_str()).collect();
+ assert_eq!(order, ["A", "D", "B", "C"]);
+ assert!(folder_names(&h, &[("Mid", &["B", "C"])]), "{:?}", folders(&h));
+
+ h.step(&json!({"click": {"handle": "timeline-folder-chip:Mid"}})).unwrap();
+ let (a, b, c) = (handle_at("timeline:A").unwrap(), handle_at("timeline:B").unwrap(), handle_at("timeline:C").unwrap());
+ h.step(&json!({"drag": [[a.x, a.y], [(b.x + c.x) / 2.0, y]]})).unwrap();
+ h.settle();
+ let order: Vec<&str> = h.app.session.doc.features.iter().map(|f| f.name.as_str()).collect();
+ assert_eq!(order, ["D", "B", "A", "C"]);
+ assert!(folder_names(&h, &[("Mid", &["B", "A", "C"])]), "dropped inside the open folder, it joins it: {:?}", folders(&h));
+ }
+
+ /// A STEP file that brings more than one item into the history (here one cylinder placed
+ /// twice) shows as one folded chip named Group #1, holding its Import feature and the rigid
+ /// joints that keep its parts in place (grouped as one button, which shows each joint); the
+ /// joints chip after the history leaves them out. A file with one object shows its Import
+ /// feature as before.
+ #[test]
+ fn a_multi_object_step_insert_shows_as_one_chip() {
+ use crate::scenario::{handle_at, handles};
+ let corpus = |name: &str| format!("{}/../../tests/step-conformance/{name}.step", env!("CARGO_MANIFEST_DIR"));
+ let mut h = Harness::new();
+ assert_eq!(h.call("ui.prefs", json!({"history_group_joints": true}))["ok"], true);
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ let one = h.app.run("file.insert_step", json!({"path": corpus("cylinder")})).unwrap();
+ let two = h.app.run("file.insert_step", json!({"path": corpus("cylinder_twice"), "folder": true})).unwrap();
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.frames(4);
+ let feature = |r: &serde_json::Value| r["name"].as_str().unwrap().to_string();
+ assert!(handle_at(&format!("timeline:{}", feature(&one))).is_some(), "one object: its Import feature as before");
+ assert_eq!(handles("timeline-folder-chip:").len(), 1, "only the second insert is a folder");
+ assert!(handle_at("timeline-folder-chip:Group #1").is_some(), "{two}");
+ assert!(handle_at(&format!("timeline:{}", feature(&two))).is_none(), "the Import feature is folded into the chip");
+ let joints = h.app.session.doc.assembly.joints.len();
+ assert_eq!(joints, 2, "a rigid joint per placement");
+ assert!(handles("timeline-joint:").is_empty() && handle_at("timeline:joints").is_none(), "its joints are in its chip");
+
+ h.step(&json!({"click": {"handle": "timeline-folder-chip:Group #1"}})).unwrap();
+ let import = handle_at(&format!("timeline:{}", feature(&two))).expect("open, the Import feature shows");
+ let group = handle_at("timeline-folder-joints:Group #1").expect("and its two joints after it, as one button");
+ assert!(group.x > import.x && handles("timeline-joint:").is_empty());
+ h.step(&json!({"click": {"handle": "timeline-folder-joints:Group #1"}})).unwrap();
+ let shown = handles("timeline-joint:");
+ assert_eq!(shown.len(), joints, "the button shows each joint");
+ assert!(shown.iter().all(|(_, at)| at.x > import.x));
+ }
+
+ /// A STEP folder's joints, shown one by one, stay shown in their own design only: another
+ /// design's `Group #1`, numbered the same, keeps its joints grouped, and the first design
+ /// shows them again when its tab comes back.
+ #[test]
+ fn a_step_folders_shown_joints_stay_with_their_design() {
+ use crate::scenario::{handle_at, handles};
+ let corpus = |name: &str| format!("{}/../../tests/step-conformance/{name}.step", env!("CARGO_MANIFEST_DIR"));
+ let mut h = Harness::new();
+ assert_eq!(h.call("ui.prefs", json!({"history_group_joints": true}))["ok"], true);
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ let insert = |h: &mut Harness| {
+ let reply = h.app.run("file.insert_step", json!({"path": corpus("cylinder_twice"), "folder": true})).unwrap();
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.frames(4);
+ h.step(&json!({"click": {"handle": "timeline-folder-chip:Group #1"}})).unwrap();
+ reply["group"].clone()
+ };
+ let first = insert(&mut h);
+ h.step(&json!({"click": {"handle": "timeline-folder-joints:Group #1"}})).unwrap();
+ assert_eq!(handles("timeline-joint:").len(), 2, "shown one by one in the first design");
+
+ crate::documents::new_design(&mut h.app);
+ assert_eq!(h.app.docs.active, 1, "the second design has a tab of its own");
+ let second = insert(&mut h);
+ assert_eq!(first, second, "both designs number their folder the same");
+ assert!(handle_at("timeline-folder-joints:Group #1").is_some(), "the second design's folder is open");
+ assert!(handles("timeline-joint:").is_empty(), "and its joints stay grouped");
+
+ crate::documents::switch(&mut h.app, 0);
+ h.frames(4);
+ assert_eq!(handles("timeline-joint:").len(), 2, "back in the first design, they show one by one again");
+ }
+
+ /// With "Fold the History bar into groups" off, as it is by default, the bar shows each feature
+ /// as it always has: a long run of one component's features doesn't fold, a feature folder
+ /// starts open (a click still folds it), and a STEP assembly the app inserts gets no `Group #N`
+ /// folder. Turned on, the run folds and the app's insert makes one; turned off again, each
+ /// feature shows.
+ #[test]
+ fn with_its_groups_off_the_bar_shows_each_feature_and_a_step_insert_makes_no_folder() {
+ use crate::scenario::handle_at;
+ let corpus = |name: &str| format!("{}/../../tests/step-conformance/{name}.step", env!("CARGO_MANIFEST_DIR"));
+ let mut h = Harness::new();
+ assert!(!h.app.preferences.history_bar_groups, "the bar's groups are off by default");
+ h.app.run("component.create", json!({"name": "Rig"})).unwrap();
+ for i in 0..crate::timeline_fold::FOLD_FROM {
+ h.app.run("sketch.create", json!({"plane": "XY", "name": format!("S{i}")})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ }
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.app.run("timeline.group", json!({"name": "Pair", "features": ["S0", "S1"]})).unwrap();
+ h.frames(4);
+ assert!(handle_at("timeline-group:Rig").is_none(), "no run folds");
+ assert!(handle_at("timeline-folder-chip:Pair").is_some(), "the folder's chip");
+ assert!(handle_at("timeline:S0").is_some() && handle_at("timeline:S49").is_some(), "each feature shows, the folder's too");
+ h.step(&json!({"click": {"handle": "timeline-folder-chip:Pair"}})).unwrap();
+ assert!(handle_at("timeline:S0").is_none() && handle_at("timeline:S2").is_some(), "a click still folds the folder");
+
+ h.app.insert_path(&corpus("cylinder_twice"));
+ let (v, _) = h.call_queued("engine.execute", json!({"command": "file.insert_step", "params": {"path": corpus("cylinder_twice")}}));
+ assert_eq!(v["ok"], true, "{v}");
+ let names: Vec<&str> = h.app.session.doc.timeline_groups.iter().map(|g| g.name.as_str()).collect();
+ assert_eq!(names, ["Pair"], "neither insert made a folder");
+ assert_eq!(h.app.session.doc.assembly.joints.len(), 4, "their rigid joints are there all the same");
+
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": true}))["ok"], true);
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.frames(4);
+ assert!(handle_at("timeline-group:Rig").is_some(), "turned on, the run folds");
+ h.app.insert_path(&corpus("cylinder_twice"));
+ let names: Vec<&str> = h.app.session.doc.timeline_groups.iter().map(|g| g.name.as_str()).collect();
+ assert!(names.contains(&"Group #1"), "turned on, the app's insert asks for a folder: {names:?}");
+ assert_eq!(h.call("ui.prefs", json!({"history_bar_groups": false}))["ok"], true);
+ h.frames(4);
+ assert!(handle_at("timeline-group:Rig").is_none() && handle_at("timeline:S49").is_some(), "off again, each feature shows");
+ }
}
diff --git a/crates/ui-egui/src/timeline_fold.rs b/crates/ui-egui/src/timeline_fold.rs
new file mode 100644
index 0000000000..d9ae2c492a
--- /dev/null
+++ b/crates/ui-egui/src/timeline_fold.rs
@@ -0,0 +1,689 @@
+//! A long History bar folds each long run of one component's features into one chip with the
+//! component's name and the number of features: a 2000-part assembly shows one chip for its top
+//! component, which opens to a chip per subassembly, and so on down to the features. Clicking a
+//! chip shows its features one by one, and clicking it again folds them (the choice belongs to the
+//! design, `history_folds`). Until then, a run that holds the history marker or the component being
+//! edited or picked is shown open.
+//!
+//! An open run or folder shows its items inside a tray drawn from its chip to its last item,
+//! nested trays inside it. A run that holds runs which fold in turn (a subassembly's) is deep:
+//! clicking it shows only its component's features instead (`timeline_scope`), so a 2000-part
+//! assembly never fills the bar with every subassembly's chip at once.
+//!
+//! While the bar shows one component's features (`timeline_scope`), the fold reads only those,
+//! from the components inside it down; the entries count the shown features (`View`).
+//!
+//! Feature folders (`timeline_folders`) come first: each folder is its own chip whatever the
+//! history's length, and its features never join a run outside it. The component fold then
+//! applies to the features outside folders and to those of an open folder, between the folders
+//! in it, as it does to the whole history.
+use crate::ui_kit::BackingTooltipExt as _;
+use std::collections::{HashMap, HashSet};
+
+use serde_json::json;
+use solidcraft_engine::Sel;
+use solidcraft_engine::doc::Component;
+
+use crate::SolveApp;
+use crate::theme::TabAccent;
+use crate::timeline_folders::Span;
+use crate::ui_kit::HistoryGroupChip;
+
+/// A history with no more features than this never folds: it still fits a window's width.
+pub(crate) const FOLD_FROM: usize = 50;
+/// A run of more features than this, all inside one component, folds into one chip.
+pub(crate) const FOLD_MIN: usize = 6;
+/// Folds go no deeper than this many nested components; deeper runs show their features.
+const FOLD_DEPTH_MAX: usize = 16;
+/// The browser-state key prefix that remembers a run was opened or folded.
+pub(crate) const KEY: &str = "timeline_component:";
+
+/// A run of features in one component, shown as one chip.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct Group {
+ pub component: u64,
+ /// The run's features, by their index in the history.
+ pub start: usize,
+ pub end: usize,
+ /// How many open chips (runs and folders) hold this one.
+ pub depth: usize,
+ pub open: bool,
+ /// It holds runs that fold in turn: a click shows only its component's features
+ /// (`timeline_scope`).
+ pub deep: bool,
+}
+
+/// A feature folder, shown as one chip.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct Folder {
+ pub id: u64,
+ /// Its features and its folders', by their index in the history; an empty folder's start
+ /// and end are where it sits.
+ pub start: usize,
+ pub end: usize,
+ /// How many open chips hold this one.
+ pub depth: usize,
+ pub open: bool,
+}
+
+/// What the History bar draws, in order: features, folded runs and folders, the joints of an
+/// open folder, and the end of each open run or folder.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Entry {
+ Feature(usize),
+ Group(Group),
+ Folder(Folder),
+ /// The joints an open folder holds (an import's rigid group).
+ Joints(u64),
+ /// What the open run or folder at this depth holds came before.
+ End(usize),
+}
+
+/// What a feature's chip would show that its run's chip shows while folded.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct Marks {
+ pub selected: bool,
+ pub hovered: bool,
+ pub error: bool,
+ pub warning: bool,
+}
+
+/// The History bar's entries for one frame, with what each feature's chip would show. Entries,
+/// runs and folders count the features the bar shows (`view`), not the design's.
+pub(crate) struct History {
+ pub entries: Vec<Entry>,
+ /// By the bar's feature; empty when nothing folds.
+ marks: Vec<Marks>,
+ pub folders: crate::timeline_folders::Folders,
+ pub view: View,
+ /// The component whose features the bar shows (`timeline_scope`); none for the whole design.
+ pub within: Option<u64>,
+}
+
+/// Which of the design's features the History bar shows: all of them, or those of one component
+/// and the components inside it, without the components marked out of the bar (#10393). A slot
+/// among the shown features maps back to a position in the design: just before the shown
+/// feature there, or just after the last one shown.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) struct View {
+ /// The shown features' indices in the design, in order; none when all are shown.
+ shown: Option<Vec<usize>>,
+ /// How many features the design has.
+ n: usize,
+}
+
+impl View {
+ /// The features of the components in `within`, or all of them, leaving out those of the
+ /// components marked out of the History bar unless `show_hidden` asks for them (#10393).
+ pub(crate) fn of(doc: &solidcraft_engine::doc::Document, within: Option<&HashSet<u64>>, show_hidden: bool) -> Self {
+ let hides = !show_hidden && doc.components.iter().any(|c| c.history_hidden);
+ let shown = (within.is_some() || hides).then(|| {
+ doc.features
+ .iter()
+ .enumerate()
+ .filter(|(_, f)| within.is_none_or(|w| w.contains(&f.component)))
+ .filter(|(_, f)| !hides || !doc.component_history_hidden(f.component))
+ .map(|(i, _)| i)
+ .collect()
+ });
+ Self { shown, n: doc.features.len() }
+ }
+
+ /// How many features the bar shows.
+ pub(crate) fn len(&self) -> usize {
+ self.shown.as_ref().map_or(self.n, Vec::len)
+ }
+
+ /// The design's position of the bar's slot `k`, the one before its feature `k`; past its last
+ /// feature, the position just after it.
+ pub(crate) fn index(&self, k: usize) -> usize {
+ match &self.shown {
+ None => k.min(self.n),
+ Some(shown) => shown.get(k).copied().unwrap_or_else(|| shown.last().map_or(self.n, |i| i + 1)),
+ }
+ }
+
+ /// The bar's slot of the design's position `at`: before the first shown feature at or after it.
+ pub(crate) fn slot(&self, at: usize) -> usize {
+ match &self.shown {
+ None => at.min(self.n),
+ Some(shown) => shown.partition_point(|&i| i < at),
+ }
+ }
+
+ /// Where the bar shows the design's feature `at`, if it does.
+ pub(crate) fn find(&self, at: usize) -> Option<usize> {
+ match &self.shown {
+ None => (at < self.n).then_some(at),
+ Some(shown) => shown.binary_search(&at).ok(),
+ }
+ }
+
+ /// The shown features' indices in the design, ascending; none when the bar shows them all.
+ pub(crate) fn shown(&self) -> Option<&[usize]> {
+ self.shown.as_deref()
+ }
+
+ /// The design's indices of the bar's features `start..end`.
+ pub(crate) fn indices(&self, start: usize, end: usize) -> Vec<usize> {
+ (start..end.min(self.len())).map(|k| self.index(k)).collect()
+ }
+
+ /// Folders as the bar counts their features; a folder holding none of the shown features is
+ /// left out, unless it or a folder in it holds joints: joints show whichever component the
+ /// bar shows, so such a folder stays, empty, where its features would be.
+ fn spans(&self, spans: &[Span]) -> Vec<Span> {
+ if self.shown.is_none() {
+ return spans.to_vec();
+ }
+ spans
+ .iter()
+ .filter_map(|s| {
+ let (start, end) = (self.slot(s.start), self.slot(s.end));
+ let children = self.spans(&s.children);
+ (start < end || s.joints > 0 || !children.is_empty()).then_some(Span { id: s.id, start, end, joints: s.joints, children })
+ })
+ .collect()
+ }
+}
+
+/// Where the History bar is drawn and what is under the pointer.
+pub(crate) struct Strip {
+ /// The history marker's position.
+ pub marker: usize,
+ /// The features that made what is under the pointer and what is picked in the viewport.
+ pub from_view: [Option<u64>; 2],
+ /// The floating History card, which also accents the last feature before the marker.
+ pub floating: bool,
+ pub accent: TabAccent,
+}
+
+/// Each component's chain of parents below the root, outermost first, ending with itself and
+/// cut after the outermost `FOLD_DEPTH_MAX` (no fold reads deeper). A parent that isn't there or
+/// a loop of parents (a damaged design) ends the chain. Each component is walked once.
+fn chains(components: &[Component]) -> HashMap<u64, Vec<u64>> {
+ let parent: HashMap<u64, u64> = components.iter().map(|c| (c.id, c.parent)).collect();
+ let mut done: HashMap<u64, Vec<u64>> = HashMap::with_capacity(components.len());
+ for component in components {
+ let mut path = Vec::new();
+ let mut seen = HashSet::new();
+ let mut at = component.id;
+ while at != 0 && !done.contains_key(&at) && seen.insert(at) {
+ path.push(at);
+ at = parent.get(&at).copied().unwrap_or(0);
+ }
+ let mut chain = done.get(&at).cloned().unwrap_or_default();
+ for id in path.into_iter().rev() {
+ if chain.len() < FOLD_DEPTH_MAX {
+ chain.push(id);
+ }
+ done.insert(id, chain.clone());
+ }
+ }
+ done
+}
+
+/// Says whether a fold is shown open: a run of `component`'s features (`start..end`), deep or
+/// not, or a folder.
+pub(crate) trait Opens {
+ fn run(&mut self, component: u64, start: usize, end: usize, deep: bool) -> bool;
+ fn folder(&mut self, id: u64) -> bool;
+}
+
+/// The entries for `n` features in `folders`, whose components have these chains (`chains[i]`
+/// for feature `i`; none when the component fold is off).
+pub(crate) fn entries(n: usize, chains: &[&[u64]], folders: &[Span], open: &mut dyn Opens) -> Vec<Entry> {
+ let mut out = Vec::with_capacity(n);
+ let fold = Fold { chains: if n > FOLD_FROM { chains } else { &[] } };
+ fold.folders(0, n, folders, 0, open, &mut out);
+ out
+}
+
+/// The component chains the component fold reads (empty: it is off).
+struct Fold<'a> {
+ chains: &'a [&'a [u64]],
+}
+
+impl Fold<'_> {
+ /// Features `start..end`, holding `folders` (in order), at `depth` open chips deep.
+ fn folders(&self, start: usize, end: usize, folders: &[Span], depth: usize, open: &mut dyn Opens, out: &mut Vec<Entry>) {
+ let mut i = start;
+ for span in folders {
+ // A damaged design's folders may overlap: each feature still shows once, in order.
+ let from = span.start.max(i).min(end);
+ let to = span.end.max(from).min(end);
+ self.runs(i, from, 0, depth, open, out);
+ let shown = open.folder(span.id);
+ out.push(Entry::Folder(Folder { id: span.id, start: from, end: to, depth, open: shown }));
+ if shown {
+ self.folders(from, to, &span.children, depth + 1, open, out);
+ if span.joints > 0 {
+ out.push(Entry::Joints(span.id));
+ }
+ out.push(Entry::End(depth));
+ }
+ i = to;
+ }
+ self.runs(i, end, 0, depth, open, out);
+ }
+
+ /// Feature `i`'s component at chain `level`: none at the root or past the deepest level.
+ fn at(&self, i: usize, level: usize) -> Option<u64> {
+ if level < FOLD_DEPTH_MAX { self.chains.get(i).and_then(|c| c.get(level)).copied() } else { None }
+ }
+
+ /// The end of the run of one component at chain `level` that starts at feature `start`.
+ fn run_end(&self, start: usize, end: usize, level: usize) -> usize {
+ let component = self.at(start, level);
+ (start + 1..end).find(|&j| self.at(j, level) != component).unwrap_or(end)
+ }
+
+ /// Whether features `start..end` hold a run that folds at chain `level`.
+ fn folds(&self, start: usize, end: usize, level: usize) -> bool {
+ let mut i = start;
+ while i < end {
+ let j = self.run_end(i, end, level);
+ if self.at(i, level).is_some() && j - i > FOLD_MIN {
+ return true;
+ }
+ i = j;
+ }
+ false
+ }
+
+ /// Features `start..end`, folding long runs of one component at chain `level`.
+ fn runs(&self, start: usize, end: usize, level: usize, depth: usize, open: &mut dyn Opens, out: &mut Vec<Entry>) {
+ let mut i = start;
+ while i < end {
+ let j = self.run_end(i, end, level);
+ match self.at(i, level) {
+ Some(component) if j - i > FOLD_MIN => {
+ let deep = self.folds(i, j, level + 1);
+ let shown = open.run(component, i, j, deep);
+ out.push(Entry::Group(Group { component, start: i, end: j, depth, open: shown, deep }));
+ if shown {
+ self.runs(i, j, level + 1, depth + 1, open, out);
+ out.push(Entry::End(depth));
+ }
+ }
+ _ => out.extend((i..j).map(Entry::Feature)),
+ }
+ i = j;
+ }
+ }
+}
+
+/// The key that remembers a run's choice: its component and its first feature (`first`, by its
+/// index in the design), so two runs of one component apart in the history fold on their own.
+fn key(app: &SolveApp, component: u64, first: usize) -> String {
+ let first = app.session.doc.features.get(first).map_or(0, |f| f.id);
+ format!("{KEY}{component}:{first}")
+}
+
+/// Whether a run is shown one by one: as last clicked, else `unless_clicked`.
+fn is_open(app: &SolveApp, key: &str, unless_clicked: bool) -> bool {
+ crate::history_folds::is_open(app, key, unless_clicked)
+}
+
+fn set_open(app: &mut SolveApp, key: &str, open: bool) {
+ crate::history_folds::set_open(app, key, open);
+}
+
+/// What the History bar shows of the design's features this frame: the whole history, or the
+/// features of one component and those inside it (`timeline_scope`).
+pub(crate) fn history(app: &SolveApp, strip: &Strip) -> History {
+ let doc = &app.session.doc;
+ let within = crate::timeline_scope::shown(app);
+ let view = View::of(doc, within.map(|c| crate::timeline_scope::components_within(app, c)).as_ref(), app.tree.history_show_hidden);
+ let n = view.len();
+ // Off, the bar shows each feature and starts folders open, as it did before (Preferences >
+ // Layout, "Fold the History bar into groups").
+ let folds = n > FOLD_FROM && app.preferences.history_bar_groups;
+ if !folds && doc.timeline_groups.is_empty() {
+ return History { entries: (0..n).map(Entry::Feature).collect(), marks: Vec::new(), folders: Default::default(), view, within };
+ }
+ let folders = crate::timeline_folders::Folders::of(doc);
+ let spans = view.spans(&folders.spans);
+ let chains = chains(&doc.components);
+ let of = |c: u64| chains.get(&c).map_or(&[][..], Vec::as_slice);
+ // Inside a component, runs fold by the components inside it.
+ let level = within.map_or(0, |c| of(c).len());
+ let per_feature: Vec<&[u64]> = if folds {
+ let chain = |i: usize| doc.features.get(i).and_then(|f| of(f.component).get(level..)).unwrap_or_default();
+ view.indices(0, n).into_iter().map(chain).collect()
+ } else {
+ Vec::new()
+ };
+ let focus = crate::timeline_scope::focus(app);
+ let mut on_the_way = HashSet::new();
+ // The way to the edited or picked component opens, while the bar shows more than it.
+ if let Some(focus) = focus.filter(|f| within != Some(*f)) {
+ let mine = crate::timeline_scope::components_within(app, focus);
+ if let Some(last) = doc.features.iter().rposition(|f| mine.contains(&f.component)).and_then(|i| view.find(i)) {
+ folders_holding(&spans, last, &mut on_the_way);
+ }
+ }
+ let mut open = Shown { app, view: &view, marker: view.slot(strip.marker), focus: focus.map_or(&[][..], of), folders: on_the_way };
+ let entries = entries(n, &per_feature, &spans, &mut open);
+ History { entries, marks: marks(app, strip, &view), folders, view, within }
+}
+
+/// The folders whose features hold feature `at`, at any depth.
+fn folders_holding(spans: &[Span], at: usize, out: &mut HashSet<u64>) {
+ for span in spans.iter().filter(|s| s.start <= at && at < s.end) {
+ out.insert(span.id);
+ folders_holding(&span.children, at, out);
+ }
+}
+
+/// Which folds the History bar shows open: the runs on the way to the component being edited or
+/// picked, and the folders holding its last feature; the rest as last clicked, and until then a
+/// run that holds the marker. A deep run elsewhere stays folded: a click on it shows only its
+/// component's features.
+struct Shown<'a> {
+ app: &'a SolveApp,
+ view: &'a View,
+ /// The marker's slot among the shown features.
+ marker: usize,
+ /// The edited or picked component and those around it.
+ focus: &'a [u64],
+ /// The folders on the way to it.
+ folders: HashSet<u64>,
+}
+
+impl Opens for Shown<'_> {
+ fn run(&mut self, component: u64, start: usize, end: usize, deep: bool) -> bool {
+ let on_the_way = self.focus.contains(&component);
+ if deep {
+ return on_the_way;
+ }
+ let unless_clicked = (start < self.marker && self.marker < end) || on_the_way;
+ is_open(self.app, &key(self.app, component, self.view.index(start)), unless_clicked)
+ }
+
+ fn folder(&mut self, id: u64) -> bool {
+ let unless_clicked = self.folders.contains(&id) || !self.app.preferences.history_bar_groups;
+ crate::timeline_folders::is_open(self.app, id, unless_clicked)
+ }
+}
+
+/// Each feature's marks, reading the results and the selection once.
+fn marks(app: &SolveApp, strip: &Strip, view: &View) -> Vec<Marks> {
+ let flags: HashMap<u64, (bool, bool)> = app.session.model.results.iter().map(|r| (r.id, (r.error.is_some(), r.warning.is_some()))).collect();
+ let in_dialog = app.dialog.as_ref().map(|d| d.items()).unwrap_or_default();
+ let picked: HashSet<u64> = app
+ .session
+ .selection
+ .iter()
+ .chain(in_dialog.iter())
+ .filter_map(|s| match s {
+ Sel::Feature { id } => Some(*id),
+ _ => None,
+ })
+ .collect();
+ let last_done = strip.marker.checked_sub(1).filter(|_| strip.floating);
+ let features = &app.session.doc.features;
+ view.indices(0, view.len())
+ .into_iter()
+ .filter_map(|i| features.get(i).map(|f| (i, f)))
+ .map(|(i, f)| {
+ let (error, warning) = flags.get(&f.id).copied().unwrap_or_default();
+ Marks { selected: picked.contains(&f.id) || last_done == Some(i), hovered: strip.from_view.contains(&Some(f.id)), error, warning }
+ })
+ .collect()
+}
+
+impl History {
+ /// The marks a chip for features `start..end` shows: any of its features' (selected only
+ /// while it is folded).
+ pub(crate) fn inside(&self, start: usize, end: usize, open: bool) -> Marks {
+ let marks = self.marks.get(start..end).unwrap_or_default();
+ Marks {
+ selected: !open && marks.iter().any(|m| m.selected),
+ hovered: marks.iter().any(|m| m.hovered),
+ error: marks.iter().any(|m| m.error),
+ warning: marks.iter().any(|m| m.warning),
+ }
+ }
+}
+
+/// The name a run's chip shows: its component's.
+pub(crate) fn name(app: &SolveApp, component: u64) -> String {
+ app.session.doc.components.iter().find(|c| c.id == component).map_or_else(|| format!("Component {component}"), |c| c.name.clone())
+}
+
+/// Draws a run's chip with its top left at `at`; a click shows its features one by one or folds
+/// them again (a deep run shows only its component's features), and its menu also selects them
+/// or rolls the marker after them. Returns its width.
+pub(crate) fn group_chip(
+ app: &mut SolveApp,
+ ui: &mut egui::Ui,
+ p: &egui::Painter,
+ at: egui::Pos2,
+ group: &Group,
+ history: &History,
+ strip: &Strip,
+) -> f32 {
+ let name = name(app, group.component);
+ let state = history.inside(group.start, group.end, group.open);
+ let chip = HistoryGroupChip {
+ icon: "component",
+ name: &name,
+ count: group.end - group.start,
+ open: group.open,
+ selected: state.selected,
+ hovered: state.hovered,
+ dim: history.view.index(group.start) >= strip.marker,
+ error: state.error,
+ warning: state.warning,
+ accent: strip.accent,
+ };
+ let rect = egui::Rect::from_min_size(at, chip.size(p));
+ let response = ui.interact(rect, ui.scope_id().with(("component_run", group.component, group.start)), egui::Sense::click());
+ crate::scenario::publish_handle(&format!("timeline-group:{name}"), rect.center());
+ chip.paint(p, rect, response.hover_pos());
+ let tip = match (group.deep, group.open) {
+ (true, _) => "click to show only its features",
+ (false, true) => "click to fold them",
+ (false, false) => "click to show each one",
+ };
+ let response = response
+ .on_hover_cursor(egui::CursorIcon::PointingHand)
+ .backing_on_hover_text(format!("{name}: {} features, {tip}", group.end - group.start));
+ if response.clicked() {
+ fold(app, group, &history.view);
+ }
+ crate::ui_kit::Menu::context(&response, |ui| group_menu(app, ui, group, &history.view));
+ rect.width()
+}
+
+/// A click on a run's chip: opens or folds it; a deep one shows only its component's features.
+fn fold(app: &mut SolveApp, group: &Group, view: &View) {
+ if group.deep {
+ crate::timeline_scope::enter(app, group.component);
+ } else {
+ let key = key(app, group.component, view.index(group.start));
+ set_open(app, &key, !group.open);
+ }
+}
+
+fn group_menu(app: &mut SolveApp, ui: &mut egui::Ui, group: &Group, view: &View) {
+ let fold_label = if group.open { "Fold Features" } else { "Show Each Feature" };
+ if crate::context_menu::button(ui, fold_label, "list").clicked() {
+ fold(app, group, view);
+ ui.close();
+ }
+ if crate::context_menu::button(ui, "Select Features", "select").clicked() {
+ let features = &app.session.doc.features;
+ let items: Vec<_> = view
+ .indices(group.start, group.end)
+ .into_iter()
+ .filter_map(|i| features.get(i))
+ .map(|f| json!({"type": "feature", "id": f.id}))
+ .collect();
+ app.tree.picked_joints.clear();
+ app.tree.picked_timeline_groups.clear();
+ let _ = app.run("select.set", json!({ "items": items }));
+ ui.close();
+ }
+ if crate::context_menu::button(ui, crate::i18n::tr_label("Roll History Marker Here"), "rollback").clicked() {
+ let end = view.index(group.end);
+ let position = if end >= app.session.doc.features.len() { json!({}) } else { json!({ "position": end }) };
+ let _ = app.run_heavy("timeline.roll_to", position);
+ ui.close();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use solidcraft_engine::doc::Component;
+
+ use super::{Entry, FOLD_DEPTH_MAX, FOLD_FROM, FOLD_MIN, Folder, Group, Opens, chains, entries};
+ use crate::timeline_folders::Span;
+
+ /// Opens the runs of these components and these folders.
+ struct Open<'a>(&'a [u64]);
+
+ impl Opens for Open<'_> {
+ fn run(&mut self, component: u64, _: usize, _: usize, _: bool) -> bool {
+ self.0.contains(&component)
+ }
+
+ fn folder(&mut self, id: u64) -> bool {
+ self.0.contains(&id)
+ }
+ }
+
+ fn run(chains: &[&[u64]], open: &[u64]) -> Vec<Entry> {
+ entries(chains.len(), chains, &[], &mut Open(open))
+ }
+
+ fn folder(id: u64, start: usize, end: usize, depth: usize, open: bool) -> Entry {
+ Entry::Folder(Folder { id, start, end, depth, open })
+ }
+
+ fn span(id: u64, start: usize, end: usize, joints: usize, children: Vec<Span>) -> Span {
+ Span { id, start, end, joints, children }
+ }
+
+ fn group(component: u64, start: usize, end: usize, depth: usize, open: bool) -> Entry {
+ Entry::Group(Group { component, start, end, depth, open, deep: false })
+ }
+
+ /// A run that holds runs folding in turn.
+ fn deep(component: u64, start: usize, end: usize, depth: usize, open: bool) -> Entry {
+ Entry::Group(Group { component, start, end, depth, open, deep: true })
+ }
+
+ fn component(id: u64, parent: u64) -> Component {
+ Component { id, name: format!("C{id}"), parent, ..Component::default() }
+ }
+
+ /// A short history shows every feature, whatever their components.
+ #[test]
+ fn a_short_history_never_folds() {
+ let chains: Vec<&[u64]> = vec![&[1u64][..]; FOLD_FROM];
+ assert_eq!(run(&chains, &[]), (0..FOLD_FROM).map(Entry::Feature).collect::<Vec<_>>());
+ }
+
+ /// Root features stay one by one; a long run inside a component folds; a short run inside
+ /// one doesn't; opening a run folds its subassemblies' runs in turn.
+ #[test]
+ fn long_runs_fold_by_component_and_open_level_by_level() {
+ let mut chains: Vec<&[u64]> = vec![&[]; 2];
+ chains.extend(vec![&[1u64, 2][..]; 30]);
+ chains.extend(vec![&[1u64, 3, 4][..]; 30]);
+ chains.push(&[1]);
+ chains.extend(vec![&[5u64][..]; FOLD_MIN]);
+ chains.push(&[]);
+ let n = chains.len();
+ let closed = run(&chains, &[]);
+ assert_eq!(closed[..2], [Entry::Feature(0), Entry::Feature(1)]);
+ assert_eq!(closed[2], deep(1, 2, 63, 0, false), "its subassemblies' runs fold too");
+ assert_eq!(closed[3..], (63..n).map(Entry::Feature).collect::<Vec<_>>()[..], "a run of {FOLD_MIN} shows each feature");
+
+ let open = run(&chains, &[1, 3]);
+ let mut expected = vec![Entry::Feature(0), Entry::Feature(1), deep(1, 2, 63, 0, true), group(2, 2, 32, 1, false), deep(3, 32, 62, 1, true)];
+ expected.push(group(4, 32, 62, 2, false));
+ expected.push(Entry::End(1));
+ expected.push(Entry::Feature(62));
+ expected.push(Entry::End(0));
+ expected.extend((63..n).map(Entry::Feature));
+ assert_eq!(open, expected);
+ }
+
+ /// Every feature appears once, in order, however deep the components nest.
+ #[test]
+ fn deep_nesting_keeps_every_feature_once_in_order() {
+ let deep: Vec<u64> = (1..=40).collect();
+ let chains: Vec<&[u64]> = vec![&deep[..]; FOLD_FROM + 10];
+ let shown = run(&chains, &deep);
+ let features: Vec<usize> = shown.iter().filter_map(|e| if let Entry::Feature(i) = e { Some(*i) } else { None }).collect();
+ assert_eq!(features, (0..chains.len()).collect::<Vec<_>>());
+ let groups = shown.iter().filter(|e| matches!(e, Entry::Group(_))).count();
+ let ends = shown.iter().filter(|e| matches!(e, Entry::End(_))).count();
+ assert_eq!(groups, FOLD_DEPTH_MAX, "folds stop at the deepest allowed level");
+ assert_eq!(ends, groups);
+ }
+
+ /// Chains run from the outermost component down; a damaged design's loops, missing parents
+ /// and very deep nesting end them without hanging.
+ #[test]
+ fn chains_survive_loops_missing_parents_and_deep_nesting() {
+ let mut components =
+ vec![component(1, 0), component(2, 1), component(3, 2), component(10, 11), component(11, 10), component(12, 12), component(20, 99)];
+ components.extend((100..5100).map(|id| component(id, if id == 100 { 0 } else { id - 1 })));
+ let chains = chains(&components);
+ assert_eq!(chains[&3], [1, 2, 3]);
+ assert!(chains[&10].contains(&10) && chains[&11].contains(&11), "a loop ends the chain");
+ assert_eq!(chains[&12], [12], "a component that is its own parent");
+ assert_eq!(chains[&20], [99, 20], "a missing parent is the outermost");
+ assert_eq!(chains[&5099], (100..100 + FOLD_DEPTH_MAX as u64).collect::<Vec<_>>(), "only the outermost levels are kept");
+ }
+
+ /// A folder is one chip whatever the history's length; open, it shows its features, its
+ /// folders folded in turn and its joints. A short history folds nothing else.
+ #[test]
+ fn folders_fold_on_their_own_and_open_level_by_level() {
+ let chains: Vec<&[u64]> = vec![&[]; 10];
+ let folders = [span(100, 2, 8, 3, vec![span(101, 4, 6, 0, vec![])]), span(102, 10, 10, 0, vec![])];
+ let closed = entries(10, &chains, &folders, &mut Open(&[]));
+ let mut expected = vec![Entry::Feature(0), Entry::Feature(1), folder(100, 2, 8, 0, false)];
+ expected.extend([8, 9].map(Entry::Feature));
+ expected.push(folder(102, 10, 10, 0, false));
+ assert_eq!(closed, expected);
+
+ let open = entries(10, &chains, &folders, &mut Open(&[100]));
+ let mut expected = vec![Entry::Feature(0), Entry::Feature(1), folder(100, 2, 8, 0, true), Entry::Feature(2), Entry::Feature(3)];
+ expected.extend([folder(101, 4, 6, 1, false), Entry::Feature(6), Entry::Feature(7), Entry::Joints(100), Entry::End(0)]);
+ expected.extend([8, 9].map(Entry::Feature));
+ expected.push(folder(102, 10, 10, 0, false));
+ assert_eq!(open, expected);
+ }
+
+ /// In a long history the component fold applies outside folders and inside an open one, but
+ /// a run never reaches across a folder's edge; the runs inside count the folder's depth.
+ #[test]
+ fn the_component_fold_runs_outside_folders_and_inside_open_ones() {
+ let chains: Vec<&[u64]> = vec![&[1u64][..]; FOLD_FROM + 20];
+ let n = chains.len();
+ let folders = [span(100, 10, 30, 0, vec![])];
+ let closed = entries(n, &chains, &folders, &mut Open(&[]));
+ assert_eq!(closed, vec![group(1, 0, 10, 0, false), folder(100, 10, 30, 0, false), group(1, 30, n, 0, false)]);
+ let open = entries(n, &chains, &folders, &mut Open(&[100]));
+ assert_eq!(
+ open,
+ vec![group(1, 0, 10, 0, false), folder(100, 10, 30, 0, true), group(1, 10, 30, 1, false), Entry::End(0), group(1, 30, n, 0, false)]
+ );
+ }
+
+ /// Folders that overlap (a damaged design) still show every feature once, in order.
+ #[test]
+ fn overlapping_folders_keep_every_feature_once_in_order() {
+ let chains: Vec<&[u64]> = vec![&[]; 20];
+ let folders = [span(1, 2, 12, 0, vec![span(3, 0, 30, 0, vec![])]), span(2, 5, 15, 0, vec![]), span(4, 40, 50, 0, vec![])];
+ let shown = entries(20, &chains, &folders, &mut Open(&[1, 2, 3, 4]));
+ let features: Vec<usize> = shown.iter().filter_map(|e| if let Entry::Feature(i) = e { Some(*i) } else { None }).collect();
+ assert_eq!(features, (0..20).collect::<Vec<_>>());
+ }
+}
diff --git a/crates/ui-egui/src/timeline_folders.rs b/crates/ui-egui/src/timeline_folders.rs
new file mode 100644
index 0000000000..9df31abeb2
--- /dev/null
+++ b/crates/ui-egui/src/timeline_folders.rs
@@ -0,0 +1,435 @@
+//! Feature folders in the History bar. Each folder shows as one chip with its name and how many
+//! items it holds; clicking it shows what it holds, and clicking again folds it. A folder is
+//! folded until it is opened, and an open folder shows the folders in it folded in turn, so they
+//! open level by level. Opening or folding a folder here or in the History beside the browser is
+//! one choice, kept with the design (`history_folds`): both show it the same way.
+//!
+//! A folder holds joints too (`timeline.group` takes them): they show after the folder's
+//! features, and the joints chip after the history shows the rest. A STEP insert puts its Import
+//! feature and the rigid joints that keep its parts where the file put them into a folder of its
+//! own, so an inserted assembly shows as one chip.
+//!
+//! How folders and the automatic component fold combine is in `timeline_fold`.
+use crate::ui_kit::BackingTooltipExt as _;
+use std::collections::{HashMap, HashSet};
+
+use serde_json::json;
+use solidcraft_engine::doc::{Document, TimelineGroup};
+
+use crate::SolveApp;
+use crate::timeline_fold::{Folder, History, Strip};
+use crate::ui_kit::HistoryGroupChip;
+
+/// The key that remembers a folder was opened or folded in its design (the History beside the
+/// browser uses it too; `history_folds`).
+pub(crate) const KEY: &str = "timeline_group:";
+/// Folders nested this deep are left out; their features show one by one.
+const DEPTH_MAX: usize = 32;
+
+fn key(id: u64) -> String {
+ format!("{KEY}{id}")
+}
+
+/// Whether folder `id` shows what it holds: as last opened or folded in either History, else
+/// `unless_clicked` (the History beside the browser shows folders open, the History bar folded).
+pub(crate) fn is_open(app: &SolveApp, id: u64, unless_clicked: bool) -> bool {
+ crate::history_folds::is_open(app, &key(id), unless_clicked)
+}
+
+/// Open or fold folder `id` in both Histories.
+pub(crate) fn set_open(app: &mut SolveApp, id: u64, open: bool) {
+ crate::history_folds::set_open(app, &key(id), open);
+}
+
+/// A folder's place in the history as the History bar shows it: its features (its own and its
+/// folders') by index, its own joints, and the folders in it in order. An empty folder sits where
+/// the run it is in ends.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Span {
+ pub id: u64,
+ pub start: usize,
+ pub end: usize,
+ pub joints: usize,
+ pub children: Vec<Span>,
+}
+
+/// What the History bar shows of the design's folders: their places, names and joints.
+#[derive(Default)]
+pub(crate) struct Folders {
+ pub spans: Vec<Span>,
+ names: HashMap<u64, String>,
+ /// Each folder's own joints, in the design's order.
+ pub joints: HashMap<u64, Vec<u64>>,
+ /// Every joint some folder shows, which the joints chip after the history leaves out.
+ pub held: HashSet<u64>,
+ /// Each folder's items: its features and the joints in it and its folders.
+ count: HashMap<u64, usize>,
+}
+
+impl Folders {
+ pub(crate) fn of(doc: &Document) -> Self {
+ if doc.timeline_groups.is_empty() {
+ return Self::default();
+ }
+ let ids: Vec<u64> = doc.features.iter().map(|f| f.id).collect();
+ let joints = folder_joints(doc);
+ let spans = spans(&ids, &doc.timeline_groups, &joints);
+ let mut count = HashMap::new();
+ for span in &spans {
+ count_items(span, &joints, &mut count);
+ }
+ // Only the folders shown hold their joints; a folder left out leaves them to the chip.
+ let held = count.keys().filter_map(|id| joints.get(id)).flatten().copied().collect();
+ let names = doc.timeline_groups.iter().map(|g| (g.id, g.name.clone())).collect();
+ Self { spans, names, joints, held, count }
+ }
+
+ pub(crate) fn name(&self, id: u64) -> &str {
+ self.names.get(&id).map_or("Folder", String::as_str)
+ }
+
+ /// The deepest folder whose run holds the slot between features `slot - 1` and `slot` (a
+ /// slot at a folder's edge is outside it), as a dropped feature joins it.
+ pub(crate) fn at_slot(&self, slot: usize) -> Option<u64> {
+ let mut level = &self.spans;
+ let mut found = None;
+ while let Some(span) = level.iter().find(|s| s.start < slot && slot < s.end) {
+ found = Some(span.id);
+ level = &span.children;
+ }
+ found
+ }
+}
+
+/// A folder's items, and those of the folders in it, into `count`. Returns them.
+fn count_items(span: &Span, joints: &HashMap<u64, Vec<u64>>, count: &mut HashMap<u64, usize>) -> usize {
+ let own = joints.get(&span.id).map_or(0, Vec::len);
+ let nested: usize = span.children.iter().map(|c| count_items(c, joints, count) - (c.end - c.start)).sum();
+ let total = (span.end - span.start) + own + nested;
+ count.insert(span.id, total);
+ total
+}
+
+/// Each folder's parent and depth, following only parents that are there (a missing parent
+/// makes a folder outermost). A loop of parents (a damaged design) or a folder nested
+/// `DEPTH_MAX` deep leaves the folder out (`None`): its features show one by one.
+fn levels(folders: &[TimelineGroup]) -> HashMap<u64, Option<(Option<u64>, usize)>> {
+ let parent: HashMap<u64, Option<u64>> = folders.iter().map(|g| (g.id, g.parent.filter(|p| *p != g.id))).collect();
+ let up = |id: u64| parent.get(&id).copied().flatten().filter(|p| parent.contains_key(p));
+ folders
+ .iter()
+ .map(|g| {
+ let mut depth = 0;
+ let mut at = up(g.id);
+ while let Some(p) = at {
+ depth += 1;
+ if depth >= DEPTH_MAX {
+ break;
+ }
+ at = up(p);
+ }
+ (g.id, at.is_none().then_some((up(g.id), depth)))
+ })
+ .collect()
+}
+
+/// The folders' places for features `ids` (in history order), outermost first. Every feature of
+/// a folder or of the folders in it counts toward its run, so a damaged design whose folder is
+/// not one run still shows each feature once (`timeline_fold::entries` cuts runs that overlap).
+pub(crate) fn spans(ids: &[u64], folders: &[TimelineGroup], joints: &HashMap<u64, Vec<u64>>) -> Vec<Span> {
+ let position: HashMap<u64, usize> = ids.iter().enumerate().map(|(i, id)| (*id, i)).collect();
+ let levels = levels(folders);
+ let kept = |id: &u64| levels.get(id).copied().flatten();
+ // Each folder's run, from its own features and then its folders', deepest first.
+ let mut run: HashMap<u64, (usize, usize)> = HashMap::new();
+ for g in folders.iter().filter(|g| kept(&g.id).is_some()) {
+ let mut own = g.features.iter().filter_map(|f| position.get(f).copied()).peekable();
+ if own.peek().is_some() {
+ let (lo, hi) = own.fold((usize::MAX, 0), |(lo, hi), i| (lo.min(i), hi.max(i + 1)));
+ run.insert(g.id, (lo, hi));
+ }
+ }
+ let mut by_depth: Vec<(usize, u64, Option<u64>)> = folders.iter().filter_map(|g| kept(&g.id).map(|(p, d)| (d, g.id, p))).collect();
+ by_depth.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
+ for (_, id, parent) in &by_depth {
+ if let (Some(parent), Some((lo, hi))) = (parent, run.get(id).copied()) {
+ let entry = run.entry(*parent).or_insert((lo, hi));
+ *entry = (entry.0.min(lo), entry.1.max(hi));
+ }
+ }
+ let mut children: HashMap<Option<u64>, Vec<u64>> = HashMap::new();
+ for (_, id, parent) in by_depth.iter().rev() {
+ children.entry(*parent).or_default().push(*id);
+ }
+ build(None, ids.len(), &children, &run, joints)
+}
+
+fn build(
+ parent: Option<u64>,
+ end: usize,
+ children: &HashMap<Option<u64>, Vec<u64>>,
+ run: &HashMap<u64, (usize, usize)>,
+ joints: &HashMap<u64, Vec<u64>>,
+) -> Vec<Span> {
+ let mut out: Vec<Span> = children
+ .get(&parent)
+ .into_iter()
+ .flatten()
+ .map(|id| {
+ let (start, stop) = run.get(id).copied().unwrap_or((end, end));
+ Span { id: *id, start, end: stop, joints: joints.get(id).map_or(0, Vec::len), children: build(Some(*id), stop, children, run, joints) }
+ })
+ .collect();
+ out.sort_by_key(|s| (s.start, s.start == s.end, s.id));
+ out
+}
+
+/// Each folder's own joints, in the design's joint order; ids no joint has any more are left out.
+fn folder_joints(doc: &Document) -> HashMap<u64, Vec<u64>> {
+ let folder_of: HashMap<u64, u64> = doc.timeline_groups.iter().flat_map(|g| g.joints.iter().map(move |j| (*j, g.id))).collect();
+ let mut out: HashMap<u64, Vec<u64>> = HashMap::new();
+ for joint in &doc.assembly.joints {
+ if let Some(folder) = folder_of.get(&joint.id) {
+ out.entry(*folder).or_default().push(joint.id);
+ }
+ }
+ out
+}
+
+/// The innermost folder that holds every one of `features` (directly or in its folders): where
+/// a folder made of them goes, so grouping features inside a folder nests the new one there.
+pub(crate) fn group_parent(folders: &[TimelineGroup], features: &[u64]) -> Option<u64> {
+ let parent: HashMap<u64, Option<u64>> = folders.iter().map(|g| (g.id, g.parent)).collect();
+ let chain = |feature: &u64| -> Vec<u64> {
+ let mut out = Vec::new();
+ let mut at = folders.iter().find(|g| g.features.contains(feature)).map(|g| g.id);
+ while let Some(id) = at {
+ if out.contains(&id) || out.len() > DEPTH_MAX {
+ break;
+ }
+ out.push(id);
+ at = parent.get(&id).copied().flatten();
+ }
+ out
+ };
+ let mut chains = features.iter().map(chain);
+ let first = chains.next()?;
+ let rest: Vec<Vec<u64>> = chains.collect();
+ first.into_iter().find(|id| rest.iter().all(|c| c.contains(id)))
+}
+
+/// A new folder of `features` in `parent`, folded, with its name to type at `at` (Group Features
+/// in a feature's menu, `timeline::feature_items`).
+pub(crate) fn group(app: &mut SolveApp, features: &[u64], parent: Option<u64>, at: egui::Pos2) -> Option<u64> {
+ let made = app.run("timeline.group", json!({ "features": features, "parent": parent })).ok()?;
+ let folder = made.get("group").and_then(serde_json::Value::as_u64)?;
+ set_open(app, folder, false);
+ crate::context_menu::start_rename(app, crate::context_menu::RenameWhat::TimelineGroup(folder), at);
+ Some(folder)
+}
+
+/// Draws a folder's chip with its top left at `at`; a click shows what it holds or folds it, and
+/// its menu also renames, ungroups or selects it, or rolls the marker after it. Returns its width.
+pub(crate) fn folder_chip(
+ app: &mut SolveApp,
+ ui: &mut egui::Ui,
+ p: &egui::Painter,
+ at: egui::Pos2,
+ folder: &Folder,
+ history: &History,
+ strip: &Strip,
+) -> f32 {
+ let name = history.folders.name(folder.id).to_string();
+ // While the bar shows one component's features, a folder counts those and its own joints.
+ let own_joints = history.folders.joints.get(&folder.id).map_or(0, Vec::len);
+ let count = match history.within {
+ Some(_) => folder.end - folder.start + own_joints,
+ None => history.folders.count.get(&folder.id).copied().unwrap_or(folder.end - folder.start),
+ };
+ let joints = count.saturating_sub(folder.end - folder.start);
+ let state = history.inside(folder.start, folder.end, folder.open);
+ let picked = app.tree.picked_timeline_groups.contains(&folder.id)
+ || (!folder.open && history.folders.joints.get(&folder.id).is_some_and(|j| j.iter().any(|j| app.tree.picked_joints.contains(j))));
+ let chip = HistoryGroupChip {
+ icon: "feature_group",
+ name: &name,
+ count,
+ open: folder.open,
+ selected: state.selected || picked,
+ hovered: state.hovered,
+ dim: history.view.index(folder.start) >= strip.marker && folder.start < folder.end,
+ error: state.error,
+ warning: state.warning,
+ accent: strip.accent,
+ };
+ let rect = egui::Rect::from_min_size(at, chip.size(p));
+ let response = ui.interact(rect, ui.scope_id().with(("feature_folder", folder.id)), egui::Sense::click());
+ crate::scenario::publish_target(&format!("timeline-folder-chip:{name}"), rect);
+ chip.paint(p, rect, response.hover_pos());
+ let features = folder.end - folder.start;
+ let what = match joints {
+ 0 => counted(features, "feature"),
+ _ => format!("{} and {}", counted(features, "feature"), counted(joints, "joint")),
+ };
+ let tip = if folder.open { "click to fold them" } else { "click to show each one" };
+ let response = response.on_hover_cursor(egui::CursorIcon::PointingHand).backing_on_hover_text(format!("{name}: {what}, {tip}"));
+ if response.clicked() {
+ set_open(app, folder.id, !folder.open);
+ }
+ crate::ui_kit::Menu::context(&response, |ui| folder_menu(app, ui, folder, &history.view, rect.left_bottom()));
+ rect.width()
+}
+
+/// `n` things: "1 feature", "3 features".
+fn counted(n: usize, thing: &str) -> String {
+ if n == 1 { format!("1 {thing}") } else { format!("{n} {thing}s") }
+}
+
+fn folder_menu(app: &mut SolveApp, ui: &mut egui::Ui, folder: &Folder, view: &crate::timeline_fold::View, at: egui::Pos2) {
+ let fold = if folder.open { "Fold Features" } else { "Show Each Feature" };
+ if crate::context_menu::button(ui, fold, "list").clicked() {
+ set_open(app, folder.id, !folder.open);
+ ui.close();
+ }
+ if crate::context_menu::button(ui, "Rename", "rename").clicked() {
+ crate::context_menu::start_rename(app, crate::context_menu::RenameWhat::TimelineGroup(folder.id), at);
+ ui.close();
+ }
+ if crate::context_menu::button(ui, "Ungroup", "feature_group").backing_on_hover_text("Keep its features and folders in the history").clicked() {
+ app.tree.picked_timeline_groups.retain(|g| *g != folder.id);
+ let _ = app.run("timeline.ungroup", json!({ "group": folder.id }));
+ ui.close();
+ }
+ ui.separator();
+ if crate::context_menu::button(ui, "Select Features", "select").clicked() {
+ let features = &app.session.doc.features;
+ let items: Vec<_> = view
+ .indices(folder.start, folder.end)
+ .into_iter()
+ .filter_map(|i| features.get(i))
+ .map(|f| json!({"type": "feature", "id": f.id}))
+ .collect();
+ app.tree.picked_joints.clear();
+ app.tree.picked_timeline_groups.clear();
+ let _ = app.run("select.set", json!({ "items": items }));
+ ui.close();
+ }
+ if crate::context_menu::button(ui, "Roll History Marker Here", "rollback").clicked() {
+ let end = view.index(folder.end);
+ let position = if end >= app.session.doc.features.len() { json!({}) } else { json!({ "position": end }) };
+ let _ = app.run_heavy("timeline.roll_to", position);
+ ui.close();
+ }
+}
+
+/// Where a feature dropped at `slot` goes: `timeline.reorder` while it stays in its folder (or
+/// out of every folder), else `timeline.move_many` into the folder the slot is in (or out of
+/// folders), so a feature dropped between an open folder's features joins it.
+/// `active`: the drop lands before the history marker, which sits at `marker_slot`; crossing it
+/// rolls the feature back or forward in the same step.
+pub(crate) fn drop_feature(app: &mut SolveApp, folders: &Folders, id: u64, slot: usize, active: bool, marker_slot: usize) {
+ let target = folders.at_slot(slot);
+ let from = app.session.doc.feature_index(id).unwrap_or(0);
+ let home = app.session.doc.timeline_groups.iter().find(|g| g.features.contains(&id)).map(|g| g.id);
+ if home == target {
+ // Dropping after itself means the slot shifts by one.
+ let to = if slot > from { slot - 1 } else { slot };
+ if to != from || active != (from < marker_slot) {
+ let _ = app.run_heavy("timeline.reorder", json!({ "feature": id, "position": to, "active": active }));
+ }
+ } else {
+ let _ = app.run_heavy("timeline.move_many", json!({ "features": [id], "group": target, "position": slot, "active": active }));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashMap;
+
+ use solidcraft_engine::doc::TimelineGroup;
+
+ use super::{Span, group_parent, spans};
+
+ fn folder(id: u64, parent: Option<u64>, features: &[u64]) -> TimelineGroup {
+ TimelineGroup { id, name: format!("F{id}"), parent, features: features.to_vec(), joints: Vec::new() }
+ }
+
+ fn span(id: u64, start: usize, end: usize, children: Vec<Span>) -> Span {
+ Span { id, start, end, joints: 0, children }
+ }
+
+ /// A folder's run takes in its folders' features; folders sit in history order, an empty one
+ /// where its parent's run ends.
+ #[test]
+ fn spans_nest_in_history_order() {
+ let ids: Vec<u64> = (100..110).collect();
+ let folders =
+ [folder(1, None, &[102, 103]), folder(2, Some(1), &[104, 105]), folder(3, None, &[107]), folder(4, Some(1), &[]), folder(5, None, &[])];
+ let got = spans(&ids, &folders, &HashMap::new());
+ assert_eq!(got, vec![span(1, 2, 6, vec![span(2, 4, 6, vec![]), span(4, 6, 6, vec![])]), span(3, 7, 8, vec![]), span(5, 10, 10, vec![])]);
+ }
+
+ /// A damaged design's loops of parents, missing parents and very deep nesting end without
+ /// hanging, and leave out only the folders they can't place.
+ #[test]
+ fn spans_survive_loops_missing_parents_and_deep_nesting() {
+ let ids: Vec<u64> = (0..200).collect();
+ let mut folders = vec![folder(1, Some(2), &[1]), folder(2, Some(1), &[2]), folder(3, Some(99), &[5]), folder(4, Some(4), &[6])];
+ folders.extend((10..60).map(|id| folder(id, (id > 10).then(|| id - 1), &[100 + id])));
+ let got = spans(&ids, &folders, &HashMap::new());
+ let ids: Vec<u64> = got.iter().map(|s| s.id).collect();
+ assert!(!ids.contains(&1) && !ids.contains(&2), "a loop of parents is left out: {ids:?}");
+ assert!(ids.contains(&3) && ids.contains(&4), "a missing parent or a folder its own parent is outermost: {ids:?}");
+ let mut depth = 0;
+ let mut at = got.iter().find(|s| s.id == 10);
+ while let Some(s) = at {
+ depth += 1;
+ at = s.children.first();
+ }
+ assert_eq!(depth, super::DEPTH_MAX, "nesting stops at the deepest allowed level");
+ }
+
+ /// An inserted assembly's folder holds its whole rigid group, also the joints inside its
+ /// sub-assemblies, whose two ends meet in a component below the import's own; none is left
+ /// for the joints chip after the history.
+ #[test]
+ fn an_import_folder_holds_the_joints_of_its_sub_assemblies() {
+ use serde_json::json;
+ use solidcraft_engine::Session;
+ use solidcraft_engine::doc::joints::JointKind;
+ let run = |s: &mut Session, command: &str, params: serde_json::Value| s.execute(command, &params).unwrap();
+ // Outer holds a plate and Inner, placed twice: the file nests Inner in Outer.
+ let mut s = Session::default();
+ run(&mut s, "component.create", json!({"name": "Outer"}));
+ run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 5, "body_name": "Plate"}));
+ run(&mut s, "component.create", json!({"name": "Inner"}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Block"}));
+ run(&mut s, "component.activate", json!({"component": "Outer"}));
+ run(&mut s, "occurrence.copy", json!({"component": "Inner", "translate": [0, 0, 30]}));
+ let dir = std::env::temp_dir().join(format!("solidcraft-timeline-folders-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("nested.step").to_string_lossy().to_string();
+ run(&mut s, "file.export", json!({"path": path}));
+
+ let mut s = Session::default();
+ let folder = run(&mut s, "file.insert_step", json!({"path": path, "folder": true}))["group"].as_u64().unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut rigid: Vec<u64> = s.doc.assembly.joints.iter().filter(|j| j.kind == JointKind::Rigid).map(|j| j.id).collect();
+ rigid.sort_unstable();
+ let mut held = super::Folders::of(&s.doc).joints.get(&folder).cloned().unwrap_or_default();
+ held.sort_unstable();
+ assert!(rigid.len() >= 3, "the plate and both Inner placements are held: {rigid:?}");
+ assert_eq!(held, rigid, "every joint of the import is in its folder");
+ }
+
+ /// A new folder goes in the innermost folder holding all the features grouped.
+ #[test]
+ fn a_new_folder_nests_where_all_its_features_are() {
+ let folders = [folder(1, None, &[1, 2]), folder(2, Some(1), &[3, 4]), folder(3, None, &[9])];
+ assert_eq!(group_parent(&folders, &[3, 4]), Some(2));
+ assert_eq!(group_parent(&folders, &[2, 3]), Some(1));
+ assert_eq!(group_parent(&folders, &[4, 9]), None);
+ assert_eq!(group_parent(&folders, &[5]), None);
+ assert_eq!(group_parent(&folders, &[]), None);
+ }
+}
diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs
index fd40c792cb..f58a6f876b 100644
--- a/crates/ui-egui/src/timeline_left.rs
+++ b/crates/ui-egui/src/timeline_left.rs
@@ -614,7 +614,7 @@ pub(crate) fn drop_items(
params["active"] = json!(active);
let _ = app.run("timeline.move_many", params);
if let Some(group) = group {
- app.tree.collapsed.remove(&format!("timeline_group:{group}"));
+ crate::timeline_folders::set_open(app, group, true);
}
}
@@ -727,7 +727,7 @@ fn selection_actions(app: &mut SolveApp, ui: &mut egui::Ui, groups: &[solidcraft
if let Ok(result) = result
&& let Some(group) = result.get("group").and_then(serde_json::Value::as_u64)
{
- app.tree.collapsed.remove(&format!("timeline_group:{group}"));
+ crate::timeline_folders::set_open(app, group, true);
crate::context_menu::start_rename(app, crate::context_menu::RenameWhat::TimelineGroup(group), pos2(0.0, 0.0));
}
ui.close();
@@ -814,15 +814,17 @@ pub fn reveal_feature(app: &mut SolveApp, feature: u64) {
}
let groups = &app.session.doc.timeline_groups;
let mut current = group_for(groups, feature);
- let mut steps = 0usize;
+ let mut folders = Vec::new();
while let Some(id) = current {
- app.tree.collapsed.remove(&format!("timeline_group:{id}"));
- steps += 1;
- if steps > groups.len() {
+ folders.push(id);
+ if folders.len() > groups.len() {
break;
}
current = groups.iter().find(|group| group.id == id).and_then(|group| group.parent);
}
+ for id in folders {
+ crate::timeline_folders::set_open(app, id, true);
+ }
}
/// The features of these folders and of the folders nested in them, in timeline order.
@@ -889,7 +891,7 @@ fn group_is_open(app: &SolveApp, groups: &[solidcraft_engine::doc::TimelineGroup
let mut current = Some(id);
let mut steps = 0usize;
while let Some(group_id) = current {
- if app.tree.collapsed.contains(&format!("timeline_group:{group_id}")) {
+ if !crate::timeline_folders::is_open(app, group_id, true) {
return false;
}
steps += 1;
@@ -907,7 +909,7 @@ fn group_ancestors_are_open(app: &SolveApp, groups: &[solidcraft_engine::doc::Ti
let mut current = groups.iter().find(|group| group.id == id).and_then(|group| group.parent);
let mut steps = 0usize;
while let Some(group_id) = current {
- if app.tree.collapsed.contains(&format!("timeline_group:{group_id}")) {
+ if !crate::timeline_folders::is_open(app, group_id, true) {
return false;
}
steps += 1;
@@ -1096,8 +1098,7 @@ fn vertical_group_row(
drop_zones: &mut Vec<(Rect, u64)>,
) -> bool {
let t = Tokens::get();
- let key = format!("timeline_group:{}", group.id);
- let open = !app.tree.collapsed.contains(&key);
+ let open = crate::timeline_folders::is_open(app, group.id, true);
let selected = app.tree.picked_timeline_groups.contains(&group.id);
slots.push(VerticalSlot {
y: ui.cursor().top(),
@@ -1151,11 +1152,7 @@ fn vertical_group_row(
crate::scenario::publish_handle(&format!("timeline-folder-fold:{}", group.name), fold_rect.center());
let fold = ui.interact(fold_rect, ui.scope_id().with(("timeline_group_fold", group.id)), Sense::click());
if fold.clicked() {
- if open {
- app.tree.collapsed.insert(key.clone());
- } else {
- app.tree.collapsed.remove(&key);
- }
+ crate::timeline_folders::set_open(app, group.id, !open);
} else if !renaming && response.clicked() {
select_item(app, ui, TimelineItem::Group(group.id), order);
}
@@ -2238,8 +2235,8 @@ mod tests {
harness.app.run("solid.box", json!({"length": 20, "width": 15, "height": 10, "name": "Base", "body_name": "Plate"})).unwrap();
let inner = harness.app.run("timeline.group", json!({"name": "Inner", "features": ["Base"]})).unwrap()["group"].as_u64().unwrap();
let outer = harness.app.run("timeline.group", json!({"name": "Outer", "groups": [inner]})).unwrap()["group"].as_u64().unwrap();
- harness.app.tree.collapsed.insert(format!("timeline_group:{inner}"));
- harness.app.tree.collapsed.insert(format!("timeline_group:{outer}"));
+ crate::timeline_folders::set_open(&mut harness.app, inner, false);
+ crate::timeline_folders::set_open(&mut harness.app, outer, false);
harness.frames(4);
assert!(handle_at("timeline:Base").is_none(), "the feature starts hidden in its folders");
@@ -2596,7 +2593,7 @@ mod tests {
assert!(y("timeline-folder:Nested") < y("timeline-joint:B"));
assert!(y("timeline-joint:B") < y("timeline-folder:Second"));
assert!(y("timeline-folder:Second") < y("timeline-joint:C"));
- h.app.tree.collapsed.insert(format!("timeline_group:{first}"));
+ crate::timeline_folders::set_open(&mut h.app, first, false);
h.frames(4);
assert!(handle_at("timeline-joint:A").is_none() && handle_at("timeline-joint:B").is_none());
assert!(handle_at("timeline-joint:C").is_some());
@@ -2716,7 +2713,7 @@ mod tests {
let marks = || crate::scenario::handles("timeline-folder-status:").into_iter().map(|(name, _)| name).collect::<Vec<_>>();
assert!(marks().is_empty(), "open folders show their features' own marks");
- harness.app.tree.collapsed.insert(format!("timeline_group:{}", id("Outer")));
+ crate::timeline_folders::set_open(&mut harness.app, id("Outer"), false);
harness.frames(2);
assert_eq!(marks(), ["timeline-folder-status:warning:Outer"]);
@@ -3294,11 +3291,14 @@ mod tests {
// and without the listed sketches shown.
let keys: Vec<String> = groups.iter().map(|group| group.id).chain([4242]).map(|id| format!("timeline_group:{id}")).collect();
let hosts: Vec<String> = table.rows.rows.iter().filter(|row| !row.listed.is_empty()).map(|row| sketches_key(row.feature)).collect();
- let kept = (h.app.tree.collapsed.clone(), h.app.tree.expanded.clone());
+ let kept = (h.app.tree.history_folds.clone(), h.app.tree.expanded.clone());
for closed in 0..(1u32 << keys.len()) {
for open_hosts in [false, true] {
let app = &mut h.app;
- app.tree.collapsed = keys.iter().enumerate().filter(|(bit, _)| closed & (1 << bit) != 0).map(|(_, key)| key.clone()).collect();
+ app.tree.history_folds = Default::default();
+ for (_, key) in keys.iter().enumerate().filter(|(bit, _)| closed & (1 << bit) != 0) {
+ crate::history_folds::set_open(app, key, false);
+ }
app.tree.expanded = if open_hosts { hosts.iter().cloned().collect() } else { Default::default() };
let folds = table.folds(app);
assert_eq!(table.visible_order(&folds), visible_order(app, features, groups, &table.rows), "closed {closed:b}, hosts {open_hosts}");
@@ -3308,7 +3308,7 @@ mod tests {
}
}
}
- (h.app.tree.collapsed, h.app.tree.expanded) = kept;
+ (h.app.tree.history_folds, h.app.tree.expanded) = kept;
}
#[test]
diff --git a/crates/ui-egui/src/timeline_left/plan.rs b/crates/ui-egui/src/timeline_left/plan.rs
index b3ddc42e14..6935954876 100644
--- a/crates/ui-egui/src/timeline_left/plan.rs
+++ b/crates/ui-egui/src/timeline_left/plan.rs
@@ -97,7 +97,7 @@ pub(super) struct RowPlan {
pub contents: Vec<Vec<u64>>,
/// By folder index: its own and nested folders' joints.
pub joints: Vec<Vec<u64>>,
- /// Each folder and parent id, with its fold key in the tree state.
+ /// Each folder and parent id, with its fold key in `history_folds`.
fold_keys: Vec<(u64, String)>,
/// Features with sketches listed under them, and their fold keys.
host_keys: Vec<(u64, String)>,
@@ -184,7 +184,7 @@ impl RowPlan {
trailing: Vec::new(),
contents: Vec::new(),
joints: Vec::new(),
- fold_keys: fold_ids.into_iter().map(|id| (id, format!("timeline_group:{id}"))).collect(),
+ fold_keys: fold_ids.into_iter().map(|id| (id, format!("{}{id}", crate::timeline_folders::KEY))).collect(),
host_keys: rows.rows.iter().filter(|row| !row.listed.is_empty()).map(|row| (row.feature, sketches_key(row.feature))).collect(),
features,
groups,
@@ -367,7 +367,8 @@ impl RowPlan {
/// Which folders and folds are open now.
pub(super) fn folds(&self, app: &SolveApp) -> Folds {
- let closed = self.fold_keys.iter().filter(|(_, key)| app.tree.collapsed.contains(key)).map(|(id, _)| *id).collect();
+ // A folder shows open here until it is folded (`timeline_folders::is_open`).
+ let closed = self.fold_keys.iter().filter(|(_, key)| !crate::history_folds::is_open(app, key, true)).map(|(id, _)| *id).collect();
let open_hosts = self.host_keys.iter().filter(|(_, key)| crate::browser::is_open(app, key, false)).map(|(feature, _)| *feature).collect();
Folds { closed, open_hosts }
}
diff --git a/crates/ui-egui/src/timeline_scope.rs b/crates/ui-egui/src/timeline_scope.rs
new file mode 100644
index 0000000000..3dcdeb3be1
--- /dev/null
+++ b/crates/ui-egui/src/timeline_scope.rs
@@ -0,0 +1,320 @@
+//! Which part of the design the History bar shows, as a path from the whole design down to one
+//! component. While a component is being edited, or one component is picked in the Browser, the
+//! bar shows only its features and those of the components inside it. A path ahead of the
+//! features names the way there: "All components", the components around it, then itself. A
+//! click on a step shows that component's features (or the whole design's), with the way to the
+//! edited or picked component still open; a step after the one shown goes back in. A click on a
+//! deep run's chip (one holding runs that fold in turn) shows its component the same way. Once
+//! another component is edited or picked, the bar follows it again.
+//!
+//! The history marker, dragging features and rolling back work on the design's own positions
+//! (`timeline_fold::View`). The choice is kept with the design's tab (`TreeState::timeline_scope`).
+//!
+//! The path comes with the bar's groups (`history_bar_groups`). Without them the bar has its
+//! toggle from #2880 instead: this component only, or the whole design, a choice that stays while
+//! another component is edited or picked.
+use crate::ui_kit::BackingTooltipExt as _;
+use std::collections::{HashMap, HashSet};
+
+use egui::{Painter, Rect, Sense, pos2, vec2};
+
+use crate::SolveApp;
+use crate::theme::Tokens;
+
+/// A step's name is cut at this width (its tooltip has it whole).
+const STEP_MAX: f32 = 120.0;
+/// The path names at most this many components; the others fold into a "…" step.
+const STEPS_SHOWN: usize = 3;
+/// Components nested deeper than this end a path (a damaged design's loop of parents).
+const DEPTH_MAX: usize = 64;
+
+/// Which part of the design the History bar shows.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
+pub(crate) enum Scope {
+ /// The component being edited, else the one picked in the Browser; the whole design when
+ /// there is neither.
+ #[default]
+ Follow,
+ /// The whole design.
+ All,
+ /// This component and the components inside it.
+ Component(u64),
+}
+
+/// The component being edited, else the one component picked in the Browser.
+pub(crate) fn focus(app: &SolveApp) -> Option<u64> {
+ let focus = match app.tree.picked_components.as_slice() {
+ _ if app.session.active_component != 0 => Some(app.session.active_component),
+ [one] if *one != 0 => Some(*one),
+ _ => None,
+ };
+ focus.filter(|c| exists(app, *c))
+}
+
+fn exists(app: &SolveApp, component: u64) -> bool {
+ app.session.doc.components.iter().any(|c| c.id == component)
+}
+
+/// The component whose features the bar shows; none for the whole design.
+pub(crate) fn shown(app: &SolveApp) -> Option<u64> {
+ match app.tree.timeline_scope {
+ Scope::Follow => focus(app),
+ Scope::All => None,
+ Scope::Component(c) => Some(c).filter(|c| exists(app, *c)).or_else(|| focus(app)),
+ }
+}
+
+/// The component `component` and every component inside it.
+pub(crate) fn components_within(app: &SolveApp, component: u64) -> HashSet<u64> {
+ let mut children: HashMap<u64, Vec<u64>> = HashMap::new();
+ for c in &app.session.doc.components {
+ children.entry(c.parent).or_default().push(c.id);
+ }
+ let mut out = HashSet::from([component]);
+ let mut stack = vec![component];
+ while let Some(c) = stack.pop() {
+ for child in children.get(&c).into_iter().flatten() {
+ if out.insert(*child) {
+ stack.push(*child);
+ }
+ }
+ }
+ out
+}
+
+/// The components from the outermost one below the root down to `component`.
+fn path_to(app: &SolveApp, component: u64) -> Vec<u64> {
+ let parent: HashMap<u64, u64> = app.session.doc.components.iter().map(|c| (c.id, c.parent)).collect();
+ let mut path = Vec::new();
+ let mut at = component;
+ while at != 0 && path.len() < DEPTH_MAX && !path.contains(&at) {
+ path.push(at);
+ at = parent.get(&at).copied().unwrap_or(0);
+ }
+ path.reverse();
+ path
+}
+
+/// Once another component is edited or picked, the bar shows it (without the bar's groups, unless
+/// the toggle shows the whole design). With the groups it also scrolls its last feature into
+/// view, and a feature to scroll to (Find in Timeline, a face picked in the view) outside the
+/// part shown widens it to the whole design.
+pub(crate) fn follow(app: &mut SolveApp) {
+ let focus = focus(app);
+ let path = app.preferences.history_bar_groups;
+ if app.tree.timeline_followed != Some(focus) {
+ app.tree.timeline_followed = Some(focus);
+ // The toggle's "All components" stays chosen (`components_toggle`).
+ if path || app.tree.timeline_scope != Scope::All {
+ app.tree.timeline_scope = Scope::Follow;
+ }
+ if path && let Some(component) = focus {
+ app.tree.timeline_reveal = last_feature(app, component);
+ }
+ }
+ let Some(shown) = shown(app).filter(|_| path) else {
+ return;
+ };
+ let outside = app.tree.timeline_reveal.and_then(|id| app.session.doc.features.iter().find(|f| f.id == id)).map(|f| f.component);
+ if let Some(component) = outside
+ && !components_within(app, shown).contains(&component)
+ {
+ app.tree.timeline_scope = if focus.is_some() { Scope::All } else { Scope::Follow };
+ }
+}
+
+/// A design that replaces the tab's own (a new or opened one) starts on the edited or picked
+/// component again, not on what the bar showed of the one before.
+pub(crate) fn reset(app: &mut SolveApp) {
+ app.tree.timeline_scope = Scope::default();
+ app.tree.timeline_followed = None;
+}
+
+/// The last feature of `component` or of a component inside it.
+fn last_feature(app: &SolveApp, component: u64) -> Option<u64> {
+ let within = components_within(app, component);
+ app.session.doc.features.iter().rev().find(|f| within.contains(&f.component)).map(|f| f.id)
+}
+
+/// Shows `component`'s features (a deep run's chip clicked).
+pub(crate) fn enter(app: &mut SolveApp, component: u64) {
+ app.tree.timeline_scope = if focus(app) == Some(component) { Scope::Follow } else { Scope::Component(component) };
+}
+
+/// One step of the path.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Step {
+ All,
+ /// Components left out between two steps; a click shows the innermost of them.
+ More(u64),
+ Component(u64),
+}
+
+/// The steps from "All components" to the edited or picked component, or to the one shown when
+/// that is not on the way to it. The shown step and the last one always show.
+fn steps(app: &SolveApp, shown: Option<u64>) -> Vec<Step> {
+ let target = match (shown, focus(app)) {
+ (Some(s), Some(f)) if path_to(app, f).contains(&s) => Some(f),
+ (Some(s), _) => Some(s),
+ (None, f) => f,
+ };
+ let path = target.map(|c| path_to(app, c)).unwrap_or_default();
+ let mut keep = vec![false; path.len()];
+ let mut left = STEPS_SHOWN;
+ let shown_at = shown.and_then(|s| path.iter().position(|c| *c == s));
+ for k in shown_at.into_iter().chain((0..path.len()).rev()) {
+ if left == 0 {
+ break;
+ }
+ if let Some(kept) = keep.get_mut(k)
+ && !*kept
+ {
+ *kept = true;
+ left -= 1;
+ }
+ }
+ let mut out = vec![Step::All];
+ let mut left_out = None;
+ for (component, kept) in path.iter().zip(keep) {
+ if kept {
+ if let Some(innermost) = left_out.take() {
+ out.push(Step::More(innermost));
+ }
+ out.push(Step::Component(*component));
+ } else {
+ left_out = Some(*component);
+ }
+ }
+ out
+}
+
+/// Draws the path (without the bar's groups, the toggle) from `x` in the bar `r` and returns where
+/// the features start; in a design without components nothing is drawn.
+pub(crate) fn header(app: &mut SolveApp, ui: &mut egui::Ui, p: &Painter, x: f32, r: Rect) -> f32 {
+ if !app.preferences.history_bar_groups {
+ return components_toggle(app, ui, p, x, r);
+ }
+ let shown = shown(app);
+ if shown.is_none() && focus(app).is_none() && !app.session.doc.features.iter().any(|f| f.component != 0) {
+ return x;
+ }
+ let t = Tokens::get();
+ let mut x = x;
+ for (k, step) in steps(app, shown).into_iter().enumerate() {
+ if k > 0 {
+ x = crate::ui_kit::history_crumb_arrow(p, pos2(x, r.center().y));
+ }
+ x = step_button(app, ui, p, x, r, step, shown) + t.space_2;
+ }
+ x + t.space_8
+}
+
+/// Without the bar's groups, a toggle ahead of the features as before (#2880): the edited or picked
+/// component's features only, or the whole design's.
+fn components_toggle(app: &mut SolveApp, ui: &mut egui::Ui, p: &Painter, x: f32, r: Rect) -> f32 {
+ let show_all = app.tree.timeline_scope == Scope::All;
+ let only = shown(app);
+ if only.is_none() && !show_all && !app.session.doc.features.iter().any(|f| f.component != 0) {
+ return x;
+ }
+ let t = Tokens::get();
+ let label = only.map_or_else(|| "All components".to_string(), |c| crate::timeline_fold::name(app, c));
+ let galley = p.layout_no_wrap(label, egui::FontId::proportional(t.font_label), t.text);
+ let br = Rect::from_min_size(pos2(x, r.top() + 9.0), vec2(galley.size().x + 12.0, 22.0));
+ crate::scenario::publish_handle("timeline:components", br.center());
+ let resp = ui.interact(br, ui.scope_id().with("tl_components"), Sense::click());
+ p.rect(br, 3.0, if resp.hovered() { t.hover } else { t.timeline_item }, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
+ p.galley(br.left_center() + vec2(6.0, -galley.size().y * 0.5), galley, t.text);
+ let tip = if show_all {
+ "Showing every component's features. Click to show only the active or picked component's"
+ } else if only.is_some() {
+ "Showing this component's features only. Click to show the whole design's"
+ } else {
+ "Activate or pick a component in the browser to show only its features"
+ };
+ if resp.backing_on_hover_text(tip).clicked() && (only.is_some() || show_all) {
+ app.tree.timeline_scope = if show_all { Scope::Follow } else { Scope::All };
+ }
+ br.right() + 8.0
+}
+
+fn step_name(app: &SolveApp, step: Step) -> String {
+ match step {
+ Step::All => crate::i18n::tr_label("All components").to_string(),
+ Step::More(_) => "\u{2026}".to_string(),
+ Step::Component(c) => crate::timeline_fold::name(app, c),
+ }
+}
+
+/// One step: the shown one stands out; a click on another shows its features. Returns where it
+/// ends.
+fn step_button(app: &mut SolveApp, ui: &mut egui::Ui, p: &Painter, x: f32, r: Rect, step: Step, shown: Option<u64>) -> f32 {
+ let t = Tokens::get();
+ let current = match step {
+ Step::All => shown.is_none(),
+ Step::Component(c) => shown == Some(c),
+ Step::More(_) => false,
+ };
+ let name = step_name(app, step);
+ let accent = crate::theme::TabAccent::for_tab(&t, &app.ui.tab);
+ let galley = p.layout_no_wrap(name.clone(), egui::FontId::proportional(t.font_small), t.text_dim);
+ let size = vec2(galley.size().x.min(STEP_MAX) + 2.0 * t.space_4, t.space_24);
+ let rect = Rect::from_min_size(pos2(x, r.center().y - t.space_24 / 2.0), size);
+ let response = ui.interact(rect, ui.scope_id().with(("history_path", step_key(step))), Sense::click());
+ crate::scenario::publish_handle(&format!("timeline-path:{name}"), rect.center());
+ let ink = if current {
+ p.rect_filled(rect, t.radius_sm, accent.soft);
+ accent.ink
+ } else if response.hovered() {
+ p.rect_filled(rect, t.radius_sm, t.hover);
+ t.text
+ } else {
+ t.text_dim
+ };
+ let text_at = pos2(rect.left() + t.space_4, rect.center().y - galley.size().y / 2.0);
+ p.with_clip_rect(rect.shrink2(vec2(t.space_4, 0.0)).intersect(p.clip_rect())).galley(text_at, galley, ink);
+ let tip = step_tip(app, step, current);
+ let response = if current { response } else { response.on_hover_cursor(egui::CursorIcon::PointingHand) };
+ if response.backing_on_hover_text(tip).clicked() && !current {
+ show_step(app, step);
+ }
+ rect.right()
+}
+
+/// Shows a step's features; the edited or picked component's last feature scrolls into view
+/// when they hold it.
+fn show_step(app: &mut SolveApp, step: Step) {
+ let focus = focus(app);
+ app.tree.timeline_scope = match step {
+ Step::All if focus.is_none() => Scope::Follow,
+ Step::All => Scope::All,
+ Step::More(c) | Step::Component(c) if focus == Some(c) => Scope::Follow,
+ Step::More(c) | Step::Component(c) => Scope::Component(c),
+ };
+ let holds = |f: u64| match shown(app) {
+ None => true,
+ Some(c) => components_within(app, c).contains(&f),
+ };
+ if let Some(focus) = focus.filter(|f| holds(*f)) {
+ app.tree.timeline_reveal = last_feature(app, focus);
+ }
+}
+
+fn step_key(step: Step) -> (u8, u64) {
+ match step {
+ Step::All => (0, 0),
+ Step::More(c) => (1, c),
+ Step::Component(c) => (2, c),
+ }
+}
+
+fn step_tip(app: &SolveApp, step: Step, current: bool) -> String {
+ match step {
+ Step::All if current && focus(app).is_none() => crate::i18n::tr("ui.history_scope_pick").to_string(),
+ Step::All if current => crate::i18n::tr("ui.history_scope_all_shown").to_string(),
+ Step::All => crate::i18n::tr("ui.history_scope_all").to_string(),
+ Step::More(c) => path_to(app, c).iter().map(|c| crate::timeline_fold::name(app, *c)).collect::<Vec<_>>().join(" \u{203a} "),
+ Step::Component(c) if current => crate::i18n::format("ui.history_scope_shown", &[("name", &crate::timeline_fold::name(app, c))]),
+ Step::Component(c) => crate::i18n::format("ui.history_scope_show", &[("name", &crate::timeline_fold::name(app, c))]),
+ }
+}
diff --git a/crates/ui-egui/src/ui_kit/history_group.rs b/crates/ui-egui/src/ui_kit/history_group.rs
new file mode 100644
index 0000000000..20351d7776
--- /dev/null
+++ b/crates/ui-egui/src/ui_kit/history_group.rs
@@ -0,0 +1,154 @@
+//! A run of history items folded into one chip: the icon, a name and the count, then, past a
+//! rule, the disclosure arrow in a well of its own. The joints, feature folders and long runs of a
+//! component's features use it. Open, a group's items show after its chip inside a tray that
+//! reaches from the chip to its last item.
+use crate::{
+ icons,
+ theme::{TabAccent, Tokens},
+};
+use egui::{Painter, Pos2, Rect, Stroke, pos2, vec2};
+
+/// The arrow's square well at the chip's right end.
+pub(crate) const GROUP_ARROW_WELL: f32 = 20.0;
+/// Chips in the History bar are this tall, and the icon sits in a square this wide.
+const CHIP_SIDE: f32 = 28.0;
+/// A longer name is cut at this width (the tooltip and the Browser have it whole).
+const NAME_MAX: f32 = 96.0;
+/// Items past the history marker fade like feature chips do.
+const DIM_OPACITY: f32 = 0.42;
+/// How far an open group's tray reaches past its chip and its last item.
+pub(crate) const HISTORY_TRAY_PAD: f32 = 4.0;
+/// How strongly a tray's edge takes the accent.
+const TRAY_EDGE: f32 = 0.6;
+
+/// The tray behind an open group in the History bar, from `left` to `right` around chips whose
+/// tops are at `chip_top`, `depth` trays deep. An outer tray takes the accent's soft tint and a
+/// tray inside one the bar's own colour, so each level stands apart from the one around it;
+/// deeper trays hug the chips a little closer.
+pub(crate) fn history_tray(left: f32, right: f32, chip_top: f32, depth: usize, accent: TabAccent) -> egui::Shape {
+ let t = Tokens::get();
+ let inset = (HISTORY_TRAY_PAD - depth as f32).max(1.0);
+ let rect = Rect::from_min_max(pos2(left, chip_top - inset), pos2(right.max(left), chip_top + CHIP_SIDE + inset));
+ let fill = if depth.is_multiple_of(2) { accent.soft } else { t.timeline };
+ let edge = Stroke::new(1.0, accent.color.gamma_multiply(TRAY_EDGE));
+ egui::Shape::Rect(egui::epaint::RectShape::new(rect, f32::from(t.radius_sm) + inset, fill, edge, egui::StrokeKind::Inside))
+}
+
+/// The arrow between two steps of the History bar's path, from `at` (its left middle). Returns
+/// where it ends. Tokens: form_dim.
+pub(crate) fn history_crumb_arrow(p: &Painter, at: Pos2) -> f32 {
+ let t = Tokens::get();
+ let side = t.form_section_icon_size;
+ icons::paint_ink(p, Rect::from_center_size(pos2(at.x + side / 2.0, at.y), vec2(side, side)), "chevron_right", t.form_dim);
+ at.x + side
+}
+
+pub(crate) struct HistoryGroupChip<'a> {
+ pub icon: &'a str,
+ /// Shown before the count; empty for none.
+ pub name: &'a str,
+ pub count: usize,
+ /// The grouped items are shown one by one after the chip.
+ pub open: bool,
+ /// Something inside the folded group is selected.
+ pub selected: bool,
+ /// Something inside is under the pointer elsewhere (in the viewport).
+ pub hovered: bool,
+ /// Everything inside is past the history marker.
+ pub dim: bool,
+ pub error: bool,
+ pub warning: bool,
+ pub accent: TabAccent,
+}
+
+impl HistoryGroupChip<'_> {
+ fn name_width(&self, p: &Painter) -> f32 {
+ if self.name.is_empty() {
+ return 0.0;
+ }
+ let t = Tokens::get();
+ let galley = p.layout_no_wrap(self.name.to_owned(), egui::FontId::proportional(t.font_small), t.text);
+ galley.size().x.min(NAME_MAX) + t.space_4
+ }
+
+ fn count_text(&self, p: &Painter) -> std::sync::Arc<egui::Galley> {
+ let t = Tokens::get();
+ let ink = if self.name.is_empty() { t.text } else { t.text_dim };
+ p.layout_no_wrap(self.count.to_string(), egui::FontId::proportional(t.font_small), ink)
+ }
+
+ /// The chip's width; its height is that of a feature chip.
+ pub fn width(&self, p: &Painter) -> f32 {
+ let t = Tokens::get();
+ CHIP_SIDE + t.space_3 + self.name_width(p) + self.count_text(p).size().x + t.space_6 + 1.0 + t.space_3 + GROUP_ARROW_WELL + t.space_4
+ }
+
+ pub fn size(&self, p: &Painter) -> egui::Vec2 {
+ vec2(self.width(p), CHIP_SIDE)
+ }
+
+ /// The arrow's well in a chip drawn at `rect`.
+ pub fn well(rect: Rect) -> Rect {
+ let t = Tokens::get();
+ Rect::from_center_size(pos2(rect.right() - t.space_4 - GROUP_ARROW_WELL / 2.0, rect.center().y), vec2(GROUP_ARROW_WELL, GROUP_ARROW_WELL))
+ }
+
+ /// Whether `pointer` is on the arrow: from the rule to the chip's end.
+ pub fn on_arrow(rect: Rect, pointer: Option<Pos2>) -> bool {
+ pointer.is_some_and(|q| q.x >= Self::well(rect).left() - Tokens::get().space_3)
+ }
+
+ /// Paints the chip at `rect`; `pointer` is where the pointer is while it is over the chip. The
+ /// arrow's well lights up under the pointer, and the chip takes the accent while its items are
+ /// shown one by one or while it holds the selection.
+ pub fn paint(&self, painter: &Painter, rect: Rect, pointer: Option<Pos2>) {
+ let t = Tokens::get();
+ let mut p = painter.clone();
+ if self.dim {
+ p.multiply_opacity(DIM_OPACITY);
+ }
+ let on_arrow = Self::on_arrow(rect, pointer);
+ let (fill, edge) = if self.error {
+ (t.form_error_fill, t.form_error)
+ } else if self.open || self.selected {
+ (self.accent.soft, self.accent.color)
+ } else if self.hovered || (pointer.is_some() && !on_arrow) {
+ (t.hover, t.border)
+ } else {
+ (t.timeline_item, t.border)
+ };
+ p.rect(rect, t.radius_sm, fill, Stroke::new(1.0, edge), egui::StrokeKind::Inside);
+ let square = Rect::from_min_size(rect.min, vec2(CHIP_SIDE, CHIP_SIDE));
+ icons::paint_icon(&p, square.shrink(t.space_4), self.icon, f32::from(t.icon.a()) / 255.0);
+ let mut x = square.right() - t.space_4 + t.space_3;
+ if !self.name.is_empty() {
+ let galley = p.layout_no_wrap(self.name.to_owned(), egui::FontId::proportional(t.font_small), t.text);
+ let clip = Rect::from_min_max(pos2(x, rect.top()), pos2(x + NAME_MAX, rect.bottom()));
+ p.with_clip_rect(clip.intersect(p.clip_rect())).galley(pos2(x, rect.center().y - galley.size().y / 2.0), galley, t.text);
+ x += self.name_width(&p);
+ }
+ let count = self.count_text(&p);
+ p.galley(pos2(x, rect.center().y - count.size().y / 2.0), count, t.text);
+ let well = Self::well(rect);
+ let rule = well.left() - t.space_3;
+ p.line_segment([pos2(rule, rect.top() + t.space_6), pos2(rule, rect.bottom() - t.space_6)], Stroke::new(1.0, edge));
+ let ink = match (self.open, on_arrow) {
+ (true, true) => {
+ p.rect_filled(well, t.radius_sm, self.accent.color);
+ t.on_accent
+ }
+ (false, true) => {
+ p.rect_filled(well, t.radius_sm, t.control_border);
+ t.form_ink
+ }
+ (true, false) => t.form_ink,
+ (false, false) => t.form_dim,
+ };
+ crate::ui_kit::disclosure(&p, well.center(), self.open, ink);
+ if self.error || self.warning {
+ let side = t.space_10;
+ let at = square.right_top() - vec2(side, 0.0);
+ icons::paint_icon(&p, Rect::from_min_size(at, vec2(side, side)), if self.error { "error" } else { "warning" }, 1.0);
+ }
+ }
+}
diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs
index ee0889e189..4273817eab 100644
--- a/crates/ui-egui/src/ui_kit/mod.rs
+++ b/crates/ui-egui/src/ui_kit/mod.rs
@@ -18,6 +18,7 @@ mod fields;
mod file_view;
mod framing;
mod history;
+mod history_group;
mod layout;
mod look_chain;
mod menu;
@@ -79,6 +80,7 @@ pub use fields::{cell_editor, wide_cell_editor};
pub(crate) use file_view::{FileView, RecentRow, RecoveryMessage, SampleCard};
pub(crate) use framing::*;
pub(crate) use history::*;
+pub(crate) use history_group::*;
pub(crate) use layout::*;
pub use look_chain::{LookStep, look_chain};
pub(crate) use menu::{Menu, MenuItem, rename_menu, workspace_menu};