panels-w11: net change of 2 commits

- panels-w11: written from its sheet
- panels-w11: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-27 14:51:30 +00:00
parent 5f4cb054b2
commit 3d78e784d6
3 changed files with 294 additions and 287 deletions
+47 -33
View File
@@ -19,16 +19,14 @@ fn harness() -> Harness<'static, SlideApp> {
s.execute("edit.select", &json!({"ids": [id]})).unwrap();
s.execute("animation.add", &json!({"effect": effect, "start": start, "duration": dur})).unwrap();
}
// P3(panels-w11): sh.A2
let mut app = SlideApp::new_base(s, Services::default());
app.ui.pane = Some("animation".into());
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
let mut h = crate::test_harness::harness_with(
s,
Services::default(),
Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0),
|_| {},
);
// The command opens Pane::Task("animation") through the editor's pane host.
h.state_mut().run("view.pane", json!({"pane": "animation"})).unwrap();
h.run_steps(3);
h
}
@@ -54,8 +52,8 @@ fn drag(h: &mut Harness<'_, SlideApp>, from: Pos2, to: Pos2) {
#[test]
fn after_previous_bar_starts_where_the_first_ends() {
let h = harness();
let a = h.get_by_label("Timing bar 1").rect();
let b = h.get_by_label("Timing bar 2").rect();
let a = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 1").rect();
let b = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2").rect();
assert!((b.left() - a.right()).abs() < 1.5, "{a:?} {b:?}");
assert!((b.width() - 2.0 * a.width()).abs() < 1.5, "2 s bar twice the 1 s bar");
}
@@ -63,22 +61,48 @@ fn after_previous_bar_starts_where_the_first_ends() {
#[test]
fn dragging_a_bar_sets_the_delay_and_undoes() {
let mut h = harness();
let a = h.get_by_label("Timing bar 1").rect();
// One second is the width of bar 1.
drag(&mut h, a.center(), a.center() + egui::vec2(a.width() / 2.0, 0.0));
assert_eq!(timing(&h, 0), (500, 1000));
let before = timing(&h, 0);
let a = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 1").rect();
// A click without a drag is not a timing edit.
drag(&mut h, a.center(), a.center());
assert_eq!(timing(&h, 0), before);
// Separate the click from the next press so it is not a double click.
h.run_steps(60);
let fraction = 0.5;
drag(&mut h, a.center(), a.center() + egui::vec2(a.width() * fraction, 0.0));
let changed = timing(&h, 0);
assert_eq!(changed.0 - before.0, (before.1 as f32 * fraction) as u32);
assert_eq!(changed.1, before.1);
h.state_mut().session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(timing(&h, 0), (0, 1000));
assert_eq!(timing(&h, 0), before);
}
#[test]
fn dragging_the_edge_sets_the_duration() {
let mut h = harness();
let b = h.get_by_label("Timing bar 2").rect();
let one_sec = b.width() / 2.0;
let edge = h.get_by_label("Duration handle 2").rect().center();
drag(&mut h, edge, edge - egui::vec2(one_sec, 0.0));
assert_eq!(timing(&h, 1), (0, 1000));
let before = timing(&h, 1);
let b = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2").rect();
let edge = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2 end").rect().center();
drag(&mut h, edge, edge - egui::vec2(b.width() / 2.0, 0.0));
assert_eq!(timing(&h, 1), (before.0, before.1 / 2));
h.state_mut().session.execute("animation.timing", &json!({"index": 1, "duration": before.1, "repeat": 2})).unwrap();
h.run_steps(2);
let repeated = timing(&h, 1);
let b = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2").rect();
let edge = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2 end").rect().center();
// Half the displayed four-second span is one second per iteration.
drag(&mut h, edge, edge - egui::vec2(b.width() / 2.0, 0.0));
assert_eq!(timing(&h, 1), (repeated.0, repeated.1 / 2));
let shortened = timing(&h, 1);
let b = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2").rect();
let edge = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2 end").rect().center();
let least = crate::animtimeline::MIN_DURATION_MS;
let span_ms = shortened.1 * 2;
let target = egui::pos2(b.left() + b.width() * least as f32 / span_ms as f32, edge.y);
drag(&mut h, edge, target);
assert_eq!(timing(&h, 1), (before.0, least));
}
/// Seconds on the play-all clock where the canvas preview is, right after the pane's play button.
@@ -118,7 +142,7 @@ fn play_from_follows_the_effect_clicked_in_the_pane() {
h.state_mut().session.execute("animation.add", &json!({"effect": "pulse", "start": "afterPrevious", "duration": 1000})).unwrap();
h.run_steps(2);
// The row of the pulse, left of its bar.
let bar = h.get_by_label("Timing bar 3").rect();
let bar = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 3").rect();
let row = egui::pos2(bar.left() - 20.0, bar.center().y);
h.hover_at(row);
h.run_steps(1);
@@ -132,7 +156,7 @@ fn play_from_follows_the_effect_clicked_in_the_pane() {
/// Clicks the pane row of effect `n` (1-based), left of its timing bar, with `button`.
fn click_row(h: &mut Harness<'_, SlideApp>, n: usize, button: egui::PointerButton) {
let bar = h.get_by_label(&format!("Timing bar {n}")).rect();
let bar = h.get_by_role_and_label(egui::accesskit::Role::Slider, &format!("Timing bar {n}")).rect();
let pos = egui::pos2(bar.left() - 20.0, bar.center().y);
h.event(egui::Event::PointerMoved(pos));
h.run_steps(1);
@@ -189,13 +213,3 @@ fn preview_rejects_a_from_that_is_not_an_effect_index() {
}
assert_eq!(h.state_mut().run("animation.preview", json!({"from": 1})).unwrap()["from"], 1.0);
}
#[test]
#[ignore = "writes a screenshot for review"]
fn screenshot() {
let _gpu = crate::gpu_lock::gpu_lock();
let mut h = harness();
h.run_steps(2);
let img = h.render().unwrap();
img.save("/tmp/animpane.png").unwrap();
}
+219 -188
View File
@@ -1,194 +1,225 @@
use super::{
Align2, AnimClass, AnimStart, Color32, CornerRadius, Icon, Rect, Sense, SlideApp, Stroke, Tokens, Ui, animtimeline, icons, json, paint_anim_tile,
pos2, run, theme, vec2,
};
use std::cell::RefCell;
/// Render the animation pane and route its controls through the engine's animation commands.
pub(super) fn animation(app: &mut SlideApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let Some(st) = app.session.active() else { return };
let Some(slide) = st.current_slide() else { return };
let anims = slide.animations.clone();
let size = (st.doc.slide_size.width, st.doc.slide_size.height);
let tl = deckcraft_anim::Timeline::new(slide, size.0, size.1);
let effects = tl.effects();
let names: Vec<(u32, String)> = st.shapes().iter().map(|s| (s.id.0, s.name.clone())).collect();
let selected: Vec<u32> = st.selection.shapes.iter().map(|i| i.0).collect();
// Play From starts at the effect last clicked here, or else the first effect of the selected
// shape; with nothing selected it is Play All. Reordering or removing forgets the click: the
// index would point at another effect.
let pick_id = egui::Id::unique(("anim_pane_pick", st.uid, st.selection.slide));
let pick = ui.data(|m| m.get_temp::<usize>(pick_id));
// A triggered effect is not on the click sequence, so it can't be played from.
let eligible = |i: usize| anims.get(i).is_some_and(|a| selected.contains(&a.shape.0)) && tl.start_of(i).is_some();
let from = pick.filter(|&i| eligible(i)).or_else(|| (0..anims.len()).find(|&i| eligible(i)));
ui.horizontal(|ui| {
let playing = app.anim_preview_active();
let label = match (playing, from) {
(true, _) => "■ Stop",
(false, Some(_)) => "▶ Play From",
(false, None) => "▶ Play All",
};
if ui.button(label).clicked() {
let p = match (playing, from) {
(false, Some(i)) => json!({"on": true, "from": i}),
_ => json!({"on": !playing}),
};
run(app, "animation.preview", p);
}
});
ui.separator();
if anims.is_empty() {
ui.label(egui::RichText::new("Select an object on the slide and add an animation from the Animations tab.").color(t.text_dim));
return;
}
let bars = animtimeline::bars(anims.len(), &effects);
let seconds = animtimeline::ruler_seconds(&bars);
let track_w = (ui.available_width() * 0.45).max(60.0);
let pps = animtimeline::pixels_per_second(track_w, seconds);
let mut click = 0;
for (i, a) in anims.iter().enumerate() {
if a.start == AnimStart::OnClick {
click += 1;
}
let name = names.iter().find(|(id, _)| *id == a.shape.0).map(|(_, n)| n.clone()).unwrap_or_else(|| format!("Shape {}", a.shape));
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click());
let sel = selected.contains(&a.shape.0);
if sel || resp.hovered() {
ui.painter().rect_filled(r, CornerRadius::same(4), if sel { t.selected } else { t.hover });
}
if from == Some(i) {
ui.painter().rect_stroke(r, CornerRadius::same(4), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);
}
let p = ui.painter();
p.text(
pos2(r.min.x + 6.0, r.center().y),
Align2::LEFT_CENTER,
if a.start == AnimStart::OnClick { click.to_string() } else { String::new() },
theme::font(12.0),
t.text_dim,
);
let icon = match a.class {
AnimClass::Entrance => Icon::AnimEntrance,
AnimClass::Emphasis => Icon::AnimEmphasis,
AnimClass::Exit => Icon::AnimExit,
_ => Icon::AnimPath,
};
icons::paint(p, Rect::from_center_size(pos2(r.min.x + 30.0, r.center().y), vec2(18.0, 18.0)), icon, t.text, false);
p.text(pos2(r.min.x + 44.0, r.center().y), Align2::LEFT_CENTER, &name, theme::font(12.5), t.text);
// Advanced timeline bar: drag the body to change the delay, the right edge for the duration.
if let Some(Some(b)) = bars.get(i) {
let col = match a.class {
AnimClass::Entrance => Color32::from_rgb(0x2E, 0xA3, 0x6F),
AnimClass::Emphasis => Color32::from_rgb(0xE3, 0xB2, 0x1C),
AnimClass::Exit => Color32::from_rgb(0xD8, 0x3F, 0x6B),
_ => Color32::from_rgb(0x2E, 0x6F, 0xD8),
};
let x0 = r.max.x - track_w - 6.0;
let x_of = |sec: f64| x0 + (sec as f32 * pps).min(track_w);
let mut bar = Rect::from_min_max(
pos2(x_of(b.start), r.center().y - 5.0),
pos2(x_of(b.start + b.span).max(x_of(b.start) + 4.0), r.center().y + 5.0),
);
let edge = Rect::from_min_max(pos2(bar.max.x - 3.0, bar.min.y - 3.0), pos2(bar.max.x + 4.0, bar.max.y + 3.0));
let body_resp = ui.interact(bar, ui.scope_id().with(("anim_bar", i)), Sense::drag()).on_hover_text(animtimeline::label(b));
body_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, format!("Timing bar {}", i + 1)));
let edge_resp = ui.interact(edge, ui.scope_id().with(("anim_edge", i)), Sense::drag());
edge_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, format!("Duration handle {}", i + 1)));
if edge_resp.hovered() || edge_resp.dragged() {
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
} else if body_resp.hovered() || body_resp.dragged() {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
}
// The drag offset is remembered: the pointer's press origin is gone on release.
let dx_id = ui.scope_id().with(("anim_drag_dx", i));
let live = ui.input(|inp| match (inp.pointer.press_origin(), inp.pointer.interact_pos()) {
(Some(o), Some(p)) => Some(p.x - o.x),
_ => None,
});
let dx = match live {
Some(d) if body_resp.dragged() || edge_resp.dragged() => {
ui.data_mut(|m| m.insert_temp(dx_id, d));
d
}
_ => ui.data_mut(|m| m.get_temp::<f32>(dx_id)).unwrap_or(0.0),
};
if body_resp.drag_stopped() || edge_resp.drag_stopped() {
ui.data_mut(|m| m.remove::<f32>(dx_id));
}
let iter_secs = f64::from(a.duration_ms) / 1000.0;
let factor = if iter_secs > 0.0 && b.span > 0.0 { b.span / iter_secs } else { 1.0 };
if edge_resp.dragged() || edge_resp.drag_stopped() {
let d = animtimeline::dragged_duration(a.duration_ms, dx, pps, factor);
bar.max.x = x_of(b.start + f64::from(d) / 1000.0 * factor).max(bar.min.x + 4.0);
if edge_resp.drag_stopped() && d != a.duration_ms {
run(app, "animation.timing", json!({"index": i, "duration": d}));
}
} else if body_resp.dragged() || body_resp.drag_stopped() {
let d = animtimeline::dragged_delay(a.delay_ms, dx, pps);
let shift = (f64::from(d) - f64::from(a.delay_ms)) / 1000.0;
let w = bar.width();
bar.min.x = x_of((b.start + shift).max(0.0));
bar.max.x = bar.min.x + w;
if body_resp.drag_stopped() && d != a.delay_ms {
run(app, "animation.timing", json!({"index": i, "delay": d}));
}
}
let p = ui.painter();
p.rect_filled(bar, CornerRadius::same(2), col);
if a.repeat == u32::MAX {
p.text(pos2(bar.max.x + 2.0, bar.center().y), Align2::LEFT_CENTER, "⟳", theme::font(10.0), t.text_dim);
}
}
if resp.clicked() {
ui.data_mut(|m| m.insert_temp(pick_id, i));
run(app, "edit.select", json!({"ids": [a.shape.0]}));
}
resp.context_menu(|ui| {
for (l, v) in [("Start On Click", "onClick"), ("Start With Previous", "withPrevious"), ("Start After Previous", "afterPrevious")] {
if ui.button(l).clicked() {
run(app, "animation.timing", json!({"index": i, "start": v}));
ui.close();
}
}
ui.separator();
if ui.button("Move Up").clicked() {
ui.data_mut(|m| m.remove::<usize>(pick_id));
run(app, "animation.move", json!({"index": i, "to": i.saturating_sub(1)}));
ui.close();
}
if ui.button("Move Down").clicked() {
ui.data_mut(|m| m.remove::<usize>(pick_id));
run(app, "animation.move", json!({"index": i, "to": i + 1}));
ui.close();
}
if ui.button("Remove").clicked() {
ui.data_mut(|m| m.remove::<usize>(pick_id));
run(app, "animation.remove", json!({"index": i}));
ui.close();
}
});
}
// Seconds ruler under the bars.
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover());
let x0 = r.max.x - track_w - 6.0;
let p = ui.painter();
p.line_segment([pos2(x0, r.min.y + 2.0), pos2(x0 + track_w, r.min.y + 2.0)], Stroke::new(1.0, t.text_faint));
let every = (seconds / 6).max(1);
for s in (0..=seconds).step_by(every as usize) {
let x = x0 + s as f32 * pps;
if x > x0 + track_w + 0.5 {
break;
}
p.line_segment([pos2(x, r.min.y), pos2(x, r.min.y + 5.0)], Stroke::new(1.0, t.text_faint));
p.text(pos2(x, r.min.y + 6.0), Align2::CENTER_TOP, format!("{s}s"), theme::font(10.0), t.text_dim);
}
let _ = paint_anim_tile;
}
use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, ItemSource, Mixed, Selection, SelectionChange};
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::display::{Divider, Icon as DisplayIcon, Shade, Text};
use craft::ui::list::{List, ListRow};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::env::{Env, Label};
use craft::ui::value_drag::{RangeSlider, RangeSliderForm};
use deckcraft_model::{AnimClass, AnimStart};
use egui::Ui;
use serde_json::json;
/// The animation pane selected effect.
#[allow(dead_code)] // P3(panels-w11): pn.A11
use super::{animtimeline, run};
use crate::{SlideApp, icons::Icon};
const CLICK: ColumnKey = ColumnKey::new("click");
const NAME: ColumnKey = ColumnKey::new("name");
const TIMING: ColumnKey = ColumnKey::new("timing");
const REPEAT: ColumnKey = ColumnKey::new("repeat");
/// The effect picked for Play From, scoped to its document and slide.
#[derive(Default)]
pub struct AnimPaneState {
picked: Option<(u64, usize, usize)>,
}
struct Rows {
names: Vec<String>,
clicks: Vec<String>,
}
impl DisplayOrder<usize> for Rows {
fn len(&self) -> usize {
self.names.len() + 1
}
fn key(&self, at: usize) -> usize {
at
}
// PLAN: plan error: List has no non-selectable plain row for a ruler
fn is_section(&self, at: usize) -> bool {
at == self.names.len()
}
}
impl ItemSource<usize> for Rows {}
/// Render the animation pane and route its controls through registered commands.
pub(super) fn animation(app: &mut SlideApp, ui: &mut Ui) {
let Some(st) = app.session.active() else { return };
let Some(slide) = st.current_slide() else { return };
let uid = st.uid;
let slide_index = st.selection.slide;
let anims = slide.animations.clone();
let tl = deckcraft_anim::Timeline::new(slide, st.doc.slide_size.width, st.doc.slide_size.height);
let bars = animtimeline::bars(anims.len(), &tl.effects());
let selected: Vec<usize> = anims.iter().enumerate().filter(|(_, a)| st.selection.shapes.contains(&a.shape)).map(|(i, _)| i).collect();
// Triggered effects have no position on the click sequence.
let eligible = |i| selected.contains(&i) && tl.start_of(i).is_some();
let from = app
.anim_pane
.picked
.filter(|&(doc, slide, i)| doc == uid && slide == slide_index && eligible(i))
.map(|(_, _, i)| i)
.or_else(|| (0..anims.len()).find(|&i| eligible(i)));
let names = anims
.iter()
.map(|a| {
st.shapes()
.iter()
.find(|s| s.id == a.shape)
.map(|s| s.name.clone())
.filter(|name| !name.is_empty())
.unwrap_or_else(|| format!("Shape {}", a.shape))
})
.collect();
// Click numbers count only OnClick; timing labels count every effect.
let mut click = 0;
let clicks = anims
.iter()
.map(|a| {
if a.start == AnimStart::OnClick {
click += 1;
click.to_string()
} else {
String::new()
}
})
.collect();
let source = Rows { names, clicks };
let playing = app.anim_preview_active();
let label = match (playing, from) {
(true, _) => "■ Stop",
(false, Some(_)) => "▶ Play From",
(false, None) => "▶ Play All",
};
if Button::new(label).show(ui).clicked() {
let params = match (playing, from) {
(false, Some(i)) => json!({"on": true, "from": i}),
_ => json!({"on": !playing}),
};
run(app, "animation.preview", params);
}
Divider::horizontal().show(ui);
if anims.is_empty() {
Text::new("Select an object on the slide and add an animation from the Animations tab.").shade(Shade::Muted).show(ui);
return;
}
let seconds = animtimeline::ruler_seconds(&bars);
let range = 0.0..=f64::from(seconds);
let every = (seconds / 6).max(1);
let columns = vec![
craft::ui::contract::ColumnSpec::new(CLICK, Label::Empty, ColumnWidth::Content),
craft::ui::contract::ColumnSpec::new(NAME, Label::Empty, ColumnWidth::Content),
craft::ui::contract::ColumnSpec::new(TIMING, Label::Empty, ColumnWidth::fill(1.0)).at_least(Env::of(ui).tokens.size.length.track),
craft::ui::contract::ColumnSpec::new(REPEAT, Label::Empty, ColumnWidth::Controls(1.0)),
];
let commits = RefCell::new(Vec::new());
let out = List::<usize>::new("Animations")
.id_salt(("animations", uid, slide_index))
.select(SelectMode::Single)
.selection(Bind::given(Selection::new(selected.clone(), None, None)))
.current(from)
.header(false)
.natural_height(true)
.columns(columns)
.show_items(ui, &source, &mut |&i, icx| {
let row = ListRow::new(source.names.get(i).cloned().unwrap_or_default())
.cells(icx.cells())
.cell(CLICK, source.clicks.get(i).cloned().unwrap_or_default())
.cell_muted(CLICK)
.cell(TIMING, Label::Empty)
.cell(REPEAT, Label::Empty);
if i == anims.len() {
let axis = RangeSlider::new(Bind::given((Mixed::Same(0.0), Mixed::Same(f64::from(seconds)))), range.clone())
.form(RangeSliderForm::Axis)
.marks_labelled((0..=seconds).step_by(every as usize).map(|s| (f64::from(s), format!("{s}s"))))
.label("Seconds");
return row.node(false).cell_field(TIMING, axis, |_| {});
}
let a = &anims[i];
let (icon, series) = match a.class {
AnimClass::Entrance => (Icon::AnimEntrance, 3),
AnimClass::Emphasis => (Icon::AnimEmphasis, 1),
AnimClass::Exit => (Icon::AnimExit, 0),
_ => (Icon::AnimPath, 5),
};
let mut row = row.icon(IconSpec::svg(icon.id())).selected(selected.contains(&i));
if let Some(b) = &bars[i] {
let pair = (Mixed::Same(b.start), Mixed::Same(b.start + b.span));
let slider = RangeSlider::new(Bind::given(pair), range.clone())
.form(RangeSliderForm::Span)
.step(f64::from(animtimeline::SNAP_MS) / 1000.0)
.min_span(f64::from(animtimeline::MIN_DURATION_MS) / 1000.0)
.series(series)
.readout(format!("Start: {:.2}s, End: {:.2}s", b.start, b.start + b.span))
.label(format!("Timing bar {}", i + 1));
let commits = &commits;
row = row.cell_field(TIMING, slider, move |out| {
if let Some((Mixed::Same(start), Mixed::Same(end))) = out.events.committed() {
commits.borrow_mut().push((i, (*start, *end)));
}
});
}
if a.repeat == u32::MAX {
row = row.cell_field(REPEAT, DisplayIcon::new(IconSpec::svg(Icon::Loop.id())).label("Repeat"), |_| {});
}
row
});
for (i, pair) in commits.into_inner() {
let Some(bar) = &bars[i] else { continue };
match animtimeline::timing_of(bar, &anims[i], pair) {
Some(animtimeline::Retime::Delay(delay)) => run(app, "animation.timing", json!({"index": i, "delay": delay})),
Some(animtimeline::Retime::Duration(duration)) => run(app, "animation.timing", json!({"index": i, "duration": duration})),
None => {}
}
}
for event in out.events {
let pick = match event {
CollectionEvent::Selection { change, .. } => match change {
SelectionChange::Set(keys) => Some(keys.last().copied()),
SelectionChange::Toggle(key) => Some((!selected.contains(&key)).then_some(key)),
SelectionChange::Clear => Some(None),
_ => None,
},
CollectionEvent::Picked { key, .. } | CollectionEvent::Activate(key) => Some(Some(key)),
_ => None,
};
if let Some(pick) = pick {
if let Some(i) = pick.filter(|&i| i < anims.len()) {
app.anim_pane.picked = Some((uid, slide_index, i));
run(app, "edit.select", json!({"ids": [anims[i].shape.0]}));
} else {
app.anim_pane.picked = None;
run(app, "edit.deselect", json!({}));
}
}
}
if let Some(request) = out.menu.filter(|request| request.key < anims.len()) {
let i = request.key;
Menu::context("Animation", &out.response).show(ui, |ui, _| {
for (label, start) in [("Start On Click", "onClick"), ("Start With Previous", "withPrevious"), ("Start After Previous", "afterPrevious")]
{
if MenuItem::new(label).show(ui).ran {
run(app, "animation.timing", json!({"index": i, "start": start}));
}
}
Divider::horizontal().show(ui);
for (label, command, params) in [
("Move Up", "animation.move", json!({"index": i, "to": i.saturating_sub(1)})),
("Move Down", "animation.move", json!({"index": i, "to": i + 1})),
("Remove", "animation.remove", json!({"index": i})),
] {
if MenuItem::new(label).show(ui).ran {
app.anim_pane.picked = None;
run(app, command, params);
}
}
});
}
}
+28 -66
View File
@@ -1,19 +1,14 @@
//! Animation Pane advanced timeline: bar geometry and drag-to-retime maths.
//!
//! Pure functions so the layout and the drag results are unit-tested without a frame. Times
//! come from [`deckcraft_anim::Timeline`], the same schedule the slide show plays.
//! Animation Pane schedule rows and committed timing edits. Times come from
//! [`deckcraft_anim::Timeline`], the same schedule the slide show plays.
use deckcraft_anim::{EffectTiming, Sequence};
/// Drags snap to this step (milliseconds), like PowerPoint's 0.05 s granularity.
/// The timing slider's step in milliseconds.
pub const SNAP_MS: u32 = 50;
/// Shortest duration a drag can produce (milliseconds).
pub const MIN_DURATION_MS: u32 = 50;
/// Upper bound for delay and duration, matching `animation.timing`'s clamp.
pub const MAX_MS: u32 = 600_000;
/// Pixels per second are kept in this range whatever the pane width.
const MIN_PPS: f32 = 8.0;
const MAX_PPS: f32 = 120.0;
/// One effect row of the timeline (first paragraph of a by-paragraph build).
#[derive(Clone, Debug, PartialEq)]
@@ -54,40 +49,34 @@ pub fn ruler_seconds(bars: &[Option<Bar>]) -> u32 {
if s.is_finite() && s >= 1.0 { s as u32 } else { 1 }
}
/// Pixels per second so `seconds` fit in `width`.
pub fn pixels_per_second(width: f32, seconds: u32) -> f32 {
let secs = seconds.max(1) as f32;
let pps = if width.is_finite() { width / secs } else { MIN_PPS };
pps.clamp(MIN_PPS, MAX_PPS)
/// The timing field changed by a committed span edit.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Retime {
/// Delay before the effect, in milliseconds.
Delay(u32),
/// Duration of one iteration, in milliseconds.
Duration(u32),
}
fn snap(ms: f64) -> u32 {
if !ms.is_finite() || ms <= 0.0 {
return 0;
/// Maps a committed displayed span to one animation timing edit.
///
/// Moving the whole span changes delay relative to its scheduled start. Moving only its end
/// changes one iteration's duration, preserving repeats and auto-reverse. An unchanged span,
/// including a click without a drag, produces no edit.
pub fn timing_of(bar: &Bar, anim: &deckcraft_model::Animation, new: (f64, f64)) -> Option<Retime> {
if !new.0.is_finite() || !new.1.is_finite() || new == (bar.start, bar.start + bar.span) {
return None;
}
let delta = new.0 - bar.start;
if delta.abs() > f64::from(SNAP_MS) / 2000.0 {
let delay = (f64::from(anim.delay_ms) + (delta * 1000.0).round()).clamp(0.0, f64::from(MAX_MS)) as u32;
(delay != anim.delay_ms).then_some(Retime::Delay(delay))
} else {
let iter_secs = f64::from(anim.duration_ms) / 1000.0;
let factor = if iter_secs > 0.0 && bar.span > 0.0 { bar.span / iter_secs } else { 1.0 };
let duration = ((new.1 - new.0) / factor * 1000.0).round().clamp(f64::from(MIN_DURATION_MS), f64::from(MAX_MS)) as u32;
(duration != anim.duration_ms).then_some(Retime::Duration(duration))
}
let snapped = (ms / f64::from(SNAP_MS)).round() * f64::from(SNAP_MS);
if snapped >= f64::from(MAX_MS) { MAX_MS } else { snapped as u32 }
}
fn delta_ms(dx: f32, pps: f32) -> f64 {
if !dx.is_finite() || !pps.is_finite() || pps <= 0.0 { 0.0 } else { f64::from(dx) / f64::from(pps) * 1000.0 }
}
/// New delay after dragging a bar's body `dx` pixels.
pub fn dragged_delay(delay_ms: u32, dx: f32, pps: f32) -> u32 {
snap(f64::from(delay_ms) + delta_ms(dx, pps))
}
/// New duration after dragging a bar's right edge `dx` pixels. The bar shows all `repeats`
/// (auto-reverse doubles each), so the edge moves `factor` times as fast as one iteration.
pub fn dragged_duration(duration_ms: u32, dx: f32, pps: f32, factor: f64) -> u32 {
let factor = if factor.is_finite() && factor >= 1.0 { factor } else { 1.0 };
snap(f64::from(duration_ms) + delta_ms(dx, pps) / factor).max(MIN_DURATION_MS)
}
/// Tooltip text for a bar: `Start: 0.5s, End: 2.5s`.
pub fn label(bar: &Bar) -> String {
format!("Start: {:.2}s, End: {:.2}s", bar.start, bar.start + bar.span)
}
#[cfg(test)]
@@ -120,31 +109,4 @@ mod tests {
assert_eq!(b[1], None);
assert_eq!(b[2], Some(Bar { anim: 2, step: Some(1), start: 0.0, span: 0.0 }));
}
#[test]
fn ruler_and_scale() {
assert_eq!(ruler_seconds(&[]), 1);
assert_eq!(ruler_seconds(&bars(1, &[eff(0, 0, 1.2, 2.0)])), 4);
assert_eq!(pixels_per_second(200.0, 4), 50.0);
assert_eq!(pixels_per_second(10_000.0, 1), MAX_PPS);
assert_eq!(pixels_per_second(f32::NAN, 0), MIN_PPS);
}
#[test]
fn drags_snap_and_clamp() {
assert_eq!(dragged_delay(0, 25.0, 50.0), 500);
assert_eq!(dragged_delay(500, -100.0, 50.0), 0);
assert_eq!(dragged_delay(0, 13.0, 50.0), 250);
assert_eq!(dragged_delay(0, f32::INFINITY, 50.0), 0);
assert_eq!(dragged_delay(MAX_MS, 1.0e9, 1.0), MAX_MS);
assert_eq!(dragged_duration(500, 50.0, 50.0, 1.0), 1500);
assert_eq!(dragged_duration(500, 50.0, 50.0, 2.0), 1000);
assert_eq!(dragged_duration(500, -1000.0, 50.0, 1.0), MIN_DURATION_MS);
assert_eq!(dragged_duration(500, 0.0, 0.0, f64::NAN), 500);
}
#[test]
fn label_text() {
assert_eq!(label(&Bar { anim: 0, step: None, start: 0.5, span: 2.0 }), "Start: 0.50s, End: 2.50s");
}
}