Restructure the entire editor codebase to consistently match the message hierarchy

Closes #744
This commit is contained in:
Keavon Chambers
2022-08-05 17:13:43 -07:00
parent 9e1f4eb46d
commit ddfd7db0a0
154 changed files with 4199 additions and 4064 deletions
@@ -0,0 +1,6 @@
pub mod overlay_renderer;
pub mod path_outline;
pub mod resize;
pub mod shape_editor;
pub mod snapping;
pub mod transformation_cage;
@@ -0,0 +1,314 @@
use crate::application::generate_uuid;
use crate::consts::VIEWPORT_GRID_ROUNDING_BIAS;
use crate::consts::{COLOR_ACCENT, MANIPULATOR_GROUP_MARKER_SIZE, PATH_OUTLINE_WEIGHT};
use crate::messages::prelude::*;
use graphene::color::Color;
use graphene::document::Document;
use graphene::layers::style::{self, Fill, Stroke};
use graphene::layers::vector::consts::ManipulatorType;
use graphene::layers::vector::manipulator_group::ManipulatorGroup;
use graphene::layers::vector::manipulator_point::ManipulatorPoint;
use graphene::layers::vector::subpath::Subpath;
use graphene::{LayerId, Operation};
use glam::{DAffine2, DVec2};
use std::collections::{HashMap, VecDeque};
/// [ManipulatorGroupOverlay]s is the collection of overlays that make up an [ManipulatorGroup] visible in the editor.
type ManipulatorGroupOverlays = [Option<Vec<LayerId>>; 5];
type ManipulatorId = u64;
const POINT_STROKE_WEIGHT: f64 = 2.;
#[derive(Clone, Debug, Default)]
pub struct OverlayRenderer {
shape_overlay_cache: HashMap<LayerId, Vec<LayerId>>,
manipulator_group_overlay_cache: HashMap<(LayerId, ManipulatorId), ManipulatorGroupOverlays>,
}
impl OverlayRenderer {
pub fn new() -> Self {
OverlayRenderer {
manipulator_group_overlay_cache: HashMap::new(),
shape_overlay_cache: HashMap::new(),
}
}
pub fn render_subpath_overlays(&mut self, document: &Document, layer_path: Vec<LayerId>, responses: &mut VecDeque<Message>) {
let transform = document.generate_transform_relative_to_viewport(&layer_path).ok().unwrap();
if let Ok(layer) = document.layer(&layer_path) {
let layer_id = layer_path.last().unwrap();
self.layer_overlay_visibility(document, layer_path.clone(), true, responses);
if let Some(shape) = layer.as_subpath() {
let outline_cache = self.shape_overlay_cache.get(layer_id);
log::trace!("Overlay: Outline cache {:?}", &outline_cache);
// Create an outline if we do not have a cached one
if outline_cache == None {
let outline_path = self.create_shape_outline_overlay(shape.clone(), responses);
self.shape_overlay_cache.insert(*layer_id, outline_path.clone());
Self::place_outline_overlays(outline_path.clone(), &transform, responses);
log::trace!("Overlay: Creating new outline {:?}", &outline_path);
} else if let Some(outline_path) = outline_cache {
log::trace!("Overlay: Updating overlays for {:?} owning layer: {:?}", outline_path, layer_id);
Self::modify_outline_overlays(outline_path.clone(), shape.clone(), responses);
Self::place_outline_overlays(outline_path.clone(), &transform, responses);
}
// Create, place, and style the manipulator overlays
for (manipulator_group_id, manipulator_group) in shape.manipulator_groups().enumerate() {
let manipulator_group_cache = self.manipulator_group_overlay_cache.get_mut(&(*layer_id, *manipulator_group_id));
// If cached update placement and style
if let Some(manipulator_group_overlays) = manipulator_group_cache {
log::trace!("Overlay: Updating detail overlays for {:?}", manipulator_group_overlays);
Self::place_manipulator_group_overlays(manipulator_group, manipulator_group_overlays, &transform, responses);
Self::style_overlays(manipulator_group, manipulator_group_overlays, responses);
} else {
// Create if not cached
let mut manipulator_group_overlays = [
Some(self.create_anchor_overlay(responses)),
Self::create_handle_overlay_if_exists(&manipulator_group.points[ManipulatorType::InHandle], responses),
Self::create_handle_overlay_if_exists(&manipulator_group.points[ManipulatorType::OutHandle], responses),
Self::create_handle_line_overlay_if_exists(&manipulator_group.points[ManipulatorType::InHandle], responses),
Self::create_handle_line_overlay_if_exists(&manipulator_group.points[ManipulatorType::OutHandle], responses),
];
Self::place_manipulator_group_overlays(manipulator_group, &mut manipulator_group_overlays, &transform, responses);
Self::style_overlays(manipulator_group, &manipulator_group_overlays, responses);
self.manipulator_group_overlay_cache.insert((*layer_id, *manipulator_group_id), manipulator_group_overlays);
}
}
// TODO Handle removing shapes from cache so we don't memory leak
// Eventually will get replaced with am immediate mode renderer for overlays
}
}
}
pub fn clear_subpath_overlays(&mut self, document: &Document, layer_path: Vec<LayerId>, responses: &mut VecDeque<Message>) {
let layer_id = layer_path.last().unwrap();
// Remove the shape outline overlays
if let Some(overlay_path) = self.shape_overlay_cache.get(layer_id) {
Self::remove_outline_overlays(overlay_path.clone(), responses)
}
self.shape_overlay_cache.remove(layer_id);
// Remove the ManipulatorGroup overlays
if let Ok(layer) = document.layer(&layer_path) {
if let Some(shape) = layer.as_subpath() {
for (id, _) in shape.manipulator_groups().enumerate() {
if let Some(manipulator_group_overlays) = self.manipulator_group_overlay_cache.get(&(*layer_id, *id)) {
Self::remove_manipulator_group_overlays(manipulator_group_overlays, responses);
self.manipulator_group_overlay_cache.remove(&(*layer_id, *id));
}
}
}
}
}
pub fn layer_overlay_visibility(&mut self, document: &Document, layer_path: Vec<LayerId>, visibility: bool, responses: &mut VecDeque<Message>) {
let layer_id = layer_path.last().unwrap();
// Hide the shape outline overlays
if let Some(overlay_path) = self.shape_overlay_cache.get(layer_id) {
Self::set_outline_overlay_visibility(overlay_path.clone(), visibility, responses);
}
// Hide the manipulator group overlays
if let Ok(layer) = document.layer(&layer_path) {
if let Some(shape) = layer.as_subpath() {
for (id, _) in shape.manipulator_groups().enumerate() {
if let Some(manipulator_group_overlays) = self.manipulator_group_overlay_cache.get(&(*layer_id, *id)) {
Self::set_manipulator_group_overlay_visibility(manipulator_group_overlays, visibility, responses);
}
}
}
}
}
/// Create the kurbo shape that matches the selected viewport shape.
fn create_shape_outline_overlay(&self, subpath: Subpath, responses: &mut VecDeque<Message>) -> Vec<LayerId> {
let layer_path = vec![generate_uuid()];
let operation = Operation::AddShape {
path: layer_path.clone(),
subpath,
style: style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, PATH_OUTLINE_WEIGHT)), Fill::None),
insert_index: -1,
transform: DAffine2::IDENTITY.to_cols_array(),
};
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
layer_path
}
/// Create a single anchor overlay and return its layer ID.
fn create_anchor_overlay(&self, responses: &mut VecDeque<Message>) -> Vec<LayerId> {
let layer_path = vec![generate_uuid()];
let operation = Operation::AddRect {
path: layer_path.clone(),
transform: DAffine2::IDENTITY.to_cols_array(),
style: style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, 2.0)), Fill::solid(Color::WHITE)),
insert_index: -1,
};
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
layer_path
}
/// Create a single handle overlay and return its layer ID.
fn create_handle_overlay(responses: &mut VecDeque<Message>) -> Vec<LayerId> {
let layer_path = vec![generate_uuid()];
let operation = Operation::AddEllipse {
path: layer_path.clone(),
transform: DAffine2::IDENTITY.to_cols_array(),
style: style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, 2.0)), Fill::solid(Color::WHITE)),
insert_index: -1,
};
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
layer_path
}
/// Create a single handle overlay and return its layer id if it exists.
fn create_handle_overlay_if_exists(handle: &Option<ManipulatorPoint>, responses: &mut VecDeque<Message>) -> Option<Vec<LayerId>> {
handle.as_ref().map(|_| Self::create_handle_overlay(responses))
}
/// Create the shape outline overlay and return its layer ID.
fn create_handle_line_overlay(responses: &mut VecDeque<Message>) -> Vec<LayerId> {
let layer_path = vec![generate_uuid()];
let operation = Operation::AddLine {
path: layer_path.clone(),
transform: DAffine2::IDENTITY.to_cols_array(),
style: style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, 1.0)), Fill::None),
insert_index: -1,
};
responses.push_front(DocumentMessage::Overlays(operation.into()).into());
layer_path
}
/// Create the shape outline overlay and return its layer ID.
fn create_handle_line_overlay_if_exists(handle: &Option<ManipulatorPoint>, responses: &mut VecDeque<Message>) -> Option<Vec<LayerId>> {
handle.as_ref().map(|_| Self::create_handle_line_overlay(responses))
}
fn place_outline_overlays(outline_path: Vec<LayerId>, parent_transform: &DAffine2, responses: &mut VecDeque<Message>) {
let transform_message = Self::overlay_transform_message(outline_path, parent_transform.to_cols_array());
responses.push_back(transform_message);
}
fn modify_outline_overlays(outline_path: Vec<LayerId>, subpath: Subpath, responses: &mut VecDeque<Message>) {
let outline_modify_message = Self::overlay_modify_message(outline_path, subpath);
responses.push_back(outline_modify_message);
}
/// Updates the position of the overlays based on the [Subpath] points.
fn place_manipulator_group_overlays(manipulator_group: &ManipulatorGroup, overlays: &mut ManipulatorGroupOverlays, parent_transform: &DAffine2, responses: &mut VecDeque<Message>) {
if let Some(manipulator_point) = &manipulator_group.points[ManipulatorType::Anchor] {
// Helper function to keep things DRY (don't-repeat-yourself)
let mut place_handle_and_line = |handle: &ManipulatorPoint, line_source: &mut Option<Vec<LayerId>>, marker_source: &mut Option<Vec<LayerId>>| {
let line_overlay = line_source.take().unwrap_or_else(|| Self::create_handle_line_overlay(responses));
let line_vector = parent_transform.transform_point2(manipulator_point.position) - parent_transform.transform_point2(handle.position);
let scale = DVec2::splat(line_vector.length());
let angle = -line_vector.angle_between(DVec2::X);
let translation = (parent_transform.transform_point2(handle.position) + VIEWPORT_GRID_ROUNDING_BIAS).round() + DVec2::splat(0.5);
let transform = DAffine2::from_scale_angle_translation(scale, angle, translation).to_cols_array();
responses.push_back(Self::overlay_transform_message(line_overlay.clone(), transform));
*line_source = Some(line_overlay);
let marker_overlay = marker_source.take().unwrap_or_else(|| Self::create_handle_overlay(responses));
let scale = DVec2::splat(MANIPULATOR_GROUP_MARKER_SIZE);
let angle = 0.;
let translation = (parent_transform.transform_point2(handle.position) - (scale / 2.) + VIEWPORT_GRID_ROUNDING_BIAS).round();
let transform = DAffine2::from_scale_angle_translation(scale, angle, translation).to_cols_array();
responses.push_back(Self::overlay_transform_message(marker_overlay.clone(), transform));
*marker_source = Some(marker_overlay);
};
// Place the handle overlays
let [_, h1, h2] = &manipulator_group.points;
let [a, b, c, line1, line2] = overlays;
let markers = [a, b, c];
if let Some(handle) = &h1 {
place_handle_and_line(handle, line1, markers[handle.manipulator_type as usize]);
}
if let Some(handle) = &h2 {
place_handle_and_line(handle, line2, markers[handle.manipulator_type as usize]);
}
// Place the anchor point overlay
if let Some(anchor_overlay) = &overlays[ManipulatorType::Anchor as usize] {
let scale = DVec2::splat(MANIPULATOR_GROUP_MARKER_SIZE);
let angle = 0.;
let translation = (parent_transform.transform_point2(manipulator_point.position) - (scale / 2.) + VIEWPORT_GRID_ROUNDING_BIAS).round();
let transform = DAffine2::from_scale_angle_translation(scale, angle, translation).to_cols_array();
let message = Self::overlay_transform_message(anchor_overlay.clone(), transform);
responses.push_back(message);
}
}
}
/// Removes the manipulator overlays from the overlay document.
fn remove_manipulator_group_overlays(overlay_paths: &ManipulatorGroupOverlays, responses: &mut VecDeque<Message>) {
overlay_paths.iter().flatten().for_each(|layer_id| {
log::trace!("Overlay: Sending delete message for: {:?}", layer_id);
responses.push_back(DocumentMessage::Overlays(Operation::DeleteLayer { path: layer_id.clone() }.into()).into());
});
}
fn remove_outline_overlays(overlay_path: Vec<LayerId>, responses: &mut VecDeque<Message>) {
responses.push_back(DocumentMessage::Overlays(Operation::DeleteLayer { path: overlay_path }.into()).into());
}
/// Sets the visibility of the handles overlay.
fn set_manipulator_group_overlay_visibility(manipulator_group_overlays: &ManipulatorGroupOverlays, visibility: bool, responses: &mut VecDeque<Message>) {
manipulator_group_overlays.iter().flatten().for_each(|layer_id| {
responses.push_back(Self::overlay_visibility_message(layer_id.clone(), visibility));
});
}
fn set_outline_overlay_visibility(overlay_path: Vec<LayerId>, visibility: bool, responses: &mut VecDeque<Message>) {
responses.push_back(Self::overlay_visibility_message(overlay_path, visibility));
}
/// Create a visibility message for an overlay.
fn overlay_visibility_message(layer_path: Vec<LayerId>, visibility: bool) -> Message {
DocumentMessage::Overlays(
Operation::SetLayerVisibility {
path: layer_path,
visible: visibility,
}
.into(),
)
.into()
}
/// Create a transform message for an overlay.
fn overlay_transform_message(layer_path: Vec<LayerId>, transform: [f64; 6]) -> Message {
DocumentMessage::Overlays(Operation::SetLayerTransformInViewport { path: layer_path, transform }.into()).into()
}
/// Create an update message for an overlay.
fn overlay_modify_message(layer_path: Vec<LayerId>, subpath: Subpath) -> Message {
DocumentMessage::Overlays(Operation::SetShapePath { path: layer_path, subpath }.into()).into()
}
/// Sets the overlay style for this point.
fn style_overlays(manipulator_group: &ManipulatorGroup, overlays: &ManipulatorGroupOverlays, responses: &mut VecDeque<Message>) {
// TODO Move the style definitions out of the Subpath, should be looked up from a stylesheet or similar
let selected_style = style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, POINT_STROKE_WEIGHT + 1.0)), Fill::solid(COLOR_ACCENT));
let deselected_style = style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, POINT_STROKE_WEIGHT)), Fill::solid(Color::WHITE));
// Update if the manipulator points are shown as selected
// Here the index is important, even though overlays[..] has five elements we only care about the first three
for (index, point) in manipulator_group.points.iter().enumerate() {
if let Some(point) = point {
if let Some(overlay) = &overlays[index] {
let style = if point.editor_state.is_selected { selected_style.clone() } else { deselected_style.clone() };
responses.push_back(DocumentMessage::Overlays(Operation::SetLayerStyle { path: overlay.clone(), style }.into()).into());
}
}
}
}
}
@@ -0,0 +1,132 @@
use crate::application::generate_uuid;
use crate::consts::{COLOR_ACCENT, PATH_OUTLINE_WEIGHT, SELECTION_TOLERANCE};
use crate::messages::prelude::*;
use graphene::intersection::Quad;
use graphene::layers::layer_info::LayerDataType;
use graphene::layers::style::{self, Fill, Stroke};
use graphene::layers::text_layer::FontCache;
use graphene::layers::vector::subpath::Subpath;
use graphene::{LayerId, Operation};
use glam::{DAffine2, DVec2};
use std::collections::VecDeque;
/// Manages the overlay used by the select tool for outlining selected shapes and when hovering over a non selected shape.
#[derive(Clone, Debug, Default)]
pub struct PathOutline {
hovered_layer_path: Option<Vec<LayerId>>,
hovered_overlay_path: Option<Vec<LayerId>>,
selected_overlay_paths: Vec<Vec<LayerId>>,
}
impl PathOutline {
/// Creates an outline of a layer either with a pre-existing overlay or by generating a new one
fn create_outline(
document_layer_path: Vec<LayerId>,
overlay_path: Option<Vec<LayerId>>,
document: &DocumentMessageHandler,
responses: &mut VecDeque<Message>,
font_cache: &FontCache,
) -> Option<Vec<LayerId>> {
// Get layer data
let document_layer = document.graphene_document.layer(&document_layer_path).ok()?;
// TODO Purge this area of BezPath and Kurbo
// Get the bezpath from the shape or text
let subpath = match &document_layer.data {
LayerDataType::Shape(layer_shape) => Some(layer_shape.shape.clone()),
LayerDataType::Text(text) => Some(text.to_subpath_nonmut(font_cache)),
_ => document_layer.aabb_for_transform(DAffine2::IDENTITY, font_cache).map(|[p1, p2]| Subpath::new_rect(p1, p2)),
}?;
// Generate a new overlay layer if necessary
let overlay = match overlay_path {
Some(path) => path,
None => {
let overlay_path = vec![generate_uuid()];
let operation = Operation::AddShape {
path: overlay_path.clone(),
subpath: Default::default(),
style: style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, PATH_OUTLINE_WEIGHT)), Fill::None),
insert_index: -1,
transform: DAffine2::IDENTITY.to_cols_array(),
};
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
overlay_path
}
};
// Update the shape bezpath
let operation = Operation::SetShapePath { path: overlay.clone(), subpath };
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
// Update the transform to match the document
let operation = Operation::SetLayerTransform {
path: overlay.clone(),
transform: document.graphene_document.multiply_transforms(&document_layer_path).unwrap().to_cols_array(),
};
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
Some(overlay)
}
/// Removes the hovered overlay and deletes path references
pub fn clear_hovered(&mut self, responses: &mut VecDeque<Message>) {
if let Some(path) = self.hovered_overlay_path.take() {
let operation = Operation::DeleteLayer { path };
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
}
self.hovered_layer_path = None;
}
/// Performs an intersect test and generates a hovered overlay if necessary
pub fn intersect_test_hovered(&mut self, input: &InputPreprocessorMessageHandler, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>, font_cache: &FontCache) {
// Get the layer the user is hovering over
let tolerance = DVec2::splat(SELECTION_TOLERANCE);
let quad = Quad::from_box([input.mouse.position - tolerance, input.mouse.position + tolerance]);
let mut intersection = document.graphene_document.intersects_quad_root(quad, font_cache);
// If the user is hovering over a layer they have not already selected, then update outline
if let Some(path) = intersection.pop() {
if !document.selected_visible_layers().any(|visible| visible == path.as_slice()) {
// Updates the overlay, generating a new one if necessary
self.hovered_overlay_path = Self::create_outline(path.clone(), self.hovered_overlay_path.take(), document, responses, font_cache);
if self.hovered_overlay_path.is_none() {
self.clear_hovered(responses);
}
self.hovered_layer_path = Some(path);
} else {
self.clear_hovered(responses);
}
} else {
self.clear_hovered(responses);
}
}
/// Clears overlays for the selected paths and removes references
pub fn clear_selected(&mut self, responses: &mut VecDeque<Message>) {
while let Some(path) = self.selected_overlay_paths.pop() {
let operation = Operation::DeleteLayer { path };
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
}
}
/// Updates the selected overlays, generating or removing overlays if necessary
pub fn update_selected<'a>(&mut self, selected: impl Iterator<Item = &'a [LayerId]>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>, font_cache: &FontCache) {
let mut old_overlay_paths = std::mem::take(&mut self.selected_overlay_paths);
for document_layer_path in selected {
if let Some(overlay_path) = Self::create_outline(document_layer_path.to_vec(), old_overlay_paths.pop(), document, responses, font_cache) {
self.selected_overlay_paths.push(overlay_path);
}
}
for path in old_overlay_paths {
let operation = Operation::DeleteLayer { path };
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
}
}
}
@@ -0,0 +1,65 @@
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::input_mouse::ViewportPosition;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::snapping::SnapManager;
use graphene::layers::text_layer::FontCache;
use graphene::LayerId;
use graphene::Operation;
use glam::{DAffine2, DVec2, Vec2Swizzles};
#[derive(Clone, Debug, Default)]
pub struct Resize {
pub drag_start: ViewportPosition,
pub path: Option<Vec<LayerId>>,
snap_manager: SnapManager,
}
impl Resize {
/// Starts a resize, assigning the snap targets and snapping the starting position.
pub fn start(&mut self, responses: &mut VecDeque<Message>, document: &DocumentMessageHandler, mouse_position: DVec2, font_cache: &FontCache) {
self.snap_manager.start_snap(document, document.bounding_boxes(None, None, font_cache), true, true);
self.snap_manager.add_all_document_handles(document, &[], &[], &[]);
self.drag_start = self.snap_manager.snap_position(responses, document, mouse_position);
}
pub fn calculate_transform(
&mut self,
responses: &mut VecDeque<Message>,
document: &DocumentMessageHandler,
center: Key,
lock_ratio: Key,
ipp: &InputPreprocessorMessageHandler,
) -> Option<Message> {
if let Some(path) = &self.path {
let mut start = self.drag_start;
let stop = self.snap_manager.snap_position(responses, document, ipp.mouse.position);
let mut size = stop - start;
if ipp.keyboard.get(lock_ratio as usize) {
size = size.abs().max(size.abs().yx()) * size.signum();
}
if ipp.keyboard.get(center as usize) {
start -= size;
size *= 2.;
}
Some(
Operation::SetLayerTransformInViewport {
path: path.to_vec(),
transform: DAffine2::from_scale_angle_translation(size, 0., start).to_cols_array(),
}
.into(),
)
} else {
None
}
}
pub fn cleanup(&mut self, responses: &mut VecDeque<Message>) {
self.snap_manager.cleanup(responses);
self.path = None;
}
}
@@ -0,0 +1,266 @@
use crate::messages::prelude::*;
use graphene::layers::vector::consts::ManipulatorType;
use graphene::layers::vector::manipulator_group::ManipulatorGroup;
use graphene::layers::vector::manipulator_point::ManipulatorPoint;
use graphene::layers::vector::subpath::Subpath;
use graphene::{LayerId, Operation};
use glam::DVec2;
use graphene::document::Document;
use std::collections::VecDeque;
/// ShapeEditor is the container for all of the layer paths that are represented as [Subpath]s and provides
/// functionality required to query and create the [Subpath] / [ManipulatorGroup]s / [ManipulatorPoint]s.
///
/// Overview:
/// ```text
/// ShapeEditor
/// |
/// selected_layers <- Paths to selected layers that may contain Subpaths
/// / | \
/// Subpath ... Subpath <- Reference from layer paths, one Subpath per layer (for now, will eventually be a CompoundPath)
/// / | \
/// ManipulatorGroup ... ManipulatorGroup <- Subpath contains many ManipulatorGroups
/// ```
#[derive(Clone, Debug, Default)]
pub struct ShapeEditor {
// The layers we can select and edit manipulators (anchors and handles) from
selected_layers: Vec<Vec<LayerId>>,
}
// TODO Consider keeping a list of selected manipulators to minimize traversals of the layers
impl ShapeEditor {
/// Select the first point within the selection threshold.
/// Returns the points if found, None otherwise.
pub fn select_point(
&self,
document: &Document,
mouse_position: DVec2,
select_threshold: f64,
add_to_selection: bool,
responses: &mut VecDeque<Message>,
) -> Option<Vec<(&[LayerId], u64, ManipulatorType)>> {
if self.selected_layers.is_empty() {
return None;
}
if let Some((shape_layer_path, manipulator_group_id, manipulator_point_index)) = self.find_nearest_point_indices(document, mouse_position, select_threshold) {
log::trace!("Selecting... manipulator group ID: {}, manipulator point index: {}", manipulator_group_id, manipulator_point_index);
// If the point we're selecting has already been selected
// we can assume this point exists.. since we did just click on it hence the unwrap
let is_point_selected = self.shape(document, shape_layer_path).unwrap().manipulator_groups().by_id(manipulator_group_id).unwrap().points[manipulator_point_index]
.as_ref()
.unwrap()
.editor_state
.is_selected;
let point_position = self.shape(document, shape_layer_path).unwrap().manipulator_groups().by_id(manipulator_group_id).unwrap().points[manipulator_point_index]
.as_ref()
.unwrap()
.position;
// The currently selected points (which are then modified to reflect the selection)
let mut points = self
.selected_layers()
.iter()
.filter_map(|path| document.layer(path).ok().map(|layer| (path, layer)))
.filter_map(|(path, shape)| shape.as_subpath().map(|subpath| (path, subpath)))
.flat_map(|(path, shape)| {
shape
.manipulator_groups()
.enumerate()
.filter(|(_id, manipulator_group)| manipulator_group.is_anchor_selected())
.flat_map(|(id, manipulator_group)| manipulator_group.selected_points().map(move |point| (id, point.manipulator_type)))
.map(|(anchor, manipulator_point)| (path.as_slice(), *anchor, manipulator_point))
})
.collect::<Vec<_>>();
// Should we select or deselect the point?
let should_select = if is_point_selected { !add_to_selection } else { true };
// This is selecting the manipulator only for now, next to generalize to points
if should_select {
let add = add_to_selection || is_point_selected;
let point = (manipulator_group_id, ManipulatorType::from_index(manipulator_point_index));
// Clear all point in other selected shapes
if !add {
responses.push_back(DocumentMessage::DeselectAllManipulatorPoints.into());
points = vec![(shape_layer_path, point.0, point.1)];
} else {
points.push((shape_layer_path, point.0, point.1));
}
responses.push_back(
Operation::SelectManipulatorPoints {
layer_path: shape_layer_path.to_vec(),
point_ids: vec![point],
add,
}
.into(),
);
// Snap the selected point to the cursor
if let Ok(viewspace) = document.generate_transform_relative_to_viewport(shape_layer_path) {
self.move_selected_points(mouse_position - viewspace.transform_point2(point_position), mouse_position, responses)
}
} else {
responses.push_back(
Operation::DeselectManipulatorPoints {
layer_path: shape_layer_path.to_vec(),
point_ids: vec![(manipulator_group_id, ManipulatorType::from_index(manipulator_point_index))],
}
.into(),
);
points.retain(|x| *x != (shape_layer_path, manipulator_group_id, ManipulatorType::from_index(manipulator_point_index)))
}
return Some(points);
}
// Deselect all points if no nearby point
responses.push_back(DocumentMessage::DeselectAllManipulatorPoints.into());
None
}
/// A wrapper for `find_nearest_point_indices()` and returns a [ManipulatorPoint].
pub fn find_nearest_point<'a>(&'a self, document: &'a Document, mouse_position: DVec2, select_threshold: f64) -> Option<&'a ManipulatorPoint> {
let (shape_layer_path, manipulator_group_id, manipulator_point_index) = self.find_nearest_point_indices(document, mouse_position, select_threshold)?;
let selected_shape = self.shape(document, shape_layer_path).unwrap();
if let Some(manipulator_group) = selected_shape.manipulator_groups().by_id(manipulator_group_id) {
return manipulator_group.points[manipulator_point_index].as_ref();
}
None
}
/// Set the shapes we consider for selection, we will choose draggable manipulators from these shapes.
pub fn set_selected_layers(&mut self, target_layers: Vec<Vec<LayerId>>) {
self.selected_layers = target_layers;
}
pub fn selected_layers(&self) -> &Vec<Vec<LayerId>> {
&self.selected_layers
}
pub fn selected_layers_ref(&self) -> Vec<&[LayerId]> {
self.selected_layers.iter().map(|l| l.as_slice()).collect::<Vec<_>>()
}
/// Clear all of the shapes we can modify.
pub fn clear_selected_layers(&mut self) {
self.selected_layers.clear();
}
pub fn has_selected_layers(&self) -> bool {
!self.selected_layers.is_empty()
}
/// Provide the currently selected manipulators by reference.
pub fn selected_manipulator_groups<'a>(&'a self, document: &'a Document) -> impl Iterator<Item = &'a ManipulatorGroup> {
self.iter(document).flat_map(|shape| shape.selected_manipulator_groups())
}
/// A mutable iterator of all the manipulators, regardless of selection.
pub fn manipulator_groups<'a>(&'a self, document: &'a Document) -> impl Iterator<Item = &'a ManipulatorGroup> {
self.iter(document).flat_map(|shape| shape.manipulator_groups().iter())
}
/// Provide the currently selected points by reference.
pub fn selected_points<'a>(&'a self, document: &'a Document) -> impl Iterator<Item = &'a ManipulatorPoint> {
self.selected_manipulator_groups(document).flat_map(|manipulator_group| manipulator_group.selected_points())
}
/// Move the selected points by dragging the mouse.
pub fn move_selected_points(&self, delta: DVec2, absolute_position: DVec2, responses: &mut VecDeque<Message>) {
for layer_path in &self.selected_layers {
responses.push_back(
DocumentMessage::MoveSelectedManipulatorPoints {
layer_path: layer_path.clone(),
delta: (delta.x, delta.y),
absolute_position: (absolute_position.x, absolute_position.y),
}
.into(),
);
}
}
/// Dissolve the selected points.
pub fn delete_selected_points(&self, responses: &mut VecDeque<Message>) {
responses.push_back(DocumentMessage::DeleteSelectedManipulatorPoints.into());
}
/// Toggle if the handles should mirror angle across the anchor position.
pub fn toggle_handle_mirroring_on_selected(&self, toggle_angle: bool, toggle_distance: bool, responses: &mut VecDeque<Message>) {
for layer_path in &self.selected_layers {
responses.push_back(
DocumentMessage::ToggleSelectedHandleMirroring {
layer_path: layer_path.clone(),
toggle_angle,
toggle_distance,
}
.into(),
);
}
}
/// Deselect all manipulators from the shapes that the manipulation handler has created.
pub fn deselect_all_points(&self, responses: &mut VecDeque<Message>) {
responses.push_back(DocumentMessage::DeselectAllManipulatorPoints.into());
}
/// Iterate over the shapes.
pub fn iter<'a>(&'a self, document: &'a Document) -> impl Iterator<Item = &'a Subpath> + 'a {
self.selected_layers.iter().flat_map(|layer_id| document.layer(layer_id)).filter_map(|shape| shape.as_subpath())
}
/// Find a [ManipulatorPoint] that is within the selection threshold and return the layer path, an index to the [ManipulatorGroup], and an enum index for [ManipulatorPoint].
/// Return value is an `Option` of the tuple representing `(layer path, ManipulatorGroup ID, ManipulatorType enum index)`.
fn find_nearest_point_indices(&self, document: &Document, mouse_position: DVec2, select_threshold: f64) -> Option<(&[LayerId], u64, usize)> {
if self.selected_layers.is_empty() {
return None;
}
let select_threshold_squared = select_threshold * select_threshold;
// Find the closest control point among all elements of shapes_to_modify
for layer in self.selected_layers.iter() {
if let Some((manipulator_id, manipulator_point_index, distance_squared)) = self.closest_point_in_layer(document, layer, mouse_position) {
// Choose the first point under the threshold
if distance_squared < select_threshold_squared {
log::trace!("Selecting... manipulator ID: {}, manipulator point index: {}", manipulator_id, manipulator_point_index);
return Some((layer, manipulator_id, manipulator_point_index));
}
}
}
None
}
// TODO Use quadtree or some equivalent spatial acceleration structure to improve this to O(log(n))
/// Find the closest manipulator, manipulator point, and distance so we can select path elements.
/// Brute force comparison to determine which manipulator (handle or anchor) we want to select taking O(n) time.
/// Return value is an `Option` of the tuple representing `(manipulator ID, manipulator point index, distance squared)`.
fn closest_point_in_layer(&self, document: &Document, layer_path: &[LayerId], pos: glam::DVec2) -> Option<(u64, usize, f64)> {
let mut closest_distance_squared: f64 = f64::MAX; // Not ideal
let mut result: Option<(u64, usize, f64)> = None;
if let Some(shape) = document.layer(layer_path).ok()?.as_subpath() {
let viewspace = document.generate_transform_relative_to_viewport(layer_path).ok()?;
for (manipulator_id, manipulator) in shape.manipulator_groups().enumerate() {
let manipulator_point_index = manipulator.closest_point(&viewspace, pos);
if let Some(point) = &manipulator.points[manipulator_point_index] {
if point.editor_state.can_be_selected {
let distance_squared = viewspace.transform_point2(point.position).distance_squared(pos);
if distance_squared < closest_distance_squared {
closest_distance_squared = distance_squared;
result = Some((*manipulator_id, manipulator_point_index, distance_squared));
}
}
}
}
}
result
}
fn shape<'a>(&'a self, document: &'a Document, layer_id: &[u64]) -> Option<&'a Subpath> {
document.layer(layer_id).ok()?.as_subpath()
}
}
@@ -0,0 +1,319 @@
use crate::application::generate_uuid;
use crate::consts::{
COLOR_ACCENT, SNAP_AXIS_OVERLAY_FADE_DISTANCE, SNAP_AXIS_TOLERANCE, SNAP_AXIS_UNSNAPPED_OPACITY, SNAP_POINT_OVERLAY_FADE_FAR, SNAP_POINT_OVERLAY_FADE_NEAR, SNAP_POINT_SIZE, SNAP_POINT_TOLERANCE,
SNAP_POINT_UNSNAPPED_OPACITY,
};
use crate::messages::prelude::*;
use graphene::layers::layer_info::{Layer, LayerDataType};
use graphene::layers::style::{self, Stroke};
use graphene::layers::vector::consts::ManipulatorType;
use graphene::{LayerId, Operation};
use glam::{DAffine2, DVec2};
use std::f64::consts::PI;
// Handles snap overlays
#[derive(Debug, Clone, Default)]
struct SnapOverlays {
axis_overlay_paths: Vec<Vec<LayerId>>,
point_overlay_paths: Vec<Vec<LayerId>>,
axis_index: usize,
point_index: usize,
}
impl SnapOverlays {
/// Draws an overlay (axis or point) with the correct transform and fade opacity, reusing lines from the pool if available.
fn add_overlay(is_axis: bool, responses: &mut VecDeque<Message>, transform: [f64; 6], opacity: Option<f64>, index: usize, overlay_paths: &mut Vec<Vec<LayerId>>) {
// If there isn't one in the pool to ruse, add a new alignment line to the pool with the intended transform
let layer_path = if index >= overlay_paths.len() {
let layer_path = vec![generate_uuid()];
responses.push_back(
DocumentMessage::Overlays(
if is_axis {
Operation::AddLine {
path: layer_path.clone(),
transform,
style: style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, 1.0)), style::Fill::None),
insert_index: -1,
}
} else {
Operation::AddEllipse {
path: layer_path.clone(),
transform,
style: style::PathStyle::new(None, style::Fill::Solid(COLOR_ACCENT)),
insert_index: -1,
}
}
.into(),
)
.into(),
);
overlay_paths.push(layer_path.clone());
layer_path
}
// Otherwise, reuse an overlay from the pool and update its new transform
else {
let layer_path = overlay_paths[index].clone();
responses.push_back(DocumentMessage::Overlays(Operation::SetLayerTransform { path: layer_path.clone(), transform }.into()).into());
layer_path
};
// Then set its opacity to the fade amount
if let Some(opacity) = opacity {
responses.push_back(DocumentMessage::Overlays(Operation::SetLayerOpacity { path: layer_path, opacity }.into()).into());
}
}
/// Draw the alignment lines for an axis
/// Note: horizontal refers to the overlay line being horizontal and the snap being along the Y axis
fn draw_alignment_lines(&mut self, is_horizontal: bool, distances: impl Iterator<Item = (DVec2, DVec2, f64)>, responses: &mut VecDeque<Message>, closest_distance: DVec2) {
for (target, goal, distance) in distances.filter(|(_target, _pos, dist)| dist.abs() < SNAP_AXIS_OVERLAY_FADE_DISTANCE) {
let offset = if is_horizontal { target.y } else { target.x }.round() - 0.5;
let offset_other = if is_horizontal { target.x } else { target.y }.round() - 0.5;
let goal_axis = if is_horizontal { goal.x } else { goal.y }.round() - 0.5;
let scale = DVec2::new(offset_other - goal_axis, 1.);
let angle = if is_horizontal { 0. } else { PI / 2. };
let translation = if is_horizontal { DVec2::new(goal_axis, offset) } else { DVec2::new(offset, goal_axis) };
let transform = DAffine2::from_scale_angle_translation(scale, angle, translation).to_cols_array();
let closest = if is_horizontal { closest_distance.y } else { closest_distance.x };
let opacity = if (closest - distance).abs() < 1. {
1.
} else {
SNAP_AXIS_UNSNAPPED_OPACITY - distance.abs() / (SNAP_AXIS_OVERLAY_FADE_DISTANCE / SNAP_AXIS_UNSNAPPED_OPACITY)
};
// Add line
Self::add_overlay(true, responses, transform, Some(opacity), self.axis_index, &mut self.axis_overlay_paths);
self.axis_index += 1;
let size = DVec2::splat(SNAP_POINT_SIZE);
// Add point at target
let transform = DAffine2::from_scale_angle_translation(size, 0., target - size / 2.).to_cols_array();
Self::add_overlay(false, responses, transform, Some(opacity), self.point_index, &mut self.point_overlay_paths);
self.point_index += 1;
// Add point along line but towards goal
let translation = if is_horizontal { DVec2::new(goal.x, target.y) } else { DVec2::new(target.x, goal.y) };
let transform = DAffine2::from_scale_angle_translation(size, 0., translation - size / 2.).to_cols_array();
Self::add_overlay(false, responses, transform, Some(opacity), self.point_index, &mut self.point_overlay_paths);
self.point_index += 1
}
}
/// Draw the snap points
fn draw_snap_points(&mut self, distances: impl Iterator<Item = (DVec2, DVec2, f64)>, responses: &mut VecDeque<Message>, closest_distance: DVec2) {
for (target, offset, distance) in distances.filter(|(_pos, _offset, dist)| dist.abs() < SNAP_POINT_OVERLAY_FADE_FAR) {
let active = (closest_distance - offset).length_squared() < 1.;
if active {
continue;
}
let opacity = (1. - (distance - SNAP_POINT_OVERLAY_FADE_NEAR) / (SNAP_POINT_OVERLAY_FADE_FAR - SNAP_POINT_OVERLAY_FADE_NEAR)).min(1.) / SNAP_POINT_UNSNAPPED_OPACITY;
let size = DVec2::splat(SNAP_POINT_SIZE);
let transform = DAffine2::from_scale_angle_translation(size, 0., target - size / 2.).to_cols_array();
Self::add_overlay(false, responses, transform, Some(opacity), self.point_index, &mut self.point_overlay_paths);
self.point_index += 1
}
}
/// Updates the snapping overlays with the specified distances.
/// `positions_and_distances` is a tuple of `x`, `y` & `point` iterators,, each with `(position, goal, distance)` values.
fn update_overlays<X, Y, P>(&mut self, responses: &mut VecDeque<Message>, positions_and_distances: (X, Y, P), closest_distance: DVec2)
where
X: Iterator<Item = (DVec2, DVec2, f64)>,
Y: Iterator<Item = (DVec2, DVec2, f64)>,
P: Iterator<Item = (DVec2, DVec2, f64)>,
{
self.axis_index = 0;
self.point_index = 0;
let (x, y, points) = positions_and_distances;
self.draw_alignment_lines(true, y, responses, closest_distance);
self.draw_alignment_lines(false, x, responses, closest_distance);
self.draw_snap_points(points, responses, closest_distance);
Self::remove_unused_overlays(&mut self.axis_overlay_paths, responses, self.axis_index);
Self::remove_unused_overlays(&mut self.point_overlay_paths, responses, self.point_index);
}
/// Remove overlays from the pool beyond a given index. Pool entries up through that index will be kept.
fn remove_unused_overlays(overlay_paths: &mut Vec<Vec<LayerId>>, responses: &mut VecDeque<Message>, remove_after_index: usize) {
while overlay_paths.len() > remove_after_index {
responses.push_back(DocumentMessage::Overlays(Operation::DeleteLayer { path: overlay_paths.pop().unwrap() }.into()).into());
}
}
/// Deletes all overlays
fn cleanup(&mut self, responses: &mut VecDeque<Message>) {
Self::remove_unused_overlays(&mut self.axis_overlay_paths, responses, 0);
Self::remove_unused_overlays(&mut self.point_overlay_paths, responses, 0);
}
}
/// Handles snapping and snap overlays
#[derive(Debug, Clone, Default)]
pub struct SnapManager {
point_targets: Option<Vec<DVec2>>,
bound_targets: Option<Vec<DVec2>>,
snap_overlays: SnapOverlays,
snap_x: bool,
snap_y: bool,
}
impl SnapManager {
/// Computes the necessary translation to the layer to snap it (as well as updating necessary overlays)
fn calculate_snap<R>(&mut self, targets: R, responses: &mut VecDeque<Message>) -> DVec2
where
R: Iterator<Item = DVec2> + Clone,
{
let empty = Vec::new();
let snap_points = self.snap_x && self.snap_y;
let axis = self.bound_targets.as_ref().unwrap_or(&empty);
let points = if snap_points { self.point_targets.as_ref().unwrap_or(&empty) } else { &empty };
let x_axis = if self.snap_x { axis } else { &empty }
.iter()
.flat_map(|&pos| targets.clone().map(move |goal| (pos, goal, (pos - goal).x)));
let y_axis = if self.snap_y { axis } else { &empty }
.iter()
.flat_map(|&pos| targets.clone().map(move |goal| (pos, goal, (pos - goal).y)));
let points = points.iter().flat_map(|&pos| targets.clone().map(move |goal| (pos, pos - goal, (pos - goal).length())));
let min_x = x_axis.clone().min_by(|a, b| a.2.abs().partial_cmp(&b.2.abs()).expect("Could not compare position."));
let min_y = y_axis.clone().min_by(|a, b| a.2.abs().partial_cmp(&b.2.abs()).expect("Could not compare position."));
let min_points = points.clone().min_by(|a, b| a.2.abs().partial_cmp(&b.2.abs()).expect("Could not compare position."));
// Snap to a point if possible
let clamped_closest_distance = if let Some(min_points) = min_points.filter(|&(_, _, dist)| dist <= SNAP_POINT_TOLERANCE) {
min_points.1
} else {
// Do not move if over snap tolerance
let closest_distance = DVec2::new(min_x.unwrap_or_default().2, min_y.unwrap_or_default().2);
DVec2::new(
if closest_distance.x.abs() > SNAP_AXIS_TOLERANCE { 0. } else { closest_distance.x },
if closest_distance.y.abs() > SNAP_AXIS_TOLERANCE { 0. } else { closest_distance.y },
)
};
self.snap_overlays.update_overlays(responses, (x_axis, y_axis, points), clamped_closest_distance);
clamped_closest_distance
}
/// Gets a list of snap targets for the X and Y axes (if specified) in Viewport coords for the target layers (usually all layers or all non-selected layers.)
/// This should be called at the start of a drag.
pub fn start_snap(&mut self, document_message_handler: &DocumentMessageHandler, bounding_boxes: impl Iterator<Item = [DVec2; 2]>, snap_x: bool, snap_y: bool) {
if document_message_handler.snapping_enabled {
self.snap_x = snap_x;
self.snap_y = snap_y;
// Could be made into sorted Vec or a HashSet for more performant lookups.
self.bound_targets = Some(bounding_boxes.flat_map(expand_bounds).collect());
self.point_targets = None;
}
}
/// Add arbitrary snapping points
///
/// This should be called after start_snap
pub fn add_snap_points(&mut self, document_message_handler: &DocumentMessageHandler, snap_points: impl Iterator<Item = DVec2>) {
if document_message_handler.snapping_enabled {
if let Some(targets) = &mut self.point_targets {
targets.extend(snap_points);
} else {
self.point_targets = Some(snap_points.collect());
}
}
}
/// Add the [ManipulatorGroup]s (optionally including handles) of the specified shape layer to the snapping points
///
/// This should be called after start_snap
pub fn add_snap_path(&mut self, document_message_handler: &DocumentMessageHandler, layer: &Layer, path: &[LayerId], include_handles: bool, ignore_points: &[(&[LayerId], u64, ManipulatorType)]) {
if let LayerDataType::Shape(shape_layer) = &layer.data {
let transform = document_message_handler.graphene_document.multiply_transforms(path).unwrap();
let snap_points = shape_layer
.shape
.manipulator_groups()
.enumerate()
.flat_map(|(id, shape)| {
if include_handles {
[
(*id, &shape.points[ManipulatorType::Anchor]),
(*id, &shape.points[ManipulatorType::InHandle]),
(*id, &shape.points[ManipulatorType::OutHandle]),
]
} else {
[(*id, &shape.points[ManipulatorType::Anchor]), (0, &None), (0, &None)]
}
})
.filter_map(|(id, point)| point.as_ref().map(|val| (id, val)))
.filter(|(id, point)| !ignore_points.contains(&(path, *id, point.manipulator_type)))
.map(|(_id, point)| DVec2::new(point.position.x, point.position.y))
.map(|pos| transform.transform_point2(pos));
self.add_snap_points(document_message_handler, snap_points);
}
}
/// Adds all of the shape handles in the document, including bézier handles of the points specified
pub fn add_all_document_handles(
&mut self,
document_message_handler: &DocumentMessageHandler,
include_handles: &[&[LayerId]],
exclude: &[&[LayerId]],
ignore_points: &[(&[LayerId], u64, ManipulatorType)],
) {
for path in document_message_handler.all_layers() {
if !exclude.contains(&path) {
let layer = document_message_handler.graphene_document.layer(path).expect("Could not get layer for snapping");
self.add_snap_path(document_message_handler, layer, path, include_handles.contains(&path), ignore_points);
}
}
}
/// Finds the closest snap from an array of layers to the specified snap targets in viewport coords.
/// Returns 0 for each axis that there is no snap less than the snap tolerance.
pub fn snap_layers(&mut self, responses: &mut VecDeque<Message>, document_message_handler: &DocumentMessageHandler, snap_anchors: Vec<DVec2>, mouse_delta: DVec2) -> DVec2 {
if document_message_handler.snapping_enabled {
self.calculate_snap(snap_anchors.iter().map(move |&snap| mouse_delta + snap), responses)
} else {
DVec2::ZERO
}
}
/// Handles snapping of a viewport position, returning another viewport position.
pub fn snap_position(&mut self, responses: &mut VecDeque<Message>, document_message_handler: &DocumentMessageHandler, position_viewport: DVec2) -> DVec2 {
if document_message_handler.snapping_enabled {
self.calculate_snap([position_viewport].into_iter(), responses) + position_viewport
} else {
position_viewport
}
}
/// Removes snap target data and overlays. Call this when snapping is done.
pub fn cleanup(&mut self, responses: &mut VecDeque<Message>) {
self.snap_overlays.cleanup(responses);
self.bound_targets = None;
self.point_targets = None;
}
}
/// Converts a bounding box into a set of points for snapping
///
/// Puts a point in the middle of each edge (top, bottom, left, right)
pub fn expand_bounds([bound1, bound2]: [DVec2; 2]) -> [DVec2; 4] {
[
DVec2::new((bound1.x + bound2.x) / 2., bound1.y),
DVec2::new((bound1.x + bound2.x) / 2., bound2.y),
DVec2::new(bound1.x, (bound1.y + bound2.y) / 2.),
DVec2::new(bound2.x, (bound1.y + bound2.y) / 2.),
]
}
@@ -0,0 +1,332 @@
use crate::application::generate_uuid;
use crate::consts::{BOUNDS_ROTATE_THRESHOLD, BOUNDS_SELECT_THRESHOLD, COLOR_ACCENT, MANIPULATOR_GROUP_MARKER_SIZE, SELECTION_DRAG_ANGLE};
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::portfolio::document::utility_types::transformation::OriginalTransforms;
use crate::messages::prelude::*;
use graphene::color::Color;
use graphene::layers::style::{self, Fill, Stroke};
use graphene::LayerId;
use graphene::Operation;
use glam::{DAffine2, DVec2};
/// Contains the edges that are being dragged along with the original bounds.
#[derive(Clone, Debug, Default)]
pub struct SelectedEdges {
bounds: [DVec2; 2],
top: bool,
bottom: bool,
left: bool,
right: bool,
// Aspect ratio in the form of width/height, so x:1 = width:height
aspect_ratio: f64,
}
impl SelectedEdges {
pub fn new(top: bool, bottom: bool, left: bool, right: bool, bounds: [DVec2; 2]) -> Self {
let size = (bounds[0] - bounds[1]).abs();
let aspect_ratio = size.x / size.y;
Self {
top,
bottom,
left,
right,
bounds,
aspect_ratio,
}
}
/// Calculate the pivot for the operation (the opposite point to the edge dragged)
pub fn calculate_pivot(&self) -> DVec2 {
let min = self.bounds[0];
let max = self.bounds[1];
let x = if self.left {
max.x
} else if self.right {
min.x
} else {
(min.x + max.x) / 2.
};
let y = if self.top {
max.y
} else if self.bottom {
min.y
} else {
(min.y + max.y) / 2.
};
DVec2::new(x, y)
}
/// Computes the new bounds with the given mouse move and modifier keys
pub fn new_size(&self, mouse: DVec2, transform: DAffine2, center: bool, constrain: bool) -> (DVec2, DVec2) {
let mouse = transform.inverse().transform_point2(mouse);
let mut min = self.bounds[0];
let mut max = self.bounds[1];
if self.top {
min.y = mouse.y;
} else if self.bottom {
max.y = mouse.y;
}
if self.left {
let delta = min.x - mouse.x;
min.x = mouse.x;
max.x += delta;
} else if self.right {
max.x = mouse.x;
}
let mut size = max - min;
if constrain {
size = match ((self.top || self.bottom), (self.left || self.right)) {
(true, true) => DVec2::new(size.x, size.x / self.aspect_ratio).abs().max(DVec2::new(size.y * self.aspect_ratio, size.y).abs()) * size.signum(),
(true, false) => DVec2::new(size.y * self.aspect_ratio, size.y),
(false, true) => DVec2::new(size.x, size.x / self.aspect_ratio),
_ => size,
};
}
if center {
if self.left || self.right {
size.x *= 2.;
}
if self.bottom || self.top {
size.y *= 2.;
}
}
(min, size)
}
/// Offsets the transformation pivot in order to scale from the center
fn offset_pivot(&self, center: bool, size: DVec2) -> DVec2 {
let mut offset = DVec2::ZERO;
if !center {
return offset;
}
if self.right {
offset.x -= size.x / 2.;
}
if self.left {
offset.x += size.x / 2.;
}
if self.bottom {
offset.y -= size.y / 2.;
}
if self.top {
offset.y += size.y / 2.;
}
offset
}
/// Moves the position to account for centering (only necessary with absolute transforms - e.g. with artboards)
pub fn center_position(&self, mut position: DVec2, size: DVec2) -> DVec2 {
if self.right {
position.x -= size.x / 2.;
}
if self.bottom {
position.y -= size.y / 2.;
}
position
}
/// Calculates the required scaling to resize the bounding box
pub fn bounds_to_scale_transform(&self, center: bool, size: DVec2) -> DAffine2 {
DAffine2::from_translation(self.offset_pivot(center, size)) * DAffine2::from_scale(size / (self.bounds[1] - self.bounds[0]))
}
}
/// Create a viewport relative bounding box overlay with no transform handles
pub fn add_bounding_box(responses: &mut VecDeque<Message>) -> Vec<LayerId> {
let path = vec![generate_uuid()];
let operation = Operation::AddRect {
path: path.clone(),
transform: DAffine2::ZERO.to_cols_array(),
style: style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, 1.0)), Fill::None),
insert_index: -1,
};
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
path
}
/// Add the transform handle overlay
fn add_transform_handles(responses: &mut VecDeque<Message>) -> [Vec<LayerId>; 8] {
const EMPTY_VEC: Vec<LayerId> = Vec::new();
let mut transform_handle_paths = [EMPTY_VEC; 8];
for item in &mut transform_handle_paths {
let current_path = vec![generate_uuid()];
let operation = Operation::AddRect {
path: current_path.clone(),
transform: DAffine2::ZERO.to_cols_array(),
style: style::PathStyle::new(Some(Stroke::new(COLOR_ACCENT, 2.0)), Fill::solid(Color::WHITE)),
insert_index: -1,
};
responses.push_back(DocumentMessage::Overlays(operation.into()).into());
*item = current_path;
}
transform_handle_paths
}
/// Converts a bounding box to a rounded transform (with translation and scale)
pub fn transform_from_box(pos1: DVec2, pos2: DVec2, transform: DAffine2) -> DAffine2 {
let inverse = transform.inverse();
transform
* DAffine2::from_scale_angle_translation(
inverse.transform_vector2(transform.transform_vector2(pos2 - pos1).round()),
0.,
inverse.transform_point2(transform.transform_point2(pos1).round() - DVec2::splat(0.5)),
)
}
/// Aligns the mouse position to the closest axis
pub fn axis_align_drag(axis_align: bool, position: DVec2, start: DVec2) -> DVec2 {
if axis_align {
let mouse_position = position - start;
let snap_resolution = SELECTION_DRAG_ANGLE.to_radians();
let angle = -mouse_position.angle_between(DVec2::X);
let snapped_angle = (angle / snap_resolution).round() * snap_resolution;
DVec2::new(snapped_angle.cos(), snapped_angle.sin()) * mouse_position.length() + start
} else {
position
}
}
/// Contains info on the overlays for the bounding box and transform handles
#[derive(Clone, Debug, Default)]
pub struct BoundingBoxOverlays {
pub bounding_box: Vec<LayerId>,
pub transform_handles: [Vec<LayerId>; 8],
pub bounds: [DVec2; 2],
pub transform: DAffine2,
pub selected_edges: Option<SelectedEdges>,
pub original_transforms: OriginalTransforms,
pub pivot: DVec2,
}
impl BoundingBoxOverlays {
#[must_use]
pub fn new(responses: &mut VecDeque<Message>) -> Self {
Self {
bounding_box: add_bounding_box(responses),
transform_handles: add_transform_handles(responses),
..Default::default()
}
}
/// Calculates the transformed handle positions based on the bounding box and the transform
pub fn evaluate_transform_handle_positions(&self) -> [DVec2; 8] {
let (left, top): (f64, f64) = self.bounds[0].into();
let (right, bottom): (f64, f64) = self.bounds[1].into();
[
self.transform.transform_point2(DVec2::new(left, top)),
self.transform.transform_point2(DVec2::new(left, (top + bottom) / 2.)),
self.transform.transform_point2(DVec2::new(left, bottom)),
self.transform.transform_point2(DVec2::new((left + right) / 2., top)),
self.transform.transform_point2(DVec2::new((left + right) / 2., bottom)),
self.transform.transform_point2(DVec2::new(right, top)),
self.transform.transform_point2(DVec2::new(right, (top + bottom) / 2.)),
self.transform.transform_point2(DVec2::new(right, bottom)),
]
}
/// Update the position of the bounding box and transform handles
pub fn transform(&mut self, responses: &mut VecDeque<Message>) {
let transform = transform_from_box(self.bounds[0], self.bounds[1], self.transform).to_cols_array();
let path = self.bounding_box.clone();
responses.push_back(DocumentMessage::Overlays(Operation::SetLayerTransformInViewport { path, transform }.into()).into());
// Helps push values that end in approximately half, plus or minus some floating point imprecision, towards the same side of the round() function
const BIAS: f64 = 0.0001;
for (position, path) in self.evaluate_transform_handle_positions().into_iter().zip(&self.transform_handles) {
let scale = DVec2::splat(MANIPULATOR_GROUP_MARKER_SIZE);
let translation = (position - (scale / 2.) - 0.5 + BIAS).round();
let transform = DAffine2::from_scale_angle_translation(scale, 0., translation).to_cols_array();
let path = path.clone();
responses.push_back(DocumentMessage::Overlays(Operation::SetLayerTransformInViewport { path, transform }.into()).into());
}
}
/// Check if the user has selected the edge for dragging (returns which edge in order top, bottom, left, right)
pub fn check_selected_edges(&self, cursor: DVec2) -> Option<(bool, bool, bool, bool)> {
let cursor = self.transform.inverse().transform_point2(cursor);
let select_threshold = self.transform.inverse().transform_vector2(DVec2::new(0., BOUNDS_SELECT_THRESHOLD)).length();
let min = self.bounds[0].min(self.bounds[1]);
let max = self.bounds[0].max(self.bounds[1]);
if min.x - cursor.x < select_threshold && min.y - cursor.y < select_threshold && cursor.x - max.x < select_threshold && cursor.y - max.y < select_threshold {
let mut top = (cursor.y - min.y).abs() < select_threshold;
let mut bottom = (max.y - cursor.y).abs() < select_threshold;
let mut left = (cursor.x - min.x).abs() < select_threshold;
let mut right = (max.x - cursor.x).abs() < select_threshold;
if cursor.y - min.y + max.y - cursor.y < select_threshold * 2. && (left || right) {
top = false;
bottom = false;
}
if cursor.x - min.x + max.x - cursor.x < select_threshold * 2. && (top || bottom) {
left = false;
right = false;
}
if top || bottom || left || right {
return Some((top, bottom, left, right));
}
}
None
}
/// Check if the user is rotating with the bounds
pub fn check_rotate(&self, cursor: DVec2) -> bool {
let cursor = self.transform.inverse().transform_point2(cursor);
let rotate_threshold = self.transform.inverse().transform_vector2(DVec2::new(0., BOUNDS_ROTATE_THRESHOLD)).length();
let min = self.bounds[0].min(self.bounds[1]);
let max = self.bounds[0].max(self.bounds[1]);
let outside_bounds = (min.x > cursor.x || cursor.x > max.x) || (min.y > cursor.y || cursor.y > max.y);
let inside_extended_bounds = min.x - cursor.x < rotate_threshold && min.y - cursor.y < rotate_threshold && cursor.x - max.x < rotate_threshold && cursor.y - max.y < rotate_threshold;
outside_bounds & inside_extended_bounds
}
/// Gets the required mouse cursor to show resizing bounds or optionally rotation
pub fn get_cursor(&self, input: &InputPreprocessorMessageHandler, rotate: bool) -> MouseCursorIcon {
if let Some(directions) = self.check_selected_edges(input.mouse.position) {
match directions {
(true, false, false, false) | (false, true, false, false) => MouseCursorIcon::NSResize,
(false, false, true, false) | (false, false, false, true) => MouseCursorIcon::EWResize,
(true, false, true, false) | (false, true, false, true) => MouseCursorIcon::NWSEResize,
(true, false, false, true) | (false, true, true, false) => MouseCursorIcon::NESWResize,
_ => MouseCursorIcon::Default,
}
} else if rotate && self.check_rotate(input.mouse.position) {
MouseCursorIcon::Grabbing
} else {
MouseCursorIcon::Default
}
}
/// Removes the overlays
pub fn delete(self, responses: &mut VecDeque<Message>) {
responses.push_back(DocumentMessage::Overlays(Operation::DeleteLayer { path: self.bounding_box }.into()).into());
responses.extend(
self.transform_handles
.iter()
.map(|path| DocumentMessage::Overlays(Operation::DeleteLayer { path: path.clone() }.into()).into()),
);
}
}