Timeline: Project items land where they are dropped (#89)

A Project item (or Media Browser file) dropped in the Timeline always
went above the selected layer, starting where new layers start.

Now, as in After Effects, a line shows where it goes in the stack (above
the first layer row whose middle is below the pointer, else below the
last), and over the time graph a marker with a timecode tag shows its In
point, which follows the pointer (frame-snapped) or, with Shift, the
current time. The layer reorder drag shares the insertion logic.

layer.addItem and layer.newModel take `index` (1-based stack position);
mediaBrowser.import passes `time` and `index` on, one layer under the
other.

Tests: project_items_land_where_they_are_dropped_in_the_timeline
(ui_drag_drop.rs, real pointer drags: outline, time graph, Shift, below
the last layer) and add_item_at_a_stack_index_and_time (engine).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatastic
2026-10-07 02:18:38 +07:00
co-authored by Claude Opus 5.5
parent 9e619d2893
commit 1a0940d50a
6 changed files with 232 additions and 30 deletions
+59 -19
View File
@@ -805,6 +805,18 @@ fn key_drag_id() -> egui::Id {
egui::Id::new("tl-key-drag")
}
/// Set on the frame the reorder drag is released.
/// Where layers dropped at height `py` land among the visible layer rows: above the first row
/// whose middle is below it (its index in `layer_rows`), else below the last row. Returns that
/// and the y of the line that shows it (`top` without rows).
fn insertion(layer_rows: &[(Rect, LayerId)], py: f32, top: f32) -> (Option<usize>, f32) {
let at = layer_rows.iter().position(|(r, _)| py < r.center().y);
let y = match at {
Some(i) => layer_rows.get(i).map_or(top, |(r, _)| r.min.y),
None => layer_rows.last().map_or(top, |(r, _)| r.max.y),
};
(at, y)
}
fn layer_drop_id() -> egui::Id {
egui::Id::new("tl-layer-drop")
}
@@ -2130,11 +2142,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let dropped = ctx.data_mut(|d| d.remove_temp::<bool>(layer_drop_id())).unwrap_or(false);
let layer_rows: Vec<(Rect, LayerId)> = hit_rows.iter().filter(|(_, r)| matches!(r.kind, RowKind::Layer)).map(|(rr, r)| (*rr, r.layer)).collect();
if let Some(py) = ui.input(|i| i.pointer.interact_pos().or(i.pointer.latest_pos())).map(|p| p.y)
&& let Some(last) = layer_rows.last()
&& !layer_rows.is_empty()
{
// The first layer row whose middle is below the pointer: the layers go above it.
let at = layer_rows.iter().position(|(rr, _)| py < rr.center().y);
let line_y = at.map(|i| layer_rows[i].0.min.y).unwrap_or(last.0.max.y);
let (at, line_y) = insertion(&layer_rows, py, rows_rect.min.y);
let target = at.and_then(|i| layer_rows[i..].iter().find(|(_, l)| !moving.contains(&l.0)).map(|(_, l)| *l));
if dropped {
ctx.data_mut(|d| d.remove::<Vec<u64>>(layer_drag_id()));
@@ -2298,25 +2308,55 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mrows = rows_rect.intersect(Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max));
super::markers_ui::comp_markers(app, ui, &comp, tm, mstrip, mrows);
// Drop targets: footage/comps from the Project panel, effects from Effects & Presets.
// Drop targets: effects from Effects & Presets go on the layer under the pointer. Footage and
// comps from the Project panel and files from the Media Browser go where they are dropped: a
// line shows the place in the stack, and over the time graph a marker shows the In point too
// (Shift: at the current time), as in After Effects.
if let Some(payload) = egui::DragAndDrop::payload::<crate::panels::DragPayload>(&ctx)
&& !matches!(*payload, crate::panels::DragPayload::Property { .. })
&& ui.rect_contains_pointer(rows_rect)
&& let Some(ptr) = ctx.input(|i| i.pointer.hover_pos()).filter(|_| ui.rect_contains_pointer(rows_rect))
{
p.rect_stroke(rows_rect, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);
if ctx.input(|i| i.pointer.any_released()) {
let hover_y = ctx.input(|i| i.pointer.hover_pos()).map(|p| p.y).unwrap_or(0.0);
let target = hit_rows.iter().find(|(r, _)| hover_y >= r.min.y && hover_y < r.max.y).map(|(_, row)| row.layer);
match payload.as_ref() {
crate::panels::DragPayload::Item(id) => actions.push(("layer.addItem".into(), json!({"item": id}))),
crate::panels::DragPayload::Effect(e) => {
if let Some(l) = target {
actions.push(("effect.apply".into(), json!({"effect": e, "layers": [l.0]})));
}
}
crate::panels::DragPayload::Files(paths) => actions.push(("mediaBrowser.import".into(), json!({"paths": paths, "addToComp": true}))),
crate::panels::DragPayload::Property { .. } => {}
let released = ctx.input(|i| i.pointer.any_released());
if let crate::panels::DragPayload::Effect(e) = payload.as_ref() {
p.rect_stroke(rows_rect, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);
let target = hit_rows.iter().find(|(r, _)| ptr.y >= r.min.y && ptr.y < r.max.y).map(|(_, row)| row.layer);
if released && let Some(l) = target {
actions.push(("effect.apply".into(), json!({"effect": e, "layers": [l.0]})));
}
} else {
let layer_rows: Vec<(Rect, LayerId)> = hit_rows.iter().filter(|(_, r)| matches!(r.kind, RowKind::Layer)).map(|(rr, r)| (*rr, r.layer)).collect();
let (at, line_y) = insertion(&layer_rows, ptr.y, rows_rect.min.y);
let index = match at.and_then(|i| layer_rows.get(i)) {
Some((_, l)) => comp.index_of(*l).unwrap_or(1),
None => layer_rows.last().and_then(|(_, l)| comp.index_of(*l)).unwrap_or(comp.layers.len()) + 1,
};
let start = (ptr.x >= graph_x0 && !graph_on).then(|| {
let t = if ctx.input(|i| i.modifiers.shift) { time } else { Tick::from_seconds_f64(tm.t(ptr.x)) };
comp.frame_rate.snap_nearest(t).clamp(Tick::ZERO, comp.duration - comp.frame_duration())
});
let rp = p.with_clip_rect(rows_rect);
rp.line_segment([pos2(rect.min.x, line_y), pos2(rows_rect.max.x, line_y)], Stroke::new(2.0, t.accent));
if let Some(s) = start {
let x = tm.x(s.seconds());
rp.line_segment([pos2(x, rows_rect.min.y), pos2(x, rows_rect.max.y)], Stroke::new(1.0, t.accent));
// The In point's time in a tag beside the marker.
let g = rp.layout_no_wrap(super::timecode(&app.session, &comp, s), Tokens::ui(11.0), Color32::WHITE);
let tag = Align2::LEFT_BOTTOM.anchor_size(pos2(x + 4.0, line_y - 3.0), g.size());
rp.rect_filled(tag.expand(2.0), 2.0, t.accent);
rp.galley(tag.min, g, Color32::WHITE);
}
if released {
let (index, time) = (json!(index), json!(start.map(Tick::seconds)));
match payload.as_ref() {
crate::panels::DragPayload::Item(id) => actions.push(("layer.addItem".into(), json!({"item": id, "index": index, "time": time}))),
crate::panels::DragPayload::Files(paths) => {
actions.push(("mediaBrowser.import".into(), json!({"paths": paths, "addToComp": true, "index": index, "time": time})))
}
crate::panels::DragPayload::Effect(_) | crate::panels::DragPayload::Property { .. } => {}
}
}
}
if released {
egui::DragAndDrop::clear_payload(&ctx);
}
}
+99
View File
@@ -0,0 +1,99 @@
//! Dragging Project items into the Timeline (egui_kittest, real pointer drags): they land where
//! they are dropped, between layers and, over the time graph, starting there (#89).
use effectcraft_engine::Session;
use effectcraft_engine::time::Tick;
use effectcraft_ui_egui::EffectcraftApp;
use egui::{Event, Modifiers, Pos2, Rect, pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
/// Comp "Main" (4 s at 30 fps, current time 1 s) with solids Top, Middle and Bottom, and comp
/// "Clip" in the Project panel to drag in.
fn harness() -> (Harness<'static, EffectcraftApp>, u64) {
let mut s = Session::default();
let clip = s.execute("comp.new", json!({"name": "Clip", "width": 160, "height": 90, "frameRate": 30, "duration": 1})).unwrap()["comp"].as_u64().unwrap();
s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap();
for name in ["Bottom", "Middle", "Top"] {
s.execute("layer.newSolid", json!({"name": name, "color": "#406080"})).unwrap();
}
s.execute("time.set", json!({"time": 1.0})).unwrap();
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
(h, clip)
}
fn rect(h: &Harness<'_, EffectcraftApp>, id: &str) -> Rect {
let e = h.state().auto.find(id).unwrap_or_else(|| panic!("no {id}")).clone();
Rect::from_min_size(pos2(e.rect[0], e.rect[1]), vec2(e.rect[2], e.rect[3]))
}
/// Press on `from`, move to `to` in steps, release there (with `modifiers` held).
fn drag(h: &mut Harness<'_, EffectcraftApp>, from: Pos2, to: Pos2, modifiers: Modifiers) {
h.event(Event::PointerMoved(from));
h.step();
h.event(Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
h.event(Event::ModifiersChanged(modifiers));
for k in 1..=10 {
h.event(Event::PointerMoved(from + (to - from) * (k as f32 / 10.0)));
h.step();
}
h.event(Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers });
h.run_steps(3);
h.event(Event::ModifiersChanged(Modifiers::NONE));
h.step();
}
/// Layer names top to bottom, and the In point of `name`.
fn stack(h: &Harness<'_, EffectcraftApp>) -> Vec<String> {
h.state().session.active_comp().unwrap().layers.iter().map(|l| l.name.clone()).collect()
}
fn in_point(h: &Harness<'_, EffectcraftApp>, index: usize) -> f64 {
h.state().session.active_comp().unwrap().layers[index].in_point.seconds()
}
fn layer_id(h: &Harness<'_, EffectcraftApp>, name: &str) -> u64 {
h.state().session.active_comp().unwrap().layers.iter().find(|l| l.name == name).unwrap().id.0
}
/// #89: dropped on the layer outline, an item goes in between the layers there; over the time
/// graph it also starts where it was dropped, or at the current time with Shift.
#[test]
fn project_items_land_where_they_are_dropped_in_the_timeline() {
let (mut h, clip) = harness();
let item = rect(&h, &format!("project.item.{clip}.name")).center();
let frame = 1.0 / 30.0;
// Between Top and Middle in the outline: the lower half of Top's row.
let top = rect(&h, &format!("timeline.layer.{}.row", layer_id(&h, "Top")));
drag(&mut h, item, pos2(top.center().x, top.max.y - 2.0), Modifiers::NONE);
assert_eq!(stack(&h), ["Top", "Clip", "Middle", "Bottom"]);
// (Settings ▸ General ▸ Create Layers at Composition Start Time, on by default.)
assert_eq!(in_point(&h, 1), 0.0, "starts where new layers start");
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
h.run_steps(2);
// Over the time graph at 2 s, on the upper half of Bottom's row: above Bottom, starting at 2 s.
let bottom = layer_id(&h, "Bottom");
let row = rect(&h, &format!("timeline.layer.{bottom}.row"));
let bar = rect(&h, &format!("timeline.layer.{bottom}.bar"));
let at_2s = bar.min.x + bar.width() * 0.5;
drag(&mut h, item, pos2(at_2s, row.min.y + 2.0), Modifiers::NONE);
assert_eq!(stack(&h), ["Top", "Middle", "Clip", "Bottom"]);
assert!((in_point(&h, 2) - 2.0).abs() <= frame + 1e-9, "starts where it was dropped: {}", in_point(&h, 2));
assert_eq!(
Tick::from_seconds_f64(in_point(&h, 2)),
h.state().session.active_comp().unwrap().frame_rate.snap_nearest(Tick::from_seconds_f64(in_point(&h, 2))),
"on a frame"
);
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
h.run_steps(2);
// Shift: at the current time; below the last layer: at the bottom of the stack.
let row = rect(&h, &format!("timeline.layer.{bottom}.row"));
drag(&mut h, item, pos2(at_2s, row.max.y + 30.0), Modifiers::SHIFT);
assert_eq!(stack(&h), ["Top", "Middle", "Bottom", "Clip"]);
assert!((in_point(&h, 3) - 1.0).abs() < 1e-9, "Shift starts it at the current time");
}