Group shapes

This commit is contained in:
Skyler Lehmkuhl
2026-02-20 11:13:56 -05:00
parent 7e2f63b62d
commit 3ba6dcb3d2
24 changed files with 2092 additions and 2176 deletions
@@ -1,50 +1,35 @@
//! Add shape action
//!
//! Handles adding a new shape and object to a vector layer.
//! Handles adding a new shape to a vector layer's keyframe.
use crate::action::Action;
use crate::document::Document;
use crate::layer::AnyLayer;
use crate::object::ShapeInstance;
use crate::shape::Shape;
use uuid::Uuid;
/// Action that adds a shape and object to a vector layer
///
/// This action creates both a Shape (the path/geometry) and an ShapeInstance
/// (the instance with transform). Both are added to the layer.
/// Action that adds a shape to a vector layer's keyframe
pub struct AddShapeAction {
/// Layer ID to add the shape to
layer_id: Uuid,
/// The shape to add (contains path and styling)
/// The shape to add (contains geometry, styling, transform, opacity)
shape: Shape,
/// The object to add (references the shape with transform)
object: ShapeInstance,
/// Time of the keyframe to add to
time: f64,
/// ID of the created shape (set after execution)
created_shape_id: Option<Uuid>,
/// ID of the created object (set after execution)
created_object_id: Option<Uuid>,
}
impl AddShapeAction {
/// Create a new add shape action
///
/// # Arguments
///
/// * `layer_id` - The layer to add the shape to
/// * `shape` - The shape to add
/// * `object` - The object instance referencing the shape
pub fn new(layer_id: Uuid, shape: Shape, object: ShapeInstance) -> Self {
pub fn new(layer_id: Uuid, shape: Shape, time: f64) -> Self {
Self {
layer_id,
shape,
object,
time,
created_shape_id: None,
created_object_id: None,
}
}
}
@@ -57,34 +42,25 @@ impl Action for AddShapeAction {
};
if let AnyLayer::Vector(vector_layer) = layer {
// Add shape and object to the layer
let shape_id = vector_layer.add_shape_internal(self.shape.clone());
let object_id = vector_layer.add_object_internal(self.object.clone());
// Store the IDs for rollback
let shape_id = self.shape.id;
vector_layer.add_shape_to_keyframe(self.shape.clone(), self.time);
self.created_shape_id = Some(shape_id);
self.created_object_id = Some(object_id);
}
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
// Remove the created shape and object if they exist
if let (Some(shape_id), Some(object_id)) = (self.created_shape_id, self.created_object_id) {
if let Some(shape_id) = self.created_shape_id {
let layer = match document.get_layer_mut(&self.layer_id) {
Some(l) => l,
None => return Ok(()),
};
if let AnyLayer::Vector(vector_layer) = layer {
// Remove in reverse order: object first, then shape
vector_layer.remove_object_internal(&object_id);
vector_layer.remove_shape_internal(&shape_id);
vector_layer.remove_shape_from_keyframe(&shape_id, self.time);
}
// Clear the stored IDs
self.created_shape_id = None;
self.created_object_id = None;
}
Ok(())
}
@@ -99,33 +75,28 @@ mod tests {
use super::*;
use crate::layer::VectorLayer;
use crate::shape::ShapeColor;
use vello::kurbo::{Circle, Rect, Shape as KurboShape};
use vello::kurbo::{Rect, Shape as KurboShape};
#[test]
fn test_add_shape_action_rectangle() {
// Create a document with a vector layer
let mut document = Document::new("Test");
let vector_layer = VectorLayer::new("Layer 1");
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
// Create a rectangle shape
let rect = Rect::new(0.0, 0.0, 100.0, 50.0);
let path = rect.to_path(0.1);
let shape = Shape::new(path).with_fill(ShapeColor::rgb(255, 0, 0));
let object = ShapeInstance::new(shape.id).with_position(50.0, 50.0);
let shape = Shape::new(path)
.with_fill(ShapeColor::rgb(255, 0, 0))
.with_position(50.0, 50.0);
// Create and execute action
let mut action = AddShapeAction::new(layer_id, shape, object);
let mut action = AddShapeAction::new(layer_id, shape, 0.0);
action.execute(&mut document).unwrap();
// Verify shape and object were added
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
assert_eq!(layer.shapes.len(), 1);
assert_eq!(layer.shape_instances.len(), 1);
let added_object = &layer.shape_instances[0];
assert_eq!(added_object.transform.x, 50.0);
assert_eq!(added_object.transform.y, 50.0);
let shapes = layer.shapes_at_time(0.0);
assert_eq!(shapes.len(), 1);
assert_eq!(shapes[0].transform.x, 50.0);
assert_eq!(shapes[0].transform.y, 50.0);
} else {
panic!("Layer not found or not a vector layer");
}
@@ -133,91 +104,8 @@ mod tests {
// Rollback
action.rollback(&mut document).unwrap();
// Verify shape and object were removed
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
assert_eq!(layer.shapes.len(), 0);
assert_eq!(layer.shape_instances.len(), 0);
}
}
#[test]
fn test_add_shape_action_circle() {
let mut document = Document::new("Test");
let vector_layer = VectorLayer::new("Layer 1");
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
// Create a circle shape
let circle = Circle::new((50.0, 50.0), 25.0);
let path = circle.to_path(0.1);
let shape = Shape::new(path)
.with_fill(ShapeColor::rgb(0, 255, 0));
let object = ShapeInstance::new(shape.id);
let mut action = AddShapeAction::new(layer_id, shape, object);
// Test description
assert_eq!(action.description(), "Add shape");
// Execute
action.execute(&mut document).unwrap();
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
assert_eq!(layer.shapes.len(), 1);
assert_eq!(layer.shape_instances.len(), 1);
}
}
#[test]
fn test_add_shape_action_multiple_execute() {
let mut document = Document::new("Test");
let vector_layer = VectorLayer::new("Layer 1");
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
let rect = Rect::new(0.0, 0.0, 50.0, 50.0);
let path = rect.to_path(0.1);
let shape = Shape::new(path);
let object = ShapeInstance::new(shape.id);
let mut action = AddShapeAction::new(layer_id, shape, object);
// Execute twice - shapes are stored in HashMap (keyed by ID, so same shape overwrites)
// while shape_instances are stored in Vec (so duplicates accumulate)
action.execute(&mut document).unwrap();
action.execute(&mut document).unwrap();
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
// Shapes use HashMap keyed by shape.id, so same shape overwrites = 1
// Shape instances use Vec, so duplicates accumulate = 2
assert_eq!(layer.shapes.len(), 1);
assert_eq!(layer.shape_instances.len(), 2);
}
}
#[test]
fn test_add_multiple_different_shapes() {
let mut document = Document::new("Test");
let vector_layer = VectorLayer::new("Layer 1");
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
// Create two different shapes
let rect1 = Rect::new(0.0, 0.0, 50.0, 50.0);
let shape1 = Shape::new(rect1.to_path(0.1));
let object1 = ShapeInstance::new(shape1.id);
let rect2 = Rect::new(100.0, 100.0, 150.0, 150.0);
let shape2 = Shape::new(rect2.to_path(0.1));
let object2 = ShapeInstance::new(shape2.id);
let mut action1 = AddShapeAction::new(layer_id, shape1, object1);
let mut action2 = AddShapeAction::new(layer_id, shape2, object2);
action1.execute(&mut document).unwrap();
action2.execute(&mut document).unwrap();
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
// Two different shapes = 2 entries in HashMap
assert_eq!(layer.shapes.len(), 2);
assert_eq!(layer.shape_instances.len(), 2);
assert_eq!(layer.shapes_at_time(0.0).len(), 0);
}
}
}
@@ -0,0 +1,412 @@
//! Group action
//!
//! Groups selected shapes and/or clip instances into a new VectorClip
//! with a ClipInstance placed on the layer. Supports grouping shapes,
//! existing clip instances (groups), or a mix of both.
use crate::action::Action;
use crate::animation::{AnimationCurve, AnimationTarget, Keyframe, TransformProperty};
use crate::clip::{ClipInstance, VectorClip};
use crate::document::Document;
use crate::layer::{AnyLayer, VectorLayer};
use crate::shape::Shape;
use uuid::Uuid;
use vello::kurbo::{Rect, Shape as KurboShape};
/// Action that groups selected shapes and/or clip instances into a VectorClip
pub struct GroupAction {
/// Layer containing the items to group
layer_id: Uuid,
/// Time of the keyframe to operate on (for shape lookup)
time: f64,
/// Shape IDs to include in the group
shape_ids: Vec<Uuid>,
/// Clip instance IDs to include in the group
clip_instance_ids: Vec<Uuid>,
/// Pre-generated clip instance ID for the new group (so caller can update selection)
instance_id: Uuid,
/// Created clip ID (for rollback)
created_clip_id: Option<Uuid>,
/// Shapes removed from the keyframe (for rollback)
removed_shapes: Vec<Shape>,
/// Clip instances removed from the layer (for rollback, preserving original order)
removed_clip_instances: Vec<ClipInstance>,
}
impl GroupAction {
pub fn new(
layer_id: Uuid,
time: f64,
shape_ids: Vec<Uuid>,
clip_instance_ids: Vec<Uuid>,
instance_id: Uuid,
) -> Self {
Self {
layer_id,
time,
shape_ids,
clip_instance_ids,
instance_id,
created_clip_id: None,
removed_shapes: Vec::new(),
removed_clip_instances: Vec::new(),
}
}
}
impl Action for GroupAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
// --- Phase 1: Collect items and compute bounding box ---
let layer = document
.get_layer(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
let vl = match layer {
AnyLayer::Vector(vl) => vl,
_ => return Err("Group is only supported on vector layers".to_string()),
};
// Collect shapes
let shapes_at_time = vl.shapes_at_time(self.time);
let mut group_shapes: Vec<Shape> = Vec::new();
for id in &self.shape_ids {
if let Some(shape) = shapes_at_time.iter().find(|s| &s.id == id) {
group_shapes.push(shape.clone());
}
}
// Collect clip instances
let mut group_clip_instances: Vec<ClipInstance> = Vec::new();
for id in &self.clip_instance_ids {
if let Some(ci) = vl.clip_instances.iter().find(|ci| &ci.id == id) {
group_clip_instances.push(ci.clone());
}
}
let total_items = group_shapes.len() + group_clip_instances.len();
if total_items < 2 {
return Err("Need at least 2 items to group".to_string());
}
// Compute combined bounding box in parent (layer) space
let mut combined_bbox: Option<Rect> = None;
// Shape bounding boxes
for shape in &group_shapes {
let local_bbox = shape.path().bounding_box();
let transform = shape.transform.to_affine();
let transformed_bbox = transform.transform_rect_bbox(local_bbox);
combined_bbox = Some(match combined_bbox {
Some(existing) => existing.union(transformed_bbox),
None => transformed_bbox,
});
}
// Clip instance bounding boxes
for ci in &group_clip_instances {
let content_bounds = if let Some(vector_clip) = document.get_vector_clip(&ci.clip_id) {
let clip_time = ((self.time - ci.timeline_start) * ci.playback_speed) + ci.trim_start;
vector_clip.calculate_content_bounds(document, clip_time)
} else if let Some(video_clip) = document.get_video_clip(&ci.clip_id) {
Rect::new(0.0, 0.0, video_clip.width, video_clip.height)
} else {
continue;
};
let ci_transform = ci.transform.to_affine();
let transformed_bbox = ci_transform.transform_rect_bbox(content_bounds);
combined_bbox = Some(match combined_bbox {
Some(existing) => existing.union(transformed_bbox),
None => transformed_bbox,
});
}
let bbox = combined_bbox.ok_or("Could not compute bounding box")?;
let center_x = (bbox.x0 + bbox.x1) / 2.0;
let center_y = (bbox.y0 + bbox.y1) / 2.0;
// --- Phase 2: Build the VectorClip ---
// Offset shapes so positions are relative to the group center
let mut clip_shapes: Vec<Shape> = group_shapes.clone();
for shape in &mut clip_shapes {
shape.transform.x -= center_x;
shape.transform.y -= center_y;
}
// Offset clip instances similarly
let mut clip_instances_inside: Vec<ClipInstance> = group_clip_instances.clone();
for ci in &mut clip_instances_inside {
ci.transform.x -= center_x;
ci.transform.y -= center_y;
}
// Create VectorClip — groups are static (one frame), not time-based clips
let frame_duration = 1.0 / document.framerate;
let mut clip = VectorClip::new("Group", bbox.width(), bbox.height(), frame_duration);
clip.is_group = true;
let clip_id = clip.id;
let mut inner_layer = VectorLayer::new("Layer 1");
for shape in clip_shapes {
inner_layer.add_shape_to_keyframe(shape, 0.0);
}
for ci in clip_instances_inside {
inner_layer.clip_instances.push(ci);
}
clip.layers.add_root(AnyLayer::Vector(inner_layer));
// Add clip to document library
document.add_vector_clip(clip);
self.created_clip_id = Some(clip_id);
// --- Phase 3: Remove originals from the layer ---
let layer = document.get_layer_mut(&self.layer_id).unwrap();
let vl = match layer {
AnyLayer::Vector(vl) => vl,
_ => unreachable!(),
};
// Remove shapes
self.removed_shapes.clear();
for id in &self.shape_ids {
if let Some(shape) = vl.remove_shape_from_keyframe(id, self.time) {
self.removed_shapes.push(shape);
}
}
// Remove clip instances (preserve order for rollback)
self.removed_clip_instances.clear();
for id in &self.clip_instance_ids {
if let Some(pos) = vl.clip_instances.iter().position(|ci| &ci.id == id) {
self.removed_clip_instances.push(vl.clip_instances.remove(pos));
}
}
// --- Phase 4: Place the new group ClipInstance ---
let instance = ClipInstance::with_id(self.instance_id, clip_id)
.with_position(center_x, center_y)
.with_name("Group");
vl.clip_instances.push(instance);
// Register the group in the current keyframe's clip_instance_ids
if let Some(kf) = vl.keyframe_at_mut(self.time) {
if !kf.clip_instance_ids.contains(&self.instance_id) {
kf.clip_instance_ids.push(self.instance_id);
}
}
// --- Phase 5: Create default animation curves with initial keyframe ---
let props_and_values = [
(TransformProperty::X, center_x),
(TransformProperty::Y, center_y),
(TransformProperty::Rotation, 0.0),
(TransformProperty::ScaleX, 1.0),
(TransformProperty::ScaleY, 1.0),
(TransformProperty::SkewX, 0.0),
(TransformProperty::SkewY, 0.0),
(TransformProperty::Opacity, 1.0),
];
for (prop, value) in props_and_values {
let target = AnimationTarget::Object {
id: self.instance_id,
property: prop,
};
let mut curve = AnimationCurve::new(target.clone(), value);
curve.set_keyframe(Keyframe::linear(0.0, value));
vl.layer.animation_data.set_curve(curve);
}
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let layer = document
.get_layer_mut(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
if let AnyLayer::Vector(vl) = layer {
// Remove animation curves for the group's clip instance
for prop in &[
TransformProperty::X, TransformProperty::Y,
TransformProperty::Rotation,
TransformProperty::ScaleX, TransformProperty::ScaleY,
TransformProperty::SkewX, TransformProperty::SkewY,
TransformProperty::Opacity,
] {
let target = AnimationTarget::Object {
id: self.instance_id,
property: *prop,
};
vl.layer.animation_data.remove_curve(&target);
}
// Remove the group's clip instance
vl.clip_instances.retain(|ci| ci.id != self.instance_id);
// Remove the group ID from the keyframe
if let Some(kf) = vl.keyframe_at_mut(self.time) {
kf.clip_instance_ids.retain(|id| id != &self.instance_id);
}
// Re-insert removed shapes
for shape in self.removed_shapes.drain(..) {
vl.add_shape_to_keyframe(shape, self.time);
}
// Re-insert removed clip instances
for ci in self.removed_clip_instances.drain(..) {
vl.clip_instances.push(ci);
}
}
// Remove the VectorClip from the document
if let Some(clip_id) = self.created_clip_id.take() {
document.remove_vector_clip(&clip_id);
}
Ok(())
}
fn description(&self) -> String {
let count = self.shape_ids.len() + self.clip_instance_ids.len();
format!("Group {} objects", count)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::shape::ShapeColor;
use vello::kurbo::{Circle, Shape as KurboShape};
#[test]
fn test_group_shapes() {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
let circle1 = Circle::new((0.0, 0.0), 20.0);
let shape1 = Shape::new(circle1.to_path(0.1))
.with_fill(ShapeColor::rgb(255, 0, 0))
.with_position(50.0, 50.0);
let shape1_id = shape1.id;
let circle2 = Circle::new((0.0, 0.0), 20.0);
let shape2 = Shape::new(circle2.to_path(0.1))
.with_fill(ShapeColor::rgb(0, 255, 0))
.with_position(150.0, 50.0);
let shape2_id = shape2.id;
layer.add_shape_to_keyframe(shape1, 0.0);
layer.add_shape_to_keyframe(shape2, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
let instance_id = Uuid::new_v4();
let mut action = GroupAction::new(
layer_id, 0.0,
vec![shape1_id, shape2_id],
vec![],
instance_id,
);
action.execute(&mut document).unwrap();
// Shapes removed, clip instance added
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
assert_eq!(vl.shapes_at_time(0.0).len(), 0);
assert_eq!(vl.clip_instances.len(), 1);
assert_eq!(vl.clip_instances[0].id, instance_id);
}
assert_eq!(document.vector_clips.len(), 1);
// Rollback
action.rollback(&mut document).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
assert_eq!(vl.shapes_at_time(0.0).len(), 2);
assert_eq!(vl.clip_instances.len(), 0);
}
assert!(document.vector_clips.is_empty());
}
#[test]
fn test_group_mixed_shapes_and_clips() {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
// Add a shape
let circle = Circle::new((0.0, 0.0), 20.0);
let shape = Shape::new(circle.to_path(0.1))
.with_fill(ShapeColor::rgb(255, 0, 0))
.with_position(50.0, 50.0);
let shape_id = shape.id;
layer.add_shape_to_keyframe(shape, 0.0);
// Add a clip instance (create a clip for it first)
let mut inner_clip = VectorClip::new("Inner", 40.0, 40.0, 1.0);
let inner_clip_id = inner_clip.id;
let mut inner_layer = VectorLayer::new("Inner Layer");
let inner_shape = Shape::new(Circle::new((20.0, 20.0), 15.0).to_path(0.1))
.with_fill(ShapeColor::rgb(0, 0, 255));
inner_layer.add_shape_to_keyframe(inner_shape, 0.0);
inner_clip.layers.add_root(AnyLayer::Vector(inner_layer));
document.add_vector_clip(inner_clip);
let ci = ClipInstance::new(inner_clip_id).with_position(150.0, 50.0);
let ci_id = ci.id;
layer.clip_instances.push(ci);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
let instance_id = Uuid::new_v4();
let mut action = GroupAction::new(
layer_id, 0.0,
vec![shape_id],
vec![ci_id],
instance_id,
);
action.execute(&mut document).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
assert_eq!(vl.shapes_at_time(0.0).len(), 0);
// Only the new group instance remains (the inner clip instance was grouped)
assert_eq!(vl.clip_instances.len(), 1);
assert_eq!(vl.clip_instances[0].id, instance_id);
}
// Two vector clips: the inner one + the new group
assert_eq!(document.vector_clips.len(), 2);
// Rollback
action.rollback(&mut document).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
assert_eq!(vl.shapes_at_time(0.0).len(), 1);
assert_eq!(vl.clip_instances.len(), 1);
assert_eq!(vl.clip_instances[0].id, ci_id);
}
// Only the inner clip remains
assert_eq!(document.vector_clips.len(), 1);
}
#[test]
fn test_group_description() {
let action = GroupAction::new(
Uuid::new_v4(), 0.0,
vec![Uuid::new_v4(), Uuid::new_v4()],
vec![Uuid::new_v4()],
Uuid::new_v4(),
);
assert_eq!(action.description(), "Group 3 objects");
}
}
@@ -28,6 +28,8 @@ pub mod update_midi_notes;
pub mod loop_clip_instances;
pub mod remove_clip_instances;
pub mod remove_shapes;
pub mod set_keyframe;
pub mod group_shapes;
pub use add_clip_instance::AddClipInstanceAction;
pub use add_effect::AddEffectAction;
@@ -54,3 +56,5 @@ pub use update_midi_notes::UpdateMidiNotesAction;
pub use loop_clip_instances::LoopClipInstancesAction;
pub use remove_clip_instances::RemoveClipInstancesAction;
pub use remove_shapes::RemoveShapesAction;
pub use set_keyframe::SetKeyframeAction;
pub use group_shapes::GroupAction;
@@ -20,6 +20,9 @@ pub struct ModifyShapePathAction {
/// Shape to modify
shape_id: Uuid,
/// Time of the keyframe containing the shape
time: f64,
/// The version index being modified (for shapes with multiple versions)
version_index: usize,
@@ -32,17 +35,11 @@ pub struct ModifyShapePathAction {
impl ModifyShapePathAction {
/// Create a new action to modify a shape's path
///
/// # Arguments
///
/// * `layer_id` - The layer containing the shape
/// * `shape_id` - The shape to modify
/// * `version_index` - The version index to modify (usually 0)
/// * `new_path` - The new path to set
pub fn new(layer_id: Uuid, shape_id: Uuid, version_index: usize, new_path: BezPath) -> Self {
pub fn new(layer_id: Uuid, shape_id: Uuid, time: f64, version_index: usize, new_path: BezPath) -> Self {
Self {
layer_id,
shape_id,
time,
version_index,
new_path,
old_path: None,
@@ -53,6 +50,7 @@ impl ModifyShapePathAction {
pub fn with_old_path(
layer_id: Uuid,
shape_id: Uuid,
time: f64,
version_index: usize,
old_path: BezPath,
new_path: BezPath,
@@ -60,6 +58,7 @@ impl ModifyShapePathAction {
Self {
layer_id,
shape_id,
time,
version_index,
new_path,
old_path: Some(old_path),
@@ -71,8 +70,7 @@ impl Action for ModifyShapePathAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
if let Some(shape) = vector_layer.shapes.get_mut(&self.shape_id) {
// Check if version exists
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(&self.shape_id, self.time) {
if self.version_index >= shape.versions.len() {
return Err(format!(
"Version index {} out of bounds (shape has {} versions)",
@@ -104,7 +102,7 @@ impl Action for ModifyShapePathAction {
if let Some(old_path) = &self.old_path {
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
if let Some(shape) = vector_layer.shapes.get_mut(&self.shape_id) {
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(&self.shape_id, self.time) {
if self.version_index < shape.versions.len() {
shape.versions[self.version_index].path = old_path.clone();
return Ok(());
@@ -130,6 +128,7 @@ mod tests {
use super::*;
use crate::layer::VectorLayer;
use crate::shape::Shape;
use vello::kurbo::Shape as KurboShape;
fn create_test_path() -> BezPath {
let mut path = BezPath::new();
@@ -144,9 +143,9 @@ mod tests {
fn create_modified_path() -> BezPath {
let mut path = BezPath::new();
path.move_to((0.0, 0.0));
path.line_to((150.0, 0.0)); // Modified
path.line_to((150.0, 150.0)); // Modified
path.line_to((0.0, 150.0)); // Modified
path.line_to((150.0, 0.0));
path.line_to((150.0, 150.0));
path.line_to((0.0, 150.0));
path.close_path();
path
}
@@ -158,13 +157,13 @@ mod tests {
let shape = Shape::new(create_test_path());
let shape_id = shape.id;
layer.shapes.insert(shape_id, shape);
layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Verify initial path
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let shape = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
let bbox = shape.versions[0].path.bounding_box();
assert_eq!(bbox.width(), 100.0);
assert_eq!(bbox.height(), 100.0);
@@ -172,12 +171,12 @@ mod tests {
// Create and execute action
let new_path = create_modified_path();
let mut action = ModifyShapePathAction::new(layer_id, shape_id, 0, new_path);
let mut action = ModifyShapePathAction::new(layer_id, shape_id, 0.0, 0, new_path);
action.execute(&mut document).unwrap();
// Verify path changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let shape = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
let bbox = shape.versions[0].path.bounding_box();
assert_eq!(bbox.width(), 150.0);
assert_eq!(bbox.height(), 150.0);
@@ -187,8 +186,8 @@ mod tests {
action.rollback(&mut document).unwrap();
// Verify restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let shape = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
let bbox = shape.versions[0].path.bounding_box();
assert_eq!(bbox.width(), 100.0);
assert_eq!(bbox.height(), 100.0);
@@ -202,13 +201,12 @@ mod tests {
let shape = Shape::new(create_test_path());
let shape_id = shape.id;
layer.shapes.insert(shape_id, shape);
layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Try to modify non-existent version
let new_path = create_modified_path();
let mut action = ModifyShapePathAction::new(layer_id, shape_id, 5, new_path);
let mut action = ModifyShapePathAction::new(layer_id, shape_id, 0.0, 5, new_path);
let result = action.execute(&mut document);
assert!(result.is_err());
@@ -219,7 +217,7 @@ mod tests {
fn test_description() {
let layer_id = Uuid::new_v4();
let shape_id = Uuid::new_v4();
let action = ModifyShapePathAction::new(layer_id, shape_id, 0, create_test_path());
let action = ModifyShapePathAction::new(layer_id, shape_id, 0.0, 0, create_test_path());
assert_eq!(action.description(), "Modify shape path");
}
}
@@ -1,6 +1,6 @@
//! Move shape instances action
//! Move shapes action
//!
//! Handles moving one or more shape instances to new positions.
//! Handles moving one or more shapes to new positions within a keyframe.
use crate::action::Action;
use crate::document::Document;
@@ -9,26 +9,20 @@ use std::collections::HashMap;
use uuid::Uuid;
use vello::kurbo::Point;
/// Action that moves shape instances to new positions
/// Action that moves shapes to new positions within a keyframe
pub struct MoveShapeInstancesAction {
/// Layer ID containing the shape instances
layer_id: Uuid,
/// Map of object IDs to their old and new positions
shape_instance_positions: HashMap<Uuid, (Point, Point)>, // (old_pos, new_pos)
time: f64,
/// Map of shape IDs to their old and new positions
shape_positions: HashMap<Uuid, (Point, Point)>,
}
impl MoveShapeInstancesAction {
/// Create a new move shape instances action
///
/// # Arguments
///
/// * `layer_id` - The layer containing the shape instances
/// * `shape_instance_positions` - Map of object IDs to (old_position, new_position)
pub fn new(layer_id: Uuid, shape_instance_positions: HashMap<Uuid, (Point, Point)>) -> Self {
pub fn new(layer_id: Uuid, time: f64, shape_positions: HashMap<Uuid, (Point, Point)>) -> Self {
Self {
layer_id,
shape_instance_positions,
time,
shape_positions,
}
}
}
@@ -41,11 +35,11 @@ impl Action for MoveShapeInstancesAction {
};
if let AnyLayer::Vector(vector_layer) = layer {
for (shape_instance_id, (_old, new)) in &self.shape_instance_positions {
vector_layer.modify_object_internal(shape_instance_id, |obj| {
obj.transform.x = new.x;
obj.transform.y = new.y;
});
for (shape_id, (_old, new)) in &self.shape_positions {
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(shape_id, self.time) {
shape.transform.x = new.x;
shape.transform.y = new.y;
}
}
}
Ok(())
@@ -58,76 +52,22 @@ impl Action for MoveShapeInstancesAction {
};
if let AnyLayer::Vector(vector_layer) = layer {
for (shape_instance_id, (old, _new)) in &self.shape_instance_positions {
vector_layer.modify_object_internal(shape_instance_id, |obj| {
obj.transform.x = old.x;
obj.transform.y = old.y;
});
for (shape_id, (old, _new)) in &self.shape_positions {
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(shape_id, self.time) {
shape.transform.x = old.x;
shape.transform.y = old.y;
}
}
}
Ok(())
}
fn description(&self) -> String {
let count = self.shape_instance_positions.len();
let count = self.shape_positions.len();
if count == 1 {
"Move shape instance".to_string()
"Move shape".to_string()
} else {
format!("Move {} shape instances", count)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layer::VectorLayer;
use crate::object::ShapeInstance;
use crate::shape::Shape;
use vello::kurbo::{Circle, Shape as KurboShape};
#[test]
fn test_move_shape_instances_action() {
// Create a document with a test object
let mut document = Document::new("Test");
let circle = Circle::new((100.0, 100.0), 50.0);
let path = circle.to_path(0.1);
let shape = Shape::new(path);
let object = ShapeInstance::new(shape.id).with_position(50.0, 50.0);
let mut vector_layer = VectorLayer::new("Layer 1");
vector_layer.add_shape(shape);
let shape_instance_id = vector_layer.add_object(object);
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
// Create move action
let mut positions = HashMap::new();
positions.insert(
shape_instance_id,
(Point::new(50.0, 50.0), Point::new(150.0, 200.0))
);
let mut action = MoveShapeInstancesAction::new(layer_id, positions);
// Execute
action.execute(&mut document).unwrap();
// Verify position changed
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
let obj = layer.get_object(&shape_instance_id).unwrap();
assert_eq!(obj.transform.x, 150.0);
assert_eq!(obj.transform.y, 200.0);
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify position restored
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
let obj = layer.get_object(&shape_instance_id).unwrap();
assert_eq!(obj.transform.x, 50.0);
assert_eq!(obj.transform.y, 50.0);
format!("Move {} shapes", count)
}
}
}
@@ -8,7 +8,6 @@ use crate::curve_segment::CurveSegment;
use crate::document::Document;
use crate::gap_handling::GapHandlingMode;
use crate::layer::AnyLayer;
use crate::object::ShapeInstance;
use crate::planar_graph::PlanarGraph;
use crate::shape::ShapeColor;
use uuid::Uuid;
@@ -19,6 +18,9 @@ pub struct PaintBucketAction {
/// Layer ID to add the filled shape to
layer_id: Uuid,
/// Time of the keyframe to operate on
time: f64,
/// Click point where fill was initiated
click_point: Point,
@@ -33,23 +35,13 @@ pub struct PaintBucketAction {
/// ID of the created shape (set after execution)
created_shape_id: Option<Uuid>,
/// ID of the created shape instance (set after execution)
created_shape_instance_id: Option<Uuid>,
}
impl PaintBucketAction {
/// Create a new paint bucket action
///
/// # Arguments
///
/// * `layer_id` - The layer to add the filled shape to
/// * `click_point` - Point where the user clicked to initiate fill
/// * `fill_color` - Color to fill the region with
/// * `tolerance` - Gap tolerance in pixels (default: 2.0)
/// * `gap_mode` - Gap handling mode (SnapAndSplit or BridgeSegment)
pub fn new(
layer_id: Uuid,
time: f64,
click_point: Point,
fill_color: ShapeColor,
tolerance: f64,
@@ -57,12 +49,12 @@ impl PaintBucketAction {
) -> Self {
Self {
layer_id,
time,
click_point,
fill_color,
_tolerance: tolerance,
_gap_mode: gap_mode,
created_shape_id: None,
created_shape_instance_id: None,
}
}
}
@@ -72,60 +64,46 @@ impl Action for PaintBucketAction {
println!("=== PaintBucketAction::execute ===");
// Optimization: Check if we're clicking on an existing shape first
// This is much faster than building a planar graph
if let Some(AnyLayer::Vector(vector_layer)) = document.get_layer_mut(&self.layer_id) {
// Iterate through shape instances in reverse order (topmost first)
for shape_instance in vector_layer.shape_instances.iter().rev() {
// Find the corresponding shape (O(1) HashMap lookup)
if let Some(shape) = vector_layer.shapes.get(&shape_instance.shape_id) {
// Skip shapes without fill color (e.g., lines with only stroke)
if shape.fill_color.is_none() {
continue;
}
// Check if the path is closed - winding number only makes sense for closed paths
use vello::kurbo::PathEl;
let is_closed = shape.path().elements().iter().any(|el| matches!(el, PathEl::ClosePath));
if !is_closed {
// Skip non-closed paths - can't use winding number test
continue;
}
// Apply the shape instance's transform to get the transformed path
let transform_affine = shape_instance.transform.to_affine();
// Transform the click point to shape's local coordinates (inverse transform)
let inverse_transform = transform_affine.inverse();
let local_point = inverse_transform * self.click_point;
// Test if the local point is inside the shape using winding number
use vello::kurbo::Shape as KurboShape;
let winding = shape.path().winding(local_point);
if winding != 0 {
// Point is inside this shape! Just change its fill color
println!("Clicked on existing shape, changing fill color");
// Store the shape ID before the immutable borrow ends
let shape_id = shape.id;
// Find mutable reference to the shape and update its fill (O(1) HashMap lookup)
if let Some(shape_mut) = vector_layer.shapes.get_mut(&shape_id) {
shape_mut.fill_color = Some(self.fill_color);
println!("Updated shape fill color");
}
return Ok(()); // Done! No need to create a new shape
// Iterate through shapes in the keyframe in reverse order (topmost first)
let shapes = vector_layer.shapes_at_time(self.time);
for shape in shapes.iter().rev() {
// Skip shapes without fill color
if shape.fill_color.is_none() {
continue;
}
use vello::kurbo::PathEl;
let is_closed = shape.path().elements().iter().any(|el| matches!(el, PathEl::ClosePath));
if !is_closed {
continue;
}
// Apply the shape's transform
let transform_affine = shape.transform.to_affine();
let inverse_transform = transform_affine.inverse();
let local_point = inverse_transform * self.click_point;
use vello::kurbo::Shape as KurboShape;
let winding = shape.path().winding(local_point);
if winding != 0 {
println!("Clicked on existing shape, changing fill color");
let shape_id = shape.id;
// Now get mutable access to change the fill
if let Some(shape_mut) = vector_layer.get_shape_in_keyframe_mut(&shape_id, self.time) {
shape_mut.fill_color = Some(self.fill_color);
}
return Ok(());
}
}
println!("No existing shape at click point, creating new fill region");
}
// Step 1: Extract curves from all shapes (rectangles, ellipses, paths, etc.)
let all_curves = extract_curves_from_all_shapes(document, &self.layer_id);
// Step 1: Extract curves from all shapes in the keyframe
let all_curves = extract_curves_from_keyframe(document, &self.layer_id, self.time);
println!("Extracted {} curves from all shapes", all_curves.len());
@@ -138,62 +116,36 @@ impl Action for PaintBucketAction {
println!("Building planar graph...");
let graph = PlanarGraph::build(&all_curves);
// Step 3: Trace the face containing the click point (optimized - only traces one face)
// Step 3: Trace the face containing the click point
println!("Tracing face from click point {:?}...", self.click_point);
if let Some(face) = graph.trace_face_from_point(self.click_point) {
println!("Successfully traced face containing click point!");
// Build the face boundary using actual curve segments
let face_path = graph.build_face_path(&face);
println!("DEBUG: Creating face shape with fill color: r={}, g={}, b={}, a={}",
self.fill_color.r, self.fill_color.g, self.fill_color.b, self.fill_color.a);
let face_shape = crate::shape::Shape::new(face_path)
.with_fill(self.fill_color); // Use the requested fill color
.with_fill(self.fill_color);
println!("DEBUG: Face shape created with fill_color: {:?}", face_shape.fill_color);
let face_shape_instance = ShapeInstance::new(face_shape.id);
// Store the created IDs for rollback
self.created_shape_id = Some(face_shape.id);
self.created_shape_instance_id = Some(face_shape_instance.id);
if let Some(AnyLayer::Vector(vector_layer)) = document.get_layer_mut(&self.layer_id) {
let shape_id_for_debug = face_shape.id;
vector_layer.add_shape_internal(face_shape);
vector_layer.add_object_internal(face_shape_instance);
println!("DEBUG: Added filled shape");
// Verify the shape still has the fill color after being added (O(1) HashMap lookup)
if let Some(added_shape) = vector_layer.shapes.get(&shape_id_for_debug) {
println!("DEBUG: After adding to layer, shape fill_color = {:?}", added_shape.fill_color);
}
vector_layer.add_shape_to_keyframe(face_shape, self.time);
println!("DEBUG: Added filled shape to keyframe");
}
} else {
println!("Click point is not inside any face!");
}
println!("=== Paint Bucket Complete: Face filled with curves ===");
println!("=== Paint Bucket Complete ===");
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
// Remove the created shape and object if they exist
if let (Some(shape_id), Some(object_id)) = (self.created_shape_id, self.created_shape_instance_id) {
let layer = match document.get_layer_mut(&self.layer_id) {
Some(l) => l,
None => return Ok(()),
};
if let AnyLayer::Vector(vector_layer) = layer {
vector_layer.remove_object_internal(&object_id);
vector_layer.remove_shape_internal(&shape_id);
if let Some(shape_id) = self.created_shape_id {
if let Some(AnyLayer::Vector(vector_layer)) = document.get_layer_mut(&self.layer_id) {
vector_layer.remove_shape_from_keyframe(&shape_id, self.time);
}
self.created_shape_id = None;
self.created_shape_instance_id = None;
}
Ok(())
}
@@ -203,54 +155,39 @@ impl Action for PaintBucketAction {
}
}
/// Extract curves from all shapes in the layer
///
/// Includes rectangles, ellipses, paths, and even previous paint bucket fills.
/// The planar graph builder will handle deduplication of overlapping edges.
fn extract_curves_from_all_shapes(
/// Extract curves from all shapes in the keyframe at the given time
fn extract_curves_from_keyframe(
document: &Document,
layer_id: &Uuid,
time: f64,
) -> Vec<CurveSegment> {
let mut all_curves = Vec::new();
// Get the specified layer
let layer = match document.get_layer(layer_id) {
Some(l) => l,
None => return all_curves,
};
// Extract curves only from this vector layer
if let AnyLayer::Vector(vector_layer) = layer {
println!("Extracting curves from {} objects in layer", vector_layer.shape_instances.len());
// Extract curves from each object (which applies transforms to shapes)
for (obj_idx, object) in vector_layer.shape_instances.iter().enumerate() {
// Find the shape for this object (O(1) HashMap lookup)
let shape = match vector_layer.shapes.get(&object.shape_id) {
Some(s) => s,
None => continue,
};
let shapes = vector_layer.shapes_at_time(time);
println!("Extracting curves from {} shapes in keyframe", shapes.len());
// Include all shapes - planar graph will handle deduplication
// (Rectangles, ellipses, paths, and even previous paint bucket fills)
// Get the transform matrix from the object
let transform_affine = object.transform.to_affine();
for (shape_idx, shape) in shapes.iter().enumerate() {
let transform_affine = shape.transform.to_affine();
let path = shape.path();
let mut current_point = Point::ZERO;
let mut subpath_start = Point::ZERO; // Track start of current subpath
let mut subpath_start = Point::ZERO;
let mut segment_index = 0;
let mut curves_in_shape = 0;
for element in path.elements() {
// Extract curve segment from path element
if let Some(mut segment) = CurveSegment::from_path_element(
shape.id.as_u128() as usize,
segment_index,
element,
current_point,
) {
// Apply the object's transform to all control points
for control_point in &mut segment.control_points {
*control_point = transform_affine * (*control_point);
}
@@ -260,24 +197,21 @@ fn extract_curves_from_all_shapes(
curves_in_shape += 1;
}
// Update current point for next iteration (keep in local space)
match element {
vello::kurbo::PathEl::MoveTo(p) => {
current_point = *p;
subpath_start = *p; // Mark start of new subpath
subpath_start = *p;
}
vello::kurbo::PathEl::LineTo(p) => current_point = *p,
vello::kurbo::PathEl::QuadTo(_, p) => current_point = *p,
vello::kurbo::PathEl::CurveTo(_, _, p) => current_point = *p,
vello::kurbo::PathEl::ClosePath => {
// Create closing segment from current_point back to subpath_start
if let Some(mut segment) = CurveSegment::from_path_element(
shape.id.as_u128() as usize,
segment_index,
&vello::kurbo::PathEl::LineTo(subpath_start),
current_point,
) {
// Apply transform
for control_point in &mut segment.control_points {
*control_point = transform_affine * (*control_point);
}
@@ -286,12 +220,12 @@ fn extract_curves_from_all_shapes(
segment_index += 1;
curves_in_shape += 1;
}
current_point = subpath_start; // ClosePath moves back to start
current_point = subpath_start;
}
}
}
println!(" Object {}: Extracted {} curves from shape", obj_idx, curves_in_shape);
println!(" Shape {}: Extracted {} curves", shape_idx, curves_in_shape);
}
}
@@ -307,57 +241,46 @@ mod tests {
#[test]
fn test_paint_bucket_action_basic() {
// Create a document with a vector layer
let mut document = Document::new("Test");
let vector_layer = VectorLayer::new("Layer 1");
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
let mut layer = VectorLayer::new("Layer 1");
// Create a simple rectangle shape (boundary for fill)
let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
let path = rect.to_path(0.1);
let shape = Shape::new(path);
let shape_instance = ShapeInstance::new(shape.id);
// Add the boundary shape
if let Some(AnyLayer::Vector(layer)) = document.get_layer_mut(&layer_id) {
layer.add_shape_internal(shape);
layer.add_object_internal(shape_instance);
}
layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Create and execute paint bucket action
let mut action = PaintBucketAction::new(
layer_id,
Point::new(50.0, 50.0), // Click in center
ShapeColor::rgb(255, 0, 0), // Red fill
0.0,
Point::new(50.0, 50.0),
ShapeColor::rgb(255, 0, 0),
2.0,
GapHandlingMode::BridgeSegment,
);
action.execute(&mut document).unwrap();
// Verify a filled shape was created
// Verify a filled shape was created (or existing shape was recolored)
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
// Should have original shape + filled shape
assert!(layer.shapes.len() >= 1);
assert!(layer.shape_instances.len() >= 1);
assert!(layer.shapes_at_time(0.0).len() >= 1);
} else {
panic!("Layer not found or not a vector layer");
}
// Test rollback
action.rollback(&mut document).unwrap();
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
// Should only have original shape
assert_eq!(layer.shapes.len(), 1);
assert_eq!(layer.shape_instances.len(), 1);
}
}
#[test]
fn test_paint_bucket_action_description() {
let action = PaintBucketAction::new(
Uuid::new_v4(),
0.0,
Point::ZERO,
ShapeColor::rgb(0, 0, 255),
2.0,
@@ -1,37 +1,32 @@
//! Remove shapes action
//!
//! Handles removing shapes and shape instances from a vector layer (for cut/delete).
//! Handles removing shapes from a vector layer's keyframe (for cut/delete).
use crate::action::Action;
use crate::document::Document;
use crate::layer::AnyLayer;
use crate::object::ShapeInstance;
use crate::shape::Shape;
use uuid::Uuid;
/// Action that removes shapes and their instances from a vector layer
/// Action that removes shapes from a vector layer's keyframe
pub struct RemoveShapesAction {
/// Layer ID containing the shapes
layer_id: Uuid,
/// Shape IDs to remove
shape_ids: Vec<Uuid>,
/// Shape instance IDs to remove
instance_ids: Vec<Uuid>,
/// Time of the keyframe
time: f64,
/// Saved shapes for rollback
saved_shapes: Vec<(Uuid, Shape)>,
/// Saved instances for rollback
saved_instances: Vec<ShapeInstance>,
saved_shapes: Vec<Shape>,
}
impl RemoveShapesAction {
/// Create a new remove shapes action
pub fn new(layer_id: Uuid, shape_ids: Vec<Uuid>, instance_ids: Vec<Uuid>) -> Self {
pub fn new(layer_id: Uuid, shape_ids: Vec<Uuid>, time: f64) -> Self {
Self {
layer_id,
shape_ids,
instance_ids,
time,
saved_shapes: Vec::new(),
saved_instances: Vec::new(),
}
}
}
@@ -39,7 +34,6 @@ impl RemoveShapesAction {
impl Action for RemoveShapesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
self.saved_shapes.clear();
self.saved_instances.clear();
let layer = document
.get_layer_mut(&self.layer_id)
@@ -50,21 +44,9 @@ impl Action for RemoveShapesAction {
_ => return Err("Not a vector layer".to_string()),
};
// Remove and save shape instances
let mut remaining_instances = Vec::new();
for inst in vector_layer.shape_instances.drain(..) {
if self.instance_ids.contains(&inst.id) {
self.saved_instances.push(inst);
} else {
remaining_instances.push(inst);
}
}
vector_layer.shape_instances = remaining_instances;
// Remove and save shape definitions
for shape_id in &self.shape_ids {
if let Some(shape) = vector_layer.shapes.remove(shape_id) {
self.saved_shapes.push((*shape_id, shape));
if let Some(shape) = vector_layer.remove_shape_from_keyframe(shape_id, self.time) {
self.saved_shapes.push(shape);
}
}
@@ -81,21 +63,15 @@ impl Action for RemoveShapesAction {
_ => return Err("Not a vector layer".to_string()),
};
// Restore shapes
for (id, shape) in self.saved_shapes.drain(..) {
vector_layer.shapes.insert(id, shape);
}
// Restore instances
for inst in self.saved_instances.drain(..) {
vector_layer.shape_instances.push(inst);
for shape in self.saved_shapes.drain(..) {
vector_layer.add_shape_to_keyframe(shape, self.time);
}
Ok(())
}
fn description(&self) -> String {
let count = self.instance_ids.len();
let count = self.shape_ids.len();
if count == 1 {
"Delete shape".to_string()
} else {
@@ -108,45 +84,35 @@ impl Action for RemoveShapesAction {
mod tests {
use super::*;
use crate::layer::VectorLayer;
use crate::object::ShapeInstance;
use crate::shape::Shape;
use vello::kurbo::BezPath;
#[test]
fn test_remove_shapes() {
let mut document = Document::new("Test");
let mut vector_layer = VectorLayer::new("Layer 1");
// Add a shape and instance
let mut path = BezPath::new();
path.move_to((0.0, 0.0));
path.line_to((100.0, 100.0));
let shape = Shape::new(path);
let shape_id = shape.id;
let instance = ShapeInstance::new(shape_id);
let instance_id = instance.id;
vector_layer.shapes.insert(shape_id, shape);
vector_layer.shape_instances.push(instance);
vector_layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(vector_layer));
// Remove
let mut action = RemoveShapesAction::new(layer_id, vec![shape_id], vec![instance_id]);
let mut action = RemoveShapesAction::new(layer_id, vec![shape_id], 0.0);
action.execute(&mut document).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
assert!(vl.shapes.is_empty());
assert!(vl.shape_instances.is_empty());
assert!(vl.shapes_at_time(0.0).is_empty());
}
// Rollback
action.rollback(&mut document).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
assert_eq!(vl.shapes.len(), 1);
assert_eq!(vl.shape_instances.len(), 1);
assert_eq!(vl.shapes_at_time(0.0).len(), 1);
}
}
}
@@ -1,7 +1,8 @@
//! Set shape instance properties action
//!
//! Handles changing individual properties on shape instances (position, rotation, scale, etc.)
//! with undo/redo support.
//! Handles changing individual properties on shapes (position, rotation, scale, etc.)
//! with undo/redo support. In the keyframe model, these operate on Shape's transform
//! and opacity fields within the active keyframe.
use crate::action::Action;
use crate::document::Document;
@@ -37,53 +38,65 @@ impl InstancePropertyChange {
}
}
/// Action that sets a property on one or more shape instances
/// Action that sets a property on one or more shapes in a keyframe
pub struct SetInstancePropertiesAction {
/// Layer containing the instances
/// Layer containing the shapes
layer_id: Uuid,
/// Instance IDs to modify and their old values
instance_changes: Vec<(Uuid, Option<f64>)>,
/// Time of the keyframe
time: f64,
/// Shape IDs to modify and their old values
shape_changes: Vec<(Uuid, Option<f64>)>,
/// Property to change
property: InstancePropertyChange,
}
impl SetInstancePropertiesAction {
/// Create a new action to set a property on a single instance
pub fn new(layer_id: Uuid, instance_id: Uuid, property: InstancePropertyChange) -> Self {
/// Create a new action to set a property on a single shape
pub fn new(layer_id: Uuid, time: f64, shape_id: Uuid, property: InstancePropertyChange) -> Self {
Self {
layer_id,
instance_changes: vec![(instance_id, None)],
time,
shape_changes: vec![(shape_id, None)],
property,
}
}
/// Create a new action to set a property on multiple instances
pub fn new_batch(layer_id: Uuid, instance_ids: Vec<Uuid>, property: InstancePropertyChange) -> Self {
/// Create a new action to set a property on multiple shapes
pub fn new_batch(layer_id: Uuid, time: f64, shape_ids: Vec<Uuid>, property: InstancePropertyChange) -> Self {
Self {
layer_id,
instance_changes: instance_ids.into_iter().map(|id| (id, None)).collect(),
time,
shape_changes: shape_ids.into_iter().map(|id| (id, None)).collect(),
property,
}
}
fn apply_to_instance(&self, document: &mut Document, instance_id: &Uuid, value: f64) {
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
vector_layer.modify_object_internal(instance_id, |instance| {
match &self.property {
InstancePropertyChange::X(_) => instance.transform.x = value,
InstancePropertyChange::Y(_) => instance.transform.y = value,
InstancePropertyChange::Rotation(_) => instance.transform.rotation = value,
InstancePropertyChange::ScaleX(_) => instance.transform.scale_x = value,
InstancePropertyChange::ScaleY(_) => instance.transform.scale_y = value,
InstancePropertyChange::SkewX(_) => instance.transform.skew_x = value,
InstancePropertyChange::SkewY(_) => instance.transform.skew_y = value,
InstancePropertyChange::Opacity(_) => instance.opacity = value,
}
});
}
fn get_value_from_shape(shape: &crate::shape::Shape, property: &InstancePropertyChange) -> f64 {
match property {
InstancePropertyChange::X(_) => shape.transform.x,
InstancePropertyChange::Y(_) => shape.transform.y,
InstancePropertyChange::Rotation(_) => shape.transform.rotation,
InstancePropertyChange::ScaleX(_) => shape.transform.scale_x,
InstancePropertyChange::ScaleY(_) => shape.transform.scale_y,
InstancePropertyChange::SkewX(_) => shape.transform.skew_x,
InstancePropertyChange::SkewY(_) => shape.transform.skew_y,
InstancePropertyChange::Opacity(_) => shape.opacity,
}
}
fn set_value_on_shape(shape: &mut crate::shape::Shape, property: &InstancePropertyChange, value: f64) {
match property {
InstancePropertyChange::X(_) => shape.transform.x = value,
InstancePropertyChange::Y(_) => shape.transform.y = value,
InstancePropertyChange::Rotation(_) => shape.transform.rotation = value,
InstancePropertyChange::ScaleX(_) => shape.transform.scale_x = value,
InstancePropertyChange::ScaleY(_) => shape.transform.scale_y = value,
InstancePropertyChange::SkewX(_) => shape.transform.skew_x = value,
InstancePropertyChange::SkewY(_) => shape.transform.skew_y = value,
InstancePropertyChange::Opacity(_) => shape.opacity = value,
}
}
}
@@ -91,25 +104,14 @@ impl SetInstancePropertiesAction {
impl Action for SetInstancePropertiesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let new_value = self.property.value();
let layer_id = self.layer_id;
// First pass: collect old values for instances that don't have them yet
for (instance_id, old_value) in &mut self.instance_changes {
if old_value.is_none() {
// Get old value inline to avoid borrow issues
if let Some(layer) = document.get_layer(&layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
if let Some(instance) = vector_layer.get_object(instance_id) {
*old_value = Some(match &self.property {
InstancePropertyChange::X(_) => instance.transform.x,
InstancePropertyChange::Y(_) => instance.transform.y,
InstancePropertyChange::Rotation(_) => instance.transform.rotation,
InstancePropertyChange::ScaleX(_) => instance.transform.scale_x,
InstancePropertyChange::ScaleY(_) => instance.transform.scale_y,
InstancePropertyChange::SkewX(_) => instance.transform.skew_x,
InstancePropertyChange::SkewY(_) => instance.transform.skew_y,
InstancePropertyChange::Opacity(_) => instance.opacity,
});
// First pass: collect old values
if let Some(layer) = document.get_layer(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
for (shape_id, old_value) in &mut self.shape_changes {
if old_value.is_none() {
if let Some(shape) = vector_layer.get_shape_in_keyframe(shape_id, self.time) {
*old_value = Some(Self::get_value_from_shape(shape, &self.property));
}
}
}
@@ -117,16 +119,28 @@ impl Action for SetInstancePropertiesAction {
}
// Second pass: apply new values
for (instance_id, _) in &self.instance_changes {
self.apply_to_instance(document, instance_id, new_value);
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
for (shape_id, _) in &self.shape_changes {
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(shape_id, self.time) {
Self::set_value_on_shape(shape, &self.property, new_value);
}
}
}
}
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
for (instance_id, old_value) in &self.instance_changes {
if let Some(value) = old_value {
self.apply_to_instance(document, instance_id, *value);
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
for (shape_id, old_value) in &self.shape_changes {
if let Some(value) = old_value {
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(shape_id, self.time) {
Self::set_value_on_shape(shape, &self.property, *value);
}
}
}
}
}
Ok(())
@@ -144,10 +158,10 @@ impl Action for SetInstancePropertiesAction {
InstancePropertyChange::Opacity(_) => "opacity",
};
if self.instance_changes.len() == 1 {
if self.shape_changes.len() == 1 {
format!("Set {}", property_name)
} else {
format!("Set {} on {} objects", property_name, self.instance_changes.len())
format!("Set {} on {} shapes", property_name, self.shape_changes.len())
}
}
}
@@ -156,80 +170,46 @@ impl Action for SetInstancePropertiesAction {
mod tests {
use super::*;
use crate::layer::VectorLayer;
use crate::object::{ShapeInstance, Transform};
use crate::shape::Shape;
use vello::kurbo::BezPath;
fn make_shape_at(x: f64, y: f64) -> Shape {
let mut path = BezPath::new();
path.move_to((0.0, 0.0));
path.line_to((10.0, 10.0));
Shape::new(path).with_position(x, y)
}
#[test]
fn test_set_x_position() {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
let shape_id = Uuid::new_v4();
let mut instance = ShapeInstance::new(shape_id);
let instance_id = instance.id;
instance.transform = Transform::with_position(10.0, 20.0);
layer.add_object(instance);
let shape = make_shape_at(10.0, 20.0);
let shape_id = shape.id;
layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Create and execute action
let mut action = SetInstancePropertiesAction::new(
layer_id,
instance_id,
0.0,
shape_id,
InstancePropertyChange::X(50.0),
);
action.execute(&mut document).unwrap();
// Verify position changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.transform.x, 50.0);
assert_eq!(obj.transform.y, 20.0); // Y unchanged
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let s = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(s.transform.x, 50.0);
assert_eq!(s.transform.y, 20.0);
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.transform.x, 10.0);
}
}
#[test]
fn test_set_rotation() {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
let shape_id = Uuid::new_v4();
let mut instance = ShapeInstance::new(shape_id);
let instance_id = instance.id;
instance.transform.rotation = 0.0;
layer.add_object(instance);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Create and execute action
let mut action = SetInstancePropertiesAction::new(
layer_id,
instance_id,
InstancePropertyChange::Rotation(45.0),
);
action.execute(&mut document).unwrap();
// Verify rotation changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.transform.rotation, 45.0);
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.transform.rotation, 0.0);
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let s = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(s.transform.x, 10.0);
}
}
@@ -238,35 +218,30 @@ mod tests {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
let shape_id = Uuid::new_v4();
let mut instance = ShapeInstance::new(shape_id);
let instance_id = instance.id;
instance.opacity = 1.0;
layer.add_object(instance);
let shape = make_shape_at(0.0, 0.0);
let shape_id = shape.id;
layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Create and execute action
let mut action = SetInstancePropertiesAction::new(
layer_id,
instance_id,
0.0,
shape_id,
InstancePropertyChange::Opacity(0.5),
);
action.execute(&mut document).unwrap();
// Verify opacity changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.opacity, 0.5);
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let s = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(s.opacity, 0.5);
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.opacity, 1.0);
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let s = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(s.opacity, 1.0);
}
}
@@ -275,69 +250,59 @@ mod tests {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
let shape_id = Uuid::new_v4();
let shape1 = make_shape_at(0.0, 0.0);
let shape1_id = shape1.id;
let shape2 = make_shape_at(10.0, 10.0);
let shape2_id = shape2.id;
let mut instance1 = ShapeInstance::new(shape_id);
let instance1_id = instance1.id;
instance1.transform.scale_x = 1.0;
let mut instance2 = ShapeInstance::new(shape_id);
let instance2_id = instance2.id;
instance2.transform.scale_x = 1.0;
layer.add_object(instance1);
layer.add_object(instance2);
layer.add_shape_to_keyframe(shape1, 0.0);
layer.add_shape_to_keyframe(shape2, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Create and execute batch action
let mut action = SetInstancePropertiesAction::new_batch(
layer_id,
vec![instance1_id, instance2_id],
0.0,
vec![shape1_id, shape2_id],
InstancePropertyChange::ScaleX(2.0),
);
action.execute(&mut document).unwrap();
// Verify both changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
assert_eq!(vl.get_object(&instance1_id).unwrap().transform.scale_x, 2.0);
assert_eq!(vl.get_object(&instance2_id).unwrap().transform.scale_x, 2.0);
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
assert_eq!(vl.get_shape_in_keyframe(&shape1_id, 0.0).unwrap().transform.scale_x, 2.0);
assert_eq!(vl.get_shape_in_keyframe(&shape2_id, 0.0).unwrap().transform.scale_x, 2.0);
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify both restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
assert_eq!(vl.get_object(&instance1_id).unwrap().transform.scale_x, 1.0);
assert_eq!(vl.get_object(&instance2_id).unwrap().transform.scale_x, 1.0);
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
assert_eq!(vl.get_shape_in_keyframe(&shape1_id, 0.0).unwrap().transform.scale_x, 1.0);
assert_eq!(vl.get_shape_in_keyframe(&shape2_id, 0.0).unwrap().transform.scale_x, 1.0);
}
}
#[test]
fn test_description() {
let layer_id = Uuid::new_v4();
let instance_id = Uuid::new_v4();
let shape_id = Uuid::new_v4();
let action1 = SetInstancePropertiesAction::new(
layer_id,
instance_id,
layer_id, 0.0, shape_id,
InstancePropertyChange::X(0.0),
);
assert_eq!(action1.description(), "Set X position");
let action2 = SetInstancePropertiesAction::new(
layer_id,
instance_id,
layer_id, 0.0, shape_id,
InstancePropertyChange::Rotation(0.0),
);
assert_eq!(action2.description(), "Set rotation");
let action3 = SetInstancePropertiesAction::new_batch(
layer_id,
layer_id, 0.0,
vec![Uuid::new_v4(), Uuid::new_v4()],
InstancePropertyChange::Opacity(1.0),
);
assert_eq!(action3.description(), "Set opacity on 2 objects");
assert_eq!(action3.description(), "Set opacity on 2 shapes");
}
}
@@ -0,0 +1,147 @@
//! Set keyframe action
//!
//! For vector layers: creates a new ShapeKeyframe at the given time by copying
//! shapes from the current keyframe span (with new UUIDs).
//! For clip instances: adds AnimationData keyframes for transform properties.
use crate::action::Action;
use crate::animation::{AnimationCurve, AnimationTarget, Keyframe, TransformProperty};
use crate::document::Document;
use crate::layer::{AnyLayer, ShapeKeyframe};
use uuid::Uuid;
/// Undo info for a clip animation curve
struct ClipUndoEntry {
target: AnimationTarget,
old_keyframe: Option<Keyframe>,
curve_created: bool,
}
pub struct SetKeyframeAction {
layer_id: Uuid,
time: f64,
/// Clip instance IDs to keyframe (motion tweens)
clip_instance_ids: Vec<Uuid>,
/// Whether a shape keyframe was created by this action
shape_keyframe_created: bool,
/// The removed keyframe for rollback (if we created one)
removed_keyframe: Option<ShapeKeyframe>,
/// Clip animation undo entries
clip_undo_entries: Vec<ClipUndoEntry>,
}
impl SetKeyframeAction {
pub fn new(layer_id: Uuid, time: f64, clip_instance_ids: Vec<Uuid>) -> Self {
Self {
layer_id,
time,
clip_instance_ids,
shape_keyframe_created: false,
removed_keyframe: None,
clip_undo_entries: Vec::new(),
}
}
}
const TRANSFORM_PROPERTIES: &[TransformProperty] = &[
TransformProperty::X,
TransformProperty::Y,
TransformProperty::Rotation,
TransformProperty::ScaleX,
TransformProperty::ScaleY,
TransformProperty::SkewX,
TransformProperty::SkewY,
TransformProperty::Opacity,
];
fn transform_default(prop: &TransformProperty) -> f64 {
match prop {
TransformProperty::ScaleX | TransformProperty::ScaleY => 1.0,
TransformProperty::Opacity => 1.0,
_ => 0.0,
}
}
impl Action for SetKeyframeAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
self.clip_undo_entries.clear();
self.shape_keyframe_created = false;
let layer = document
.get_layer_mut(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
// For vector layers: create a shape keyframe
if let AnyLayer::Vector(vl) = layer {
// Check if a keyframe already exists at this exact time
let already_exists = vl.keyframe_index_at_exact(self.time, 0.001).is_some();
if !already_exists {
vl.insert_keyframe_from_current(self.time);
self.shape_keyframe_created = true;
}
// Add clip animation keyframes
for clip_id in &self.clip_instance_ids {
for prop in TRANSFORM_PROPERTIES {
let target = AnimationTarget::Object {
id: *clip_id,
property: *prop,
};
let default = transform_default(prop);
let value = vl.layer.animation_data.eval(&target, self.time, default);
let curve_created = vl.layer.animation_data.get_curve(&target).is_none();
if curve_created {
vl.layer
.animation_data
.set_curve(AnimationCurve::new(target.clone(), default));
}
let curve = vl.layer.animation_data.get_curve_mut(&target).unwrap();
let old_keyframe = curve.get_keyframe_at(self.time, 0.001).cloned();
curve.set_keyframe(Keyframe::linear(self.time, value));
self.clip_undo_entries.push(ClipUndoEntry {
target,
old_keyframe,
curve_created,
});
}
}
}
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let layer = document
.get_layer_mut(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
if let AnyLayer::Vector(vl) = layer {
// Undo clip animation keyframes in reverse order
for entry in self.clip_undo_entries.drain(..).rev() {
if entry.curve_created {
vl.layer.animation_data.remove_curve(&entry.target);
} else if let Some(curve) = vl.layer.animation_data.get_curve_mut(&entry.target) {
curve.remove_keyframe(self.time, 0.001);
if let Some(old_kf) = entry.old_keyframe {
curve.set_keyframe(old_kf);
}
}
}
// Remove the shape keyframe if we created one
if self.shape_keyframe_created {
self.removed_keyframe = vl.remove_keyframe_at(self.time, 0.001);
self.shape_keyframe_created = false;
}
}
Ok(())
}
fn description(&self) -> String {
"New keyframe".to_string()
}
}
@@ -25,6 +25,9 @@ pub struct SetShapePropertiesAction {
/// Shape to modify
shape_id: Uuid,
/// Time of the keyframe containing the shape
time: f64,
/// New property value
new_value: ShapePropertyChange,
@@ -34,28 +37,50 @@ pub struct SetShapePropertiesAction {
impl SetShapePropertiesAction {
/// Create a new action to set a property on a shape
pub fn new(layer_id: Uuid, shape_id: Uuid, new_value: ShapePropertyChange) -> Self {
pub fn new(layer_id: Uuid, shape_id: Uuid, time: f64, new_value: ShapePropertyChange) -> Self {
Self {
layer_id,
shape_id,
time,
new_value,
old_value: None,
}
}
/// Create action to set fill color
pub fn set_fill_color(layer_id: Uuid, shape_id: Uuid, color: Option<ShapeColor>) -> Self {
Self::new(layer_id, shape_id, ShapePropertyChange::FillColor(color))
pub fn set_fill_color(layer_id: Uuid, shape_id: Uuid, time: f64, color: Option<ShapeColor>) -> Self {
Self::new(layer_id, shape_id, time, ShapePropertyChange::FillColor(color))
}
/// Create action to set stroke color
pub fn set_stroke_color(layer_id: Uuid, shape_id: Uuid, color: Option<ShapeColor>) -> Self {
Self::new(layer_id, shape_id, ShapePropertyChange::StrokeColor(color))
pub fn set_stroke_color(layer_id: Uuid, shape_id: Uuid, time: f64, color: Option<ShapeColor>) -> Self {
Self::new(layer_id, shape_id, time, ShapePropertyChange::StrokeColor(color))
}
/// Create action to set stroke width
pub fn set_stroke_width(layer_id: Uuid, shape_id: Uuid, width: f64) -> Self {
Self::new(layer_id, shape_id, ShapePropertyChange::StrokeWidth(width))
pub fn set_stroke_width(layer_id: Uuid, shape_id: Uuid, time: f64, width: f64) -> Self {
Self::new(layer_id, shape_id, time, ShapePropertyChange::StrokeWidth(width))
}
}
fn apply_property(shape: &mut crate::shape::Shape, change: &ShapePropertyChange) {
match change {
ShapePropertyChange::FillColor(color) => {
shape.fill_color = *color;
}
ShapePropertyChange::StrokeColor(color) => {
shape.stroke_color = *color;
}
ShapePropertyChange::StrokeWidth(width) => {
if let Some(ref mut style) = shape.stroke_style {
style.width = *width;
} else {
shape.stroke_style = Some(StrokeStyle {
width: *width,
..Default::default()
});
}
}
}
}
@@ -63,7 +88,7 @@ impl Action for SetShapePropertiesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
if let Some(shape) = vector_layer.shapes.get_mut(&self.shape_id) {
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(&self.shape_id, self.time) {
// Store old value if not already stored
if self.old_value.is_none() {
self.old_value = Some(match &self.new_value {
@@ -84,26 +109,7 @@ impl Action for SetShapePropertiesAction {
});
}
// Apply new value
match &self.new_value {
ShapePropertyChange::FillColor(color) => {
shape.fill_color = *color;
}
ShapePropertyChange::StrokeColor(color) => {
shape.stroke_color = *color;
}
ShapePropertyChange::StrokeWidth(width) => {
if let Some(ref mut style) = shape.stroke_style {
style.width = *width;
} else {
// Create stroke style if it doesn't exist
shape.stroke_style = Some(StrokeStyle {
width: *width,
..Default::default()
});
}
}
}
apply_property(shape, &self.new_value);
}
}
}
@@ -111,23 +117,11 @@ impl Action for SetShapePropertiesAction {
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(old_value) = &self.old_value {
if let Some(old_value) = &self.old_value.clone() {
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
if let Some(shape) = vector_layer.shapes.get_mut(&self.shape_id) {
match old_value {
ShapePropertyChange::FillColor(color) => {
shape.fill_color = *color;
}
ShapePropertyChange::StrokeColor(color) => {
shape.stroke_color = *color;
}
ShapePropertyChange::StrokeWidth(width) => {
if let Some(ref mut style) = shape.stroke_style {
style.width = *width;
}
}
}
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(&self.shape_id, self.time) {
apply_property(shape, old_value);
}
}
}
@@ -149,7 +143,7 @@ mod tests {
use super::*;
use crate::layer::VectorLayer;
use crate::shape::Shape;
use kurbo::BezPath;
use vello::kurbo::BezPath;
fn create_test_shape() -> Shape {
let mut path = BezPath::new();
@@ -176,24 +170,24 @@ mod tests {
let shape = create_test_shape();
let shape_id = shape.id;
layer.shapes.insert(shape_id, shape);
layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Verify initial color
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let shape = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(shape.fill_color.unwrap().r, 255);
}
// Create and execute action
let new_color = Some(ShapeColor::rgb(0, 255, 0));
let mut action = SetShapePropertiesAction::set_fill_color(layer_id, shape_id, new_color);
let mut action = SetShapePropertiesAction::set_fill_color(layer_id, shape_id, 0.0, new_color);
action.execute(&mut document).unwrap();
// Verify color changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let shape = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(shape.fill_color.unwrap().g, 255);
}
@@ -201,8 +195,8 @@ mod tests {
action.rollback(&mut document).unwrap();
// Verify restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let shape = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(shape.fill_color.unwrap().r, 255);
}
}
@@ -214,23 +208,17 @@ mod tests {
let shape = create_test_shape();
let shape_id = shape.id;
layer.shapes.insert(shape_id, shape);
layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Verify initial width
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
assert_eq!(shape.stroke_style.as_ref().unwrap().width, 2.0);
}
// Create and execute action
let mut action = SetShapePropertiesAction::set_stroke_width(layer_id, shape_id, 5.0);
let mut action = SetShapePropertiesAction::set_stroke_width(layer_id, shape_id, 0.0, 5.0);
action.execute(&mut document).unwrap();
// Verify width changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let shape = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(shape.stroke_style.as_ref().unwrap().width, 5.0);
}
@@ -238,8 +226,8 @@ mod tests {
action.rollback(&mut document).unwrap();
// Verify restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let shape = vl.shapes.get(&shape_id).unwrap();
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let shape = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(shape.stroke_style.as_ref().unwrap().width, 2.0);
}
}
@@ -250,14 +238,14 @@ mod tests {
let shape_id = Uuid::new_v4();
let action1 =
SetShapePropertiesAction::set_fill_color(layer_id, shape_id, Some(ShapeColor::rgb(0, 0, 0)));
SetShapePropertiesAction::set_fill_color(layer_id, shape_id, 0.0, Some(ShapeColor::rgb(0, 0, 0)));
assert_eq!(action1.description(), "Set fill color");
let action2 =
SetShapePropertiesAction::set_stroke_color(layer_id, shape_id, Some(ShapeColor::rgb(0, 0, 0)));
SetShapePropertiesAction::set_stroke_color(layer_id, shape_id, 0.0, Some(ShapeColor::rgb(0, 0, 0)));
assert_eq!(action2.description(), "Set stroke color");
let action3 = SetShapePropertiesAction::set_stroke_width(layer_id, shape_id, 3.0);
let action3 = SetShapePropertiesAction::set_stroke_width(layer_id, shape_id, 0.0, 3.0);
assert_eq!(action3.description(), "Set stroke width");
}
}
@@ -1,8 +1,10 @@
//! Transform clip instances action
//!
//! Handles spatial transformation (move, scale, rotate) of clip instances on the stage.
//! Updates both the clip instance's transform and the animation keyframe at the current time.
use crate::action::Action;
use crate::animation::{AnimationTarget, Keyframe, TransformProperty};
use crate::document::Document;
use crate::layer::AnyLayer;
use crate::object::Transform;
@@ -12,6 +14,8 @@ use uuid::Uuid;
/// Action that transforms clip instances spatially on the stage
pub struct TransformClipInstancesAction {
layer_id: Uuid,
/// Current time for animation keyframe update
time: f64,
/// Map of clip instance ID to (old transform, new transform)
clip_instance_transforms: HashMap<Uuid, (Transform, Transform)>,
}
@@ -19,15 +23,48 @@ pub struct TransformClipInstancesAction {
impl TransformClipInstancesAction {
pub fn new(
layer_id: Uuid,
time: f64,
clip_instance_transforms: HashMap<Uuid, (Transform, Transform)>,
) -> Self {
Self {
layer_id,
time,
clip_instance_transforms,
}
}
}
/// Update animation keyframes for a clip instance's transform properties at the given time.
/// If a curve exists for a property, updates the keyframe at that time. If no curve exists, does nothing.
fn update_animation_keyframes(
animation_data: &mut crate::animation::AnimationData,
instance_id: Uuid,
transform: &Transform,
opacity: f64,
time: f64,
) {
let props_and_values = [
(TransformProperty::X, transform.x),
(TransformProperty::Y, transform.y),
(TransformProperty::Rotation, transform.rotation),
(TransformProperty::ScaleX, transform.scale_x),
(TransformProperty::ScaleY, transform.scale_y),
(TransformProperty::SkewX, transform.skew_x),
(TransformProperty::SkewY, transform.skew_y),
(TransformProperty::Opacity, opacity),
];
for (prop, value) in props_and_values {
let target = AnimationTarget::Object {
id: instance_id,
property: prop,
};
if let Some(curve) = animation_data.get_curve_mut(&target) {
curve.set_keyframe(Keyframe::linear(time, value));
}
}
}
impl Action for TransformClipInstancesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let layer = match document.get_layer_mut(&self.layer_id) {
@@ -35,19 +72,33 @@ impl Action for TransformClipInstancesAction {
None => return Ok(()),
};
// Get mutable reference to clip_instances for this layer type
let clip_instances = match layer {
AnyLayer::Vector(vl) => &mut vl.clip_instances,
AnyLayer::Audio(al) => &mut al.clip_instances,
AnyLayer::Video(vl) => &mut vl.clip_instances,
AnyLayer::Effect(_) => return Ok(()), // Effect layers don't have clip instances
};
// Apply new transforms
for (clip_id, (_old, new)) in &self.clip_instance_transforms {
if let Some(clip_instance) = clip_instances.iter_mut().find(|ci| ci.id == *clip_id) {
clip_instance.transform = new.clone();
match layer {
AnyLayer::Vector(vl) => {
for (clip_id, (_old, new)) in &self.clip_instance_transforms {
if let Some(clip_instance) = vl.clip_instances.iter_mut().find(|ci| ci.id == *clip_id) {
let opacity = clip_instance.opacity;
clip_instance.transform = new.clone();
update_animation_keyframes(
&mut vl.layer.animation_data, *clip_id, new, opacity, self.time,
);
}
}
}
AnyLayer::Audio(al) => {
for (clip_id, (_old, new)) in &self.clip_instance_transforms {
if let Some(ci) = al.clip_instances.iter_mut().find(|ci| ci.id == *clip_id) {
ci.transform = new.clone();
}
}
}
AnyLayer::Video(vl) => {
for (clip_id, (_old, new)) in &self.clip_instance_transforms {
if let Some(ci) = vl.clip_instances.iter_mut().find(|ci| ci.id == *clip_id) {
ci.transform = new.clone();
}
}
}
AnyLayer::Effect(_) => {}
}
Ok(())
}
@@ -58,19 +109,33 @@ impl Action for TransformClipInstancesAction {
None => return Ok(()),
};
// Get mutable reference to clip_instances for this layer type
let clip_instances = match layer {
AnyLayer::Vector(vl) => &mut vl.clip_instances,
AnyLayer::Audio(al) => &mut al.clip_instances,
AnyLayer::Video(vl) => &mut vl.clip_instances,
AnyLayer::Effect(_) => return Ok(()), // Effect layers don't have clip instances
};
// Restore old transforms
for (clip_id, (old, _new)) in &self.clip_instance_transforms {
if let Some(clip_instance) = clip_instances.iter_mut().find(|ci| ci.id == *clip_id) {
clip_instance.transform = old.clone();
match layer {
AnyLayer::Vector(vl) => {
for (clip_id, (old, _new)) in &self.clip_instance_transforms {
if let Some(clip_instance) = vl.clip_instances.iter_mut().find(|ci| ci.id == *clip_id) {
let opacity = clip_instance.opacity;
clip_instance.transform = old.clone();
update_animation_keyframes(
&mut vl.layer.animation_data, *clip_id, old, opacity, self.time,
);
}
}
}
AnyLayer::Audio(al) => {
for (clip_id, (old, _new)) in &self.clip_instance_transforms {
if let Some(ci) = al.clip_instances.iter_mut().find(|ci| ci.id == *clip_id) {
ci.transform = old.clone();
}
}
}
AnyLayer::Video(vl) => {
for (clip_id, (old, _new)) in &self.clip_instance_transforms {
if let Some(ci) = vl.clip_instances.iter_mut().find(|ci| ci.id == *clip_id) {
ci.transform = old.clone();
}
}
}
AnyLayer::Effect(_) => {}
}
Ok(())
}
@@ -94,7 +159,6 @@ mod tests {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
// Create a clip instance with initial transform
let clip_id = Uuid::new_v4();
let instance_id = Uuid::new_v4();
let mut instance = ClipInstance::with_id(instance_id, clip_id);
@@ -103,18 +167,14 @@ mod tests {
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Create transform action: move from (10, 20) to (100, 200)
let old_transform = Transform::with_position(10.0, 20.0);
let new_transform = Transform::with_position(100.0, 200.0);
let mut transforms = HashMap::new();
transforms.insert(instance_id, (old_transform, new_transform));
let mut action = TransformClipInstancesAction::new(layer_id, transforms);
// Execute action
let mut action = TransformClipInstancesAction::new(layer_id, 0.0, transforms);
action.execute(&mut document).unwrap();
// Verify transform changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let inst = vl.clip_instances.iter().find(|ci| ci.id == instance_id).unwrap();
assert_eq!(inst.transform.x, 100.0);
@@ -123,10 +183,8 @@ mod tests {
panic!("Layer not found");
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify transform restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let inst = vl.clip_instances.iter().find(|ci| ci.id == instance_id).unwrap();
assert_eq!(inst.transform.x, 10.0);
@@ -141,7 +199,6 @@ mod tests {
let mut document = Document::new("Test");
let mut layer = AudioLayer::new("Audio Layer");
// Create a clip instance
let clip_id = Uuid::new_v4();
let instance_id = Uuid::new_v4();
let mut instance = ClipInstance::with_id(instance_id, clip_id);
@@ -150,16 +207,14 @@ mod tests {
let layer_id = document.root_mut().add_child(AnyLayer::Audio(layer));
// Create transform action
let old_transform = Transform::with_position(0.0, 0.0);
let new_transform = Transform::with_position(50.0, 75.0);
let mut transforms = HashMap::new();
transforms.insert(instance_id, (old_transform, new_transform));
let mut action = TransformClipInstancesAction::new(layer_id, transforms);
let mut action = TransformClipInstancesAction::new(layer_id, 0.0, transforms);
action.execute(&mut document).unwrap();
// Verify
if let Some(AnyLayer::Audio(al)) = document.get_layer_mut(&layer_id) {
let inst = al.clip_instances.iter().find(|ci| ci.id == instance_id).unwrap();
assert_eq!(inst.transform.x, 50.0);
@@ -174,7 +229,6 @@ mod tests {
let mut document = Document::new("Test");
let mut layer = VideoLayer::new("Video Layer");
// Create a clip instance
let clip_id = Uuid::new_v4();
let instance_id = Uuid::new_v4();
let mut instance = ClipInstance::with_id(instance_id, clip_id);
@@ -184,7 +238,6 @@ mod tests {
let layer_id = document.root_mut().add_child(AnyLayer::Video(layer));
// Create transform with rotation and scale
let mut old_transform = Transform::new();
old_transform.rotation = 0.0;
old_transform.scale_x = 1.0;
@@ -197,10 +250,9 @@ mod tests {
let mut transforms = HashMap::new();
transforms.insert(instance_id, (old_transform, new_transform));
let mut action = TransformClipInstancesAction::new(layer_id, transforms);
let mut action = TransformClipInstancesAction::new(layer_id, 0.0, transforms);
action.execute(&mut document).unwrap();
// Verify rotation and scale
if let Some(AnyLayer::Video(vl)) = document.get_layer_mut(&layer_id) {
let inst = vl.clip_instances.iter().find(|ci| ci.id == instance_id).unwrap();
assert_eq!(inst.transform.rotation, 45.0);
@@ -216,7 +268,6 @@ mod tests {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
// Create two clip instances
let clip_id = Uuid::new_v4();
let instance1_id = Uuid::new_v4();
let instance2_id = Uuid::new_v4();
@@ -232,7 +283,6 @@ mod tests {
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Transform both instances
let mut transforms = HashMap::new();
transforms.insert(
instance1_id,
@@ -243,10 +293,9 @@ mod tests {
(Transform::with_position(100.0, 100.0), Transform::with_position(150.0, 150.0)),
);
let mut action = TransformClipInstancesAction::new(layer_id, transforms);
let mut action = TransformClipInstancesAction::new(layer_id, 0.0, transforms);
action.execute(&mut document).unwrap();
// Verify both transformed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let inst1 = vl.clip_instances.iter().find(|ci| ci.id == instance1_id).unwrap();
assert_eq!(inst1.transform.x, 50.0);
@@ -259,10 +308,8 @@ mod tests {
panic!("Layer not found");
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify both restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let inst1 = vl.clip_instances.iter().find(|ci| ci.id == instance1_id).unwrap();
assert_eq!(inst1.transform.x, 0.0);
@@ -276,25 +323,6 @@ mod tests {
}
}
#[test]
fn test_transform_nonexistent_layer() {
let mut document = Document::new("Test");
let fake_layer_id = Uuid::new_v4();
let instance_id = Uuid::new_v4();
let mut transforms = HashMap::new();
transforms.insert(
instance_id,
(Transform::with_position(0.0, 0.0), Transform::with_position(50.0, 50.0)),
);
let mut action = TransformClipInstancesAction::new(fake_layer_id, transforms);
// Should not panic, just return early
action.execute(&mut document).unwrap();
action.rollback(&mut document).unwrap();
}
#[test]
fn test_description() {
let layer_id = Uuid::new_v4();
@@ -306,16 +334,7 @@ mod tests {
(Transform::new(), Transform::with_position(10.0, 10.0)),
);
let action = TransformClipInstancesAction::new(layer_id, transforms);
let action = TransformClipInstancesAction::new(layer_id, 0.0, transforms);
assert_eq!(action.description(), "Transform 1 clip instance(s)");
// Multiple instances
let mut transforms2 = HashMap::new();
transforms2.insert(Uuid::new_v4(), (Transform::new(), Transform::new()));
transforms2.insert(Uuid::new_v4(), (Transform::new(), Transform::new()));
transforms2.insert(Uuid::new_v4(), (Transform::new(), Transform::new()));
let action2 = TransformClipInstancesAction::new(layer_id, transforms2);
assert_eq!(action2.description(), "Transform 3 clip instance(s)");
}
}
@@ -1,6 +1,6 @@
//! Transform shape instances action
//! Transform shapes action
//!
//! Applies scale, rotation, and other transformations to shape instances with undo/redo support.
//! Applies scale, rotation, and other transformations to shapes in a keyframe.
use crate::action::Action;
use crate::document::Document;
@@ -9,22 +9,24 @@ use crate::object::Transform;
use std::collections::HashMap;
use uuid::Uuid;
/// Action to transform multiple shape instances
/// Action to transform multiple shapes in a keyframe
pub struct TransformShapeInstancesAction {
layer_id: Uuid,
/// Map of shape instance ID to (old transform, new transform)
shape_instance_transforms: HashMap<Uuid, (Transform, Transform)>,
time: f64,
/// Map of shape ID to (old transform, new transform)
shape_transforms: HashMap<Uuid, (Transform, Transform)>,
}
impl TransformShapeInstancesAction {
/// Create a new transform action
pub fn new(
layer_id: Uuid,
shape_instance_transforms: HashMap<Uuid, (Transform, Transform)>,
time: f64,
shape_transforms: HashMap<Uuid, (Transform, Transform)>,
) -> Self {
Self {
layer_id,
shape_instance_transforms,
time,
shape_transforms,
}
}
}
@@ -33,10 +35,10 @@ impl Action for TransformShapeInstancesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
for (shape_instance_id, (_old, new)) in &self.shape_instance_transforms {
vector_layer.modify_object_internal(shape_instance_id, |obj| {
obj.transform = new.clone();
});
for (shape_id, (_old, new)) in &self.shape_transforms {
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(shape_id, self.time) {
shape.transform = new.clone();
}
}
}
}
@@ -46,10 +48,10 @@ impl Action for TransformShapeInstancesAction {
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
if let AnyLayer::Vector(vector_layer) = layer {
for (shape_instance_id, (old, _new)) in &self.shape_instance_transforms {
vector_layer.modify_object_internal(shape_instance_id, |obj| {
obj.transform = old.clone();
});
for (shape_id, (old, _new)) in &self.shape_transforms {
if let Some(shape) = vector_layer.get_shape_in_keyframe_mut(shape_id, self.time) {
shape.transform = old.clone();
}
}
}
}
@@ -57,7 +59,7 @@ impl Action for TransformShapeInstancesAction {
}
fn description(&self) -> String {
format!("Transform {} shape instance(s)", self.shape_instance_transforms.len())
format!("Transform {} shape(s)", self.shape_transforms.len())
}
}
@@ -65,239 +67,43 @@ impl Action for TransformShapeInstancesAction {
mod tests {
use super::*;
use crate::layer::VectorLayer;
use crate::object::ShapeInstance;
use crate::shape::Shape;
use vello::kurbo::BezPath;
#[test]
fn test_transform_single_shape_instance() {
fn test_transform_shape() {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
// Create a shape instance with initial position
let shape_id = Uuid::new_v4();
let instance_id = Uuid::new_v4();
let mut instance = ShapeInstance::new(shape_id);
instance.id = instance_id;
instance.transform = Transform::with_position(10.0, 20.0);
layer.add_object(instance);
let mut path = BezPath::new();
path.move_to((0.0, 0.0));
path.line_to((100.0, 100.0));
let shape = Shape::new(path).with_position(10.0, 20.0);
let shape_id = shape.id;
layer.add_shape_to_keyframe(shape, 0.0);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Create transform action
let old_transform = Transform::with_position(10.0, 20.0);
let new_transform = Transform::with_position(100.0, 200.0);
let mut transforms = HashMap::new();
transforms.insert(instance_id, (old_transform, new_transform));
transforms.insert(shape_id, (old_transform, new_transform));
let mut action = TransformShapeInstancesAction::new(layer_id, transforms);
// Execute
let mut action = TransformShapeInstancesAction::new(layer_id, 0.0, transforms);
action.execute(&mut document).unwrap();
// Verify transform changed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.transform.x, 100.0);
assert_eq!(obj.transform.y, 200.0);
} else {
panic!("Layer not found");
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let s = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(s.transform.x, 100.0);
assert_eq!(s.transform.y, 200.0);
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.transform.x, 10.0);
assert_eq!(obj.transform.y, 20.0);
} else {
panic!("Layer not found");
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
let s = vl.get_shape_in_keyframe(&shape_id, 0.0).unwrap();
assert_eq!(s.transform.x, 10.0);
assert_eq!(s.transform.y, 20.0);
}
}
#[test]
fn test_transform_shape_instance_rotation_scale() {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
let shape_id = Uuid::new_v4();
let instance_id = Uuid::new_v4();
let mut instance = ShapeInstance::new(shape_id);
instance.id = instance_id;
instance.transform.rotation = 0.0;
instance.transform.scale_x = 1.0;
instance.transform.scale_y = 1.0;
layer.add_object(instance);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Create transform with rotation and scale
let mut old_transform = Transform::new();
let mut new_transform = Transform::new();
new_transform.rotation = 90.0;
new_transform.scale_x = 2.0;
new_transform.scale_y = 0.5;
let mut transforms = HashMap::new();
transforms.insert(instance_id, (old_transform, new_transform));
let mut action = TransformShapeInstancesAction::new(layer_id, transforms);
action.execute(&mut document).unwrap();
// Verify
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj = vl.get_object(&instance_id).unwrap();
assert_eq!(obj.transform.rotation, 90.0);
assert_eq!(obj.transform.scale_x, 2.0);
assert_eq!(obj.transform.scale_y, 0.5);
} else {
panic!("Layer not found");
}
}
#[test]
fn test_transform_multiple_shape_instances() {
let mut document = Document::new("Test");
let mut layer = VectorLayer::new("Test Layer");
let shape_id = Uuid::new_v4();
let instance1_id = Uuid::new_v4();
let instance2_id = Uuid::new_v4();
let mut instance1 = ShapeInstance::new(shape_id);
instance1.id = instance1_id;
instance1.transform = Transform::with_position(0.0, 0.0);
let mut instance2 = ShapeInstance::new(shape_id);
instance2.id = instance2_id;
instance2.transform = Transform::with_position(50.0, 50.0);
layer.add_object(instance1);
layer.add_object(instance2);
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
// Transform both
let mut transforms = HashMap::new();
transforms.insert(
instance1_id,
(Transform::with_position(0.0, 0.0), Transform::with_position(10.0, 10.0)),
);
transforms.insert(
instance2_id,
(Transform::with_position(50.0, 50.0), Transform::with_position(60.0, 60.0)),
);
let mut action = TransformShapeInstancesAction::new(layer_id, transforms);
action.execute(&mut document).unwrap();
// Verify both transformed
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj1 = vl.get_object(&instance1_id).unwrap();
assert_eq!(obj1.transform.x, 10.0);
assert_eq!(obj1.transform.y, 10.0);
let obj2 = vl.get_object(&instance2_id).unwrap();
assert_eq!(obj2.transform.x, 60.0);
assert_eq!(obj2.transform.y, 60.0);
} else {
panic!("Layer not found");
}
// Rollback
action.rollback(&mut document).unwrap();
// Verify both restored
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
let obj1 = vl.get_object(&instance1_id).unwrap();
assert_eq!(obj1.transform.x, 0.0);
assert_eq!(obj1.transform.y, 0.0);
let obj2 = vl.get_object(&instance2_id).unwrap();
assert_eq!(obj2.transform.x, 50.0);
assert_eq!(obj2.transform.y, 50.0);
} else {
panic!("Layer not found");
}
}
#[test]
fn test_transform_nonexistent_layer() {
let mut document = Document::new("Test");
let fake_layer_id = Uuid::new_v4();
let instance_id = Uuid::new_v4();
let mut transforms = HashMap::new();
transforms.insert(
instance_id,
(Transform::new(), Transform::with_position(10.0, 10.0)),
);
let mut action = TransformShapeInstancesAction::new(fake_layer_id, transforms);
// Should not panic
action.execute(&mut document).unwrap();
action.rollback(&mut document).unwrap();
}
#[test]
fn test_transform_nonexistent_instance() {
let mut document = Document::new("Test");
let layer = VectorLayer::new("Test Layer");
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
let fake_instance_id = Uuid::new_v4();
let mut transforms = HashMap::new();
transforms.insert(
fake_instance_id,
(Transform::new(), Transform::with_position(10.0, 10.0)),
);
let mut action = TransformShapeInstancesAction::new(layer_id, transforms);
// Should not panic - just silently skip nonexistent instance
action.execute(&mut document).unwrap();
action.rollback(&mut document).unwrap();
}
#[test]
fn test_transform_on_non_vector_layer() {
use crate::layer::AudioLayer;
let mut document = Document::new("Test");
let layer = AudioLayer::new("Audio Layer");
let layer_id = document.root_mut().add_child(AnyLayer::Audio(layer));
let instance_id = Uuid::new_v4();
let mut transforms = HashMap::new();
transforms.insert(
instance_id,
(Transform::new(), Transform::with_position(10.0, 10.0)),
);
let mut action = TransformShapeInstancesAction::new(layer_id, transforms);
// Should not panic - action only operates on vector layers
action.execute(&mut document).unwrap();
action.rollback(&mut document).unwrap();
}
#[test]
fn test_description() {
let layer_id = Uuid::new_v4();
let mut transforms1 = HashMap::new();
transforms1.insert(Uuid::new_v4(), (Transform::new(), Transform::new()));
let action1 = TransformShapeInstancesAction::new(layer_id, transforms1);
assert_eq!(action1.description(), "Transform 1 shape instance(s)");
let mut transforms3 = HashMap::new();
transforms3.insert(Uuid::new_v4(), (Transform::new(), Transform::new()));
transforms3.insert(Uuid::new_v4(), (Transform::new(), Transform::new()));
transforms3.insert(Uuid::new_v4(), (Transform::new(), Transform::new()));
let action3 = TransformShapeInstancesAction::new(layer_id, transforms3);
assert_eq!(action3.description(), "Transform 3 shape instance(s)");
}
}