-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathpath_tool.rs
More file actions
3672 lines (3194 loc) · 139 KB
/
path_tool.rs
File metadata and controls
3672 lines (3194 loc) · 139 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::select_tool::extend_lasso;
use super::tool_prelude::*;
use crate::consts::{
COLOR_OVERLAY_BLUE, COLOR_OVERLAY_GRAY, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, DEFAULT_STROKE_WIDTH, DOUBLE_CLICK_MILLISECONDS, DRAG_DIRECTION_MODE_DETERMINATION_THRESHOLD, DRAG_THRESHOLD,
DRILL_THROUGH_THRESHOLD, HANDLE_ROTATE_SNAP_ANGLE, SEGMENT_INSERTION_DISTANCE, SEGMENT_OVERLAY_SIZE, SELECTION_THRESHOLD, SELECTION_TOLERANCE,
};
use crate::messages::clipboard::utility_types::ClipboardContent;
use crate::messages::input_mapper::utility_types::macros::action_shortcut_manual;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::{path_overlays, selected_segments};
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::document::utility_types::transformation::Axis;
use crate::messages::preferences::SelectionMode;
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::pivot::{PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget};
use crate::messages::tool::common_functionality::shape_editor::{
ClosestSegment, ManipulatorAngle, OpposingHandleLengths, SelectedLayerState, SelectedPointsInfo, SelectionChange, SelectionShape, SelectionShapeType, ShapeState,
};
use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager};
use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, find_two_param_best_approximate, make_path_editable_is_allowed};
use graphene_std::Color;
use graphene_std::renderer::Quad;
use graphene_std::subpath::pathseg_points;
use graphene_std::transform::ReferencePoint;
use graphene_std::uuid::NodeId;
use graphene_std::vector::algorithms::util::pathseg_tangent;
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2};
use graphene_std::vector::{HandleExt, NoHashBuilder, PointId, SegmentId, Vector, VectorModificationType};
use kurbo::{DEFAULT_ACCURACY, ParamCurve, ParamCurveNearest, PathSeg, Rect};
use std::vec;
#[derive(Default, ExtractField)]
pub struct PathTool {
fsm_state: PathToolFsmState,
tool_data: PathToolData,
options: PathToolOptions,
}
#[derive(Default)]
pub struct PathToolOptions {
path_overlay_mode: PathOverlayMode,
path_editing_mode: PathEditingMode,
}
#[impl_message(Message, ToolMessage, Path)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum PathToolMessage {
// Standard messages
Abort,
SelectionChanged,
Overlays {
context: OverlayContext,
},
// Tool-specific messages
BreakPath,
DeselectAllSelected,
Delete,
DeleteAndBreakPath,
DragStop {
extend_selection: Key,
shrink_selection: Key,
},
Enter {
extend_selection: Key,
shrink_selection: Key,
},
Escape,
ClosePath,
ConnectPointsByPosition {
layer: LayerNodeIdentifier,
start_position: DVec2,
end_position: DVec2,
},
DoubleClick {
extend_selection: Key,
shrink_selection: Key,
},
GRS {
// Should be `Key::KeyG` (Grab), `Key::KeyR` (Rotate), or `Key::KeyS` (Scale)
key: Key,
},
ManipulatorMakeHandlesFree,
ManipulatorMakeHandlesColinear,
MouseDown {
extend_selection: Key,
lasso_select: Key,
handle_drag_from_anchor: Key,
drag_restore_handle: Key,
segment_editing_modifier: Key,
},
NudgeSelectedPoints {
delta_x: f64,
delta_y: f64,
},
PointerMove {
equidistant: Key,
toggle_colinear: Key,
move_anchor_with_handles: Key,
snap_angle: Key,
lock_angle: Key,
delete_segment: Key,
break_colinear_molding: Key,
segment_editing_modifier: Key,
},
PointerOutsideViewport {
equidistant: Key,
toggle_colinear: Key,
move_anchor_with_handles: Key,
snap_angle: Key,
lock_angle: Key,
delete_segment: Key,
break_colinear_molding: Key,
segment_editing_modifier: Key,
},
RightClick,
SelectAll,
SelectedPointUpdated,
SelectedPointXChanged {
new_x: f64,
},
SelectedPointYChanged {
new_y: f64,
},
SetPivot {
position: ReferencePoint,
},
SwapSelectedHandles,
UpdateOptions {
options: PathOptionsUpdate,
},
UpdateSelectedPointsStatus {
overlay_context: OverlayContext,
},
StartSlidingPoint,
Copy {
clipboard: Clipboard,
},
Cut {
clipboard: Clipboard,
},
Paste {
data: String,
},
DeleteSelected,
Duplicate,
TogglePointEditing,
ToggleSegmentEditing,
}
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug, Default, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum PathOverlayMode {
AllHandles = 0,
#[default]
SelectedPointHandles = 1,
FrontierHandles = 2,
}
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
pub struct PathEditingMode {
point_editing_mode: bool,
segment_editing_mode: bool,
}
impl Default for PathEditingMode {
fn default() -> Self {
Self {
point_editing_mode: true,
segment_editing_mode: false,
}
}
}
#[derive(PartialEq, Eq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum PathOptionsUpdate {
OverlayModeType(PathOverlayMode),
PointEditingMode { enabled: bool },
SegmentEditingMode { enabled: bool },
PivotGizmoType(PivotGizmoType),
SetPivotGizmoEnabled(bool),
TogglePivotPinned,
}
impl ToolMetadata for PathTool {
fn icon_name(&self) -> String {
"VectorPathTool".into()
}
fn tooltip_label(&self) -> String {
"Path Tool".into()
}
fn tool_type(&self) -> crate::messages::tool::utility_types::ToolType {
ToolType::Path
}
}
impl LayoutHolder for PathTool {
fn layout(&self) -> Layout {
let coordinates = self.tool_data.selection_status.as_one().as_ref().map(|point| point.coordinates);
let (x, y) = coordinates.map(|point| (Some(point.x), Some(point.y))).unwrap_or((None, None));
let selection_status = &self.tool_data.selection_status;
let manipulator_angle = selection_status.angle();
let x_location = NumberInput::new(x)
.unit(" px")
.label("X")
.min_width(120)
.disabled(x.is_none())
.min(-((1_u64 << f64::MANTISSA_DIGITS) as f64))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.on_update(move |number_input: &NumberInput| {
if let Some(new_x) = number_input.value.or(x) {
PathToolMessage::SelectedPointXChanged { new_x }.into()
} else {
Message::NoOp
}
})
.widget_instance();
let y_location = NumberInput::new(y)
.unit(" px")
.label("Y")
.min_width(120)
.disabled(y.is_none())
.min(-((1_u64 << f64::MANTISSA_DIGITS) as f64))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.on_update(move |number_input: &NumberInput| {
if let Some(new_y) = number_input.value.or(y) {
PathToolMessage::SelectedPointYChanged { new_y }.into()
} else {
Message::NoOp
}
})
.widget_instance();
let related_seperator = Separator::new(SeparatorStyle::Related).widget_instance();
let unrelated_seperator = Separator::new(SeparatorStyle::Unrelated).widget_instance();
let colinear_handles_description = "Keep both handles unbent, each 180° apart, when moving either.";
let colinear_handles_state = manipulator_angle.and_then(|angle| match angle {
ManipulatorAngle::Colinear => Some(true),
ManipulatorAngle::Free => Some(false),
ManipulatorAngle::Mixed => None,
})
// TODO: Remove `unwrap_or_default` once checkboxes are capable of displaying a mixed state
.unwrap_or_default();
let checkbox_id = CheckboxId::new();
let colinear_handle_checkbox = CheckboxInput::new(colinear_handles_state)
.disabled(!self.tool_data.can_toggle_colinearity)
.on_update(|&CheckboxInput { checked, .. }| {
if checked {
PathToolMessage::ManipulatorMakeHandlesColinear.into()
} else {
PathToolMessage::ManipulatorMakeHandlesFree.into()
}
})
.tooltip_label("Colinear Handles")
.tooltip_description(colinear_handles_description)
.for_label(checkbox_id)
.widget_instance();
let colinear_handles_label = TextLabel::new("Colinear Handles")
.disabled(!self.tool_data.can_toggle_colinearity)
.tooltip_label("Colinear Handles")
.tooltip_description(colinear_handles_description)
.for_checkbox(checkbox_id)
.widget_instance();
let point_editing_mode = CheckboxInput::new(self.options.path_editing_mode.point_editing_mode)
// TODO(Keavon): Replace with a real icon
.icon("Dot")
.tooltip_label("Point Editing Mode")
.tooltip_description("To multi-select modes, perform the shortcut shown.")
.tooltip_shortcut(action_shortcut_manual!(Key::Shift, Key::MouseLeft))
.on_update(|_| PathToolMessage::TogglePointEditing.into())
.widget_instance();
let segment_editing_mode = CheckboxInput::new(self.options.path_editing_mode.segment_editing_mode)
// TODO(Keavon): Replace with a real icon
.icon("Remove")
.tooltip_label("Segment Editing Mode")
.tooltip_description("To multi-select modes, perform the shortcut shown.")
.tooltip_shortcut(action_shortcut_manual!(Key::Shift, Key::MouseLeft))
.on_update(|_| PathToolMessage::ToggleSegmentEditing.into())
.widget_instance();
let path_overlay_mode_widget = RadioInput::new(vec![
RadioEntryData::new("all")
.icon("HandleVisibilityAll")
.tooltip_label("Show All Handles")
.tooltip_description("Show all handles regardless of selection.")
.on_update(move |_| {
PathToolMessage::UpdateOptions {
options: PathOptionsUpdate::OverlayModeType(PathOverlayMode::AllHandles),
}
.into()
}),
RadioEntryData::new("selected")
.icon("HandleVisibilitySelected")
.tooltip_label("Show Connected Handles")
.tooltip_description("Show only handles of the segments connected to selected points.")
.on_update(move |_| {
PathToolMessage::UpdateOptions {
options: PathOptionsUpdate::OverlayModeType(PathOverlayMode::SelectedPointHandles),
}
.into()
}),
RadioEntryData::new("frontier")
.icon("HandleVisibilityFrontier")
.tooltip_label("Show Frontier Handles")
.tooltip_description("Show only handles at the frontiers of the segments connected to selected points.")
.on_update(move |_| {
PathToolMessage::UpdateOptions {
options: PathOptionsUpdate::OverlayModeType(PathOverlayMode::FrontierHandles),
}
.into()
}),
])
.selected_index(Some(self.options.path_overlay_mode as u32))
.widget_instance();
// Works only if a single layer is selected and its type is Vector
let path_node_button = TextButton::new("Make Path Editable")
.icon(Some("NodeShape".into()))
.tooltip_label("Make Path Editable")
.tooltip_description(
"Enables the Pen and Path tools to directly edit layer geometry resulting from nondestructive operations. This inserts a 'Path' node as the last operation of the selected layer.",
)
.on_update(|_| NodeGraphMessage::AddPathNode.into())
.disabled(!self.tool_data.make_path_editable_is_allowed)
.widget_instance();
let [_checkbox, _dropdown] = {
let pivot_gizmo_type_widget = pivot_gizmo_type_widget(self.tool_data.pivot_gizmo.state, PivotToolSource::Path);
[pivot_gizmo_type_widget[0].clone(), pivot_gizmo_type_widget[2].clone()]
};
let has_something = !self.tool_data.saved_points_before_anchor_convert_smooth_sharp.is_empty();
let _pivot_reference = pivot_reference_point_widget(
has_something || !self.tool_data.pivot_gizmo.state.is_pivot(),
self.tool_data.pivot_gizmo.pivot.to_pivot_position(),
PivotToolSource::Path,
);
let _pin_pivot = pin_pivot_widget(self.tool_data.pivot_gizmo.pin_active(), false, PivotToolSource::Path);
Layout(vec![LayoutGroup::Row {
widgets: vec![
x_location,
related_seperator.clone(),
y_location,
unrelated_seperator.clone(),
colinear_handle_checkbox,
related_seperator.clone(),
colinear_handles_label,
unrelated_seperator.clone(),
point_editing_mode,
related_seperator.clone(),
segment_editing_mode,
unrelated_seperator.clone(),
path_overlay_mode_widget,
unrelated_seperator.clone(),
path_node_button,
// checkbox.clone(),
// related_seperator.clone(),
// dropdown.clone(),
// unrelated_seperator,
// pivot_reference,
// related_seperator.clone(),
// pin_pivot,
],
}])
}
}
#[message_handler_data]
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for PathTool {
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
let updating_point = message == ToolMessage::Path(PathToolMessage::SelectedPointUpdated);
match message {
ToolMessage::Path(PathToolMessage::UpdateOptions { options }) => match options {
PathOptionsUpdate::OverlayModeType(overlay_mode_type) => {
self.options.path_overlay_mode = overlay_mode_type;
responses.add(OverlaysMessage::Draw);
}
PathOptionsUpdate::PointEditingMode { enabled } => {
self.options.path_editing_mode.point_editing_mode = enabled;
responses.add(OverlaysMessage::Draw);
}
PathOptionsUpdate::SegmentEditingMode { enabled } => {
self.options.path_editing_mode.segment_editing_mode = enabled;
responses.add(OverlaysMessage::Draw);
}
PathOptionsUpdate::PivotGizmoType(gizmo_type) => {
if !self.tool_data.pivot_gizmo.state.enabled {
self.tool_data.pivot_gizmo.state.gizmo_type = gizmo_type;
responses.add(ToolMessage::UpdateHints);
let pivot_gizmo = self.tool_data.pivot_gizmo();
responses.add(TransformLayerMessage::SetPivotGizmo { pivot_gizmo });
responses.add(NodeGraphMessage::RunDocumentGraph);
self.send_layout(responses, LayoutTarget::ToolOptions);
}
}
PathOptionsUpdate::SetPivotGizmoEnabled(enabled) => {
self.tool_data.pivot_gizmo.state.enabled = enabled;
responses.add(ToolMessage::UpdateHints);
responses.add(NodeGraphMessage::RunDocumentGraph);
self.send_layout(responses, LayoutTarget::ToolOptions);
}
PathOptionsUpdate::TogglePivotPinned => {
self.tool_data.pivot_gizmo.pivot.pinned = !self.tool_data.pivot_gizmo.pivot.pinned;
responses.add(ToolMessage::UpdateHints);
responses.add(NodeGraphMessage::RunDocumentGraph);
self.send_layout(responses, LayoutTarget::ToolOptions);
}
},
ToolMessage::Path(PathToolMessage::SwapSelectedHandles) => {
if context.shape_editor.handle_with_pair_selected(&context.document.network_interface) {
context.shape_editor.alternate_selected_handles(&context.document.network_interface);
responses.add(PathToolMessage::SelectedPointUpdated);
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::None });
responses.add(OverlaysMessage::Draw);
}
}
_ => {
self.fsm_state.process_event(message, &mut self.tool_data, context, &self.options, responses, true);
}
}
if updating_point {
self.send_layout(responses, LayoutTarget::ToolOptions);
}
}
// Different actions depending on state may be wanted:
fn actions(&self) -> ActionList {
match self.fsm_state {
PathToolFsmState::Ready => actions!(PathToolMessageDiscriminant;
DoubleClick,
MouseDown,
Delete,
NudgeSelectedPoints,
Enter,
SelectAll,
DeselectAllSelected,
BreakPath,
DeleteAndBreakPath,
ClosePath,
PointerMove,
StartSlidingPoint,
Copy,
Cut,
DeleteSelected,
Paste,
Duplicate,
TogglePointEditing,
ToggleSegmentEditing
),
PathToolFsmState::Dragging(_) => actions!(PathToolMessageDiscriminant;
Escape,
RightClick,
DoubleClick,
DragStop,
PointerMove,
Delete,
BreakPath,
DeleteAndBreakPath,
SwapSelectedHandles,
StartSlidingPoint,
Copy,
Cut,
DeleteSelected,
Paste,
Duplicate,
TogglePointEditing,
ToggleSegmentEditing
),
PathToolFsmState::Drawing { .. } => actions!(PathToolMessageDiscriminant;
DoubleClick,
DragStop,
PointerMove,
Delete,
Enter,
BreakPath,
DeleteAndBreakPath,
Escape,
RightClick,
StartSlidingPoint,
TogglePointEditing,
ToggleSegmentEditing
),
PathToolFsmState::SlidingPoint => actions!(PathToolMessageDiscriminant;
PointerMove,
DragStop,
Escape,
RightClick
),
}
}
}
impl ToolTransition for PathTool {
fn event_to_message_map(&self) -> EventToMessageMap {
EventToMessageMap {
tool_abort: Some(PathToolMessage::Abort.into()),
selection_changed: Some(PathToolMessage::SelectionChanged.into()),
overlay_provider: Some(|context| PathToolMessage::Overlays { context }.into()),
..Default::default()
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DraggingState {
point_select_state: PointSelectState,
colinear: ManipulatorAngle,
}
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub enum PointSelectState {
HandleWithPair,
#[default]
HandleNoPair,
Anchor,
}
#[derive(Clone, Copy)]
pub struct SlidingSegmentData {
segment_id: SegmentId,
bezier: PathSeg,
start: PointId,
}
#[derive(Clone, Copy)]
pub struct SlidingPointInfo {
anchor: PointId,
layer: LayerNodeIdentifier,
connected_segments: [SlidingSegmentData; 2],
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum PathToolFsmState {
#[default]
Ready,
Dragging(DraggingState),
Drawing {
selection_shape: SelectionShapeType,
},
SlidingPoint,
}
#[derive(Default)]
struct PathToolData {
snap_manager: SnapManager,
lasso_polygon: Vec<DVec2>,
selection_mode: Option<SelectionMode>,
drag_start_pos: DVec2,
previous_mouse_position: DVec2,
toggle_colinear_debounce: bool,
opposing_handle_lengths: Option<OpposingHandleLengths>,
/// Describes information about the selected point(s), if any, across one or multiple shapes and manipulator point types (anchor or handle).
/// The available information varies depending on whether `None`, `One`, or `Multiple` points are currently selected.
/// NOTE: It must be updated using `update_selection_status` to ensure `can_toggle_colinearity` stays synchronized with the current selection.
selection_status: SelectionStatus,
/// `true` if we can change the current selection to colinear or not.
can_toggle_colinearity: bool,
segment: Option<ClosestSegment>,
snap_cache: SnapCache,
double_click_handled: bool,
delete_segment_pressed: bool,
segment_editing_modifier: bool,
multiple_toggle_pressed: bool,
auto_panning: AutoPanning,
saved_points_before_anchor_select_toggle: HashMap<LayerNodeIdentifier, Vec<ManipulatorPointId>>,
select_anchor_toggled: bool,
saved_selection_before_handle_drag: HashMap<LayerNodeIdentifier, (HashSet<ManipulatorPointId>, HashSet<SegmentId>)>,
handle_drag_toggle: bool,
saved_points_before_anchor_convert_smooth_sharp: HashMap<LayerNodeIdentifier, Vec<ManipulatorPointId>>,
last_click_time: u64,
dragging_state: DraggingState,
angle: f64,
pivot_gizmo: PivotGizmo,
ordered_points: Vec<ManipulatorPointId>,
opposite_handle_position: Option<DVec2>,
last_clicked_point_was_selected: bool,
last_clicked_segment_was_selected: bool,
snapping_axis: Option<Axis>,
alt_clicked_on_anchor: bool,
alt_dragging_from_anchor: bool,
angle_locked: bool,
temporary_colinear_handles: bool,
molding_info: Option<(DVec2, DVec2)>,
molding_segment: bool,
temporary_adjacent_handles_while_molding: Option<[Option<HandleId>; 2]>,
frontier_handles_info: Option<HashMap<LayerNodeIdentifier, HashMap<SegmentId, Vec<PointId>>>>,
adjacent_anchor_offset: Option<DVec2>,
sliding_point_info: Option<SlidingPointInfo>,
started_drawing_from_inside: bool,
first_selected_with_single_click: bool,
stored_selection: Option<HashMap<LayerNodeIdentifier, SelectedLayerState>>,
last_drill_through_click_position: Option<DVec2>,
drill_through_cycle_index: usize,
drill_through_cycle_count: usize,
hovered_layers: Vec<LayerNodeIdentifier>,
ghost_outline: Vec<(Vec<ClickTargetType>, LayerNodeIdentifier)>,
make_path_editable_is_allowed: bool,
}
impl PathToolData {
fn save_points_before_anchor_toggle(&mut self, points: HashMap<LayerNodeIdentifier, Vec<ManipulatorPointId>>) -> PathToolFsmState {
self.saved_points_before_anchor_select_toggle = points;
PathToolFsmState::Dragging(self.dragging_state)
}
pub fn selection_quad(&self, metadata: &DocumentMetadata) -> Quad {
let bbox = self.selection_box(metadata);
Quad::from_box(bbox)
}
pub fn calculate_selection_mode_from_direction(&mut self, metadata: &DocumentMetadata) -> SelectionMode {
let bbox = self.selection_box(metadata);
let above_threshold = bbox[1].distance_squared(bbox[0]) > DRAG_DIRECTION_MODE_DETERMINATION_THRESHOLD.powi(2);
if self.selection_mode.is_none() && above_threshold {
let mode = if bbox[1].x < bbox[0].x {
SelectionMode::Touched
} else {
// This also covers the case where they're equal: the area is zero, so we use `Enclosed` to ensure the selection ends up empty, as nothing will be enclosed by an empty area
SelectionMode::Enclosed
};
self.selection_mode = Some(mode);
}
self.selection_mode.unwrap_or(SelectionMode::Touched)
}
pub fn selection_box(&self, metadata: &DocumentMetadata) -> [DVec2; 2] {
// Convert previous mouse position to viewport space first
let document_to_viewport = metadata.document_to_viewport;
let previous_mouse = document_to_viewport.transform_point2(self.previous_mouse_position);
if previous_mouse == self.drag_start_pos {
let tolerance = DVec2::splat(SELECTION_TOLERANCE);
[self.drag_start_pos - tolerance, self.drag_start_pos + tolerance]
} else {
[self.drag_start_pos, previous_mouse]
}
}
fn update_selection_status(&mut self, shape_editor: &mut ShapeState, document: &DocumentMessageHandler) {
let selection_status = get_selection_status(&document.network_interface, shape_editor);
self.can_toggle_colinearity = match &selection_status {
SelectionStatus::None => false,
SelectionStatus::One(single_selected_point) => {
let vector = document.network_interface.compute_modified_vector(single_selected_point.layer).unwrap();
if single_selected_point.id.get_handle_pair(&vector).is_some() {
let anchor = single_selected_point.id.get_anchor(&vector).expect("Cannot find connected anchor");
vector.all_connected(anchor).count() <= 2
} else {
false
}
}
SelectionStatus::Multiple(_) => true,
};
self.selection_status = selection_status;
}
fn remove_saved_points(&mut self) {
self.saved_points_before_anchor_select_toggle.clear();
}
fn reset_drill_through_cycle(&mut self) {
self.last_drill_through_click_position = None;
self.drill_through_cycle_index = 0;
}
fn next_drill_through_cycle(&mut self, position: DVec2) -> usize {
if self.last_drill_through_click_position.is_none_or(|last_pos| last_pos.distance(position) > DRILL_THROUGH_THRESHOLD) {
// New position, reset cycle
self.drill_through_cycle_index = 0;
} else {
// Same position, advance cycle
self.drill_through_cycle_index = (self.drill_through_cycle_index + 1) % self.drill_through_cycle_count.max(1);
}
self.last_drill_through_click_position = Some(position);
self.drill_through_cycle_index
}
fn peek_drill_through_index(&self) -> usize {
if self.drill_through_cycle_count == 0 {
0
} else {
(self.drill_through_cycle_index + 1) % self.drill_through_cycle_count.max(1)
}
}
fn has_drill_through_mouse_moved(&self, position: DVec2) -> bool {
self.last_drill_through_click_position.is_none_or(|last_pos| last_pos.distance(position) > DRILL_THROUGH_THRESHOLD)
}
fn set_ghost_outline(&mut self, shape_editor: &ShapeState, document: &DocumentMessageHandler) {
self.ghost_outline.clear();
for &layer in shape_editor.selected_shape_state.keys() {
// We probably need to collect here
let outline: Vec<ClickTargetType> = document.metadata().layer_with_free_points_outline(layer).cloned().collect();
self.ghost_outline.push((outline, layer));
}
}
// TODO: This function is for basic point select mode. We definitely need to make a new one for the segment select mode.
#[allow(clippy::too_many_arguments)]
fn mouse_down(
&mut self,
shape_editor: &mut ShapeState,
document: &DocumentMessageHandler,
input: &InputPreprocessorMessageHandler,
viewport: &ViewportMessageHandler,
responses: &mut VecDeque<Message>,
extend_selection: bool,
lasso_select: bool,
handle_drag_from_anchor: bool,
drag_zero_handle: bool,
segment_editing_modifier: bool,
path_overlay_mode: PathOverlayMode,
segment_editing_mode: bool,
point_editing_mode: bool,
) -> PathToolFsmState {
self.double_click_handled = false;
self.opposing_handle_lengths = None;
self.drag_start_pos = input.mouse.position;
if input.time - self.last_click_time > DOUBLE_CLICK_MILLISECONDS {
self.saved_points_before_anchor_convert_smooth_sharp.clear();
self.stored_selection = None;
}
self.last_click_time = input.time;
let mut old_selection = HashMap::new();
for (layer, state) in &shape_editor.selected_shape_state {
let selected_points = state.selected_points().collect::<HashSet<_>>();
let selected_segments = state.selected_segments().collect::<HashSet<_>>();
old_selection.insert(*layer, (selected_points, selected_segments));
}
// Check if the point is already selected; if not, select the first point within the threshold (in pixels)
// Don't select the points which are not shown currently in PathOverlayMode
if let Some((already_selected, mut selection_info)) = shape_editor.get_point_selection_state(
&document.network_interface,
input.mouse.position,
SELECTION_THRESHOLD,
path_overlay_mode,
self.frontier_handles_info.as_ref(),
point_editing_mode,
) {
responses.add(DocumentMessage::StartTransaction);
self.set_ghost_outline(shape_editor, document);
self.last_clicked_point_was_selected = already_selected;
// If the point is already selected and shift (`extend_selection`) is used, keep the selection unchanged.
// Otherwise, select the first point within the threshold.
if !(already_selected && extend_selection)
&& let Some(updated_selection_info) = shape_editor.change_point_selection(
&document.network_interface,
input.mouse.position,
SELECTION_THRESHOLD,
extend_selection,
path_overlay_mode,
self.frontier_handles_info.as_ref(),
) {
selection_info = updated_selection_info;
}
if let Some(selected_points) = selection_info {
self.drag_start_pos = input.mouse.position;
// If selected points contain only handles and there was some selection before, then it is stored and becomes restored upon release
let mut dragging_only_handles = true;
for point in &selected_points.points {
if matches!(point.point_id, ManipulatorPointId::Anchor(_)) {
dragging_only_handles = false;
break;
}
}
if dragging_only_handles && !self.handle_drag_toggle && !old_selection.is_empty() {
self.saved_selection_before_handle_drag = old_selection;
}
if handle_drag_from_anchor && let Some((layer, point)) = shape_editor.find_nearest_point_indices(&document.network_interface, input.mouse.position, SELECTION_THRESHOLD) {
// Check that selected point is an anchor
if let (Some(point_id), Some(vector)) = (point.as_anchor(), document.network_interface.compute_modified_vector(layer)) {
let handles = vector.all_connected(point_id).collect::<Vec<_>>();
self.alt_clicked_on_anchor = true;
for handle in &handles {
let modification_type = handle.set_relative_position(DVec2::ZERO);
responses.add(GraphOperationMessage::Vector { layer, modification_type });
for &handles in &vector.colinear_manipulators {
if handles.contains(handle) {
let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
}
}
let manipulator_point_id = handles[0].to_manipulator_point();
shape_editor.deselect_all_points();
shape_editor.select_point_by_layer_and_id(manipulator_point_id, layer);
responses.add(PathToolMessage::SelectedPointUpdated);
}
}
if let Some((Some(point), Some(vector), layer)) = shape_editor
.find_nearest_point_indices(&document.network_interface, input.mouse.position, SELECTION_THRESHOLD)
.map(|(layer, point)| (point.as_anchor(), document.network_interface.compute_modified_vector(layer), layer))
{
let handles = vector
.all_connected(point)
.filter(|handle| handle.length(&vector) < 1e-6)
.map(|handle| handle.to_manipulator_point())
.collect::<Vec<_>>();
let endpoint = vector.anchor_endpoints().any(|anchor| point == anchor);
if drag_zero_handle && (handles.len() == 1 && !endpoint) {
shape_editor.deselect_all_points();
shape_editor.select_points_by_layer_and_id(&HashMap::from([(layer, handles)]));
shape_editor.convert_selected_manipulators_to_colinear_handles(responses, document);
}
}
self.start_dragging_point(selected_points, input, document, shape_editor);
responses.add(OverlaysMessage::Draw);
}
PathToolFsmState::Dragging(self.dragging_state)
}
// We didn't find a point nearby, so we will see if there is a segment to select or insert a point on
else if let Some(segment) = shape_editor.upper_closest_segment(&document.network_interface, input.mouse.position, SELECTION_THRESHOLD) {
responses.add(DocumentMessage::StartTransaction);
self.set_ghost_outline(shape_editor, document);
if segment_editing_mode && !segment_editing_modifier {
let layer = segment.layer();
let segment_id = segment.segment();
let already_selected = shape_editor.selected_shape_state.get(&layer).is_some_and(|state| state.is_segment_selected(segment_id));
self.last_clicked_segment_was_selected = already_selected;
if !(already_selected && extend_selection) {
let retain_existing_selection = extend_selection || already_selected;
if !retain_existing_selection {
shape_editor.deselect_all_segments();
shape_editor.deselect_all_points();
}
// Add to selected segments
if let Some(selected_shape_state) = shape_editor.selected_shape_state.get_mut(&layer) {
selected_shape_state.select_segment(segment_id);
}
// TODO: If the segment connected to one of the endpoints is also selected then select that point
}
self.drag_start_pos = input.mouse.position;
let viewport_to_document = document.metadata().document_to_viewport.inverse();
self.previous_mouse_position = viewport_to_document.transform_point2(input.mouse.position);
responses.add(OverlaysMessage::Draw);
PathToolFsmState::Dragging(self.dragging_state)
} else {
let points = pathseg_points(segment.pathseg());
let [pos1, pos2] = match (points.p1, points.p2) {
(Some(p1), Some(p2)) => [p1, p2],
(Some(p1), None) | (None, Some(p1)) => [p1, points.p3],
(None, None) => [points.p0 + (points.p3 - points.p0) / 3., points.p3 + (points.p0 - points.p3) / 3.],
};
self.molding_info = Some((pos1, pos2));
PathToolFsmState::Dragging(self.dragging_state)
}
}
// If no other layers are selected and this is a single-click, then also select the layer (exception)
else if let Some(layer) = document.click(input, viewport) {
if shape_editor.selected_shape_state.is_empty() {
self.first_selected_with_single_click = true;
// This ensures we don't need to double click a second time to get the drill through to work
self.last_drill_through_click_position = Some(input.mouse.position);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
}
self.started_drawing_from_inside = true;
self.drag_start_pos = input.mouse.position;
self.previous_mouse_position = document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position);
let selection_shape = if lasso_select { SelectionShapeType::Lasso } else { SelectionShapeType::Box };
PathToolFsmState::Drawing { selection_shape }
}
// Start drawing
else {
self.drag_start_pos = input.mouse.position;
self.previous_mouse_position = document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position);
let selection_shape = if lasso_select { SelectionShapeType::Lasso } else { SelectionShapeType::Box };
PathToolFsmState::Drawing { selection_shape }
}
}
fn start_dragging_point(&mut self, selected_points: SelectedPointsInfo, input: &InputPreprocessorMessageHandler, document: &DocumentMessageHandler, shape_editor: &mut ShapeState) {
let mut manipulators = HashMap::with_hasher(NoHashBuilder);
let mut unselected = Vec::new();
for (&layer, state) in &shape_editor.selected_shape_state {
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
let transform = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface);
let mut layer_manipulators = HashSet::with_hasher(NoHashBuilder);
for point in state.selected_points() {
let Some(anchor) = point.get_anchor(&vector) else { continue };
layer_manipulators.insert(anchor);
let Some([handle1, handle2]) = point.get_handle_pair(&vector) else { continue };
let Some(handle) = point.as_handle() else { continue };
// Check which handle is selected and which is opposite
let opposite = if handle == handle1 { handle2 } else { handle1 };
self.opposite_handle_position = if self.opposite_handle_position.is_none() {
opposite.to_manipulator_point().get_position(&vector)
} else {
self.opposite_handle_position
};
}
for (&id, &position) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) {
if layer_manipulators.contains(&id) {
continue;
}
unselected.push(SnapCandidatePoint::handle(transform.transform_point2(position)))
}
if !layer_manipulators.is_empty() {
manipulators.insert(layer, layer_manipulators);
}
}
self.snap_cache = SnapCache { manipulators, unselected };
let viewport_to_document = document.metadata().document_to_viewport.inverse();
self.previous_mouse_position = viewport_to_document.transform_point2(input.mouse.position - selected_points.offset);
}
fn update_colinear(&mut self, equidistant: bool, toggle_colinear: bool, shape_editor: &mut ShapeState, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) -> bool {
// Check handle colinear state
let is_colinear = self
.selection_status
.angle()
.map(|angle| match angle {
ManipulatorAngle::Colinear => true,
ManipulatorAngle::Free | ManipulatorAngle::Mixed => false,
})
.unwrap_or(false);
// Check if the toggle_colinear key has just been pressed
if toggle_colinear && !self.toggle_colinear_debounce {
self.opposing_handle_lengths = None;
if is_colinear {
shape_editor.disable_colinear_handles_state_on_selected(&document.network_interface, responses);
} else {
shape_editor.convert_selected_manipulators_to_colinear_handles(responses, document);
}
self.toggle_colinear_debounce = true;
return true;
}
self.toggle_colinear_debounce = toggle_colinear;
if equidistant && self.opposing_handle_lengths.is_none() {
if !is_colinear {
// Try to get selected handle info
let Some((_, _, selected_handle_id)) = self.try_get_selected_handle_and_anchor(shape_editor, document) else {
self.opposing_handle_lengths = Some(shape_editor.opposing_handle_lengths(document));
return false;
};
let Some((layer, _)) = shape_editor.selected_shape_state.iter().next() else {
self.opposing_handle_lengths = Some(shape_editor.opposing_handle_lengths(document));
return false;
};
let Some(vector) = document.network_interface.compute_modified_vector(*layer) else {
self.opposing_handle_lengths = Some(shape_editor.opposing_handle_lengths(document));
return false;
};
// Check if handle has a pair (to ignore handles of edges of open paths)
if let Some(handle_pair) = selected_handle_id.get_handle_pair(&vector) {
let opposite_handle_length = handle_pair.iter().filter(|&&h| h.to_manipulator_point() != selected_handle_id).find_map(|&h| {
let opp_handle_pos = h.to_manipulator_point().get_position(&vector)?;