diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index d78b5840f..a5f26a821 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -384,7 +384,7 @@ pub(crate) fn clipboard_buttons(app: &mut SolveApp, ui: &mut egui::Ui, id: u64) /// Where each feature's result is in `results`, by feature id: the first result of an id, as /// `Model::result` finds it. -fn result_index(results: &[solidcraft_engine::doc::FeatureResult]) -> std::collections::HashMap { +pub(crate) fn result_index(results: &[solidcraft_engine::doc::FeatureResult]) -> std::collections::HashMap { results.iter().enumerate().rev().map(|(k, r)| (r.id, k)).collect() } @@ -884,6 +884,19 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { // Each feature's result, found once for the strip: a search per chip made a long // timeline cost the square of its length every frame. let results = result_index(&app.session.model.results); + // The features picked in the design or in the open dialog, collected once for the + // strip: the dialog built its item list again for every chip. + let feature_of = |selection: &solidcraft_engine::Sel| match selection { + solidcraft_engine::Sel::Feature { id } => Some(*id), + _ => None, + }; + let picked: std::collections::HashSet = app + .session + .selection + .iter() + .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) => { @@ -950,8 +963,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { let err = res.and_then(|r| r.error.clone()); let warn = res.and_then(|r| r.warning.clone()); let rolled = i >= marker; - let is_it = |s: &solidcraft_engine::Sel| matches!(s, solidcraft_engine::Sel::Feature { id: f } if f == id); - let sel = app.session.selection.iter().any(is_it) || app.dialog.as_ref().is_some_and(|d| d.items().iter().any(is_it)); + let sel = picked.contains(id); if resp.hovered() { hovered = Some(*id); } @@ -974,25 +986,30 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { if floating && marker > 0 && i == marker - 1 { p.circle_filled(pos2(br.center().x, br.bottom() + t.space_3), t.space_2, accent.color); } - let mut tip = status_text(name, ty, err.as_deref(), warn.as_deref()); - // Greyed out says only "not shown": say why (#8100). - if rolled { - tip.push('\n'); - tip.push_str(crate::i18n::tr("timeline.feature_rolled_back")); - } - if let Some(state) = sketch_state { - tip.push('\n'); - tip.push_str(&state.text()); - } - if let Some(r) = res { - tip += &format!("\n{:.1} ms", r.ms); - } - tip.push('\n'); - tip.push_str(crate::i18n::tr("timeline.feature_hint")); + let ms = res.map(|r| r.ms); if resp.drag_started() { drag = Some(Drag::Feature(*id)); } - let resp = resp.on_hover_text(tip); + // The tip is written only while it shows (as `on_hover_text` would lay it out). + let resp = resp.on_hover_ui(|ui| { + let mut tip = status_text(name, ty, err.as_deref(), warn.as_deref()); + // Greyed out says only "not shown": say why (#8100). + if rolled { + tip.push('\n'); + tip.push_str(crate::i18n::tr("timeline.feature_rolled_back")); + } + if let Some(state) = sketch_state { + tip.push('\n'); + tip.push_str(&state.text()); + } + if let Some(ms) = ms { + tip += &format!("\n{ms:.1} ms"); + } + tip.push('\n'); + tip.push_str(crate::i18n::tr("timeline.feature_hint")); + ui.set_max_width(ui.spacing().tooltip_width); + ui.add(egui::Label::new(tip)); + }); if resp.clicked() && !pick_feature_into_dialog(app, *id, ui.input(|i| i.modifiers)) { let modifiers = ui.input(|i| i.modifiers); if modifiers.shift { diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index c4b906f09..dbcbcdcee 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -7,10 +7,14 @@ use serde_json::json; use crate::history_rows::{HistoryFeature, HistoryRows}; use crate::theme::Tokens; use crate::timeline::{ - TimelineKind, clipboard_buttons, delete_after_marker_button, delete_button, delete_features, icon_of, message_button, selected_feature_ids, + TimelineKind, clipboard_buttons, delete_after_marker_button, delete_button, delete_features, message_button, selected_feature_ids, }; use crate::{SolveApp, icons}; +mod plan; + +use plan::RowPlan; + const FOLDER_INDENT: f32 = 14.0; const DROP_LEVEL_ANCHOR: f32 = 12.0; const DROP_BAR_INSET: f32 = 4.0; @@ -893,6 +897,8 @@ fn group_is_open(app: &SolveApp, groups: &[solidcraft_engine::doc::TimelineGroup true } +/// The reference the cached [`RowPlan`] is tested against. +#[cfg(test)] fn group_ancestors_are_open(app: &SolveApp, groups: &[solidcraft_engine::doc::TimelineGroup], id: u64) -> bool { let mut current = groups.iter().find(|group| group.id == id).and_then(|group| group.parent); let mut steps = 0usize; @@ -909,6 +915,8 @@ fn group_ancestors_are_open(app: &SolveApp, groups: &[solidcraft_engine::doc::Ti true } +/// The reference the cached [`RowPlan`] is tested against. +#[cfg(test)] fn group_first_feature( groups: &[solidcraft_engine::doc::TimelineGroup], features: &[(u64, String, &'static str, bool, &'static str, TimelineKind)], @@ -920,6 +928,8 @@ fn group_first_feature( direct.into_iter().chain(children).min() } +/// The reference the cached [`RowPlan`] is tested against. +#[cfg(test)] fn group_last_feature( groups: &[solidcraft_engine::doc::TimelineGroup], features: &[(u64, String, &'static str, bool, &'static str, TimelineKind)], @@ -932,6 +942,7 @@ fn group_last_feature( } /// A folder with only joints shares its nearest feature-bearing ancestor's position. +#[cfg(test)] fn group_position( groups: &[solidcraft_engine::doc::TimelineGroup], features: &[(u64, String, &'static str, bool, &'static str, TimelineKind)], @@ -971,6 +982,8 @@ pub(crate) fn sketches_key(feature: u64) -> String { format!("timeline/feature/{feature}/sketches") } +/// The reference the cached [`RowPlan`] is tested against. +#[cfg(test)] fn visible_order( app: &SolveApp, features: &[(u64, String, &'static str, bool, &'static str, TimelineKind)], @@ -1066,7 +1079,9 @@ fn vertical_group_row( names: bool, ui: &mut egui::Ui, group: &solidcraft_engine::doc::TimelineGroup, - groups: &[solidcraft_engine::doc::TimelineGroup], + table: &RowPlan, + contents: &[u64], + joints: &[u64], order: &[TimelineItem], drag: &mut Option, depth: usize, @@ -1100,15 +1115,9 @@ fn vertical_group_row( let centre = pos2(rect.left() + 9.0 + offset, rect.center().y); crate::ui_kit::disclosure(ui.painter(), centre, open, t.text_dim); // A folder whose features are all suppressed looks like a suppressed feature. - let contents = folder_features(app, &[group.id]); - let joints: Vec<_> = groups - .iter() - .filter(|candidate| candidate.id == group.id || group_is_descendant(groups, candidate.id, group.id)) - .flat_map(|group| group.joints.iter()) - .collect(); let suppressed = (!contents.is_empty() || !joints.is_empty()) - && contents.iter().all(|id| app.session.doc.feature(*id).is_some_and(|f| f.suppressed)) - && joints.iter().all(|id| app.session.doc.assembly.joints.iter().any(|joint| joint.id == **id && joint.suppressed)); + && contents.iter().all(|id| table.suppressed(*id)) + && joints.iter().all(|id| app.session.doc.assembly.joints.iter().any(|joint| joint.id == *id && joint.suppressed)); let mut painter = ui.painter().clone(); if suppressed { painter.multiply_opacity(0.42); @@ -1119,7 +1128,7 @@ fn vertical_group_row( painter.line_segment([icon.left_bottom(), icon.right_top()], Stroke::new(1.5, t.text_dim)); } // Folded, it carries the worst mark of its features, as a feature chip marks its own (#8592). - let (status, tip) = if open { (None, None) } else { crate::timeline::worst_status(app, &contents) }; + let (status, tip) = if open { (None, None) } else { crate::timeline::worst_status(app, contents) }; if let Some(status) = status { let side = if names { t.space_12 } else { t.space_10 }; let at = @@ -1165,7 +1174,7 @@ fn vertical_group_row( ui.close(); } ui.separator(); - selection_actions(app, ui, groups, false); + selection_actions(app, ui, &table.groups, false); }); open } @@ -1208,12 +1217,14 @@ struct Rows<'a> { names: bool, /// Sketches: Under their feature, while the History shows names (#6489). under_feature: bool, - features: &'a [(u64, String, &'static str, bool, &'static str, TimelineKind)], - groups: &'a [solidcraft_engine::doc::TimelineGroup], + /// The design's rows, built once per change. + table: &'a RowPlan, order: &'a [TimelineItem], - /// The rows to draw (`drawn_rows`). - plan: &'a HistoryRows, marker: usize, + /// The features picked in the design, collected once for the column. + selected: std::collections::HashSet, + /// Each feature's result, found once for the column. + results: std::collections::HashMap, /// Find in Timeline: the feature to scroll into view this frame (#5850). reveal: Option, /// The feature whose body is under the pointer in the 3D view. @@ -1242,39 +1253,33 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { }); let among_features = |y: f32| features_top.is_none_or(|top| y >= top); ui.spacing_mut().item_spacing.y = if names { t.space_2 } else { t.space_4 }; - let features: Vec<_> = app - .session - .doc - .features - .iter() - .map(|feature| { - (feature.id, feature.name.clone(), icon_of(&feature.kind), feature.suppressed, feature.kind.type_name(), TimelineKind::of(&feature.kind)) - }) - .collect(); - let groups = app.session.doc.timeline_groups.clone(); - let n = features.len(); - let marker = app.session.doc.marker.unwrap_or(n); // The narrow icon strip has no room for nesting: it keeps the creation order. let under_feature = names && nests(app); - let plan = drawn_rows(app, under_feature); - let order = visible_order(app, &features, &groups, &plan); - let first_indices: std::collections::BTreeMap> = - groups.iter().map(|group| (group.id, group_position(&groups, &features, group.id))).collect(); - let end_indices: std::collections::BTreeMap = groups - .iter() - .map(|group| (group.id, group_last_feature(&groups, &features, group.id).map_or(features.len(), |index| index.saturating_add(1)))) - .collect(); + let table = RowPlan::cached(app, ui, under_feature); + let folds = table.folds(app); + let order = table.order(ui, &folds); + let (features, groups, plan) = (&table.features, &table.groups, &table.rows); + let n = features.len(); + let marker = app.session.doc.marker.unwrap_or(n); let from_view = [crate::timeline::hovered_feature(app), crate::timeline::picked_feature(app)]; let drag_id = ui.id().with("tl_vertical_drag"); let mut rows = Rows { sketch_states: crate::sketch_state::SketchStates::of(app), names, under_feature, - features: &features, - groups: &groups, + table: &table, order: &order, - plan: &plan, marker, + selected: app + .session + .selection + .iter() + .filter_map(|selection| match selection { + solidcraft_engine::Sel::Feature { id } => Some(*id), + _ => None, + }) + .collect(), + results: crate::timeline::result_index(&app.session.model.results), reveal: app.tree.timeline_reveal.take(), from_view, linked_hover: app.viewport.hover_feature.filter(|id| plan.referenced(*id)), @@ -1289,42 +1294,44 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { let mut previous_visible_group = None; let mut marker_y = f32::INFINITY; - for (index, (id, ..)) in features.iter().enumerate() { - let group_id = group_for(&groups, *id); - let mut at_index: Vec<_> = groups.iter().filter(|group| first_indices.get(&group.id).copied().flatten() == Some(index)).collect(); - at_index.sort_by_key(|group| group_path(&groups, group.id)); + for index in 0..n { + let group_id = table.group_of.get(index).copied().flatten(); + let at_index = table.starting.get(index).map_or(&[][..], Vec::as_slice); let marker_before_group = index == marker && !at_index.is_empty(); if marker_before_group { - let group = at_index.first().and_then(|group| group.parent); + let group = at_index.first().and_then(|group| groups.get(*group)).and_then(|group| group.parent); let indent_group = previous_visible_group.filter(|previous| Some(*previous) != group); slots.push(VerticalSlot { y: ui.cursor().top(), position: index, group, indent_group }); marker_y = vertical_marker(app, ui, &mut rows.drag); } let mut rendered_group_header = false; - for group in at_index { - if group_ancestors_are_open(app, &groups, group.id) && shown_groups.insert(group.id) { + for &at in at_index { + let Some(group) = groups.get(at) else { continue }; + if table.ancestors_open(&folds, group.id) && shown_groups.insert(group.id) { vertical_group_row( app, names, ui, group, - &groups, + &table, + table.contents.get(at).map_or(&[][..], Vec::as_slice), + table.joints.get(at).map_or(&[][..], Vec::as_slice), &order, &mut rows.drag, - group_depth(&groups, group.id), + table.depth.get(at).copied().unwrap_or(0), index, - end_indices.get(&group.id).copied().unwrap_or(index), + table.end.get(at).copied().unwrap_or(index), previous_visible_group, &mut slots, &mut folder_drop_zones, ); - if group_first_feature(&groups, &features, group.id).is_none() { - folder_joint_rows(app, ui, group, &groups); + if table.first.get(at).copied().flatten().is_none() { + folder_joint_rows(app, ui, group, groups); } rendered_group_header = true; } } - let group_open = group_id.is_none_or(|id| group_is_open(app, &groups, id)); + let group_open = group_id.is_none_or(|id| table.is_open(&folds, id)); let indent_group = (!rendered_group_header).then_some(previous_visible_group).flatten().filter(|previous| Some(*previous) != group_id); if index == marker && !marker_before_group { slots.push(VerticalSlot { y: ui.cursor().top(), position: index, group: group_open.then_some(group_id).flatten(), indent_group }); @@ -1333,36 +1340,35 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { // A sketch listed under a feature is drawn after that feature's row. if group_open && let Some(row) = plan.row_at(index) { slots.push(VerticalSlot { y: ui.cursor().top(), position: row.slot.min(index), group: group_id, indent_group }); - let indent = group_id.map(|id| (group_depth(&groups, id) + 1) as f32 * FOLDER_INDENT).unwrap_or(0.0); + let indent = group_id.map(|id| (table.depth_of(id) + 1) as f32 * FOLDER_INDENT).unwrap_or(0.0); feature_row(app, ui, &mut rows, index, indent, RowKind::Own); previous_visible_group = group_id; } - let mut ending: Vec<_> = groups.iter().filter(|group| group_last_feature(&groups, &features, group.id) == Some(index)).collect(); - ending.sort_by_key(|group| std::cmp::Reverse(group_depth(&groups, group.id))); - for group in ending { - folder_joint_rows(app, ui, group, &groups); + for group in table.ending.get(index).map_or(&[][..], Vec::as_slice).iter().filter_map(|group| groups.get(*group)) { + folder_joint_rows(app, ui, group, groups); } } - let mut trailing: Vec<_> = groups.iter().filter(|group| !shown_groups.contains(&group.id)).collect(); - trailing.sort_by_key(|group| (first_indices.get(&group.id).copied().flatten().unwrap_or(usize::MAX), group_path(&groups, group.id))); - for group in trailing { - if group_ancestors_are_open(app, &groups, group.id) && shown_groups.insert(group.id) { + for &at in &table.trailing { + let Some(group) = groups.get(at) else { continue }; + if !shown_groups.contains(&group.id) && table.ancestors_open(&folds, group.id) && shown_groups.insert(group.id) { vertical_group_row( app, names, ui, group, - &groups, + &table, + table.contents.get(at).map_or(&[][..], Vec::as_slice), + table.joints.get(at).map_or(&[][..], Vec::as_slice), &order, &mut rows.drag, - group_depth(&groups, group.id), + table.depth.get(at).copied().unwrap_or(0), n, n, previous_visible_group, &mut slots, &mut folder_drop_zones, ); - folder_joint_rows(app, ui, group, &groups); + folder_joint_rows(app, ui, group, groups); } } slots.push(VerticalSlot { y: ui.cursor().top(), position: n, group: None, indent_group: previous_visible_group }); @@ -1386,8 +1392,8 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { let folder_target = match active { Drag::Items(items) => { let panel_left = ui.min_rect().left(); - vertical_drop_group(pointer, slot, &folder_drop_zones, &groups, panel_left, drag_x(items, pointer.x), items.source_group) - .filter(|target| valid_folder_target(items, &groups, *target)) + vertical_drop_group(pointer, slot, &folder_drop_zones, groups, panel_left, drag_x(items, pointer.x), items.source_group) + .filter(|target| valid_folder_target(items, groups, *target)) } Drag::Marker => None, }; @@ -1397,7 +1403,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { if let Some(rect) = hovered_folder { ui.painter().rect_stroke(rect.shrink(1.0), t.radius_sm.saturating_sub(1), Stroke::new(2.0, t.sketch_accent), egui::StrokeKind::Inside); } else { - let left = vertical_drop_bar_left(ui.min_rect().left(), folder_target, &groups); + let left = vertical_drop_bar_left(ui.min_rect().left(), folder_target, groups); crate::ui_kit::history_drop_bar( ui.painter(), Rect::from_min_max(pos2(left, slot.y), pos2(ui.max_rect().right() - 5.0, slot.y)), @@ -1418,10 +1424,10 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { Drag::Items(items) => { let panel_left = ui.min_rect().left(); let folder_target = - vertical_drop_group(pointer, slot, &folder_drop_zones, &groups, panel_left, drag_x(&items, pointer.x), items.source_group); - let valid_target = folder_target.is_none_or(|target| valid_folder_target(&items, &groups, target)); + vertical_drop_group(pointer, slot, &folder_drop_zones, groups, panel_left, drag_x(&items, pointer.x), items.source_group); + let valid_target = folder_target.is_none_or(|target| valid_folder_target(&items, groups, target)); if valid_target { - drop_items(app, &plan, &items.features, &items.groups, folder_target, slot.position, slot.y < marker_y); + drop_items(app, plan, &items.features, &items.groups, folder_target, slot.position, slot.y < marker_y); } } } @@ -1441,16 +1447,15 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { /// One feature's row at timeline position `index`, `indent` points in, and for a feature that /// sketches are listed under, those sketches' rows when its fold is open. fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: usize, indent: f32, row_kind: RowKind) { - let t = Tokens::get(); - let (features, names, plan, groups, order, marker) = (rows.features, rows.names, rows.plan, rows.groups, rows.order, rows.marker); - let Some((id, name, icon, suppressed, ty, kind)) = features.get(index) else { return }; + let (table, names) = (rows.table, rows.names); + let (features, plan) = (&table.features, &table.rows); + let Some((id, name, _, _, _, kind)) = features.get(index) else { return }; let id = *id; - let group_id = group_for(groups, id); + let group_id = table.group_of.get(index).copied().flatten(); let reference = matches!(row_kind, RowKind::Reference { .. }); let listed = (row_kind == RowKind::Own).then(|| plan.row_at(index)).flatten().map(|row| row.listed.as_slice()).filter(|listed| !listed.is_empty()); - let has_patterns = !reference && matches!(kind, TimelineKind::Sketch) && crate::sketch_pattern_tree::has_patterns(app, id); - let sketch_state = matches!(kind, TimelineKind::Sketch).then(|| rows.sketch_states.get(id)).flatten(); + let has_patterns = !reference && matches!(kind, TimelineKind::Sketch) && table.has_patterns.get(index).copied().unwrap_or(false); // One fold per row: a feature's listed sketches, or a sketch's patterns. let fold = match listed { Some(_) => Some((sketches_key(id), false)), @@ -1458,8 +1463,10 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us }; let fold_open = fold.as_ref().is_some_and(|(key, default)| crate::browser::is_open(app, key, *default)); let style = if names { crate::ui_kit::HistoryStyle::Names } else { crate::ui_kit::HistoryStyle::Icons }; - let sense = if reference { Sense::click() } else { Sense::click_and_drag() }; - let (row, response) = ui.allocate_exact_size(vec2(ui.available_width(), style.height()), sense); + // `allocate_exact_size` in two steps, so a row outside the view takes its place and no more. + let size = vec2(ui.available_width(), style.height()); + let (row_id, frame) = ui.allocate_space(size); + let row = ui.layout().align_size_within_rect(size, frame); let rect = if style == crate::ui_kit::HistoryStyle::Icons { Rect::from_center_size(row.center(), vec2(style.height(), style.height())) } else { row }; let parent = match row_kind { @@ -1477,8 +1484,93 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us } } let fold_rect = Rect::from_min_size(rect.left_top() + vec2(indent, 0.0), vec2(FOLD_COLUMN, rect.height())); + if fold.is_some() { + let handle = if listed.is_some() { "timeline-sketches-fold" } else { "timeline-sketch-fold" }; + crate::scenario::publish_handle(&format!("{handle}:{name}"), fold_rect.center()); + } + // A row scrolled out of the History is neither drawn nor interactive: a long history drew + // and hit-tested every row each frame. Its slot still places the marker and drops, and its + // handles stay published. One being found, dragged or focused, or under an open menu, stays. + let shown = ui.clip_rect().intersects(frame) + || rows.reveal == Some(id) + || ui.ctx().is_being_dragged(row_id) + || ui.memory(|memory| memory.has_focus(row_id)) + || egui::Popup::is_any_open(ui.ctx()) + || draw_every_row(); + if shown { + let sense = if reference { Sense::click() } else { Sense::click_and_drag() }; + let mut response = ui.interact(frame, row_id, sense); + response.set_intrinsic_size(size); + let places = RowPlaces { rect, fold_rect, indent }; + feature_row_body(app, ui, rows, index, row_kind, fold.as_ref(), fold_open, places, response); + } + if names && has_patterns && fold_open { + let depth = group_id.map_or(1, |group| table.depth_of(group) + 2) + usize::from(row_kind == RowKind::Nested); + crate::sketch_pattern_tree::rows(app, ui, id, depth, "timeline", None, false); + } + if let Some(listed) = listed.filter(|_| names && fold_open) { + for child in listed { + let child_kind = if child.reference { RowKind::Reference { parent: index } } else { RowKind::Nested }; + feature_row(app, ui, rows, child.index, indent + FOLDER_INDENT, child_kind); + } + } +} + +#[cfg(test)] +thread_local! { + /// Tests compare the History drawn row by row with the one that leaves out what is out of view. + static DRAW_EVERY_ROW: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many feature rows were drawn and made interactive. + static ROWS_DRAWN: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +fn draw_every_row() -> bool { + DRAW_EVERY_ROW.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn draw_every_row() -> bool { + false +} + +/// Where a feature row in view is drawn: its chip, its fold arrow, and how far it is indented. +#[derive(Clone, Copy)] +struct RowPlaces { + rect: Rect, + fold_rect: Rect, + indent: f32, +} + +/// The drawing and interaction of a feature row that is in view. +fn feature_row_body( + app: &mut SolveApp, + ui: &mut egui::Ui, + rows: &mut Rows, + index: usize, + row_kind: RowKind, + fold: Option<&(String, bool)>, + fold_open: bool, + places: RowPlaces, + response: egui::Response, +) { + let RowPlaces { rect, fold_rect, indent } = places; + #[cfg(test)] + ROWS_DRAWN.with(|drawn| drawn.set(drawn.get() + 1)); + let t = Tokens::get(); + let (table, names, order, marker) = (rows.table, rows.names, rows.order, rows.marker); + let (features, plan, groups) = (&table.features, &table.rows, &table.groups); + let Some((id, name, icon, suppressed, ty, kind)) = features.get(index) else { return }; + let id = *id; + let group_id = table.group_of.get(index).copied().flatten(); + let reference = matches!(row_kind, RowKind::Reference { .. }); + let sketch_state = matches!(kind, TimelineKind::Sketch).then(|| rows.sketch_states.get(id)).flatten(); let on_fold = fold.is_some() && response.interact_pointer_pos().is_some_and(|p| fold_rect.contains(p)); - let result = app.session.model.result(id); + // An index that no longer holds this id (a command run from an earlier row) is searched for. + let result = rows + .results + .get(&id) + .and_then(|at| app.session.model.results.get(*at).filter(|result| result.id == id).or_else(|| app.session.model.result(id))); let elapsed = result.map(|r| r.ms); let error = result.and_then(|result| result.error.clone()); let warning = result.and_then(|result| result.warning.clone()); @@ -1486,13 +1578,13 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us RowKind::Reference { parent } => parent >= marker, RowKind::Own | RowKind::Nested => index >= marker, }; - let selected = - app.session.selection.iter().any(|selection| matches!(selection, solidcraft_engine::Sel::Feature { id: selected } if *selected == id)); + let selected = rows.selected.contains(&id); // Folder and sketch-pattern disclosure targets retain their original handles. Listing sketches // under their features keeps the fold column on every row, so the icons line up. let column = if rows.under_feature || fold.is_some() { FOLD_COLUMN } else { 0.0 }; let inset = if names { indent + column } else { 0.0 }; let chip = Rect::from_min_max(rect.min + vec2(inset.min(rect.width()), 0.0), rect.max); + let style = if names { crate::ui_kit::HistoryStyle::Names } else { crate::ui_kit::HistoryStyle::Icons }; // Dragged features take the colour of their drop bar, with the sketches listed under them. let dragged = matches!(&rows.drag, Some(Drag::Items(items)) if items.features.contains(&id) || (row_kind == RowKind::Nested && plan.host(id).is_some_and(|host| items.features.contains(&host)))); @@ -1513,8 +1605,6 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us .paint(ui.painter(), chip, style); if fold.is_some() { crate::ui_kit::disclosure(ui.painter(), fold_rect.center(), fold_open, t.text_dim); - let handle = if listed.is_some() { "timeline-sketches-fold" } else { "timeline-sketch-fold" }; - crate::scenario::publish_handle(&format!("{handle}:{name}"), fold_rect.center()); } if response.hovered() { rows.hovered = Some(id); @@ -1524,7 +1614,7 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us let origin_x = drag_press_x(&response, rect.center().x); rows.drag = Some(Drag::Items(DragItems { features, ..selected_drag_items(app, origin_x, group_id) })); } - let listed_under = plan.host(id).and_then(|host| features.iter().find(|feature| feature.0 == host)).map(|feature| feature.1.as_str()); + let listed_under = plan.host(id).and_then(|host| table.name(host)); let mut tooltip = egui::Tooltip::for_enabled(&response); tooltip.popup = tooltip.popup.align(egui::RectAlign::RIGHT_START); tooltip.show(|ui| { @@ -1555,7 +1645,7 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us } }); if response.clicked() && on_fold { - if let Some((key, default)) = &fold { + if let Some((key, default)) = fold { crate::browser::toggle(app, key, *default); } } else if response.clicked() && !crate::timeline::pick_feature_into_dialog(app, id, ui.input(|i| i.modifiers)) { @@ -1605,16 +1695,6 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us if edit { rows.edit = Some(id); } - if names && has_patterns && fold_open { - let depth = group_id.map_or(1, |group| group_depth(groups, group) + 2) + usize::from(row_kind == RowKind::Nested); - crate::sketch_pattern_tree::rows(app, ui, id, depth, "timeline", None, false); - } - if let Some(listed) = listed.filter(|_| names && fold_open) { - for child in listed { - let child_kind = if child.reference { RowKind::Reference { parent: index } } else { RowKind::Nested }; - feature_row(app, ui, rows, child.index, indent + FOLDER_INDENT, child_kind); - } - } } #[cfg(test)] @@ -3141,4 +3221,331 @@ mod tests { assert!(handle_at(&pattern_row).is_none(), "the listed sketch folds its patterns"); assert!(handle_at("timeline:Patterned").is_some()); } + + /// Folders that nest three deep, a folder with only joints, a stale feature id, a parent that + /// is no folder any more, and a feature listed in two folders: the cases the plan's tables + /// have to place as the per-frame searches did. + fn tangled_folders(h: &mut Harness) { + let ids: Vec = h.app.session.doc.features.iter().map(|feature| feature.id).collect(); + let group = |id: u64, name: &str, parent: Option, features: Vec, joints: Vec| solidcraft_engine::doc::TimelineGroup { + id, + name: name.into(), + parent, + features, + joints, + }; + let doc = h.app.session.doc_mut(); + doc.timeline_groups = vec![ + group(9001, "Outer", None, vec![ids[1], ids[2]], vec![]), + group(9002, "Middle", Some(9001), vec![ids[3], 777_777], vec![]), + group(9003, "Inner", Some(9002), vec![ids[4]], vec![55]), + group(9004, "Joints only", Some(9001), vec![], vec![56, 57]), + group(9005, "Loose", None, vec![ids[6], ids[7]], vec![]), + group(9006, "Orphan", Some(4242), vec![ids[8]], vec![]), + group(9007, "Twice", None, vec![ids[7], ids[9]], vec![]), + group(9008, "Empty", Some(9005), vec![], vec![]), + ]; + h.app.session.revision += 1; + } + + /// The plan's tables against the per-frame searches they replaced, in every fold state. + fn assert_plan_matches_the_searches(h: &mut Harness, under_feature: bool) { + let table = RowPlan::of(&h.app, under_feature); + let app = &h.app; + let (features, groups) = (&table.features, &table.groups); + let n = features.len(); + assert_eq!(table.rows, drawn_rows(app, under_feature)); + for (index, feature) in features.iter().enumerate() { + assert_eq!(table.group_of[index], group_for(groups, feature.0), "{}", feature.1); + let sketch = matches!(feature.5, TimelineKind::Sketch); + assert_eq!(sketch && table.has_patterns[index], sketch && crate::sketch_pattern_tree::has_patterns(app, feature.0)); + } + for (at, group) in groups.iter().enumerate() { + assert_eq!(table.depth[at], group_depth(groups, group.id), "{}", group.name); + assert_eq!(table.first[at], group_first_feature(groups, features, group.id), "{}", group.name); + assert_eq!(table.position[at], group_position(groups, features, group.id), "{}", group.name); + assert_eq!(table.end[at], group_last_feature(groups, features, group.id).map_or(n, |index| index + 1), "{}", group.name); + assert_eq!(table.contents[at], folder_features(app, &[group.id]), "{}", group.name); + let joints: Vec = groups + .iter() + .filter(|candidate| candidate.id == group.id || group_is_descendant(groups, candidate.id, group.id)) + .flat_map(|group| group.joints.iter().copied()) + .collect(); + assert_eq!(table.joints[at], joints, "{}", group.name); + } + let index_of = |group: &solidcraft_engine::doc::TimelineGroup| groups.iter().position(|candidate| std::ptr::eq(candidate, group)).unwrap(); + for index in 0..n { + let mut at_index: Vec<_> = groups.iter().filter(|group| group_position(groups, features, group.id) == Some(index)).collect(); + at_index.sort_by_key(|group| group_path(groups, group.id)); + assert_eq!(table.starting[index], at_index.into_iter().map(index_of).collect::>(), "headers before {index}"); + let mut ending: Vec<_> = groups.iter().filter(|group| group_last_feature(groups, features, group.id) == Some(index)).collect(); + ending.sort_by_key(|group| std::cmp::Reverse(group_depth(groups, group.id))); + assert_eq!(table.ending[index], ending.into_iter().map(index_of).collect::>(), "folders ending at {index}"); + } + let mut trailing: Vec<_> = groups.iter().collect(); + trailing.sort_by_key(|group| (group_position(groups, features, group.id).unwrap_or(usize::MAX), group_path(groups, group.id))); + assert_eq!(table.trailing, trailing.into_iter().map(index_of).collect::>()); + // Every combination of closed folders (and a stale key for the missing parent), with + // and without the listed sketches shown. + let keys: Vec = groups.iter().map(|group| group.id).chain([4242]).map(|id| format!("timeline_group:{id}")).collect(); + let hosts: Vec = 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()); + 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.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}"); + for group in groups { + assert_eq!(table.is_open(&folds, group.id), group_is_open(app, groups, group.id), "{}", group.name); + assert_eq!(table.ancestors_open(&folds, group.id), group_ancestors_are_open(app, groups, group.id), "{}", group.name); + } + } + } + (h.app.tree.collapsed, h.app.tree.expanded) = kept; + } + + #[test] + fn the_row_plan_places_folders_and_rows_as_the_per_frame_searches_did() { + let mut h = nested_history(); + square(&mut h, "Profile", 0.0); + extrude(&mut h, "Profile", "Block", "new"); + square(&mut h, "Pocket", 20.0); + extrude(&mut h, "Pocket", "Second", "new"); + for (k, x) in [40.0, 60.0, 80.0].into_iter().enumerate() { + let name = format!("Sketch {k}"); + square(&mut h, &name, x); + extrude(&mut h, &name, &format!("Body {k}"), "new"); + } + h.app.run("timeline.roll_to", json!({"position": 7})).unwrap(); + tangled_folders(&mut h); + h.settle(); + for under_feature in [false, true] { + assert_plan_matches_the_searches(&mut h, under_feature); + } + // Without folders, and with an empty design. + h.app.session.doc_mut().timeline_groups.clear(); + assert_plan_matches_the_searches(&mut h, true); + assert_plan_matches_the_searches(&mut Harness::new(), false); + } + + #[test] + fn the_kept_row_plan_is_the_one_built_afresh_after_every_change() { + let mut h = nested_history(); + square(&mut h, "Profile", 0.0); + extrude(&mut h, "Profile", "Block", "new"); + square(&mut h, "Pocket", 20.0); + extrude(&mut h, "Pocket", "Second", "new"); + h.settle(); + let check = |h: &mut Harness, what: &str| { + h.frames(2); + let kept = RowPlan::kept(&h.ctx).expect("the History drew a plan"); + assert_eq!(kept.summary(), RowPlan::of(&h.app, kept.under_feature()).summary(), "{what}"); + }; + check(&mut h, "opened"); + let id = |h: &Harness, name: &str| h.app.session.doc.find_feature(name).unwrap().id; + let (block, second) = (id(&h, "Block"), id(&h, "Second")); + assert!(RowPlan::kept(&h.ctx).unwrap().under_feature(), "sketches are listed under their features"); + let steps: [(&str, serde_json::Value); 6] = [ + ("timeline.group", json!({"name": "Housing", "features": ["Profile", "Block"]})), + ("timeline.rename", json!({"feature": second, "name": "Lid"})), + ("timeline.suppress", json!({"feature": block})), + ("timeline.roll_to", json!({"position": 2})), + ("timeline.roll_to", json!({})), + ("timeline.move_many", json!({"features": [block], "position": 4, "group": null, "active": true})), + ]; + for (command, params) in steps { + h.app.run(command, params.clone()).unwrap_or_else(|e| panic!("{command} {params}: {e}")); + check(&mut h, command); + } + h.app.run("edit.undo", json!({})).unwrap(); + check(&mut h, "undo"); + // An edit in place without a revision, and the preference. + h.app.session.doc_mut().marker = Some(1); + check(&mut h, "marker set in place"); + h.app.preferences.history_sketches = crate::prefs::HistorySketches::InOrder; + check(&mut h, "sketches in order"); + // Another design in the same window. + let other = h.app.session.doc.clone(); + h.app.session = solidcraft_engine::Session::new(solidcraft_engine::doc::Document::default()); + check(&mut h, "new design"); + h.app.session = solidcraft_engine::Session::new((*other).clone()); + check(&mut h, "the first design again"); + } + + /// A history taller than its panel, drawn with every row and with the rows out of view left + /// out: the same places, the same text in view, and only the rows in view painted. + #[test] + fn rows_out_of_view_keep_their_places_and_what_is_in_view_draws_the_same() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_left_width = 240.0; + h.call("ui.resize", json!({"width": 1200, "height": 700})); + for k in 0..60 { + h.app + .run( + "solid.box", + json!({"length": 5, "width": 5, "height": 5, "corner": [k * 10, 0, 0], "operation": "new_body", "name": format!("Box {k}")}), + ) + .unwrap(); + } + let ids: Vec = h.app.session.doc.features.iter().map(|feature| feature.id).collect(); + h.app.run("timeline.group", json!({"name": "Front", "features": ids[5..15]})).unwrap(); + h.app.run("timeline.roll_to", json!({"position": 40})).unwrap(); + h.settle(); + let draw = |h: &mut Harness, every: bool| { + DRAW_EVERY_ROW.with(|cell| cell.set(every)); + h.frames(2); + ROWS_DRAWN.with(|drawn| drawn.set(0)); + h.frame(); + let painted = ROWS_DRAWN.with(std::cell::Cell::get); + DRAW_EVERY_ROW.with(|cell| cell.set(false)); + let card = h.app.shell.history.expect("history bounds"); + let places: Vec<_> = (0..60).map(|k| crate::scenario::rect_of(&format!("history:feature:Box {k}"))).collect(); + // The text that shows in the History: inside the card and inside its clip. + let texts: Vec = h + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some((clipped.clip_rect, text)), + _ => None, + }) + .filter(|(clip, text)| text.visual_bounding_rect().intersects(card.intersect(*clip))) + .map(|(_, text)| text.galley.text().to_string()) + .collect(); + (places, texts, painted) + }; + for reveal in [None, Some(ids[30]), Some(ids[59])] { + h.app.tree.timeline_reveal = reveal; + // A second for the scroll to arrive. + h.frames(60); + let (every_places, every_texts, every_painted) = draw(&mut h, true); + let (places, texts, painted) = draw(&mut h, false); + assert!(places.iter().all(Option::is_some), "every row keeps its handle"); + assert_eq!(places, every_places, "{reveal:?}"); + assert_eq!(texts, every_texts, "{reveal:?}"); + assert!(texts.iter().any(|text| text.starts_with("Box ")), "{reveal:?}: rows are in view"); + assert_eq!(every_painted, 60, "{reveal:?}"); + assert!(painted < 40, "{reveal:?}: {painted} of {every_painted} rows drawn"); + } + // A drag among the rows in view still moves a feature, with rows out of view left out. + h.app.tree.timeline_reveal = Some(ids[0]); + h.frames(60); + let target = handle_at("timeline:Box 3").unwrap(); + h.step(&json!({"drag": [{"handle": "timeline:Box 1"}, [target.x, target.y + 8.0]]})).unwrap(); + let names = feature_names(&h); + assert_eq!(names[..4], ["Box 0", "Box 2", "Box 3", "Box 1"], "{names:?}"); + assert_eq!(names.len(), 60); + } + + /// Frame time of the vertical History alone on a large design (P5 measurement, run by hand): + /// `SOLIDCRAFT_HISTORY_BENCH= cargo test --release -p solidcraft-ui-egui --lib + /// bench_history_panel -- --ignored --nocapture`. Prints one JSON line per case. The folders + /// cases add 120 folders of 20 features (every fourth nested in the one before). + #[test] + #[ignore = "timing, run by hand with SOLIDCRAFT_HISTORY_BENCH"] + fn bench_history_panel_frames() { + let Some(path) = std::env::var_os("SOLIDCRAFT_HISTORY_BENCH") else { return }; + let frames: usize = std::env::var("SOLIDCRAFT_HISTORY_BENCH_FRAMES").ok().and_then(|n| n.parse().ok()).unwrap_or(40); + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.timeline_left = true; + h.app.run("doc.open", json!({"path": path.to_string_lossy()})).unwrap(); + let ctx = crate::fonts::test_context(); + let size = egui::vec2(300.0, 1000.0); + let mut time = 0.0; + let mut run = |app: &mut SolveApp, events: Vec| { + time += 1.0 / 60.0; + crate::scenario::clear_handles(); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), + time: Some(time), + focused: true, + events, + ..Default::default() + }; + let start = std::time::Instant::now(); + let mut out = ctx.run_ui(raw, |ui| left_timeline(app, ui)); + let ms = start.elapsed().as_secs_f64() * 1000.0; + out.textures_delta.clear(); + ms + }; + let report = |case: &str, mut ms: Vec| { + ms.sort_by(f64::total_cmp); + let median = ms[ms.len() / 2]; + println!("{}", json!({"case": case, "median_ms": median, "min_ms": ms[0], "max_ms": ms[ms.len() - 1], "frames": ms.len()})); + }; + let features = h.app.session.doc.features.len(); + println!("{}", json!({"features": features, "groups": h.app.session.doc.timeline_groups.len()})); + let order: Vec = h.app.session.doc.features.iter().map(|f| f.id).collect(); + let middle = h.app.session.doc.features[features / 2].id; + let middle_name = h.app.session.doc.features[features / 2].name.clone(); + let moves = |y0: f32, i: usize| vec![egui::Event::PointerMoved(egui::pos2(150.0, y0 + (i % 7) as f32 * 3.0))]; + // SOLIDCRAFT_HISTORY_BENCH_CASES: "plain", "folders" or both (the default). + let cases = std::env::var("SOLIDCRAFT_HISTORY_BENCH_CASES").unwrap_or_default(); + for folders in [false, true] { + if !cases.is_empty() && cases != if folders { "folders" } else { "plain" } { + continue; + } + if folders { + // 120 folders of 20 features each, every fourth nested in the folder before it. + let ids: Vec = h.app.session.doc.features.iter().map(|f| f.id).collect(); + let doc = h.app.session.doc_mut(); + let mut next = doc.next_id.max(1_000_000); + let mut previous = None; + for (k, chunk) in ids.chunks(20).take(120).enumerate() { + let id = next; + next += 1; + let parent = if k % 4 == 3 { previous } else { None }; + doc.timeline_groups.push(solidcraft_engine::doc::TimelineGroup { + id, + name: format!("Folder {k}"), + parent, + features: chunk.to_vec(), + joints: Vec::new(), + }); + previous = Some(id); + } + doc.next_id = next; + h.app.session.revision += 1; + } + let tag = if folders { "folders" } else { "plain" }; + for _ in 0..3 { + run(&mut h.app, Vec::new()); + } + report(&format!("{tag}/top idle"), (0..frames).map(|_| run(&mut h.app, Vec::new())).collect()); + report(&format!("{tag}/top hover"), (0..frames).map(|i| run(&mut h.app, moves(300.0, i))).collect()); + h.app.tree.timeline_reveal = Some(middle); + for _ in 0..3 { + run(&mut h.app, Vec::new()); + } + report(&format!("{tag}/middle idle"), (0..frames).map(|_| run(&mut h.app, Vec::new())).collect()); + report(&format!("{tag}/middle hover"), (0..frames).map(|i| run(&mut h.app, moves(400.0, i))).collect()); + // Drag the middle feature: press on it, then move the pointer each frame. + crate::scenario::clear_handles(); + run(&mut h.app, Vec::new()); + let at = handle_at(&format!("timeline:{middle_name}")).unwrap_or(egui::pos2(150.0, 500.0)); + run(&mut h.app, vec![egui::Event::PointerMoved(at)]); + run( + &mut h.app, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + let drag: Vec = + (0..frames).map(|i| run(&mut h.app, vec![egui::Event::PointerMoved(at + egui::vec2(0.0, 12.0 + (i % 5) as f32 * 4.0))])).collect(); + report(&format!("{tag}/middle drag"), drag); + // Let go with the pointer gone in the same frame: the drop has no place, so nothing moves. + run( + &mut h.app, + vec![ + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }, + egui::Event::PointerGone, + ], + ); + run(&mut h.app, Vec::new()); + } + let after: Vec = h.app.session.doc.features.iter().map(|f| f.id).collect(); + assert_eq!(after, order, "measuring moved nothing"); + } } diff --git a/crates/ui-egui/src/timeline_left/plan.rs b/crates/ui-egui/src/timeline_left/plan.rs new file mode 100644 index 000000000..5eefcce74 --- /dev/null +++ b/crates/ui-egui/src/timeline_left/plan.rs @@ -0,0 +1,452 @@ +//! The vertical History's row plan: which folder headers, feature rows and joint rows come where. +//! +//! Working this out from the design took every frame several passes over all features for each +//! folder (and a search for each folder's last feature at every row), which a long history with +//! folders paid for on every repaint, even with the pointer only moving. Everything here follows +//! from the design alone, so it is built once per design change ([`RowPlan::of`]) and kept in the +//! egui context; what the open folders and folds change ([`RowPlan::order`]) is kept beside it +//! until one of them opens or closes. The functions it replaced live on in the tests as the +//! reference it is compared with. + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::sync::Arc; + +use solidcraft_engine::doc::TimelineGroup; + +use super::{TimelineItem, group_path, sketches_key}; +use crate::SolveApp; +use crate::history_rows::{HistoryFeature, HistoryRows}; +use crate::timeline::{TimelineKind, icon_of}; + +/// A feature as its row draws it: id, name, icon, suppressed, type name and kind. +pub(super) type FeatureInfo = (u64, String, &'static str, bool, &'static str, TimelineKind); + +/// What a plan was built from. The design changes through commands, which count the session's +/// revision up; the marker and the counts guard edits made in place without one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PlanKey { + session: u64, + revision: u64, + document: usize, + marker: Option, + features: usize, + groups: usize, + under_feature: bool, +} + +impl PlanKey { + fn of(app: &SolveApp, under_feature: bool) -> Self { + let doc = &app.session.doc; + Self { + session: app.session.uid, + revision: app.session.revision, + document: Arc::as_ptr(doc) as usize, + marker: doc.marker, + features: doc.features.len(), + groups: doc.timeline_groups.len(), + under_feature, + } + } +} + +/// The folders and folds that are open: the visible order follows from these and the plan. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(super) struct Folds { + /// Folders closed by the person, by id. + closed: HashSet, + /// Features whose listed sketches are shown. + open_hosts: BTreeSet, +} + +impl Folds { + pub(super) fn is_closed(&self, group: u64) -> bool { + self.closed.contains(&group) + } +} + +pub(super) struct RowPlan { + key: PlanKey, + pub features: Vec, + pub groups: Vec, + /// The rows to draw (`drawn_rows`). + pub rows: HistoryRows, + /// Each feature id's first timeline position. + index_of: HashMap, + /// The folder each feature is in (`group_for`), by timeline position. + pub group_of: Vec>, + /// Whether the sketch at each timeline position has patterns. + pub has_patterns: Vec, + /// The first folder with each id: the one `groups.iter().find` would give. + by_id: HashMap, + /// By folder index: its nesting depth. + pub depth: Vec, + /// By folder index: the position of its first own or nested feature. + pub first: Vec>, + /// By folder index: where its header goes, its own first feature or that of the nearest + /// ancestor that has one. + pub position: Vec>, + /// By folder index: the position after its last own or nested feature (the end with none). + pub end: Vec, + /// By timeline position: the folders whose header goes before it, outermost first. + pub starting: Vec>, + /// By timeline position: the folders whose last feature it is, innermost first. + pub ending: Vec>, + /// Every folder in the order of headers left over after the features. + pub trailing: Vec, + /// By folder index: its own and nested features in timeline order (`folder_features`). + pub contents: Vec>, + /// By folder index: its own and nested folders' joints. + pub joints: Vec>, + /// Each folder and parent id, with its fold key in the tree state. + fold_keys: Vec<(u64, String)>, + /// Features with sketches listed under them, and their fold keys. + host_keys: Vec<(u64, String)>, +} + +impl RowPlan { + /// The plan for the design as it is, kept until it changes. + pub(super) fn cached(app: &SolveApp, ui: &egui::Ui, under_feature: bool) -> Arc { + let id = egui::Id::new("sc_history_row_plan"); + let key = PlanKey::of(app, under_feature); + if let Some(plan) = ui.data(|data| data.get_temp::>(id)).filter(|plan| plan.key == key) { + return plan; + } + let plan = Arc::new(Self::of(app, under_feature)); + ui.data_mut(|data| data.insert_temp(id, plan.clone())); + plan + } + + /// Build the plan from the design. + pub(super) fn of(app: &SolveApp, under_feature: bool) -> Self { + let doc = &app.session.doc; + let features: Vec = doc + .features + .iter() + .map(|feature| { + ( + feature.id, + feature.name.clone(), + icon_of(&feature.kind), + feature.suppressed, + feature.kind.type_name(), + TimelineKind::of(&feature.kind), + ) + }) + .collect(); + let groups = doc.timeline_groups.clone(); + let rows = if under_feature { + let listed: Vec = doc.features.iter().map(HistoryFeature::of).collect(); + crate::history_rows::rows(&listed, &groups, doc.marker, true) + } else { + let sketch = |feature: &solidcraft_engine::doc::Feature| matches!(feature.kind, solidcraft_engine::doc::FeatureKind::Sketch { .. }); + HistoryRows::in_order(doc.features.iter().map(|feature| (feature.id, sketch(feature)))) + }; + let mut index_of = HashMap::with_capacity(features.len()); + for (index, feature) in features.iter().enumerate() { + index_of.entry(feature.0).or_insert(index); + } + let mut by_id = HashMap::with_capacity(groups.len()); + let mut member_of = HashMap::new(); + let mut children: HashMap> = HashMap::new(); + for (index, group) in groups.iter().enumerate() { + by_id.entry(group.id).or_insert(index); + for feature in &group.features { + member_of.entry(*feature).or_insert(group.id); + } + if let Some(parent) = group.parent { + children.entry(parent).or_default().push(index); + } + } + let group_of: Vec> = features.iter().map(|feature| member_of.get(&feature.0).copied()).collect(); + // `doc.sketch(id)` reads the first feature with the id. + let has_patterns = features + .iter() + .map(|feature| { + index_of.get(&feature.0).and_then(|index| doc.features.get(*index)).is_some_and( + |feature| matches!(&feature.kind, solidcraft_engine::doc::FeatureKind::Sketch { sketch, .. } if !sketch.patterns.is_empty()), + ) + }) + .collect(); + // A parent that is no folder (any more) is still looked up by its key, as before. + let fold_ids: BTreeSet = groups.iter().flat_map(|group| [Some(group.id), group.parent]).flatten().collect(); + let mut plan = Self { + key: PlanKey::of(app, under_feature), + index_of, + group_of, + has_patterns, + by_id, + depth: Vec::new(), + first: Vec::new(), + position: Vec::new(), + end: Vec::new(), + starting: vec![Vec::new(); features.len()], + ending: vec![Vec::new(); features.len()], + trailing: Vec::new(), + contents: Vec::new(), + joints: Vec::new(), + fold_keys: fold_ids.into_iter().map(|id| (id, format!("timeline_group:{id}"))).collect(), + host_keys: rows.rows.iter().filter(|row| !row.listed.is_empty()).map(|row| (row.feature, sketches_key(row.feature))).collect(), + features, + groups, + rows, + }; + plan.place_folders(&children); + plan + } + + /// The folders' depths, extents, header places and contents. + fn place_folders(&mut self, children: &HashMap>) { + let groups = &self.groups; + let n = self.features.len(); + let ids: Vec = groups.iter().map(|group| group.id).collect(); + self.depth = ids.iter().map(|id| self.depth_of(*id)).collect(); + let mut first = HashMap::new(); + let mut last = HashMap::new(); + for id in &ids { + self.extent(*id, children, &mut first, &mut last, &mut HashSet::new()); + } + self.first = ids.iter().map(|id| first.get(id).copied().flatten()).collect(); + self.end = ids.iter().map(|id| last.get(id).copied().flatten().map_or(n, |index: usize| index.saturating_add(1))).collect(); + // A folder with only joints shares its nearest feature-bearing ancestor's position. + self.position = ids + .iter() + .map(|id| { + let mut current = Some(*id); + for _ in 0..groups.len() { + let id = current?; + if let Some(first) = first.get(&id).copied().flatten() { + return Some(first); + } + current = self.parent_of(id); + } + None + }) + .collect(); + let paths: Vec> = ids.iter().map(|id| group_path(groups, *id)).collect(); + for (index, position) in self.position.iter().enumerate() { + if let Some(slot) = position.and_then(|position| self.starting.get_mut(position)) { + slot.push(index); + } + } + for starting in &mut self.starting { + starting.sort_by(|a, b| paths.get(*a).cmp(&paths.get(*b))); + } + for (index, id) in ids.iter().enumerate() { + if let Some(slot) = last.get(id).copied().flatten().and_then(|last| self.ending.get_mut(last)) { + slot.push(index); + } + } + for ending in &mut self.ending { + ending.sort_by_key(|index| std::cmp::Reverse(self.depth.get(*index).copied())); + } + let mut trailing: Vec = (0..groups.len()).collect(); + let place = |at: usize| (self.position.get(at).copied().flatten().unwrap_or(usize::MAX), paths.get(at)); + trailing.sort_by(|a, b| place(*a).cmp(&place(*b))); + self.trailing = trailing; + // A folder holds its own features and those of the folders nested in it, as + // `group_is_descendant` decides (a broken chain of parents counts as inside everything). + let ancestors: HashMap>> = ids.iter().map(|id| (*id, self.ancestors(*id))).collect(); + let inside = |group: u64, root: u64| group == root || ancestors.get(&group).is_some_and(|up| up.as_ref().is_none_or(|up| up.contains(&root))); + self.contents = ids + .iter() + .map(|root| { + self.group_of + .iter() + .zip(&self.features) + .filter(|(group, _)| group.is_some_and(|group| inside(group, *root))) + .map(|(_, feature)| feature.0) + .collect() + }) + .collect(); + self.joints = ids + .iter() + .map(|root| groups.iter().filter(|candidate| inside(candidate.id, *root)).flat_map(|group| group.joints.iter().copied()).collect()) + .collect(); + } + + /// The first and last timeline positions of `id`'s own and nested features. + fn extent( + &self, + id: u64, + children: &HashMap>, + first: &mut HashMap>, + last: &mut HashMap>, + visiting: &mut HashSet, + ) -> (Option, Option) { + if let (Some(a), Some(b)) = (first.get(&id), last.get(&id)) { + return (*a, *b); + } + // A folder nested in itself adds nothing more. + if !visiting.insert(id) { + return (None, None); + } + let Some(group) = self.by_id.get(&id).and_then(|index| self.groups.get(*index)) else { + first.insert(id, None); + last.insert(id, None); + return (None, None); + }; + let direct: Vec = group.features.iter().filter_map(|feature| self.index_of.get(feature).copied()).collect(); + let (mut low, mut high) = (direct.iter().copied().min(), direct.iter().copied().max()); + for child in children.get(&id).into_iter().flatten() { + let Some(child) = self.groups.get(*child).map(|child| child.id) else { continue }; + let (a, b) = self.extent(child, children, first, last, visiting); + low = low.into_iter().chain(a).min(); + high = high.into_iter().chain(b).max(); + } + visiting.remove(&id); + first.insert(id, low); + last.insert(id, high); + (low, high) + } + + fn parent_of(&self, id: u64) -> Option { + self.by_id.get(&id).and_then(|index| self.groups.get(*index)).and_then(|group| group.parent) + } + + /// The depth of the first folder with `id` (`group_depth`). + pub(super) fn depth_of(&self, id: u64) -> usize { + let mut depth = 0; + let mut current = self.parent_of(id); + while let Some(parent) = current { + depth += 1; + if depth > self.groups.len() { + break; + } + current = self.parent_of(parent); + } + depth + } + + /// The folders above `id`; `None` when its chain of parents never ends. + fn ancestors(&self, id: u64) -> Option> { + let mut found = HashSet::new(); + let mut current = self.parent_of(id); + let mut steps = 0usize; + while let Some(parent) = current { + found.insert(parent); + steps += 1; + if steps > self.groups.len() { + return None; + } + current = self.parent_of(parent); + } + Some(found) + } + + /// Whether `id` and every folder around it are open (`group_is_open`). + pub(super) fn is_open(&self, folds: &Folds, id: u64) -> bool { + !folds.is_closed(id) && self.ancestors_open(folds, id) + } + + /// Whether every folder around `id` is open (`group_ancestors_are_open`). + pub(super) fn ancestors_open(&self, folds: &Folds, id: u64) -> bool { + let mut current = self.parent_of(id); + let mut steps = 0usize; + while let Some(group) = current { + if folds.is_closed(group) { + return false; + } + steps += 1; + if steps > self.groups.len() { + return false; + } + current = self.parent_of(group); + } + true + } + + /// Whether the feature with `id` is suppressed. + pub(super) fn suppressed(&self, id: u64) -> bool { + self.index_of.get(&id).and_then(|index| self.features.get(*index)).is_some_and(|feature| feature.3) + } + + /// The name of the feature with `id`. + pub(super) fn name(&self, id: u64) -> Option<&str> { + self.index_of.get(&id).and_then(|index| self.features.get(*index)).map(|feature| feature.1.as_str()) + } + + /// 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(); + let open_hosts = self.host_keys.iter().filter(|(_, key)| crate::browser::is_open(app, key, false)).map(|(feature, _)| *feature).collect(); + Folds { closed, open_hosts } + } + + /// The visible items top to bottom (`visible_order`), kept until a folder or fold opens or + /// closes. + pub(super) fn order(&self, ui: &egui::Ui, folds: &Folds) -> Arc> { + type Kept = (PlanKey, Folds, Arc>); + let id = egui::Id::new("sc_history_row_order"); + if let Some(kept) = ui.data(|data| data.get_temp::>(id)).filter(|kept| kept.0 == self.key && kept.1 == *folds) { + return kept.2.clone(); + } + let order = Arc::new(self.visible_order(folds)); + ui.data_mut(|data| data.insert_temp(id, Arc::new((self.key, folds.clone(), order.clone())))); + order + } + + pub(super) fn visible_order(&self, folds: &Folds) -> Vec { + let mut order = Vec::new(); + let mut shown = HashSet::new(); + for (index, (id, ..)) in self.features.iter().enumerate() { + for group in self.starting.get(index).into_iter().flatten().filter_map(|group| self.groups.get(*group)) { + if self.ancestors_open(folds, group.id) && shown.insert(group.id) { + order.push(TimelineItem::Group(group.id)); + } + } + // A listed sketch follows the feature built from it. + let Some(row) = self.rows.row_at(index) else { continue }; + if self.group_of.get(index).copied().flatten().is_none_or(|group| self.is_open(folds, group)) { + order.push(TimelineItem::Feature(*id)); + if !row.listed.is_empty() && folds.open_hosts.contains(id) { + order.extend(row.listed.iter().filter(|listed| !listed.reference).map(|listed| TimelineItem::Feature(listed.sketch))); + } + } + } + for group in self.trailing.iter().filter_map(|group| self.groups.get(*group)) { + if !shown.contains(&group.id) && self.ancestors_open(folds, group.id) && shown.insert(group.id) { + order.push(TimelineItem::Group(group.id)); + } + } + order + } +} + +#[cfg(test)] +impl RowPlan { + /// Everything the plan holds, comparable: a cached plan must equal one built afresh. + pub(super) fn summary(&self) -> String { + let features: Vec<_> = self.features.iter().map(|f| (f.0, &f.1, f.2, f.3, f.4, std::mem::discriminant(&f.5))).collect(); + let mut index_of: Vec<_> = self.index_of.iter().collect(); + index_of.sort(); + let mut by_id: Vec<_> = self.by_id.iter().collect(); + by_id.sort(); + format!( + "{features:?}\n{:?}\n{:?}\n{index_of:?}\n{:?}\n{:?}\n{by_id:?}\n{:?}\n{:?}\n{:?}\n{:?}\n{:?}\n{:?}\n{:?}\n{:?}\n{:?}\n{:?}\n{:?}", + self.groups, + self.rows, + self.group_of, + self.has_patterns, + self.depth, + self.first, + self.position, + self.end, + self.starting, + self.ending, + self.trailing, + self.contents, + self.joints, + self.fold_keys, + self.host_keys, + ) + } + + pub(super) fn under_feature(&self) -> bool { + self.key.under_feature + } + + /// The plan the History drew with last, from the egui context. + pub(super) fn kept(ctx: &egui::Context) -> Option> { + ctx.data(|data| data.get_temp::>(egui::Id::new("sc_history_row_plan"))) + } +}