Clips in timeline

This commit is contained in:
Skyler Lehmkuhl
2025-11-28 05:53:11 -05:00
parent 1cb2aabc9c
commit bbeb85b3a3
24 changed files with 3613 additions and 424 deletions
@@ -5,6 +5,7 @@ edition = "2021"
[dependencies]
lightningbeam-core = { path = "../lightningbeam-core" }
daw-backend = { path = "../../daw-backend" }
# UI Framework
eframe = { workspace = true }
@@ -266,6 +266,9 @@ struct EditorApp {
draw_simplify_mode: lightningbeam_core::tool::SimplifyMode, // Current simplification mode for draw tool
rdp_tolerance: f64, // RDP simplification tolerance (default: 10.0)
schneider_max_error: f64, // Schneider curve fitting max error (default: 30.0)
// Audio engine integration
audio_controller: Option<daw_backend::EngineController>, // Audio engine controller for playback
audio_event_rx: Option<rtrb::Consumer<daw_backend::AudioEvent>>, // Audio event receiver
}
impl EditorApp {
@@ -282,14 +285,14 @@ impl EditorApp {
// Add a test layer with a simple shape to visualize
use lightningbeam_core::layer::{AnyLayer, VectorLayer};
use lightningbeam_core::object::Object;
use lightningbeam_core::object::ShapeInstance;
use lightningbeam_core::shape::{Shape, ShapeColor};
use vello::kurbo::{Circle, Shape as KurboShape};
let circle = Circle::new((200.0, 150.0), 50.0);
let path = circle.to_path(0.1);
let shape = Shape::new(path).with_fill(ShapeColor::rgb(100, 150, 250));
let object = Object::new(shape.id);
let object = ShapeInstance::new(shape.id);
let mut vector_layer = VectorLayer::new("Layer 1");
vector_layer.add_shape(shape);
@@ -464,8 +467,17 @@ impl EditorApp {
// Layer menu
MenuAction::AddLayer => {
println!("Menu: Add Layer");
// TODO: Implement add layer
// Create a new vector layer with a default name
let layer_count = self.action_executor.document().root.children.len();
let layer_name = format!("Layer {}", layer_count + 1);
let action = lightningbeam_core::actions::AddLayerAction::new_vector(layer_name);
self.action_executor.execute(Box::new(action));
// Select the newly created layer (last child in the document)
if let Some(last_layer) = self.action_executor.document().root.children.last() {
self.active_layer_id = Some(last_layer.id());
}
}
MenuAction::AddVideoLayer => {
println!("Menu: Add Video Layer");
@@ -479,6 +491,65 @@ impl EditorApp {
println!("Menu: Add MIDI Track");
// TODO: Implement add MIDI track
}
MenuAction::AddTestClip => {
// Require an active layer
if let Some(layer_id) = self.active_layer_id {
// Create a test vector clip (5 second duration)
use lightningbeam_core::clip::{VectorClip, ClipInstance};
use lightningbeam_core::layer::{VectorLayer, AnyLayer};
use lightningbeam_core::shape::{Shape, ShapeColor};
use lightningbeam_core::object::ShapeInstance;
use kurbo::{Circle, Rect, Shape as KurboShape};
let mut test_clip = VectorClip::new("Test Clip", 400.0, 400.0, 5.0);
// Create a layer with some shapes
let mut layer = VectorLayer::new("Test Layer");
// Create a red circle shape
let circle_path = Circle::new((100.0, 100.0), 50.0).to_path(0.1);
let mut circle_shape = Shape::new(circle_path);
circle_shape.fill_color = Some(ShapeColor::rgb(255, 0, 0));
let circle_id = circle_shape.id;
layer.add_shape(circle_shape);
// Create a blue rectangle shape
let rect_path = Rect::new(200.0, 50.0, 350.0, 150.0).to_path(0.1);
let mut rect_shape = Shape::new(rect_path);
rect_shape.fill_color = Some(ShapeColor::rgb(0, 0, 255));
let rect_id = rect_shape.id;
layer.add_shape(rect_shape);
// Add shape instances
layer.shape_instances.push(ShapeInstance::new(circle_id));
layer.shape_instances.push(ShapeInstance::new(rect_id));
// Add the layer to the clip
test_clip.layers.add_root(AnyLayer::Vector(layer));
// Add to document's clip library
let clip_id = self.action_executor.document_mut().add_vector_clip(test_clip);
// Create clip instance at current time
let current_time = self.action_executor.document().current_time;
let instance = ClipInstance::new(clip_id)
.with_timeline_start(current_time)
.with_name("Test Instance");
// Add to layer (only vector layers can have clip instances)
if let Some(layer) = self.action_executor.document_mut().get_layer_mut(&layer_id) {
use lightningbeam_core::layer::AnyLayer;
if let AnyLayer::Vector(vector_layer) = layer {
vector_layer.clip_instances.push(instance);
println!("Added test clip instance with red circle and blue rectangle at time {}", current_time);
} else {
println!("Can only add clip instances to vector layers");
}
}
} else {
println!("No active layer selected");
}
}
MenuAction::DeleteLayer => {
println!("Menu: Delete Layer");
// TODO: Implement delete layer
@@ -678,7 +749,7 @@ impl eframe::App for EditorApp {
&self.theme,
&mut self.action_executor,
&mut self.selection,
&self.active_layer_id,
&mut self.active_layer_id,
&mut self.tool_state,
&mut pending_actions,
&mut self.draw_simplify_mode,
@@ -769,7 +840,7 @@ fn render_layout_node(
theme: &Theme,
action_executor: &mut lightningbeam_core::action::ActionExecutor,
selection: &mut lightningbeam_core::selection::Selection,
active_layer_id: &Option<Uuid>,
active_layer_id: &mut Option<Uuid>,
tool_state: &mut lightningbeam_core::tool::ToolState,
pending_actions: &mut Vec<Box<dyn lightningbeam_core::action::Action>>,
draw_simplify_mode: &mut lightningbeam_core::tool::SimplifyMode,
@@ -1121,7 +1192,7 @@ fn render_pane(
theme: &Theme,
action_executor: &mut lightningbeam_core::action::ActionExecutor,
selection: &mut lightningbeam_core::selection::Selection,
active_layer_id: &Option<Uuid>,
active_layer_id: &mut Option<Uuid>,
tool_state: &mut lightningbeam_core::tool::ToolState,
pending_actions: &mut Vec<Box<dyn lightningbeam_core::action::Action>>,
draw_simplify_mode: &mut lightningbeam_core::tool::SimplifyMode,
@@ -164,6 +164,7 @@ pub enum MenuAction {
AddVideoLayer,
AddAudioTrack,
AddMidiTrack,
AddTestClip, // For testing: adds a test clip instance to the current layer
DeleteLayer,
ToggleLayerVisibility,
@@ -254,6 +255,7 @@ impl MenuItemDef {
const ADD_VIDEO_LAYER: Self = Self { label: "Add Video Layer", action: MenuAction::AddVideoLayer, shortcut: None };
const ADD_AUDIO_TRACK: Self = Self { label: "Add Audio Track", action: MenuAction::AddAudioTrack, shortcut: None };
const ADD_MIDI_TRACK: Self = Self { label: "Add MIDI Track", action: MenuAction::AddMidiTrack, shortcut: None };
const ADD_TEST_CLIP: Self = Self { label: "Add Test Clip", action: MenuAction::AddTestClip, shortcut: None };
const DELETE_LAYER: Self = Self { label: "Delete Layer", action: MenuAction::DeleteLayer, shortcut: None };
const TOGGLE_LAYER_VISIBILITY: Self = Self { label: "Hide/Show Layer", action: MenuAction::ToggleLayerVisibility, shortcut: None };
@@ -364,6 +366,8 @@ impl MenuItemDef {
MenuDef::Item(&Self::ADD_AUDIO_TRACK),
MenuDef::Item(&Self::ADD_MIDI_TRACK),
MenuDef::Separator,
MenuDef::Item(&Self::ADD_TEST_CLIP),
MenuDef::Separator,
MenuDef::Item(&Self::DELETE_LAYER),
MenuDef::Item(&Self::TOGGLE_LAYER_VISIBILITY),
],
@@ -64,7 +64,7 @@ pub struct SharedPaneState<'a> {
/// Current selection state (mutable for tools to modify)
pub selection: &'a mut lightningbeam_core::selection::Selection,
/// Currently active layer ID
pub active_layer_id: &'a Option<uuid::Uuid>,
pub active_layer_id: &'a mut Option<uuid::Uuid>,
/// Current tool interaction state (mutable for tools to modify)
pub tool_state: &'a mut lightningbeam_core::tool::ToolState,
/// Actions to execute after rendering completes (two-phase dispatch)
@@ -332,7 +332,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
// 1. Draw selection outlines around selected objects
// NOTE: Skip this if Transform tool is active (it has its own handles)
if !self.selection.is_empty() && !matches!(self.selected_tool, Tool::Transform) {
for &object_id in self.selection.objects() {
for &object_id in self.selection.shape_instances() {
if let Some(object) = vector_layer.get_object(&object_id) {
if let Some(shape) = vector_layer.get_shape(&object.shape_id) {
// Get shape bounding box
@@ -385,6 +385,66 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
}
}
}
// Also draw selection outlines for clip instances
for &clip_id in self.selection.clip_instances() {
if let Some(clip_instance) = vector_layer.clip_instances.iter().find(|ci| ci.id == clip_id) {
// Get clip dimensions from document
let (width, height) = if let Some(vector_clip) = self.document.get_vector_clip(&clip_instance.clip_id) {
(vector_clip.width, vector_clip.height)
} else if let Some(video_clip) = self.document.get_video_clip(&clip_instance.clip_id) {
(video_clip.width, video_clip.height)
} else {
continue; // Clip not found or is audio
};
// Create bounding box from clip dimensions
let bbox = KurboRect::new(0.0, 0.0, width, height);
// Apply clip instance transform and camera transform
let clip_transform = clip_instance.transform.to_affine();
let combined_transform = camera_transform * clip_transform;
// Draw selection outline with different color for clip instances
let clip_selection_color = Color::rgb8(255, 120, 0); // Orange
scene.stroke(
&Stroke::new(stroke_width),
combined_transform,
clip_selection_color,
None,
&bbox,
);
// Draw corner handles (4 circles at corners)
let handle_radius = (6.0 / self.zoom.max(0.5) as f64).max(4.0);
let corners = [
(bbox.x0, bbox.y0),
(bbox.x1, bbox.y0),
(bbox.x1, bbox.y1),
(bbox.x0, bbox.y1),
];
for (x, y) in corners {
let corner_circle = Circle::new((x, y), handle_radius);
// Fill with orange
scene.fill(
Fill::NonZero,
combined_transform,
clip_selection_color,
None,
&corner_circle,
);
// White outline
scene.stroke(
&Stroke::new(1.0),
combined_transform,
Color::rgb8(255, 255, 255),
None,
&corner_circle,
);
}
}
}
}
// 2. Draw marquee selection rectangle
@@ -673,9 +733,9 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
// For single object: use object-aligned (rotated) bounding box
// For multiple objects: use axis-aligned bounding box (simpler for now)
if self.selection.objects().len() == 1 {
if self.selection.shape_instances().len() == 1 {
// Single object - draw rotated bounding box
let object_id = *self.selection.objects().iter().next().unwrap();
let object_id = *self.selection.shape_instances().iter().next().unwrap();
if let Some(object) = vector_layer.get_object(&object_id) {
if let Some(shape) = vector_layer.get_shape(&object.shape_id) {
@@ -863,7 +923,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
// Multiple objects - use axis-aligned bbox (existing code)
let mut combined_bbox: Option<KurboRect> = None;
for &object_id in self.selection.objects() {
for &object_id in self.selection.shape_instances() {
if let Some(object) = vector_layer.get_object(&object_id) {
if let Some(shape) = vector_layer.get_shape(&object.shape_id) {
let shape_bbox = shape.path().bounding_box();
@@ -1178,7 +1238,7 @@ impl StagePane {
None => return, // No active layer
};
let active_layer = match shared.action_executor.document().get_layer(active_layer_id) {
let active_layer = match shared.action_executor.document().get_layer(&active_layer_id) {
Some(layer) => layer,
None => return,
};
@@ -1194,38 +1254,92 @@ impl StagePane {
// Mouse down: start interaction (use drag_started for immediate feedback)
if response.drag_started() || response.clicked() {
// Hit test at click position
let hit = hit_test::hit_test_layer(vector_layer, point, 5.0, Affine::IDENTITY);
// Test clip instances first (they're on top of shapes)
let document = shared.action_executor.document();
let clip_hit = hit_test::hit_test_clip_instances(
&vector_layer.clip_instances,
&document.vector_clips,
&document.video_clips,
point,
Affine::IDENTITY,
);
if let Some(object_id) = hit {
// Object was hit
if shift_held {
// Shift: toggle selection
shared.selection.toggle_object(object_id);
} else {
// No shift: replace selection
if !shared.selection.contains_object(&object_id) {
shared.selection.select_only_object(object_id);
}
}
let hit_result = if let Some(clip_id) = clip_hit {
Some(hit_test::HitResult::ClipInstance(clip_id))
} else {
// No clip hit, test shape instances
hit_test::hit_test_layer(vector_layer, point, 5.0, Affine::IDENTITY)
.map(|id| hit_test::HitResult::ShapeInstance(id))
};
// If object is now selected, prepare for dragging
if shared.selection.contains_object(&object_id) {
// Store original positions of all selected objects
let mut original_positions = std::collections::HashMap::new();
for &obj_id in shared.selection.objects() {
if let Some(obj) = vector_layer.get_object(&obj_id) {
original_positions.insert(
obj_id,
Point::new(obj.transform.x, obj.transform.y),
);
if let Some(hit) = hit_result {
match hit {
hit_test::HitResult::ShapeInstance(object_id) => {
// Shape instance was hit
if shift_held {
// Shift: toggle selection
shared.selection.toggle_shape_instance(object_id);
} else {
// No shift: replace selection
if !shared.selection.contains_shape_instance(&object_id) {
shared.selection.select_only_shape_instance(object_id);
}
}
// If object is now selected, prepare for dragging
if shared.selection.contains_shape_instance(&object_id) {
// Store original positions of all selected objects
let mut original_positions = std::collections::HashMap::new();
for &obj_id in shared.selection.shape_instances() {
if let Some(obj) = vector_layer.get_object(&obj_id) {
original_positions.insert(
obj_id,
Point::new(obj.transform.x, obj.transform.y),
);
}
}
*shared.tool_state = ToolState::DraggingSelection {
start_pos: point,
start_mouse: point,
original_positions,
};
}
}
hit_test::HitResult::ClipInstance(clip_id) => {
// Clip instance was hit
if shift_held {
// Shift: toggle selection
shared.selection.toggle_clip_instance(clip_id);
} else {
// No shift: replace selection
if !shared.selection.contains_clip_instance(&clip_id) {
shared.selection.select_only_clip_instance(clip_id);
}
}
*shared.tool_state = ToolState::DraggingSelection {
start_pos: point,
start_mouse: point,
original_positions,
};
// If clip instance is now selected, prepare for dragging
if shared.selection.contains_clip_instance(&clip_id) {
// Store original positions of all selected clip instances
let mut original_positions = std::collections::HashMap::new();
for &clip_inst_id in shared.selection.clip_instances() {
// Find the clip instance in the layer
if let Some(clip_inst) = vector_layer.clip_instances.iter()
.find(|ci| ci.id == clip_inst_id) {
original_positions.insert(
clip_inst_id,
Point::new(clip_inst.transform.x, clip_inst.transform.y),
);
}
}
*shared.tool_state = ToolState::DraggingSelection {
start_pos: point,
start_mouse: point,
original_positions,
};
}
}
}
} else {
// Nothing hit - start marquee selection
@@ -1266,22 +1380,54 @@ impl StagePane {
let delta = point - start_mouse;
if delta.x.abs() > 0.01 || delta.y.abs() > 0.01 {
// Create move action with new positions
// Create move actions with new positions
use std::collections::HashMap;
let mut object_positions = HashMap::new();
for (object_id, original_pos) in original_positions {
// Separate shape instances from clip instances
use lightningbeam_core::object::Transform;
let mut shape_instance_positions = HashMap::new();
let mut clip_instance_transforms = HashMap::new();
for (id, original_pos) in original_positions {
let new_pos = Point::new(
original_pos.x + delta.x,
original_pos.y + delta.y,
);
object_positions.insert(object_id, (original_pos, new_pos));
// Check if this is a shape instance or clip instance
if shared.selection.contains_shape_instance(&id) {
shape_instance_positions.insert(id, (original_pos, new_pos));
} else if shared.selection.contains_clip_instance(&id) {
// For clip instances, we need to get the full Transform
// Find the clip instance in the layer
if let Some(clip_inst) = vector_layer.clip_instances.iter()
.find(|ci| ci.id == id) {
let mut old_transform = clip_inst.transform.clone();
old_transform.x = original_pos.x;
old_transform.y = original_pos.y;
let mut new_transform = clip_inst.transform.clone();
new_transform.x = new_pos.x;
new_transform.y = new_pos.y;
clip_instance_transforms.insert(id, (old_transform, new_transform));
}
}
}
// Create and submit the action
use lightningbeam_core::actions::MoveObjectsAction;
let action = MoveObjectsAction::new(*active_layer_id, object_positions);
shared.pending_actions.push(Box::new(action));
// Create and submit move action for shape instances
if !shape_instance_positions.is_empty() {
use lightningbeam_core::actions::MoveShapeInstancesAction;
let action = MoveShapeInstancesAction::new(*active_layer_id, shape_instance_positions);
shared.pending_actions.push(Box::new(action));
}
// Create and submit transform action for clip instances
if !clip_instance_transforms.is_empty() {
use lightningbeam_core::actions::TransformClipInstancesAction;
let action = TransformClipInstancesAction::new(*active_layer_id, clip_instance_transforms);
shared.pending_actions.push(Box::new(action));
}
}
// Reset tool state
@@ -1296,24 +1442,49 @@ impl StagePane {
let selection_rect = KurboRect::new(min_x, min_y, max_x, max_y);
// Hit test all objects in rectangle
let hits = hit_test::hit_test_objects_in_rect(
// Hit test clip instances in rectangle
let document = shared.action_executor.document();
let clip_hits = hit_test::hit_test_clip_instances_in_rect(
&vector_layer.clip_instances,
&document.vector_clips,
&document.video_clips,
selection_rect,
Affine::IDENTITY,
);
// Hit test shape instances in rectangle
let shape_hits = hit_test::hit_test_objects_in_rect(
vector_layer,
selection_rect,
Affine::IDENTITY,
);
// Add to selection
for obj_id in hits {
// Add clip instances to selection
for clip_id in clip_hits {
if shift_held {
shared.selection.add_object(obj_id);
shared.selection.add_clip_instance(clip_id);
} else {
// First hit replaces selection
if shared.selection.is_empty() {
shared.selection.add_object(obj_id);
shared.selection.add_clip_instance(clip_id);
} else {
// Subsequent hits add to selection
shared.selection.add_object(obj_id);
shared.selection.add_clip_instance(clip_id);
}
}
}
// Add shape instances to selection
for obj_id in shape_hits {
if shift_held {
shared.selection.add_shape_instance(obj_id);
} else {
// First hit replaces selection
if shared.selection.is_empty() {
shared.selection.add_shape_instance(obj_id);
} else {
// Subsequent hits add to selection
shared.selection.add_shape_instance(obj_id);
}
}
}
@@ -1340,12 +1511,12 @@ impl StagePane {
use vello::kurbo::Point;
// Check if we have an active vector layer
let active_layer_id = match shared.active_layer_id {
let active_layer_id = match *shared.active_layer_id {
Some(id) => id,
None => return,
};
let active_layer = match shared.action_executor.document().get_layer(active_layer_id) {
let active_layer = match shared.action_executor.document().get_layer(&active_layer_id) {
Some(layer) => layer,
None => return,
};
@@ -1428,7 +1599,7 @@ impl StagePane {
// Only create shape if rectangle has non-zero size
if width > 1.0 && height > 1.0 {
use lightningbeam_core::shape::{Shape, ShapeColor};
use lightningbeam_core::object::Object;
use lightningbeam_core::object::ShapeInstance;
use lightningbeam_core::actions::AddShapeAction;
// Create shape with rectangle path (built from lines)
@@ -1436,10 +1607,10 @@ impl StagePane {
let shape = Shape::new(path).with_fill(ShapeColor::from_egui(*shared.fill_color));
// Create object at the calculated position
let object = Object::new(shape.id).with_position(position.x, position.y);
let object = ShapeInstance::new(shape.id).with_position(position.x, position.y);
// Create and execute action immediately
let action = AddShapeAction::new(*active_layer_id, shape, object);
let action = AddShapeAction::new(active_layer_id, shape, object);
shared.action_executor.execute(Box::new(action));
// Clear tool state to stop preview rendering
@@ -1463,12 +1634,12 @@ impl StagePane {
use vello::kurbo::Point;
// Check if we have an active vector layer
let active_layer_id = match shared.active_layer_id {
let active_layer_id = match *shared.active_layer_id {
Some(id) => id,
None => return,
};
let active_layer = match shared.action_executor.document().get_layer(active_layer_id) {
let active_layer = match shared.action_executor.document().get_layer(&active_layer_id) {
Some(layer) => layer,
None => return,
};
@@ -1545,7 +1716,7 @@ impl StagePane {
// Only create shape if ellipse has non-zero size
if rx > 1.0 && ry > 1.0 {
use lightningbeam_core::shape::{Shape, ShapeColor};
use lightningbeam_core::object::Object;
use lightningbeam_core::object::ShapeInstance;
use lightningbeam_core::actions::AddShapeAction;
// Create shape with ellipse path (built from bezier curves)
@@ -1553,10 +1724,10 @@ impl StagePane {
let shape = Shape::new(path).with_fill(ShapeColor::from_egui(*shared.fill_color));
// Create object at the calculated position
let object = Object::new(shape.id).with_position(position.x, position.y);
let object = ShapeInstance::new(shape.id).with_position(position.x, position.y);
// Create and execute action immediately
let action = AddShapeAction::new(*active_layer_id, shape, object);
let action = AddShapeAction::new(active_layer_id, shape, object);
shared.action_executor.execute(Box::new(action));
// Clear tool state to stop preview rendering
@@ -1580,12 +1751,12 @@ impl StagePane {
use vello::kurbo::Point;
// Check if we have an active vector layer
let active_layer_id = match shared.active_layer_id {
let active_layer_id = match *shared.active_layer_id {
Some(id) => id,
None => return,
};
let active_layer = match shared.action_executor.document().get_layer(active_layer_id) {
let active_layer = match shared.action_executor.document().get_layer(&active_layer_id) {
Some(layer) => layer,
None => return,
};
@@ -1626,7 +1797,7 @@ impl StagePane {
// Only create shape if line has reasonable length
if length > 1.0 {
use lightningbeam_core::shape::{Shape, ShapeColor, StrokeStyle};
use lightningbeam_core::object::Object;
use lightningbeam_core::object::ShapeInstance;
use lightningbeam_core::actions::AddShapeAction;
// Create shape with line path
@@ -1643,10 +1814,10 @@ impl StagePane {
);
// Create object at the start point
let object = Object::new(shape.id).with_position(start_point.x, start_point.y);
let object = ShapeInstance::new(shape.id).with_position(start_point.x, start_point.y);
// Create and execute action immediately
let action = AddShapeAction::new(*active_layer_id, shape, object);
let action = AddShapeAction::new(active_layer_id, shape, object);
shared.action_executor.execute(Box::new(action));
// Clear tool state to stop preview rendering
@@ -1670,12 +1841,12 @@ impl StagePane {
use vello::kurbo::Point;
// Check if we have an active vector layer
let active_layer_id = match shared.active_layer_id {
let active_layer_id = match *shared.active_layer_id {
Some(id) => id,
None => return,
};
let active_layer = match shared.action_executor.document().get_layer(active_layer_id) {
let active_layer = match shared.action_executor.document().get_layer(&active_layer_id) {
Some(layer) => layer,
None => return,
};
@@ -1718,7 +1889,7 @@ impl StagePane {
// Only create shape if polygon has reasonable size
if radius > 5.0 {
use lightningbeam_core::shape::{Shape, ShapeColor};
use lightningbeam_core::object::Object;
use lightningbeam_core::object::ShapeInstance;
use lightningbeam_core::actions::AddShapeAction;
// Create shape with polygon path
@@ -1726,10 +1897,10 @@ impl StagePane {
let shape = Shape::new(path).with_fill(ShapeColor::from_egui(*shared.fill_color));
// Create object at the center point
let object = Object::new(shape.id).with_position(center.x, center.y);
let object = ShapeInstance::new(shape.id).with_position(center.x, center.y);
// Create and execute action immediately
let action = AddShapeAction::new(*active_layer_id, shape, object);
let action = AddShapeAction::new(active_layer_id, shape, object);
shared.action_executor.execute(Box::new(action));
// Clear tool state to stop preview rendering
@@ -1893,12 +2064,12 @@ impl StagePane {
use vello::kurbo::Point;
// Check if we have an active vector layer
let active_layer_id = match shared.active_layer_id {
let active_layer_id = match *shared.active_layer_id {
Some(id) => id,
None => return,
};
let active_layer = match shared.action_executor.document().get_layer(active_layer_id) {
let active_layer = match shared.action_executor.document().get_layer(&active_layer_id) {
Some(layer) => layer,
None => return,
};
@@ -1944,7 +2115,7 @@ impl StagePane {
simplify_rdp, fit_bezier_curves, RdpConfig, SchneiderConfig,
};
use lightningbeam_core::shape::{Shape, ShapeColor};
use lightningbeam_core::object::Object;
use lightningbeam_core::object::ShapeInstance;
use lightningbeam_core::actions::AddShapeAction;
// Convert points to the appropriate path based on simplify mode
@@ -2003,10 +2174,10 @@ impl StagePane {
);
// Create object at the calculated position
let object = Object::new(shape.id).with_position(position.x, position.y);
let object = ShapeInstance::new(shape.id).with_position(position.x, position.y);
// Create and execute action immediately
let action = AddShapeAction::new(*active_layer_id, shape, object);
let action = AddShapeAction::new(active_layer_id, shape, object);
shared.action_executor.execute(Box::new(action));
}
}
@@ -2037,7 +2208,7 @@ impl StagePane {
}
};
let active_layer = match shared.action_executor.document().get_layer(active_layer_id) {
let active_layer = match shared.action_executor.document().get_layer(&active_layer_id) {
Some(layer) => layer,
None => {
println!("Paint bucket: Layer not found");
@@ -2071,6 +2242,57 @@ impl StagePane {
}
}
/// Decompose an affine matrix into transform components
/// Returns (translation_x, translation_y, rotation_deg, scale_x, scale_y, skew_x_deg, skew_y_deg)
fn decompose_affine(affine: kurbo::Affine) -> (f64, f64, f64, f64, f64, f64, f64) {
let coeffs = affine.as_coeffs();
let a = coeffs[0];
let b = coeffs[1];
let c = coeffs[2];
let d = coeffs[3];
let e = coeffs[4]; // translation_x
let f = coeffs[5]; // translation_y
// Extract translation
let tx = e;
let ty = f;
// Decompose linear part [[a, c], [b, d]] into rotate * scale * skew
// Using QR-like decomposition
// Extract rotation
let rotation_rad = b.atan2(a);
let cos_r = rotation_rad.cos();
let sin_r = rotation_rad.sin();
// Remove rotation to get scale * skew
// R^(-1) * M where M = [[a, c], [b, d]]
let m11 = a * cos_r + b * sin_r;
let m12 = c * cos_r + d * sin_r;
let m21 = -a * sin_r + b * cos_r;
let m22 = -c * sin_r + d * cos_r;
// Now [[m11, m12], [m21, m22]] = scale * skew
// scale * skew = [[sx, 0], [0, sy]] * [[1, tan(skew_y)], [tan(skew_x), 1]]
// = [[sx, sx*tan(skew_y)], [sy*tan(skew_x), sy]]
let scale_x = m11;
let scale_y = m22;
let skew_x_rad = if scale_y.abs() > 0.001 { (m21 / scale_y).atan() } else { 0.0 };
let skew_y_rad = if scale_x.abs() > 0.001 { (m12 / scale_x).atan() } else { 0.0 };
(
tx,
ty,
rotation_rad.to_degrees(),
scale_x,
scale_y,
skew_x_rad.to_degrees(),
skew_y_rad.to_degrees(),
)
}
/// Apply transform preview to objects based on current mouse position
fn apply_transform_preview(
vector_layer: &mut lightningbeam_core::layer::VectorLayer,
@@ -2169,12 +2391,15 @@ impl StagePane {
}
TransformMode::ScaleEdge { axis, origin } => {
// Calculate scale along one axis
// UNIFIED MATRIX APPROACH: Calculate bounding box transform, then apply to each object
// Step 1: Calculate the bounding box transform (world-space scale from origin)
// Preserve sign to allow flipping when dragging past the origin
let (scale_x_world, scale_y_world) = match axis {
Axis::Horizontal => {
let start_dist = (start_mouse.x - origin.x).abs();
let current_dist = (current_mouse.x - origin.x).abs();
let scale = if start_dist > 0.001 {
let start_dist = start_mouse.x - origin.x;
let current_dist = current_mouse.x - origin.x;
let scale = if start_dist.abs() > 0.001 {
current_dist / start_dist
} else {
1.0
@@ -2182,9 +2407,9 @@ impl StagePane {
(scale, 1.0)
}
Axis::Vertical => {
let start_dist = (start_mouse.y - origin.y).abs();
let current_dist = (current_mouse.y - origin.y).abs();
let scale = if start_dist > 0.001 {
let start_dist = start_mouse.y - origin.y;
let current_dist = current_mouse.y - origin.y;
let scale = if start_dist.abs() > 0.001 {
current_dist / start_dist
} else {
1.0
@@ -2193,36 +2418,59 @@ impl StagePane {
}
};
// Apply scale to all selected objects
// Build the bounding box transform: translate to origin, scale, translate back
use kurbo::Affine;
let bbox_transform = Affine::translate((origin.x, origin.y))
* Affine::scale_non_uniform(scale_x_world, scale_y_world)
* Affine::translate((-origin.x, -origin.y));
// Step 2: Apply to each object using matrix composition
for (object_id, original_transform) in original_transforms {
// Get original opacity (now separate from transform)
let original_opacity = if let Some(obj) = vector_layer.get_object(object_id) {
obj.opacity
} else {
1.0
};
// New position: transform the object's position through bbox_transform
let new_pos = bbox_transform * kurbo::Point::new(original_transform.x, original_transform.y);
// Transform bbox operation to object's local space
// local_transform = R^(-1) * bbox_transform * R
let rotation = Affine::rotate(original_transform.rotation.to_radians());
let rotation_inv = Affine::rotate(-original_transform.rotation.to_radians());
// Extract just the linear part of bbox_transform (no translation)
let bbox_linear = Affine::scale_non_uniform(scale_x_world, scale_y_world);
// Transform to local space
let local_transform = rotation_inv * bbox_linear * rotation;
// Extract scale and skew directly from the 2x2 matrix
// Matrix form: [[a, c], [b, d]] = [[sx, sx*tan(ky)], [sy*tan(kx), sy]]
let coeffs = local_transform.as_coeffs();
let a = coeffs[0];
let b = coeffs[1];
let c = coeffs[2];
let d = coeffs[3];
// Direct extraction (no rotation assumed in local space)
let local_sx = a;
let local_sy = d;
let local_skew_x = if d.abs() > 0.001 { (b / d).atan().to_degrees() } else { 0.0 };
let local_skew_y = if a.abs() > 0.001 { (c / a).atan().to_degrees() } else { 0.0 };
// Apply to object
vector_layer.modify_object_internal(object_id, |obj| {
// Get object's rotation in radians
let rotation_rad = original_transform.rotation.to_radians();
let cos_r = rotation_rad.cos();
let sin_r = rotation_rad.sin();
// Transform scale from world space to local space (same as corner mode)
let cos_r_sq = cos_r * cos_r;
let sin_r_sq = sin_r * sin_r;
let sx_abs = scale_x_world.abs();
let sy_abs = scale_y_world.abs();
let local_scale_x = (cos_r_sq * sx_abs * sx_abs + sin_r_sq * sy_abs * sy_abs).sqrt();
let local_scale_y = (sin_r_sq * sx_abs * sx_abs + cos_r_sq * sy_abs * sy_abs).sqrt();
// Scale position relative to origin in world space
let rel_x = original_transform.x - origin.x;
let rel_y = original_transform.y - origin.y;
obj.transform.x = origin.x + rel_x * scale_x_world;
obj.transform.y = origin.y + rel_y * scale_y_world;
// Apply local-space scale
obj.transform.scale_x = original_transform.scale_x * local_scale_x;
obj.transform.scale_y = original_transform.scale_y * local_scale_y;
// Keep rotation unchanged
obj.transform.rotation = original_transform.rotation;
obj.transform.x = new_pos.x;
obj.transform.y = new_pos.y;
obj.transform.rotation = original_transform.rotation; // Preserve rotation
obj.transform.scale_x = original_transform.scale_x * local_sx;
obj.transform.scale_y = original_transform.scale_y * local_sy;
obj.transform.skew_x = original_transform.skew_x + local_skew_x;
obj.transform.skew_y = original_transform.skew_y + local_skew_y;
obj.opacity = original_opacity; // Preserve opacity (now separate from transform)
});
}
}
@@ -2492,14 +2740,14 @@ impl StagePane {
use vello::kurbo::Point;
// Check if we have an active vector layer
let active_layer_id = match shared.active_layer_id {
let active_layer_id = match *shared.active_layer_id {
Some(id) => id,
None => return,
};
// Only work on VectorLayer - just check type, don't hold reference
{
let active_layer = match shared.action_executor.document().get_layer(active_layer_id) {
let active_layer = match shared.action_executor.document().get_layer(&active_layer_id) {
Some(layer) => layer,
None => return,
};
@@ -2518,17 +2766,17 @@ impl StagePane {
// For single object: use rotated bounding box
// For multiple objects: use axis-aligned bounding box
if shared.selection.objects().len() == 1 {
if shared.selection.shape_instances().len() == 1 {
// Single object - rotated bounding box
self.handle_transform_single_object(ui, response, point, active_layer_id, shared);
self.handle_transform_single_object(ui, response, point, &active_layer_id, shared);
} else {
// Multiple objects - axis-aligned bounding box
// Calculate combined bounding box for handle hit testing
let mut combined_bbox: Option<vello::kurbo::Rect> = None;
// Get immutable reference just for bbox calculation
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(active_layer_id) {
for &object_id in shared.selection.objects() {
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(&active_layer_id) {
for &object_id in shared.selection.shape_instances() {
if let Some(object) = vector_layer.get_object(&object_id) {
if let Some(shape) = vector_layer.get_shape(&object.shape_id) {
// Get shape's local bounding box
@@ -2603,8 +2851,8 @@ impl StagePane {
use std::collections::HashMap;
let mut original_transforms = HashMap::new();
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(active_layer_id) {
for &object_id in shared.selection.objects() {
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(&active_layer_id) {
for &object_id in shared.selection.shape_instances() {
if let Some(object) = vector_layer.get_object(&object_id) {
original_transforms.insert(object_id, object.transform.clone());
}
@@ -2661,12 +2909,12 @@ impl StagePane {
if response.drag_stopped() || (ui.input(|i| i.pointer.any_released()) && matches!(shared.tool_state, ToolState::Transforming { .. })) {
if let ToolState::Transforming { original_transforms, .. } = shared.tool_state.clone() {
use std::collections::HashMap;
use lightningbeam_core::actions::TransformObjectsAction;
use lightningbeam_core::actions::TransformShapeInstancesAction;
let mut object_transforms = HashMap::new();
// Get current transforms and pair with originals
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(active_layer_id) {
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(&active_layer_id) {
for (object_id, original) in original_transforms {
if let Some(object) = vector_layer.get_object(&object_id) {
let new_transform = object.transform.clone();
@@ -2676,7 +2924,7 @@ impl StagePane {
}
if !object_transforms.is_empty() {
let action = TransformObjectsAction::new(*active_layer_id, object_transforms);
let action = TransformShapeInstancesAction::new(active_layer_id, object_transforms);
shared.pending_actions.push(Box::new(action));
}
@@ -2699,11 +2947,11 @@ impl StagePane {
use lightningbeam_core::layer::AnyLayer;
use vello::kurbo::Affine;
let object_id = *shared.selection.objects().iter().next().unwrap();
let object_id = *shared.selection.shape_instances().iter().next().unwrap();
// Calculate rotated bounding box corners
let (local_bbox, world_corners, obj_transform, object) = {
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(active_layer_id) {
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(&active_layer_id) {
if let Some(object) = vector_layer.get_object(&object_id) {
if let Some(shape) = vector_layer.get_shape(&object.shape_id) {
let local_bbox = shape.path().bounding_box();
@@ -3303,11 +3551,11 @@ impl StagePane {
if response.drag_stopped() || (ui.input(|i| i.pointer.any_released()) && matches!(shared.tool_state, ToolState::Transforming { .. })) {
if let ToolState::Transforming { original_transforms, .. } = shared.tool_state.clone() {
use std::collections::HashMap;
use lightningbeam_core::actions::TransformObjectsAction;
use lightningbeam_core::actions::TransformShapeInstancesAction;
let mut object_transforms = HashMap::new();
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(active_layer_id) {
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(&active_layer_id) {
for (obj_id, original) in original_transforms {
if let Some(object) = vector_layer.get_object(&obj_id) {
object_transforms.insert(obj_id, (original, object.transform.clone()));
@@ -3316,7 +3564,7 @@ impl StagePane {
}
if !object_transforms.is_empty() {
let action = TransformObjectsAction::new(*active_layer_id, object_transforms);
let action = TransformShapeInstancesAction::new(*active_layer_id, object_transforms);
shared.pending_actions.push(Box::new(action));
}
@@ -3356,8 +3604,8 @@ impl StagePane {
object_positions.insert(object_id, (original_pos, new_pos));
}
use lightningbeam_core::actions::MoveObjectsAction;
let action = MoveObjectsAction::new(*active_layer_id, object_positions);
use lightningbeam_core::actions::MoveShapeInstancesAction;
let action = MoveShapeInstancesAction::new(*active_layer_id, object_positions);
shared.pending_actions.push(Box::new(action));
}
}
@@ -3372,7 +3620,7 @@ impl StagePane {
use lightningbeam_core::hit_test;
use vello::kurbo::{Rect as KurboRect, Affine};
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(active_layer_id) {
if let Some(AnyLayer::Vector(vector_layer)) = shared.action_executor.document().get_layer(&active_layer_id) {
// Create selection rectangle
let min_x = start.x.min(current.x);
let min_y = start.y.min(current.y);
@@ -3390,7 +3638,7 @@ impl StagePane {
// Add to selection
for obj_id in hits {
shared.selection.add_object(obj_id);
shared.selection.add_shape_instance(obj_id);
}
}
}
@@ -14,6 +14,15 @@ const LAYER_HEIGHT: f32 = 60.0;
const LAYER_HEADER_WIDTH: f32 = 200.0;
const MIN_PIXELS_PER_SECOND: f32 = 20.0;
const MAX_PIXELS_PER_SECOND: f32 = 500.0;
const EDGE_DETECTION_PIXELS: f32 = 8.0; // Distance from edge to detect trim handles
/// Type of clip drag operation
#[derive(Debug, Clone, Copy, PartialEq)]
enum ClipDragType {
Move,
TrimLeft,
TrimRight,
}
pub struct TimelinePane {
/// Current playback time in seconds
@@ -38,11 +47,15 @@ pub struct TimelinePane {
is_panning: bool,
last_pan_pos: Option<egui::Pos2>,
/// Clip drag state (None if not dragging)
clip_drag_state: Option<ClipDragType>,
drag_offset: f64, // Time offset being applied during drag (for preview)
/// Cached mouse position from mousedown (used for edge detection when drag starts)
mousedown_pos: Option<egui::Pos2>,
/// Is playback currently active?
is_playing: bool,
/// Currently selected/active layer index
active_layer: usize,
}
impl TimelinePane {
@@ -51,12 +64,14 @@ impl TimelinePane {
current_time: 0.0,
pixels_per_second: 100.0,
viewport_start_time: 0.0,
active_layer: 0,
viewport_scroll_y: 0.0,
duration: 10.0, // Default 10 seconds
is_scrubbing: false,
is_panning: false,
last_pan_pos: None,
clip_drag_state: None,
drag_offset: 0.0,
mousedown_pos: None,
is_playing: false,
}
}
@@ -74,6 +89,83 @@ impl TimelinePane {
}
}
/// Detect which clip is under the pointer and what type of drag would occur
///
/// Returns (drag_type, clip_id) if pointer is over a clip, None otherwise
fn detect_clip_at_pointer(
&self,
pointer_pos: egui::Pos2,
document: &lightningbeam_core::document::Document,
content_rect: egui::Rect,
header_rect: egui::Rect,
) -> Option<(ClipDragType, uuid::Uuid)> {
let layer_count = document.root.children.len();
// Check if pointer is in valid area
if pointer_pos.y < header_rect.min.y {
return None;
}
if pointer_pos.x < content_rect.min.x {
return None;
}
let hover_time = self.x_to_time(pointer_pos.x - content_rect.min.x);
let relative_y = pointer_pos.y - header_rect.min.y + self.viewport_scroll_y;
let hovered_layer_index = (relative_y / LAYER_HEIGHT) as usize;
if hovered_layer_index >= layer_count {
return None;
}
let layers: Vec<_> = document.root.children.iter().rev().collect();
let layer = layers.get(hovered_layer_index)?;
let layer_data = layer.layer();
let clip_instances = match layer {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
};
// Check each clip instance
for clip_instance in clip_instances {
let clip_duration = match layer {
lightningbeam_core::layer::AnyLayer::Vector(_) => {
document.get_vector_clip(&clip_instance.clip_id).map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Audio(_) => {
document.get_audio_clip(&clip_instance.clip_id).map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Video(_) => {
document.get_video_clip(&clip_instance.clip_id).map(|c| c.duration)
}
}?;
let instance_duration = clip_instance.effective_duration(clip_duration);
let instance_start = clip_instance.timeline_start;
let instance_end = instance_start + instance_duration;
if hover_time >= instance_start && hover_time <= instance_end {
let start_x = self.time_to_x(instance_start);
let end_x = self.time_to_x(instance_end);
let mouse_x = pointer_pos.x - content_rect.min.x;
// Determine drag type based on edge proximity (check both sides of edge)
let drag_type = if (mouse_x - start_x).abs() <= EDGE_DETECTION_PIXELS {
ClipDragType::TrimLeft
} else if (end_x - mouse_x).abs() <= EDGE_DETECTION_PIXELS {
ClipDragType::TrimRight
} else {
ClipDragType::Move
};
return Some((drag_type, clip_instance.id));
}
}
None
}
/// Zoom in by a fixed increment
pub fn zoom_in(&mut self, center_x: f32) {
self.apply_zoom_at_point(0.2, center_x);
@@ -243,7 +335,14 @@ impl TimelinePane {
}
/// Render layer header column (left side with track names and controls)
fn render_layer_headers(&self, ui: &mut egui::Ui, rect: egui::Rect, theme: &crate::theme::Theme) {
fn render_layer_headers(
&self,
ui: &mut egui::Ui,
rect: egui::Rect,
theme: &crate::theme::Theme,
document: &lightningbeam_core::document::Document,
active_layer_id: &Option<uuid::Uuid>,
) {
let painter = ui.painter();
// Background for header column
@@ -264,9 +363,10 @@ impl TimelinePane {
// Get text color from theme
let text_style = theme.style(".text-primary", ui.ctx());
let text_color = text_style.text_color.unwrap_or(egui::Color32::from_gray(200));
let secondary_text_color = egui::Color32::from_gray(150);
// Test: Draw 3 layer headers
for i in 0..3 {
// Draw layer headers from document (reversed so newest layers appear on top)
for (i, layer) in document.root.children.iter().rev().enumerate() {
let y = rect.min.y + i as f32 * LAYER_HEIGHT - self.viewport_scroll_y;
// Skip if layer is outside visible area
@@ -280,7 +380,8 @@ impl TimelinePane {
);
// Active vs inactive background colors
let bg_color = if i == self.active_layer {
let is_active = active_layer_id.map_or(false, |id| id == layer.id());
let bg_color = if is_active {
active_color
} else {
inactive_color
@@ -288,15 +389,58 @@ impl TimelinePane {
painter.rect_filled(header_rect, 0.0, bg_color);
// Get layer info
let layer_data = layer.layer();
let layer_name = &layer_data.name;
let (layer_type, type_color) = match layer {
lightningbeam_core::layer::AnyLayer::Vector(_) => ("Vector", egui::Color32::from_rgb(100, 150, 255)), // Blue
lightningbeam_core::layer::AnyLayer::Audio(_) => ("Audio", egui::Color32::from_rgb(100, 255, 150)), // Green
lightningbeam_core::layer::AnyLayer::Video(_) => ("Video", egui::Color32::from_rgb(255, 150, 100)), // Orange
};
// Color indicator bar on the left edge
let indicator_rect = egui::Rect::from_min_size(
header_rect.min,
egui::vec2(4.0, LAYER_HEIGHT),
);
painter.rect_filled(indicator_rect, 0.0, type_color);
// Layer name
painter.text(
header_rect.min + egui::vec2(10.0, 10.0),
egui::Align2::LEFT_TOP,
format!("Layer {}", i + 1),
layer_name,
egui::FontId::proportional(14.0),
text_color,
);
// Layer type (smaller text below name with colored background)
let type_text_pos = header_rect.min + egui::vec2(10.0, 28.0);
let type_text_galley = painter.layout_no_wrap(
layer_type.to_string(),
egui::FontId::proportional(11.0),
secondary_text_color,
);
// Draw colored background for type label
let type_bg_rect = egui::Rect::from_min_size(
type_text_pos + egui::vec2(-2.0, -1.0),
egui::vec2(type_text_galley.size().x + 4.0, type_text_galley.size().y + 2.0),
);
painter.rect_filled(
type_bg_rect,
2.0,
egui::Color32::from_rgba_unmultiplied(type_color.r(), type_color.g(), type_color.b(), 60),
);
painter.text(
type_text_pos,
egui::Align2::LEFT_TOP,
layer_type,
egui::FontId::proportional(11.0),
secondary_text_color,
);
// Separator line at bottom
painter.line_segment(
[
@@ -318,7 +462,15 @@ impl TimelinePane {
}
/// Render layer rows (timeline content area)
fn render_layers(&self, ui: &mut egui::Ui, rect: egui::Rect, theme: &crate::theme::Theme) {
fn render_layers(
&self,
ui: &mut egui::Ui,
rect: egui::Rect,
theme: &crate::theme::Theme,
document: &lightningbeam_core::document::Document,
active_layer_id: &Option<uuid::Uuid>,
selection: &lightningbeam_core::selection::Selection,
) {
let painter = ui.painter();
// Theme colors for active/inactive layers
@@ -327,8 +479,8 @@ impl TimelinePane {
let active_color = active_style.background_color.unwrap_or(egui::Color32::from_rgb(85, 85, 85));
let inactive_color = inactive_style.background_color.unwrap_or(egui::Color32::from_rgb(136, 136, 136));
// Test: Draw 3 layer rows
for i in 0..3 {
// Draw layer rows from document (reversed so newest layers appear on top)
for (i, layer) in document.root.children.iter().rev().enumerate() {
let y = rect.min.y + i as f32 * LAYER_HEIGHT - self.viewport_scroll_y;
// Skip if layer is outside visible area
@@ -342,7 +494,8 @@ impl TimelinePane {
);
// Active vs inactive background colors
let bg_color = if i == self.active_layer {
let is_active = active_layer_id.map_or(false, |id| id == layer.id());
let bg_color = if is_active {
active_color
} else {
inactive_color
@@ -372,6 +525,141 @@ impl TimelinePane {
time += interval;
}
// Draw clip instances for this layer
let clip_instances = match layer {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
};
for clip_instance in clip_instances {
// Get the clip to determine duration
let clip_duration = match layer {
lightningbeam_core::layer::AnyLayer::Vector(_) => {
document.get_vector_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Audio(_) => {
document.get_audio_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Video(_) => {
document.get_video_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
};
if let Some(clip_duration) = clip_duration {
// Calculate effective duration accounting for trimming
let mut instance_duration = clip_instance.effective_duration(clip_duration);
// Instance positioned on the layer's timeline using timeline_start
// The layer itself has start_time, so the absolute timeline position is:
// layer.start_time + instance.timeline_start
let layer_data = layer.layer();
let mut instance_start = clip_instance.timeline_start;
// Apply drag offset preview for selected clips
let is_selected = selection.contains_clip_instance(&clip_instance.id);
if let Some(drag_type) = self.clip_drag_state {
if is_selected {
match drag_type {
ClipDragType::Move => {
// Move: shift the entire clip along the timeline
instance_start += self.drag_offset;
}
ClipDragType::TrimLeft => {
// Trim left: calculate new trim_start and clamp to valid range
let new_trim_start = (clip_instance.trim_start + self.drag_offset)
.max(0.0)
.min(clip_duration);
let actual_offset = new_trim_start - clip_instance.trim_start;
// Move start and reduce duration by actual clamped offset
instance_start = (clip_instance.timeline_start + actual_offset)
.max(0.0);
instance_duration = (clip_duration - new_trim_start).max(0.0);
// Adjust for existing trim_end
if let Some(trim_end) = clip_instance.trim_end {
instance_duration = (trim_end - new_trim_start).max(0.0);
}
}
ClipDragType::TrimRight => {
// Trim right: extend or reduce duration, clamped to available content
let max_duration = clip_duration - clip_instance.trim_start;
instance_duration = (instance_duration + self.drag_offset)
.max(0.0)
.min(max_duration);
}
}
}
}
let instance_end = instance_start + instance_duration;
let start_x = self.time_to_x(instance_start);
let end_x = self.time_to_x(instance_end);
// Only draw if any part is visible in viewport
if end_x >= 0.0 && start_x <= rect.width() {
let visible_start_x = start_x.max(0.0);
let visible_end_x = end_x.min(rect.width());
// Choose color based on layer type
let (clip_color, bright_color) = match layer {
lightningbeam_core::layer::AnyLayer::Vector(_) => (
egui::Color32::from_rgb(100, 150, 255), // Blue
egui::Color32::from_rgb(150, 200, 255), // Bright blue
),
lightningbeam_core::layer::AnyLayer::Audio(_) => (
egui::Color32::from_rgb(100, 255, 150), // Green
egui::Color32::from_rgb(150, 255, 200), // Bright green
),
lightningbeam_core::layer::AnyLayer::Video(_) => (
egui::Color32::from_rgb(255, 150, 100), // Orange
egui::Color32::from_rgb(255, 200, 150), // Bright orange
),
};
let clip_rect = egui::Rect::from_min_max(
egui::pos2(rect.min.x + visible_start_x, y + 10.0),
egui::pos2(rect.min.x + visible_end_x, y + LAYER_HEIGHT - 10.0),
);
// Draw the clip instance
painter.rect_filled(
clip_rect,
3.0, // Rounded corners
clip_color,
);
// Draw border only if selected (brighter version of clip color)
if selection.contains_clip_instance(&clip_instance.id) {
painter.rect_stroke(
clip_rect,
3.0,
egui::Stroke::new(3.0, bright_color),
);
}
// Draw clip name if there's space
if let Some(name) = &clip_instance.name {
if clip_rect.width() > 50.0 {
painter.text(
clip_rect.min + egui::vec2(5.0, 5.0),
egui::Align2::LEFT_TOP,
name,
egui::FontId::proportional(11.0),
egui::Color32::WHITE,
);
}
}
}
}
}
// Separator line at bottom
painter.line_segment(
[
@@ -383,8 +671,20 @@ impl TimelinePane {
}
}
/// Handle mouse input for scrubbing, panning, and zooming
fn handle_input(&mut self, ui: &mut egui::Ui, full_timeline_rect: egui::Rect, ruler_rect: egui::Rect, content_rect: egui::Rect) {
/// Handle mouse input for scrubbing, panning, zooming, layer selection, and clip instance selection
fn handle_input(
&mut self,
ui: &mut egui::Ui,
full_timeline_rect: egui::Rect,
ruler_rect: egui::Rect,
content_rect: egui::Rect,
header_rect: egui::Rect,
layer_count: usize,
document: &lightningbeam_core::document::Document,
active_layer_id: &mut Option<uuid::Uuid>,
selection: &mut lightningbeam_core::selection::Selection,
pending_actions: &mut Vec<Box<dyn lightningbeam_core::action::Action>>,
) {
let response = ui.allocate_rect(full_timeline_rect, egui::Sense::click_and_drag());
// Only process input if mouse is over the timeline pane
@@ -397,34 +697,358 @@ impl TimelinePane {
let alt_held = ui.input(|i| i.modifiers.alt);
let ctrl_held = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
let shift_held = ui.input(|i| i.modifiers.shift);
// Handle clip instance selection by clicking on clip rectangles
let mut clicked_clip_instance = false;
if response.clicked() && !alt_held {
if let Some(pos) = response.interact_pointer_pos() {
// Check if click is in content area (not ruler or header column)
if pos.y >= header_rect.min.y && pos.x >= content_rect.min.x {
let relative_y = pos.y - header_rect.min.y + self.viewport_scroll_y;
let clicked_layer_index = (relative_y / LAYER_HEIGHT) as usize;
let click_time = self.x_to_time(pos.x - content_rect.min.x);
// Get the layer at this index (accounting for reversed display order)
if clicked_layer_index < layer_count {
let layers: Vec<_> = document.root.children.iter().rev().collect();
if let Some(layer) = layers.get(clicked_layer_index) {
let layer_data = layer.layer();
// Get clip instances for this layer
let clip_instances = match layer {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
};
// Check if click is within any clip instance
for clip_instance in clip_instances {
// Get the clip to determine duration
let clip_duration = match layer {
lightningbeam_core::layer::AnyLayer::Vector(_) => {
document.get_vector_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Audio(_) => {
document.get_audio_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Video(_) => {
document.get_video_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
};
if let Some(clip_duration) = clip_duration {
let instance_duration = clip_instance.effective_duration(clip_duration);
let instance_start = clip_instance.timeline_start;
let instance_end = instance_start + instance_duration;
// Check if click is within this clip instance's time range
if click_time >= instance_start && click_time <= instance_end {
// Found a clicked clip instance!
if shift_held {
// Shift+click: add to selection
selection.add_clip_instance(clip_instance.id);
} else {
// Regular click: select only this clip
selection.select_only_clip_instance(clip_instance.id);
}
clicked_clip_instance = true;
break;
}
}
}
}
}
}
}
}
// Cache mouse position on mousedown (before any dragging)
if response.hovered() && ui.input(|i| i.pointer.button_pressed(egui::PointerButton::Primary)) {
if let Some(pos) = response.hover_pos() {
self.mousedown_pos = Some(pos);
}
}
// Handle clip dragging (only if not panning or scrubbing)
if !alt_held && !self.is_scrubbing && !self.is_panning {
if response.drag_started() {
// Use cached mousedown position for edge detection
if let Some(mousedown_pos) = self.mousedown_pos {
if let Some((drag_type, clip_id)) = self.detect_clip_at_pointer(
mousedown_pos,
document,
content_rect,
header_rect,
) {
// If this clip is not selected, select it (respecting shift key)
if !selection.contains_clip_instance(&clip_id) {
if shift_held {
selection.add_clip_instance(clip_id);
} else {
selection.select_only_clip_instance(clip_id);
}
}
// Start dragging with the detected drag type
self.clip_drag_state = Some(drag_type);
self.drag_offset = 0.0;
}
}
}
// Update drag offset during drag
if self.clip_drag_state.is_some() && response.dragged() {
let drag_delta = response.drag_delta();
let time_delta = drag_delta.x / self.pixels_per_second;
self.drag_offset += time_delta as f64;
}
// End drag - create action based on drag type
if let Some(drag_type) = self.clip_drag_state {
if response.drag_stopped() {
// Build layer_moves map for the action
use std::collections::HashMap;
let mut layer_moves: HashMap<uuid::Uuid, Vec<(uuid::Uuid, f64, f64)>> =
HashMap::new();
// Iterate through all layers to find selected clip instances
for layer in &document.root.children {
let layer_id = layer.id();
// Get clip instances for this layer
let clip_instances = match layer {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
};
// Find selected clip instances in this layer
for clip_instance in clip_instances {
if selection.contains_clip_instance(&clip_instance.id) {
let old_timeline_start = clip_instance.timeline_start;
let new_timeline_start = old_timeline_start + self.drag_offset;
// Add to layer_moves
layer_moves
.entry(layer_id)
.or_insert_with(Vec::new)
.push((clip_instance.id, old_timeline_start, new_timeline_start));
}
}
}
// Create and add the action based on drag type
match drag_type {
ClipDragType::Move => {
if !layer_moves.is_empty() {
let action = Box::new(
lightningbeam_core::actions::MoveClipInstancesAction::new(
layer_moves,
),
);
pending_actions.push(action);
}
}
ClipDragType::TrimLeft | ClipDragType::TrimRight => {
// Build layer_trims map for trim action
let mut layer_trims: HashMap<
uuid::Uuid,
Vec<(
uuid::Uuid,
lightningbeam_core::actions::TrimType,
lightningbeam_core::actions::TrimData,
lightningbeam_core::actions::TrimData,
)>,
> = HashMap::new();
// Iterate through all layers to find selected clip instances
for layer in &document.root.children {
let layer_id = layer.id();
let layer_data = layer.layer();
let clip_instances = match layer {
lightningbeam_core::layer::AnyLayer::Vector(vl) => {
&vl.clip_instances
}
lightningbeam_core::layer::AnyLayer::Audio(al) => {
&al.clip_instances
}
lightningbeam_core::layer::AnyLayer::Video(vl) => {
&vl.clip_instances
}
};
// Find selected clip instances in this layer
for clip_instance in clip_instances {
if selection.contains_clip_instance(&clip_instance.id) {
// Get clip duration to validate trim bounds
let clip_duration = match layer {
lightningbeam_core::layer::AnyLayer::Vector(_) => {
document
.get_vector_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Audio(_) => {
document
.get_audio_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Video(_) => {
document
.get_video_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
};
if let Some(clip_duration) = clip_duration {
match drag_type {
ClipDragType::TrimLeft => {
let old_trim_start = clip_instance.trim_start;
let old_timeline_start =
clip_instance.timeline_start;
// New trim_start is clamped to valid range
let new_trim_start = (old_trim_start
+ self.drag_offset)
.max(0.0)
.min(clip_duration);
// Calculate actual offset after clamping
let actual_offset = new_trim_start - old_trim_start;
let new_timeline_start =
old_timeline_start + actual_offset;
layer_trims
.entry(layer_id)
.or_insert_with(Vec::new)
.push((
clip_instance.id,
lightningbeam_core::actions::TrimType::TrimLeft,
lightningbeam_core::actions::TrimData::left(
old_trim_start,
old_timeline_start,
),
lightningbeam_core::actions::TrimData::left(
new_trim_start,
new_timeline_start,
),
));
}
ClipDragType::TrimRight => {
let old_trim_end = clip_instance.trim_end;
// Calculate new trim_end based on current duration
let current_duration =
clip_instance.effective_duration(clip_duration);
let new_duration =
(current_duration + self.drag_offset).max(0.0);
// Convert new duration back to trim_end value
let new_trim_end = if new_duration >= clip_duration {
None // Use full clip duration
} else {
Some((clip_instance.trim_start + new_duration).min(clip_duration))
};
layer_trims
.entry(layer_id)
.or_insert_with(Vec::new)
.push((
clip_instance.id,
lightningbeam_core::actions::TrimType::TrimRight,
lightningbeam_core::actions::TrimData::right(
old_trim_end,
),
lightningbeam_core::actions::TrimData::right(
new_trim_end,
),
));
}
_ => {}
}
}
}
}
}
// Create and add the trim action if there are any trims
if !layer_trims.is_empty() {
let action = Box::new(
lightningbeam_core::actions::TrimClipInstancesAction::new(
layer_trims,
),
);
pending_actions.push(action);
}
}
}
// Reset drag state
self.clip_drag_state = None;
self.drag_offset = 0.0;
self.mousedown_pos = None;
}
}
}
// Handle layer selection by clicking on layer header or content (only if no clip was clicked)
if response.clicked() && !alt_held && !clicked_clip_instance {
if let Some(pos) = response.interact_pointer_pos() {
// Check if click is in header or content area (not ruler)
if pos.y >= header_rect.min.y {
let relative_y = pos.y - header_rect.min.y + self.viewport_scroll_y;
let clicked_layer_index = (relative_y / LAYER_HEIGHT) as usize;
// Get the layer at this index (accounting for reversed display order)
if clicked_layer_index < layer_count {
let layers: Vec<_> = document.root.children.iter().rev().collect();
if let Some(layer) = layers.get(clicked_layer_index) {
*active_layer_id = Some(layer.id());
// Clear clip instance selection when clicking on empty layer area
if !shift_held {
selection.clear_clip_instances();
}
}
}
}
}
}
// Get mouse position relative to content area
let mouse_pos = response.hover_pos().unwrap_or(content_rect.center());
let mouse_x = (mouse_pos.x - content_rect.min.x).max(0.0);
// Calculate max vertical scroll based on number of layers
// TODO: Get actual layer count from document - for now using test count of 3
const TEST_LAYER_COUNT: usize = 3;
let total_content_height = TEST_LAYER_COUNT as f32 * LAYER_HEIGHT;
let total_content_height = layer_count as f32 * LAYER_HEIGHT;
let visible_height = content_rect.height();
let max_scroll_y = (total_content_height - visible_height).max(0.0);
// Scrubbing (clicking/dragging on ruler, but only when not panning)
if ruler_rect.contains(ui.input(|i| i.pointer.hover_pos().unwrap_or_default())) && !alt_held {
if response.clicked() || (response.dragged() && !self.is_panning) {
if let Some(pos) = response.interact_pointer_pos() {
let x = (pos.x - content_rect.min.x).max(0.0);
self.current_time = self.x_to_time(x).max(0.0).min(self.duration);
self.is_scrubbing = true;
}
} else if !response.dragged() {
self.is_scrubbing = false;
let cursor_over_ruler = ruler_rect.contains(ui.input(|i| i.pointer.hover_pos().unwrap_or_default()));
// Start scrubbing if cursor is over ruler and we click/drag
if cursor_over_ruler && !alt_held && (response.clicked() || (response.dragged() && !self.is_panning)) {
if let Some(pos) = response.interact_pointer_pos() {
let x = (pos.x - content_rect.min.x).max(0.0);
self.current_time = self.x_to_time(x).max(0.0);
self.is_scrubbing = true;
}
} else {
if !response.dragged() {
self.is_scrubbing = false;
}
// Continue scrubbing while dragging, even if cursor leaves ruler
else if self.is_scrubbing && response.dragged() && !self.is_panning {
if let Some(pos) = response.interact_pointer_pos() {
let x = (pos.x - content_rect.min.x).max(0.0);
self.current_time = self.x_to_time(x).max(0.0);
}
}
// Stop scrubbing when drag ends
else if !response.dragged() {
self.is_scrubbing = false;
}
// Distinguish between mouse wheel (discrete) and trackpad (smooth)
let mut handled = false;
@@ -492,6 +1116,29 @@ impl TimelinePane {
self.last_pan_pos = None;
}
}
// Update cursor based on hover position (only if not scrubbing or panning)
if !self.is_scrubbing && !self.is_panning {
// If dragging a clip with trim, keep the resize cursor
if let Some(drag_type) = self.clip_drag_state {
if drag_type != ClipDragType::Move {
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
}
} else if let Some(hover_pos) = response.hover_pos() {
// Not dragging - detect hover for cursor feedback
if let Some((drag_type, _clip_id)) = self.detect_clip_at_pointer(
hover_pos,
document,
content_rect,
header_rect,
) {
// Set cursor for trim operations
if drag_type != ClipDragType::Move {
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
}
}
}
}
}
}
@@ -558,6 +1205,48 @@ impl PaneRenderer for TimelinePane {
_path: &NodePath,
shared: &mut SharedPaneState,
) {
// Sync timeline's current_time to document
shared.action_executor.document_mut().current_time = self.current_time;
// Get document from action executor
let document = shared.action_executor.document();
let layer_count = document.root.children.len();
// Calculate project duration from last clip endpoint across all layers
let mut max_endpoint: f64 = 10.0; // Default minimum duration
for layer in &document.root.children {
let clip_instances = match layer {
lightningbeam_core::layer::AnyLayer::Vector(vl) => &vl.clip_instances,
lightningbeam_core::layer::AnyLayer::Audio(al) => &al.clip_instances,
lightningbeam_core::layer::AnyLayer::Video(vl) => &vl.clip_instances,
};
for clip_instance in clip_instances {
// Get clip duration
let clip_duration = match layer {
lightningbeam_core::layer::AnyLayer::Vector(_) => {
document.get_vector_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Audio(_) => {
document.get_audio_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
lightningbeam_core::layer::AnyLayer::Video(_) => {
document.get_video_clip(&clip_instance.clip_id)
.map(|c| c.duration)
}
};
if let Some(clip_duration) = clip_duration {
let instance_duration = clip_instance.effective_duration(clip_duration);
let instance_end = clip_instance.timeline_start + instance_duration;
max_endpoint = max_endpoint.max(instance_end);
}
}
}
self.duration = max_endpoint;
// Split into layer header column (left) and timeline content (right)
let header_column_rect = egui::Rect::from_min_size(
rect.min,
@@ -605,7 +1294,7 @@ impl PaneRenderer for TimelinePane {
// Render layer header column with clipping
ui.set_clip_rect(layer_headers_rect.intersect(original_clip_rect));
self.render_layer_headers(ui, layer_headers_rect, shared.theme);
self.render_layer_headers(ui, layer_headers_rect, shared.theme, document, shared.active_layer_id);
// Render time ruler (clip to ruler rect)
ui.set_clip_rect(ruler_rect.intersect(original_clip_rect));
@@ -613,7 +1302,7 @@ impl PaneRenderer for TimelinePane {
// Render layer rows with clipping
ui.set_clip_rect(content_rect.intersect(original_clip_rect));
self.render_layers(ui, content_rect, shared.theme);
self.render_layers(ui, content_rect, shared.theme, document, shared.active_layer_id, shared.selection);
// Render playhead on top (clip to timeline area)
ui.set_clip_rect(timeline_rect.intersect(original_clip_rect));
@@ -623,7 +1312,18 @@ impl PaneRenderer for TimelinePane {
ui.set_clip_rect(original_clip_rect);
// Handle input (use full rect including header column)
self.handle_input(ui, rect, ruler_rect, content_rect);
self.handle_input(
ui,
rect,
ruler_rect,
content_rect,
layer_headers_rect,
layer_count,
document,
shared.active_layer_id,
shared.selection,
shared.pending_actions,
);
// Register handler for pending view actions (two-phase dispatch)
// Priority: Mouse-over (0-99) > Fallback Timeline(1001)