diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e9b3d7ec5..351020f57 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -39,13 +39,13 @@ pub static COMMANDS: &[CommandSpec] = &[ .doc_only() .params("features?: [id|name], groups?: [ids], group?: id (omit or null to move to the timeline root)"), CommandSpec::new("timeline.move_many", "Move Timeline Items", move_many).icon("reorder").params( - "features?: [id|name], groups?: [folder ids], group?: folder id, position: insertion slot; atomically changes folder membership and moves all selected contents as one block", + "features?: [id|name], groups?: [folder ids], group?: folder id, position: insertion slot, active?: bool (true = the moved contents end up before the history marker, false = behind it; other features keep their state); atomically changes folder membership and moves all selected contents as one block", ), CommandSpec::new("timeline.rollback", "Move Timeline Marker", rollback).icon("rollback").params("position: number of features to keep active, or \"end\" (omit = end)"), CommandSpec::new("timeline.roll_to", "Roll History Marker", rollback).icon("rollback") .params("position: number of features to keep active, or \"end\" (omit = end) | feature: id|name (the marker goes right after it)"), CommandSpec::new("timeline.reorder", "Reorder Feature", reorder).icon("reorder") - .params("feature: id|name, position: its new index; refused when a feature that worked would fail"), + .params("feature: id|name, position: its new index, active?: bool (true = it ends up before the history marker, false = behind it; other features keep their state); refused when a feature that worked would fail"), CommandSpec::new("timeline.reorder_many", "Reorder Features", reorder_many).icon("reorder").params( "features: [id|name], position: insertion slot in the current history; selected features keep their relative order; refused when a feature that worked would fail", ), @@ -491,7 +491,9 @@ fn move_many(s: &mut Session, p: &Value) -> Result { } sort_group_features(&mut next); let slot = num(p, "position").map(|x| x.max(0.0) as usize).ok_or_else(|| bad(cmd, "`position` must be a number"))?; - let (next, ordered) = reorder_features(s, next, &moving, slot, cmd)?; + let active = active_param(p, cmd)?; + let (mut next, ordered) = reorder_features(s, next, &moving, slot, cmd)?; + place_marker(s, &mut next, &moving, active, cmd)?; if next != *s.doc { *s.doc_mut() = next; } @@ -1057,7 +1059,8 @@ fn reorder(s: &mut Session, p: &Value) -> Result { let n = s.doc.features.len(); let to = num(p, "position").map(|x| x.max(0.0) as usize).ok_or_else(|| bad(cmd, "`position` must be a number"))?.min(n.saturating_sub(1)); let from = s.doc.feature_index(id).ok_or_else(|| bad(cmd, "feature"))?; - if from == to { + let active = active_param(p, cmd)?; + if from == to && active.is_none() { return Ok(json!({"feature": id, "position": to})); } let mut next = (*s.doc).clone(); @@ -1074,10 +1077,39 @@ fn reorder(s: &mut Session, p: &Value) -> Result { let list: Vec = broken.iter().map(|(n, e)| format!("{n} ({e})")).collect(); return Err(bad(cmd, format!("moving {name} there breaks {}", list.join("; ")))); } - *s.doc_mut() = next; + place_marker(s, &mut next, &[id], active, cmd)?; + if next != *s.doc { + *s.doc_mut() = next; + } Ok(json!({"feature": id, "position": to})) } +/// The optional `active` of a move: whether the moved features end up before the history marker. +fn active_param(p: &Value, cmd: &str) -> Result> { + match p.get("active") { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(active)) => Ok(Some(*active)), + Some(_) => Err(bad(cmd, "`active` must be true or false")), + } +} + +/// With `active` given, put the history marker of the reordered `next` so the `moving` features +/// are active (before it) or rolled back (behind it) while every other feature keeps its state, in +/// the same step as the move. Refused when `position` puts them on the other side of it. +fn place_marker(s: &Session, next: &mut solidcraft_doc::Document, moving: &[u64], active: Option, cmd: &str) -> Result<()> { + let Some(active) = active else { return Ok(()) }; + let n = s.doc.features.len(); + let was_active: std::collections::BTreeSet = s.doc.features.iter().take(s.doc.marker.unwrap_or(n)).map(|feature| feature.id).collect(); + let stays_active = |id: u64| if moving.contains(&id) { active } else { was_active.contains(&id) }; + let count = next.features.iter().filter(|feature| stays_active(feature.id)).count(); + if !next.features.iter().take(count).all(|feature| stays_active(feature.id)) { + let side = if active { "before" } else { "behind" }; + return Err(bad(cmd, format!("`position` is not {side} the history marker, as `active: {active}` asks"))); + } + next.marker = (count < next.features.len()).then_some(count); + Ok(()) +} + fn reorder_many(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.reorder_many"; let ids = group_features(s, p, true, cmd)?; diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index 6e8116051..15b60ec68 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -545,6 +545,40 @@ fn timeline_move_many_is_atomic_and_one_undo_step() { assert_eq!(*s.doc, before_parent, "creating a parent for selected folders is one undo step"); } +/// `active` moves features across the history marker together with the reorder: one undo step +/// restores both the order and the marker. Before, moving a feature more than one step behind the +// history marker would need two undo steps: one to retore the order and one to move the marker +#[test] +fn timeline_moves_across_the_marker_are_one_undo_step() { + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 20), ("C", 40), ("D", 60)] { + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0], "operation": "new_body", "name": name})); + } + run(&mut s, "timeline.roll_to", json!({"position": 2})); + let names = |s: &Session| s.doc.features.iter().map(|feature| feature.name.clone()).collect::>(); + let before = (*s.doc).clone(); + + // A B | C D: B moves between C and D, rolled back; C stays rolled back. + run(&mut s, "timeline.move_many", json!({"features": ["B"], "position": 3, "active": false})); + assert_eq!((names(&s), s.doc.marker), (vec!["A".into(), "C".into(), "B".into(), "D".into()], Some(1))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(*s.doc, before, "one undo restores both order and marker"); + + // B stays in place and only crosses the marker; and back again with `timeline.reorder`. + run(&mut s, "timeline.move_many", json!({"features": ["B"], "position": 2, "active": false})); + assert_eq!((names(&s), s.doc.marker), (vec!["A".into(), "B".into(), "C".into(), "D".into()], Some(1))); + run(&mut s, "timeline.reorder", json!({"feature": "B", "position": 1, "active": true})); + assert_eq!(s.doc.marker, Some(2)); + run(&mut s, "timeline.reorder", json!({"feature": "C", "position": 2, "active": true})); + run(&mut s, "timeline.reorder", json!({"feature": "D", "position": 3, "active": true})); + assert_eq!(s.doc.marker, None, "every feature active again"); + + let undo = s.undo.len(); + let error = s.execute("timeline.reorder", &json!({"feature": "A", "position": 0, "active": false})).unwrap_err().to_string(); + assert!(error.contains("behind the history marker"), "{error}"); + assert_eq!(s.undo.len(), undo, "a refused move adds no undo step"); +} + #[test] fn failed_timeline_move_many_keeps_folder_membership_and_order() { let mut s = Session::default(); diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 6a418cda0..9f2d67e96 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -459,7 +459,8 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { suppressed: *suppressed, error: err.is_some(), warning: warn.is_some(), - accent, + // A dragged feature takes the colour of its drop bar. + accent: if drag == Some(Drag::Feature(*id)) { crate::theme::TabAccent::for_tab(&t, "SKETCH") } else { accent }, } .paint(&p, br, crate::ui_kit::HistoryStyle::Bottom); let mut tip = status_text(name, ty, err.as_deref(), warn.as_deref()); @@ -549,6 +550,9 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { if resp.drag_started() { drag = Some(Drag::Marker); } + if resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } crate::ui_kit::history_marker(&p, mr, false, accent); resp.on_hover_text("History marker: drag to roll the model back; new features go here"); } @@ -556,9 +560,31 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { // 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 let (Some(dg), Some(pp)) = (drag.as_ref(), pointer) { - let slot = slot_at(&xs, end, pp.x); - let sx = xs.get(slot).copied().unwrap_or(end) - 4.0; + 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)); + // 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) + { + // 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) { + mr.left() - 2.0 + } else { + mr.right() + 2.0 + } + } + _ => xs.get(slot).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); crate::ui_kit::history_drop_bar( &p, Rect::from_min_max(pos2(sx, r.top() + 3.0), pos2(sx, r.bottom() - 3.0)), @@ -581,8 +607,10 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { 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 }; - if to != from { - let _ = app.run_heavy("timeline.reorder", json!({ "feature": id, "position": to })); + // 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 })); } } } @@ -987,6 +1015,33 @@ mod tests { assert_eq!(h.app.session.doc.marker, None); } } + /// A feature dropped just past the history marker is rolled back, and dropped just before it + /// is active again, in both strips. + #[test] + fn dragging_a_feature_across_the_marker_rolls_it_back_and_forward() { + use crate::scenario::{handle_at, rect_of}; + for left in [false, true] { + let mut h = two_boxes(left); + h.settle(); + let second = handle_at("timeline:Second").unwrap(); + let marker = rect_of("history:marker").unwrap(); + let behind = if left { [second.x, marker.bottom() + 3.0] } else { [marker.right() + 4.0, second.y] }; + let undo = h.app.session.undo.len(); + h.step(&json!({"drag":[[second.x,second.y],behind]})).unwrap(); + h.settle(); + assert_eq!(h.app.session.doc.marker, Some(1), "left={left}: dropped behind the marker, Second is rolled back"); + assert_eq!(h.app.session.undo.len(), undo + 1, "left={left}: crossing the marker is one undo step"); + let second = handle_at("timeline:Second").unwrap(); + let marker = rect_of("history:marker").unwrap(); + let before = if left { [second.x, marker.top() - 2.0] } else { [marker.left() - 3.0, second.y] }; + h.step(&json!({"drag":[[second.x,second.y],before]})).unwrap(); + h.settle(); + assert_eq!(h.app.session.doc.marker, None, "left={left}: dropped before the marker, Second is active again"); + let names: Vec<_> = h.app.session.doc.features.iter().map(|feature| feature.name.as_str()).collect(); + assert_eq!(names, ["First", "Second"], "left={left}: crossing the marker keeps the order"); + } + } + #[test] fn floating_strip_has_only_history_text_and_accents_the_last_done_chip_and_marker() { let mut h = two_boxes(false); diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index 6886d2d85..bb5d13b94 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -478,7 +478,9 @@ fn vertical_drop_bar_left(panel_left: f32, target: Option, groups: &[solidc target.map(|group| panel_left + DROP_BAR_INSET + (group_depth(groups, group) + 1) as f32 * FOLDER_INDENT).unwrap_or(panel_left + DROP_BAR_INSET) } -fn vertical_marker(app: &mut SolveApp, ui: &mut egui::Ui, drag: &mut Option) { +/// Paints the marker row and returns its centre height, which splits the slots at its position +/// into before and after the marker. +fn vertical_marker(app: &mut SolveApp, ui: &mut egui::Ui, drag: &mut Option) -> f32 { let t = Tokens::get(); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), t.space_12), Sense::drag()); crate::ui_kit::history_marker(ui.painter(), rect, true, crate::theme::TabAccent::for_tab(&t, &app.ui.tab)); @@ -487,7 +489,11 @@ fn vertical_marker(app: &mut SolveApp, ui: &mut egui::Ui, drag: &mut Option Option { @@ -933,6 +939,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { let mut previous_visible_group = None; let mut hovered = None; let mut edit = None; + let mut marker_y = f32::INFINITY; for (index, (id, name, icon, suppressed, ty, kind)) in features.iter().enumerate() { let group_id = group_for(&groups, *id); @@ -943,7 +950,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { let group = at_index.first().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 }); - vertical_marker(app, ui, &mut drag); + marker_y = vertical_marker(app, ui, &mut drag); } let mut rendered_group_header = false; for group in at_index { @@ -970,7 +977,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { 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 }); - vertical_marker(app, ui, &mut drag); + marker_y = vertical_marker(app, ui, &mut drag); } if !group_open { continue; @@ -1011,7 +1018,11 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { suppressed: *suppressed, error: error.is_some(), warning: warning.is_some(), - accent: crate::theme::TabAccent::for_tab(&t, &app.ui.tab), + // Dragged features take the colour of their drop bar. + accent: crate::theme::TabAccent::for_tab( + &t, + if matches!(&drag, Some(Drag::Items(items)) if items.features.contains(id)) { "SKETCH" } else { &app.ui.tab }, + ), } .paint(ui.painter(), chip, style); if has_patterns { @@ -1121,12 +1132,19 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { } slots.push(VerticalSlot { y: ui.cursor().top(), position: n, group: None, indent_group: previous_visible_group }); if marker >= n { - vertical_marker(app, ui, &mut drag); + marker_y = vertical_marker(app, ui, &mut drag); + // Below the marker at the end: a feature dropped here is rolled back. + slots.push(VerticalSlot { y: ui.cursor().top(), position: n, group: None, indent_group: previous_visible_group }); } crate::dialogs_assembly::timeline_joints_vertical(app, ui); + if drag.is_some() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } + // The marker dropped where it already is needs no bar: the marker shows the spot. if let (Some(active), Some(pointer)) = (drag.as_ref(), pointer) && let Some(slot) = nearest_vertical_slot(&slots, pointer.y) + && !(matches!(active, Drag::Marker) && slot.position == marker.min(n)) { let folder_target = match active { Drag::Items(items) => { @@ -1173,6 +1191,8 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { if !items.groups.is_empty() { params["groups"] = json!(items.groups); } + // Crossing the marker rolls the moved features back or forward, in the same step. + params["active"] = json!(slot.y < marker_y); let _ = app.run("timeline.move_many", params); if let Some(group) = folder_target { app.tree.collapsed.remove(&format!("timeline_group:{group}"));