Select and move shapes
This commit is contained in:
@@ -0,0 +1,277 @@
|
||||
//! Action system for undo/redo functionality
|
||||
//!
|
||||
//! This module provides a type-safe action system that ensures document
|
||||
//! mutations can only happen through actions, enforced by Rust's type system.
|
||||
//!
|
||||
//! ## Architecture
|
||||
//!
|
||||
//! - `Action` trait: Defines execute() and rollback() operations
|
||||
//! - `ActionExecutor`: Wraps the document and manages undo/redo stacks
|
||||
//! - Document mutations are only accessible via `pub(crate)` methods
|
||||
//! - External code gets read-only access via `ActionExecutor::document()`
|
||||
|
||||
use crate::document::Document;
|
||||
|
||||
/// Action trait for undo/redo operations
|
||||
///
|
||||
/// Each action must be able to execute (apply changes) and rollback (undo changes).
|
||||
/// Actions are stored in the undo stack and can be re-executed from the redo stack.
|
||||
pub trait Action: Send {
|
||||
/// Apply this action to the document
|
||||
fn execute(&mut self, document: &mut Document);
|
||||
|
||||
/// Undo this action (rollback changes)
|
||||
fn rollback(&mut self, document: &mut Document);
|
||||
|
||||
/// Get a human-readable description of this action (for UI display)
|
||||
fn description(&self) -> String;
|
||||
}
|
||||
|
||||
/// Action executor that wraps the document and manages undo/redo
|
||||
///
|
||||
/// This is the only way to get mutable access to the document, ensuring
|
||||
/// all mutations go through the action system.
|
||||
pub struct ActionExecutor {
|
||||
/// The document being edited
|
||||
document: Document,
|
||||
|
||||
/// Stack of executed actions (for undo)
|
||||
undo_stack: Vec<Box<dyn Action>>,
|
||||
|
||||
/// Stack of undone actions (for redo)
|
||||
redo_stack: Vec<Box<dyn Action>>,
|
||||
|
||||
/// Maximum number of actions to keep in undo stack
|
||||
max_undo_depth: usize,
|
||||
}
|
||||
|
||||
impl ActionExecutor {
|
||||
/// Create a new action executor with the given document
|
||||
pub fn new(document: Document) -> Self {
|
||||
Self {
|
||||
document,
|
||||
undo_stack: Vec::new(),
|
||||
redo_stack: Vec::new(),
|
||||
max_undo_depth: 100, // Default: keep last 100 actions
|
||||
}
|
||||
}
|
||||
|
||||
/// Get read-only access to the document
|
||||
///
|
||||
/// This is the public API for reading document state.
|
||||
/// Mutations must go through execute() which requires an Action.
|
||||
pub fn document(&self) -> &Document {
|
||||
&self.document
|
||||
}
|
||||
|
||||
/// Execute an action and add it to the undo stack
|
||||
///
|
||||
/// This clears the redo stack since we're creating a new timeline branch.
|
||||
pub fn execute(&mut self, mut action: Box<dyn Action>) {
|
||||
// Apply the action
|
||||
action.execute(&mut self.document);
|
||||
|
||||
// Clear redo stack (new action invalidates redo history)
|
||||
self.redo_stack.clear();
|
||||
|
||||
// Add to undo stack
|
||||
self.undo_stack.push(action);
|
||||
|
||||
// Limit undo stack size
|
||||
if self.undo_stack.len() > self.max_undo_depth {
|
||||
self.undo_stack.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo the last action
|
||||
///
|
||||
/// Returns true if an action was undone, false if undo stack is empty.
|
||||
pub fn undo(&mut self) -> bool {
|
||||
if let Some(mut action) = self.undo_stack.pop() {
|
||||
// Rollback the action
|
||||
action.rollback(&mut self.document);
|
||||
|
||||
// Move to redo stack
|
||||
self.redo_stack.push(action);
|
||||
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Redo the last undone action
|
||||
///
|
||||
/// Returns true if an action was redone, false if redo stack is empty.
|
||||
pub fn redo(&mut self) -> bool {
|
||||
if let Some(mut action) = self.redo_stack.pop() {
|
||||
// Re-execute the action
|
||||
action.execute(&mut self.document);
|
||||
|
||||
// Move back to undo stack
|
||||
self.undo_stack.push(action);
|
||||
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if undo is available
|
||||
pub fn can_undo(&self) -> bool {
|
||||
!self.undo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Check if redo is available
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.redo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Get the description of the next action to undo
|
||||
pub fn undo_description(&self) -> Option<String> {
|
||||
self.undo_stack.last().map(|a| a.description())
|
||||
}
|
||||
|
||||
/// Get the description of the next action to redo
|
||||
pub fn redo_description(&self) -> Option<String> {
|
||||
self.redo_stack.last().map(|a| a.description())
|
||||
}
|
||||
|
||||
/// Get the number of actions in the undo stack
|
||||
pub fn undo_depth(&self) -> usize {
|
||||
self.undo_stack.len()
|
||||
}
|
||||
|
||||
/// Get the number of actions in the redo stack
|
||||
pub fn redo_depth(&self) -> usize {
|
||||
self.redo_stack.len()
|
||||
}
|
||||
|
||||
/// Clear all undo/redo history
|
||||
pub fn clear_history(&mut self) {
|
||||
self.undo_stack.clear();
|
||||
self.redo_stack.clear();
|
||||
}
|
||||
|
||||
/// Set the maximum undo depth
|
||||
pub fn set_max_undo_depth(&mut self, depth: usize) {
|
||||
self.max_undo_depth = depth;
|
||||
|
||||
// Trim undo stack if needed
|
||||
if self.undo_stack.len() > depth {
|
||||
let remove_count = self.undo_stack.len() - depth;
|
||||
self.undo_stack.drain(0..remove_count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Test action that just tracks execute/rollback calls
|
||||
struct TestAction {
|
||||
description: String,
|
||||
executed: bool,
|
||||
}
|
||||
|
||||
impl TestAction {
|
||||
fn new(description: &str) -> Self {
|
||||
Self {
|
||||
description: description.to_string(),
|
||||
executed: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for TestAction {
|
||||
fn execute(&mut self, _document: &mut Document) {
|
||||
self.executed = true;
|
||||
}
|
||||
|
||||
fn rollback(&mut self, _document: &mut Document) {
|
||||
self.executed = false;
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
self.description.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_action_executor_basic() {
|
||||
let document = Document::new("Test");
|
||||
let mut executor = ActionExecutor::new(document);
|
||||
|
||||
assert!(!executor.can_undo());
|
||||
assert!(!executor.can_redo());
|
||||
|
||||
// Execute an action
|
||||
let action = Box::new(TestAction::new("Test Action"));
|
||||
executor.execute(action);
|
||||
|
||||
assert!(executor.can_undo());
|
||||
assert!(!executor.can_redo());
|
||||
assert_eq!(executor.undo_depth(), 1);
|
||||
|
||||
// Undo
|
||||
assert!(executor.undo());
|
||||
assert!(!executor.can_undo());
|
||||
assert!(executor.can_redo());
|
||||
assert_eq!(executor.redo_depth(), 1);
|
||||
|
||||
// Redo
|
||||
assert!(executor.redo());
|
||||
assert!(executor.can_undo());
|
||||
assert!(!executor.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_action_descriptions() {
|
||||
let document = Document::new("Test");
|
||||
let mut executor = ActionExecutor::new(document);
|
||||
|
||||
executor.execute(Box::new(TestAction::new("Action 1")));
|
||||
executor.execute(Box::new(TestAction::new("Action 2")));
|
||||
|
||||
assert_eq!(executor.undo_description(), Some("Action 2".to_string()));
|
||||
|
||||
executor.undo();
|
||||
assert_eq!(executor.redo_description(), Some("Action 2".to_string()));
|
||||
assert_eq!(executor.undo_description(), Some("Action 1".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_action_clears_redo() {
|
||||
let document = Document::new("Test");
|
||||
let mut executor = ActionExecutor::new(document);
|
||||
|
||||
executor.execute(Box::new(TestAction::new("Action 1")));
|
||||
executor.execute(Box::new(TestAction::new("Action 2")));
|
||||
executor.undo();
|
||||
|
||||
assert!(executor.can_redo());
|
||||
|
||||
// Execute new action should clear redo stack
|
||||
executor.execute(Box::new(TestAction::new("Action 3")));
|
||||
|
||||
assert!(!executor.can_redo());
|
||||
assert_eq!(executor.undo_depth(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_max_undo_depth() {
|
||||
let document = Document::new("Test");
|
||||
let mut executor = ActionExecutor::new(document);
|
||||
executor.set_max_undo_depth(3);
|
||||
|
||||
executor.execute(Box::new(TestAction::new("Action 1")));
|
||||
executor.execute(Box::new(TestAction::new("Action 2")));
|
||||
executor.execute(Box::new(TestAction::new("Action 3")));
|
||||
executor.execute(Box::new(TestAction::new("Action 4")));
|
||||
|
||||
// Should only keep last 3
|
||||
assert_eq!(executor.undo_depth(), 3);
|
||||
assert_eq!(executor.undo_description(), Some("Action 4".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Action implementations for document editing
|
||||
//!
|
||||
//! This module contains all the concrete action types that can be executed
|
||||
//! through the action system.
|
||||
|
||||
pub mod move_objects;
|
||||
|
||||
pub use move_objects::MoveObjectsAction;
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Move objects action
|
||||
//!
|
||||
//! Handles moving one or more objects to new positions.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
use vello::kurbo::Point;
|
||||
|
||||
/// Action that moves objects to new positions
|
||||
pub struct MoveObjectsAction {
|
||||
/// Layer ID containing the objects
|
||||
layer_id: Uuid,
|
||||
|
||||
/// Map of object IDs to their old and new positions
|
||||
object_positions: HashMap<Uuid, (Point, Point)>, // (old_pos, new_pos)
|
||||
}
|
||||
|
||||
impl MoveObjectsAction {
|
||||
/// Create a new move objects action
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `layer_id` - The layer containing the objects
|
||||
/// * `object_positions` - Map of object IDs to (old_position, new_position)
|
||||
pub fn new(layer_id: Uuid, object_positions: HashMap<Uuid, (Point, Point)>) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
object_positions,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for MoveObjectsAction {
|
||||
fn execute(&mut self, document: &mut Document) {
|
||||
let layer = match document.get_layer_mut(&self.layer_id) {
|
||||
Some(l) => l,
|
||||
None => return,
|
||||
};
|
||||
|
||||
if let AnyLayer::Vector(vector_layer) = layer {
|
||||
for (object_id, (_old, new)) in &self.object_positions {
|
||||
vector_layer.modify_object_internal(object_id, |obj| {
|
||||
obj.transform.x = new.x;
|
||||
obj.transform.y = new.y;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) {
|
||||
let layer = match document.get_layer_mut(&self.layer_id) {
|
||||
Some(l) => l,
|
||||
None => return,
|
||||
};
|
||||
|
||||
if let AnyLayer::Vector(vector_layer) = layer {
|
||||
for (object_id, (old, _new)) in &self.object_positions {
|
||||
vector_layer.modify_object_internal(object_id, |obj| {
|
||||
obj.transform.x = old.x;
|
||||
obj.transform.y = old.y;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
let count = self.object_positions.len();
|
||||
if count == 1 {
|
||||
"Move object".to_string()
|
||||
} else {
|
||||
format!("Move {} objects", count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::layer::VectorLayer;
|
||||
use crate::object::Object;
|
||||
use crate::shape::Shape;
|
||||
use vello::kurbo::{Circle, Shape as KurboShape};
|
||||
|
||||
#[test]
|
||||
fn test_move_objects_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 = Object::new(shape.id).with_position(50.0, 50.0);
|
||||
|
||||
let mut vector_layer = VectorLayer::new("Layer 1");
|
||||
vector_layer.add_shape(shape);
|
||||
let object_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(
|
||||
object_id,
|
||||
(Point::new(50.0, 50.0), Point::new(150.0, 200.0))
|
||||
);
|
||||
|
||||
let mut action = MoveObjectsAction::new(layer_id, positions);
|
||||
|
||||
// Execute
|
||||
action.execute(&mut document);
|
||||
|
||||
// Verify position changed
|
||||
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
|
||||
let obj = layer.get_object(&object_id).unwrap();
|
||||
assert_eq!(obj.transform.x, 150.0);
|
||||
assert_eq!(obj.transform.y, 200.0);
|
||||
}
|
||||
|
||||
// Rollback
|
||||
action.rollback(&mut document);
|
||||
|
||||
// Verify position restored
|
||||
if let Some(AnyLayer::Vector(layer)) = document.get_layer(&layer_id) {
|
||||
let obj = layer.get_object(&object_id).unwrap();
|
||||
assert_eq!(obj.transform.x, 50.0);
|
||||
assert_eq!(obj.transform.y, 50.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -169,6 +169,29 @@ impl Document {
|
||||
layer.visible && layer.contains_time(self.current_time)
|
||||
})
|
||||
}
|
||||
|
||||
/// Get a layer by ID
|
||||
pub fn get_layer(&self, id: &Uuid) -> Option<&AnyLayer> {
|
||||
self.root.get_child(id)
|
||||
}
|
||||
|
||||
// === MUTATION METHODS (pub(crate) - only accessible to action module) ===
|
||||
|
||||
/// Get mutable access to the root graphics object
|
||||
///
|
||||
/// This method is intentionally `pub(crate)` to ensure mutations
|
||||
/// only happen through the action system.
|
||||
pub(crate) fn root_mut(&mut self) -> &mut GraphicsObject {
|
||||
&mut self.root
|
||||
}
|
||||
|
||||
/// Get mutable access to a layer by ID
|
||||
///
|
||||
/// This method is intentionally `pub(crate)` to ensure mutations
|
||||
/// only happen through the action system.
|
||||
pub(crate) fn get_layer_mut(&mut self, id: &Uuid) -> Option<&mut AnyLayer> {
|
||||
self.root.get_child_mut(id)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Hit testing for selection and interaction
|
||||
//!
|
||||
//! Provides functions for testing if points or rectangles intersect with
|
||||
//! shapes and objects, taking into account transform hierarchies.
|
||||
|
||||
use crate::layer::VectorLayer;
|
||||
use crate::object::Object;
|
||||
use crate::shape::Shape;
|
||||
use uuid::Uuid;
|
||||
use vello::kurbo::{Affine, Point, Rect, Shape as KurboShape};
|
||||
|
||||
/// Hit test a layer at a specific point
|
||||
///
|
||||
/// Tests objects in reverse order (front to back) and returns the first hit.
|
||||
/// Combines parent_transform with object transforms for hierarchical testing.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `layer` - The vector layer to test
|
||||
/// * `point` - The point to test in screen/canvas space
|
||||
/// * `tolerance` - Additional tolerance in pixels for stroke hit testing
|
||||
/// * `parent_transform` - Transform from parent GraphicsObject(s)
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The UUID of the first object hit, or None if no hit
|
||||
pub fn hit_test_layer(
|
||||
layer: &VectorLayer,
|
||||
point: Point,
|
||||
tolerance: f64,
|
||||
parent_transform: Affine,
|
||||
) -> Option<Uuid> {
|
||||
// Test objects in reverse order (back to front in Vec = front to back for hit testing)
|
||||
for object in layer.objects.iter().rev() {
|
||||
// Get the shape for this object
|
||||
let shape = layer.get_shape(&object.shape_id)?;
|
||||
|
||||
// Combine parent transform with object transform
|
||||
let combined_transform = parent_transform * object.to_affine();
|
||||
|
||||
if hit_test_shape(shape, point, tolerance, combined_transform) {
|
||||
return Some(object.id);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Hit test a single shape with a given transform
|
||||
///
|
||||
/// Tests if a point hits the shape, considering both fill and stroke.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `shape` - The shape to test
|
||||
/// * `point` - The point to test in screen/canvas space
|
||||
/// * `tolerance` - Additional tolerance in pixels for stroke hit testing
|
||||
/// * `transform` - The combined transform to apply to the shape
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// true if the point hits the shape, false otherwise
|
||||
pub fn hit_test_shape(
|
||||
shape: &Shape,
|
||||
point: Point,
|
||||
tolerance: f64,
|
||||
transform: Affine,
|
||||
) -> bool {
|
||||
// Transform point to shape's local space
|
||||
// We need the inverse transform to go from screen space to shape space
|
||||
let inverse_transform = transform.inverse();
|
||||
let local_point = inverse_transform * point;
|
||||
|
||||
// Check if point is inside filled path
|
||||
if shape.fill_color.is_some() {
|
||||
if shape.path().contains(local_point) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check stroke bounds if has stroke
|
||||
if let Some(stroke_style) = &shape.stroke_style {
|
||||
let stroke_tolerance = stroke_style.width / 2.0 + tolerance;
|
||||
|
||||
// For stroke hit testing, we need to check if the point is within
|
||||
// stroke_tolerance distance of the path
|
||||
// kurbo's winding() method can be used, or we can check bounding box first
|
||||
|
||||
// Quick bounding box check with stroke tolerance
|
||||
let bbox = shape.path().bounding_box();
|
||||
let expanded_bbox = bbox.inflate(stroke_tolerance, stroke_tolerance);
|
||||
|
||||
if !expanded_bbox.contains(local_point) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// For more accurate stroke hit testing, we would need to:
|
||||
// 1. Stroke the path with the stroke width
|
||||
// 2. Check if the point is contained in the stroked outline
|
||||
// For now, we do a simpler bounding box check
|
||||
// TODO: Implement accurate stroke hit testing using kurbo's stroke functionality
|
||||
|
||||
// Simple approach: if within expanded bbox, consider it a hit for now
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Hit test objects within a rectangle (for marquee selection)
|
||||
///
|
||||
/// Returns all objects whose bounding boxes intersect with the given rectangle.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `layer` - The vector layer to test
|
||||
/// * `rect` - The selection rectangle in screen/canvas space
|
||||
/// * `parent_transform` - Transform from parent GraphicsObject(s)
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Vector of UUIDs for all objects that intersect the rectangle
|
||||
pub fn hit_test_objects_in_rect(
|
||||
layer: &VectorLayer,
|
||||
rect: Rect,
|
||||
parent_transform: Affine,
|
||||
) -> Vec<Uuid> {
|
||||
let mut hits = Vec::new();
|
||||
|
||||
for object in &layer.objects {
|
||||
// Get the shape for this object
|
||||
if let Some(shape) = layer.get_shape(&object.shape_id) {
|
||||
// Combine parent transform with object transform
|
||||
let combined_transform = parent_transform * object.to_affine();
|
||||
|
||||
// Get shape bounding box in local space
|
||||
let bbox = shape.path().bounding_box();
|
||||
|
||||
// Transform bounding box to screen space
|
||||
let transformed_bbox = combined_transform.transform_rect_bbox(bbox);
|
||||
|
||||
// Check if rectangles intersect
|
||||
if rect.intersect(transformed_bbox).area() > 0.0 {
|
||||
hits.push(object.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hits
|
||||
}
|
||||
|
||||
/// Get the bounding box of an object in screen space
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `object` - The object to get bounds for
|
||||
/// * `shape` - The shape definition
|
||||
/// * `parent_transform` - Transform from parent GraphicsObject(s)
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The bounding box in screen/canvas space
|
||||
pub fn get_object_bounds(
|
||||
object: &Object,
|
||||
shape: &Shape,
|
||||
parent_transform: Affine,
|
||||
) -> Rect {
|
||||
let combined_transform = parent_transform * object.to_affine();
|
||||
let local_bbox = shape.path().bounding_box();
|
||||
combined_transform.transform_rect_bbox(local_bbox)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::shape::ShapeColor;
|
||||
use vello::kurbo::{Circle, Shape as KurboShape};
|
||||
|
||||
#[test]
|
||||
fn test_hit_test_simple_circle() {
|
||||
let mut layer = VectorLayer::new("Test Layer");
|
||||
|
||||
// Create a circle at (100, 100) with radius 50
|
||||
let circle = Circle::new((100.0, 100.0), 50.0);
|
||||
let path = circle.to_path(0.1);
|
||||
let shape = Shape::new(path).with_fill(ShapeColor::rgb(255, 0, 0));
|
||||
let object = Object::new(shape.id);
|
||||
|
||||
layer.add_shape(shape);
|
||||
layer.add_object(object);
|
||||
|
||||
// Test hit inside circle
|
||||
let hit = hit_test_layer(&layer, Point::new(100.0, 100.0), 0.0, Affine::IDENTITY);
|
||||
assert!(hit.is_some());
|
||||
|
||||
// Test miss outside circle
|
||||
let miss = hit_test_layer(&layer, Point::new(200.0, 200.0), 0.0, Affine::IDENTITY);
|
||||
assert!(miss.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hit_test_with_transform() {
|
||||
let mut layer = VectorLayer::new("Test Layer");
|
||||
|
||||
// Create a circle at origin
|
||||
let circle = Circle::new((0.0, 0.0), 50.0);
|
||||
let path = circle.to_path(0.1);
|
||||
let shape = Shape::new(path).with_fill(ShapeColor::rgb(255, 0, 0));
|
||||
|
||||
// Create object with translation
|
||||
let object = Object::new(shape.id).with_position(100.0, 100.0);
|
||||
|
||||
layer.add_shape(shape);
|
||||
layer.add_object(object);
|
||||
|
||||
// Test hit at translated position
|
||||
let hit = hit_test_layer(&layer, Point::new(100.0, 100.0), 0.0, Affine::IDENTITY);
|
||||
assert!(hit.is_some());
|
||||
|
||||
// Test miss at origin (where shape is defined, but object is translated)
|
||||
let miss = hit_test_layer(&layer, Point::new(0.0, 0.0), 0.0, Affine::IDENTITY);
|
||||
assert!(miss.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_marquee_selection() {
|
||||
let mut layer = VectorLayer::new("Test Layer");
|
||||
|
||||
// Create two circles
|
||||
let circle1 = Circle::new((50.0, 50.0), 20.0);
|
||||
let path1 = circle1.to_path(0.1);
|
||||
let shape1 = Shape::new(path1).with_fill(ShapeColor::rgb(255, 0, 0));
|
||||
let object1 = Object::new(shape1.id);
|
||||
|
||||
let circle2 = Circle::new((150.0, 150.0), 20.0);
|
||||
let path2 = circle2.to_path(0.1);
|
||||
let shape2 = Shape::new(path2).with_fill(ShapeColor::rgb(0, 255, 0));
|
||||
let object2 = Object::new(shape2.id);
|
||||
|
||||
layer.add_shape(shape1);
|
||||
layer.add_object(object1);
|
||||
layer.add_shape(shape2);
|
||||
layer.add_object(object2);
|
||||
|
||||
// Marquee that contains both circles
|
||||
let rect = Rect::new(0.0, 0.0, 200.0, 200.0);
|
||||
let hits = hit_test_objects_in_rect(&layer, rect, Affine::IDENTITY);
|
||||
assert_eq!(hits.len(), 2);
|
||||
|
||||
// Marquee that contains only first circle
|
||||
let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
let hits = hit_test_objects_in_rect(&layer, rect, Affine::IDENTITY);
|
||||
assert_eq!(hits.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -158,6 +158,68 @@ impl VectorLayer {
|
||||
pub fn get_object_mut(&mut self, id: &Uuid) -> Option<&mut Object> {
|
||||
self.objects.iter_mut().find(|o| &o.id == id)
|
||||
}
|
||||
|
||||
// === MUTATION METHODS (pub(crate) - only accessible to action module) ===
|
||||
|
||||
/// Add a shape to this layer (internal, for actions only)
|
||||
///
|
||||
/// This method is intentionally `pub(crate)` to ensure mutations
|
||||
/// only happen through the action system.
|
||||
pub(crate) fn add_shape_internal(&mut self, shape: Shape) -> Uuid {
|
||||
let id = shape.id;
|
||||
self.shapes.push(shape);
|
||||
id
|
||||
}
|
||||
|
||||
/// Add an object to this layer (internal, for actions only)
|
||||
///
|
||||
/// This method is intentionally `pub(crate)` to ensure mutations
|
||||
/// only happen through the action system.
|
||||
pub(crate) fn add_object_internal(&mut self, object: Object) -> Uuid {
|
||||
let id = object.id;
|
||||
self.objects.push(object);
|
||||
id
|
||||
}
|
||||
|
||||
/// Remove a shape from this layer (internal, for actions only)
|
||||
///
|
||||
/// Returns the removed shape if found.
|
||||
/// This method is intentionally `pub(crate)` to ensure mutations
|
||||
/// only happen through the action system.
|
||||
pub(crate) fn remove_shape_internal(&mut self, id: &Uuid) -> Option<Shape> {
|
||||
if let Some(index) = self.shapes.iter().position(|s| &s.id == id) {
|
||||
Some(self.shapes.remove(index))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an object from this layer (internal, for actions only)
|
||||
///
|
||||
/// Returns the removed object if found.
|
||||
/// This method is intentionally `pub(crate)` to ensure mutations
|
||||
/// only happen through the action system.
|
||||
pub(crate) fn remove_object_internal(&mut self, id: &Uuid) -> Option<Object> {
|
||||
if let Some(index) = self.objects.iter().position(|o| &o.id == id) {
|
||||
Some(self.objects.remove(index))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Modify an object in place (internal, for actions only)
|
||||
///
|
||||
/// Applies the given function to the object if found.
|
||||
/// This method is intentionally `pub(crate)` to ensure mutations
|
||||
/// only happen through the action system.
|
||||
pub(crate) fn modify_object_internal<F>(&mut self, id: &Uuid, f: F)
|
||||
where
|
||||
F: FnOnce(&mut Object),
|
||||
{
|
||||
if let Some(object) = self.get_object_mut(id) {
|
||||
f(object);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio layer (placeholder for future implementation)
|
||||
|
||||
@@ -11,3 +11,7 @@ pub mod object;
|
||||
pub mod layer;
|
||||
pub mod document;
|
||||
pub mod renderer;
|
||||
pub mod action;
|
||||
pub mod actions;
|
||||
pub mod selection;
|
||||
pub mod hit_test;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
use vello::kurbo::Shape as KurboShape;
|
||||
|
||||
/// 2D transform for an object
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -170,6 +171,20 @@ impl Object {
|
||||
self.transform.set_position(x, y);
|
||||
self
|
||||
}
|
||||
|
||||
/// Convert object transform to affine matrix
|
||||
pub fn to_affine(&self) -> kurbo::Affine {
|
||||
self.transform.to_affine()
|
||||
}
|
||||
|
||||
/// Get the bounding box of this object given its shape
|
||||
///
|
||||
/// Returns the bounding box in the object's parent coordinate space
|
||||
/// (i.e., with the object's transform applied).
|
||||
pub fn bounding_box(&self, shape: &crate::shape::Shape) -> kurbo::Rect {
|
||||
let path_bbox = shape.path().bounding_box();
|
||||
self.to_affine().transform_rect_bbox(path_bbox)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Selection state management
|
||||
//!
|
||||
//! Tracks selected objects and shapes for editing operations.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Selection state for the editor
|
||||
///
|
||||
/// Maintains sets of selected objects and shapes.
|
||||
/// This is separate from the document to make it easy to
|
||||
/// pass around for UI rendering without needing mutable access.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Selection {
|
||||
/// Currently selected objects (instances)
|
||||
selected_objects: Vec<Uuid>,
|
||||
|
||||
/// Currently selected shapes (definitions)
|
||||
selected_shapes: Vec<Uuid>,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
/// Create a new empty selection
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
selected_objects: Vec::new(),
|
||||
selected_shapes: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an object to the selection
|
||||
pub fn add_object(&mut self, id: Uuid) {
|
||||
if !self.selected_objects.contains(&id) {
|
||||
self.selected_objects.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a shape to the selection
|
||||
pub fn add_shape(&mut self, id: Uuid) {
|
||||
if !self.selected_shapes.contains(&id) {
|
||||
self.selected_shapes.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an object from the selection
|
||||
pub fn remove_object(&mut self, id: &Uuid) {
|
||||
self.selected_objects.retain(|&x| x != *id);
|
||||
}
|
||||
|
||||
/// Remove a shape from the selection
|
||||
pub fn remove_shape(&mut self, id: &Uuid) {
|
||||
self.selected_shapes.retain(|&x| x != *id);
|
||||
}
|
||||
|
||||
/// Toggle an object's selection state
|
||||
pub fn toggle_object(&mut self, id: Uuid) {
|
||||
if self.contains_object(&id) {
|
||||
self.remove_object(&id);
|
||||
} else {
|
||||
self.add_object(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle a shape's selection state
|
||||
pub fn toggle_shape(&mut self, id: Uuid) {
|
||||
if self.contains_shape(&id) {
|
||||
self.remove_shape(&id);
|
||||
} else {
|
||||
self.add_shape(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear all selections
|
||||
pub fn clear(&mut self) {
|
||||
self.selected_objects.clear();
|
||||
self.selected_shapes.clear();
|
||||
}
|
||||
|
||||
/// Clear only object selections
|
||||
pub fn clear_objects(&mut self) {
|
||||
self.selected_objects.clear();
|
||||
}
|
||||
|
||||
/// Clear only shape selections
|
||||
pub fn clear_shapes(&mut self) {
|
||||
self.selected_shapes.clear();
|
||||
}
|
||||
|
||||
/// Check if an object is selected
|
||||
pub fn contains_object(&self, id: &Uuid) -> bool {
|
||||
self.selected_objects.contains(id)
|
||||
}
|
||||
|
||||
/// Check if a shape is selected
|
||||
pub fn contains_shape(&self, id: &Uuid) -> bool {
|
||||
self.selected_shapes.contains(id)
|
||||
}
|
||||
|
||||
/// Check if selection is empty
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.selected_objects.is_empty() && self.selected_shapes.is_empty()
|
||||
}
|
||||
|
||||
/// Get the selected objects
|
||||
pub fn objects(&self) -> &[Uuid] {
|
||||
&self.selected_objects
|
||||
}
|
||||
|
||||
/// Get the selected shapes
|
||||
pub fn shapes(&self) -> &[Uuid] {
|
||||
&self.selected_shapes
|
||||
}
|
||||
|
||||
/// Get the number of selected objects
|
||||
pub fn object_count(&self) -> usize {
|
||||
self.selected_objects.len()
|
||||
}
|
||||
|
||||
/// Get the number of selected shapes
|
||||
pub fn shape_count(&self) -> usize {
|
||||
self.selected_shapes.len()
|
||||
}
|
||||
|
||||
/// Set selection to a single object (clears previous selection)
|
||||
pub fn select_only_object(&mut self, id: Uuid) {
|
||||
self.clear();
|
||||
self.add_object(id);
|
||||
}
|
||||
|
||||
/// Set selection to a single shape (clears previous selection)
|
||||
pub fn select_only_shape(&mut self, id: Uuid) {
|
||||
self.clear();
|
||||
self.add_shape(id);
|
||||
}
|
||||
|
||||
/// Set selection to multiple objects (clears previous selection)
|
||||
pub fn select_objects(&mut self, ids: &[Uuid]) {
|
||||
self.clear_objects();
|
||||
for &id in ids {
|
||||
self.add_object(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set selection to multiple shapes (clears previous selection)
|
||||
pub fn select_shapes(&mut self, ids: &[Uuid]) {
|
||||
self.clear_shapes();
|
||||
for &id in ids {
|
||||
self.add_shape(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_selection_creation() {
|
||||
let selection = Selection::new();
|
||||
assert!(selection.is_empty());
|
||||
assert_eq!(selection.object_count(), 0);
|
||||
assert_eq!(selection.shape_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add_remove_objects() {
|
||||
let mut selection = Selection::new();
|
||||
let id1 = Uuid::new_v4();
|
||||
let id2 = Uuid::new_v4();
|
||||
|
||||
selection.add_object(id1);
|
||||
assert_eq!(selection.object_count(), 1);
|
||||
assert!(selection.contains_object(&id1));
|
||||
|
||||
selection.add_object(id2);
|
||||
assert_eq!(selection.object_count(), 2);
|
||||
|
||||
selection.remove_object(&id1);
|
||||
assert_eq!(selection.object_count(), 1);
|
||||
assert!(!selection.contains_object(&id1));
|
||||
assert!(selection.contains_object(&id2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_toggle() {
|
||||
let mut selection = Selection::new();
|
||||
let id = Uuid::new_v4();
|
||||
|
||||
selection.toggle_object(id);
|
||||
assert!(selection.contains_object(&id));
|
||||
|
||||
selection.toggle_object(id);
|
||||
assert!(!selection.contains_object(&id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_select_only() {
|
||||
let mut selection = Selection::new();
|
||||
let id1 = Uuid::new_v4();
|
||||
let id2 = Uuid::new_v4();
|
||||
|
||||
selection.add_object(id1);
|
||||
selection.add_object(id2);
|
||||
assert_eq!(selection.object_count(), 2);
|
||||
|
||||
selection.select_only_object(id1);
|
||||
assert_eq!(selection.object_count(), 1);
|
||||
assert!(selection.contains_object(&id1));
|
||||
assert!(!selection.contains_object(&id2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clear() {
|
||||
let mut selection = Selection::new();
|
||||
selection.add_object(Uuid::new_v4());
|
||||
selection.add_shape(Uuid::new_v4());
|
||||
|
||||
assert!(!selection.is_empty());
|
||||
|
||||
selection.clear();
|
||||
assert!(selection.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -299,6 +299,14 @@ impl Shape {
|
||||
self.fill_rule = rule;
|
||||
self
|
||||
}
|
||||
|
||||
/// Get the base path (first version) for this shape
|
||||
///
|
||||
/// This is useful for hit testing and bounding box calculations
|
||||
/// when shape morphing is not being considered.
|
||||
pub fn path(&self) -> &BezPath {
|
||||
&self.versions[0].path
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
/// Defines the available drawing/editing tools
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
use vello::kurbo::Point;
|
||||
|
||||
/// Drawing and editing tools
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -24,6 +27,86 @@ pub enum Tool {
|
||||
Eyedropper,
|
||||
}
|
||||
|
||||
/// Tool state tracking for interactive operations
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ToolState {
|
||||
/// Tool is idle (no operation in progress)
|
||||
Idle,
|
||||
|
||||
/// Drawing a freehand path
|
||||
DrawingPath {
|
||||
points: Vec<Point>,
|
||||
simplify_mode: SimplifyMode,
|
||||
},
|
||||
|
||||
/// Dragging selected objects
|
||||
DraggingSelection {
|
||||
start_pos: Point,
|
||||
start_mouse: Point,
|
||||
original_positions: HashMap<Uuid, Point>,
|
||||
},
|
||||
|
||||
/// Creating a marquee selection rectangle
|
||||
MarqueeSelecting {
|
||||
start: Point,
|
||||
current: Point,
|
||||
},
|
||||
|
||||
/// Creating a rectangle shape
|
||||
CreatingRectangle {
|
||||
start_corner: Point,
|
||||
current_corner: Point,
|
||||
},
|
||||
|
||||
/// Creating an ellipse shape
|
||||
CreatingEllipse {
|
||||
center: Point,
|
||||
current_point: Point,
|
||||
},
|
||||
|
||||
/// Transforming selected objects (scale, rotate)
|
||||
Transforming {
|
||||
mode: TransformMode,
|
||||
original_transforms: HashMap<Uuid, crate::object::Transform>,
|
||||
pivot: Point,
|
||||
},
|
||||
}
|
||||
|
||||
/// Path simplification mode for the draw tool
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SimplifyMode {
|
||||
/// Ramer-Douglas-Peucker corner detection
|
||||
Corners,
|
||||
/// Schneider curve fitting for smooth curves
|
||||
Smooth,
|
||||
/// No simplification (use raw points)
|
||||
Verbatim,
|
||||
}
|
||||
|
||||
/// Transform mode for the transform tool
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum TransformMode {
|
||||
/// Scale from a corner
|
||||
ScaleCorner { origin: Point },
|
||||
/// Scale along an edge
|
||||
ScaleEdge { axis: Axis, origin: Point },
|
||||
/// Rotate around a pivot
|
||||
Rotate { center: Point },
|
||||
}
|
||||
|
||||
/// Axis for edge scaling
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Axis {
|
||||
Horizontal,
|
||||
Vertical,
|
||||
}
|
||||
|
||||
impl Default for ToolState {
|
||||
fn default() -> Self {
|
||||
Self::Idle
|
||||
}
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
/// Get display name for the tool
|
||||
pub fn display_name(self) -> &'static str {
|
||||
|
||||
Reference in New Issue
Block a user