Add layer controls, fix dragging for clips

This commit is contained in:
Skyler Lehmkuhl
2025-11-29 12:33:17 -05:00
parent 5fbb2c078b
commit f9761b8af3
7 changed files with 972 additions and 109 deletions
@@ -8,6 +8,7 @@ pub mod add_shape;
pub mod move_clip_instances;
pub mod move_objects;
pub mod paint_bucket;
pub mod set_layer_properties;
pub mod transform_clip_instances;
pub mod transform_objects;
pub mod trim_clip_instances;
@@ -17,6 +18,7 @@ pub use add_shape::AddShapeAction;
pub use move_clip_instances::MoveClipInstancesAction;
pub use move_objects::MoveShapeInstancesAction;
pub use paint_bucket::PaintBucketAction;
pub use set_layer_properties::{LayerProperty, SetLayerPropertiesAction};
pub use transform_clip_instances::TransformClipInstancesAction;
pub use transform_objects::TransformShapeInstancesAction;
pub use trim_clip_instances::{TrimClipInstancesAction, TrimData, TrimType};
@@ -0,0 +1,224 @@
//! Set layer properties action
//!
//! Handles changing layer properties (volume, mute, solo, lock, opacity, visible)
//! with undo/redo support.
use crate::action::Action;
use crate::document::Document;
use crate::layer::LayerTrait;
use uuid::Uuid;
/// Property that can be set on a layer
#[derive(Clone, Debug)]
pub enum LayerProperty {
Volume(f64),
Muted(bool),
Soloed(bool),
Locked(bool),
Opacity(f64),
Visible(bool),
}
/// Stored old value for rollback
#[derive(Clone, Debug)]
enum OldValue {
Volume(f64),
Muted(bool),
Soloed(bool),
Locked(bool),
Opacity(f64),
Visible(bool),
}
/// Action that sets a property on one or more layers
pub struct SetLayerPropertiesAction {
/// IDs of layers to modify
layer_ids: Vec<Uuid>,
/// Property to set
property: LayerProperty,
/// Old values for rollback (stored after first execution)
old_values: Vec<Option<OldValue>>,
}
impl SetLayerPropertiesAction {
/// Create a new action to set a property on a single layer
///
/// # Arguments
///
/// * `layer_id` - ID of the layer to modify
/// * `property` - Property to set
pub fn new(layer_id: Uuid, property: LayerProperty) -> Self {
Self {
layer_ids: vec![layer_id],
property,
old_values: vec![None],
}
}
/// Create a new action to set a property on multiple layers
///
/// # Arguments
///
/// * `layer_ids` - IDs of layers to modify
/// * `property` - Property to set on all layers
pub fn new_batch(layer_ids: Vec<Uuid>, property: LayerProperty) -> Self {
let old_values = vec![None; layer_ids.len()];
Self {
layer_ids,
property,
old_values,
}
}
}
impl Action for SetLayerPropertiesAction {
fn execute(&mut self, document: &mut Document) {
for (i, &layer_id) in self.layer_ids.iter().enumerate() {
// Find the layer in the document
if let Some(layer) = document.root_mut().get_child_mut(&layer_id) {
// Store old value if not already stored
if self.old_values[i].is_none() {
self.old_values[i] = Some(match &self.property {
LayerProperty::Volume(_) => OldValue::Volume(layer.volume()),
LayerProperty::Muted(_) => OldValue::Muted(layer.muted()),
LayerProperty::Soloed(_) => OldValue::Soloed(layer.soloed()),
LayerProperty::Locked(_) => OldValue::Locked(layer.locked()),
LayerProperty::Opacity(_) => OldValue::Opacity(layer.opacity()),
LayerProperty::Visible(_) => OldValue::Visible(layer.visible()),
});
}
// Set new value
match &self.property {
LayerProperty::Volume(v) => layer.set_volume(*v),
LayerProperty::Muted(m) => layer.set_muted(*m),
LayerProperty::Soloed(s) => layer.set_soloed(*s),
LayerProperty::Locked(l) => layer.set_locked(*l),
LayerProperty::Opacity(o) => layer.set_opacity(*o),
LayerProperty::Visible(v) => layer.set_visible(*v),
}
}
}
}
fn rollback(&mut self, document: &mut Document) {
for (i, &layer_id) in self.layer_ids.iter().enumerate() {
// Find the layer in the document
if let Some(layer) = document.root_mut().get_child_mut(&layer_id) {
// Restore old value if we have one
if let Some(old_value) = &self.old_values[i] {
match old_value {
OldValue::Volume(v) => layer.set_volume(*v),
OldValue::Muted(m) => layer.set_muted(*m),
OldValue::Soloed(s) => layer.set_soloed(*s),
OldValue::Locked(l) => layer.set_locked(*l),
OldValue::Opacity(o) => layer.set_opacity(*o),
OldValue::Visible(v) => layer.set_visible(*v),
}
}
}
}
}
fn description(&self) -> String {
let property_name = match &self.property {
LayerProperty::Volume(_) => "volume",
LayerProperty::Muted(_) => "mute",
LayerProperty::Soloed(_) => "solo",
LayerProperty::Locked(_) => "lock",
LayerProperty::Opacity(_) => "opacity",
LayerProperty::Visible(_) => "visibility",
};
if self.layer_ids.len() == 1 {
format!("Set layer {}", property_name)
} else {
format!("Set layer {} on {} layers", property_name, self.layer_ids.len())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layer::{AnyLayer, VectorLayer};
#[test]
fn test_set_volume() {
let mut document = Document::new("Test");
let layer = VectorLayer::new("Test Layer");
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Initial volume should be 1.0
let layer_ref = document.root().find_child(&layer_id).unwrap();
assert_eq!(layer_ref.volume(), 1.0);
// Create and execute action
let mut action = SetLayerPropertiesAction::new(layer_id, LayerProperty::Volume(0.5));
action.execute(&mut document);
// Verify volume changed
let layer_ref = document.root().find_child(&layer_id).unwrap();
assert_eq!(layer_ref.volume(), 0.5);
// Rollback
action.rollback(&mut document);
// Verify volume restored
let layer_ref = document.root().find_child(&layer_id).unwrap();
assert_eq!(layer_ref.volume(), 1.0);
}
#[test]
fn test_toggle_mute() {
let mut document = Document::new("Test");
let layer = VectorLayer::new("Test Layer");
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Initial state should be unmuted
let layer_ref = document.root().find_child(&layer_id).unwrap();
assert_eq!(layer_ref.muted(), false);
// Mute
let mut action = SetLayerPropertiesAction::new(layer_id, LayerProperty::Muted(true));
action.execute(&mut document);
let layer_ref = document.root().find_child(&layer_id).unwrap();
assert_eq!(layer_ref.muted(), true);
// Unmute via rollback
action.rollback(&mut document);
let layer_ref = document.root().find_child(&layer_id).unwrap();
assert_eq!(layer_ref.muted(), false);
}
#[test]
fn test_batch_solo() {
let mut document = Document::new("Test");
let layer1 = VectorLayer::new("Layer 1");
let layer2 = VectorLayer::new("Layer 2");
let id1 = document.root_mut().add_child(AnyLayer::Vector(layer1));
let id2 = document.root_mut().add_child(AnyLayer::Vector(layer2));
// Solo both layers
let mut action = SetLayerPropertiesAction::new_batch(
vec![id1, id2],
LayerProperty::Soloed(true),
);
action.execute(&mut document);
// Verify both soloed
assert_eq!(document.root().find_child(&id1).unwrap().soloed(), true);
assert_eq!(document.root().find_child(&id2).unwrap().soloed(), true);
// Rollback
action.rollback(&mut document);
// Verify both unsoloed
assert_eq!(document.root().find_child(&id1).unwrap().soloed(), false);
assert_eq!(document.root().find_child(&id2).unwrap().soloed(), false);
}
}
@@ -16,6 +16,7 @@ use crate::layer_tree::LayerTree;
use crate::object::Transform;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use vello::kurbo::{Rect, Affine, Shape as KurboShape};
/// Vector clip containing nested layers
///
@@ -73,6 +74,88 @@ impl VectorClip {
layers: LayerTree::new(),
}
}
/// Calculate the bounding box of all content in this clip at a specific time
///
/// This recursively calculates the union of all shape and nested clip bounding boxes
/// across all layers, evaluating animations at the specified clip-local time.
///
/// # Arguments
/// * `document` - The document containing all clip definitions (for resolving nested clips)
/// * `clip_time` - The time within this clip (already converted from timeline time)
///
/// # Returns
/// The bounding box of all visible content at the specified time
pub fn calculate_content_bounds(&self, document: &crate::document::Document, clip_time: f64) -> Rect {
let mut combined_bounds: Option<Rect> = None;
// Iterate through all layers in the layer tree
for layer_node in self.layers.iter() {
// Only process vector layers (skip other layer types)
if let AnyLayer::Vector(vector_layer) = &layer_node.data {
// Calculate bounds for all shape instances in this layer
for shape_instance in &vector_layer.shape_instances {
// Get the shape for this instance
if let Some(shape) = vector_layer.shapes.get(&shape_instance.shape_id) {
// Get the local bounding box of the shape's path
let local_bbox = shape.path().bounding_box();
// Apply the shape instance's transform (TODO: evaluate animations at clip_time)
let instance_transform = shape_instance.to_affine();
let transformed_bbox = instance_transform.transform_rect_bbox(local_bbox);
// Union with combined bounds
combined_bounds = Some(match combined_bounds {
None => transformed_bbox,
Some(existing) => existing.union(transformed_bbox),
});
}
}
// Handle nested clip instances recursively
for clip_instance in &vector_layer.clip_instances {
// Convert parent clip time to nested clip local time
// Apply timeline offset and playback speed, then add trim offset
let nested_clip_time = ((clip_time - clip_instance.timeline_start) * clip_instance.playback_speed) + clip_instance.trim_start;
// Look up the nested clip definition
let nested_bounds = if let Some(nested_clip) = document.get_vector_clip(&clip_instance.clip_id) {
// Recursively calculate bounds for nested clip at its local time
nested_clip.calculate_content_bounds(document, nested_clip_time)
} else if let Some(video_clip) = document.get_video_clip(&clip_instance.clip_id) {
// Video clips have fixed dimensions
Rect::new(0.0, 0.0, video_clip.width, video_clip.height)
} else {
// Clip not found or is audio (no spatial representation)
continue;
};
// Apply clip instance transform to the nested bounds
let instance_transform = clip_instance.transform.to_affine();
let transformed_bounds = instance_transform.transform_rect_bbox(nested_bounds);
// Union with combined bounds
combined_bounds = Some(match combined_bounds {
None => transformed_bounds,
Some(existing) => existing.union(transformed_bounds),
});
}
}
}
// If no content found, return a small rect at origin
combined_bounds.unwrap_or_else(|| Rect::new(0.0, 0.0, 1.0, 1.0))
}
/// Get the width of the content bounds at a specific time
pub fn content_width(&self, document: &crate::document::Document, clip_time: f64) -> f64 {
self.calculate_content_bounds(document, clip_time).width()
}
/// Get the height of the content bounds at a specific time
pub fn content_height(&self, document: &crate::document::Document, clip_time: f64) -> f64 {
self.calculate_content_bounds(document, clip_time).height()
}
}
/// Video clip referencing an external video file
@@ -203,7 +203,7 @@ pub fn hit_test_clip_instance(
point: Point,
parent_transform: Affine,
) -> bool {
// Create bounding rectangle for the clip
// Create bounding rectangle for the clip (top-left origin)
let clip_rect = Rect::new(0.0, 0.0, clip_width, clip_height);
// Combine parent transform with clip instance transform
@@ -242,39 +242,48 @@ pub fn get_clip_instance_bounds(
/// Hit test clip instances at a specific point
///
/// Tests clip instances in reverse order (front to back) and returns the first hit.
/// This function requires the clip libraries to look up clip dimensions.
/// Uses dynamic bounds calculation based on clip content and current time.
///
/// # Arguments
///
/// * `clip_instances` - The clip instances to test
/// * `vector_clips` - HashMap of vector clips for looking up dimensions
/// * `video_clips` - HashMap of video clips for looking up dimensions
/// * `document` - Document containing all clip definitions
/// * `point` - The point to test in screen/canvas space
/// * `parent_transform` - Transform from parent layer/clip
/// * `timeline_time` - Current timeline time for evaluating animations
///
/// # Returns
///
/// The UUID of the first clip instance hit, or None if no hit
pub fn hit_test_clip_instances(
clip_instances: &[ClipInstance],
vector_clips: &std::collections::HashMap<Uuid, VectorClip>,
video_clips: &std::collections::HashMap<Uuid, VideoClip>,
document: &crate::document::Document,
point: Point,
parent_transform: Affine,
timeline_time: f64,
) -> Option<Uuid> {
// Test in reverse order (front to back)
for clip_instance in clip_instances.iter().rev() {
// Try to get clip dimensions from either vector or video clips
let (width, height) = if let Some(vector_clip) = vector_clips.get(&clip_instance.clip_id) {
(vector_clip.width, vector_clip.height)
} else if let Some(video_clip) = video_clips.get(&clip_instance.clip_id) {
(video_clip.width, video_clip.height)
// Calculate clip-local time from timeline time
// Apply timeline offset and playback speed, then add trim offset
let clip_time = ((timeline_time - clip_instance.timeline_start) * clip_instance.playback_speed) + clip_instance.trim_start;
// Get dynamic clip bounds from content at this time
let content_bounds = if let Some(vector_clip) = document.get_vector_clip(&clip_instance.clip_id) {
vector_clip.calculate_content_bounds(document, clip_time)
} else if let Some(video_clip) = document.get_video_clip(&clip_instance.clip_id) {
Rect::new(0.0, 0.0, video_clip.width, video_clip.height)
} else {
// Clip not found or is audio (no spatial representation)
continue;
};
if hit_test_clip_instance(clip_instance, width, height, point, parent_transform) {
// Transform content bounds to screen space
let clip_transform = parent_transform * clip_instance.transform.to_affine();
let clip_bbox = clip_transform.transform_rect_bbox(content_bounds);
// Test if point is inside the transformed rectangle
if clip_bbox.contains(point) {
return Some(clip_instance.id);
}
}
@@ -285,40 +294,46 @@ pub fn hit_test_clip_instances(
/// Hit test clip instances within a rectangle (for marquee selection)
///
/// Returns all clip instances whose bounding boxes intersect with the given rectangle.
/// Uses dynamic bounds calculation based on clip content and current time.
///
/// # Arguments
///
/// * `clip_instances` - The clip instances to test
/// * `vector_clips` - HashMap of vector clips for looking up dimensions
/// * `video_clips` - HashMap of video clips for looking up dimensions
/// * `document` - Document containing all clip definitions
/// * `rect` - The selection rectangle in screen/canvas space
/// * `parent_transform` - Transform from parent layer/clip
/// * `timeline_time` - Current timeline time for evaluating animations
///
/// # Returns
///
/// Vector of UUIDs for all clip instances that intersect the rectangle
pub fn hit_test_clip_instances_in_rect(
clip_instances: &[ClipInstance],
vector_clips: &std::collections::HashMap<Uuid, VectorClip>,
video_clips: &std::collections::HashMap<Uuid, VideoClip>,
document: &crate::document::Document,
rect: Rect,
parent_transform: Affine,
timeline_time: f64,
) -> Vec<Uuid> {
let mut hits = Vec::new();
for clip_instance in clip_instances {
// Try to get clip dimensions from either vector or video clips
let (width, height) = if let Some(vector_clip) = vector_clips.get(&clip_instance.clip_id) {
(vector_clip.width, vector_clip.height)
} else if let Some(video_clip) = video_clips.get(&clip_instance.clip_id) {
(video_clip.width, video_clip.height)
// Calculate clip-local time from timeline time
// Apply timeline offset and playback speed, then add trim offset
let clip_time = ((timeline_time - clip_instance.timeline_start) * clip_instance.playback_speed) + clip_instance.trim_start;
// Get dynamic clip bounds from content at this time
let content_bounds = if let Some(vector_clip) = document.get_vector_clip(&clip_instance.clip_id) {
vector_clip.calculate_content_bounds(document, clip_time)
} else if let Some(video_clip) = document.get_video_clip(&clip_instance.clip_id) {
Rect::new(0.0, 0.0, video_clip.width, video_clip.height)
} else {
// Clip not found or is audio (no spatial representation)
continue;
};
// Get clip instance bounding box in screen space
let clip_bbox = get_clip_instance_bounds(clip_instance, width, height, parent_transform);
// Transform content bounds to screen space
let clip_transform = parent_transform * clip_instance.transform.to_affine();
let clip_bbox = clip_transform.transform_rect_bbox(content_bounds);
// Check if rectangles intersect
if rect.intersect(clip_bbox).area() > 0.0 {
@@ -4,7 +4,7 @@
use crate::animation::TransformProperty;
use crate::document::Document;
use crate::layer::{AnyLayer, VectorLayer};
use crate::layer::{AnyLayer, LayerTrait, VectorLayer};
use crate::object::ShapeInstance;
use kurbo::{Affine, Shape};
use vello::kurbo::Rect;
@@ -45,16 +45,30 @@ fn render_background(document: &Document, scene: &mut Scene, base_transform: Aff
/// Recursively render the root graphics object and its children
fn render_graphics_object(document: &Document, time: f64, scene: &mut Scene, base_transform: Affine) {
// Render all visible layers in the root graphics object
// Check if any layers are soloed
let any_soloed = document.visible_layers().any(|layer| layer.soloed());
// Render layers based on solo state
// If any layer is soloed, only render soloed layers
// Otherwise, render all visible layers
// Start with full opacity (1.0)
for layer in document.visible_layers() {
render_layer(document, time, layer, scene, base_transform);
if any_soloed {
// Only render soloed layers when solo is active
if layer.soloed() {
render_layer(document, time, layer, scene, base_transform, 1.0);
}
} else {
// Render all visible layers when no solo is active
render_layer(document, time, layer, scene, base_transform, 1.0);
}
}
}
/// Render a single layer
fn render_layer(document: &Document, time: f64, layer: &AnyLayer, scene: &mut Scene, base_transform: Affine) {
fn render_layer(document: &Document, time: f64, layer: &AnyLayer, scene: &mut Scene, base_transform: Affine, parent_opacity: f64) {
match layer {
AnyLayer::Vector(vector_layer) => render_vector_layer(document, time, vector_layer, scene, base_transform),
AnyLayer::Vector(vector_layer) => render_vector_layer(document, time, vector_layer, scene, base_transform, parent_opacity),
AnyLayer::Audio(_) => {
// Audio layers don't render visually
}
@@ -69,9 +83,10 @@ fn render_clip_instance(
document: &Document,
time: f64,
clip_instance: &crate::clip::ClipInstance,
_parent_opacity: f64,
parent_opacity: f64,
scene: &mut Scene,
base_transform: Affine,
animation_data: &crate::animation::AnimationData,
) {
// Try to find the clip in the document's clip libraries
// For now, only handle VectorClips (VideoClip and AudioClip rendering not yet implemented)
@@ -84,28 +99,134 @@ fn render_clip_instance(
return; // Clip instance not active at this time
};
// Build transform for this clip instance
let instance_transform = base_transform * clip_instance.to_affine();
// Evaluate animated transform properties
let transform = &clip_instance.transform;
let x = animation_data.eval(
&crate::animation::AnimationTarget::Object {
id: clip_instance.id,
property: TransformProperty::X,
},
time,
transform.x,
);
let y = animation_data.eval(
&crate::animation::AnimationTarget::Object {
id: clip_instance.id,
property: TransformProperty::Y,
},
time,
transform.y,
);
let rotation = animation_data.eval(
&crate::animation::AnimationTarget::Object {
id: clip_instance.id,
property: TransformProperty::Rotation,
},
time,
transform.rotation,
);
let scale_x = animation_data.eval(
&crate::animation::AnimationTarget::Object {
id: clip_instance.id,
property: TransformProperty::ScaleX,
},
time,
transform.scale_x,
);
let scale_y = animation_data.eval(
&crate::animation::AnimationTarget::Object {
id: clip_instance.id,
property: TransformProperty::ScaleY,
},
time,
transform.scale_y,
);
let skew_x = animation_data.eval(
&crate::animation::AnimationTarget::Object {
id: clip_instance.id,
property: TransformProperty::SkewX,
},
time,
transform.skew_x,
);
let skew_y = animation_data.eval(
&crate::animation::AnimationTarget::Object {
id: clip_instance.id,
property: TransformProperty::SkewY,
},
time,
transform.skew_y,
);
// TODO: Properly handle clip instance opacity by threading opacity through rendering pipeline
// Currently clip_instance.opacity is not being applied to nested layers
// Build transform matrix (similar to shape instances)
// For clip instances, we don't have a path to calculate center from,
// so we use the clip's center point (width/2, height/2)
let center_x = vector_clip.width / 2.0;
let center_y = vector_clip.height / 2.0;
// Build skew transforms (applied around clip center)
let skew_transform = if skew_x != 0.0 || skew_y != 0.0 {
let skew_x_affine = if skew_x != 0.0 {
let tan_skew = skew_x.to_radians().tan();
Affine::new([1.0, 0.0, tan_skew, 1.0, 0.0, 0.0])
} else {
Affine::IDENTITY
};
let skew_y_affine = if skew_y != 0.0 {
let tan_skew = skew_y.to_radians().tan();
Affine::new([1.0, tan_skew, 0.0, 1.0, 0.0, 0.0])
} else {
Affine::IDENTITY
};
// Skew around center: translate to origin, skew, translate back
Affine::translate((center_x, center_y))
* skew_x_affine
* skew_y_affine
* Affine::translate((-center_x, -center_y))
} else {
Affine::IDENTITY
};
let clip_transform = Affine::translate((x, y))
* Affine::rotate(rotation.to_radians())
* Affine::scale_non_uniform(scale_x, scale_y)
* skew_transform;
let instance_transform = base_transform * clip_transform;
// Evaluate animated opacity
let opacity = animation_data.eval(
&crate::animation::AnimationTarget::Object {
id: clip_instance.id,
property: TransformProperty::Opacity,
},
time,
clip_instance.opacity,
);
// Cascade opacity: parent_opacity × animated opacity
let clip_opacity = parent_opacity * opacity;
// Recursively render all root layers in the clip at the remapped time
for layer_node in vector_clip.layers.iter() {
// TODO: Filter by visibility and time range once LayerNode exposes that data
render_layer(document, clip_time, &layer_node.data, scene, instance_transform);
// Skip invisible layers for performance
if !layer_node.data.visible() {
continue;
}
render_layer(document, clip_time, &layer_node.data, scene, instance_transform, clip_opacity);
}
}
/// Render a vector layer with all its clip instances and shape instances
fn render_vector_layer(document: &Document, time: f64, layer: &VectorLayer, scene: &mut Scene, base_transform: Affine) {
fn render_vector_layer(document: &Document, time: f64, layer: &VectorLayer, scene: &mut Scene, base_transform: Affine, parent_opacity: f64) {
// Get layer-level opacity
let layer_opacity = layer.layer.opacity;
// Cascade opacity: parent_opacity × layer.opacity
let layer_opacity = parent_opacity * layer.layer.opacity;
// Render clip instances first (they appear under shape instances)
for clip_instance in &layer.clip_instances {
render_clip_instance(document, time, clip_instance, layer_opacity, scene, base_transform);
render_clip_instance(document, time, clip_instance, layer_opacity, scene, base_transform, &layer.layer.animation_data);
}
// Render each shape instance in the layer
@@ -259,7 +380,8 @@ fn render_vector_layer(document: &Document, time: f64, layer: &VectorLayer, scen
* skew_transform;
let affine = base_transform * object_transform;
// Calculate final opacity (layer * object)
// Calculate final opacity (cascaded from parent → layer → shape instance)
// layer_opacity already includes parent_opacity from render_vector_layer
let final_opacity = (layer_opacity * opacity) as f32;
// Render fill if present