Repository: GraphiteEditor/Graphite (language: rust)

Issue:
Tracking Issue: Pen and Path tool improvements
Much of this is explained/demonstrated in this detailed webcast: https://youtu.be/OmveqhzXJFg

## Path tool

When dragging a handle:
- [x] <kbd>Alt</kbd> keeps the handles equidistant while pressed (instead of <kbd>Shift</kbd> in use now) (#2058)
- [x] <kbd>Alt</kbd>, as part of keeping the handles equidistant, also creates a matching handle if the other is zero-length or not a cubic Bézier (#2196)
- [x] <kbd>Shift</kbd> locks the handle angle to 15° increments (shouldn't interfere with <kbd>Shift</kbd>-clicking handles for multi-selecting points such as handles) (#2160)
- [x] <kbd>Ctrl</kbd> locks the current angle of the handle (#2160)
- [x] <kbd>Tab</kbd> swaps to dragging the opposite handle (native: teleports the cursor / web: enters pointer lock and draws a fake cursor at the new location) (#2058)
- [x] <kbd>Space</kbd> shifts the anchor (and handles) while pressed (#2065)
- [x] <kbd>C</kbd> toggles bent vs. colinear handles (instead of <kbd>Alt</kbd> in use now) (#2058)

When dragging an anchor:
- [ ] <kbd>Alt</kbd> **(new since video was recorded)**, if held during the start of the click-drag, converts the anchor's handles to colinear and drags the handle pair instead of the anchor, keeping them equidistant unless <kbd>Alt</kbd> is released to temporarily return the opposite handle back to where it started before the <kbd>Alt</kbd>-drag began (which involves returning its colinear state back to what it was before). Should work with <kbd>Tab</kbd> to swap which is the dragged handle, so its opposite can be the one that's returned if <kbd>Alt</kbd> is temporarily released. Just <kbd>Alt</kbd> clicking but not dragging the anchor should remove both handles by setting them to zero length.
- [ ] <kbd>Ctrl</kbd> **(new since video was recorded)**, if pressed before the drag begins, should select and drag a zero-length handle out of its anchor locked to the angle of the opposite non-zero-length handle, which it should be made colinear to. This applies only to anchors with two handles where exactly one is zero-length. Otherwise, the key is ignored and the anchor is dragged per usual. One more scenario is where a non-endpoint anchor has no handles (they're both zero-length), if <kbd>Ctrl</kbd> and <kbd>Alt</kbd> (see previous bullet point) are both pressed before dragging, it locks the angle to that of the [line perpendicular to the average of the two tangents](https://files.keavon.com/-/NovelGruesomePangolin/capture.png) from that anchor to its adjacent curves.
- [ ] <kbd>Shift</kbd>, locks the drag to the nearer of the X or Y axes from its drag starting point. (If pressed before the drag begins, it shouldn't break <kbd>Shift</kbd>-clicking points to add to the selection.)
- [ ] <kbd>Ctrl</kbd><kbd>Shift</kbd> **(updated since video was recorded which indicated this would use <kbd>Alt</kbd>)** slides the anchor along its adjacent segment(s) while adjusting its handle(s) to best approximate the initial curvature. This will require a computational geometry algorithm researched and added to our Bezier-rs library. (If pressed before the drag begins, it shouldn't break <kbd>Shift</kbd>-clicking points to add to the selection.)

When double-clicking an anchor **(new since video was recorded)**:
- [ ] Currently this swaps between smooth and sharp, but doesn't work if multiple handles are multi-selected to convert them all to smooth or sharp. If they're of mixed type, the specific on that's double clicked on should be the decider for the rest of them as to which they should all be swapped to.

When clicking a segment **(new since video was recorded)**:
- [ ] Clicking without any modifier key should split the segment where clicked. Currently this has the extra complication of entering an insertion mode where the point of the segment split can be slid within the segment and left click confirms it while right click cancels. We want to remove that extra step and just insert directly. An overlay should be drawn in cases where the cursor is hovered over the segment such that clicking would insert a split, it should be a short line segment (20px in diameter) running perpendicular to the curve.
- [ ] <kbd>Ctrl</kbd> clicking should delete the segment that's clicked. Currently a user would have to split the segment then delete the newly created point.
- [ ] Clicking and dragging without any modifier key should [mold the segment](https://pomax.github.io/bezierinfo/#molding) as per #615.

When a single handle is selected:
- [x] <kbd>R</kbd> rotates about its anchor (#2180)
- [x] <kbd>S</kbd> scales about its anchor (#2180)

## Pen tool

When no drawing has begun yet (pointer is up):
- [x] **(New since video was recorded)** clicking a path's endpoint should begin drawing from it with an initial handle that's colinear and equidistant from the opposite handle, instead of the current behavior where clicking the endpoint begins drawing the segment with a zero-length handle. If the user wants the current behavior, they can simply click the endpoint anchor a second time to make the current segment's handle zero-length. This solves the pain point that switching away from the Pen tool, then back to it, causes a discontinuity at the previous endpoint where the handles can't easily be opposite each other like when drawing consecutive segments normally. (#2295)

When stretching out a segment to be placed (pointer is up):
- [x] <kbd>Backspace</kbd>/<kbd>Delete</kbd> removes the current segment's handle (equivalent to clicking the current anchor) (#2180)
- [x] <kbd>G</kbd> grabs (translates) the current segment's connected outgoing handle (#2211)
- [x] <kbd>R</kbd> rotates the current segment's connected outgoing handle about its anchor (#2211)
- [x] <kbd>S</kbd> scales the current segment's connected outgoing handle about its anchor (#2211)

When dragging the handles of the segment being placed (pointer is down):
- [x] <kbd>C</kbd> toggles bent vs. colinear handles (instead of the momentary <kbd>Alt</kbd> in use now) (#2242)
- [x] <kbd>Alt</kbd> stops keeping the handles equidistant while pressed, as long as they're currently colinear (otherwise it does nothing). Exception: the reverse is the case (it keeps the handles equidistant while pressed) when the click-drag began with a single handle (either by click-dragging the current segment's connected anchor, click-dragging an endpoint of an existing not-yet-being-edited layer, or click-dragging the start point to close the shape) but <kbd>Ctrl</kbd> was pressed to keep (#2242)
- [x] <kbd>Ctrl</kbd> locks the current angle of the handle (already implemented), but should also work to be colinear with the opposite handle if being dragged out of an existing anchor point, or if that anchor point has no handle then it should use the angle of the actual curve segment entering that handle, i.e. its tangent angle at its endpoint (#2284)
- [ ] <kbd>Space</kbd> shifts the anchor (and handles) while pressed
- [ ] <kbd>Tab</kbd> swaps to dragging the opposite handle (native: teleports the cursor / web: enters pointer lock and draws a fake cursor at the new location)
- [ ] If the current segment is closing the shape by connecting to its start point, the handle that's being dragged should be the closing handle, not a fake handle on the opposite side, and all the above shortcuts should work on that anchor/handle group spanning the start/end point (<kbd>Tab</kbd> will modify the shape of the first segment while the current/final segment is still in-progress)
- [ ] All the above shortcuts should work with the "Bend Prev. Point" case where the current segment's connected anchor can be clicked to turn it sharp or click-dragged to bend its outgoing handle (turning its handles to not colinear), meaning <kbd>C</kbd> should be able to turn it back to colinear

---

- Not yet figured out: improving the UX for extending an endpoint with a new segment, by having control to extend the handle on either end of the new segment instead of just the new endpoint's side, and by locking the angle of the new endpoint side's handle to avoid a discontinuity. [Video](https://files.keavon.com/-/PoliticalGiantQueensnake/capture_22_.mp4).


Discussion / hints:
Aight, I start with it. Wish me luck
Here are some more potential additions (coming from features I found useful in an abandoned vector graphics editor I had been working on years ago; originally listed [here](https://news.ycombinator.com/item?id=41854972)):

- shift+G/R/S (or some other modifier) for setting handle mode (bent, colinear, and colinear+equidistant respectively) is a potential intuitive keybind option kinda following what regular g/r/s do;
- that handle mode can be displayed visually as different icons on the point (square for bent, rectangle aligned to angle for colinear, and perhaps circle for equidistant, though that may get confusing with handles being circles; ellipse?)
- allow both rotate and scale at the same time (maybe never useful but I still had this ¯\\\_(ツ)\_/¯)
- middle-mouse-dragging while holding an element should ignore the delta mouse movement during the movement (currently doing this in Graphite results in jumpiness)
- another option for visual indicators r/g/s:
  - g: a line from the starting mouse position in the canvas to where it'd be dragged to
  - s: line from the anchor point through the current and original mouse position with different colors (i.e. the ratio of the color lengths is the ratio of scaling)
  - r: lines from the anchor to original & current mouse position, with an arc in between (very busy-looking, don't quite like it)

Some general actions:
- cut a path into two, snapping to cutting on an existing point if near enough (potentially, if dragging, could cut into three segments)
- join paths if two end-points are selected (incl. closing a path)
- select all points linked to currently already selected ones

[screen recording](https://github.com/user-attachments/assets/f64318f6-7f70-4b6e-88ad-33edaccffed8) showing some of these in my editor


Thank you for posting those here @dzaima! The feedback and ideas are very useful.
Hey, I plan working on the remaining few things for the path tool. I will be traveling for the next few weeks so wont be able to start anytime soon. Although if anyone else wants to pick them up before im back feel free!
@DaraghD hello again, I hope your travels were fruitful! Just wanted to see if you're interested in returning to some of the bullet points in this issue. In particular, the Pen tool ones aren't being attempted by anybody yet so those would be free to work on anytime you'd like, perhaps if you have some time over the holidays. Cheers!
#2160 will add the following requested features-
> - [x] <kbd>Shift</kbd> locks the handle angle to 15° increments
>   - [x] (shouldn't interfere with <kbd>Shift</kbd>-clicking handles for multi-selecting points such as handles)
> - [x] <kbd>Ctrl</kbd> locks the current angle of the handle

Fix patch:
diff --git a/editor/src/messages/input_mapper/input_mappings.rs b/editor/src/messages/input_mapper/input_mappings.rs
index f29c0fb2be..a684eba092 100644
--- a/editor/src/messages/input_mapper/input_mappings.rs
+++ b/editor/src/messages/input_mapper/input_mappings.rs
@@ -258,6 +258,8 @@ pub fn input_mappings() -> Mapping {
 		entry!(KeyDown(MouseRight); action_dispatch=PenToolMessage::Confirm),
 		entry!(KeyDown(Escape); action_dispatch=PenToolMessage::Confirm),
 		entry!(KeyDown(Enter); action_dispatch=PenToolMessage::Confirm),
+		entry!(KeyDown(Delete); action_dispatch=PenToolMessage::RemovePreviousHandle),
+		entry!(KeyDown(Backspace); action_dispatch=PenToolMessage::RemovePreviousHandle),
 		//
 		// FreehandToolMessage
 		entry!(PointerMove; action_dispatch=FreehandToolMessage::PointerMove),
diff --git a/editor/src/messages/tool/tool_message_handler.rs b/editor/src/messages/tool/tool_message_handler.rs
index ca855b90d7..239f0acc09 100644
--- a/editor/src/messages/tool/tool_message_handler.rs
+++ b/editor/src/messages/tool/tool_message_handler.rs
@@ -76,8 +76,8 @@ impl MessageHandler<ToolMessage, ToolMessageData<'_>> for ToolMessageHandler {
 				self.tool_is_active = true;
 
 				// Send the old and new tools a transition to their FSM Abort states
-				let mut send_abort_to_tool = |tool_type, update_hints_and_cursor: bool| {
-					if let Some(tool) = tool_data.tools.get_mut(&tool_type) {
+				let mut send_abort_to_tool = |old_tool: ToolType, new_tool: ToolType, update_hints_and_cursor: bool| {
+					if let Some(tool) = tool_data.tools.get_mut(&new_tool) {
 						let mut data = ToolActionHandlerData {
 							document,
 							document_id,
@@ -101,9 +101,14 @@ impl MessageHandler<ToolMessage, ToolMessageData<'_>> for ToolMessageHandler {
 							tool.process_message(ToolMessage::UpdateCursor, responses, &mut data);
 						}
 					}
+
+					if matches!(old_tool, ToolType::Path | ToolType::Select) {
+						responses.add(TransformLayerMessage::CancelTransformOperation);
+					}
 				};
-				send_abort_to_tool(tool_type, true);
-				send_abort_to_tool(old_tool, false);
+
+				send_abort_to_tool(old_tool, tool_type, true);
+				send_abort_to_tool(old_tool, old_tool, false);
 
 				// Unsubscribe old tool from the broadcaster
 				tool_data.tools.get(&tool_type).unwrap().deactivate(responses);
diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs
index ab582d5eaf..e883a87f9a 100644
--- a/editor/src/messages/tool/tool_messages/path_tool.rs
+++ b/editor/src/messages/tool/tool_messages/path_tool.rs
@@ -648,19 +648,7 @@ impl Fsm for PathToolFsmState {
 				self
 			}
 			(Self::InsertPoint, PathToolMessage::Escape | PathToolMessage::Delete | PathToolMessage::RightClick) => tool_data.end_insertion(shape_editor, responses, InsertEndKind::Abort),
-			(Self::InsertPoint, PathToolMessage::GRS { key: propagate }) => {
-				// MAYBE: use `InputMapperMessage::KeyDown(..)` instead
-				match propagate {
-					// TODO: Don't use `Key::G` directly, instead take it as a variable from the input mappings list like in all other places
-					Key::KeyG => responses.add(TransformLayerMessage::BeginGrab),
-					// TODO: Don't use `Key::R` directly, instead take it as a variable from the input mappings list like in all other places
-					Key::KeyR => responses.add(TransformLayerMessage::BeginRotate),
-					// TODO: Don't use `Key::S` directly, instead take it as a variable from the input mappings list like in all other places
-					Key::KeyS => responses.add(TransformLayerMessage::BeginScale),
-					_ => warn!("Unexpected GRS key"),
-				}
-				tool_data.end_insertion(shape_editor, responses, InsertEndKind::Abort)
-			}
+			(Self::InsertPoint, PathToolMessage::GRS { key: _ }) => PathToolFsmState::InsertPoint,
 			// Mouse down
 			(
 				_,
diff --git a/editor/src/messages/tool/tool_messages/pen_tool.rs b/editor/src/messages/tool/tool_messages/pen_tool.rs
index 356200de3c..1d2169ca30 100644
--- a/editor/src/messages/tool/tool_messages/pen_tool.rs
+++ b/editor/src/messages/tool/tool_messages/pen_tool.rs
@@ -62,6 +62,7 @@ pub enum PenToolMessage {
 	Undo,
 	UpdateOptions(PenOptionsUpdate),
 	RecalculateLatestPointsPosition,
+	RemovePreviousHandle,
 }
 
 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -175,6 +176,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionHandlerData<'a>> for PenTool
 				PointerMove,
 				Confirm,
 				Abort,
+				RemovePreviousHandle,
 			),
 		}
 	}
@@ -685,6 +687,15 @@ impl Fsm for PenToolFsmState {
 					PenToolFsmState::PlacingAnchor
 				}
 			}
+			(PenToolFsmState::PlacingAnchor, PenToolMessage::RemovePreviousHandle) => {
+				if let Some(last_point) = tool_data.latest_points.last_mut() {
+					last_point.handle_start = last_point.pos;
+					responses.add(OverlaysMessage::Draw);
+				} else {
+					log::warn!("No latest point available to modify handle_start.");
+				}
+				self
+			}
 			(PenToolFsmState::DraggingHandle, PenToolMessage::DragStop) => tool_data
 				.finish_placing_handle(SnapData::new(document, input), transform, responses)
 				.unwrap_or(PenToolFsmState::PlacingAnchor),
diff --git a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs
index 6b2f3ac525..477796c89c 100644
--- a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs
+++ b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs
@@ -43,6 +43,7 @@ type TransformData<'a> = (&'a DocumentMessageHandler, &'a InputPreprocessorMessa
 impl MessageHandler<TransformLayerMessage, TransformData<'_>> for TransformLayerMessageHandler {
 	fn process_message(&mut self, message: TransformLayerMessage, responses: &mut VecDeque<Message>, (document, input, tool_data, shape_editor): TransformData) {
 		let using_path_tool = tool_data.active_tool_type == ToolType::Path;
+		let using_select_tool = tool_data.active_tool_type == ToolType::Select;
 
 		// TODO: Add support for transforming layer not in the document network
 		let selected_layers = document
@@ -75,10 +76,18 @@ impl MessageHandler<TransformLayerMessage, TransformData<'_>> for TransformLayer
 					let viewspace = document.metadata().transform_to_viewport(selected_layers[0]);
 
 					let mut point_count: usize = 0;
-					let get_location = |point: &ManipulatorPointId| point.get_position(&vector_data).map(|position| viewspace.transform_point2(position));
+					let get_location = |point: &&ManipulatorPointId| point.get_position(&vector_data).map(|position| viewspace.transform_point2(position));
 					let points = shape_editor.selected_points();
-
-					*selected.pivot = points.filter_map(get_location).inspect(|_| point_count += 1).sum::<DVec2>() / point_count as f64;
+					let selected_points: Vec<&ManipulatorPointId> = points.collect();
+
+					if let [point] = selected_points.as_slice() {
+						if let ManipulatorPointId::PrimaryHandle(_) | ManipulatorPointId::EndHandle(_) = point {
+							let anchor_position = point.get_anchor_position(&vector_data).unwrap();
+							*selected.pivot = viewspace.transform_point2(anchor_position);
+						} else {
+							*selected.pivot = selected_points.iter().filter_map(get_location).inspect(|_| point_count += 1).sum::<DVec2>() / point_count as f64;
+						}
+					}
 				}
 			} else {
 				*selected.pivot = selected.mean_average_of_pivots();
@@ -104,12 +113,13 @@ impl MessageHandler<TransformLayerMessage, TransformData<'_>> for TransformLayer
 				responses.add(NodeGraphMessage::RunDocumentGraph);
 			}
 			TransformLayerMessage::BeginGrab => {
-				if let TransformOperation::Grabbing(_) = self.transform_operation {
-					return;
-				}
+				if (!using_path_tool && !using_select_tool)
+					|| (using_path_tool && shape_editor.selected_points().next().is_none())
+					|| selected_layers.is_empty()
+					|| matches!(self.transform_operation, TransformOperation::Grabbing(_))
+				{
+					selected.original_transforms.clear();
 
-				// Don't allow grab with no selected layers
-				if selected_layers.is_empty() {
 					return;
 				}
 
@@ -120,13 +130,42 @@ impl MessageHandler<TransformLayerMessage, TransformData<'_>> for TransformLayer
 				selected.original_transforms.clear();
 			}
 			TransformLayerMessage::BeginRotate => {
-				if let TransformOperation::Rotating(_) = self.transform_operation {
+				let selected_points: Vec<&ManipulatorPointId> = shape_editor.selected_points().collect();
+
+				if (!using_path_tool && !using_select_tool)
+					|| (using_path_tool && selected_points.is_empty())
+					|| selected_layers.is_empty()
+					|| matches!(self.transform_operation, TransformOperation::Rotating(_))
+				{
+					selected.original_transforms.clear();
 					return;
 				}
 
-				// Don't allow rotate with no selected layers
-				if selected_layers.is_empty() {
+				let Some(vector_data) = selected_layers.first().and_then(|&layer| document.network_interface.compute_modified_vector(layer)) else {
+					selected.original_transforms.clear();
 					return;
+				};
+
+				if let [point] = selected_points.as_slice() {
+					if matches!(point, ManipulatorPointId::Anchor(_)) {
+						if let Some([handle1, handle2]) = point.get_handle_pair(&vector_data) {
+							let handle1_length = handle1.length(&vector_data);
+							let handle2_length = handle2.length(&vector_data);
+
+							if (handle1_length == 0. && handle2_length == 0.) || (handle1_length == f64::MAX && handle2_length == f64::MAX) {
+								return;
+							}
+						}
+					} else {
+						// TODO: Fix handle snap to anchor issue, see <https://discord.com/channels/731730685944922173/1217752903209713715>
+
+						let handle_length = point.as_handle().map(|handle| handle.length(&vector_data));
+
+						if handle_length == Some(0.) {
+							selected.original_transforms.clear();
+							return;
+						}
+					}
 				}
 
 				begin_operation(self.transform_operation, &mut self.typing, &mut self.mouse_position, &mut self.start_mouse);
@@ -136,13 +175,41 @@ impl MessageHandler<TransformLayerMessage, TransformData<'_>> for TransformLayer
 				selected.original_transforms.clear();
 			}
 			TransformLayerMessage::BeginScale => {
-				if let TransformOperation::Scaling(_) = self.transform_operation {
+				let selected_points: Vec<&ManipulatorPointId> = shape_editor.selected_points().collect();
+
+				if (using_path_tool && selected_points.is_empty())
+					|| (!using_path_tool && !using_select_tool)
+					|| selected_layers.is_empty()
+					|| matches!(self.transform_operation, TransformOperation::Scaling(_))
+				{
+					selected.original_transforms.clear();
 					return;
 				}
 
-				// Don't allow scale with no selected layers
-				if selected_layers.is_empty() {
+				let Some(vector_data) = selected_layers.first().and_then(|&layer| document.network_interface.compute_modified_vector(layer)) else {
+					selected.original_transforms.clear();
 					return;
+				};
+
+				if let [point] = selected_points.as_slice() {
+					if matches!(point, ManipulatorPointId::Anchor(_)) {
+						if let Some([handle1, handle2]) = point.get_handle_pair(&vector_data) {
+							let handle1_length = handle1.length(&vector_data);
+							let handle2_length = handle2.length(&vector_data);
+
+							if (handle1_length == 0. && handle2_length == 0.) || (handle1_length == f64::MAX && handle2_length == f64::MAX) {
+								selected.original_transforms.clear();
+								return;
+							}
+						}
+					} else {
+						let handle_length = point.as_handle().map(|handle| handle.length(&vector_data));
+
+						if handle_length == Some(0.) {
+							selected.original_transforms.clear();
+							return;
+						}
+					}
 				}
 
 				begin_operation(self.transform_operation, &mut self.typing, &mut self.mouse_position, &mut self.start_mouse);
@@ -215,6 +282,7 @@ impl MessageHandler<TransformLayerMessage, TransformData<'_>> for TransformLayer
 						}
 					};
 				}
+
 				self.mouse_position = input.mouse.position;
 			}
 			TransformLayerMessage::SelectionChanged => {
diff --git a/node-graph/gcore/src/vector/vector_data.rs b/node-graph/gcore/src/vector/vector_data.rs
index 21e5630b05..93cadbbb52 100644
--- a/node-graph/gcore/src/vector/vector_data.rs
+++ b/node-graph/gcore/src/vector/vector_data.rs
@@ -306,6 +306,13 @@ impl ManipulatorPointId {
 		}
 	}
 
+	pub fn get_anchor_position(&self, vector_data: &VectorData) -> Option<DVec2> {
+		match self {
+			ManipulatorPointId::EndHandle(_) | ManipulatorPointId::PrimaryHandle(_) => self.get_anchor(vector_data).and_then(|id| vector_data.point_domain.position_from_id(id)),
+			_ => self.get_position(vector_data),
+		}
+	}
+
 	/// Attempt to get a pair of handles. For an anchor this is the first two handles connected. For a handle it is self and the first opposing handle.
 	#[must_use]
 	pub fn get_handle_pair(self, vector_data: &VectorData) -> Option<[HandleId; 2]> {
@@ -396,6 +403,13 @@ impl HandleId {
 		}
 	}
 
+	/// Calculate the magnitude of the handle from the anchor.
+	pub fn length(self, vector_data: &VectorData) -> f64 {
+		let anchor_position = self.to_manipulator_point().get_anchor_position(vector_data).unwrap();
+		let handle_position = self.to_manipulator_point().get_position(vector_data);
+		handle_position.map(|pos| (pos - anchor_position).length()).unwrap_or(f64::MAX)
+	}
+
 	/// Set the handle's position relative to the anchor which is the start anchor for the primary handle and end anchor for the end handle.
 	#[must_use]
 	pub fn set_relative_position(self, relative_position: DVec2) -> VectorModificationType {


Test patch: