Add History playback to the Inspect ribbon (#3693) (#7853)

* claim: #3693

* Fix timeline playback to show each rebuilt feature

* Move History playback into the Inspect ribbon

* Refuse Play History up front when playback couldn't run

Starting Play and the per-frame check that stops it were looking at
different app state, so Play could be accepted during an apply, a delete
check or queued history work and then stop silently on the next frame.
Both now use one playback_blocked check.

The UI also reads the engine's PlaybackAction as the typed enum instead of
matching strings, so a bad reply is an error rather than a quiet toggle.

* Put Play History in the History controls

History now shows five controls in transport order: start, previous,
play, next, end. Play runs timeline.play, so it turns into Stop while
playback runs, same as the ribbon button and the shortcut.

It's on by default (#3688, #3740, #4216). Anyone who wants the old four
controls back can right-click them and pick Hide Play Button, or clear
history_play_button under Preferences > Interface. In a named vertical
History too narrow for five buttons beside its grip, Play is left to the
ribbon rather than overlapping the grip.

* Draw the History Play button as a plain play/pause glyph

The Play button in the History controls now uses the same drawn glyphs as
its neighbours: a filled triangle, and two bars while History plays. The
triangle is bigger than the step arrows so it doesn't read as Forward.
The ribbon command keeps its timeline_play and timeline_stop icons.

* Keep the playback changes clear of PRs queued ahead

Several PRs in the merge queue touch the same lines, so this moves ours
aside without changing behaviour:

- history_play_button and its reset-test row sit with the other History
  preferences, not beside view_confirm_corner (#7248 adds status_bar there).
- History keeps main's history_transport_width() for four controls (#6430
  and #7459 call it); the Play button's count uses history_controls_width.
- A new or opened document stops playback after dim_view::cancel(), clear
  of the line #7819 adds after reset_chat.
- The Play/Stop label swap moves from interactive_command_info, which #7906
  rewrites, into the ribbon's command_info.

* Stop playback after the command completes, clear of #6433

#6433 rewrites the session.execute line in execute_command, and our playback check sat right under it, so the queue couldn't merge the two. Checking the revision after command_completed does the same job a couple of lines later.

---------

Co-authored-by: cfaulkingham <colin.faulkingham@gmail.com>
This commit is contained in:
The Nomad
2026-10-29 02:14:53 +00:00
committed by GitHub
parent be757154d6
commit 674ef84b53
30 changed files with 735 additions and 28 deletions
@@ -290,6 +290,8 @@ svg false
sweep false
text false
thread false
timeline_play false
timeline_stop false
torus false
trace false
trim false
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><title>Play History</title><path d="M11.22 20L32 32L32 56L11.22 44Z" fill="#b8c3cf"/><path d="M52.78 20L32 32L32 56L52.78 44Z" fill="#8e9faf"/><path d="M32 8L52.78 20L32 32L11.22 20Z" fill="#e2e8ef"/><path d="M32 8L52.78 20L52.78 44L32 56L11.22 44L11.22 20Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/><path d="M11.22 20L32 32L52.78 20" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/><path d="M32 32L32 56" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/><path d="M35 34L56 46L35 58Z" fill="#ffffff" stroke="#ffffff" stroke-width="4.55" stroke-linejoin="round" stroke-linecap="round"/><path d="M35 34L56 46L35 58Z" fill="#236ead" stroke="#236ead" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 935 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><title>Stop History</title><path d="M11.22 20L32 32L32 56L11.22 44Z" fill="#b8c3cf"/><path d="M52.78 20L32 32L32 56L52.78 44Z" fill="#8e9faf"/><path d="M32 8L52.78 20L32 32L11.22 20Z" fill="#e2e8ef"/><path d="M32 8L52.78 20L52.78 44L32 56L11.22 44L11.22 20Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/><path d="M11.22 20L32 32L52.78 20" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/><path d="M32 32L32 56" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/><path d="M36 35L53 35A2 2 0 0 1 55 37L55 54A2 2 0 0 1 53 56L36 56A2 2 0 0 1 34 54L34 37A2 2 0 0 1 36 35Z" fill="#ffffff" stroke="#ffffff" stroke-width="4.55" stroke-linejoin="round" stroke-linecap="round"/><path d="M36 35L53 35A2 2 0 0 1 55 37L55 54A2 2 0 0 1 53 56L36 56A2 2 0 0 1 34 54L34 37A2 2 0 0 1 36 35Z" fill="#236ead" stroke="#236ead" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+11
View File
@@ -15,6 +15,17 @@ pub(crate) fn transport_glyph(p: &egui::Painter, c: egui::Pos2, what: &str, col:
}
"back" => tri(-1.0, 0.0),
"forward" => tri(1.0, 0.0),
// Play History: larger than the step arrows so it doesn't read as Forward, and two bars
// while it plays.
"play" => {
let pts = vec![pos2(c.x - 4.5, c.y - 7.0), pos2(c.x + 6.5, c.y), pos2(c.x - 4.5, c.y + 7.0)];
p.add(egui::Shape::convex_polygon(pts, col, Stroke::NONE));
}
"pause" => {
for dx in [-3.0, 3.0] {
p.rect_filled(Rect::from_center_size(pos2(c.x + dx, c.y), vec2(3.0, 12.0)), 0.5, col);
}
}
_ => {
tri(1.0, -1.0);
bar(5.0);
@@ -0,0 +1,90 @@
{
"en": {
"cmd.timeline_play": "Play History",
"cmd.timeline_stop": "Stop History",
"help.timeline.play": "Replay the remaining features one at a time, with a half-second pause after each rebuild. Run this command again or press Escape to stop; Go to end jumps immediately.",
"ui.history_play_finish_action": "Finish the current action before playing History",
"ui.history_play_roll_back": "Move the History marker back before playing",
"prefs.history_play_button": "Play History button in the History controls",
"prefs.history_play_button_note": "Puts Play History between Go back one step and Go forward one step in the History controls. You can also right-click the controls to show or hide it.",
"ui.history_play_button_show": "Show Play Button",
"ui.history_play_button_hide": "Hide Play Button"
},
"ar": {
"cmd.timeline_play": "تشغيل السجل",
"cmd.timeline_stop": "إيقاف السجل",
"help.timeline.play": "أعد تشغيل الميزات المتبقية واحدة تلو الأخرى، مع توقف لمدة نصف ثانية بعد كل إعادة بناء. شغّل هذا الأمر مرة أخرى أو اضغط Escape للإيقاف؛ ينتقل «الذهاب إلى النهاية» فورًا إلى النهاية.",
"ui.history_play_finish_action": "أكمل الإجراء الحالي قبل تشغيل السجل",
"ui.history_play_roll_back": "أعد مؤشر السجل إلى الخلف قبل التشغيل",
"prefs.history_play_button": "زر تشغيل السجل في عناصر تحكم السجل",
"prefs.history_play_button_note": "يضيف تشغيل السجل بين الرجوع خطوة والتقدم خطوة في عناصر تحكم السجل. يمكنك أيضًا النقر بزر الماوس الأيمن على عناصر التحكم لإظهاره أو إخفائه.",
"ui.history_play_button_show": "إظهار زر التشغيل",
"ui.history_play_button_hide": "إخفاء زر التشغيل"
},
"de": {
"cmd.timeline_play": "Verlauf abspielen",
"cmd.timeline_stop": "Verlauf anhalten",
"help.timeline.play": "Die verbleibenden Features nacheinander abspielen, mit einer halben Sekunde Pause nach jedem Neuaufbau. Diesen Befehl erneut ausführen oder Escape drücken, um anzuhalten; Zum Ende springt sofort ans Ende.",
"ui.history_play_finish_action": "Die aktuelle Aktion abschließen, bevor der Verlauf abgespielt wird",
"ui.history_play_roll_back": "Die Verlaufsmarkierung vor dem Abspielen zurücksetzen",
"prefs.history_play_button": "Schaltfläche „Verlauf abspielen“ in den Verlaufssteuerelementen",
"prefs.history_play_button_note": "Fügt „Verlauf abspielen“ zwischen „Einen Schritt zurück“ und „Einen Schritt vor“ in die Verlaufssteuerelemente ein. Mit einem Rechtsklick auf die Steuerelemente lässt sich die Schaltfläche auch ein- oder ausblenden.",
"ui.history_play_button_show": "Wiedergabe-Schaltfläche einblenden",
"ui.history_play_button_hide": "Wiedergabe-Schaltfläche ausblenden"
},
"he": {
"cmd.timeline_play": "הפעלת ציר הזמן",
"cmd.timeline_stop": "עצירת ציר הזמן",
"help.timeline.play": "הפעלה מחדש של הפיצ'רים שנותרו, אחד בכל פעם, עם השהיה של חצי שנייה לאחר כל בנייה מחדש. להפסקה יש להפעיל שוב את הפקודה או ללחוץ על Escape; מעבר לסוף מתבצע מיד.",
"ui.history_play_finish_action": "יש לסיים את הפעולה הנוכחית לפני הפעלת ציר הזמן",
"ui.history_play_roll_back": "יש להזיז את סמן ציר הזמן לאחור לפני ההפעלה",
"prefs.history_play_button": "כפתור הפעלת ציר הזמן בפקדי ציר הזמן",
"prefs.history_play_button_note": "מוסיף את הפעלת ציר הזמן בין צעד אחד אחורה לצעד אחד קדימה בפקדי ציר הזמן. אפשר גם ללחוץ לחיצה ימנית על הפקדים כדי להציג או להסתיר אותו.",
"ui.history_play_button_show": "הצגת כפתור ההפעלה",
"ui.history_play_button_hide": "הסתרת כפתור ההפעלה"
},
"ja": {
"cmd.timeline_play": "履歴を再生",
"cmd.timeline_stop": "履歴を停止",
"help.timeline.play": "残りのフィーチャを一つずつ再生し、再構築のたびに0.5秒間停止します。このコマンドをもう一度実行するかEscキーで停止し、「最後へ」で直ちに最後へ移動します。",
"ui.history_play_finish_action": "現在の操作を完了してから履歴を再生してください",
"ui.history_play_roll_back": "再生する前に履歴マーカーを戻してください",
"prefs.history_play_button": "履歴コントロールに「履歴を再生」ボタンを表示",
"prefs.history_play_button_note": "履歴コントロールの「1ステップ戻る」と「1ステップ進む」の間に「履歴を再生」を追加します。コントロールを右クリックして表示/非表示を切り替えることもできます。",
"ui.history_play_button_show": "再生ボタンを表示",
"ui.history_play_button_hide": "再生ボタンを非表示"
},
"ko": {
"cmd.timeline_play": "기록 재생",
"cmd.timeline_stop": "기록 재생 중지",
"help.timeline.play": "남은 피처를 하나씩 재생하고 각 재생성 후 0.5초 동안 멈춥니다. 이 명령을 다시 실행하거나 Escape 키를 누르면 중지됩니다. 끝으로 이동은 즉시 마지막 단계로 이동합니다.",
"ui.history_play_finish_action": "기록을 재생하기 전에 현재 작업을 완료하세요",
"ui.history_play_roll_back": "재생하기 전에 기록 마커를 이전 단계로 이동하세요",
"prefs.history_play_button": "기록 컨트롤에 기록 재생 버튼 표시",
"prefs.history_play_button_note": "기록 컨트롤의 한 단계 뒤로와 한 단계 앞으로 사이에 기록 재생을 추가합니다. 컨트롤을 마우스 오른쪽 버튼으로 클릭해 표시하거나 숨길 수도 있습니다.",
"ui.history_play_button_show": "재생 버튼 표시",
"ui.history_play_button_hide": "재생 버튼 숨기기"
},
"vi": {
"cmd.timeline_play": "Phát lịch sử",
"cmd.timeline_stop": "Dừng lịch sử",
"help.timeline.play": "Phát lại lần lượt các tính năng còn lại, tạm dừng nửa giây sau mỗi lần dựng lại. Chạy lại lệnh này hoặc nhấn Escape để dừng; Đến cuối sẽ chuyển ngay đến cuối lịch sử.",
"ui.history_play_finish_action": "Hoàn tất thao tác hiện tại trước khi phát lịch sử",
"ui.history_play_roll_back": "Đưa điểm đánh dấu lịch sử lùi lại trước khi phát",
"prefs.history_play_button": "Nút Phát lịch sử trong các điều khiển Lịch sử",
"prefs.history_play_button_note": "Thêm Phát lịch sử vào giữa Lùi một bước và Tiến một bước trong các điều khiển Lịch sử. Bạn cũng có thể nhấp chuột phải vào các điều khiển để hiện hoặc ẩn nút này.",
"ui.history_play_button_show": "Hiện nút Phát",
"ui.history_play_button_hide": "Ẩn nút Phát"
},
"zh": {
"cmd.timeline_play": "播放历史",
"cmd.timeline_stop": "停止历史播放",
"help.timeline.play": "逐个播放剩余特征,每次重建后暂停半秒。再次运行此命令或按Escape停止;转到末尾会立即跳转。",
"ui.history_play_finish_action": "请先完成当前操作,再播放历史",
"ui.history_play_roll_back": "播放前请将历史标记向后移动",
"prefs.history_play_button": "在历史控件中显示“播放历史”按钮",
"prefs.history_play_button_note": "在历史控件的“后退一步”和“前进一步”之间添加“播放历史”。也可以右键单击这些控件来显示或隐藏它。",
"ui.history_play_button_show": "显示播放按钮",
"ui.history_play_button_hide": "隐藏播放按钮"
}
}
+2
View File
@@ -0,0 +1,2 @@
| assets/icons/ui/design/svg/model/timeline_play.svg | SolidCraft contributors | Original history playback icon; canonical grey_cube base and original action cue | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/model/timeline_stop.svg | SolidCraft contributors | Original history playback icon; canonical grey_cube base and original action cue | MIT OR Apache-2.0 |
+16
View File
@@ -29,6 +29,15 @@ pub static COMMANDS: &[CommandSpec] = &[
.doc_only()
.params("checkpoint: id; forget?: bool (true = drop it without going back). Goes back to it, undo history included"),
CommandSpec::new("timeline.compute_all", "Compute All", compute_all).at("SOLID", "MODIFY").icon("compute").noundo(),
CommandSpec::new("timeline.play", "Play History", crate::checked!("timeline.play", play))
.at("INSPECT", "HISTORY")
.icon("timeline_play")
.noundo()
.doc_only()
.enabled(super::not_in_sketch)
.contract(&PLAY_CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::edit::TimelinePlayResult>)
.params("action?: toggle|play|stop (default toggle) → action: validated display request; the connected UI plays from the marker to the end with a half-second pause per rebuilt step. Headless callers only validate the request; no dialog, document edit or animation clock is created"),
CommandSpec::new("timeline.delete", "Delete", delete)
.at("SOLID", "MODIFY")
.icon("delete")
@@ -87,6 +96,13 @@ pub static COMMANDS: &[CommandSpec] = &[
.params("body?: world body name, face?: face index; defaults to the current body/face selection → selects objects using the resolved appearance"),
];
const PLAY_CONTRACT: crate::schema::TypedContract<crate::schema::edit::TimelinePlayParams> = crate::schema::TypedContract::new();
fn play(_s: &mut Session, p: &Value) -> Result<Value> {
let request: crate::schema::edit::TimelinePlayParams = serde_json::from_value(p.clone()).map_err(|e| bad("timeline.play", e.to_string()))?;
serde_json::to_value(crate::schema::edit::TimelinePlayResult { action: request.action }).map_err(|e| EngineError::Other(e.to_string()))
}
fn undo(s: &mut Session, _p: &Value) -> Result<Value> {
let Some(prev) = s.undo.pop() else { return Err(EngineError::Other("nothing to undo".into())) };
let now = go_to(s, prev);
+22
View File
@@ -8,6 +8,28 @@ fn run(s: &mut Session, id: &str, params: Value) -> Value {
s.execute(id, &params).unwrap_or_else(|e| panic!("{id} {params}: {e}"))
}
#[test]
fn history_playback_is_a_typed_display_request_without_history_edits() {
let mut s = Session::default();
let revision = s.revision;
let undo = s.undo.len();
for action in ["toggle", "play", "stop"] {
assert_eq!(run(&mut s, "timeline.play", json!({"action": action})), json!({"action": action}));
}
assert_eq!(run(&mut s, "timeline.play", json!({})), json!({"action": "toggle"}));
for action in [json!("pause"), json!(true), json!(1), json!([])] {
assert!(s.execute("timeline.play", &json!({"action": action})).is_err());
}
assert_eq!(s.revision, revision);
assert_eq!(s.undo.len(), undo);
assert!(s.doc.marker.is_none());
let description = run(&mut s, "engine.describe", json!({"command": "timeline.play"}));
assert!(description["input"].is_object());
assert!(description["output"].is_object());
run(&mut s, "sketch.create", json!({"plane": "XY"}));
assert!(s.execute("timeline.play", &json!({})).is_err());
}
/// `timeline.roll_to` takes a number of features or "end"; any other value is refused instead of
/// silently moving the marker to the end.
#[test]
+24
View File
@@ -13,6 +13,30 @@ pub struct RepeatParams {}
#[derive(Debug, Serialize, JsonSchema)]
pub struct RepeatResult {}
/// Display-only timeline playback requests. The connected UI owns the animation clock.
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PlaybackAction {
#[default]
Toggle,
Play,
Stop,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct TimelinePlayParams {
/// Omit to toggle; explicit play/stop requests are idempotent.
#[serde(default)]
pub action: PlaybackAction,
}
#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelinePlayResult {
/// Validated display request. A connected UI applies it; a headless engine has no clock.
pub action: PlaybackAction,
}
#[cfg(test)]
mod tests {
use super::RepeatParams;
+1
View File
@@ -38,6 +38,7 @@ pub const DOCUMENTED: &[&str] = &[
"solid.sweep",
"timeline.compute_all",
"timeline.delete",
"timeline.play",
];
/// The help for `command` in the current language, when it has any.
+8
View File
@@ -69,6 +69,8 @@ pub enum Target {
},
/// The toolbar's empty space.
Toolbar,
/// The History controls (first, previous, next, last, and Play when shown).
HistoryControls,
/// The workspace switcher.
Workspace,
/// The Named Views folder, and one view (saved or standard) in it.
@@ -388,6 +390,7 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec<Item> {
Target::Joint { id } => joint_items(app, *id),
Target::ToolbarCommand { id } => crate::toolbar_custom::command_items(app, id),
Target::Toolbar => crate::toolbar_custom::toolbar_items(app),
Target::HistoryControls => crate::timeline::transport_items(app),
Target::Workspace => {
let rendering = crate::render_workspace::active(app);
let mut v = vec![
@@ -1493,6 +1496,11 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {
"ui.toolbarPin" | "ui.toolbarRemove" | "ui.toolbarReset" | "ui.toolbarCustomize" | "ui.shortcutPin" => {
crate::toolbar_custom::run(app, &item.id, &p)
}
"ui.historyPlayButton" => {
if let Err(e) = crate::prefs::set(app, &json!({ "history_play_button": p["show"] })) {
app.set_status(e, true);
}
}
"ui.workspace" | "ui.workspace.design" | "ui.workspace.render" => {
if let Some(workspace) = p.get("workspace").and_then(Value::as_str)
&& let Err(e) = crate::render_workspace::enter(app, workspace == "render")
+1
View File
@@ -247,6 +247,7 @@ fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result<Value, String>
| "view.angle_readout"
| "view.graphics_preset"
| "view.history_layout"
| "timeline.play"
| "browser.expand_all"
| "browser.collapse_all"
)
+9
View File
@@ -123,6 +123,12 @@ impl SolveApp {
/// a while (see the module notes). `Ok(Null)` when it is left computing or waiting its turn:
/// its outcome then shows as any command's does (an error in the status line).
pub fn run_heavy(&mut self, id: &str, params: Value) -> Result<Value, String> {
if id == "timeline.play" {
return self.run(id, params);
}
// A manual history action takes over from playback. Playback takes its state out
// while submitting its own next step, then puts it back to wait for that step.
crate::timeline::stop_playback(self);
if self.deferred.is_some() {
if replaced_by_a_later_one(id) && self.deferred_queue.last().is_some_and(|(q, _)| q == id) {
self.deferred_queue.pop();
@@ -234,7 +240,10 @@ impl SolveApp {
// The design changed meanwhile: computed again for the design as it is now.
let _ = self.run_heavy(&id, params);
} else if !superseded {
// This is playback's own completed step, not a manual history edit.
let playback = self.timeline_playback.take();
let _ = self.run_evaluated(&id, params, job.evaluated.flatten().as_ref(), job.kept);
self.timeline_playback = playback;
}
}
}
+1
View File
@@ -136,6 +136,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot {
let _ = crate::render_workspace::enter(app, false);
}
// Whatever was going on in the design leaves with it.
crate::timeline::stop_playback(app);
crate::sketch_text_move::cancel_drag(app);
crate::dialogs::cancel(app);
crate::dim_view::cancel();
@@ -120,6 +120,82 @@ fn a_parameter_change_computed_off_the_thread_is_not_evaluated_again() {
assert!((v - (50.0 * 20.0 * 10.0 + 500.0)).abs() < 1.0, "{v}");
}
#[test]
fn playback_waits_for_each_background_rebuild_before_timing_the_next_step() {
let mut h = block_boss_hole();
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.app.start("timeline.play");
h.frames(1);
for position in 1..=3 {
assert!(h.app.deferred.is_some(), "step {position} is computed in the background");
assert!(h.app.deferred_queue.is_empty(), "playback must not queue steps that supersede each other");
for _ in 0..500 {
if h.app.deferred.as_mut().is_some_and(crate::deferred::Deferred::finished) {
break;
}
std::thread::sleep(Duration::from_millis(10));
}
// A large design can evict these states before the UI receives the completed step.
// Playback must consume the worker's evaluated features, not rebuild them again.
h.app.session.model.cache = Default::default();
until_settled(&mut h);
assert_eq!(h.app.session.model.last_recomputed, 0, "playback step {position} uses the background evaluation");
assert_eq!(marker(&h).unwrap_or(3), position);
h.frames(10);
assert_eq!(marker(&h).unwrap_or(3), position, "step {position} stays visible after computation");
if position < 3 {
// Advance only until the next step starts; never sleep through a whole playback.
for _ in 0..40 {
if h.app.deferred.is_some() {
break;
}
h.frames(1);
}
}
}
assert!(h.app.timeline_playback.is_none());
assert!(h.app.deferred_queue.is_empty());
}
#[test]
fn interrupted_playback_never_applies_its_pending_background_step() {
for action in ["stop", "last", "edit", "marker", "tool", "palette", "new"] {
let mut h = block_boss_hole();
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.app.start("timeline.play");
h.frames(1);
assert!(h.app.deferred.is_some());
match action {
"stop" => h.app.start("timeline.play"),
"last" => {
crate::timeline::run_transport(&mut h.app, crate::ui_kit::HistoryTransport::Last);
until_settled(&mut h);
assert_eq!(marker(&h), None, "Go to end supersedes the pending playback step");
}
"edit" => {
h.app.run("timeline.rename", json!({"feature": 1, "name": "Renamed"})).unwrap();
}
"marker" => {
h.app.run("timeline.roll_to", json!({"position": 2})).unwrap();
}
"tool" => h.app.start("solid.box"),
"palette" => {
h.app.start("ui.palette");
assert!(h.app.timeline_playback.is_some());
h.app.start("timeline.play");
}
_ => {
h.app.run("file.new", json!({})).unwrap();
}
}
assert!(h.app.timeline_playback.is_none(), "{action}");
assert!(h.app.deferred.is_none(), "{action}: the worker cannot apply the old marker");
let marker = marker(&h);
h.frames(90);
assert_eq!(h.app.session.doc.marker, marker, "{action}");
}
}
#[test]
fn a_marker_moved_again_replaces_the_move_still_waiting() {
let mut h = block_boss_hole();
+1 -1
View File
@@ -33,7 +33,7 @@ fn take(app: &SolveApp, out: &mut BTreeSet<String>) {
let components: Vec<u64> = app.session.doc.components.iter().map(|c| c.id).collect();
let groups: Vec<u64> = app.session.doc.browser_groups.iter().map(|g| g.id).collect();
for target in [Target::Viewport, Target::Origin, Target::Units, Target::Toolbar, Target::Workspace, Target::NamedViews] {
for target in [Target::Viewport, Target::Origin, Target::Units, Target::Toolbar, Target::HistoryControls, Target::Workspace, Target::NamedViews] {
take_items(out, &context_menu::items(app, &target));
}
for name in &bodies {
+21
View File
@@ -532,6 +532,7 @@ pub struct SolveApp {
/// A feature started from a sketch while the marker rolls back, and that sketch: it starts
/// once the marker is back.
pub start_after_roll: Option<(String, u64)>,
pub(crate) timeline_playback: Option<timeline::Playback>,
/// A delete's check of what it takes with it or breaks, computing off the window thread
/// ([`deferred::DeleteCheck`], #2678).
pub delete_check: Option<deferred::DeleteCheck>,
@@ -735,6 +736,7 @@ impl SolveApp {
deferred: None,
deferred_queue: Vec::new(),
start_after_roll: None,
timeline_playback: None,
delete_check: None,
apply_off_thread: None,
#[cfg(test)]
@@ -1023,7 +1025,14 @@ impl SolveApp {
if matches!(id, "file.save_mesh" | "file.send_to_slicer") {
solidcraft_engine::slicers::set_chosen_programs(&self.preferences.custom_slicers);
}
if id == "timeline.play" {
let reply = self.session.execute(id, &params).map_err(|e| e.to_string())?;
let action = serde_json::from_value(reply["action"].clone()).map_err(|e| e.to_string())?;
timeline::request_playback(self, action)?;
return Ok(reply);
}
let t0 = now_ms();
let revision = self.session.revision;
let selected_before = self.session.selection.clone();
let r = self.session.execute(id, &params).map_err(|e| e.to_string()).and_then(|reply| {
render_workspace::apply_command(self, id, &reply)?;
@@ -1031,6 +1040,9 @@ impl SolveApp {
});
self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS;
let done = self.command_completed(id, r);
if self.session.revision != revision {
timeline::stop_playback(self);
}
// Render focus already applies its semantic selection after clearing object picks.
// A tab switch brings in the other design's own Render selection.
if done.is_ok()
@@ -1237,6 +1249,7 @@ impl SolveApp {
self.edit_in_place.active = None;
render_workspace::reset_document(self);
dim_view::cancel();
timeline::stop_playback(self);
self.menu.props = None;
sketch_attachment_ui::clear(self);
// The old document is already replaced: discard its editor without
@@ -1301,10 +1314,17 @@ impl SolveApp {
}
fn start_with_variant_memory(&mut self, id: &str, remember_variant: bool, opener: Option<egui::Rect>) {
if id == "timeline.play" {
if let Err(why) = self.run(id, json!({})) {
self.set_status(why, true);
}
return;
}
if id == "ui.palette" {
shortcut_box::open(self, None);
return;
}
timeline::stop_playback(self);
// A file is loading: the design waits for it.
if self.file_load.busy() || self.file_picker.is_some() {
return;
@@ -2394,6 +2414,7 @@ impl SolveApp {
self.poll_feature_edit(ui.ctx());
self.poll_deferred(ui.ctx());
self.poll_delete_check(ui.ctx());
timeline::tick_playback(self, ui.ctx());
if !self.embedded {
toolbar::app_bar(self, ui);
}
+1
View File
@@ -1443,6 +1443,7 @@ fn every_context_target_has_identified_icon_rows_including_submenus() {
Target::Units,
Target::ToolbarCommand { id: "solid.extrude".into() },
Target::Toolbar,
Target::HistoryControls,
Target::Workspace,
Target::NamedViews,
Target::NamedView { name: "Top".into() },
+4
View File
@@ -965,6 +965,9 @@ preference_settings! {
timeline_left_browser_collapsed: bool = false, PAGE_INTERFACE;
/// Whether the History at the left lists a sketch under the feature built from it.
history_sketches: HistorySketches = HistorySketches::default(), PAGE_INTERFACE;
/// 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_INTERFACE => check_id("prefs.history_play_button");
/// 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_INTERFACE;
@@ -4525,6 +4528,7 @@ mod tests {
("timeline_left", json!(true), PAGE_INTERFACE),
("timeline_under_browser", json!(true), PAGE_INTERFACE),
("history_sketches", json!("under_feature"), PAGE_INTERFACE),
("history_play_button", json!(false), PAGE_INTERFACE),
("browser_float", json!(true), PAGE_INTERFACE),
("dialog_place", json!("left_column"), PAGE_INTERFACE),
("color_vision", json!("protan"), PAGE_INTERFACE),
+5
View File
@@ -183,6 +183,11 @@ pub(super) fn interface(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
crate::scenario::publish_target("prefs:history_origin_bodies", check.rect);
});
});
// Play History between Previous and Next, for people who want it there (#3688).
ui_kit::row(ui, "", |ui| {
let check = setting::history_play_button(app, ui).on_hover_text(app.tr("prefs.history_play_button_note"));
crate::scenario::publish_target("prefs:history_play_button", check.rect);
});
ui_kit::row(ui, app.tr("prefs.browser"), |ui| {
ui.add_enabled_ui(app.ui.layout == crate::shell::LayoutMode::Floating, |ui| {
let mut selected = usize::from(app.preferences.browser_float);
@@ -106,6 +106,10 @@ pub(super) fn action_ready(app: &SolveApp, id: &str) -> Result<(), String> {
}
pub(super) fn command_info(app: &SolveApp, command: &CommandSpec) -> CommandInfo {
// Play History swaps to Stop History while it runs, wherever the command is shown.
if command.id == "timeline.play" {
return crate::timeline::playback_command_info(app, command);
}
let mut info = command.info(&app.session);
if info.enabled
&& super::active(app)
+5 -3
View File
@@ -140,19 +140,21 @@ pub fn search(app: &SolveApp, q: &str) -> Vec<Row> {
.filter(|c| !crate::workspace::AGENT_ONLY.contains(&c.id))
.filter_map(|c| {
let (home_tab, home_panel) = crate::workspace::destination(c).unwrap_or(("", ""));
let info = crate::render_workspace::interactive_command_info(app, c);
let (label, tab, panel) =
(crate::i18n::tr_label(c.label), crate::i18n::tr_label(crate::workspace::tab_label(home_tab)), crate::i18n::tr_label(home_panel));
(crate::i18n::tr_label(info.label), crate::i18n::tr_label(crate::workspace::tab_label(home_tab)), crate::i18n::tr_label(home_panel));
let place = (!home_tab.is_empty()).then_some((tab, panel));
let s = score(&q, label)
.max(score(&q, c.label))
.max(score(&q, info.label))
.max(score(&q, c.id) * 9 / 10)
.max(keyword_score(&q, keywords(c.id)))
.max(score(&q, tab).max(score(&q, home_tab)) / 3)
.max(score(&q, panel).max(score(&q, home_panel)) / 3);
let recent = app.sbox.recent.iter().position(|r| r == c.id).map_or(0, |i| 2000u32.saturating_sub(i.min(2000) as u32));
// Commands that can run now come before those that can't.
let usable = if crate::render_workspace::interactive_command_info(app, c).enabled { 150 } else { 0 };
(s > 0).then_some((s + usable + if q.is_empty() { recent } else { recent / 20 }, (c.id, label, c.icon, place)))
let usable = if info.enabled { 150 } else { 0 };
(s > 0).then_some((s + usable + if q.is_empty() { recent } else { recent / 20 }, (c.id, label, info.icon, place)))
})
.collect();
v.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.1.cmp(b.1.1)));
+364 -4
View File
@@ -8,6 +8,8 @@ use solidcraft_engine::doc::{
construct::{AxisDef, PointDef},
};
use solidcraft_engine::schema::edit::PlaybackAction;
use crate::SolveApp;
use crate::theme::Tokens;
@@ -19,6 +21,10 @@ pub(crate) fn run_transport(app: &mut SolveApp, control: crate::ui_kit::HistoryT
let position = match control {
crate::ui_kit::HistoryTransport::First => 0,
crate::ui_kit::HistoryTransport::Back => marker.saturating_sub(1),
crate::ui_kit::HistoryTransport::Play => {
app.start("timeline.play");
return;
}
crate::ui_kit::HistoryTransport::Forward => marker.saturating_add(1).min(n),
crate::ui_kit::HistoryTransport::Last => n,
};
@@ -26,6 +32,24 @@ pub(crate) fn run_transport(app: &mut SolveApp, control: crate::ui_kit::HistoryT
let _ = app.run_heavy("timeline.roll_to", params);
}
/// A click runs a History control; a right-click offers to show or hide the Play button.
pub(crate) fn transport_response(app: &mut SolveApp, control: crate::ui_kit::HistoryTransport, response: &egui::Response) {
if response.clicked() {
run_transport(app, control);
}
if response.secondary_clicked() {
let at = response.interact_pointer_pos().unwrap_or(response.rect.left_bottom());
crate::context_menu::open_for(app, at, crate::context_menu::Target::HistoryControls);
}
}
/// The History controls' menu: shows or hides the Play button.
pub(crate) fn transport_items(app: &SolveApp) -> Vec<crate::context_menu::Item> {
let show = !app.preferences.history_play_button;
let label = crate::i18n::tr(if show { "ui.history_play_button_show" } else { "ui.history_play_button_hide" });
vec![crate::context_menu::Item::action("ui.historyPlayButton", label, "timeline_play").with(json!({ "show": show }))]
}
/// The feature that made a face, edge or vertex of `body` (its world name): a face's own creator,
/// as Edit Feature on a face finds it (the hole, not the plate it was cut into), else the feature
/// that made the body.
@@ -448,6 +472,125 @@ fn toggle_feature(app: &mut SolveApp, id: u64) {
}
}
/// One history step at a time. The delay starts when the computed step is displayed, so a
/// slow rebuild cannot consume the pause or make queued marker moves skip intermediate steps.
pub(crate) struct Playback {
revision: u64,
position: usize,
waiting: bool,
next_at: f64,
}
const PLAYBACK_STEP_SECONDS: f64 = 0.5;
pub(crate) fn stop_playback(app: &mut SolveApp) {
if app.timeline_playback.take().is_some_and(|p| p.waiting) {
// The worker only fills the evaluation cache. Dropping its reply prevents an
// interrupted playback step from later moving the marker in an edited/new design.
app.deferred = None;
}
}
pub(crate) fn playback_command_info(app: &SolveApp, command: &solidcraft_engine::CommandSpec) -> solidcraft_engine::CommandInfo {
let mut info = command.info(&app.session);
if app.timeline_playback.is_some() {
info.label = "Stop History";
info.icon = "timeline_stop";
} else if let Err(why) = playback_ready(app) {
info.enabled = false;
info.disabled_reason = Some(why);
}
info
}
/// What playback can't run alongside: starting refuses on these, and a running playback stops on them.
fn playback_blocked(app: &SolveApp) -> bool {
app.home.open
|| crate::render_workspace::active(app)
|| app.session.active_sketch.is_some()
|| app.dialog.is_some()
|| app.tool.is_some()
|| app.file_load.busy()
|| app.file_picker.is_some()
|| app.saving.is_some()
|| app.applying.is_some()
|| app.delete_check.is_some()
|| !app.deferred_queue.is_empty()
}
fn playback_ready(app: &SolveApp) -> Result<(), String> {
if app.computing_since().is_some() || playback_blocked(app) {
return Err(crate::i18n::tr("ui.history_play_finish_action").into());
}
let n = app.session.doc.features.len();
if app.session.doc.marker.unwrap_or(n) >= n {
return Err(crate::i18n::tr("ui.history_play_roll_back").into());
}
Ok(())
}
pub(crate) fn request_playback(app: &mut SolveApp, action: PlaybackAction) -> Result<(), String> {
if matches!(action, PlaybackAction::Stop) || (matches!(action, PlaybackAction::Toggle) && app.timeline_playback.is_some()) {
stop_playback(app);
return Ok(());
}
if app.timeline_playback.is_some() {
return Ok(());
}
playback_ready(app)?;
let n = app.session.doc.features.len();
let position = app.session.doc.marker.unwrap_or(n);
app.timeline_playback = Some(Playback { revision: app.session.revision, position, waiting: false, next_at: 0.0 });
Ok(())
}
pub(crate) fn tick_playback(app: &mut SolveApp, ctx: &egui::Context) {
if app.timeline_playback.is_none() {
return;
}
if playback_blocked(app) || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
stop_playback(app);
return;
}
let Some(mut playback) = app.timeline_playback.take() else { return };
let now = ctx.input(|i| i.time);
let n = app.session.doc.features.len();
let position = app.session.doc.marker.unwrap_or(n);
if playback.waiting {
if app.deferred.is_some() {
if app.session.revision == playback.revision {
app.timeline_playback = Some(playback);
} else {
app.deferred = None;
}
return;
}
// A failed step, another edit, or a different marker move stops the sequence.
if app.session.revision != playback.revision.saturating_add(1) || position != playback.position {
return;
}
playback.waiting = false;
playback.revision = app.session.revision;
playback.next_at = now + PLAYBACK_STEP_SECONDS;
} else if app.session.revision != playback.revision || position != playback.position || app.deferred.is_some() {
return;
}
if position >= n {
return;
}
if now >= playback.next_at {
playback.position = position.saturating_add(1).min(n);
if app.run_heavy("timeline.roll_to", json!({"position": playback.position})).is_err() {
return;
}
// Observe completion on the next frame even for a synchronous rebuild (the web).
// This frame's input time predates that work and cannot time the visible pause.
playback.waiting = true;
}
ctx.request_repaint_after(std::time::Duration::from_millis(50));
app.timeline_playback = Some(playback);
}
pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) {
let t = Tokens::get();
app.shell.history_dock_space = Some(ui.available_rect_before_wrap());
@@ -508,11 +651,11 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) {
let response = ui.interact(drag_rect, egui::Id::new("sc_history_dock_grip"), Sense::drag());
crate::scenario::publish_handle("history:grip", drag_rect.center());
crate::timeline_left::dock_drag(app, ui, &response);
for control in crate::ui_kit::HistoryTransport::ALL {
let controls = crate::ui_kit::HistoryTransport::shown(app.preferences.history_play_button);
for &control in controls {
let br = Rect::from_center_size(pos2(x + t.space_24 / 2.0, r.center().y), vec2(t.space_24, t.space_24));
if control.show(ui, br).clicked() {
run_transport(app, control);
}
let response = control.show(ui, br, app.timeline_playback.is_some());
transport_response(app, control, &response);
x += t.space_24 + t.space_2;
}
x += 14.0;
@@ -974,6 +1117,223 @@ mod tests {
h
}
#[test]
fn playback_command_runs_from_ribbon_palette_shortcut_and_json() {
let mut h = two_boxes(false);
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.app.ui.tab = "INSPECT".into();
h.frames(3);
assert!(crate::scenario::handle_at("history:play").is_some(), "Play sits in the History controls by default");
let command = solidcraft_engine::find_command("timeline.play").unwrap();
let info = crate::render_workspace::interactive_command_info(&h.app, command);
assert!(info.enabled);
assert_eq!((info.label, info.icon), ("Play History", "timeline_play"));
h.step(&json!({"click": {"handle": "toolbar:timeline.play"}})).unwrap();
assert!(h.app.timeline_playback.is_some());
let info = crate::render_workspace::interactive_command_info(&h.app, command);
assert_eq!((info.label, info.icon), ("Stop History", "timeline_stop"));
// Opening search must leave playback running so Stop is available there too.
h.app.start("ui.palette");
h.call("ui.palette", json!({"text": "timeline.play"}));
h.frames(2);
assert!(h.app.timeline_playback.is_some());
let row = crate::shortcut_box::search(&h.app, "stop history").into_iter().find(|r| r.0 == "timeline.play").unwrap();
assert_eq!((row.1, row.2), ("Stop History", "timeline_stop"));
h.step(&json!({"key": "Enter"})).unwrap();
assert!(h.app.timeline_playback.is_none());
h.frames(3);
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
crate::keymap::bind(&mut h.app, "timeline.play", "Shift+P", true).unwrap();
h.step(&json!({"key": "P", "shift": true})).unwrap();
assert!(h.app.timeline_playback.is_some(), "marker {:?}, status {:?}", h.app.session.doc.marker, h.app.status);
h.step(&json!({"key": "P", "shift": true})).unwrap();
assert!(h.app.timeline_playback.is_none());
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.app.ui.show_timeline = false;
let camera = serde_json::to_value(h.app.cam).unwrap();
assert_eq!(h.call("engine.execute", json!({"command": "timeline.play", "params": {"action": "play"}}))["ok"], true);
h.frames(2);
assert_eq!(h.app.session.doc.marker, Some(1));
h.app.run("timeline.play", json!({"action": "play"})).unwrap();
assert!(h.app.timeline_playback.is_some(), "explicit Play is idempotent");
assert_eq!(h.call("engine.execute", json!({"command": "timeline.play", "params": {"action": "stop"}}))["ok"], true);
assert_eq!(serde_json::to_value(h.app.cam).unwrap(), camera, "playback never refits the view");
h.app.run("timeline.play", json!({"action": "stop"})).unwrap();
assert!(h.app.timeline_playback.is_none());
}
#[test]
fn playback_shows_each_feature_in_every_history_layout() {
for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] {
for (dock, width) in
[("bottom", 130.0), ("left", 56.0), ("left", crate::ui_kit::history_width(true)), ("left", 320.0), ("under_browser", 170.0)]
{
let mut h = two_boxes(dock != "bottom");
h.app.ui.layout = layout;
h.app.preferences.browser_width = 170.0;
h.app.run("view.history_layout", json!({"dock":dock,"width":width})).unwrap();
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.frames(2);
h.app.start("timeline.play");
h.frames(2);
assert_eq!(h.app.session.doc.marker, Some(1), "the first feature must be shown before the end; {layout:?} {dock} {width}");
assert_eq!(h.app.session.model.state().bodies.len(), 1);
h.frames(10);
assert_eq!(h.app.session.doc.marker, Some(1), "leave time to see each step");
h.frames(60);
assert_eq!(h.app.session.doc.marker, None);
assert_eq!(h.app.session.model.state().bodies.len(), 2);
}
}
}
#[test]
fn playback_advances_in_an_embed_without_application_chrome() {
let mut h = two_boxes(false);
h.app.embedded = true;
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.frames(2);
h.app.start("timeline.play");
h.frames(2);
assert_eq!(h.app.session.doc.marker, Some(1));
assert_eq!(h.app.session.model.state().bodies.len(), 1);
assert!(crate::scenario::rect_of("toolbar").is_none());
h.frames(60);
assert_eq!(h.app.session.doc.marker, None);
assert_eq!(h.app.session.model.state().bodies.len(), 2);
assert!(crate::scenario::rect_of("toolbar").is_none());
}
#[test]
fn playback_can_be_stopped_or_interrupted() {
for action in ["stop", "back", "last", "escape", "edit", "tool", "anchored_tool", "pinned_tool", "new"] {
let mut h = two_boxes(false);
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.frames(2);
h.app.start("timeline.play");
h.frames(2);
assert_eq!(h.app.session.doc.marker, Some(1));
match action {
"stop" => h.app.start("timeline.play"),
"back" => h.step(&json!({"click": {"handle": "history:back"}})).unwrap(),
"last" => {
h.step(&json!({"click": {"handle": "history:last"}})).unwrap();
assert_eq!(h.app.session.doc.marker, None, "Go to end jumps immediately, even during playback");
assert_eq!(h.app.session.model.state().bodies.len(), 2);
}
"escape" => h.step(&json!({"key": "Escape"})).unwrap(),
"edit" => {
h.app.run("timeline.rename", json!({"feature": "First", "name": "Renamed"})).unwrap();
}
"tool" => h.app.start("solid.box"),
"anchored_tool" => h.app.start_at("solid.box", Some(egui::Rect::from_min_size(egui::pos2(20.0, 20.0), egui::vec2(28.0, 28.0)))),
"pinned_tool" => h.app.start_pinned("solid.box", None),
_ => {
h.call("ui.documents", json!({"action": "new"}));
}
}
h.frames(1);
let marker = h.app.session.doc.marker;
h.frames(90);
assert!(h.app.timeline_playback.is_none(), "{action}");
assert_eq!(h.app.session.doc.marker, marker, "no later step after {action}");
}
}
#[test]
fn playback_keeps_a_visible_pause_after_a_synchronous_rebuild() {
let mut h = two_boxes(false);
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.app.run("timeline.play", json!({})).unwrap();
super::tick_playback(&mut h.app, &h.ctx);
assert_eq!(h.app.session.doc.marker, Some(1));
// Model a rebuild that held the window thread for ten seconds. Its first visible
// frame must still show the first feature; elapsed compute time is not playback.
let time = h.ctx.input(|i| i.time) + 10.0;
let _ = h.ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| {
super::tick_playback(&mut h.app, ui.ctx());
});
assert_eq!(h.app.session.doc.marker, Some(1));
assert_eq!(h.app.session.model.state().bodies.len(), 1);
}
#[test]
fn playback_at_the_end_or_in_an_empty_design_leaves_history_unchanged() {
for mut h in [Harness::new(), two_boxes(false)] {
h.frames(2);
let revision = h.app.session.revision;
h.app.start("timeline.play");
h.frames(2);
h.frames(60);
assert_eq!(h.app.session.revision, revision);
assert!(h.app.timeline_playback.is_none());
}
}
#[test]
fn playback_refuses_to_start_while_other_history_work_waits() {
let mut h = two_boxes(false);
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.app.deferred_queue.push(("timeline.roll_to".into(), json!({"position": 1})));
assert!(h.app.run("timeline.play", json!({"action": "play"})).is_err(), "refused up front, not stopped a frame later");
assert!(h.app.timeline_playback.is_none());
h.app.deferred_queue.clear();
h.app.run("timeline.play", json!({"action": "play"})).unwrap();
assert!(h.app.timeline_playback.is_some());
}
fn right_click(h: &mut Harness, handle: &str) {
let at = crate::scenario::handle_at(handle).unwrap();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() };
h.frame_with(vec![egui::Event::PointerMoved(at)]);
h.frame_with(vec![button(true)]);
h.frame_with(vec![button(false)]);
}
/// History shows Play between Previous and Next (#3688); turning it off gives back the four
/// controls it had before.
#[test]
fn the_play_button_plays_and_stops_and_the_controls_menu_hides_it() {
use crate::context_menu::Target;
for (dock, width) in [("bottom", 130.0), ("left", 56.0), ("left", 320.0)] {
let mut h = two_boxes(dock != "bottom");
h.app.run("view.history_layout", json!({"dock": dock, "width": width})).unwrap();
h.frames(2);
assert!(h.app.preferences.history_play_button, "on by default");
let at = |name: &str| crate::scenario::handle_at(name).unwrap();
let (back, play, forward) = (at("history:back"), at("history:play"), at("history:forward"));
let across = dock == "bottom" || width > 56.0;
if across {
assert!(back.x < play.x && play.x < forward.x, "Play sits between Previous and Next; {dock} {width}");
} else {
assert!(back.y < play.y && play.y < forward.y, "Play sits between Previous and Next; {dock} {width}");
}
h.app.run("timeline.roll_to", json!({"position": 0})).unwrap();
h.frames(2);
h.step(&json!({"click": {"handle": "history:play"}})).unwrap();
assert!(h.app.timeline_playback.is_some(), "the button plays; {dock} {width}");
h.step(&json!({"click": {"handle": "history:play"}})).unwrap();
assert!(h.app.timeline_playback.is_none(), "and stops; {dock} {width}");
right_click(&mut h, "history:back");
assert!(h.app.viewport.context_menu.is_some() && h.app.menu.target == Target::HistoryControls, "{dock} {width}");
let items = crate::context_menu::items(&h.app, &Target::HistoryControls);
assert_eq!(items[0].label, crate::i18n::tr("ui.history_play_button_hide"));
crate::context_menu::run_item(&mut h.app, &items[0], egui::Pos2::ZERO);
assert!(!h.app.preferences.history_play_button);
h.frames(2);
assert!(crate::scenario::handle_at("history:play").is_none(), "the four controls again; {dock} {width}");
let items = crate::context_menu::items(&h.app, &Target::HistoryControls);
assert_eq!(items[0].label, crate::i18n::tr("ui.history_play_button_show"));
crate::context_menu::run_item(&mut h.app, &items[0], egui::Pos2::ZERO);
h.frames(2);
assert!(crate::scenario::handle_at("history:play").is_some(), "and Play back; {dock} {width}");
}
}
#[test]
fn sketch_context_menu_redefines_the_plane_in_both_timelines() {
for left in [false, true] {
+15 -7
View File
@@ -335,7 +335,8 @@ pub fn left_timeline(app: &mut SolveApp, ui: &mut egui::Ui) {
fn timeline_transport(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) {
let t = Tokens::get();
let count = crate::ui_kit::HistoryTransport::ALL.len() as f32;
let mut controls = crate::ui_kit::HistoryTransport::shown(app.preferences.history_play_button);
let count = controls.len() as f32;
let height = if names { crate::ui_kit::TREE_ROW_HEIGHT } else { t.control_height * count + t.space_2 * (count - 1.0) };
let (header, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
crate::scenario::publish_rect("history:transport", header);
@@ -362,7 +363,11 @@ fn timeline_transport(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) {
.layout(egui::Layout::left_to_right(egui::Align::Center)),
);
let handle = crate::ui_kit::panel_grip(&mut grip).rect;
let controls_width = crate::ui_kit::history_transport_width();
// A named column too narrow for five buttons beside its grip leaves Play to the ribbon.
if controls_right - crate::ui_kit::history_controls_width(controls.len()) < handle.right() + t.space_2 {
controls = &crate::ui_kit::HistoryTransport::ALL;
}
let controls_width = crate::ui_kit::history_controls_width(controls.len());
let title = crate::i18n::tr("ui.history_title");
let galley = ui.painter().layout_no_wrap(title.to_owned(), crate::fonts::semibold(t.font_heading), t.text);
let text_left = handle.right() + t.space_8;
@@ -379,19 +384,21 @@ fn timeline_transport(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) {
crate::scenario::publish_handle("history:grip", drag_rect.center());
dock_drag(app, ui, &drag);
}
for (i, control) in crate::ui_kit::HistoryTransport::ALL.into_iter().enumerate() {
for (i, &control) in controls.iter().enumerate() {
let side = if names { t.space_24 } else { t.control_height };
let rect = if names {
Rect::from_min_size(
pos2(controls_right - crate::ui_kit::history_transport_width() + i as f32 * (side + t.space_2), header.center().y - side / 2.0),
pos2(
controls_right - crate::ui_kit::history_controls_width(controls.len()) + i as f32 * (side + t.space_2),
header.center().y - side / 2.0,
),
vec2(side, side),
)
} else {
Rect::from_min_size(pos2(header.center().x - side / 2.0, header.top() + i as f32 * (side + t.space_2)), vec2(side, side))
};
if control.show(ui, rect).clicked() {
crate::timeline::run_transport(app, control);
}
let response = control.show(ui, rect, app.timeline_playback.is_some());
crate::timeline::transport_response(app, control, &response);
}
}
@@ -1688,6 +1695,7 @@ mod tests {
("last", None),
] {
h.step(&json!({"click":{"handle":format!("history:{control}")}})).unwrap();
assert!(h.app.timeline_playback.is_none(), "navigation never starts playback");
h.settle();
assert_eq!(h.app.session.doc.marker, position, "{mode:?} {dock} {width}: {control}");
assert_eq!(h.app.session.model.state().bodies.len(), position.unwrap_or(3));
+3 -3
View File
@@ -1577,13 +1577,13 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) {
icons::paint_icon(
&painter,
Rect::from_center_size(cell.center(), vec2(15.0, 15.0)),
c.icon,
info.icon,
if info.enabled { 1.0 } else { 0.35 },
);
for prefix in ["toolbar", "button", "ribbon:constraint"] {
crate::scenario::publish_target(&format!("{prefix}:{}", c.id), cell);
}
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, info.enabled, app.tr_label(c.label)));
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, info.enabled, app.tr_label(info.label)));
if resp.drag_started() {
resp.dnd_set_drag_payload(ToolbarDrag { id: c.id, from_menu: false });
}
@@ -1865,7 +1865,7 @@ const CONSTRAINT_GRID_WIDTH: f32 = 82.0;
fn ribbon_tooltip(app: &SolveApp, response: egui::Response, command: &solidcraft_engine::CommandSpec, disabled: Option<&str>) -> egui::Response {
response.on_hover_ui(|ui| {
let t = Tokens::get();
let name = app.tr_label(command.info(&app.session).label);
let name = app.tr_label(crate::render_workspace::interactive_command_info(app, command).label);
let name_width =
ui.painter().layout_no_wrap(name.to_string(), crate::fonts::semibold(crate::theme::Tokens::get().font_heading), t.text).size().x;
let key_width = crate::keymap::display_for(app, command.id)
+1 -1
View File
@@ -575,7 +575,7 @@ const ELEMENTS: &[Element] = &[
let side = Tokens::get().space_24;
for control in HistoryTransport::ALL {
let (rect, _) = ui.allocate_exact_size(vec2(side, side), egui::Sense::hover());
control.show(ui, rect);
control.show(ui, rect, false);
}
});
}),
+27 -7
View File
@@ -193,46 +193,60 @@ pub(crate) fn history_marker(p: &Painter, rect: Rect, vertical: bool, accent: Ta
p.circle(centre, outer_radius - t.space_2 / 2.0, if vertical { t.panel } else { t.timeline }, Stroke::new(t.space_2, accent.color));
}
/// The same four rollback controls are used in every History orientation.
#[derive(Clone, Copy)]
/// The same controls are used in every History orientation: first, previous, Play History, next
/// and last, or the four without Play when `history_play_button` is off.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum HistoryTransport {
First,
Back,
Play,
Forward,
Last,
}
impl HistoryTransport {
pub const ALL: [Self; 4] = [Self::First, Self::Back, Self::Forward, Self::Last];
pub const WITH_PLAY: [Self; 5] = [Self::First, Self::Back, Self::Play, Self::Forward, Self::Last];
/// The controls History shows: the four, or five with the Play button preference on.
pub fn shown(play: bool) -> &'static [Self] {
if play { &Self::WITH_PLAY } else { &Self::ALL }
}
pub fn id(self) -> &'static str {
match self {
Self::First => "first",
Self::Back => "back",
Self::Play => "play",
Self::Forward => "forward",
Self::Last => "last",
}
}
fn label(self) -> &'static str {
fn label(self, playing: bool) -> &'static str {
crate::i18n::tr(match self {
Self::First => "ui.history_first",
Self::Back => "ui.history_back",
Self::Play if playing => "cmd.timeline_stop",
Self::Play => "cmd.timeline_play",
Self::Forward => "ui.history_forward",
Self::Last => "ui.history_last",
})
}
pub fn show(self, ui: &mut egui::Ui, rect: Rect) -> egui::Response {
/// `playing` turns the Play button into Stop; the other controls ignore it.
pub fn show(self, ui: &mut egui::Ui, rect: Rect, playing: bool) -> egui::Response {
let t = Tokens::get();
let response = ui.interact(rect, ui.id().with(("history_transport", self.id())), egui::Sense::click());
crate::scenario::publish_target(&format!("history:{}", self.id()), rect);
if response.hovered() {
ui.painter().rect_filled(rect, t.radius_sm, t.hover);
}
icons::glyphs::transport_glyph(ui.painter(), rect.center(), self.id(), t.icon);
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.label()));
response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(self.label())
let glyph = if self == Self::Play && playing { "pause" } else { self.id() };
icons::glyphs::transport_glyph(ui.painter(), rect.center(), glyph, t.icon);
let label = self.label(playing);
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label));
response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(label)
}
}
@@ -241,6 +255,12 @@ pub(crate) fn history_transport_width() -> f32 {
t.space_24 * HistoryTransport::ALL.len() as f32 + t.space_2 * (HistoryTransport::ALL.len() - 1) as f32
}
/// The width of `count` transport buttons side by side (five with Play History shown).
pub(crate) fn history_controls_width(count: usize) -> f32 {
let t = Tokens::get();
t.space_24 * count as f32 + t.space_2 * count.saturating_sub(1) as f32
}
/// Thin and minimum named widths; wider named panels retain their measured width.
pub(crate) fn history_width(names: bool) -> f32 {
let t = Tokens::get();
+1 -1
View File
@@ -199,7 +199,7 @@ pub const SECTIONS: &[Section] = &[
"inspect.continuity",
],
},
Section { tab: "INSPECT", panel: "HISTORY", promoted: 2, ids: &["timeline.dependents", "document.inspect"] },
Section { tab: "INSPECT", panel: "HISTORY", promoted: 3, ids: &["timeline.play", "timeline.dependents", "document.inspect"] },
Section {
tab: "MANAGE",
panel: "PARAMETERS",
+10
View File
@@ -277,6 +277,16 @@ fn requested_menu_icons_have_artwork_and_match_manifest() {
history.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":name})).unwrap();
}
history.frames(3);
history.app.run("timeline.roll_to", json!({"position":0})).unwrap();
history.app.ui.tab = "INSPECT".into();
history.frames(2);
click(&mut history, "toolbar:timeline.play");
history.frames(1);
collect(&mut history, "history playback stop", &mut requested);
history.app.ui.tab = "INSPECT".into();
history.frames(2);
click(&mut history, "toolbar:timeline.play");
history.app.run("timeline.roll_to", json!({})).unwrap();
// Named feature history has independent menus in both layout preferences.
for left in [false, true] {
history.app.preferences.timeline_left = left;
+8 -1
View File
@@ -114,7 +114,14 @@
chips and compact feature names; the browser can collapse to a rail beside either width.
Docked under the browser, the two share the column: drag the seam between them to give either
more height, and the split is remembered.
Previous, Play and Next sit at the top. Double-click Previous to roll to the start.
Its controls jump to the beginning, step back one feature, play, step forward one feature or
jump to the end. **Play History**, in the middle of those controls and under
**Inspect → History**, advances through the remaining features, pausing half a second after
each rebuilt step appears. It becomes **Stop History** while running; it is also in command
search and can be assigned a shortcut in Preferences → Keyboard Shortcuts. Click Stop History
or press Escape to stop playback; navigation and editing stop it too. To keep the controls to
four, right-click them and choose **Hide Play Button**, or clear the setting under
Preferences → Interface.
Interface › **Sketches** › **Under their feature** lists a sketch in the vertical timeline one
level in, under the first feature built from it, behind that feature's fold arrow. Dragging the
feature takes its sketch along. A later feature built from the same sketch gets a row that