diff --git a/desktop/src/cef/input/keymap.rs b/desktop/src/cef/input/keymap.rs index 17816fb694..f61ce660ba 100644 --- a/desktop/src/cef/input/keymap.rs +++ b/desktop/src/cef/input/keymap.rs @@ -7,14 +7,14 @@ pub(crate) trait ToCharRepresentation { impl ToCharRepresentation for Key { fn to_char_representation(&self) -> char { match self { - Key::Named(named) => match named { + Self::Named(named) => match named { NamedKey::Tab => '\t', NamedKey::Enter => '\r', NamedKey::Backspace => '\x08', NamedKey::Escape => '\x1b', _ => '\0', }, - Key::Character(char) => char.chars().next().unwrap_or_default(), + Self::Character(char) => char.chars().next().unwrap_or_default(), _ => '\0', } } diff --git a/desktop/src/window/mac/menu.rs b/desktop/src/window/mac/menu.rs index 41358b46b1..9a039bbe23 100644 --- a/desktop/src/window/mac/menu.rs +++ b/desktop/src/window/mac/menu.rs @@ -117,30 +117,30 @@ enum MenuContainer<'a> { impl<'a> MenuContainer<'a> { fn items(&self) -> Vec { match self { - MenuContainer::Menu(menu) => menu.items(), - MenuContainer::Submenu(submenu) => submenu.items(), + Self::Menu(menu) => menu.items(), + Self::Submenu(submenu) => submenu.items(), } } fn remove(&self, item: &dyn IsMenuItem) -> Result<()> { match self { - MenuContainer::Menu(menu) => menu.remove(item), - MenuContainer::Submenu(submenu) => submenu.remove(item), + Self::Menu(menu) => menu.remove(item), + Self::Submenu(submenu) => submenu.remove(item), } } fn append_items(&self, items: &[&dyn IsMenuItem]) -> Result<()> { match self { - MenuContainer::Menu(menu) => menu.append_items(items), - MenuContainer::Submenu(submenu) => submenu.append_items(items), + Self::Menu(menu) => menu.append_items(items), + Self::Submenu(submenu) => submenu.append_items(items), } } } impl<'a> From<&'a MudaMenu> for MenuContainer<'a> { fn from(menu: &'a MudaMenu) -> Self { - MenuContainer::Menu(menu) + Self::Menu(menu) } } impl<'a> From<&'a Submenu> for MenuContainer<'a> { fn from(submenu: &'a Submenu) -> Self { - MenuContainer::Submenu(submenu) + Self::Submenu(submenu) } } diff --git a/editor/src/messages/frontend/utility_types.rs b/editor/src/messages/frontend/utility_types.rs index 89dc539c53..7b78874f0c 100644 --- a/editor/src/messages/frontend/utility_types.rs +++ b/editor/src/messages/frontend/utility_types.rs @@ -48,9 +48,9 @@ pub enum FileType { impl FileType { pub fn to_mime(self) -> &'static str { match self { - FileType::Png => "image/png", - FileType::Jpg => "image/jpeg", - FileType::Svg => "image/svg+xml", + Self::Png => "image/png", + Self::Jpg => "image/jpeg", + Self::Svg => "image/svg+xml", } } } diff --git a/editor/src/messages/layout/utility_types/layout_widget.rs b/editor/src/messages/layout/utility_types/layout_widget.rs index 0c8d7ac257..33687fa1d4 100644 --- a/editor/src/messages/layout/utility_types/layout_widget.rs +++ b/editor/src/messages/layout/utility_types/layout_widget.rs @@ -351,8 +351,8 @@ impl Default for LayoutGroup { } } impl From> for LayoutGroup { - fn from(widgets: Vec) -> LayoutGroup { - LayoutGroup::Row { widgets } + fn from(widgets: Vec) -> Self { + Self::Row { widgets } } } @@ -360,8 +360,8 @@ impl LayoutGroup { /// Applies a tooltip description to all widgets without a tooltip in this row or column. pub fn with_tooltip_description(self, description: impl Into) -> Self { let (is_col, mut widgets) = match self { - LayoutGroup::Column { widgets } => (true, widgets), - LayoutGroup::Row { widgets } => (false, widgets), + Self::Column { widgets } => (true, widgets), + Self::Row { widgets } => (false, widgets), _ => unimplemented!(), }; let description = description.into(); diff --git a/editor/src/messages/layout/utility_types/widgets/button_widgets.rs b/editor/src/messages/layout/utility_types/widgets/button_widgets.rs index 54a1e5ba1d..6e243ca3a7 100644 --- a/editor/src/messages/layout/utility_types/widgets/button_widgets.rs +++ b/editor/src/messages/layout/utility_types/widgets/button_widgets.rs @@ -32,7 +32,7 @@ pub struct IconButton { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, @@ -96,7 +96,7 @@ pub struct ParameterExposeButton { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, @@ -140,7 +140,7 @@ pub struct TextButton { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, @@ -201,7 +201,7 @@ pub struct ColorInput { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, diff --git a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs index 59273cf88c..fa62be183d 100644 --- a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs +++ b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs @@ -29,7 +29,7 @@ pub struct CheckboxInput { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, @@ -201,13 +201,13 @@ pub struct NumberInput { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub increment_callback_increase: WidgetCallback, + pub increment_callback_increase: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub increment_callback_decrease: WidgetCallback, + pub increment_callback_decrease: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, @@ -359,7 +359,7 @@ pub struct TextAreaInput { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, @@ -396,7 +396,7 @@ pub struct TextInput { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, @@ -420,7 +420,7 @@ pub struct CurveInput { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, @@ -445,7 +445,7 @@ pub struct ReferencePointInput { // Callbacks #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] - pub on_update: WidgetCallback, + pub on_update: WidgetCallback, #[serde(skip)] #[derivative(Debug = "ignore", PartialEq = "ignore")] pub on_commit: WidgetCallback<()>, diff --git a/editor/src/messages/message.rs b/editor/src/messages/message.rs index 4b104495ee..62ab489bef 100644 --- a/editor/src/messages/message.rs +++ b/editor/src/messages/message.rs @@ -42,7 +42,7 @@ pub enum Message { // Messages Batched { - messages: Box<[Message]>, + messages: Box<[Self]>, }, NoOp, } diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 6402f609fd..7fdd01abe9 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -343,7 +343,7 @@ impl MessageHandler> for DocumentMes .deepest_common_ancestor(&selected_nodes, &self.selection_network_path, true) .unwrap_or(LayerNodeIdentifier::ROOT_PARENT); - let insert_index = DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &self.network_interface.selected_nodes(), parent); + let insert_index = Self::get_calculated_insert_index(self.metadata(), &self.network_interface.selected_nodes(), parent); responses.add(DocumentMessage::AddTransaction); responses.add(GraphOperationMessage::NewCustomLayer { id, @@ -430,7 +430,7 @@ impl MessageHandler> for DocumentMes layers.sort_by_key(|layer| { let Some(parent) = layer.parent(self.metadata()) else { return usize::MAX }; - DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &SelectedNodes(vec![layer.to_node()]), parent) + Self::get_calculated_insert_index(self.metadata(), &SelectedNodes(vec![layer.to_node()]), parent) }); for layer in layers.into_iter().rev() { @@ -450,7 +450,7 @@ impl MessageHandler> for DocumentMes let nodes = self.network_interface.copy_nodes(©_ids, &[]).collect::>(); - let insert_index = DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &SelectedNodes(vec![layer.to_node()]), parent); + let insert_index = Self::get_calculated_insert_index(self.metadata(), &SelectedNodes(vec![layer.to_node()]), parent); let new_ids: HashMap<_, _> = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect(); @@ -637,9 +637,9 @@ impl MessageHandler> for DocumentMes let Some(selected_nodes) = &self.network_interface.selected_nodes_in_nested_network(&self.selection_network_path) else { return; }; - let insert_index = DocumentMessageHandler::get_calculated_insert_index(self.metadata(), selected_nodes, parent); + let insert_index = Self::get_calculated_insert_index(self.metadata(), selected_nodes, parent); - DocumentMessageHandler::group_layers(responses, insert_index, parent, group_folder_type, &mut self.network_interface); + Self::group_layers(responses, insert_index, parent, group_folder_type, &mut self.network_interface); } // Artboard workflow else { @@ -657,11 +657,11 @@ impl MessageHandler> for DocumentMes let Some(parent) = self.network_interface.deepest_common_ancestor(&child_selected_nodes, &self.selection_network_path, false) else { continue; }; - let insert_index = DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &child_selected_nodes, parent); + let insert_index = Self::get_calculated_insert_index(self.metadata(), &child_selected_nodes, parent); responses.add(NodeGraphMessage::SelectedNodesSet { nodes: child_selected_nodes.0 }); - new_folders.push(DocumentMessageHandler::group_layers(responses, insert_index, parent, group_folder_type, &mut self.network_interface)); + new_folders.push(Self::group_layers(responses, insert_index, parent, group_folder_type, &mut self.network_interface)); } responses.add(NodeGraphMessage::SelectedNodesSet { nodes: new_folders }); @@ -1830,7 +1830,7 @@ impl DocumentMessageHandler { } pub fn deserialize_document(serialized_content: &str) -> Result { - let document_message_handler = serde_json::from_str::(serialized_content) + let document_message_handler = serde_json::from_str::(serialized_content) .or_else(|e| { log::warn!("Failed to directly load document with the following error: {e}. Trying old DocumentMessageHandler."); // TODO: Eventually remove this document upgrade code @@ -1869,7 +1869,7 @@ impl DocumentMessageHandler { pub snapping_state: SnappingState, } - serde_json::from_str::(serialized_content).map(|old_message_handler| DocumentMessageHandler { + serde_json::from_str::(serialized_content).map(|old_message_handler| Self { network_interface: NodeNetworkInterface::from_old_network(old_message_handler.network), collapsed: old_message_handler.collapsed, commit_hash: old_message_handler.commit_hash, diff --git a/editor/src/messages/portfolio/document/node_graph/node_properties.rs b/editor/src/messages/portfolio/document/node_graph/node_properties.rs index 2ea963345b..e8feb32840 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_properties.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_properties.rs @@ -2144,7 +2144,7 @@ pub struct ParameterWidgetsInfo<'a> { } impl<'a> ParameterWidgetsInfo<'a> { - pub fn new(node_id: NodeId, index: usize, blank_assist: bool, context: &'a mut NodePropertiesContext) -> ParameterWidgetsInfo<'a> { + pub fn new(node_id: NodeId, index: usize, blank_assist: bool, context: &'a mut NodePropertiesContext) -> Self { let (name, description) = context.network_interface.displayed_input_name_and_description(&node_id, index, context.selection_network_path); let input_type = context .network_interface diff --git a/editor/src/messages/portfolio/document/node_graph/utility_types.rs b/editor/src/messages/portfolio/document/node_graph/utility_types.rs index 5b202ef483..57db941a5e 100644 --- a/editor/src/messages/portfolio/document/node_graph/utility_types.rs +++ b/editor/src/messages/portfolio/document/node_graph/utility_types.rs @@ -217,12 +217,12 @@ pub struct FrontendXY { impl From for FrontendXY { fn from(v: DVec2) -> Self { - FrontendXY { x: v.x as i32, y: v.y as i32 } + Self { x: v.x as i32, y: v.y as i32 } } } impl From for FrontendXY { fn from(v: IVec2) -> Self { - FrontendXY { x: v.x, y: v.y } + Self { x: v.x, y: v.y } } } diff --git a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs index 7ba8eaa7ae..7c1e4c776a 100644 --- a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs +++ b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs @@ -233,7 +233,7 @@ pub struct LayerNodeIdentifier(NonZeroU64); impl core::fmt::Debug for LayerNodeIdentifier { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let node_id = if *self != LayerNodeIdentifier::ROOT_PARENT { self.to_node() } else { NodeId(0) }; + let node_id = if *self != Self::ROOT_PARENT { self.to_node() } else { NodeId(0) }; f.debug_tuple("LayerNodeIdentifier").field(&node_id).finish() } @@ -247,7 +247,7 @@ impl Default for LayerNodeIdentifier { impl LayerNodeIdentifier { /// A conceptual layer used to represent the parent of layers that feed into the export - pub const ROOT_PARENT: Self = LayerNodeIdentifier::new_unchecked(NodeId(0)); + pub const ROOT_PARENT: Self = Self::new_unchecked(NodeId(0)); /// Construct a [`LayerNodeIdentifier`] without checking if it is a layer node pub const fn new_unchecked(node_id: NodeId) -> Self { @@ -271,27 +271,27 @@ impl LayerNodeIdentifier { } /// Access the parent layer if possible - pub fn parent(self, metadata: &DocumentMetadata) -> Option { + pub fn parent(self, metadata: &DocumentMetadata) -> Option { metadata.get_relations(self).and_then(|relations| relations.parent) } /// Access the previous sibling of this layer (up the Layers panel) - pub fn previous_sibling(self, metadata: &DocumentMetadata) -> Option { + pub fn previous_sibling(self, metadata: &DocumentMetadata) -> Option { metadata.get_relations(self).and_then(|relations| relations.previous_sibling) } /// Access the next sibling of this layer (down the Layers panel) - pub fn next_sibling(self, metadata: &DocumentMetadata) -> Option { + pub fn next_sibling(self, metadata: &DocumentMetadata) -> Option { metadata.get_relations(self).and_then(|relations| relations.next_sibling) } /// Access the first child of this layer (top most in Layers panel) - pub fn first_child(self, metadata: &DocumentMetadata) -> Option { + pub fn first_child(self, metadata: &DocumentMetadata) -> Option { metadata.get_relations(self).and_then(|relations| relations.first_child) } /// Access the last child of this layer (bottom most in Layers panel) - pub fn last_child(self, metadata: &DocumentMetadata) -> Option { + pub fn last_child(self, metadata: &DocumentMetadata) -> Option { metadata.get_relations(self).and_then(|relations| relations.last_child) } @@ -301,12 +301,12 @@ impl LayerNodeIdentifier { } /// Is the layer a child of the given layer? - pub fn is_child_of(self, metadata: &DocumentMetadata, parent: &LayerNodeIdentifier) -> bool { + pub fn is_child_of(self, metadata: &DocumentMetadata, parent: &Self) -> bool { parent.children(metadata).any(|child| child == self) } /// Is the layer an ancestor of the given layer? - pub fn is_ancestor_of(self, metadata: &DocumentMetadata, child: &LayerNodeIdentifier) -> bool { + pub fn is_ancestor_of(self, metadata: &DocumentMetadata, child: &Self) -> bool { child.ancestors(metadata).any(|ancestor| ancestor == self) } @@ -361,7 +361,7 @@ impl LayerNodeIdentifier { } /// Add a child towards the top of the Layers panel - pub fn push_front_child(self, metadata: &mut DocumentMetadata, new: LayerNodeIdentifier) { + pub fn push_front_child(self, metadata: &mut DocumentMetadata, new: Self) { assert!(!metadata.structure.contains_key(&new), "Cannot add already existing layer"); let parent = metadata.get_structure_mut(self); let old_first_child = parent.first_child.replace(new); @@ -374,7 +374,7 @@ impl LayerNodeIdentifier { } /// Add a child towards the bottom of the Layers panel - pub fn push_child(self, metadata: &mut DocumentMetadata, new: LayerNodeIdentifier) { + pub fn push_child(self, metadata: &mut DocumentMetadata, new: Self) { assert!(!metadata.structure.contains_key(&new), "Cannot add already existing layer"); let parent = metadata.get_structure_mut(self); let old_last_child = parent.last_child.replace(new); @@ -387,7 +387,7 @@ impl LayerNodeIdentifier { } /// Add sibling above in the Layers panel - pub fn add_before(self, metadata: &mut DocumentMetadata, new: LayerNodeIdentifier) { + pub fn add_before(self, metadata: &mut DocumentMetadata, new: Self) { assert!(!metadata.structure.contains_key(&new), "Cannot add already existing layer"); metadata.get_structure_mut(new).next_sibling = Some(self); metadata.get_structure_mut(new).parent = self.parent(metadata); @@ -405,7 +405,7 @@ impl LayerNodeIdentifier { } /// Add sibling below in the Layers panel - pub fn add_after(self, metadata: &mut DocumentMetadata, new: LayerNodeIdentifier) { + pub fn add_after(self, metadata: &mut DocumentMetadata, new: Self) { assert!(!metadata.structure.contains_key(&new), "Cannot add already existing layer"); metadata.get_structure_mut(new).previous_sibling = Some(self); metadata.get_structure_mut(new).parent = self.parent(metadata); diff --git a/editor/src/messages/portfolio/document/utility_types/misc.rs b/editor/src/messages/portfolio/document/utility_types/misc.rs index c474bf9665..4796284e4f 100644 --- a/editor/src/messages/portfolio/document/utility_types/misc.rs +++ b/editor/src/messages/portfolio/document/utility_types/misc.rs @@ -276,9 +276,9 @@ pub enum BoundingBoxSnapSource { impl fmt::Display for BoundingBoxSnapSource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - BoundingBoxSnapSource::CornerPoint => write!(f, "Bounding Box: Corner Point"), - BoundingBoxSnapSource::CenterPoint => write!(f, "Bounding Box: Center Point"), - BoundingBoxSnapSource::EdgeMidpoint => write!(f, "Bounding Box: Edge Midpoint"), + Self::CornerPoint => write!(f, "Bounding Box: Corner Point"), + Self::CenterPoint => write!(f, "Bounding Box: Center Point"), + Self::EdgeMidpoint => write!(f, "Bounding Box: Edge Midpoint"), } } } @@ -292,8 +292,8 @@ pub enum ArtboardSnapSource { impl fmt::Display for ArtboardSnapSource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ArtboardSnapSource::CornerPoint => write!(f, "Artboard: Corner Point"), - ArtboardSnapSource::CenterPoint => write!(f, "Artboard: Center Point"), + Self::CornerPoint => write!(f, "Artboard: Corner Point"), + Self::CenterPoint => write!(f, "Artboard: Center Point"), } } } @@ -310,10 +310,10 @@ pub enum PathSnapSource { impl fmt::Display for PathSnapSource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - PathSnapSource::AnchorPointWithColinearHandles | PathSnapSource::AnchorPointWithFreeHandles => write!(f, "Path: Anchor Point"), - PathSnapSource::HandlePoint => write!(f, "Path: Handle Point"), - PathSnapSource::LineMidpoint => write!(f, "Path: Line Midpoint"), - PathSnapSource::IntersectionPoint => write!(f, "Path: Intersection Point"), + Self::AnchorPointWithColinearHandles | Self::AnchorPointWithFreeHandles => write!(f, "Path: Anchor Point"), + Self::HandlePoint => write!(f, "Path: Handle Point"), + Self::LineMidpoint => write!(f, "Path: Line Midpoint"), + Self::IntersectionPoint => write!(f, "Path: Intersection Point"), } } } @@ -330,11 +330,11 @@ pub enum AlignmentSnapSource { impl fmt::Display for AlignmentSnapSource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - AlignmentSnapSource::BoundingBoxCornerPoint => write!(f, "{}", BoundingBoxSnapSource::CornerPoint), - AlignmentSnapSource::BoundingBoxCenterPoint => write!(f, "{}", BoundingBoxSnapSource::CenterPoint), - AlignmentSnapSource::BoundingBoxEdgeMidpoint => write!(f, "{}", BoundingBoxSnapSource::EdgeMidpoint), - AlignmentSnapSource::ArtboardCornerPoint => write!(f, "{}", ArtboardSnapSource::CornerPoint), - AlignmentSnapSource::ArtboardCenterPoint => write!(f, "{}", ArtboardSnapSource::CenterPoint), + Self::BoundingBoxCornerPoint => write!(f, "{}", BoundingBoxSnapSource::CornerPoint), + Self::BoundingBoxCenterPoint => write!(f, "{}", BoundingBoxSnapSource::CenterPoint), + Self::BoundingBoxEdgeMidpoint => write!(f, "{}", BoundingBoxSnapSource::EdgeMidpoint), + Self::ArtboardCornerPoint => write!(f, "{}", ArtboardSnapSource::CornerPoint), + Self::ArtboardCenterPoint => write!(f, "{}", ArtboardSnapSource::CenterPoint), } } } @@ -372,11 +372,11 @@ impl SnapSource { impl fmt::Display for SnapSource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - SnapSource::None => write!(f, "None"), - SnapSource::BoundingBox(bounding_box_snap_source) => write!(f, "{bounding_box_snap_source}"), - SnapSource::Artboard(artboard_snap_source) => write!(f, "{artboard_snap_source}"), - SnapSource::Path(path_snap_source) => write!(f, "{path_snap_source}"), - SnapSource::Alignment(alignment_snap_source) => write!(f, "{alignment_snap_source}"), + Self::None => write!(f, "None"), + Self::BoundingBox(bounding_box_snap_source) => write!(f, "{bounding_box_snap_source}"), + Self::Artboard(artboard_snap_source) => write!(f, "{artboard_snap_source}"), + Self::Path(path_snap_source) => write!(f, "{path_snap_source}"), + Self::Alignment(alignment_snap_source) => write!(f, "{alignment_snap_source}"), } } } @@ -464,9 +464,9 @@ pub enum BoundingBoxSnapTarget { impl fmt::Display for BoundingBoxSnapTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - BoundingBoxSnapTarget::CornerPoint => write!(f, "Bounding Box: Corner Point"), - BoundingBoxSnapTarget::CenterPoint => write!(f, "Bounding Box: Center Point"), - BoundingBoxSnapTarget::EdgeMidpoint => write!(f, "Bounding Box: Edge Midpoint"), + Self::CornerPoint => write!(f, "Bounding Box: Corner Point"), + Self::CenterPoint => write!(f, "Bounding Box: Center Point"), + Self::EdgeMidpoint => write!(f, "Bounding Box: Edge Midpoint"), } } } @@ -486,13 +486,13 @@ pub enum PathSnapTarget { impl fmt::Display for PathSnapTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - PathSnapTarget::AnchorPointWithColinearHandles | PathSnapTarget::AnchorPointWithFreeHandles => write!(f, "Path: Anchor Point"), - PathSnapTarget::LineMidpoint => write!(f, "Path: Line Midpoint"), - PathSnapTarget::AlongPath => write!(f, "Path: Along Path"), - PathSnapTarget::NormalToPath => write!(f, "Path: Normal to Path"), - PathSnapTarget::TangentToPath => write!(f, "Path: Tangent to Path"), - PathSnapTarget::IntersectionPoint => write!(f, "Path: Intersection Point"), - PathSnapTarget::PerpendicularToEndpoint => write!(f, "Path: Perp. to Endpoint"), + Self::AnchorPointWithColinearHandles | Self::AnchorPointWithFreeHandles => write!(f, "Path: Anchor Point"), + Self::LineMidpoint => write!(f, "Path: Line Midpoint"), + Self::AlongPath => write!(f, "Path: Along Path"), + Self::NormalToPath => write!(f, "Path: Normal to Path"), + Self::TangentToPath => write!(f, "Path: Tangent to Path"), + Self::IntersectionPoint => write!(f, "Path: Intersection Point"), + Self::PerpendicularToEndpoint => write!(f, "Path: Perp. to Endpoint"), } } } @@ -507,9 +507,9 @@ pub enum ArtboardSnapTarget { impl fmt::Display for ArtboardSnapTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ArtboardSnapTarget::CornerPoint => write!(f, "Artboard: Corner Point"), - ArtboardSnapTarget::CenterPoint => write!(f, "Artboard: Center Point"), - ArtboardSnapTarget::AlongEdge => write!(f, "Artboard: Along Edge"), + Self::CornerPoint => write!(f, "Artboard: Corner Point"), + Self::CenterPoint => write!(f, "Artboard: Center Point"), + Self::AlongEdge => write!(f, "Artboard: Along Edge"), } } } @@ -524,9 +524,9 @@ pub enum GridSnapTarget { impl fmt::Display for GridSnapTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - GridSnapTarget::Line => write!(f, "Grid: Along Line"), - GridSnapTarget::LineNormal => write!(f, "Grid: Normal to Line"), - GridSnapTarget::Intersection => write!(f, "Grid: Intersection Point"), + Self::Line => write!(f, "Grid: Along Line"), + Self::LineNormal => write!(f, "Grid: Normal to Line"), + Self::Intersection => write!(f, "Grid: Intersection Point"), } } } @@ -545,13 +545,13 @@ pub enum AlignmentSnapTarget { impl fmt::Display for AlignmentSnapTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - AlignmentSnapTarget::BoundingBoxCornerPoint => write!(f, "{}", BoundingBoxSnapTarget::CornerPoint), - AlignmentSnapTarget::BoundingBoxCenterPoint => write!(f, "{}", BoundingBoxSnapTarget::CenterPoint), - AlignmentSnapTarget::ArtboardCornerPoint => write!(f, "{}", ArtboardSnapTarget::CornerPoint), - AlignmentSnapTarget::ArtboardCenterPoint => write!(f, "{}", ArtboardSnapTarget::CenterPoint), - AlignmentSnapTarget::AlignWithAnchorPoint => write!(f, "{}", PathSnapTarget::AnchorPointWithColinearHandles), - AlignmentSnapTarget::IntersectionPoint => write!(f, "{}", PathSnapTarget::IntersectionPoint), - AlignmentSnapTarget::PerpendicularToEndpoint => write!(f, "{}", PathSnapTarget::PerpendicularToEndpoint), + Self::BoundingBoxCornerPoint => write!(f, "{}", BoundingBoxSnapTarget::CornerPoint), + Self::BoundingBoxCenterPoint => write!(f, "{}", BoundingBoxSnapTarget::CenterPoint), + Self::ArtboardCornerPoint => write!(f, "{}", ArtboardSnapTarget::CornerPoint), + Self::ArtboardCenterPoint => write!(f, "{}", ArtboardSnapTarget::CenterPoint), + Self::AlignWithAnchorPoint => write!(f, "{}", PathSnapTarget::AnchorPointWithColinearHandles), + Self::IntersectionPoint => write!(f, "{}", PathSnapTarget::IntersectionPoint), + Self::PerpendicularToEndpoint => write!(f, "{}", PathSnapTarget::PerpendicularToEndpoint), } } } @@ -570,13 +570,13 @@ pub enum DistributionSnapTarget { impl fmt::Display for DistributionSnapTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - DistributionSnapTarget::X => write!(f, "Distribute: X"), - DistributionSnapTarget::Y => write!(f, "Distribute: Y"), - DistributionSnapTarget::Right => write!(f, "Distribute: Right"), - DistributionSnapTarget::Left => write!(f, "Distribute: Left"), - DistributionSnapTarget::Up => write!(f, "Distribute: Up"), - DistributionSnapTarget::Down => write!(f, "Distribute: Down"), - DistributionSnapTarget::XY => write!(f, "Distribute: XY"), + Self::X => write!(f, "Distribute: X"), + Self::Y => write!(f, "Distribute: Y"), + Self::Right => write!(f, "Distribute: Right"), + Self::Left => write!(f, "Distribute: Left"), + Self::Up => write!(f, "Distribute: Up"), + Self::Down => write!(f, "Distribute: Down"), + Self::XY => write!(f, "Distribute: XY"), } } } @@ -614,13 +614,13 @@ impl SnapTarget { impl fmt::Display for SnapTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - SnapTarget::None => write!(f, "None"), - SnapTarget::BoundingBox(bounding_box_snap_target) => write!(f, "{bounding_box_snap_target}"), - SnapTarget::Path(path_snap_target) => write!(f, "{path_snap_target}"), - SnapTarget::Artboard(artboard_snap_target) => write!(f, "{artboard_snap_target}"), - SnapTarget::Grid(grid_snap_target) => write!(f, "{grid_snap_target}"), - SnapTarget::Alignment(alignment_snap_target) => write!(f, "{alignment_snap_target}"), - SnapTarget::DistributeEvenly(distribution_snap_target) => write!(f, "{distribution_snap_target}"), + Self::None => write!(f, "None"), + Self::BoundingBox(bounding_box_snap_target) => write!(f, "{bounding_box_snap_target}"), + Self::Path(path_snap_target) => write!(f, "{path_snap_target}"), + Self::Artboard(artboard_snap_target) => write!(f, "{artboard_snap_target}"), + Self::Grid(grid_snap_target) => write!(f, "{grid_snap_target}"), + Self::Alignment(alignment_snap_target) => write!(f, "{alignment_snap_target}"), + Self::DistributeEvenly(distribution_snap_target) => write!(f, "{distribution_snap_target}"), } } } @@ -634,8 +634,8 @@ pub enum SnappingOptions { impl fmt::Display for SnappingOptions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - SnappingOptions::BoundingBoxes => write!(f, "Bounding Boxes"), - SnappingOptions::Paths => write!(f, "Paths"), + Self::BoundingBoxes => write!(f, "Bounding Boxes"), + Self::Paths => write!(f, "Paths"), } } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface.rs b/editor/src/messages/portfolio/document/utility_types/network_interface.rs index ed485a1f06..02fb4626d2 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -3182,7 +3182,7 @@ impl NodeNetworkInterface { // Public mutable methods impl NodeNetworkInterface { - pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) { + pub fn copy_all_navigation_metadata(&mut self, other_interface: &Self) { let mut stack = vec![vec![]]; while let Some(path) = stack.pop() { let Some(self_network_metadata) = self.network_metadata_mut(&path) else { @@ -5719,25 +5719,24 @@ pub enum InputConnector { impl Default for InputConnector { fn default() -> Self { - InputConnector::Export(0) + Self::Export(0) } } impl InputConnector { pub fn node(node_id: NodeId, input_index: usize) -> Self { - InputConnector::Node { node_id, input_index } + Self::Node { node_id, input_index } } pub fn input_index(&self) -> usize { match self { - InputConnector::Node { input_index, .. } => *input_index, - InputConnector::Export(input_index) => *input_index, + Self::Node { input_index, .. } | Self::Export(input_index) => *input_index, } } pub fn node_id(&self) -> Option { match self { - InputConnector::Node { node_id, .. } => Some(*node_id), + Self::Node { node_id, .. } => Some(*node_id), _ => None, } } @@ -5759,25 +5758,24 @@ pub enum OutputConnector { impl Default for OutputConnector { fn default() -> Self { - OutputConnector::Import(0) + Self::Import(0) } } impl OutputConnector { pub fn node(node_id: NodeId, output_index: usize) -> Self { - OutputConnector::Node { node_id, output_index } + Self::Node { node_id, output_index } } pub fn index(&self) -> usize { match self { - OutputConnector::Node { output_index, .. } => *output_index, - OutputConnector::Import(output_index) => *output_index, + Self::Node { output_index, .. } | Self::Import(output_index) => *output_index, } } pub fn node_id(&self) -> Option { match self { - OutputConnector::Node { node_id, .. } => Some(*node_id), + Self::Node { node_id, .. } => Some(*node_id), _ => None, } } @@ -5804,8 +5802,8 @@ impl Default for Ports { } impl Ports { - pub fn new() -> Ports { - Ports { + pub fn new() -> Self { + Self { input_ports: Vec::new(), output_ports: Vec::new(), } @@ -5934,7 +5932,7 @@ pub struct NodeNetworkMetadata { impl Clone for NodeNetworkMetadata { fn clone(&self) -> Self { - NodeNetworkMetadata { + Self { persistent_metadata: self.persistent_metadata.clone(), transient_metadata: Default::default(), } @@ -5965,7 +5963,7 @@ impl NodeNetworkMetadata { for segment in nested_path { network_metadata = network_metadata - .and_then(|network: &mut NodeNetworkMetadata| network.persistent_metadata.node_metadata.get_mut(segment)) + .and_then(|network: &mut Self| network.persistent_metadata.node_metadata.get_mut(segment)) .and_then(|node| node.persistent_metadata.network_metadata.as_mut()); } network_metadata @@ -6007,7 +6005,7 @@ impl TransientMetadata { } pub fn is_loaded(&self) -> bool { - matches!(self, TransientMetadata::Loaded(_)) + matches!(self, Self::Loaded(_)) } } @@ -6067,7 +6065,7 @@ pub struct DocumentNodeMetadata { impl Clone for DocumentNodeMetadata { fn clone(&self) -> Self { - DocumentNodeMetadata { + Self { persistent_metadata: self.persistent_metadata.clone(), transient_metadata: Default::default(), } @@ -6095,7 +6093,7 @@ pub struct NumberInputSettings { impl Default for NumberInputSettings { fn default() -> Self { - NumberInputSettings { + Self { unit: None, min: None, max: None, @@ -6259,7 +6257,7 @@ pub struct InputMetadata { impl Clone for InputMetadata { fn clone(&self) -> Self { - InputMetadata { + Self { persistent_metadata: self.persistent_metadata.clone(), transient_metadata: Default::default(), } @@ -6274,7 +6272,7 @@ impl PartialEq for InputMetadata { impl From<(&str, &str)> for InputMetadata { fn from(input_name_and_description: (&str, &str)) -> Self { - InputMetadata { + Self { persistent_metadata: InputPersistentMetadata::default() .with_name(input_name_and_description.0) .with_description(input_name_and_description.1), @@ -6285,7 +6283,7 @@ impl From<(&str, &str)> for InputMetadata { impl InputMetadata { pub fn with_name_description_override(input_name: &str, description: &str, widget_override: WidgetOverride) -> Self { - InputMetadata { + Self { persistent_metadata: InputPersistentMetadata::default().with_name(input_name).with_description(description).with_override(widget_override), ..Default::default() } @@ -6300,18 +6298,18 @@ pub enum NodeTypePersistentMetadata { impl Default for NodeTypePersistentMetadata { fn default() -> Self { - NodeTypePersistentMetadata::node(IVec2::ZERO) + Self::node(IVec2::ZERO) } } impl NodeTypePersistentMetadata { - pub fn node(position: IVec2) -> NodeTypePersistentMetadata { - NodeTypePersistentMetadata::Node(NodePersistentMetadata { + pub fn node(position: IVec2) -> Self { + Self::Node(NodePersistentMetadata { position: NodePosition::Absolute(position), }) } - pub fn layer(position: IVec2) -> NodeTypePersistentMetadata { - NodeTypePersistentMetadata::Layer(LayerPersistentMetadata { + pub fn layer(position: IVec2) -> Self { + Self::Layer(LayerPersistentMetadata { position: LayerPosition::Absolute(position), owned_nodes: TransientMetadata::default(), }) diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/deserialization.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/deserialization.rs index c1099a0f17..c4969f34fb 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/deserialization.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/deserialization.rs @@ -21,7 +21,7 @@ pub struct DocumentNodePersistentMetadataInputNames { impl From for DocumentNodePersistentMetadata { fn from(old: DocumentNodePersistentMetadataInputNames) -> Self { - DocumentNodePersistentMetadata { + Self { input_metadata: Vec::new(), reference: old.reference, display_name: old.display_name, @@ -74,7 +74,7 @@ impl From for DocumentNodePersisten ..Default::default() }) } - DocumentNodePersistentMetadata { + Self { reference: old.reference, display_name: old.display_name, input_metadata: Vec::new(), @@ -106,7 +106,7 @@ pub struct DocumentNodePersistentMetadataHasPrimaryOutput { impl From for DocumentNodePersistentMetadata { fn from(old: DocumentNodePersistentMetadataHasPrimaryOutput) -> Self { - DocumentNodePersistentMetadata { + Self { reference: old.reference, display_name: old.display_name, input_metadata: old.input_metadata, diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs index 97eb99ac14..30d94fcd97 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs @@ -48,7 +48,7 @@ pub enum TypeSource { impl TypeSource { /// The reduced set of frontend types for displaying color. pub fn displayed_type(&self) -> FrontendGraphDataType { - if matches!(self, TypeSource::Invalid) { + if matches!(self, Self::Invalid) { return FrontendGraphDataType::Invalid; }; match self.compiled_nested_type() { @@ -77,8 +77,8 @@ impl TypeSource { pub fn compiled_nested_type(&self) -> Option<&Type> { match self { - TypeSource::Compiled(compiled_type) => Some(compiled_type.nested_type()), - TypeSource::TaggedValue(value_type) => Some(value_type.nested_type()), + Self::Compiled(compiled_type) => Some(compiled_type.nested_type()), + Self::TaggedValue(value_type) => Some(value_type.nested_type()), _ => None, } } @@ -91,22 +91,22 @@ impl TypeSource { /// The type to display in the tooltip label. pub fn resolved_type_tooltip_string(&self) -> String { match self { - TypeSource::Compiled(compiled_type) => format!("Data Type: {:?}", compiled_type.nested_type().to_string()), - TypeSource::TaggedValue(value_type) => format!("Data Type: {:?}", value_type.nested_type().to_string()), - TypeSource::Unknown => "Unknown Data Type".to_string(), - TypeSource::Invalid => "Invalid Type Combination".to_string(), - TypeSource::Error(_) => "Error Getting Data Type".to_string(), + Self::Compiled(compiled_type) => format!("Data Type: {:?}", compiled_type.nested_type().to_string()), + Self::TaggedValue(value_type) => format!("Data Type: {:?}", value_type.nested_type().to_string()), + Self::Unknown => "Unknown Data Type".to_string(), + Self::Invalid => "Invalid Type Combination".to_string(), + Self::Error(_) => "Error Getting Data Type".to_string(), } } /// The type to display in the node row. pub fn resolved_type_node_string(&self) -> String { match self { - TypeSource::Compiled(compiled_type) => compiled_type.nested_type().to_string(), - TypeSource::TaggedValue(value_type) => value_type.nested_type().to_string(), - TypeSource::Unknown => "Unknown".to_string(), - TypeSource::Invalid => "Invalid".to_string(), - TypeSource::Error(_) => "Error".to_string(), + Self::Compiled(compiled_type) => compiled_type.nested_type().to_string(), + Self::TaggedValue(value_type) => value_type.nested_type().to_string(), + Self::Unknown => "Unknown".to_string(), + Self::Invalid => "Invalid".to_string(), + Self::Error(_) => "Error".to_string(), } } } diff --git a/editor/src/messages/portfolio/document/utility_types/nodes.rs b/editor/src/messages/portfolio/document/utility_types/nodes.rs index de2aac20d5..9578a3e507 100644 --- a/editor/src/messages/portfolio/document/utility_types/nodes.rs +++ b/editor/src/messages/portfolio/document/utility_types/nodes.rs @@ -167,8 +167,8 @@ impl SelectedNodes { std::mem::replace(&mut self.0, new) } - pub fn filtered_selected_nodes(&self, filter: impl Fn(&NodeId) -> bool) -> SelectedNodes { - SelectedNodes(self.0.iter().copied().filter(filter).collect()) + pub fn filtered_selected_nodes(&self, filter: impl Fn(&NodeId) -> bool) -> Self { + Self(self.0.iter().copied().filter(filter).collect()) } } diff --git a/editor/src/messages/portfolio/document/utility_types/transformation.rs b/editor/src/messages/portfolio/document/utility_types/transformation.rs index 63e1b8baa8..45bef48f7e 100644 --- a/editor/src/messages/portfolio/document/utility_types/transformation.rs +++ b/editor/src/messages/portfolio/document/utility_types/transformation.rs @@ -40,14 +40,14 @@ pub enum OriginalTransforms { } impl Default for OriginalTransforms { fn default() -> Self { - OriginalTransforms::Path(HashMap::new()) + Self::Path(HashMap::new()) } } impl OriginalTransforms { pub fn clear(&mut self) { match self { - OriginalTransforms::Layer(layer_map) => layer_map.clear(), - OriginalTransforms::Path(path_map) => path_map.clear(), + Self::Layer(layer_map) => layer_map.clear(), + Self::Path(path_map) => path_map.clear(), } } @@ -61,7 +61,7 @@ impl OriginalTransforms { pub fn update<'a>(&mut self, selected: &'a [LayerNodeIdentifier], network_interface: &NodeNetworkInterface, shape_editor: Option<&'a ShapeState>) { match self { - OriginalTransforms::Layer(layer_map) => { + Self::Layer(layer_map) => { layer_map.retain(|layer, _| selected.contains(layer)); for &layer in selected { if layer == LayerNodeIdentifier::ROOT_PARENT { @@ -71,7 +71,7 @@ impl OriginalTransforms { layer_map.entry(layer).or_insert_with(|| Self::get_layer_transform(layer, network_interface).unwrap_or_default()); } } - OriginalTransforms::Path(path_map) => { + Self::Path(path_map) => { let Some(shape_editor) = shape_editor else { warn!("No shape editor structure found, which only happens in select tool, which cannot reach this point as we check for ToolType"); return; @@ -139,12 +139,12 @@ pub enum Axis { } impl Axis { - pub fn contrainted_to_axis(self, target: Axis, local: bool) -> (Self, bool) { + pub fn contrainted_to_axis(self, target: Self, local: bool) -> (Self, bool) { if self != target { return (target, false); } - if local { (Axis::Both, false) } else { (self, true) } + if local { (Self::Both, false) } else { (self, true) } } } @@ -323,7 +323,7 @@ impl TransformType { pub fn equivalent_to(&self, operation: TransformOperation) -> bool { matches!( (operation, self), - (TransformOperation::Scaling(_), TransformType::Scale) | (TransformOperation::Grabbing(_), TransformType::Grab) | (TransformOperation::Rotating(_), TransformType::Rotate) + (TransformOperation::Scaling(_), Self::Scale) | (TransformOperation::Grabbing(_), Self::Grab) | (TransformOperation::Rotating(_), Self::Rotate) ) } } @@ -331,12 +331,12 @@ impl TransformType { impl TransformOperation { #[allow(clippy::too_many_arguments)] pub fn apply_transform_operation(&self, selected: &mut Selected, state: &TransformationState, document: &DocumentMessageHandler) { - if self != &TransformOperation::None { + if self != &Self::None { let mut transformation = match self { - TransformOperation::Grabbing(translation) => DAffine2::from_translation(translation.to_dvec(state, document)), - TransformOperation::Rotating(rotation) => DAffine2::from_angle(rotation.to_f64(state.is_rounded_to_intervals)), - TransformOperation::Scaling(scale) => DAffine2::from_scale(scale.to_dvec(state.is_rounded_to_intervals)), - TransformOperation::None => unreachable!(), + Self::Grabbing(translation) => DAffine2::from_translation(translation.to_dvec(state, document)), + Self::Rotating(rotation) => DAffine2::from_angle(rotation.to_f64(state.is_rounded_to_intervals)), + Self::Scaling(scale) => DAffine2::from_scale(scale.to_dvec(state.is_rounded_to_intervals)), + Self::None => unreachable!(), }; let normalized_transform = state.local_to_viewport_transform(); transformation = normalized_transform * transformation * normalized_transform.inverse(); @@ -348,27 +348,27 @@ impl TransformOperation { pub fn axis_constraint(&self) -> Axis { match self { - TransformOperation::Grabbing(grabbing) => grabbing.constraint, - TransformOperation::Scaling(scaling) => scaling.constraint, + Self::Grabbing(grabbing) => grabbing.constraint, + Self::Scaling(scaling) => scaling.constraint, _ => Axis::Both, } } pub fn can_begin_typing(&self) -> bool { - self.is_constraint_to_axis() || !matches!(self, TransformOperation::Grabbing(_)) + self.is_constraint_to_axis() || !matches!(self, Self::Grabbing(_)) } #[allow(clippy::too_many_arguments)] pub fn constrain_axis(&mut self, axis: Axis, selected: &mut Selected, state: &TransformationState, document: &DocumentMessageHandler) -> bool { let resulting_local; (*self, resulting_local) = match self { - TransformOperation::Grabbing(translation) => { + Self::Grabbing(translation) => { let (translation, resulting_local) = translation.with_constraint(axis, state.is_transforming_in_local_space); - (TransformOperation::Grabbing(translation), resulting_local) + (Self::Grabbing(translation), resulting_local) } - TransformOperation::Scaling(scale) => { + Self::Scaling(scale) => { let (scale, resulting_local) = scale.with_constraint(axis, state.is_transforming_in_local_space); - (TransformOperation::Scaling(scale), resulting_local) + (Self::Scaling(scale), resulting_local) } _ => (*self, false), }; @@ -381,10 +381,10 @@ impl TransformOperation { #[allow(clippy::too_many_arguments)] pub fn grs_typed(&mut self, typed: Option, selected: &mut Selected, state: &TransformationState, document: &DocumentMessageHandler) { match self { - TransformOperation::None => (), - TransformOperation::Grabbing(translation) => translation.typed_distance = typed, - TransformOperation::Rotating(rotation) => rotation.typed_angle = typed, - TransformOperation::Scaling(scale) => scale.typed_factor = typed, + Self::None => (), + Self::Grabbing(translation) => translation.typed_distance = typed, + Self::Rotating(rotation) => rotation.typed_angle = typed, + Self::Scaling(scale) => scale.typed_factor = typed, }; self.apply_transform_operation(selected, state, document); @@ -420,10 +420,10 @@ impl TransformOperation { } let grs_hint_group = match self { - TransformOperation::None => unreachable!(), - TransformOperation::Scaling(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyG], [Key::KeyR]], "Grab/Rotate Selected")]), - TransformOperation::Grabbing(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyR], [Key::KeyS]], "Rotate/Scale Selected")]), - TransformOperation::Rotating(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyG], [Key::KeyS]], "Grab/Scale Selected")]), + Self::None => unreachable!(), + Self::Scaling(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyG], [Key::KeyR]], "Grab/Rotate Selected")]), + Self::Grabbing(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyR], [Key::KeyS]], "Rotate/Scale Selected")]), + Self::Rotating(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyG], [Key::KeyS]], "Grab/Scale Selected")]), }; let confirm_and_cancel_group = HintGroup(vec![ @@ -436,11 +436,11 @@ impl TransformOperation { if !self.is_typing() { let modifiers = vec![ HintInfo::keys([Key::Shift], "Slow"), - HintInfo::keys([Key::Control], if matches!(self, TransformOperation::Rotating(_)) { "15° Increments" } else { "Increments" }), + HintInfo::keys([Key::Control], if matches!(self, Self::Rotating(_)) { "15° Increments" } else { "Increments" }), ]; hint_groups.push(HintGroup(modifiers)); } - if !matches!(self, TransformOperation::Rotating(_)) { + if !matches!(self, Self::Rotating(_)) { hint_groups.push(HintGroup(input_hints)); } let mut typing_hints = vec![HintInfo::keys([Key::Minus], "Negate Direction")]; @@ -461,20 +461,20 @@ impl TransformOperation { pub fn is_typing(&self) -> bool { match self { - TransformOperation::None => false, - TransformOperation::Grabbing(translation) => translation.typed_distance.is_some(), - TransformOperation::Rotating(rotation) => rotation.typed_angle.is_some(), - TransformOperation::Scaling(scale) => scale.typed_factor.is_some(), + Self::None => false, + Self::Grabbing(translation) => translation.typed_distance.is_some(), + Self::Rotating(rotation) => rotation.typed_angle.is_some(), + Self::Scaling(scale) => scale.typed_factor.is_some(), } } #[allow(clippy::too_many_arguments)] pub fn negate(&mut self, selected: &mut Selected, state: &TransformationState, document: &DocumentMessageHandler) { - if *self != TransformOperation::None { + if *self != Self::None { *self = match self { - TransformOperation::Scaling(scale) => TransformOperation::Scaling(scale.negate()), - TransformOperation::Rotating(rotation) => TransformOperation::Rotating(rotation.negate()), - TransformOperation::Grabbing(translation) => TransformOperation::Grabbing(translation.negate()), + Self::Scaling(scale) => Self::Scaling(scale.negate()), + Self::Rotating(rotation) => Self::Rotating(rotation.negate()), + Self::Grabbing(translation) => Self::Grabbing(translation.negate()), _ => *self, }; diff --git a/editor/src/messages/portfolio/document/utility_types/wires.rs b/editor/src/messages/portfolio/document/utility_types/wires.rs index 7aad6977db..e2235b2b73 100644 --- a/editor/src/messages/portfolio/document/utility_types/wires.rs +++ b/editor/src/messages/portfolio/document/utility_types/wires.rs @@ -33,8 +33,8 @@ pub enum GraphWireStyle { impl std::fmt::Display for GraphWireStyle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - GraphWireStyle::GridAligned => write!(f, "Grid-Aligned"), - GraphWireStyle::Direct => write!(f, "Direct"), + Self::GridAligned => write!(f, "Grid-Aligned"), + Self::Direct => write!(f, "Direct"), } } } @@ -42,13 +42,13 @@ impl std::fmt::Display for GraphWireStyle { impl GraphWireStyle { pub fn tooltip_description(&self) -> &'static str { match self { - GraphWireStyle::GridAligned => "Wires follow the grid, running in straight lines between nodes.", - GraphWireStyle::Direct => "Wires bend to run at an angle directly between nodes.", + Self::GridAligned => "Wires follow the grid, running in straight lines between nodes.", + Self::Direct => "Wires bend to run at an angle directly between nodes.", } } pub fn is_direct(&self) -> bool { - *self == GraphWireStyle::Direct + *self == Self::Direct } } diff --git a/editor/src/messages/portfolio/utility_types.rs b/editor/src/messages/portfolio/utility_types.rs index 54a526ecdc..8f1a0f4abd 100644 --- a/editor/src/messages/portfolio/utility_types.rs +++ b/editor/src/messages/portfolio/utility_types.rs @@ -67,10 +67,10 @@ impl FontCatalogStyle { format!("{named_weight}{maybe_italic} ({weight})") } - pub fn from_named_style(named_style: &str, url: impl Into) -> FontCatalogStyle { + pub fn from_named_style(named_style: &str, url: impl Into) -> Self { let weight = named_style.split_terminator(['(', ')']).next_back().and_then(|x| x.parse::().ok()).unwrap_or(400); let italic = named_style.contains("Italic ("); - FontCatalogStyle { weight, italic, url: url.into() } + Self { weight, italic, url: url.into() } } /// Get the URL for the stylesheet for loading a font preview for this style of the given family name, subsetted to only the letters in the family name. @@ -94,9 +94,9 @@ pub enum Platform { impl Platform { pub fn as_keyboard_platform_layout(&self) -> KeyboardPlatformLayout { match self { - Platform::Mac => KeyboardPlatformLayout::Mac, - Platform::Windows | Platform::Linux => KeyboardPlatformLayout::Standard, - Platform::Unknown => { + Self::Mac => KeyboardPlatformLayout::Mac, + Self::Windows | Self::Linux => KeyboardPlatformLayout::Standard, + Self::Unknown => { warn!("The platform has not been set, remember to send `GlobalsMessage::SetPlatform` during editor initialization."); KeyboardPlatformLayout::Standard } @@ -126,11 +126,11 @@ pub enum PanelType { impl From for PanelType { fn from(value: String) -> Self { match value.as_str() { - "Document" => PanelType::Document, - "Welcome" => PanelType::Welcome, - "Layers" => PanelType::Layers, - "Properties" => PanelType::Properties, - "Data" => PanelType::DataPanel, + "Document" => Self::Document, + "Welcome" => Self::Welcome, + "Layers" => Self::Layers, + "Properties" => Self::Properties, + "Data" => Self::DataPanel, _ => panic!("Unknown panel type: {value}"), } } diff --git a/editor/src/messages/preferences/utility_types.rs b/editor/src/messages/preferences/utility_types.rs index dabcb5b7e4..248488e41e 100644 --- a/editor/src/messages/preferences/utility_types.rs +++ b/editor/src/messages/preferences/utility_types.rs @@ -9,9 +9,9 @@ pub enum SelectionMode { impl std::fmt::Display for SelectionMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - SelectionMode::Touched => write!(f, "Touched"), - SelectionMode::Enclosed => write!(f, "Enclosed"), - SelectionMode::Directional => write!(f, "Directional"), + Self::Touched => write!(f, "Touched"), + Self::Enclosed => write!(f, "Enclosed"), + Self::Directional => write!(f, "Directional"), } } } @@ -19,9 +19,9 @@ impl std::fmt::Display for SelectionMode { impl SelectionMode { pub fn tooltip_description(&self) -> &'static str { match self { - SelectionMode::Touched => "Select all layers at least partially covered by the dragged selection area.", - SelectionMode::Enclosed => "Select only layers fully enclosed by the dragged selection area.", - SelectionMode::Directional => r#""Touched" for leftward drags, "Enclosed" for rightward drags."#, + Self::Touched => "Select all layers at least partially covered by the dragged selection area.", + Self::Enclosed => "Select only layers fully enclosed by the dragged selection area.", + Self::Directional => r#""Touched" for leftward drags, "Enclosed" for rightward drags."#, } } } diff --git a/editor/src/messages/tool/common_functionality/compass_rose.rs b/editor/src/messages/tool/common_functionality/compass_rose.rs index bedc1ca230..1929c32349 100644 --- a/editor/src/messages/tool/common_functionality/compass_rose.rs +++ b/editor/src/messages/tool/common_functionality/compass_rose.rs @@ -86,9 +86,9 @@ impl CompassRoseState { pub fn axis_type(&self) -> Option { match self { - CompassRoseState::AxisX => Some(Axis::X), - CompassRoseState::AxisY => Some(Axis::Y), - CompassRoseState::Ring => Some(Axis::None), + Self::AxisX => Some(Axis::X), + Self::AxisY => Some(Axis::Y), + Self::Ring => Some(Axis::None), _ => None, } } @@ -111,9 +111,9 @@ impl Axis { impl From for DVec2 { fn from(value: Axis) -> Self { match value { - Axis::X => DVec2::X, - Axis::Y => DVec2::Y, - Axis::None => DVec2::ZERO, + Axis::X => Self::X, + Axis::Y => Self::Y, + Axis::None => Self::ZERO, } } } diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/grid_rows_columns_gizmo.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/grid_rows_columns_gizmo.rs index 308dbbdb48..c0f1c50c24 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/grid_rows_columns_gizmo.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/grid_rows_columns_gizmo.rs @@ -381,33 +381,33 @@ impl RowColumnGizmoType { pub fn direction(&self, viewport: DAffine2) -> DVec2 { match self { - RowColumnGizmoType::Top => viewport.transform_vector2(-DVec2::Y), - RowColumnGizmoType::Bottom => viewport.transform_vector2(DVec2::Y), - RowColumnGizmoType::Right => viewport.transform_vector2(DVec2::X), - RowColumnGizmoType::Left => viewport.transform_vector2(-DVec2::X), - RowColumnGizmoType::None => panic!("RowColumnGizmoType::None does not have a line"), + Self::Top => viewport.transform_vector2(-DVec2::Y), + Self::Bottom => viewport.transform_vector2(DVec2::Y), + Self::Right => viewport.transform_vector2(DVec2::X), + Self::Left => viewport.transform_vector2(-DVec2::X), + Self::None => panic!("RowColumnGizmoType::None does not have a line"), } } fn initial_dimension(&self, rows: u32, columns: u32) -> u32 { match self { - RowColumnGizmoType::Top | RowColumnGizmoType::Bottom => rows, - RowColumnGizmoType::Left | RowColumnGizmoType::Right => columns, - RowColumnGizmoType::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"), + Self::Top | Self::Bottom => rows, + Self::Left | Self::Right => columns, + Self::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"), } } fn spacing(&self, spacing: DVec2, grid_type: GridType, angles: DVec2) -> f64 { match self { - RowColumnGizmoType::Top | RowColumnGizmoType::Bottom => spacing.y, - RowColumnGizmoType::Left | RowColumnGizmoType::Right => { + Self::Top | Self::Bottom => spacing.y, + Self::Left | Self::Right => { if grid_type == GridType::Rectangular { spacing.x } else { spacing.y / (angles.x.to_radians().tan() + angles.y.to_radians().tan()) } } - RowColumnGizmoType::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"), + Self::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"), } } @@ -415,17 +415,17 @@ impl RowColumnGizmoType { use graphene_std::vector::generator_nodes::grid::*; match self { - RowColumnGizmoType::Top | RowColumnGizmoType::Bottom => RowsInput::INDEX, - RowColumnGizmoType::Left | RowColumnGizmoType::Right => ColumnsInput::INDEX, - RowColumnGizmoType::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"), + Self::Top | Self::Bottom => RowsInput::INDEX, + Self::Left | Self::Right => ColumnsInput::INDEX, + Self::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"), } } pub fn mouse_icon(&self) -> MouseCursorIcon { match self { - RowColumnGizmoType::Top | RowColumnGizmoType::Bottom => MouseCursorIcon::NSResize, - RowColumnGizmoType::Left | RowColumnGizmoType::Right => MouseCursorIcon::EWResize, - RowColumnGizmoType::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"), + Self::Top | Self::Bottom => MouseCursorIcon::NSResize, + Self::Left | Self::Right => MouseCursorIcon::EWResize, + Self::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"), } } diff --git a/editor/src/messages/tool/common_functionality/pivot.rs b/editor/src/messages/tool/common_functionality/pivot.rs index 20013bf678..f5038b5304 100644 --- a/editor/src/messages/tool/common_functionality/pivot.rs +++ b/editor/src/messages/tool/common_functionality/pivot.rs @@ -181,9 +181,9 @@ impl PivotGizmoState { impl fmt::Display for PivotGizmoType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - PivotGizmoType::Pivot => write!(f, "Custom Pivot"), - PivotGizmoType::Average => write!(f, "Origin (Average Point)"), - PivotGizmoType::Active => write!(f, "Origin (Active Object)"), + Self::Pivot => write!(f, "Custom Pivot"), + Self::Average => write!(f, "Origin (Average Point)"), + Self::Active => write!(f, "Origin (Active Object)"), // TODO: Add "Origin (Individual)" } } diff --git a/editor/src/messages/tool/tool_messages/artboard_tool.rs b/editor/src/messages/tool/tool_messages/artboard_tool.rs index e257dc359c..e4e60a9f13 100644 --- a/editor/src/messages/tool/tool_messages/artboard_tool.rs +++ b/editor/src/messages/tool/tool_messages/artboard_tool.rs @@ -241,7 +241,7 @@ impl Fsm for ArtboardToolFsmState { match (self, event) { (state, ArtboardToolMessage::Overlays { context: mut overlay_context }) => { let display_transform_cage = overlay_context.visibility_settings.transform_cage(); - if display_transform_cage && state != ArtboardToolFsmState::Drawing { + if display_transform_cage && state != Self::Drawing { if let Some(bounds) = tool_data.selected_artboard.and_then(|layer| document.metadata().bounding_box_document(layer)) { let bounding_box_manager = tool_data.bounding_box_manager.get_or_insert(BoundingBoxManager::default()); bounding_box_manager.bounds = bounds; @@ -260,7 +260,7 @@ impl Fsm for ArtboardToolFsmState { // TODO: Don't use `Key::Alt` directly, instead take it as a variable from the input mappings list like in all other places let alt_pressed = input.keyboard.get(Key::Alt as usize); let quick_measurement_enabled = overlay_context.visibility_settings.quick_measurement(); - let not_resizing = !matches!(state, ArtboardToolFsmState::ResizingBounds); + let not_resizing = !matches!(state, Self::ResizingBounds); if quick_measurement_enabled && not_resizing && alt_pressed { // Get the selected artboard bounds @@ -293,7 +293,7 @@ impl Fsm for ArtboardToolFsmState { self } - (ArtboardToolFsmState::Ready { .. }, ArtboardToolMessage::PointerDown) => { + (Self::Ready { .. }, ArtboardToolMessage::PointerDown) => { let to_viewport = document.metadata().document_to_viewport; let to_document = to_viewport.inverse(); tool_data.drag_start = to_document.transform_point2(input.mouse.position); @@ -302,19 +302,19 @@ impl Fsm for ArtboardToolFsmState { let state = if let Some(selected_edges) = tool_data.check_dragging_bounds(input.mouse.position) { tool_data.start_resizing(selected_edges, document, input); tool_data.get_snap_candidates(document, input); - ArtboardToolFsmState::ResizingBounds + Self::ResizingBounds } else if tool_data.select_artboard(document, input, viewport, responses) { tool_data.get_snap_candidates(document, input); - ArtboardToolFsmState::Dragging + Self::Dragging } else { tool_data.draw.start(document, input, viewport); - ArtboardToolFsmState::Drawing + Self::Drawing }; responses.add(DocumentMessage::StartTransaction); state } - (ArtboardToolFsmState::ResizingBounds, ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }) => { + (Self::ResizingBounds, ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }) => { let from_center = input.keyboard.get(center as usize); let constrain_square = input.keyboard.get(constrain_axis_or_aspect as usize); tool_data.resize_artboard(responses, document, input, viewport, from_center, constrain_square); @@ -326,9 +326,9 @@ impl Fsm for ArtboardToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - ArtboardToolFsmState::ResizingBounds + Self::ResizingBounds } - (ArtboardToolFsmState::Dragging, ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }) => { + (Self::Dragging, ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }) => { if let Some(bounds) = &mut tool_data.bounding_box_manager { let axis_align = input.keyboard.get(constrain_axis_or_aspect as usize); @@ -343,7 +343,7 @@ impl Fsm for ArtboardToolFsmState { if tool_data.selected_artboard.unwrap() == LayerNodeIdentifier::ROOT_PARENT { log::error!("Selected artboard cannot be ROOT_PARENT"); - return ArtboardToolFsmState::Ready { hovered }; + return Self::Ready { hovered }; } responses.add(GraphOperationMessage::ResizeArtboard { layer: tool_data.selected_artboard.unwrap(), @@ -365,9 +365,9 @@ impl Fsm for ArtboardToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); } - ArtboardToolFsmState::Dragging + Self::Dragging } - (ArtboardToolFsmState::Drawing, ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }) => { + (Self::Drawing, ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }) => { // The draw.calculate_points_ignore_layer uses this value to avoid snapping to itself. tool_data.draw.layer = tool_data.selected_artboard; let [start, end] = tool_data.draw.calculate_points_ignore_layer(document, input, viewport, center, constrain_axis_or_aspect, true); @@ -406,10 +406,10 @@ impl Fsm for ArtboardToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - ArtboardToolFsmState::Drawing + Self::Drawing } - (ArtboardToolFsmState::Ready { .. }, ArtboardToolMessage::PointerMove { .. }) => { + (Self::Ready { .. }, ArtboardToolMessage::PointerMove { .. }) => { let mut cursor = tool_data .bounding_box_manager .as_ref() @@ -428,25 +428,25 @@ impl Fsm for ArtboardToolFsmState { responses.add(FrontendMessage::UpdateMouseCursor { cursor }); } - ArtboardToolFsmState::Ready { hovered } + Self::Ready { hovered } } - (ArtboardToolFsmState::ResizingBounds, ArtboardToolMessage::PointerOutsideViewport { .. }) => { + (Self::ResizingBounds, ArtboardToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses); - ArtboardToolFsmState::ResizingBounds + Self::ResizingBounds } - (ArtboardToolFsmState::Dragging, ArtboardToolMessage::PointerOutsideViewport { .. }) => { + (Self::Dragging, ArtboardToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning tool_data.auto_panning.shift_viewport(input, viewport, responses); - ArtboardToolFsmState::Dragging + Self::Dragging } - (ArtboardToolFsmState::Drawing, ArtboardToolMessage::PointerOutsideViewport { .. }) => { + (Self::Drawing, ArtboardToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning tool_data.auto_panning.shift_viewport(input, viewport, responses); - ArtboardToolFsmState::Drawing + Self::Drawing } (state, ArtboardToolMessage::PointerOutsideViewport { constrain_axis_or_aspect, center }) => { // Auto-panning @@ -458,7 +458,7 @@ impl Fsm for ArtboardToolFsmState { state } - (ArtboardToolFsmState::Drawing | ArtboardToolFsmState::ResizingBounds | ArtboardToolFsmState::Dragging, ArtboardToolMessage::PointerUp) => { + (Self::Drawing | Self::ResizingBounds | Self::Dragging, ArtboardToolMessage::PointerUp) => { responses.add(DocumentMessage::EndTransaction); tool_data.draw.cleanup(responses); @@ -469,7 +469,7 @@ impl Fsm for ArtboardToolFsmState { responses.add(OverlaysMessage::Draw); - ArtboardToolFsmState::Ready { hovered } + Self::Ready { hovered } } (_, ArtboardToolMessage::UpdateSelectedArtboard) => { tool_data.selected_artboard = document @@ -483,7 +483,7 @@ impl Fsm for ArtboardToolFsmState { tool_data.selected_artboard.take(); responses.add(DocumentMessage::DeleteSelectedLayers); - ArtboardToolFsmState::Ready { hovered } + Self::Ready { hovered } } ( _, @@ -495,14 +495,14 @@ impl Fsm for ArtboardToolFsmState { }, ) => { let Some(bounds) = &mut tool_data.bounding_box_manager else { - return ArtboardToolFsmState::Ready { hovered }; + return Self::Ready { hovered }; }; let Some(selected_artboard) = tool_data.selected_artboard else { - return ArtboardToolFsmState::Ready { hovered }; + return Self::Ready { hovered }; }; if selected_artboard == LayerNodeIdentifier::ROOT_PARENT { log::error!("Selected artboard cannot be ROOT_PARENT"); - return ArtboardToolFsmState::Ready { hovered }; + return Self::Ready { hovered }; } let resize = input.keyboard.key(resize); @@ -519,7 +519,7 @@ impl Fsm for ArtboardToolFsmState { dimensions: (existing_bottom_right - existing_top_left).round().as_ivec2(), }); - return ArtboardToolFsmState::Ready { hovered }; + return Self::Ready { hovered }; } // Swap and negate coordinates as needed to match the resize direction that's closest to the current tilt angle @@ -566,15 +566,15 @@ impl Fsm for ArtboardToolFsmState { dimensions: new.transform_vector2(existing_bottom_right - existing_top_left).round().as_ivec2(), }); - ArtboardToolFsmState::Ready { hovered } + Self::Ready { hovered } } - (ArtboardToolFsmState::Dragging | ArtboardToolFsmState::Drawing | ArtboardToolFsmState::ResizingBounds, ArtboardToolMessage::Abort) => { + (Self::Dragging | Self::Drawing | Self::ResizingBounds, ArtboardToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); tool_data.draw.cleanup(responses); responses.add(OverlaysMessage::Draw); - ArtboardToolFsmState::Ready { hovered } + Self::Ready { hovered } } _ => self, } @@ -582,20 +582,20 @@ impl Fsm for ArtboardToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - ArtboardToolFsmState::Ready { .. } => HintData(vec![ + Self::Ready { .. } => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDrag, "Draw Artboard")]), HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDrag, "Move Artboard")]), HintGroup(vec![HintInfo::keys([Key::Backspace], "Delete Artboard")]), ]), - ArtboardToolFsmState::Dragging => HintData(vec![ + Self::Dragging => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "Constrain to Axis")]), ]), - ArtboardToolFsmState::Drawing => HintData(vec![ + Self::Drawing => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "Constrain Square"), HintInfo::keys([Key::Alt], "From Center")]), ]), - ArtboardToolFsmState::ResizingBounds => HintData(vec![ + Self::ResizingBounds => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "Preserve Aspect Ratio"), HintInfo::keys([Key::Alt], "From Center")]), ]), diff --git a/editor/src/messages/tool/tool_messages/brush_tool.rs b/editor/src/messages/tool/tool_messages/brush_tool.rs index ba344fcc59..cc38823b37 100644 --- a/editor/src/messages/tool/tool_messages/brush_tool.rs +++ b/editor/src/messages/tool/tool_messages/brush_tool.rs @@ -358,7 +358,7 @@ impl Fsm for BrushToolFsmState { let ToolMessage::Brush(event) = event else { return self }; match (self, event) { - (BrushToolFsmState::Ready, BrushToolMessage::DragStart) => { + (Self::Ready, BrushToolMessage::DragStart) => { responses.add(DocumentMessage::StartTransaction); let loaded_layer = tool_data.load_existing_strokes(document); @@ -397,7 +397,7 @@ impl Fsm for BrushToolFsmState { }); tool_data.update_strokes(responses); - BrushToolFsmState::Drawing + Self::Drawing } // Create the new layer, wait for the render output to return its transform, and then create the rest of the layer else { @@ -406,11 +406,11 @@ impl Fsm for BrushToolFsmState { responses.add(DeferMessage::AfterGraphRun { messages: vec![BrushToolMessage::DragStart.into()], }); - BrushToolFsmState::Ready + Self::Ready } } - (BrushToolFsmState::Drawing, BrushToolMessage::PointerMove) => { + (Self::Drawing, BrushToolMessage::PointerMove) => { if let Some(layer) = tool_data.layer && let Some(stroke) = tool_data.strokes.last_mut() { @@ -426,10 +426,10 @@ impl Fsm for BrushToolFsmState { } tool_data.update_strokes(responses); - BrushToolFsmState::Drawing + Self::Drawing } - (BrushToolFsmState::Drawing, BrushToolMessage::DragStop) => { + (Self::Drawing, BrushToolMessage::DragStop) => { if !tool_data.strokes.is_empty() { responses.add(DocumentMessage::EndTransaction); } else { @@ -437,13 +437,13 @@ impl Fsm for BrushToolFsmState { } tool_data.strokes.clear(); - BrushToolFsmState::Ready + Self::Ready } - (BrushToolFsmState::Drawing, BrushToolMessage::Abort) => { + (Self::Drawing, BrushToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); tool_data.strokes.clear(); - BrushToolFsmState::Ready + Self::Ready } (_, BrushToolMessage::WorkingColorChanged) => { responses.add(BrushToolMessage::UpdateOptions { @@ -457,11 +457,11 @@ impl Fsm for BrushToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - BrushToolFsmState::Ready => HintData(vec![ + Self::Ready => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDrag, "Draw")]), HintGroup(vec![HintInfo::multi_keys([[Key::BracketLeft], [Key::BracketRight]], "Shrink/Grow Brush")]), ]), - BrushToolFsmState::Drawing => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), + Self::Drawing => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), }; hint_data.send_layout(responses); diff --git a/editor/src/messages/tool/tool_messages/eyedropper_tool.rs b/editor/src/messages/tool/tool_messages/eyedropper_tool.rs index ea7843a923..a95050a496 100644 --- a/editor/src/messages/tool/tool_messages/eyedropper_tool.rs +++ b/editor/src/messages/tool/tool_messages/eyedropper_tool.rs @@ -88,17 +88,17 @@ impl Fsm for EyedropperToolFsmState { let ToolMessage::Eyedropper(event) = event else { return self }; match (self, event) { // Ready -> Sampling - (EyedropperToolFsmState::Ready, mouse_down) if matches!(mouse_down, EyedropperToolMessage::SamplePrimaryColorBegin | EyedropperToolMessage::SampleSecondaryColorBegin) => { + (Self::Ready, mouse_down) if matches!(mouse_down, EyedropperToolMessage::SamplePrimaryColorBegin | EyedropperToolMessage::SampleSecondaryColorBegin) => { update_cursor_preview(responses, input, global_tool_data, None); if mouse_down == EyedropperToolMessage::SamplePrimaryColorBegin { - EyedropperToolFsmState::SamplingPrimary + Self::SamplingPrimary } else { - EyedropperToolFsmState::SamplingSecondary + Self::SamplingSecondary } } // Sampling -> Sampling - (EyedropperToolFsmState::SamplingPrimary | EyedropperToolFsmState::SamplingSecondary, EyedropperToolMessage::PointerMove) => { + (Self::SamplingPrimary | Self::SamplingSecondary, EyedropperToolMessage::PointerMove) => { let mouse_position = viewport.logical(input.mouse.position); if viewport.is_in_bounds(mouse_position + viewport.offset()) { update_cursor_preview(responses, input, global_tool_data, None); @@ -109,18 +109,18 @@ impl Fsm for EyedropperToolFsmState { self } // Sampling -> Ready - (EyedropperToolFsmState::SamplingPrimary, EyedropperToolMessage::SamplePrimaryColorEnd) | (EyedropperToolFsmState::SamplingSecondary, EyedropperToolMessage::SampleSecondaryColorEnd) => { - let set_color_choice = if self == EyedropperToolFsmState::SamplingPrimary { "Primary" } else { "Secondary" }.to_string(); + (Self::SamplingPrimary, EyedropperToolMessage::SamplePrimaryColorEnd) | (Self::SamplingSecondary, EyedropperToolMessage::SampleSecondaryColorEnd) => { + let set_color_choice = if self == Self::SamplingPrimary { "Primary" } else { "Secondary" }.to_string(); update_cursor_preview(responses, input, global_tool_data, Some(set_color_choice)); disable_cursor_preview(responses); - EyedropperToolFsmState::Ready + Self::Ready } // Any -> Ready (_, EyedropperToolMessage::Abort) => { disable_cursor_preview(responses); - EyedropperToolFsmState::Ready + Self::Ready } // Ready -> Ready _ => self, @@ -129,13 +129,11 @@ impl Fsm for EyedropperToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - EyedropperToolFsmState::Ready => HintData(vec![HintGroup(vec![ + Self::Ready => HintData(vec![HintGroup(vec![ HintInfo::mouse(MouseMotion::Lmb, "Sample to Primary"), HintInfo::keys_and_mouse([Key::Shift], MouseMotion::Lmb, "Sample to Secondary"), ])]), - EyedropperToolFsmState::SamplingPrimary | EyedropperToolFsmState::SamplingSecondary => { - HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]) - } + Self::SamplingPrimary | Self::SamplingSecondary => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), }; hint_data.send_layout(responses); @@ -143,8 +141,8 @@ impl Fsm for EyedropperToolFsmState { fn update_cursor(&self, responses: &mut VecDeque) { let cursor = match *self { - EyedropperToolFsmState::Ready => MouseCursorIcon::Default, - EyedropperToolFsmState::SamplingPrimary | EyedropperToolFsmState::SamplingSecondary => MouseCursorIcon::None, + Self::Ready => MouseCursorIcon::Default, + Self::SamplingPrimary | Self::SamplingSecondary => MouseCursorIcon::None, }; responses.add(FrontendMessage::UpdateMouseCursor { cursor }); diff --git a/editor/src/messages/tool/tool_messages/fill_tool.rs b/editor/src/messages/tool/tool_messages/fill_tool.rs index f29d73d1b7..1fc571ff87 100644 --- a/editor/src/messages/tool/tool_messages/fill_tool.rs +++ b/editor/src/messages/tool/tool_messages/fill_tool.rs @@ -120,7 +120,7 @@ impl Fsm for FillToolFsmState { responses.add(OverlaysMessage::Draw); self } - (FillToolFsmState::Ready, color_event) => { + (Self::Ready, color_event) => { let Some(layer_identifier) = document.click(input, viewport) else { return self; }; @@ -137,13 +137,13 @@ impl Fsm for FillToolFsmState { responses.add(DocumentMessage::AddTransaction); responses.add(GraphOperationMessage::FillSet { layer: layer_identifier, fill }); - FillToolFsmState::Filling + Self::Filling } - (FillToolFsmState::Filling, FillToolMessage::PointerUp) => FillToolFsmState::Ready, - (FillToolFsmState::Filling, FillToolMessage::Abort) => { + (Self::Filling, FillToolMessage::PointerUp) => Self::Ready, + (Self::Filling, FillToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); - FillToolFsmState::Ready + Self::Ready } _ => self, } @@ -151,11 +151,11 @@ impl Fsm for FillToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - FillToolFsmState::Ready => HintData(vec![HintGroup(vec![ + Self::Ready => HintData(vec![HintGroup(vec![ HintInfo::mouse(MouseMotion::Lmb, "Fill with Primary"), HintInfo::keys([Key::Shift], "Fill with Secondary").prepend_plus(), ])]), - FillToolFsmState::Filling => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), + Self::Filling => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), }; hint_data.send_layout(responses); diff --git a/editor/src/messages/tool/tool_messages/freehand_tool.rs b/editor/src/messages/tool/tool_messages/freehand_tool.rs index 9412577b48..ab08223db5 100644 --- a/editor/src/messages/tool/tool_messages/freehand_tool.rs +++ b/editor/src/messages/tool/tool_messages/freehand_tool.rs @@ -247,7 +247,7 @@ impl Fsm for FreehandToolFsmState { self } - (FreehandToolFsmState::Ready, FreehandToolMessage::DragStart { append_to_selected }) => { + (Self::Ready, FreehandToolMessage::DragStart { append_to_selected }) => { responses.add(DocumentMessage::StartTransaction); tool_data.dragged = false; @@ -263,7 +263,7 @@ impl Fsm for FreehandToolFsmState { extend_path_with_next_segment(tool_data, position, true, responses); - return FreehandToolFsmState::Drawing; + return Self::Drawing; } if input.keyboard.key(append_to_selected) { @@ -277,7 +277,7 @@ impl Fsm for FreehandToolFsmState { extend_path_with_next_segment(tool_data, position, false, responses); - return FreehandToolFsmState::Drawing; + return Self::Drawing; } } @@ -294,9 +294,9 @@ impl Fsm for FreehandToolFsmState { tool_options.stroke.apply_stroke(tool_data.weight, layer, responses); tool_data.layer = Some(layer); - FreehandToolFsmState::Drawing + Self::Drawing } - (FreehandToolFsmState::Drawing, FreehandToolMessage::PointerMove) => { + (Self::Drawing, FreehandToolMessage::PointerMove) => { if let Some(layer) = tool_data.layer { let transform = document.metadata().transform_to_viewport(layer); let position = transform.inverse().transform_point2(input.mouse.position); @@ -304,9 +304,9 @@ impl Fsm for FreehandToolFsmState { extend_path_with_next_segment(tool_data, position, true, responses); } - FreehandToolFsmState::Drawing + Self::Drawing } - (FreehandToolFsmState::Drawing, FreehandToolMessage::DragStop) => { + (Self::Drawing, FreehandToolMessage::DragStop) => { if tool_data.dragged { responses.add(DocumentMessage::CommitTransaction); } else { @@ -316,14 +316,14 @@ impl Fsm for FreehandToolFsmState { tool_data.end_point = None; tool_data.layer = None; - FreehandToolFsmState::Ready + Self::Ready } - (FreehandToolFsmState::Drawing, FreehandToolMessage::Abort) => { + (Self::Drawing, FreehandToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); tool_data.layer = None; tool_data.end_point = None; - FreehandToolFsmState::Ready + Self::Ready } (_, FreehandToolMessage::WorkingColorChanged) => { responses.add(FreehandToolMessage::UpdateOptions { @@ -337,12 +337,12 @@ impl Fsm for FreehandToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - FreehandToolFsmState::Ready => HintData(vec![HintGroup(vec![ + Self::Ready => HintData(vec![HintGroup(vec![ HintInfo::mouse(MouseMotion::LmbDrag, "Draw Polyline"), // TODO: Only show this if a single layer is selected and it's of a valid type (e.g. a vector path but not raster or artboard) HintInfo::keys([Key::Shift], "Append to Selected Layer").prepend_plus(), ])]), - FreehandToolFsmState::Drawing => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), + Self::Drawing => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), }; hint_data.send_layout(responses); diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index fa5b3f38a4..d83d79c7b2 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -292,7 +292,7 @@ impl Fsm for GradientToolFsmState { self } - (GradientToolFsmState::Ready, GradientToolMessage::DeleteStop) => { + (Self::Ready, GradientToolMessage::DeleteStop) => { let Some(selected_gradient) = &mut tool_data.selected_gradient else { return self; }; @@ -383,7 +383,7 @@ impl Fsm for GradientToolFsmState { self } - (GradientToolFsmState::Ready, GradientToolMessage::PointerDown) => { + (Self::Ready, GradientToolMessage::PointerDown) => { let mouse = input.mouse.position; tool_data.drag_start = mouse; let tolerance = (MANIPULATOR_GROUP_MARKER_SIZE * 2.).powi(2); @@ -422,7 +422,7 @@ impl Fsm for GradientToolFsmState { } let gradient_state = if dragging { - GradientToolFsmState::Drawing + Self::Drawing } else { let selected_layer = document.click(input, viewport); @@ -430,7 +430,7 @@ impl Fsm for GradientToolFsmState { if let Some(layer) = selected_layer { // Add check for raster layer if NodeGraphLayer::is_raster_layer(layer, &mut document.network_interface) { - return GradientToolFsmState::Ready; + return Self::Ready; } if !document.network_interface.selected_nodes().selected_layers_contains(layer, document.metadata()) { let nodes = vec![layer.to_node()]; @@ -449,15 +449,15 @@ impl Fsm for GradientToolFsmState { tool_data.selected_gradient = Some(selected_gradient); - GradientToolFsmState::Drawing + Self::Drawing } else { - GradientToolFsmState::Ready + Self::Ready } }; responses.add(DocumentMessage::StartTransaction); gradient_state } - (GradientToolFsmState::Drawing, GradientToolMessage::PointerMove { constrain_axis }) => { + (Self::Drawing, GradientToolMessage::PointerMove { constrain_axis }) => { if let Some(selected_gradient) = &mut tool_data.selected_gradient { let mouse = input.mouse.position; // tool_data.snap_manager.snap_position(responses, document, input.mouse.position); selected_gradient.update_gradient(mouse, responses, input.keyboard.get(constrain_axis as usize), selected_gradient.gradient.gradient_type); @@ -470,9 +470,9 @@ impl Fsm for GradientToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - GradientToolFsmState::Drawing + Self::Drawing } - (GradientToolFsmState::Drawing, GradientToolMessage::PointerOutsideViewport { .. }) => { + (Self::Drawing, GradientToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) && let Some(selected_gradient) = &mut tool_data.selected_gradient @@ -480,7 +480,7 @@ impl Fsm for GradientToolFsmState { selected_gradient.transform.translation += shift; } - GradientToolFsmState::Drawing + Self::Drawing } (state, GradientToolMessage::PointerOutsideViewport { constrain_axis }) => { // Auto-panning @@ -492,7 +492,7 @@ impl Fsm for GradientToolFsmState { state } - (GradientToolFsmState::Drawing, GradientToolMessage::PointerUp) => { + (Self::Drawing, GradientToolMessage::PointerUp) => { input.mouse.finish_transaction(tool_data.drag_start, responses); tool_data.snap_manager.cleanup(responses); let was_dragging = tool_data.selected_gradient.is_some(); @@ -503,28 +503,28 @@ impl Fsm for GradientToolFsmState { { tool_data.selected_gradient = Some(SelectedGradient::new(gradient, selected_layer, document)); } - GradientToolFsmState::Ready + Self::Ready } - (GradientToolFsmState::Drawing, GradientToolMessage::Abort) => { + (Self::Drawing, GradientToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); tool_data.snap_manager.cleanup(responses); responses.add(OverlaysMessage::Draw); - GradientToolFsmState::Ready + Self::Ready } - (_, GradientToolMessage::Abort) => GradientToolFsmState::Ready, + (_, GradientToolMessage::Abort) => Self::Ready, _ => self, } } fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - GradientToolFsmState::Ready => HintData(vec![HintGroup(vec![ + Self::Ready => HintData(vec![HintGroup(vec![ HintInfo::mouse(MouseMotion::LmbDrag, "Draw Gradient"), HintInfo::keys([Key::Shift], "15° Increments").prepend_plus(), ])]), - GradientToolFsmState::Drawing => HintData(vec![ + Self::Drawing => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "15° Increments")]), ]), diff --git a/editor/src/messages/tool/tool_messages/navigate_tool.rs b/editor/src/messages/tool/tool_messages/navigate_tool.rs index 8809ccdebd..1c8e78bfba 100644 --- a/editor/src/messages/tool/tool_messages/navigate_tool.rs +++ b/editor/src/messages/tool/tool_messages/navigate_tool.rs @@ -99,7 +99,7 @@ impl Fsm for NavigateToolFsmState { let ToolMessage::Navigate(navigate) = message else { return self }; match navigate { NavigateToolMessage::PointerUp { zoom_in } => { - if self == NavigateToolFsmState::ZoomOrClickZooming { + if self == Self::ZoomOrClickZooming { // Mouse has not moved from pointerdown to pointerup if tool_data.drag_start == Some(input.mouse.position) { responses.add_front(if zoom_in { @@ -113,12 +113,12 @@ impl Fsm for NavigateToolFsmState { } tool_data.drag_start = None; - NavigateToolFsmState::Ready + Self::Ready } NavigateToolMessage::PointerMove { snap } => { - if self == NavigateToolFsmState::ZoomOrClickZooming { + if self == Self::ZoomOrClickZooming { responses.add_front(NavigationMessage::BeginCanvasZoom); - NavigateToolFsmState::Zooming + Self::Zooming } else { responses.add_front(NavigationMessage::PointerMove { snap }); self @@ -126,28 +126,28 @@ impl Fsm for NavigateToolFsmState { } NavigateToolMessage::TiltCanvasBegin => { responses.add_front(NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: false }); - NavigateToolFsmState::Tilting + Self::Tilting } NavigateToolMessage::ZoomCanvasBegin => { // Wait to decide between zooming and click zooming based on whether the next event is a PointerMove or PointerUp tool_data.drag_start = Some(input.mouse.position); - NavigateToolFsmState::ZoomOrClickZooming + Self::ZoomOrClickZooming } NavigateToolMessage::End => { tool_data.drag_start = None; - NavigateToolFsmState::Ready + Self::Ready } NavigateToolMessage::Abort => { responses.add_front(NavigationMessage::EndCanvasPTZ { abort_transform: false }); tool_data.drag_start = None; - NavigateToolFsmState::Ready + Self::Ready } } } fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - NavigateToolFsmState::Ready | NavigateToolFsmState::ZoomOrClickZooming => HintData(vec![ + Self::Ready | Self::ZoomOrClickZooming => HintData(vec![ HintGroup(vec![ HintInfo::mouse(MouseMotion::MmbDrag, ""), HintInfo::keys_and_mouse([Key::Space], MouseMotion::LmbDrag, "Pan").prepend_slash(), @@ -156,11 +156,11 @@ impl Fsm for NavigateToolFsmState { HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDrag, "Zoom"), HintInfo::keys([Key::Shift], "Increments").prepend_plus()]), HintGroup(vec![HintInfo::mouse(MouseMotion::Lmb, "Zoom In"), HintInfo::keys([Key::Shift], "Zoom Out").prepend_plus()]), ]), - NavigateToolFsmState::Tilting => HintData(vec![ + Self::Tilting => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "15° Increments")]), ]), - NavigateToolFsmState::Zooming => HintData(vec![ + Self::Zooming => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "Increments")]), ]), @@ -171,9 +171,9 @@ impl Fsm for NavigateToolFsmState { fn update_cursor(&self, responses: &mut VecDeque) { let cursor = match *self { - NavigateToolFsmState::Ready => MouseCursorIcon::ZoomIn, - NavigateToolFsmState::Tilting => MouseCursorIcon::Default, - NavigateToolFsmState::Zooming | NavigateToolFsmState::ZoomOrClickZooming => MouseCursorIcon::ZoomIn, + Self::Ready => MouseCursorIcon::ZoomIn, + Self::Tilting => MouseCursorIcon::Default, + Self::Zooming | Self::ZoomOrClickZooming => MouseCursorIcon::ZoomIn, }; responses.add(FrontendMessage::UpdateMouseCursor { cursor }); diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs index 35fd18e940..b558174c48 100644 --- a/editor/src/messages/tool/tool_messages/path_tool.rs +++ b/editor/src/messages/tool/tool_messages/path_tool.rs @@ -2034,7 +2034,7 @@ impl Fsm for PathToolFsmState { ) } ( - PathToolFsmState::Drawing { selection_shape }, + Self::Drawing { selection_shape }, PathToolMessage::PointerMove { equidistant, toggle_colinear, @@ -2084,10 +2084,10 @@ impl Fsm for PathToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - PathToolFsmState::Drawing { selection_shape } + Self::Drawing { selection_shape } } ( - PathToolFsmState::Dragging(_), + Self::Dragging(_), PathToolMessage::PointerMove { equidistant, toggle_colinear, @@ -2125,7 +2125,7 @@ impl Fsm for PathToolFsmState { tool_data.temporary_adjacent_handles_while_molding, ); - return PathToolFsmState::Dragging(tool_data.dragging_state); + return Self::Dragging(tool_data.dragging_state); } let anchor_and_handle_toggled = input.keyboard.get(move_anchor_with_handles as usize); @@ -2202,14 +2202,14 @@ impl Fsm for PathToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - PathToolFsmState::Dragging(tool_data.dragging_state) + Self::Dragging(tool_data.dragging_state) } - (PathToolFsmState::SlidingPoint, PathToolMessage::PointerMove { .. }) => { + (Self::SlidingPoint, PathToolMessage::PointerMove { .. }) => { tool_data.slide_point(input.mouse.position, responses, &document.network_interface, shape_editor); - PathToolFsmState::SlidingPoint + Self::SlidingPoint } ( - PathToolFsmState::Ready, + Self::Ready, PathToolMessage::PointerMove { delete_segment, segment_editing_modifier, @@ -2245,21 +2245,21 @@ impl Fsm for PathToolFsmState { self } - (PathToolFsmState::Drawing { selection_shape: selection_type }, PathToolMessage::PointerOutsideViewport { .. }) => { + (Self::Drawing { selection_shape: selection_type }, PathToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning if let Some(offset) = tool_data.auto_panning.shift_viewport(input, viewport, responses) { tool_data.drag_start_pos += offset; } - PathToolFsmState::Drawing { selection_shape: selection_type } + Self::Drawing { selection_shape: selection_type } } - (PathToolFsmState::Dragging(dragging_state), PathToolMessage::PointerOutsideViewport { .. }) => { + (Self::Dragging(dragging_state), PathToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning if let Some(offset) = tool_data.auto_panning.shift_viewport(input, viewport, responses) { tool_data.drag_start_pos += offset; } - PathToolFsmState::Dragging(dragging_state) + Self::Dragging(dragging_state) } ( state, @@ -2303,7 +2303,7 @@ impl Fsm for PathToolFsmState { state } - (PathToolFsmState::Drawing { selection_shape }, PathToolMessage::Enter { extend_selection, shrink_selection }) => { + (Self::Drawing { selection_shape }, PathToolMessage::Enter { extend_selection, shrink_selection }) => { let extend_selection = input.keyboard.get(extend_selection as usize); let shrink_selection = input.keyboard.get(shrink_selection as usize); @@ -2355,9 +2355,9 @@ impl Fsm for PathToolFsmState { responses.add(OverlaysMessage::Draw); - PathToolFsmState::Ready + Self::Ready } - (PathToolFsmState::Dragging { .. }, PathToolMessage::Escape | PathToolMessage::RightClick) => { + (Self::Dragging { .. }, PathToolMessage::Escape | PathToolMessage::RightClick) => { if tool_data.handle_drag_toggle && tool_data.drag_start_pos.distance(input.mouse.position) > DRAG_THRESHOLD { shape_editor.deselect_all_points(); shape_editor.deselect_all_segments(); @@ -2377,22 +2377,22 @@ impl Fsm for PathToolFsmState { tool_data.angle_locked = false; responses.add(DocumentMessage::AbortTransaction); tool_data.snap_manager.cleanup(responses); - PathToolFsmState::Ready + Self::Ready } - (PathToolFsmState::Drawing { .. }, PathToolMessage::Escape | PathToolMessage::RightClick) => { + (Self::Drawing { .. }, PathToolMessage::Escape | PathToolMessage::RightClick) => { tool_data.snap_manager.cleanup(responses); - PathToolFsmState::Ready + Self::Ready } - (PathToolFsmState::SlidingPoint, PathToolMessage::Escape | PathToolMessage::RightClick) => { + (Self::SlidingPoint, PathToolMessage::Escape | PathToolMessage::RightClick) => { tool_data.sliding_point_info = None; responses.add(DocumentMessage::AbortTransaction); tool_data.snap_manager.cleanup(responses); - PathToolFsmState::Ready + Self::Ready } // Mouse up - (PathToolFsmState::Drawing { selection_shape }, PathToolMessage::DragStop { extend_selection, shrink_selection }) => { + (Self::Drawing { selection_shape }, PathToolMessage::DragStop { extend_selection, shrink_selection }) => { let extend_selection = input.keyboard.get(extend_selection as usize); let shrink_selection = input.keyboard.get(shrink_selection as usize); @@ -2452,7 +2452,7 @@ impl Fsm for PathToolFsmState { responses.add(OverlaysMessage::Draw); responses.add(PathToolMessage::SelectedPointUpdated); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::DragStop { extend_selection, .. }) => { tool_data.ghost_outline.clear(); @@ -2500,7 +2500,7 @@ impl Fsm for PathToolFsmState { if segment_dissolved || point_inserted { responses.add(DocumentMessage::EndTransaction); - return PathToolFsmState::Ready; + return Self::Ready; } } @@ -2632,7 +2632,7 @@ impl Fsm for PathToolFsmState { tool_data.snap_manager.cleanup(responses); tool_data.opposite_handle_position = None; - PathToolFsmState::Ready + Self::Ready } // Delete key @@ -2650,15 +2650,15 @@ impl Fsm for PathToolFsmState { } responses.add(PathToolMessage::SelectionChanged); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::BreakPath) => { shape_editor.break_path_at_selected_point(document, responses); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::DeleteAndBreakPath) => { shape_editor.delete_point_and_break_path(document, responses); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::ClosePath) => { responses.add(DocumentMessage::AddTransaction); @@ -2671,11 +2671,7 @@ impl Fsm for PathToolFsmState { } (_, PathToolMessage::StartSlidingPoint) => { responses.add(DocumentMessage::StartTransaction); - if tool_data.start_sliding_point(shape_editor, document) { - PathToolFsmState::SlidingPoint - } else { - PathToolFsmState::Ready - } + if tool_data.start_sliding_point(shape_editor, document) { Self::SlidingPoint } else { Self::Ready } } (_, PathToolMessage::Copy { clipboard }) => { // TODO: Add support for selected segments @@ -2721,7 +2717,7 @@ impl Fsm for PathToolFsmState { if both_ends_selected || segment_selected { let Some((start_index, end_index)) = find_index(start).zip(find_index(end)) else { error!("Point does not exist in point domain"); - return PathToolFsmState::Ready; + return Self::Ready; }; new_vector.segment_domain.push(segment_id, start_index, end_index, bezier.handles, *stroke); } @@ -2747,14 +2743,14 @@ impl Fsm for PathToolFsmState { } // TODO: Add implementation for internal clipboard - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::Cut { clipboard }) => { responses.add(PathToolMessage::Copy { clipboard }); // Delete the selected points/segments responses.add(PathToolMessage::DeleteSelected); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::Paste { data }) => { // Deserialize the data @@ -2865,14 +2861,14 @@ impl Fsm for PathToolFsmState { } } - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::DeleteSelected) => { // Delete the selected points and segments let deleted_some_point = shape_editor.delete_point_and_break_path(document, responses); shape_editor.delete_selected_segments(document, responses, !deleted_some_point); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::Duplicate) => { responses.add(DocumentMessage::AddTransaction); @@ -2964,7 +2960,7 @@ impl Fsm for PathToolFsmState { } } - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::DoubleClick { extend_selection, shrink_selection }) => { // Double-clicked on a point (flip smooth/sharp behavior) @@ -2998,7 +2994,7 @@ impl Fsm for PathToolFsmState { }); } - return PathToolFsmState::Ready; + return Self::Ready; } // Double-clicked on a filled region else if let Some(layer) = &get_drill_through_layer() { @@ -3065,11 +3061,11 @@ impl Fsm for PathToolFsmState { responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] }); } - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::Abort) => { responses.add(OverlaysMessage::Draw); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::NudgeSelectedPoints { delta_x, delta_y }) => { shape_editor.move_selected_points_and_segments( @@ -3084,7 +3080,7 @@ impl Fsm for PathToolFsmState { responses, ); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::SelectAll) => { shape_editor.select_all_anchors_in_selected_layers(document); @@ -3100,7 +3096,7 @@ impl Fsm for PathToolFsmState { } responses.add(OverlaysMessage::Draw); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::DeselectAllSelected) => { shape_editor.deselect_all_points(); @@ -3108,19 +3104,19 @@ impl Fsm for PathToolFsmState { responses.add(OverlaysMessage::Draw); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::SelectedPointXChanged { new_x }) => { if let Some(&SingleSelectedPoint { coordinates, id, layer, .. }) = tool_data.selection_status.as_one() { shape_editor.reposition_control_point(&id, &document.network_interface, DVec2::new(new_x, coordinates.y), layer, responses); } - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::SelectedPointYChanged { new_y }) => { if let Some(&SingleSelectedPoint { coordinates, id, layer, .. }) = tool_data.selection_status.as_one() { shape_editor.reposition_control_point(&id, &document.network_interface, DVec2::new(coordinates.x, new_y), layer, responses); } - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::SelectedPointUpdated) => { let colinear = shape_editor.selected_manipulator_angles(&document.network_interface); @@ -3144,13 +3140,13 @@ impl Fsm for PathToolFsmState { shape_editor.convert_selected_manipulators_to_colinear_handles(responses, document); responses.add(DocumentMessage::EndTransaction); responses.add(PathToolMessage::SelectionChanged); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::ManipulatorMakeHandlesFree) => { responses.add(DocumentMessage::StartTransaction); shape_editor.disable_colinear_handles_state_on_selected(&document.network_interface, responses); responses.add(DocumentMessage::EndTransaction); - PathToolFsmState::Ready + Self::Ready } (_, PathToolMessage::SetPivot { position }) => { responses.add(DocumentMessage::StartTransaction); @@ -3164,7 +3160,7 @@ impl Fsm for PathToolFsmState { self } - (_, _) => PathToolFsmState::Ready, + (_, _) => Self::Ready, } } @@ -3188,7 +3184,7 @@ enum SelectionStatus { impl SelectionStatus { fn as_one(&self) -> Option<&SingleSelectedPoint> { match self { - SelectionStatus::One(one) => Some(one), + Self::One(one) => Some(one), _ => None, } } diff --git a/editor/src/messages/tool/tool_messages/pen_tool.rs b/editor/src/messages/tool/tool_messages/pen_tool.rs index ec379844c6..bdb3eeaade 100644 --- a/editor/src/messages/tool/tool_messages/pen_tool.rs +++ b/editor/src/messages/tool/tool_messages/pen_tool.rs @@ -1471,12 +1471,12 @@ impl Fsm for PenToolFsmState { let ToolMessage::Pen(event) = event else { return self }; match (self, event) { - (PenToolFsmState::PlacingAnchor | PenToolFsmState::GRSHandle, PenToolMessage::GRS { grab, rotate, scale }) => { - let Some(layer) = layer else { return PenToolFsmState::PlacingAnchor }; + (Self::PlacingAnchor | Self::GRSHandle, PenToolMessage::GRS { grab, rotate, scale }) => { + let Some(layer) = layer else { return Self::PlacingAnchor }; - let Some(latest) = tool_data.latest_point() else { return PenToolFsmState::PlacingAnchor }; + let Some(latest) = tool_data.latest_point() else { return Self::PlacingAnchor }; if latest.handle_start == latest.pos { - return PenToolFsmState::PlacingAnchor; + return Self::PlacingAnchor; } let latest_pos = latest.pos; @@ -1500,18 +1500,18 @@ impl Fsm for PenToolFsmState { tool_data.previous_handle_end_pos = tool_data.target_handle_position(opposite_handle, &vector); let handle1 = latest_handle_start - latest_pos; let Some(opposite_handle_pos) = tool_data.target_handle_position(opposite_handle, &vector) else { - return PenToolFsmState::GRSHandle; + return Self::GRSHandle; }; let handle2 = opposite_handle_pos - latest_pos; let pi = std::f64::consts::PI; let angle = handle1.angle_to(handle2); tool_data.colinear = (angle - pi).abs() < 1e-6 || (angle + pi).abs() < 1e-6; - PenToolFsmState::GRSHandle + Self::GRSHandle } - (PenToolFsmState::GRSHandle, PenToolMessage::FinalPosition { final_position }) => { - let Some(layer) = layer else { return PenToolFsmState::GRSHandle }; + (Self::GRSHandle, PenToolMessage::FinalPosition { final_position }) => { + let Some(layer) = layer else { return Self::GRSHandle }; let vector = document.network_interface.compute_modified_vector(layer); - let Some(vector) = vector else { return PenToolFsmState::GRSHandle }; + let Some(vector) = vector else { return Self::GRSHandle }; if let Some(latest_pt) = tool_data.latest_point_mut() { let layer_space_to_viewport = document.metadata().transform_to_viewport(layer); @@ -1521,20 +1521,20 @@ impl Fsm for PenToolFsmState { responses.add(OverlaysMessage::Draw); let Some(latest) = tool_data.latest_point() else { - return PenToolFsmState::GRSHandle; + return Self::GRSHandle; }; let opposite_handle = tool_data.check_grs_end_handle(&vector); let Some(opposite_handle_pos) = tool_data.target_handle_position(opposite_handle, &vector) else { - return PenToolFsmState::GRSHandle; + return Self::GRSHandle; }; if tool_data.colinear { let Some(direction) = (latest.pos - latest.handle_start).try_normalize() else { - return PenToolFsmState::GRSHandle; + return Self::GRSHandle; }; if (latest.pos - latest.handle_start).length_squared() < f64::EPSILON { - return PenToolFsmState::GRSHandle; + return Self::GRSHandle; } let relative_distance = (opposite_handle_pos - latest.pos).length(); let relative_position = relative_distance * direction + latest.pos; @@ -1543,9 +1543,9 @@ impl Fsm for PenToolFsmState { responses.add(OverlaysMessage::Draw); - PenToolFsmState::GRSHandle + Self::GRSHandle } - (PenToolFsmState::GRSHandle, PenToolMessage::Confirm) => { + (Self::GRSHandle, PenToolMessage::Confirm) => { tool_data.next_point = input.mouse.position; tool_data.next_handle_start = input.mouse.position; @@ -1558,13 +1558,13 @@ impl Fsm for PenToolFsmState { move_anchor_with_handles: Key::Space, }); - PenToolFsmState::PlacingAnchor + Self::PlacingAnchor } - (PenToolFsmState::GRSHandle, PenToolMessage::Abort) => { + (Self::GRSHandle, PenToolMessage::Abort) => { tool_data.next_point = input.mouse.position; tool_data.next_handle_start = input.mouse.position; - let Some(layer) = layer else { return PenToolFsmState::GRSHandle }; + let Some(layer) = layer else { return Self::GRSHandle }; let vector = document.network_interface.compute_modified_vector(layer).unwrap(); let opposite_handle = tool_data.check_grs_end_handle(&vector); @@ -1572,7 +1572,7 @@ impl Fsm for PenToolFsmState { if let Some(latest) = tool_data.latest_point_mut() { latest.handle_start = previous; } else { - return PenToolFsmState::PlacingAnchor; + return Self::PlacingAnchor; } responses.add(OverlaysMessage::Draw); @@ -1585,17 +1585,17 @@ impl Fsm for PenToolFsmState { }); let Some((previous_pos, latest)) = tool_data.previous_handle_end_pos.zip(tool_data.latest_point()) else { - return PenToolFsmState::PlacingAnchor; + return Self::PlacingAnchor; }; tool_data.update_target_handle_pos(opposite_handle, latest.pos, responses, previous_pos, layer); - PenToolFsmState::PlacingAnchor + Self::PlacingAnchor } (_, PenToolMessage::SelectionChanged) => { responses.add(OverlaysMessage::Draw); self } - (PenToolFsmState::Ready, PenToolMessage::Overlays { context: mut overlay_context }) => { + (Self::Ready, PenToolMessage::Overlays { context: mut overlay_context }) => { match tool_options.pen_overlay_mode { PenOverlayMode::AllHandles => { path_overlays(document, DrawHandles::All, shape_editor, &mut overlay_context); @@ -1685,17 +1685,17 @@ impl Fsm for PenToolFsmState { overlay_context.line(next_anchor, handle_end, None, None); } - if self == PenToolFsmState::PlacingAnchor && anchor_start != handle_start && tool_data.modifiers.lock_angle { + if self == Self::PlacingAnchor && anchor_start != handle_start && tool_data.modifiers.lock_angle { // Draw the line between the currently-being-placed anchor and last-placed point (lock angle bent overlays) overlay_context.dashed_line(anchor_start, next_anchor, None, None, Some(4.), Some(4.), Some(0.5)); } // Draw the line between the currently-being-placed anchor and last-placed point (snap angle bent overlays) - if self == PenToolFsmState::PlacingAnchor && anchor_start != handle_start && tool_data.modifiers.snap_angle { + if self == Self::PlacingAnchor && anchor_start != handle_start && tool_data.modifiers.snap_angle { overlay_context.dashed_line(anchor_start, next_anchor, None, None, Some(4.), Some(4.), Some(0.5)); } - if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) && valid(next_anchor, handle_end) && display_handles { + if self == Self::DraggingHandle(tool_data.handle_mode) && valid(next_anchor, handle_end) && display_handles { // Draw the handle circle for the currently-being-dragged-out incoming handle (opposite the one currently being dragged out) let selected = tool_data.handle_type == TargetHandle::PreviewInHandle; if display_handles { @@ -1720,18 +1720,18 @@ impl Fsm for PenToolFsmState { } } - if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) && valid(next_anchor, next_handle_start) && display_handles { + if self == Self::DraggingHandle(tool_data.handle_mode) && valid(next_anchor, next_handle_start) && display_handles { // Draw the handle circle for the currently-being-dragged-out outgoing handle (the one currently being dragged out, under the user's cursor) let selected = tool_data.handle_type == TargetHandle::FuturePreviewOutHandle; overlay_context.manipulator_handle(next_handle_start, selected, None); } - if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) && display_anchors { + if self == Self::DraggingHandle(tool_data.handle_mode) && display_anchors { // Draw the anchor square for the most recently placed anchor overlay_context.manipulator_anchor(next_anchor, false, None); } - if self == PenToolFsmState::PlacingAnchor { + if self == Self::PlacingAnchor { let tolerance = crate::consts::SNAP_POINT_TOLERANCE; let point = SnapCandidatePoint::handle(document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position)); let snapped = tool_data.snap_manager.free_snap(&SnapData::new(document, input, viewport), &point, SnapTypeConfiguration::default()); @@ -1804,7 +1804,7 @@ impl Fsm for PenToolFsmState { }); self } - (PenToolFsmState::Ready, PenToolMessage::DragStart { append_to_selected }) => { + (Self::Ready, PenToolMessage::DragStart { append_to_selected }) => { responses.add(DocumentMessage::StartTransaction); tool_data.handle_mode = HandleMode::Free; @@ -1815,7 +1815,7 @@ impl Fsm for PenToolFsmState { tool_data.create_initial_point(document, input, viewport, responses, tool_options, append, shape_editor); // Enter the dragging handle state while the mouse is held down, allowing the user to move the mouse and position the handle - PenToolFsmState::DraggingHandle(tool_data.handle_mode) + Self::DraggingHandle(tool_data.handle_mode) } (_, PenToolMessage::AddPointLayerPosition { layer, viewport }) => { tool_data.add_point_layer_position(document, responses, layer, viewport); @@ -1826,7 +1826,7 @@ impl Fsm for PenToolFsmState { tool_data.recalculate_latest_points_position(document); state } - (PenToolFsmState::PlacingAnchor, PenToolMessage::DragStart { append_to_selected }) => { + (Self::PlacingAnchor, PenToolMessage::DragStart { append_to_selected }) => { let point = SnapCandidatePoint::handle(document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position)); let snapped = tool_data.snap_manager.free_snap(&SnapData::new(document, input, viewport), &point, SnapTypeConfiguration::default()); let viewport_vec = document.metadata().document_to_viewport.transform_point2(snapped.snapped_point_document); @@ -1840,7 +1840,7 @@ impl Fsm for PenToolFsmState { tool_data.place_anchor(SnapData::new(document, input, viewport), transform, input.mouse.position, responses); } tool_data.buffering_merged_vector = false; - PenToolFsmState::DraggingHandle(tool_data.handle_mode) + Self::DraggingHandle(tool_data.handle_mode) } else { if tool_data.handle_end.is_some() { responses.add(DocumentMessage::StartTransaction); @@ -1867,10 +1867,10 @@ impl Fsm for PenToolFsmState { // Even if no buffer was started, the message still has to be run again in order to call bend_from_previous_point tool_data.buffering_merged_vector = true; responses.add(PenToolMessage::DragStart { append_to_selected }); - PenToolFsmState::PlacingAnchor + Self::PlacingAnchor } } - (PenToolFsmState::PlacingAnchor, PenToolMessage::RemovePreviousHandle) => { + (Self::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); @@ -1879,14 +1879,14 @@ impl Fsm for PenToolFsmState { } self } - (PenToolFsmState::DraggingHandle(_), PenToolMessage::DragStop) => { + (Self::DraggingHandle(_), PenToolMessage::DragStop) => { tool_data.cleanup_target_selections(shape_editor, layer, document, responses); tool_data .finish_placing_handle(SnapData::new(document, input, viewport), transform, responses) - .unwrap_or(PenToolFsmState::PlacingAnchor) + .unwrap_or(Self::PlacingAnchor) } ( - PenToolFsmState::DraggingHandle(_), + Self::DraggingHandle(_), PenToolMessage::PointerMove { snap_angle, break_handle, @@ -1952,7 +1952,7 @@ impl Fsm for PenToolFsmState { let state = tool_data .drag_handle(snap_data, transform, input.mouse.position, responses, layer, input, viewport) - .unwrap_or(PenToolFsmState::Ready); + .unwrap_or(Self::Ready); if tool_data.handle_swapped { responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::None }); @@ -1982,7 +1982,7 @@ impl Fsm for PenToolFsmState { state } ( - PenToolFsmState::PlacingAnchor, + Self::PlacingAnchor, PenToolMessage::PointerMove { snap_angle, break_handle, @@ -2002,7 +2002,7 @@ impl Fsm for PenToolFsmState { }; let state = tool_data .place_anchor(SnapData::new(document, input, viewport), transform, input.mouse.position, responses) - .unwrap_or(PenToolFsmState::Ready); + .unwrap_or(Self::Ready); // Auto-panning let messages = [ @@ -2027,7 +2027,7 @@ impl Fsm for PenToolFsmState { state } - (PenToolFsmState::DraggingHandle(_), PenToolMessage::SwapHandles) => { + (Self::DraggingHandle(_), PenToolMessage::SwapHandles) => { if !tool_data.handle_swapped { tool_data.handle_swapped = true } @@ -2036,7 +2036,7 @@ impl Fsm for PenToolFsmState { self } ( - PenToolFsmState::Ready, + Self::Ready, PenToolMessage::PointerMove { snap_angle, break_handle, @@ -2056,20 +2056,20 @@ impl Fsm for PenToolFsmState { responses.add(OverlaysMessage::Draw); self } - (PenToolFsmState::DraggingHandle(mode), PenToolMessage::PointerOutsideViewport { .. }) => { + (Self::DraggingHandle(mode), PenToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses); - PenToolFsmState::DraggingHandle(mode) + Self::DraggingHandle(mode) } - (PenToolFsmState::PlacingAnchor, PenToolMessage::PointerOutsideViewport { .. }) => { + (Self::PlacingAnchor, PenToolMessage::PointerOutsideViewport { .. }) => { if !input.mouse.mouse_keys.contains(MouseKeys::LEFT) { return self; } // Auto-panning let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses); - PenToolFsmState::PlacingAnchor + Self::PlacingAnchor } ( state, @@ -2104,7 +2104,7 @@ impl Fsm for PenToolFsmState { state } - (PenToolFsmState::DraggingHandle(..), PenToolMessage::Confirm) => { + (Self::DraggingHandle(..), PenToolMessage::Confirm) => { // Confirm to end path if let Some((vector, layer)) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)).zip(layer) { let single_point_in_layer = vector.point_domain.ids().len() == 1; @@ -2137,29 +2137,29 @@ impl Fsm for PenToolFsmState { responses.add(OverlaysMessage::Draw); - PenToolFsmState::Ready + Self::Ready } - (PenToolFsmState::PlacingAnchor, PenToolMessage::Confirm) => { + (Self::PlacingAnchor, PenToolMessage::Confirm) => { responses.add(DocumentMessage::EndTransaction); tool_data.cleanup(responses); tool_data.cleanup_target_selections(shape_editor, layer, document, responses); - PenToolFsmState::Ready + Self::Ready } - (PenToolFsmState::DraggingHandle(..), PenToolMessage::Abort) => { + (Self::DraggingHandle(..), PenToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); if tool_data.handle_end.is_none() { tool_data.cleanup(responses); tool_data.cleanup_target_selections(shape_editor, layer, document, responses); - PenToolFsmState::Ready + Self::Ready } else { tool_data .place_anchor(SnapData::new(document, input, viewport), transform, input.mouse.position, responses) - .unwrap_or(PenToolFsmState::Ready) + .unwrap_or(Self::Ready) } } - (PenToolFsmState::PlacingAnchor, PenToolMessage::Abort) => { + (Self::PlacingAnchor, PenToolMessage::Abort) => { let should_delete_layer = if let Some(vector) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)) { vector.point_domain.ids().len() == 1 } else { @@ -2179,15 +2179,15 @@ impl Fsm for PenToolFsmState { } responses.add(OverlaysMessage::Draw); - PenToolFsmState::Ready + Self::Ready } - (_, PenToolMessage::Abort) => PenToolFsmState::Ready, - (PenToolFsmState::DraggingHandle(..) | PenToolFsmState::PlacingAnchor, PenToolMessage::Undo) => { + (_, PenToolMessage::Abort) => Self::Ready, + (Self::DraggingHandle(..) | Self::PlacingAnchor, PenToolMessage::Undo) => { if tool_data.point_index > 0 { tool_data.point_index -= 1; tool_data .place_anchor(SnapData::new(document, input, viewport), transform, input.mouse.position, responses) - .unwrap_or(PenToolFsmState::PlacingAnchor) + .unwrap_or(Self::PlacingAnchor) } else { responses.add(PenToolMessage::Abort); self @@ -2197,8 +2197,8 @@ impl Fsm for PenToolFsmState { tool_data.point_index = (tool_data.point_index + 1).min(tool_data.latest_points.len().saturating_sub(1)); tool_data.place_anchor(SnapData::new(document, input, viewport), transform, input.mouse.position, responses); match tool_data.point_index { - 0 => PenToolFsmState::Ready, - _ => PenToolFsmState::PlacingAnchor, + 0 => Self::Ready, + _ => Self::PlacingAnchor, } } _ => self, @@ -2207,12 +2207,12 @@ impl Fsm for PenToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - PenToolFsmState::Ready | PenToolFsmState::GRSHandle => HintData(vec![HintGroup(vec![ + Self::Ready | Self::GRSHandle => HintData(vec![HintGroup(vec![ HintInfo::mouse(MouseMotion::Lmb, "Draw Path"), // TODO: Only show this if a single layer is selected and it's of a valid type (e.g. a vector path but not raster or artboard) HintInfo::keys([Key::Shift], "Append to Selected Layer").prepend_plus(), ])]), - PenToolFsmState::PlacingAnchor => HintData(vec![ + Self::PlacingAnchor => HintData(vec![ HintGroup(vec![ HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "").prepend_slash(), @@ -2226,7 +2226,7 @@ impl Fsm for PenToolFsmState { HintInfo::keys([Key::Control], "Lock Angle").prepend_plus(), ]), ]), - PenToolFsmState::DraggingHandle(mode) => { + Self::DraggingHandle(mode) => { let mut dragging_hint_data = HintData(Vec::new()); dragging_hint_data.0.push(HintGroup(vec![ HintInfo::mouse(MouseMotion::Rmb, ""), diff --git a/editor/src/messages/tool/tool_messages/select_tool.rs b/editor/src/messages/tool/tool_messages/select_tool.rs index 717903ab10..0acc1277a9 100644 --- a/editor/src/messages/tool/tool_messages/select_tool.rs +++ b/editor/src/messages/tool/tool_messages/select_tool.rs @@ -59,8 +59,8 @@ pub enum NestedSelectionBehavior { impl fmt::Display for NestedSelectionBehavior { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - NestedSelectionBehavior::Deepest => write!(f, "Deep Select"), - NestedSelectionBehavior::Shallowest => write!(f, "Shallow Select"), + Self::Deepest => write!(f, "Deep Select"), + Self::Shallowest => write!(f, "Shallow Select"), } } } @@ -370,7 +370,7 @@ enum SelectToolFsmState { impl Default for SelectToolFsmState { fn default() -> Self { let selection = NestedSelectionBehavior::Deepest; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } } @@ -747,7 +747,7 @@ impl Fsm for SelectToolFsmState { let mouse_position = input.mouse.position; let compass_rose_state = tool_data.compass_rose.compass_rose_state(mouse_position, angle); - let show_hover_ring = if let SelectToolFsmState::Dragging { axis, using_compass, .. } = self { + let show_hover_ring = if let Self::Dragging { axis, using_compass, .. } = self { using_compass && !axis.is_constraint() } else { compass_rose_state.is_ring() @@ -765,13 +765,13 @@ impl Fsm for SelectToolFsmState { .map(|bounding_box| bounding_box.check_rotate(input.mouse.position)) .unwrap_or_default(); - let is_resizing_or_rotating = matches!(self, SelectToolFsmState::ResizingBounds | SelectToolFsmState::SkewingBounds { .. } | SelectToolFsmState::RotatingBounds); + let is_resizing_or_rotating = matches!(self, Self::ResizingBounds | Self::SkewingBounds { .. } | Self::RotatingBounds); if overlay_context.visibility_settings.transform_cage() && let Some(bounds) = tool_data.bounding_box_manager.as_mut() { let edges = bounds.check_selected_edges(input.mouse.position); - let is_skewing = matches!(self, SelectToolFsmState::SkewingBounds { .. }); + let is_skewing = matches!(self, Self::SkewingBounds { .. }); let is_near_square = edges.is_some_and(|hover_edge| bounds.over_extended_edge_midpoint(input.mouse.position, hover_edge)); if is_skewing || (dragging_bounds && is_near_square && !is_resizing_or_rotating) { bounds.render_skew_gizmos(&mut overlay_context, tool_data.skew_edge); @@ -784,14 +784,14 @@ impl Fsm for SelectToolFsmState { } let might_resize_or_rotate = dragging_bounds || rotating_bounds; - let can_get_into_other_states = might_resize_or_rotate && !matches!(self, SelectToolFsmState::Dragging { .. }); + let can_get_into_other_states = might_resize_or_rotate && !matches!(self, Self::Dragging { .. }); let show_compass = !(can_get_into_other_states || is_resizing_or_rotating); let show_compass_with_ring = bounds.map(|bounds| transform * Quad::from_box(bounds)).and_then(|quad| { const MIN_ARROWS_TO_RESIZE_HANDLE_DISTANCE: f64 = 4.; (show_compass && quad.all_sides_at_least_width(COMPASS_ROSE_HOVER_RING_DIAMETER + RESIZE_HANDLE_SIZE + MIN_ARROWS_TO_RESIZE_HANDLE_DISTANCE)) .then_some( - matches!(self, SelectToolFsmState::Dragging { .. }) + matches!(self, Self::Dragging { .. }) .then_some(show_hover_ring) .or((quad.contains(mouse_position)).then_some(show_hover_ring)), ) @@ -872,7 +872,7 @@ impl Fsm for SelectToolFsmState { overlay_context.compass_rose(compass_center, angle, show_compass_with_ring); - let axis_state = if let SelectToolFsmState::Dragging { axis, .. } = self { + let axis_state = if let Self::Dragging { axis, .. } = self { Some((axis, false)) } else { compass_rose_state.axis_type().and_then(|axis| axis.is_constraint().then_some((axis, true))) @@ -1012,7 +1012,7 @@ impl Fsm for SelectToolFsmState { self } ( - SelectToolFsmState::Ready { .. }, + Self::Ready { .. }, SelectToolMessage::DragStart { extend_selection, remove_from_selection, @@ -1062,10 +1062,10 @@ impl Fsm for SelectToolFsmState { // Dragging one (or two, forming a corner) of the transform cage bounding box edges else if resize { tool_data.get_snap_candidates(document, input, viewport); - SelectToolFsmState::ResizingBounds + Self::ResizingBounds } else if skew { tool_data.get_snap_candidates(document, input, viewport); - SelectToolFsmState::SkewingBounds { skew: Key::Control } + Self::SkewingBounds { skew: Key::Control } } // Dragging the selected layers around to transform them else if can_grab_compass_rose || intersection.is_some_and(|intersection| selected.iter().any(|selected_layer| intersection.starts_with(*selected_layer, document.metadata()))) { @@ -1086,7 +1086,7 @@ impl Fsm for SelectToolFsmState { tool_data.pivot_gizmo_start = Some(tool_data.drag_current); - SelectToolFsmState::Dragging { + Self::Dragging { axis, using_compass, has_dragged: false, @@ -1096,7 +1096,7 @@ impl Fsm for SelectToolFsmState { } // Dragging near the transform cage bounding box to rotate it else if rotate { - SelectToolFsmState::RotatingBounds + Self::RotatingBounds } // Dragging a selection box else { @@ -1127,7 +1127,7 @@ impl Fsm for SelectToolFsmState { tool_data.pivot_gizmo_start = Some(tool_data.drag_current); - SelectToolFsmState::Dragging { + Self::Dragging { axis: Axis::None, using_compass: false, has_dragged: false, @@ -1136,21 +1136,21 @@ impl Fsm for SelectToolFsmState { } } else { let selection_shape = if input.keyboard.key(lasso_select) { SelectionShapeType::Lasso } else { SelectionShapeType::Box }; - SelectToolFsmState::Drawing { selection_shape, has_drawn: false } + Self::Drawing { selection_shape, has_drawn: false } } }; tool_data.non_duplicated_layers = None; state } - (SelectToolFsmState::DraggingPivot, SelectToolMessage::Abort) => { + (Self::DraggingPivot, SelectToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); let selection = tool_data.nested_selection_behavior; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } ( - SelectToolFsmState::Dragging { + Self::Dragging { axis, using_compass, has_dragged, @@ -1207,7 +1207,7 @@ impl Fsm for SelectToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - SelectToolFsmState::Dragging { + Self::Dragging { axis, using_compass, has_dragged: true, @@ -1215,7 +1215,7 @@ impl Fsm for SelectToolFsmState { remove, } } - (SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => { + (Self::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => { if let Some(bounds) = &mut tool_data.bounding_box_manager { resize_bounds( document, @@ -1236,9 +1236,9 @@ impl Fsm for SelectToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); } - SelectToolFsmState::ResizingBounds + Self::ResizingBounds } - (SelectToolFsmState::SkewingBounds { skew }, SelectToolMessage::PointerMove { .. }) => { + (Self::SkewingBounds { skew }, SelectToolMessage::PointerMove { .. }) => { if let Some(bounds) = &mut tool_data.bounding_box_manager { skew_bounds( document, @@ -1250,9 +1250,9 @@ impl Fsm for SelectToolFsmState { ToolType::Select, ); } - SelectToolFsmState::SkewingBounds { skew } + Self::SkewingBounds { skew } } - (SelectToolFsmState::RotatingBounds, SelectToolMessage::PointerMove { .. }) => { + (Self::RotatingBounds, SelectToolMessage::PointerMove { .. }) => { if let Some(bounds) = &mut tool_data.bounding_box_manager { rotate_bounds( document, @@ -1266,9 +1266,9 @@ impl Fsm for SelectToolFsmState { ); } - SelectToolFsmState::RotatingBounds + Self::RotatingBounds } - (SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerMove { modifier_keys }) => { + (Self::DraggingPivot, SelectToolMessage::PointerMove { modifier_keys }) => { let mouse_position = input.mouse.position; let snapped_mouse_position = mouse_position; @@ -1283,9 +1283,9 @@ impl Fsm for SelectToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - SelectToolFsmState::DraggingPivot + Self::DraggingPivot } - (SelectToolFsmState::Drawing { selection_shape, has_drawn }, SelectToolMessage::PointerMove { modifier_keys }) => { + (Self::Drawing { selection_shape, has_drawn }, SelectToolMessage::PointerMove { modifier_keys }) => { if !has_drawn { responses.add(ToolMessage::UpdateHints); } @@ -1304,9 +1304,9 @@ impl Fsm for SelectToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - SelectToolFsmState::Drawing { selection_shape, has_drawn: true } + Self::Drawing { selection_shape, has_drawn: true } } - (SelectToolFsmState::Ready { .. }, SelectToolMessage::PointerMove { .. }) => { + (Self::Ready { .. }, SelectToolMessage::PointerMove { .. }) => { let dragging_bounds = tool_data .bounding_box_manager .as_mut() @@ -1332,10 +1332,10 @@ impl Fsm for SelectToolFsmState { } let selection = tool_data.nested_selection_behavior; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } ( - SelectToolFsmState::Dragging { + Self::Dragging { axis, using_compass, has_dragged, @@ -1350,7 +1350,7 @@ impl Fsm for SelectToolFsmState { tool_data.drag_start += shift; } - SelectToolFsmState::Dragging { + Self::Dragging { axis, using_compass, has_dragged, @@ -1358,7 +1358,7 @@ impl Fsm for SelectToolFsmState { remove, } } - (SelectToolFsmState::ResizingBounds | SelectToolFsmState::SkewingBounds { .. }, SelectToolMessage::PointerOutsideViewport { .. }) => { + (Self::ResizingBounds | Self::SkewingBounds { .. }, SelectToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) && let Some(bounds) = &mut tool_data.bounding_box_manager @@ -1369,13 +1369,13 @@ impl Fsm for SelectToolFsmState { self } - (SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => { + (Self::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses); self } - (SelectToolFsmState::Drawing { .. }, SelectToolMessage::PointerOutsideViewport { .. }) => { + (Self::Drawing { .. }, SelectToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) { tool_data.drag_start += shift; @@ -1393,7 +1393,7 @@ impl Fsm for SelectToolFsmState { state } - (SelectToolFsmState::Dragging { has_dragged, remove, deepest, .. }, SelectToolMessage::DragStop { remove_from_selection }) => { + (Self::Dragging { has_dragged, remove, deepest, .. }, SelectToolMessage::DragStop { remove_from_selection }) => { // Deselect layer if not snap dragging responses.add(DocumentMessage::EndTransaction); tool_data.axis_align = false; @@ -1473,12 +1473,9 @@ impl Fsm for SelectToolFsmState { responses.add(TransformLayerMessage::SetPivotGizmo { pivot_gizmo }); let selection = tool_data.nested_selection_behavior; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } - ( - SelectToolFsmState::ResizingBounds | SelectToolFsmState::SkewingBounds { .. } | SelectToolFsmState::RotatingBounds | SelectToolFsmState::DraggingPivot, - SelectToolMessage::DragStop { .. } | SelectToolMessage::Enter, - ) => { + (Self::ResizingBounds | Self::SkewingBounds { .. } | Self::RotatingBounds | Self::DraggingPivot, SelectToolMessage::DragStop { .. } | SelectToolMessage::Enter) => { let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON; let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction }; @@ -1490,16 +1487,16 @@ impl Fsm for SelectToolFsmState { tool_data.axis_align = false; tool_data.snap_manager.cleanup(responses); - if !matches!(self, SelectToolFsmState::DraggingPivot) + if !matches!(self, Self::DraggingPivot) && let Some(bounds) = &mut tool_data.bounding_box_manager { bounds.original_transforms.clear(); } let selection = tool_data.nested_selection_behavior; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } - (SelectToolFsmState::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => { + (Self::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => { let quad = tool_data.selection_quad(); let selection_mode = match tool_action_data.preferences.get_selection_mode() { @@ -1571,9 +1568,9 @@ impl Fsm for SelectToolFsmState { responses.add(OverlaysMessage::Draw); let selection = tool_data.nested_selection_behavior; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } - (SelectToolFsmState::Ready { .. }, SelectToolMessage::Enter) => { + (Self::Ready { .. }, SelectToolMessage::Enter) => { let selected_nodes = document.network_interface.selected_nodes(); let mut selected_layers = selected_nodes.selected_layers(document.metadata()); @@ -1586,9 +1583,9 @@ impl Fsm for SelectToolFsmState { } let selection = tool_data.nested_selection_behavior; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } - (SelectToolFsmState::Dragging { .. }, SelectToolMessage::Abort) => { + (Self::Dragging { .. }, SelectToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); tool_data.snap_manager.cleanup(responses); tool_data.axis_align = false; @@ -1596,7 +1593,7 @@ impl Fsm for SelectToolFsmState { responses.add(OverlaysMessage::Draw); let selection = tool_data.nested_selection_behavior; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } (_, SelectToolMessage::Abort) => { tool_data.layers_dragging.retain(|layer| { @@ -1617,7 +1614,7 @@ impl Fsm for SelectToolFsmState { responses.add(OverlaysMessage::Draw); let selection = tool_data.nested_selection_behavior; - SelectToolFsmState::Ready { selection } + Self::Ready { selection } } (_, SelectToolMessage::SetPivot { position }) => { tool_data.pivot_gizmo.pivot.last_non_none_reference_point = position; @@ -1688,7 +1685,7 @@ impl Fsm for SelectToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { match self { - SelectToolFsmState::Ready { selection } => { + Self::Ready { selection } => { let hint_data = HintData(vec![ HintGroup({ let mut hints = vec![HintInfo::mouse(MouseMotion::Lmb, "Select Object"), HintInfo::keys([Key::Shift], "Extend").prepend_plus()]; @@ -1719,7 +1716,7 @@ impl Fsm for SelectToolFsmState { ]); hint_data.send_layout(responses); } - SelectToolFsmState::Dragging { axis, using_compass, has_dragged, .. } if *has_dragged => { + Self::Dragging { axis, using_compass, has_dragged, .. } if *has_dragged => { let mut hint_data = vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![ @@ -1734,7 +1731,7 @@ impl Fsm for SelectToolFsmState { let hint_data = HintData(hint_data); hint_data.send_layout(responses); } - SelectToolFsmState::Drawing { has_drawn, .. } if *has_drawn => { + Self::Drawing { has_drawn, .. } if *has_drawn => { let hint_data = HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "Extend"), HintInfo::keys([Key::Alt], "Subtract")]), @@ -1744,29 +1741,29 @@ impl Fsm for SelectToolFsmState { ]); hint_data.send_layout(responses); } - SelectToolFsmState::Drawing { .. } | SelectToolFsmState::Dragging { .. } => {} - SelectToolFsmState::ResizingBounds => { + Self::Drawing { .. } | Self::Dragging { .. } => {} + Self::ResizingBounds => { let hint_data = HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Alt], "From Pivot"), HintInfo::keys([Key::Shift], "Preserve Aspect Ratio")]), ]); hint_data.send_layout(responses); } - SelectToolFsmState::RotatingBounds => { + Self::RotatingBounds => { let hint_data = HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "15° Increments")]), ]); hint_data.send_layout(responses); } - SelectToolFsmState::SkewingBounds { .. } => { + Self::SkewingBounds { .. } => { let hint_data = HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Control], "Unlock Slide")]), ]); hint_data.send_layout(responses); } - SelectToolFsmState::DraggingPivot => { + Self::DraggingPivot => { let hint_data = HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]); hint_data.send_layout(responses); } diff --git a/editor/src/messages/tool/tool_messages/shape_tool.rs b/editor/src/messages/tool/tool_messages/shape_tool.rs index ead0e1e1ce..5c0f5f98d0 100644 --- a/editor/src/messages/tool/tool_messages/shape_tool.rs +++ b/editor/src/messages/tool/tool_messages/shape_tool.rs @@ -468,7 +468,7 @@ pub enum ShapeToolFsmState { impl Default for ShapeToolFsmState { fn default() -> Self { - ShapeToolFsmState::Ready(ShapeType::default()) + Self::Ready(ShapeType::default()) } } @@ -585,29 +585,29 @@ impl Fsm for ShapeToolFsmState { tool_data.gizmo_manager.overlays(document, input, shape_editor, mouse_position, &mut overlay_context); } - if matches!(self, ShapeToolFsmState::ModifyingGizmo) && !input.keyboard.key(Key::Control) { + if matches!(self, Self::ModifyingGizmo) && !input.keyboard.key(Key::Control) { tool_data.gizmo_manager.dragging_overlays(document, input, shape_editor, mouse_position, &mut overlay_context); let cursor = tool_data.gizmo_manager.mouse_cursor_icon().unwrap_or(MouseCursorIcon::Crosshair); tool_data.cursor = cursor; responses.add(FrontendMessage::UpdateMouseCursor { cursor }); } - let modifying_transform_cage = matches!(self, ShapeToolFsmState::ResizingBounds | ShapeToolFsmState::RotatingBounds | ShapeToolFsmState::SkewingBounds { .. }); + let modifying_transform_cage = matches!(self, Self::ResizingBounds | Self::RotatingBounds | Self::SkewingBounds { .. }); let hovering_over_gizmo = tool_data.gizmo_manager.hovering_over_gizmo(); - if !matches!(self, ShapeToolFsmState::ModifyingGizmo) && !modifying_transform_cage && !hovering_over_gizmo { + if !matches!(self, Self::ModifyingGizmo) && !modifying_transform_cage && !hovering_over_gizmo { tool_data.data.snap_manager.draw_overlays(SnapData::new(document, input, viewport), &mut overlay_context); } - if modifying_transform_cage && !matches!(self, ShapeToolFsmState::ModifyingGizmo) { + if modifying_transform_cage && !matches!(self, Self::ModifyingGizmo) { transform_cage_overlays(document, tool_data, &mut overlay_context); responses.add(FrontendMessage::UpdateMouseCursor { cursor: tool_data.cursor }); } - if input.keyboard.key(Key::Control) && matches!(self, ShapeToolFsmState::Ready(_)) { + if input.keyboard.key(Key::Control) && matches!(self, Self::Ready(_)) { anchor_overlays(document, &mut overlay_context); responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair }); - } else if matches!(self, ShapeToolFsmState::Ready(_)) { + } else if matches!(self, Self::Ready(_)) { Line::overlays(document, tool_data, &mut overlay_context); if all_selected_layers_line { @@ -626,7 +626,7 @@ impl Fsm for ShapeToolFsmState { if let Some(bounds) = tool_data.bounding_box_manager.as_mut() { let edges = bounds.check_selected_edges(input.mouse.position); - let is_skewing = matches!(self, ShapeToolFsmState::SkewingBounds { .. }); + let is_skewing = matches!(self, Self::SkewingBounds { .. }); let is_near_square = edges.is_some_and(|hover_edge| bounds.over_extended_edge_midpoint(input.mouse.position, hover_edge)); if is_skewing || (dragging_bounds && is_near_square && !hovering_over_gizmo) { bounds.render_skew_gizmos(&mut overlay_context, tool_data.skew_edge); @@ -645,7 +645,7 @@ impl Fsm for ShapeToolFsmState { responses.add(FrontendMessage::UpdateMouseCursor { cursor }); } - if matches!(self, ShapeToolFsmState::Drawing(_) | ShapeToolFsmState::DraggingLineEndpoints) { + if matches!(self, Self::Drawing(_) | Self::DraggingLineEndpoints) { Line::overlays(document, tool_data, &mut overlay_context); if tool_options.shape_type == ShapeType::Circle { tool_data.gizmo_manager.overlays(document, input, shape_editor, mouse_position, &mut overlay_context); @@ -654,7 +654,7 @@ impl Fsm for ShapeToolFsmState { self } - (ShapeToolFsmState::Ready(_), ShapeToolMessage::IncreaseSides) => { + (Self::Ready(_), ShapeToolMessage::IncreaseSides) => { if matches!(tool_options.shape_type, ShapeType::Star | ShapeType::Polygon) { responses.add(ShapeToolMessage::UpdateOptions { options: ShapeOptionsUpdate::Vertices(tool_options.vertices + 1), @@ -669,7 +669,7 @@ impl Fsm for ShapeToolFsmState { self } - (ShapeToolFsmState::Ready(_), ShapeToolMessage::DecreaseSides) => { + (Self::Ready(_), ShapeToolMessage::DecreaseSides) => { if matches!(tool_options.shape_type, ShapeType::Star | ShapeType::Polygon) { responses.add(ShapeToolMessage::UpdateOptions { options: ShapeOptionsUpdate::Vertices((tool_options.vertices - 1).max(3)), @@ -684,7 +684,7 @@ impl Fsm for ShapeToolFsmState { self } ( - ShapeToolFsmState::Ready(_), + Self::Ready(_), ShapeToolMessage::NudgeSelectedLayers { delta_x, delta_y, @@ -701,7 +701,7 @@ impl Fsm for ShapeToolFsmState { self } - (ShapeToolFsmState::Drawing(_), ShapeToolMessage::NudgeSelectedLayers { .. }) => { + (Self::Drawing(_), ShapeToolMessage::NudgeSelectedLayers { .. }) => { let increase = input.keyboard.key(Key::ArrowUp); let decrease = input.keyboard.key(Key::ArrowDown); @@ -716,15 +716,15 @@ impl Fsm for ShapeToolFsmState { } self } - (ShapeToolFsmState::Drawing(_), ShapeToolMessage::IncreaseSides) => { + (Self::Drawing(_), ShapeToolMessage::IncreaseSides) => { tool_data.decrease_or_increase_sides(document, tool_options.shape_type, responses, false); self } - (ShapeToolFsmState::Drawing(_), ShapeToolMessage::DecreaseSides) => { + (Self::Drawing(_), ShapeToolMessage::DecreaseSides) => { tool_data.decrease_or_increase_sides(document, tool_options.shape_type, responses, true); self } - (ShapeToolFsmState::Ready(_), ShapeToolMessage::DragStart) => { + (Self::Ready(_), ShapeToolMessage::DragStart) => { tool_data.line_data.drag_start = input.mouse.position; // Snapped position in viewport space @@ -751,7 +751,7 @@ impl Fsm for ShapeToolFsmState { responses.add(DocumentMessage::StartTransaction); - return ShapeToolFsmState::ModifyingGizmo; + return Self::ModifyingGizmo; } // If clicked on endpoints of a selected line, drag its endpoints @@ -764,7 +764,7 @@ impl Fsm for ShapeToolFsmState { ) && clicked_on_line_endpoints(layer, document, input, tool_data) && !input.keyboard.key(Key::Control) { - return ShapeToolFsmState::DraggingLineEndpoints; + return Self::DraggingLineEndpoints; } let (resize, rotate, skew) = transforming_transform_cage(document, &mut tool_data.bounding_box_manager, input, responses, &mut tool_data.layers_dragging, None); @@ -785,19 +785,19 @@ impl Fsm for ShapeToolFsmState { tool_data.get_snap_candidates(document, input, viewport); update_cursor_and_pointer(tool_data, responses); - return ShapeToolFsmState::ResizingBounds; + return Self::ResizingBounds; } (false, true, false) => { tool_data.data.drag_start = mouse_pos; update_cursor_and_pointer(tool_data, responses); - return ShapeToolFsmState::RotatingBounds; + return Self::RotatingBounds; } (false, false, true) => { tool_data.get_snap_candidates(document, input, viewport); update_cursor_and_pointer(tool_data, responses); - return ShapeToolFsmState::SkewingBounds { skew: Key::Control }; + return Self::SkewingBounds { skew: Key::Control }; } _ => {} } @@ -862,11 +862,11 @@ impl Fsm for ShapeToolFsmState { }); responses.add(NodeGraphMessage::RunDocumentGraph); - ShapeToolFsmState::Drawing(tool_data.current_shape) + Self::Drawing(tool_data.current_shape) } - (ShapeToolFsmState::Drawing(shape), ShapeToolMessage::PointerMove { modifier }) => { + (Self::Drawing(shape), ShapeToolMessage::PointerMove { modifier }) => { let Some(layer) = tool_data.data.layer else { - return ShapeToolFsmState::Ready(shape); + return Self::Ready(shape); }; match tool_data.current_shape { @@ -887,9 +887,9 @@ impl Fsm for ShapeToolFsmState { self } - (ShapeToolFsmState::DraggingLineEndpoints, ShapeToolMessage::PointerMove { modifier }) => { + (Self::DraggingLineEndpoints, ShapeToolMessage::PointerMove { modifier }) => { let Some(layer) = tool_data.line_data.editing_layer else { - return ShapeToolFsmState::Ready(tool_data.current_shape); + return Self::Ready(tool_data.current_shape); }; Line::update_shape(document, input, viewport, layer, tool_data, modifier, responses); @@ -899,14 +899,14 @@ impl Fsm for ShapeToolFsmState { self } - (ShapeToolFsmState::ModifyingGizmo, ShapeToolMessage::PointerMove { .. }) => { + (Self::ModifyingGizmo, ShapeToolMessage::PointerMove { .. }) => { tool_data.gizmo_manager.handle_update(tool_data.data.viewport_drag_start(document), document, input, responses); responses.add(OverlaysMessage::Draw); - ShapeToolFsmState::ModifyingGizmo + Self::ModifyingGizmo } - (ShapeToolFsmState::ResizingBounds, ShapeToolMessage::PointerMove { modifier }) => { + (Self::ResizingBounds, ShapeToolMessage::PointerMove { modifier }) => { if let Some(bounds) = &mut tool_data.bounding_box_manager { let messages = [ShapeToolMessage::PointerOutsideViewport { modifier }.into(), ShapeToolMessage::PointerMove { modifier }.into()]; resize_bounds( @@ -926,9 +926,9 @@ impl Fsm for ShapeToolFsmState { } responses.add(OverlaysMessage::Draw); - ShapeToolFsmState::ResizingBounds + Self::ResizingBounds } - (ShapeToolFsmState::RotatingBounds, ShapeToolMessage::PointerMove { modifier }) => { + (Self::RotatingBounds, ShapeToolMessage::PointerMove { modifier }) => { if let Some(bounds) = &mut tool_data.bounding_box_manager { rotate_bounds( document, @@ -942,9 +942,9 @@ impl Fsm for ShapeToolFsmState { ); } - ShapeToolFsmState::RotatingBounds + Self::RotatingBounds } - (ShapeToolFsmState::SkewingBounds { skew }, ShapeToolMessage::PointerMove { .. }) => { + (Self::SkewingBounds { skew }, ShapeToolMessage::PointerMove { .. }) => { if let Some(bounds) = &mut tool_data.bounding_box_manager { skew_bounds( document, @@ -957,7 +957,7 @@ impl Fsm for ShapeToolFsmState { ); } - ShapeToolFsmState::SkewingBounds { skew } + Self::SkewingBounds { skew } } (_, ShapeToolMessage::PointerMove { .. }) => { @@ -982,7 +982,7 @@ impl Fsm for ShapeToolFsmState { responses.add(OverlaysMessage::Draw); self } - (ShapeToolFsmState::ResizingBounds | ShapeToolFsmState::SkewingBounds { .. }, ShapeToolMessage::PointerOutsideViewport { .. }) => { + (Self::ResizingBounds | Self::SkewingBounds { .. }, ShapeToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) && let Some(bounds) = &mut tool_data.bounding_box_manager @@ -993,21 +993,13 @@ impl Fsm for ShapeToolFsmState { self } - (ShapeToolFsmState::Ready(_), ShapeToolMessage::PointerOutsideViewport { .. }) => self, + (Self::Ready(_), ShapeToolMessage::PointerOutsideViewport { .. }) => self, (_, ShapeToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses); self } - ( - ShapeToolFsmState::Drawing(_) - | ShapeToolFsmState::DraggingLineEndpoints - | ShapeToolFsmState::ResizingBounds - | ShapeToolFsmState::RotatingBounds - | ShapeToolFsmState::SkewingBounds { .. } - | ShapeToolFsmState::ModifyingGizmo, - ShapeToolMessage::DragStop, - ) => { + (Self::Drawing(_) | Self::DraggingLineEndpoints | Self::ResizingBounds | Self::RotatingBounds | Self::SkewingBounds { .. } | Self::ModifyingGizmo, ShapeToolMessage::DragStop) => { input.mouse.finish_transaction(tool_data.data.drag_start, responses); tool_data.data.cleanup(responses); @@ -1021,17 +1013,9 @@ impl Fsm for ShapeToolFsmState { responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair }); - ShapeToolFsmState::Ready(tool_data.current_shape) + Self::Ready(tool_data.current_shape) } - ( - ShapeToolFsmState::Drawing(_) - | ShapeToolFsmState::DraggingLineEndpoints - | ShapeToolFsmState::ResizingBounds - | ShapeToolFsmState::RotatingBounds - | ShapeToolFsmState::SkewingBounds { .. } - | ShapeToolFsmState::ModifyingGizmo, - ShapeToolMessage::Abort, - ) => { + (Self::Drawing(_) | Self::DraggingLineEndpoints | Self::ResizingBounds | Self::RotatingBounds | Self::SkewingBounds { .. } | Self::ModifyingGizmo, ShapeToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); tool_data.data.cleanup(responses); tool_data.line_data.dragging_endpoint = None; @@ -1045,7 +1029,7 @@ impl Fsm for ShapeToolFsmState { tool_data.cursor = MouseCursorIcon::Crosshair; responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair }); - ShapeToolFsmState::Ready(tool_data.current_shape) + Self::Ready(tool_data.current_shape) } (_, ShapeToolMessage::WorkingColorChanged) => { responses.add(ShapeToolMessage::UpdateOptions { @@ -1064,7 +1048,7 @@ impl Fsm for ShapeToolFsmState { responses.add(ShapeToolMessage::UpdateOptions { options: ShapeOptionsUpdate::ShapeType(shape), }); - ShapeToolFsmState::Ready(shape) + Self::Ready(shape) } (_, ShapeToolMessage::HideShapeTypeWidget { hide }) => { tool_data.hide_shape_option_widget = hide; diff --git a/editor/src/messages/tool/tool_messages/spline_tool.rs b/editor/src/messages/tool/tool_messages/spline_tool.rs index 9aa7fcb5e0..40f29cd77d 100644 --- a/editor/src/messages/tool/tool_messages/spline_tool.rs +++ b/editor/src/messages/tool/tool_messages/spline_tool.rs @@ -306,19 +306,19 @@ impl Fsm for SplineToolFsmState { tool_data.snap_manager.draw_overlays(SnapData::new(document, input, viewport), &mut overlay_context); self } - (SplineToolFsmState::MergingEndpoints, SplineToolMessage::MergeEndpoints) => { - let Some(current_layer) = tool_data.current_layer else { return SplineToolFsmState::Ready }; + (Self::MergingEndpoints, SplineToolMessage::MergeEndpoints) => { + let Some(current_layer) = tool_data.current_layer else { return Self::Ready }; if let Some(&layer) = tool_data.merge_layers.iter().last() { merge_layers(document, current_layer, layer, responses); tool_data.merge_layers.remove(&layer); responses.add(SplineToolMessage::MergeEndpoints); - return SplineToolFsmState::MergingEndpoints; + return Self::MergingEndpoints; } - let Some((start_endpoint, _)) = tool_data.points.first() else { return SplineToolFsmState::Ready }; - let Some((last_endpoint, _)) = tool_data.points.last() else { return SplineToolFsmState::Ready }; + let Some((start_endpoint, _)) = tool_data.points.first() else { return Self::Ready }; + let Some((last_endpoint, _)) = tool_data.points.last() else { return Self::Ready }; if let Some((position, second_endpoint)) = tool_data.merge_endpoints.pop() { let first_endpoint = match position { @@ -328,13 +328,13 @@ impl Fsm for SplineToolFsmState { merge_points(document, current_layer, first_endpoint, second_endpoint, responses); responses.add(SplineToolMessage::MergeEndpoints); - return SplineToolFsmState::MergingEndpoints; + return Self::MergingEndpoints; } responses.add(DocumentMessage::EndTransaction); - SplineToolFsmState::Ready + Self::Ready } - (SplineToolFsmState::Ready, SplineToolMessage::DragStart { append_to_selected }) => { + (Self::Ready, SplineToolMessage::DragStart { append_to_selected }) => { responses.add(DocumentMessage::StartTransaction); tool_data.snap_manager.cleanup(responses); @@ -360,7 +360,7 @@ impl Fsm for SplineToolFsmState { extend_spline(tool_data, true, responses); - return SplineToolFsmState::Drawing; + return Self::Drawing; } else { tool_data.merge_layers.insert(layer); tool_data.merge_endpoints.push((EndpointPosition::Start, point)); @@ -381,7 +381,7 @@ impl Fsm for SplineToolFsmState { let position = transform.inverse().transform_point2(input.mouse.position); tool_data.next_point = position; - return SplineToolFsmState::Drawing; + return Self::Drawing; } responses.add(DocumentMessage::DeselectAllLayers); @@ -399,16 +399,16 @@ impl Fsm for SplineToolFsmState { tool_options.stroke.apply_stroke(tool_data.weight, layer, responses); tool_data.current_layer = Some(layer); - SplineToolFsmState::Drawing + Self::Drawing } - (SplineToolFsmState::Drawing, SplineToolMessage::DragStop) => { + (Self::Drawing, SplineToolMessage::DragStop) => { // The first DragStop event will be ignored to prevent insertion of new point. if tool_data.extend { tool_data.extend = false; - return SplineToolFsmState::Drawing; + return Self::Drawing; } if tool_data.current_layer.is_none() { - return SplineToolFsmState::Ready; + return Self::Ready; }; tool_data.next_point = tool_data.snapped_point(document, input, viewport).snapped_point_document; if tool_data.points.last().is_none_or(|last_pos| last_pos.1.distance(tool_data.next_point) > DRAG_THRESHOLD) { @@ -421,10 +421,10 @@ impl Fsm for SplineToolFsmState { } } - SplineToolFsmState::Drawing + Self::Drawing } - (SplineToolFsmState::Drawing, SplineToolMessage::PointerMove) => { - let Some(layer) = tool_data.current_layer else { return SplineToolFsmState::Ready }; + (Self::Drawing, SplineToolMessage::PointerMove) => { + let Some(layer) = tool_data.current_layer else { return Self::Ready }; let ignore = |cp: PointId| tool_data.preview_point.is_some_and(|pp| pp == cp) || tool_data.points.last().is_some_and(|(ep, _)| *ep == cp); let join_point = closest_point(document, input.mouse.position, PATH_JOIN_THRESHOLD, vec![layer].into_iter(), ignore); @@ -444,21 +444,21 @@ impl Fsm for SplineToolFsmState { let messages = [SplineToolMessage::PointerOutsideViewport.into(), SplineToolMessage::PointerMove.into()]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - SplineToolFsmState::Drawing + Self::Drawing } (_, SplineToolMessage::PointerMove) => { tool_data.snap_manager.preview_draw(&SnapData::new(document, input, viewport), input.mouse.position); responses.add(OverlaysMessage::Draw); self } - (SplineToolFsmState::Drawing, SplineToolMessage::PointerOutsideViewport) => { + (Self::Drawing, SplineToolMessage::PointerOutsideViewport) => { if !input.mouse.mouse_keys.contains(MouseKeys::LEFT) { return self; } // Auto-panning let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses); - SplineToolFsmState::Drawing + Self::Drawing } (state, SplineToolMessage::PointerOutsideViewport) => { // Auto-panning @@ -467,16 +467,16 @@ impl Fsm for SplineToolFsmState { state } - (SplineToolFsmState::Drawing, SplineToolMessage::Confirm) => { + (Self::Drawing, SplineToolMessage::Confirm) => { if tool_data.points.len() >= 2 { delete_preview(tool_data, responses); } responses.add(SplineToolMessage::MergeEndpoints); - SplineToolFsmState::MergingEndpoints + Self::MergingEndpoints } - (SplineToolFsmState::Drawing, SplineToolMessage::Abort) => { + (Self::Drawing, SplineToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); - SplineToolFsmState::Ready + Self::Ready } (_, SplineToolMessage::WorkingColorChanged) => { responses.add(SplineToolMessage::UpdateOptions { @@ -490,16 +490,16 @@ impl Fsm for SplineToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - SplineToolFsmState::Ready => HintData(vec![HintGroup(vec![ + Self::Ready => HintData(vec![HintGroup(vec![ HintInfo::mouse(MouseMotion::Lmb, "Draw Spline"), HintInfo::keys([Key::Shift], "Append to Selected Layer").prepend_plus(), ])]), - SplineToolFsmState::Drawing => HintData(vec![ + Self::Drawing => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::mouse(MouseMotion::Lmb, "Extend Spline")]), HintGroup(vec![HintInfo::keys([Key::Enter], "End Spline")]), ]), - SplineToolFsmState::MergingEndpoints => HintData(vec![]), + Self::MergingEndpoints => HintData(vec![]), }; hint_data.send_layout(responses); diff --git a/editor/src/messages/tool/tool_messages/text_tool.rs b/editor/src/messages/tool/tool_messages/text_tool.rs index fdd2678aef..0f40ce9b36 100644 --- a/editor/src/messages/tool/tool_messages/text_tool.rs +++ b/editor/src/messages/tool/tool_messages/text_tool.rs @@ -576,7 +576,7 @@ impl Fsm for TextToolFsmState { let ToolMessage::Text(event) = event else { return self }; match (self, event) { - (TextToolFsmState::Editing, TextToolMessage::Overlays { context: mut overlay_context }) => { + (Self::Editing, TextToolMessage::Overlays { context: mut overlay_context }) => { let transform = document.metadata().transform_to_viewport(tool_data.layer).to_cols_array(); responses.add(FrontendMessage::DisplayEditableTextboxTransform { transform }); if let Some(editing_text) = tool_data.editing_text.as_mut() { @@ -588,7 +588,7 @@ impl Fsm for TextToolFsmState { } } - TextToolFsmState::Editing + Self::Editing } (_, TextToolMessage::Overlays { context: mut overlay_context }) => { if matches!(self, Self::Placing) { @@ -646,12 +646,12 @@ impl Fsm for TextToolFsmState { (state, TextToolMessage::EditSelected) => { if let Some(layer) = can_edit_selected(document) { tool_data.start_editing_layer(layer, state, document, font_cache, responses); - return TextToolFsmState::Editing; + return Self::Editing; } state } - (TextToolFsmState::Ready, TextToolMessage::DragStart) => { + (Self::Ready, TextToolMessage::DragStart) => { tool_data.resize.start(document, input, viewport); tool_data.cached_resize_bounds = [tool_data.resize.viewport_drag_start(document); 2]; tool_data.drag_start = input.mouse.position; @@ -688,7 +688,7 @@ impl Fsm for TextToolFsmState { } tool_data.get_snap_candidates(document, font_cache); - return TextToolFsmState::ResizingBounds; + return Self::ResizingBounds; } else if let Some(clicked_layer) = TextToolData::check_click(document, input, font_cache) { responses.add(DocumentMessage::StartTransaction); @@ -702,11 +702,11 @@ impl Fsm for TextToolFsmState { original_transform, }); tool_data.get_snap_candidates(document, font_cache); - return TextToolFsmState::Dragging; + return Self::Dragging; } - TextToolFsmState::Placing + Self::Placing } - (TextToolFsmState::Ready, TextToolMessage::PointerMove { .. }) => { + (Self::Ready, TextToolMessage::PointerMove { .. }) => { // This ensures the cursor only changes if a layer is selected let selected = document.network_interface.selected_nodes(); let mut all_selected = selected.selected_visible_and_unlocked_layers(&document.network_interface); @@ -723,9 +723,9 @@ impl Fsm for TextToolFsmState { responses.add(OverlaysMessage::Draw); responses.add(FrontendMessage::UpdateMouseCursor { cursor }); - TextToolFsmState::Ready + Self::Ready } - (TextToolFsmState::Placing, TextToolMessage::PointerMove { center, lock_ratio }) => { + (Self::Placing, TextToolMessage::PointerMove { center, lock_ratio }) => { tool_data.cached_resize_bounds = tool_data.resize.calculate_points_ignore_layer(document, input, viewport, center, lock_ratio, false); responses.add(OverlaysMessage::Draw); @@ -737,9 +737,9 @@ impl Fsm for TextToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); - TextToolFsmState::Placing + Self::Placing } - (TextToolFsmState::Dragging, TextToolMessage::PointerMove { center, lock_ratio }) => { + (Self::Dragging, TextToolMessage::PointerMove { center, lock_ratio }) => { if let Some(dragging_layer) = &tool_data.layer_dragging { let delta = input.mouse.position - tool_data.drag_current; tool_data.drag_current = input.mouse.position; @@ -761,20 +761,20 @@ impl Fsm for TextToolFsmState { tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); } - TextToolFsmState::Dragging + Self::Dragging } - (TextToolFsmState::ResizingBounds, TextToolMessage::PointerMove { center, lock_ratio }) => { + (Self::ResizingBounds, TextToolMessage::PointerMove { center, lock_ratio }) => { if let Some(bounds) = &mut tool_data.bounding_box_manager && let Some(movement) = &mut bounds.selected_edges { let (centered, constrain) = (input.keyboard.key(center), input.keyboard.key(lock_ratio)); let center_position = centered.then_some(bounds.center_of_transformation); - let Some(dragging_layer) = tool_data.layer_dragging else { return TextToolFsmState::Ready }; + let Some(dragging_layer) = tool_data.layer_dragging else { return Self::Ready }; let Some(node_id) = graph_modification_utils::get_text_id(dragging_layer.id, &document.network_interface) else { warn!("Cannot get text node id"); tool_data.layer_dragging.take(); - return TextToolFsmState::Ready; + return Self::Ready; }; let selected = vec![dragging_layer.id]; @@ -822,7 +822,7 @@ impl Fsm for TextToolFsmState { ]; tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses); } - TextToolFsmState::ResizingBounds + Self::ResizingBounds } (_, TextToolMessage::PointerMove { .. }) => { tool_data.resize.snap_manager.preview_draw(&SnapData::new(document, input, viewport), input.mouse.position); @@ -830,13 +830,13 @@ impl Fsm for TextToolFsmState { self } - (TextToolFsmState::Placing, TextToolMessage::PointerOutsideViewport { .. }) => { + (Self::Placing, TextToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning setup let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses); - TextToolFsmState::Placing + Self::Placing } - (TextToolFsmState::ResizingBounds | TextToolFsmState::Dragging, TextToolMessage::PointerOutsideViewport { .. }) => { + (Self::ResizingBounds | Self::Dragging, TextToolMessage::PointerOutsideViewport { .. }) => { // Auto-panning if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) && let Some(bounds) = &mut tool_data.bounding_box_manager @@ -857,7 +857,7 @@ impl Fsm for TextToolFsmState { state } - (TextToolFsmState::ResizingBounds, TextToolMessage::DragStop) => { + (Self::ResizingBounds, TextToolMessage::DragStop) => { let drag_too_small = input.mouse.position.distance(tool_data.resize.viewport_drag_start(document)) < 10. * f64::EPSILON; let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction }; responses.add(response); @@ -868,16 +868,16 @@ impl Fsm for TextToolFsmState { bounds.original_transforms.clear(); } - TextToolFsmState::Ready + Self::Ready } - (TextToolFsmState::Placing, TextToolMessage::DragStop) => { + (Self::Placing, TextToolMessage::DragStop) => { let [start, end] = tool_data.cached_resize_bounds; let has_dragged = (start - end).length_squared() > DRAG_THRESHOLD * DRAG_THRESHOLD; // Check if the user has clicked (no dragging) on some existing text if !has_dragged && let Some(clicked_text_layer_path) = TextToolData::check_click(document, input, font_cache) { tool_data.start_editing_layer(clicked_text_layer_path, self, document, font_cache, responses); - return TextToolFsmState::Editing; + return Self::Editing; } // Otherwise create some new text @@ -898,9 +898,9 @@ impl Fsm for TextToolFsmState { color: tool_options.fill.active_color(), }; tool_data.new_text(document, editing_text, font_cache, responses); - TextToolFsmState::Editing + Self::Editing } - (TextToolFsmState::Dragging, TextToolMessage::DragStop) => { + (Self::Dragging, TextToolMessage::DragStop) => { let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON; let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction }; responses.add(response); @@ -913,21 +913,21 @@ impl Fsm for TextToolFsmState { if drag_too_small && let Some(layer_info) = &tool_data.layer_dragging { tool_data.start_editing_layer(layer_info.id, self, document, font_cache, responses); - return TextToolFsmState::Editing; + return Self::Editing; } tool_data.layer_dragging.take(); - TextToolFsmState::Ready + Self::Ready } - (TextToolFsmState::Editing, TextToolMessage::RefreshEditingFontData) => { + (Self::Editing, TextToolMessage::RefreshEditingFontData) => { let font = Font::new(tool_options.font.font_family.clone(), tool_options.font.font_style.clone()); responses.add(FrontendMessage::DisplayEditableTextboxUpdateFontData { font_data: font_cache.get(&font).map(|(data, _)| data.clone()).unwrap_or_default(), }); - TextToolFsmState::Editing + Self::Editing } - (TextToolFsmState::Editing, TextToolMessage::TextChange { new_text, is_left_or_right_click }) => { + (Self::Editing, TextToolMessage::TextChange { new_text, is_left_or_right_click }) => { tool_data.new_text = new_text; if !is_left_or_right_click { @@ -939,7 +939,7 @@ impl Fsm for TextToolFsmState { }); responses.add(NodeGraphMessage::RunDocumentGraph); - TextToolFsmState::Ready + Self::Ready } else { if tool_data.new_text.is_empty() { return tool_data.delete_empty_layer(font_cache, responses); @@ -947,13 +947,13 @@ impl Fsm for TextToolFsmState { responses.add(FrontendMessage::TriggerTextCommit); - TextToolFsmState::Editing + Self::Editing } } - (TextToolFsmState::Editing, TextToolMessage::UpdateBounds { new_text }) => { + (Self::Editing, TextToolMessage::UpdateBounds { new_text }) => { tool_data.new_text = new_text; responses.add(OverlaysMessage::Draw); - TextToolFsmState::Editing + Self::Editing } (_, TextToolMessage::WorkingColorChanged) => { responses.add(TextToolMessage::UpdateOptions { @@ -961,21 +961,21 @@ impl Fsm for TextToolFsmState { }); self } - (TextToolFsmState::Editing, TextToolMessage::Abort) => { + (Self::Editing, TextToolMessage::Abort) => { if tool_data.new_text.is_empty() { return tool_data.delete_empty_layer(font_cache, responses); } responses.add(FrontendMessage::TriggerTextCommit); - TextToolFsmState::Editing + Self::Editing } (state, TextToolMessage::Abort) => { - if matches!(state, TextToolFsmState::ResizingBounds | TextToolFsmState::Dragging) { + if matches!(state, Self::ResizingBounds | Self::Dragging) { responses.add(DocumentMessage::AbortTransaction); if let Some(bounds) = &mut tool_data.bounding_box_manager { bounds.original_transforms.clear(); } - if matches!(state, TextToolFsmState::Dragging) { + if matches!(state, Self::Dragging) { tool_data.layer_dragging.take(); } } else { @@ -983,7 +983,7 @@ impl Fsm for TextToolFsmState { } tool_data.resize.cleanup(responses); - TextToolFsmState::Ready + Self::Ready } _ => self, } @@ -991,7 +991,7 @@ impl Fsm for TextToolFsmState { fn update_hints(&self, responses: &mut VecDeque) { let hint_data = match self { - TextToolFsmState::Ready => HintData(vec![ + Self::Ready => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Lmb, "Place Text")]), HintGroup(vec![ HintInfo::mouse(MouseMotion::LmbDrag, "Place Text Box"), @@ -1000,16 +1000,16 @@ impl Fsm for TextToolFsmState { ]), HintGroup(vec![HintInfo::mouse(MouseMotion::Lmb, "Edit Text")]), ]), - TextToolFsmState::Editing => HintData(vec![HintGroup(vec![ + Self::Editing => HintData(vec![HintGroup(vec![ HintInfo::keys([Key::Control, Key::Enter], "").add_mac_keys([Key::Command, Key::Enter]), HintInfo::keys([Key::Escape], "Commit Changes").prepend_slash(), ])]), - TextToolFsmState::Placing => HintData(vec![ + Self::Placing => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "Constrain Square"), HintInfo::keys([Key::Alt], "From Center")]), ]), - TextToolFsmState::Dragging => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), - TextToolFsmState::ResizingBounds => HintData(vec![ + Self::Dragging => HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), + Self::ResizingBounds => HintData(vec![ HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), HintGroup(vec![HintInfo::keys([Key::Shift], "Lock Aspect Ratio"), HintInfo::keys([Key::Alt], "From Center")]), ]), @@ -1020,7 +1020,7 @@ impl Fsm for TextToolFsmState { fn update_cursor(&self, responses: &mut VecDeque) { let cursor = match self { - TextToolFsmState::Placing => MouseCursorIcon::Crosshair, + Self::Placing => MouseCursorIcon::Crosshair, _ => MouseCursorIcon::Text, }; responses.add(FrontendMessage::UpdateMouseCursor { cursor }); diff --git a/editor/src/messages/tool/utility_types.rs b/editor/src/messages/tool/utility_types.rs index ead8c52214..5046a922a8 100644 --- a/editor/src/messages/tool/utility_types.rs +++ b/editor/src/messages/tool/utility_types.rs @@ -400,7 +400,7 @@ impl ToolType { } pub fn get_tool(self) -> Self { - if self.get_shape().is_some() { ToolType::Shape } else { self } + if self.get_shape().is_some() { Self::Shape } else { self } } } diff --git a/editor/src/messages/viewport/viewport_message_handler.rs b/editor/src/messages/viewport/viewport_message_handler.rs index 628343bd07..e100ddb53f 100644 --- a/editor/src/messages/viewport/viewport_message_handler.rs +++ b/editor/src/messages/viewport/viewport_message_handler.rs @@ -158,10 +158,10 @@ struct Point { } impl Point { fn convert_to_logical(&self, scale: f64) -> LogicalPoint { - Point { x: self.x(), y: self.y() }.into_scaled(scale) + Self { x: self.x(), y: self.y() }.into_scaled(scale) } fn convert_to_physical(&self, scale: f64) -> PhysicalPoint { - Point { + Self { x: self.x() / scale, y: self.y() / scale, } @@ -385,133 +385,133 @@ impl FromWithScale for PhysicalBounds { } impl Mul for Point { - type Output = Point; + type Output = Self; fn mul(self, rhs: f64) -> Self::Output { assert_ne!(rhs, 0.0, "Cannot multiply point by zero"); - Point { x: self.x * rhs, y: self.y * rhs } + Self { x: self.x * rhs, y: self.y * rhs } } } impl Div for Point { - type Output = Point; + type Output = Self; fn div(self, rhs: f64) -> Self::Output { assert_ne!(rhs, 0.0, "Cannot divide point by zero"); - Point { x: self.x / rhs, y: self.y / rhs } + Self { x: self.x / rhs, y: self.y / rhs } } } impl Add for Point { - type Output = Point; + type Output = Self; fn add(self, rhs: f64) -> Self::Output { - Point { x: self.x + rhs, y: self.y + rhs } + Self { x: self.x + rhs, y: self.y + rhs } } } impl Sub for Point { - type Output = Point; + type Output = Self; fn sub(self, rhs: f64) -> Self::Output { - Point { x: self.x - rhs, y: self.y - rhs } + Self { x: self.x - rhs, y: self.y - rhs } } } -impl Mul for Point { - type Output = Point; - fn mul(self, rhs: Point) -> Self::Output { +impl Mul for Point { + type Output = Self; + fn mul(self, rhs: Self) -> Self::Output { assert_ne!(rhs.x, 0.0, "Cannot multiply point by zero"); assert_ne!(rhs.y, 0.0, "Cannot multiply point by zero"); - Point { x: self.x * rhs.x, y: self.y * rhs.y } + Self { x: self.x * rhs.x, y: self.y * rhs.y } } } -impl Div for Point { - type Output = Point; - fn div(self, rhs: Point) -> Self::Output { +impl Div for Point { + type Output = Self; + fn div(self, rhs: Self) -> Self::Output { assert_ne!(rhs.x, 0.0, "Cannot multiply point by zero"); assert_ne!(rhs.y, 0.0, "Cannot multiply point by zero"); - Point { x: self.x / rhs.x, y: self.y / rhs.y } + Self { x: self.x / rhs.x, y: self.y / rhs.y } } } -impl Add for Point { - type Output = Point; - fn add(self, rhs: Point) -> Self::Output { - Point { x: self.x + rhs.x, y: self.y + rhs.y } +impl Add for Point { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + Self { x: self.x + rhs.x, y: self.y + rhs.y } } } -impl Sub for Point { - type Output = Point; - fn sub(self, rhs: Point) -> Self::Output { - Point { x: self.x - rhs.x, y: self.y - rhs.y } +impl Sub for Point { + type Output = Self; + fn sub(self, rhs: Self) -> Self::Output { + Self { x: self.x - rhs.x, y: self.y - rhs.y } } } impl Mul for Bounds { - type Output = Bounds; + type Output = Self; fn mul(self, rhs: f64) -> Self::Output { assert_ne!(rhs, 0.0, "Cannot multiply bounds by zero"); - Bounds { + Self { offset: self.offset * rhs, size: self.size * rhs, } } } impl Div for Bounds { - type Output = Bounds; + type Output = Self; fn div(self, rhs: f64) -> Self::Output { assert_ne!(rhs, 0.0, "Cannot divide bounds by zero"); - Bounds { + Self { offset: self.offset / rhs, size: self.size / rhs, } } } -impl Mul for LogicalPoint { - type Output = LogicalPoint; - fn mul(self, rhs: LogicalPoint) -> Self::Output { +impl Mul for LogicalPoint { + type Output = Self; + fn mul(self, rhs: Self) -> Self::Output { assert_scale(&self, &rhs); (self.as_point() * rhs.as_point()).into_scaled(self.scale()) } } -impl Div for LogicalPoint { - type Output = LogicalPoint; - fn div(self, rhs: LogicalPoint) -> Self::Output { +impl Div for LogicalPoint { + type Output = Self; + fn div(self, rhs: Self) -> Self::Output { assert_scale(&self, &rhs); (self.as_point() / rhs.as_point()).into_scaled(self.scale()) } } -impl Add for LogicalPoint { - type Output = LogicalPoint; - fn add(self, rhs: LogicalPoint) -> Self::Output { +impl Add for LogicalPoint { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { assert_scale(&self, &rhs); (self.as_point() + rhs.as_point()).into_scaled(self.scale()) } } -impl Sub for LogicalPoint { - type Output = LogicalPoint; - fn sub(self, rhs: LogicalPoint) -> Self::Output { +impl Sub for LogicalPoint { + type Output = Self; + fn sub(self, rhs: Self) -> Self::Output { assert_scale(&self, &rhs); (self.as_point() - rhs.as_point()).into_scaled(self.scale()) } } -impl Mul for PhysicalPoint { - type Output = PhysicalPoint; - fn mul(self, rhs: PhysicalPoint) -> Self::Output { +impl Mul for PhysicalPoint { + type Output = Self; + fn mul(self, rhs: Self) -> Self::Output { assert_scale(&self, &rhs); (self.as_point() * rhs.as_point()).into_scaled(self.scale()) } } -impl Div for PhysicalPoint { - type Output = PhysicalPoint; - fn div(self, rhs: PhysicalPoint) -> Self::Output { +impl Div for PhysicalPoint { + type Output = Self; + fn div(self, rhs: Self) -> Self::Output { assert_scale(&self, &rhs); (self.as_point() / rhs.as_point()).into_scaled(self.scale()) } } -impl Add for PhysicalPoint { - type Output = PhysicalPoint; - fn add(self, rhs: PhysicalPoint) -> Self::Output { +impl Add for PhysicalPoint { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { assert_scale(&self, &rhs); (self.as_point() + rhs.as_point()).into_scaled(self.scale()) } } -impl Sub for PhysicalPoint { - type Output = PhysicalPoint; - fn sub(self, rhs: PhysicalPoint) -> Self::Output { +impl Sub for PhysicalPoint { + type Output = Self; + fn sub(self, rhs: Self) -> Self::Output { assert_scale(&self, &rhs); (self.as_point() - rhs.as_point()).into_scaled(self.scale()) } @@ -562,12 +562,12 @@ impl From for Point { } impl From for glam::DVec2 { fn from(val: LogicalPoint) -> Self { - glam::DVec2::new(val.x(), val.y()) + Self::new(val.x(), val.y()) } } impl From for glam::DVec2 { fn from(val: PhysicalPoint) -> Self { - glam::DVec2::new(val.x(), val.y()) + Self::new(val.x(), val.y()) } } diff --git a/editor/src/utility_types.rs b/editor/src/utility_types.rs index c27ce5c12b..e1fe7e0e3b 100644 --- a/editor/src/utility_types.rs +++ b/editor/src/utility_types.rs @@ -6,8 +6,8 @@ pub struct MessageData { } impl MessageData { - pub fn new(name: String, fields: Vec<(String, usize)>, path: &'static str) -> MessageData { - MessageData { name, fields, path } + pub fn new(name: String, fields: Vec<(String, usize)>, path: &'static str) -> Self { + Self { name, fields, path } } pub fn name(&self) -> &str { @@ -27,15 +27,15 @@ impl MessageData { pub struct DebugMessageTree { name: String, fields: Option>, - variants: Option>, + variants: Option>, message_handler: Option, message_handler_data: Option, path: &'static str, } impl DebugMessageTree { - pub fn new(name: &str) -> DebugMessageTree { - DebugMessageTree { + pub fn new(name: &str) -> Self { + Self { name: name.to_string(), fields: None, variants: None, @@ -53,7 +53,7 @@ impl DebugMessageTree { self.path = path; } - pub fn add_variant(&mut self, variant: DebugMessageTree) { + pub fn add_variant(&mut self, variant: Self) { if let Some(variants) = &mut self.variants { variants.push(variant); } else { @@ -81,7 +81,7 @@ impl DebugMessageTree { self.path } - pub fn variants(&self) -> Option<&Vec> { + pub fn variants(&self) -> Option<&Vec> { self.variants.as_ref() } diff --git a/frontend/wasm/src/editor_api.rs b/frontend/wasm/src/editor_api.rs index 8f386c3879..ca34ee93e4 100644 --- a/frontend/wasm/src/editor_api.rs +++ b/frontend/wasm/src/editor_api.rs @@ -92,7 +92,7 @@ impl EditorHandle { #[wasm_bindgen(constructor)] pub fn new(frontend_message_handler_callback: js_sys::Function) -> Self { let editor = Editor::new(); - let editor_handle = EditorHandle { frontend_message_handler_callback }; + let editor_handle = Self { frontend_message_handler_callback }; if EDITOR.with(|handle| handle.lock().ok().map(|mut guard| *guard = Some(editor))).is_none() { log::error!("Attempted to initialize the editor more than once"); } diff --git a/libraries/dyn-any/src/lib.rs b/libraries/dyn-any/src/lib.rs index 047557a4b4..326e31929e 100644 --- a/libraries/dyn-any/src/lib.rs +++ b/libraries/dyn-any/src/lib.rs @@ -242,7 +242,7 @@ impl<'n, T: StaticType + 'n> IntoDynAny<'n> for T {} #[cfg(feature = "alloc")] impl From<()> for Box> { - fn from(_: ()) -> Box> { + fn from(_: ()) -> Self { Box::new(()) } } diff --git a/libraries/math-parser/src/ast.rs b/libraries/math-parser/src/ast.rs index 4c42fc4b1d..78beecea02 100644 --- a/libraries/math-parser/src/ast.rs +++ b/libraries/math-parser/src/ast.rs @@ -17,16 +17,16 @@ impl Default for Unit { } impl Unit { - pub const BASE_UNIT: Unit = Unit { length: 0, mass: 0, time: 0 }; + pub const BASE_UNIT: Self = Self { length: 0, mass: 0, time: 0 }; - pub const LENGTH: Unit = Unit { length: 1, mass: 0, time: 0 }; - pub const MASS: Unit = Unit { length: 0, mass: 1, time: 0 }; - pub const TIME: Unit = Unit { length: 0, mass: 0, time: 1 }; + pub const LENGTH: Self = Self { length: 1, mass: 0, time: 0 }; + pub const MASS: Self = Self { length: 0, mass: 1, time: 0 }; + pub const TIME: Self = Self { length: 0, mass: 0, time: 1 }; - pub const VELOCITY: Unit = Unit { length: 1, mass: 0, time: -1 }; - pub const ACCELERATION: Unit = Unit { length: 1, mass: 0, time: -2 }; + pub const VELOCITY: Self = Self { length: 1, mass: 0, time: -1 }; + pub const ACCELERATION: Self = Self { length: 1, mass: 0, time: -2 }; - pub const FORCE: Unit = Unit { length: 1, mass: 1, time: -2 }; + pub const FORCE: Self = Self { length: 1, mass: 1, time: -2 }; pub fn base_unit() -> Self { Self::BASE_UNIT @@ -69,7 +69,7 @@ pub enum UnaryOp { pub enum Node { Lit(Literal), Var(String), - FnCall { name: String, expr: Vec }, - BinOp { lhs: Box, op: BinaryOp, rhs: Box }, - UnaryOp { expr: Box, op: UnaryOp }, + FnCall { name: String, expr: Vec }, + BinOp { lhs: Box, op: BinaryOp, rhs: Box }, + UnaryOp { expr: Box, op: UnaryOp }, } diff --git a/libraries/math-parser/src/executer.rs b/libraries/math-parser/src/executer.rs index 9d6180f1ab..7de728d572 100644 --- a/libraries/math-parser/src/executer.rs +++ b/libraries/math-parser/src/executer.rs @@ -18,19 +18,19 @@ pub enum EvalError { impl Node { pub fn eval(&self, context: &EvalContext) -> Result { match self { - Node::Lit(lit) => match lit { + Self::Lit(lit) => match lit { Literal::Float(num) => Ok(Value::from_f64(*num)), Literal::Complex(num) => Ok(Value::Number(Number::Complex(*num))), }, - Node::BinOp { lhs, op, rhs } => match (lhs.eval(context)?, rhs.eval(context)?) { + Self::BinOp { lhs, op, rhs } => match (lhs.eval(context)?, rhs.eval(context)?) { (Value::Number(lhs), Value::Number(rhs)) => Ok(Value::Number(lhs.binary_op(*op, rhs))), }, - Node::UnaryOp { expr, op } => match expr.eval(context)? { + Self::UnaryOp { expr, op } => match expr.eval(context)? { Value::Number(num) => Ok(Value::Number(num.unary_op(*op))), }, - Node::Var(name) => context.get_value(name).ok_or_else(|| EvalError::MissingValue(name.clone())), - Node::FnCall { name, expr } => { + Self::Var(name) => context.get_value(name).ok_or_else(|| EvalError::MissingValue(name.clone())), + Self::FnCall { name, expr } => { let values = expr.iter().map(|expr| expr.eval(context)).collect::, EvalError>>()?; if let Some(function) = DEFAULT_FUNCTIONS.get(&name.as_str()) { function(&values).ok_or(EvalError::TypeError) diff --git a/libraries/math-parser/src/parser.rs b/libraries/math-parser/src/parser.rs index e707b500f4..6e5fc2164d 100644 --- a/libraries/math-parser/src/parser.rs +++ b/libraries/math-parser/src/parser.rs @@ -50,7 +50,7 @@ pub enum ParseError { } impl Node { - pub fn try_parse_from_str(s: &str) -> Result<(Node, Unit), ParseError> { + pub fn try_parse_from_str(s: &str) -> Result<(Self, Unit), ParseError> { let pairs = ExprParser::parse(Rule::program, s).map_err(Box::new)?; let (node, metadata) = parse_expr(pairs)?; Ok((node, metadata.unit)) diff --git a/libraries/math-parser/src/value.rs b/libraries/math-parser/src/value.rs index 3577f3ea60..d3038c11ee 100644 --- a/libraries/math-parser/src/value.rs +++ b/libraries/math-parser/src/value.rs @@ -31,7 +31,7 @@ impl From for Value { impl core::fmt::Display for Value { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Value::Number(num) => num.fmt(f), + Self::Number(num) => num.fmt(f), } } } @@ -45,16 +45,16 @@ pub enum Number { impl std::fmt::Display for Number { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Number::Real(real) => real.fmt(f), - Number::Complex(complex) => complex.fmt(f), + Self::Real(real) => real.fmt(f), + Self::Complex(complex) => complex.fmt(f), } } } impl Number { - pub fn binary_op(self, op: BinaryOp, other: Number) -> Number { + pub fn binary_op(self, op: BinaryOp, other: Self) -> Self { match (self, other) { - (Number::Real(lhs), Number::Real(rhs)) => { + (Self::Real(lhs), Self::Real(rhs)) => { let result = match op { BinaryOp::Add => lhs + rhs, BinaryOp::Sub => lhs - rhs, @@ -62,10 +62,10 @@ impl Number { BinaryOp::Div => lhs / rhs, BinaryOp::Pow => lhs.powf(rhs), }; - Number::Real(result) + Self::Real(result) } - (Number::Complex(lhs), Number::Complex(rhs)) => { + (Self::Complex(lhs), Self::Complex(rhs)) => { let result = match op { BinaryOp::Add => lhs + rhs, BinaryOp::Sub => lhs - rhs, @@ -73,10 +73,10 @@ impl Number { BinaryOp::Div => lhs / rhs, BinaryOp::Pow => lhs.powc(rhs), }; - Number::Complex(result) + Self::Complex(result) } - (Number::Real(lhs), Number::Complex(rhs)) => { + (Self::Real(lhs), Self::Complex(rhs)) => { let lhs_complex = Complex::new(lhs, 0.0); let result = match op { BinaryOp::Add => lhs_complex + rhs, @@ -85,10 +85,10 @@ impl Number { BinaryOp::Div => lhs_complex / rhs, BinaryOp::Pow => lhs_complex.powc(rhs), }; - Number::Complex(result) + Self::Complex(result) } - (Number::Complex(lhs), Number::Real(rhs)) => { + (Self::Complex(lhs), Self::Real(rhs)) => { let rhs_complex = Complex::new(rhs, 0.0); let result = match op { BinaryOp::Add => lhs + rhs_complex, @@ -97,23 +97,23 @@ impl Number { BinaryOp::Div => lhs / rhs_complex, BinaryOp::Pow => lhs.powf(rhs), }; - Number::Complex(result) + Self::Complex(result) } } } - pub fn unary_op(self, op: UnaryOp) -> Number { + pub fn unary_op(self, op: UnaryOp) -> Self { match self { - Number::Real(real) => match op { - UnaryOp::Neg => Number::Real(-real), - UnaryOp::Sqrt => Number::Real(real.sqrt()), + Self::Real(real) => match op { + UnaryOp::Neg => Self::Real(-real), + UnaryOp::Sqrt => Self::Real(real.sqrt()), UnaryOp::Fac => todo!("Implement factorial"), }, - Number::Complex(complex) => match op { - UnaryOp::Neg => Number::Complex(-complex), - UnaryOp::Sqrt => Number::Complex(complex.sqrt()), + Self::Complex(complex) => match op { + UnaryOp::Neg => Self::Complex(-complex), + UnaryOp::Sqrt => Self::Complex(complex.sqrt()), UnaryOp::Fac => todo!("Implement factorial"), }, diff --git a/libraries/path-bool/src/path/path_segment.rs b/libraries/path-bool/src/path/path_segment.rs index eb0b6443ec..fa0ea06b46 100644 --- a/libraries/path-bool/src/path/path_segment.rs +++ b/libraries/path-bool/src/path/path_segment.rs @@ -99,8 +99,8 @@ impl PathSegment { /// ``` pub fn start_angle(&self) -> f64 { let angle = match *self { - PathSegment::Line(start, end) => (end - start).angle_to(DVec2::X), - PathSegment::Cubic(start, control1, control2, _) => { + Self::Line(start, end) => (end - start).angle_to(DVec2::X), + Self::Cubic(start, control1, control2, _) => { let diff = control1 - start; if diff.abs_diff_eq(DVec2::ZERO, EPS.point) { // if this diff were empty too, the segments would have been converted to a line @@ -110,8 +110,8 @@ impl PathSegment { } } // Apply same logic as for cubic bezier - PathSegment::Quadratic(start, control, _) => (control - start).to_angle(), - PathSegment::Arc(..) => self.arc_segment_to_cubics(0.001)[0].start_angle(), + Self::Quadratic(start, control, _) => (control - start).to_angle(), + Self::Arc(..) => self.arc_segment_to_cubics(0.001)[0].start_angle(), }; use std::f64::consts::TAU; (angle + TAU) % TAU @@ -146,8 +146,8 @@ impl PathSegment { /// ``` pub fn start_curvature(&self) -> f64 { match *self { - PathSegment::Line(_, _) => 0., - PathSegment::Cubic(start, control1, control2, _) => { + Self::Line(_, _) => 0., + Self::Cubic(start, control1, control2, _) => { let a = control1 - start; let a = 3. * a; let b = start - 2. * control1 + control2; @@ -156,7 +156,7 @@ impl PathSegment { let denominator = a.length_squared() * a.length(); if denominator == 0. { 0. } else { numerator / denominator } } - PathSegment::Quadratic(start, control, end) => { + Self::Quadratic(start, control, end) => { // First derivative let a = 2. * (control - start); // Second derivative @@ -165,7 +165,7 @@ impl PathSegment { let denominator = a.length_squared() * a.length(); if denominator == 0. { 0. } else { numerator / denominator } } - PathSegment::Arc(..) => self.arc_segment_to_cubics(0.001)[0].start_curvature(), + Self::Arc(..) => self.arc_segment_to_cubics(0.001)[0].start_curvature(), } } /// Converts the segment to a cubic Bézier curve representation. @@ -198,9 +198,9 @@ impl PathSegment { /// `to_cubic()` on an `Arc` segment will result in a panic. pub fn to_cubic(&self) -> [DVec2; 4] { match *self { - PathSegment::Line(start, end) => [start, start, end, end], - PathSegment::Cubic(s, c1, c2, e) => [s, c1, c2, e], - PathSegment::Quadratic(start, control, end) => { + Self::Line(start, end) => [start, start, end, end], + Self::Cubic(s, c1, c2, e) => [s, c1, c2, e], + Self::Quadratic(start, control, end) => { // C0 = Q0 // C1 = Q0 + (2/3) (Q1 - Q0) // C2 = Q2 + (2/3) (Q1 - Q2) @@ -209,7 +209,7 @@ impl PathSegment { let d2 = control - end; [start, start + (2. / 3.) * d1, end + (2. / 3.) * d2, end] } - PathSegment::Arc(..) => unimplemented!(), + Self::Arc(..) => unimplemented!(), } } @@ -217,10 +217,7 @@ impl PathSegment { /// Retrieves the start point of a path segment. pub fn start(&self) -> DVec2 { match self { - PathSegment::Line(start, _) => *start, - PathSegment::Cubic(start, _, _, _) => *start, - PathSegment::Quadratic(start, _, _) => *start, - PathSegment::Arc(start, _, _, _, _, _, _) => *start, + Self::Line(start, _) | Self::Cubic(start, _, _, _) | Self::Quadratic(start, _, _) | Self::Arc(start, _, _, _, _, _, _) => *start, } } @@ -228,10 +225,7 @@ impl PathSegment { /// Retrieves the end point of a path segment. pub fn end(&self) -> DVec2 { match self { - PathSegment::Line(_, end) => *end, - PathSegment::Cubic(_, _, _, end) => *end, - PathSegment::Quadratic(_, _, end) => *end, - PathSegment::Arc(_, _, _, _, _, _, end) => *end, + Self::Line(_, end) | Self::Cubic(_, _, _, end) | Self::Quadratic(_, _, end) | Self::Arc(_, _, _, _, _, _, end) => *end, } } @@ -252,12 +246,12 @@ impl PathSegment { /// assert_eq!(reversed.start(), DVec2::new(1., 1.)); /// assert_eq!(reversed.end(), DVec2::new(0., 0.)); /// ``` - pub fn reverse(&self) -> PathSegment { + pub fn reverse(&self) -> Self { match *self { - PathSegment::Line(start, end) => PathSegment::Line(end, start), - PathSegment::Cubic(p1, p2, p3, p4) => PathSegment::Cubic(p4, p3, p2, p1), - PathSegment::Quadratic(p1, p2, p3) => PathSegment::Quadratic(p3, p2, p1), - PathSegment::Arc(start, rx, ry, phi, fa, fs, end) => PathSegment::Arc(end, rx, ry, phi, fa, !fs, start), + Self::Line(start, end) => Self::Line(end, start), + Self::Cubic(p1, p2, p3, p4) => Self::Cubic(p4, p3, p2, p1), + Self::Quadratic(p1, p2, p3) => Self::Quadratic(p3, p2, p1), + Self::Arc(start, rx, ry, phi, fa, fs, end) => Self::Arc(end, rx, ry, phi, fa, !fs, start), } } @@ -272,7 +266,7 @@ impl PathSegment { /// An `Option` containing `PathArcSegmentCenterParametrization` if the segment /// is an `Arc`, or `None` otherwise. pub fn arc_segment_to_center(&self) -> Option { - if let PathSegment::Arc(xy1, rx, ry, phi, fa, fs, xy2) = *self { + if let Self::Arc(xy1, rx, ry, phi, fa, fs, xy2) = *self { if rx == 0. || ry == 0. { return None; } @@ -345,8 +339,8 @@ impl PathSegment { /// ``` pub fn sample_at(&self, t: f64) -> DVec2 { match *self { - PathSegment::Line(start, end) => start.lerp(end, t), - PathSegment::Cubic(p1, p2, p3, p4) => { + Self::Line(start, end) => start.lerp(end, t), + Self::Cubic(p1, p2, p3, p4) => { let p01 = p1.lerp(p2, t); let p12 = p2.lerp(p3, t); let p23 = p3.lerp(p4, t); @@ -354,12 +348,12 @@ impl PathSegment { let p123 = p12.lerp(p23, t); p012.lerp(p123, t) } - PathSegment::Quadratic(p1, p2, p3) => { + Self::Quadratic(p1, p2, p3) => { let p01 = p1.lerp(p2, t); let p12 = p2.lerp(p3, t); p01.lerp(p12, t) } - PathSegment::Arc(start, rx, ry, phi, _, _, end) => { + Self::Arc(start, rx, ry, phi, _, _, end) => { if let Some(center_param) = self.arc_segment_to_center() { let theta = center_param.theta1 + t * center_param.delta_theta; let p = DVec2::new(rx * theta.cos(), ry * theta.sin()); @@ -387,8 +381,8 @@ impl PathSegment { /// # Returns /// /// A vector of `PathSegment::Cubic` approximating the original segment. - pub fn arc_segment_to_cubics(&self, max_delta_theta: f64) -> Vec { - if let PathSegment::Arc(start, rx, ry, phi, _, _, end) = *self { + pub fn arc_segment_to_cubics(&self, max_delta_theta: f64) -> Vec { + if let Self::Arc(start, rx, ry, phi, _, _, end) = *self { if let Some(center_param) = self.arc_segment_to_center() { let count = ((center_param.delta_theta.abs() / max_delta_theta).ceil() as usize).max(1); @@ -412,11 +406,11 @@ impl PathSegment { let control2 = (matrix * control2.extend(1.)).truncate(); let end = (matrix * end.extend(1.)).truncate(); - PathSegment::Cubic(start, control1, control2, end) + Self::Cubic(start, control1, control2, end) }) .collect() } else { - vec![PathSegment::Line(start, end)] + vec![Self::Line(start, end)] } } else { vec![*self] @@ -588,18 +582,18 @@ impl PathSegment { /// An [`Aabb`] representing the axis-aligned bounding box of the segment. pub(crate) fn bounding_box(&self) -> Aabb { match *self { - PathSegment::Line(start, end) => Aabb::new(start.x.min(end.x), start.y.min(end.y), start.x.max(end.x), start.y.max(end.y)), - PathSegment::Cubic(p1, p2, p3, p4) => { + Self::Line(start, end) => Aabb::new(start.x.min(end.x), start.y.min(end.y), start.x.max(end.x), start.y.max(end.y)), + Self::Cubic(p1, p2, p3, p4) => { let (left, right) = cubic_bounding_interval(p1.x, p2.x, p3.x, p4.x); let (top, bottom) = cubic_bounding_interval(p1.y, p2.y, p3.y, p4.y); Aabb::new(left, top, right, bottom) } - PathSegment::Quadratic(p1, p2, p3) => { + Self::Quadratic(p1, p2, p3) => { let (left, right) = quadratic_bounding_interval(p1.x, p2.x, p3.x); let (top, bottom) = quadratic_bounding_interval(p1.y, p2.y, p3.y); Aabb::new(left, top, right, bottom) } - PathSegment::Arc(start, rx, ry, phi, _, _, end) => { + Self::Arc(start, rx, ry, phi, _, _, end) => { if let Some(center_param) = self.arc_segment_to_center() { let theta2 = center_param.theta1 + center_param.delta_theta; let mut bounding_box = extend_bounding_box(Some(bounding_box_around_point(start, 0.)), end); @@ -639,7 +633,7 @@ impl PathSegment { /// This will usually be larger than the actual bounding box, but is faster to compute because it does not have to find where each curve reaches its maximum and minimum. pub(crate) fn approx_bounding_box(&self) -> Aabb { match *self { - PathSegment::Cubic(p1, p2, p3, p4) => { + Self::Cubic(p1, p2, p3, p4) => { // Use the control points to create a bounding box let left = p1.x.min(p2.x).min(p3.x).min(p4.x); let right = p1.x.max(p2.x).max(p3.x).max(p4.x); @@ -647,7 +641,7 @@ impl PathSegment { let bottom = p1.y.max(p2.y).max(p3.y).max(p4.y); Aabb::new(left, top, right, bottom) } - PathSegment::Quadratic(p1, p2, p3) => { + Self::Quadratic(p1, p2, p3) => { // Use the control points to create a bounding box let left = p1.x.min(p2.x).min(p3.x); let right = p1.x.max(p2.x).max(p3.x); @@ -680,13 +674,13 @@ impl PathSegment { /// assert_eq!(first_half.end(), DVec2::new(1., 1.)); /// assert_eq!(second_half.start(), DVec2::new(1., 1.)); /// ``` - pub fn split_at(&self, t: f64) -> (PathSegment, PathSegment) { + pub fn split_at(&self, t: f64) -> (Self, Self) { match *self { - PathSegment::Line(start, end) => { + Self::Line(start, end) => { let p = start.lerp(end, t); - (PathSegment::Line(start, p), PathSegment::Line(p, end)) + (Self::Line(start, p), Self::Line(p, end)) } - PathSegment::Cubic(p0, p1, p2, p3) => { + Self::Cubic(p0, p1, p2, p3) => { let p01 = p0.lerp(p1, t); let p12 = p1.lerp(p2, t); let p23 = p2.lerp(p3, t); @@ -694,16 +688,16 @@ impl PathSegment { let p123 = p12.lerp(p23, t); let p = p012.lerp(p123, t); - (PathSegment::Cubic(p0, p01, p012, p), PathSegment::Cubic(p, p123, p23, p3)) + (Self::Cubic(p0, p01, p012, p), Self::Cubic(p, p123, p23, p3)) } - PathSegment::Quadratic(p0, p1, p2) => { + Self::Quadratic(p0, p1, p2) => { let p01 = p0.lerp(p1, t); let p12 = p1.lerp(p2, t); let p = p01.lerp(p12, t); - (PathSegment::Quadratic(p0, p01, p), PathSegment::Quadratic(p, p12, p2)) + (Self::Quadratic(p0, p01, p), Self::Quadratic(p, p12, p2)) } - PathSegment::Arc(start, _, _, _, _, _, end) => { + Self::Arc(start, _, _, _, _, _, end) => { if let Some(center_param) = self.arc_segment_to_center() { let mid_delta_theta = center_param.delta_theta * t; let seg1 = PathArcSegmentCenterParametrization { @@ -721,7 +715,7 @@ impl PathSegment { } else { // https://svgwg.org/svg2-draft/implnote.html#ArcCorrectionOutOfRangeRadii let p = start.lerp(end, t); - (PathSegment::Line(start, p), PathSegment::Line(p, end)) + (Self::Line(start, p), Self::Line(p, end)) } } } diff --git a/libraries/path-bool/src/path_boolean.rs b/libraries/path-bool/src/path_boolean.rs index 34d178559e..41a2fb9a6f 100644 --- a/libraries/path-bool/src/path_boolean.rs +++ b/libraries/path-bool/src/path_boolean.rs @@ -304,7 +304,7 @@ struct DualGraph { #[derive(Debug, Clone)] struct NestingTree { component: DualGraphComponent, - outgoing_edges: HashMap>, + outgoing_edges: HashMap>, } #[cfg(feature = "logging")] diff --git a/libraries/path-bool/src/util/aabb.rs b/libraries/path-bool/src/util/aabb.rs index 7d68cfd084..06fb409eb9 100644 --- a/libraries/path-bool/src/util/aabb.rs +++ b/libraries/path-bool/src/util/aabb.rs @@ -26,7 +26,7 @@ impl Aabb { } pub(crate) const fn new(left: f64, top: f64, right: f64, bottom: f64) -> Self { - Aabb { + Self { min: DVec2::new(left, top), max: DVec2::new(right, bottom), } diff --git a/libraries/path-bool/src/util/grid.rs b/libraries/path-bool/src/util/grid.rs index 4cb38c477b..9e530d18af 100644 --- a/libraries/path-bool/src/util/grid.rs +++ b/libraries/path-bool/src/util/grid.rs @@ -10,7 +10,7 @@ pub(crate) struct Grid { impl Grid { pub(crate) fn new(cell_size: f64, edges: usize) -> Self { - Grid { + Self { cell_factor: cell_size.recip(), cells: FxHashMap::with_capacity_and_hasher(edges, Default::default()), } @@ -59,7 +59,7 @@ pub struct BitVec { impl BitVec { pub fn new(capacity: usize) -> Self { let num_words = capacity.div_ceil(64); - BitVec { data: vec![0; num_words] } + Self { data: vec![0; num_words] } } pub fn set(&mut self, index: usize) { diff --git a/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs b/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs index 214835283e..e92b11ce35 100644 --- a/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs +++ b/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs @@ -15,17 +15,17 @@ enum CustomValue { impl ToTokens for CustomValue { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { match self { - CustomValue::String(x) => x.to_tokens(tokens), - CustomValue::Integer(x) => { + Self::String(x) => x.to_tokens(tokens), + Self::Integer(x) => { let x: proc_macro2::TokenStream = format!("{:?}", x).parse().unwrap(); x.to_tokens(tokens) } - CustomValue::Float(x) => { + Self::Float(x) => { let x: proc_macro2::TokenStream = format!("{:?}", x).parse().unwrap(); x.to_tokens(tokens) } - CustomValue::Boolean(x) => x.to_tokens(tokens), - CustomValue::Array(x) => quote! { [ #( #x ),* ] }.to_tokens(tokens), + Self::Boolean(x) => x.to_tokens(tokens), + Self::Array(x) => quote! { [ #( #x ),* ] }.to_tokens(tokens), } } } @@ -33,11 +33,11 @@ impl ToTokens for CustomValue { impl From for CustomValue { fn from(value: Value) -> Self { match value { - Value::String(x) => CustomValue::String(x), - Value::Integer(x) => CustomValue::Integer(x), - Value::Float(x) => CustomValue::Float(x), - Value::Boolean(x) => CustomValue::Boolean(x), - Value::Array(x) => CustomValue::Array(x.into_iter().map(|x| x.into()).collect()), + Value::String(x) => Self::String(x), + Value::Integer(x) => Self::Integer(x), + Value::Float(x) => Self::Float(x), + Value::Boolean(x) => Self::Boolean(x), + Value::Array(x) => Self::Array(x.into_iter().map(|x| x.into()).collect()), _ => panic!("Unsupported data type"), } } diff --git a/node-graph/graph-craft/src/document.rs b/node-graph/graph-craft/src/document.rs index 6ef88e9992..b5bc727359 100644 --- a/node-graph/graph-craft/src/document.rs +++ b/node-graph/graph-craft/src/document.rs @@ -216,7 +216,7 @@ pub enum DocumentNodeMetadata { impl DocumentNodeMetadata { pub fn ty(&self) -> Type { match self { - DocumentNodeMetadata::DocumentNodePath => concrete!(Vec), + Self::DocumentNodePath => concrete!(Vec), } } } @@ -240,45 +240,45 @@ impl NodeInput { } fn map_ids(&mut self, f: impl Fn(NodeId) -> NodeId) { - if let &mut NodeInput::Node { node_id, output_index } = self { - *self = NodeInput::Node { node_id: f(node_id), output_index } + if let &mut Self::Node { node_id, output_index } = self { + *self = Self::Node { node_id: f(node_id), output_index } } } pub fn is_exposed(&self) -> bool { match self { - NodeInput::Node { .. } => true, - NodeInput::Value { exposed, .. } => *exposed, - NodeInput::Import { .. } => true, - NodeInput::Inline(_) => false, - NodeInput::Scope(_) => false, - NodeInput::Reflection(_) => false, + Self::Node { .. } => true, + Self::Value { exposed, .. } => *exposed, + Self::Import { .. } => true, + Self::Inline(_) => false, + Self::Scope(_) => false, + Self::Reflection(_) => false, } } pub fn ty(&self) -> Type { match self { - NodeInput::Node { .. } => unreachable!("ty() called on NodeInput::Node"), - NodeInput::Value { tagged_value, .. } => tagged_value.ty(), - NodeInput::Import { import_type, .. } => import_type.clone(), - NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"), - NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"), - NodeInput::Reflection(_) => concrete!(Metadata), + Self::Node { .. } => unreachable!("ty() called on NodeInput::Node"), + Self::Value { tagged_value, .. } => tagged_value.ty(), + Self::Import { import_type, .. } => import_type.clone(), + Self::Inline(_) => panic!("ty() called on NodeInput::Inline"), + Self::Scope(_) => panic!("ty() called on NodeInput::Scope"), + Self::Reflection(_) => concrete!(Metadata), } } pub fn as_value(&self) -> Option<&TaggedValue> { - if let NodeInput::Value { tagged_value, .. } = self { Some(tagged_value) } else { None } + if let Self::Value { tagged_value, .. } = self { Some(tagged_value) } else { None } } pub fn as_value_mut(&mut self) -> Option> { - if let NodeInput::Value { tagged_value, .. } = self { Some(tagged_value.inner_mut()) } else { None } + if let Self::Value { tagged_value, .. } = self { Some(tagged_value.inner_mut()) } else { None } } pub fn as_non_exposed_value(&self) -> Option<&TaggedValue> { - if let NodeInput::Value { tagged_value, exposed: false } = self { Some(tagged_value) } else { None } + if let Self::Value { tagged_value, exposed: false } = self { Some(tagged_value) } else { None } } pub fn as_node(&self) -> Option { - if let NodeInput::Node { node_id, .. } = self { Some(*node_id) } else { None } + if let Self::Node { node_id, .. } = self { Some(*node_id) } else { None } } } @@ -335,28 +335,28 @@ impl Default for DocumentNodeImplementation { impl DocumentNodeImplementation { pub fn get_network(&self) -> Option<&NodeNetwork> { match self { - DocumentNodeImplementation::Network(n) => Some(n), + Self::Network(n) => Some(n), _ => None, } } pub fn get_network_mut(&mut self) -> Option<&mut NodeNetwork> { match self { - DocumentNodeImplementation::Network(n) => Some(n), + Self::Network(n) => Some(n), _ => None, } } pub fn get_proto_node(&self) -> Option<&ProtoNodeIdentifier> { match self { - DocumentNodeImplementation::ProtoNode(p) => Some(p), + Self::ProtoNode(p) => Some(p), _ => None, } } pub fn output_count(&self) -> usize { match self { - DocumentNodeImplementation::Network(network) => network.exports.len(), + Self::Network(network) => network.exports.len(), _ => 1, } } diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 48f15c0422..5ad6c5866a 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -265,14 +265,14 @@ tagged_value! { impl TaggedValue { pub fn to_primitive_string(&self) -> String { match self { - TaggedValue::None => "()".to_string(), - TaggedValue::String(x) => format!("\"{x}\""), - TaggedValue::U32(x) => x.to_string() + "_u32", - TaggedValue::U64(x) => x.to_string() + "_u64", - TaggedValue::F32(x) => x.to_string() + "_f32", - TaggedValue::F64(x) => x.to_string() + "_f64", - TaggedValue::Bool(x) => x.to_string(), - TaggedValue::BlendMode(x) => "BlendMode::".to_string() + &x.to_string(), + Self::None => "()".to_string(), + Self::String(x) => format!("\"{x}\""), + Self::U32(x) => x.to_string() + "_u32", + Self::U64(x) => x.to_string() + "_u64", + Self::F32(x) => x.to_string() + "_f32", + Self::F64(x) => x.to_string() + "_f64", + Self::Bool(x) => x.to_string(), + Self::BlendMode(x) => "BlendMode::".to_string() + &x.to_string(), _ => panic!("Cannot convert to primitive string"), } } @@ -358,31 +358,31 @@ impl TaggedValue { // TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types // Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned. let ty = match internal_id { - x if x == TypeId::of::<()>() => TaggedValue::None, - x if x == TypeId::of::() => TaggedValue::String(string.into()), - x if x == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::F64).ok()?, - x if x == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::F32).ok()?, - x if x == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::U64).ok()?, - x if x == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::U32).ok()?, - x if x == TypeId::of::() => to_dvec2(string).map(TaggedValue::DVec2)?, - x if x == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?, - x if x == TypeId::of::>() => to_color(string).map(|color| TaggedValue::Color(Table::new_from_element(color)))?, - x if x == TypeId::of::() => to_color(string).map(TaggedValue::ColorNotInTable)?, - x if x == TypeId::of::>() => TaggedValue::ColorNotInTable(to_color(string)?), - x if x == TypeId::of::() => to_color(string).map(|color| TaggedValue::Fill(Fill::solid(color)))?, - x if x == TypeId::of::() => to_reference_point(string).map(TaggedValue::ReferencePoint)?, + x if x == TypeId::of::<()>() => Self::None, + x if x == TypeId::of::() => Self::String(string.into()), + x if x == TypeId::of::() => FromStr::from_str(string).map(Self::F64).ok()?, + x if x == TypeId::of::() => FromStr::from_str(string).map(Self::F32).ok()?, + x if x == TypeId::of::() => FromStr::from_str(string).map(Self::U64).ok()?, + x if x == TypeId::of::() => FromStr::from_str(string).map(Self::U32).ok()?, + x if x == TypeId::of::() => to_dvec2(string).map(Self::DVec2)?, + x if x == TypeId::of::() => FromStr::from_str(string).map(Self::Bool).ok()?, + x if x == TypeId::of::>() => to_color(string).map(|color| Self::Color(Table::new_from_element(color)))?, + x if x == TypeId::of::() => to_color(string).map(Self::ColorNotInTable)?, + x if x == TypeId::of::>() => Self::ColorNotInTable(to_color(string)?), + x if x == TypeId::of::() => to_color(string).map(|color| Self::Fill(Fill::solid(color)))?, + x if x == TypeId::of::() => to_reference_point(string).map(Self::ReferencePoint)?, _ => return None, }; Some(ty) } - Type::Fn(_, output) => TaggedValue::from_primitive_string(string, output), - Type::Future(fut) => TaggedValue::from_primitive_string(string, fut), + Type::Fn(_, output) => Self::from_primitive_string(string, output), + Type::Future(fut) => Self::from_primitive_string(string, fut), } } pub fn to_u32(&self) -> u32 { match self { - TaggedValue::U32(x) => *x, + Self::U32(x) => *x, _ => panic!("Passed value is not of type u32"), } } @@ -391,12 +391,12 @@ impl TaggedValue { impl Display for TaggedValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - TaggedValue::String(x) => f.write_str(x), - TaggedValue::U32(x) => f.write_fmt(format_args!("{x}")), - TaggedValue::U64(x) => f.write_fmt(format_args!("{x}")), - TaggedValue::F32(x) => f.write_fmt(format_args!("{x}")), - TaggedValue::F64(x) => f.write_fmt(format_args!("{x}")), - TaggedValue::Bool(x) => f.write_fmt(format_args!("{x}")), + Self::String(x) => f.write_str(x), + Self::U32(x) => f.write_fmt(format_args!("{x}")), + Self::U64(x) => f.write_fmt(format_args!("{x}")), + Self::F32(x) => f.write_fmt(format_args!("{x}")), + Self::F64(x) => f.write_fmt(format_args!("{x}")), + Self::Bool(x) => f.write_fmt(format_args!("{x}")), _ => panic!("Cannot convert to string"), } } @@ -430,8 +430,8 @@ impl<'i, T: 'i + AsRef + Sync + Send, U: 'i + StaticType + Sync + Send> Node< } impl + Sync + Send, U: Sync + Send> UpcastAsRefNode { - pub const fn new(value: T) -> UpcastAsRefNode { - UpcastAsRefNode(value, PhantomData) + pub const fn new(value: T) -> Self { + Self(value, PhantomData) } } diff --git a/node-graph/graph-craft/src/proto.rs b/node-graph/graph-craft/src/proto.rs index 1a18371dd6..e923e45e90 100644 --- a/node-graph/graph-craft/src/proto.rs +++ b/node-graph/graph-craft/src/proto.rs @@ -117,9 +117,9 @@ impl Hash for ConstructionArgs { impl ConstructionArgs { pub fn new_function_args(&self) -> Vec { match self { - ConstructionArgs::Nodes(nodes) => nodes.iter().map(|n| format!("n{:0x}", n.0)).collect(), - ConstructionArgs::Value(value) => vec![value.to_primitive_string()], - ConstructionArgs::Inline(inline) => vec![inline.expr.clone()], + Self::Nodes(nodes) => nodes.iter().map(|n| format!("n{:0x}", n.0)).collect(), + Self::Value(value) => vec![value.to_primitive_string()], + Self::Inline(inline) => vec![inline.expr.clone()], } } } @@ -223,7 +223,7 @@ impl ProtoNetwork { pub fn example() -> (Self, NodeId, ProtoNode) { let node_id = NodeId(1); let proto_node = ProtoNode::default(); - let proto_network = ProtoNetwork { + let proto_network = Self { inputs: vec![node_id], output: node_id, nodes: vec![(node_id, proto_node.clone())], @@ -561,11 +561,11 @@ impl Debug for GraphErrorType { // TODO: format with the document graph context so the input index is the same as in the graph UI. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - GraphErrorType::NodeNotFound(id) => write!(f, "Input node {id} is not present in the typing context"), - GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"), - GraphErrorType::NoImplementations => write!(f, "No implementations found"), - GraphErrorType::NoConstructor => write!(f, "No construct found for node"), - GraphErrorType::InvalidImplementations { inputs, error_inputs } => { + Self::NodeNotFound(id) => write!(f, "Input node {id} is not present in the typing context"), + Self::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"), + Self::NoImplementations => write!(f, "No implementations found"), + Self::NoConstructor => write!(f, "No construct found for node"), + Self::InvalidImplementations { inputs, error_inputs } => { let format_error = |(index, (found, expected)): &(usize, (Type, Type))| { let index = index + 1; format!( @@ -598,7 +598,7 @@ impl Debug for GraphErrorType { " ) } - GraphErrorType::MultipleImplementations { inputs, valid } => write!(f, "Multiple implementations found ({inputs}):\n{valid:#?}"), + Self::MultipleImplementations { inputs, valid } => write!(f, "Multiple implementations found ({inputs}):\n{valid:#?}"), } } } diff --git a/node-graph/graph-craft/src/wasm_application_io.rs b/node-graph/graph-craft/src/wasm_application_io.rs index 9a956d52b6..421021c08a 100644 --- a/node-graph/graph-craft/src/wasm_application_io.rs +++ b/node-graph/graph-craft/src/wasm_application_io.rs @@ -166,7 +166,7 @@ impl WasmApplicationIo { } unsafe impl StaticType for WasmApplicationIo { - type Static = WasmApplicationIo; + type Static = Self; } impl<'a> From<&'a WasmEditorApi> for &'a WasmApplicationIo { @@ -355,5 +355,5 @@ impl Default for EditorPreferences { } unsafe impl StaticType for EditorPreferences { - type Static = EditorPreferences; + type Static = Self; } diff --git a/node-graph/graphene-cli/src/export.rs b/node-graph/graphene-cli/src/export.rs index daf8172386..b565a783af 100644 --- a/node-graph/graphene-cli/src/export.rs +++ b/node-graph/graphene-cli/src/export.rs @@ -21,7 +21,7 @@ pub fn detect_file_type(path: &Path) -> Result { Some("svg") => Ok(FileType::Svg), Some("png") => Ok(FileType::Png), Some("jpg" | "jpeg") => Ok(FileType::Jpg), - _ => Err(format!("Unsupported file extension. Supported formats: .svg, .png, .jpg")), + _ => Err("Unsupported file extension. Supported formats: .svg, .png, .jpg".to_string()), } } diff --git a/node-graph/interpreted-executor/src/dynamic_executor.rs b/node-graph/interpreted-executor/src/dynamic_executor.rs index bfa097ea1a..709944c62d 100644 --- a/node-graph/interpreted-executor/src/dynamic_executor.rs +++ b/node-graph/interpreted-executor/src/dynamic_executor.rs @@ -169,10 +169,10 @@ pub enum IntrospectError { impl std::fmt::Display for IntrospectError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - IntrospectError::PathNotFound(path) => write!(f, "Path not found: {path:?}"), - IntrospectError::ProtoNodeNotFound(id) => write!(f, "ProtoNode not found: {id:?}"), - IntrospectError::NoData => write!(f, "No data found for this node"), - IntrospectError::RuntimeNotReady => write!(f, "Node runtime is not ready"), + Self::PathNotFound(path) => write!(f, "Path not found: {path:?}"), + Self::ProtoNodeNotFound(id) => write!(f, "ProtoNode not found: {id:?}"), + Self::NoData => write!(f, "No data found for this node"), + Self::RuntimeNotReady => write!(f, "Node runtime is not ready"), } } } @@ -204,8 +204,8 @@ pub struct BorrowTree { } impl BorrowTree { - pub async fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result { - let mut nodes = BorrowTree::default(); + pub async fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result { + let mut nodes = Self::default(); for (id, node) in proto_network.nodes { nodes.push_node(id, node, typing_context).await? } diff --git a/node-graph/libraries/application-io/src/lib.rs b/node-graph/libraries/application-io/src/lib.rs index cf0d9edc58..e39513086c 100644 --- a/node-graph/libraries/application-io/src/lib.rs +++ b/node-graph/libraries/application-io/src/lib.rs @@ -36,7 +36,7 @@ impl Hash for SurfaceFrame { } unsafe impl StaticType for SurfaceFrame { - type Static = SurfaceFrame; + type Static = Self; } pub trait Size { @@ -90,7 +90,7 @@ impl PartialEq for ImageTexture { } unsafe impl StaticType for ImageTexture { - type Static = ImageTexture; + type Static = Self; } #[cfg(feature = "wgpu")] @@ -129,7 +129,7 @@ impl Size for SurfaceHandle { } unsafe impl StaticType for SurfaceHandle { - type Static = SurfaceHandle; + type Static = Self; } #[derive(Clone, Debug, PartialEq)] @@ -139,7 +139,7 @@ pub struct SurfaceHandleFrame { } unsafe impl StaticType for SurfaceHandleFrame { - type Static = SurfaceHandleFrame; + type Static = Self; } #[cfg(feature = "wasm")] diff --git a/node-graph/libraries/core-types/src/context.rs b/node-graph/libraries/core-types/src/context.rs index 2ee87a393b..832b5c70e3 100644 --- a/node-graph/libraries/core-types/src/context.rs +++ b/node-graph/libraries/core-types/src/context.rs @@ -430,7 +430,7 @@ impl Hash for OwnedContextImpl { impl OwnedContextImpl { #[track_caller] pub fn from(value: T) -> Self { - OwnedContextImpl::from_flags(value, ContextFeatures::all()) + Self::from_flags(value, ContextFeatures::all()) } #[track_caller] @@ -448,7 +448,7 @@ impl OwnedContextImpl { }) .flatten(); - OwnedContextImpl { + Self { footprint, varargs: None, parent, @@ -460,7 +460,7 @@ impl OwnedContextImpl { } pub const fn empty() -> Self { - OwnedContextImpl { + Self { footprint: None, varargs: None, parent: None, diff --git a/node-graph/libraries/core-types/src/generic.rs b/node-graph/libraries/core-types/src/generic.rs index 055c0cb53d..09bfb54662 100644 --- a/node-graph/libraries/core-types/src/generic.rs +++ b/node-graph/libraries/core-types/src/generic.rs @@ -12,6 +12,6 @@ impl<'i, T: Fn(I) -> O + 'i, O: 'i, I: 'i> Node<'i, I> for FnNode { impl O, I, O> FnNode { pub fn new(f: T) -> Self { - FnNode(f, PhantomData) + Self(f, PhantomData) } } diff --git a/node-graph/libraries/core-types/src/math/bbox.rs b/node-graph/libraries/core-types/src/math/bbox.rs index f12ecef250..f717782aab 100644 --- a/node-graph/libraries/core-types/src/math/bbox.rs +++ b/node-graph/libraries/core-types/src/math/bbox.rs @@ -23,30 +23,30 @@ impl AxisAlignedBbox { point.x >= self.start.x && point.x <= self.end.x && point.y >= self.start.y && point.y <= self.end.y } - pub fn intersects(&self, other: &AxisAlignedBbox) -> bool { + pub fn intersects(&self, other: &Self) -> bool { other.start.x <= self.end.x && other.end.x >= self.start.x && other.start.y <= self.end.y && other.end.y >= self.start.y } - pub fn union(&self, other: &AxisAlignedBbox) -> AxisAlignedBbox { - AxisAlignedBbox { + pub fn union(&self, other: &Self) -> Self { + Self { start: DVec2::new(self.start.x.min(other.start.x), self.start.y.min(other.start.y)), end: DVec2::new(self.end.x.max(other.end.x), self.end.y.max(other.end.y)), } } - pub fn union_non_empty(&self, other: &AxisAlignedBbox) -> Option { + pub fn union_non_empty(&self, other: &Self) -> Option { match (self.size() == DVec2::ZERO, other.size() == DVec2::ZERO) { (true, true) => None, (true, _) => Some(other.clone()), (_, true) => Some(self.clone()), - _ => Some(AxisAlignedBbox { + _ => Some(Self { start: DVec2::new(self.start.x.min(other.start.x), self.start.y.min(other.start.y)), end: DVec2::new(self.end.x.max(other.end.x), self.end.y.max(other.end.y)), }), } } - pub fn intersect(&self, other: &AxisAlignedBbox) -> AxisAlignedBbox { - AxisAlignedBbox { + pub fn intersect(&self, other: &Self) -> Self { + Self { start: DVec2::new(self.start.x.max(other.start.x), self.start.y.max(other.start.y)), end: DVec2::new(self.end.x.min(other.end.x), self.end.y.min(other.end.y)), } diff --git a/node-graph/libraries/core-types/src/math/polynomial.rs b/node-graph/libraries/core-types/src/math/polynomial.rs index 392fee51e4..0e18d6a001 100644 --- a/node-graph/libraries/core-types/src/math/polynomial.rs +++ b/node-graph/libraries/core-types/src/math/polynomial.rs @@ -14,13 +14,13 @@ impl Polynomial { /// Create a new polynomial from the coefficients given in the array. /// /// The coefficient for nth degree is at the nth index in array. Therefore the order of coefficients are reversed than the usual order for writing polynomials mathematically. - pub fn new(coefficients: [f64; N]) -> Polynomial { - Polynomial { coefficients } + pub fn new(coefficients: [f64; N]) -> Self { + Self { coefficients } } /// Create a polynomial where all its coefficients are zero. - pub fn zero() -> Polynomial { - Polynomial { coefficients: [0.; N] } + pub fn zero() -> Self { + Self { coefficients: [0.; N] } } /// Return an immutable reference to the coefficients. @@ -78,7 +78,7 @@ impl Polynomial { } /// Computes the polynomial's derivative. - pub fn derivative(&self) -> Polynomial { + pub fn derivative(&self) -> Self { let mut ans = *self; ans.derivative_mut(); ans @@ -87,7 +87,7 @@ impl Polynomial { /// Computes the antiderivative at `C = 0`. /// /// Returns `None` if the polynomial is not big enough to accommodate the extra degree. - pub fn antiderivative(&self) -> Option> { + pub fn antiderivative(&self) -> Option { let mut ans = *self; ans.antiderivative_mut()?; Some(ans) @@ -126,8 +126,8 @@ impl Display for Polynomial { } } -impl AddAssign<&Polynomial> for Polynomial { - fn add_assign(&mut self, rhs: &Polynomial) { +impl AddAssign<&Self> for Polynomial { + fn add_assign(&mut self, rhs: &Self) { self.coefficients.iter_mut().zip(rhs.coefficients.iter()).for_each(|(a, b)| *a += b); } } @@ -153,16 +153,16 @@ impl Neg for &Polynomial { } impl Neg for Polynomial { - type Output = Polynomial; + type Output = Self; - fn neg(mut self) -> Polynomial { + fn neg(mut self) -> Self { self.coefficients.iter_mut().for_each(|x| *x = -*x); self } } -impl SubAssign<&Polynomial> for Polynomial { - fn sub_assign(&mut self, rhs: &Polynomial) { +impl SubAssign<&Self> for Polynomial { + fn sub_assign(&mut self, rhs: &Self) { self.coefficients.iter_mut().zip(rhs.coefficients.iter()).for_each(|(a, b)| *a -= b); } } @@ -177,8 +177,8 @@ impl Sub for &Polynomial { } } -impl MulAssign<&Polynomial> for Polynomial { - fn mul_assign(&mut self, rhs: &Polynomial) { +impl MulAssign<&Self> for Polynomial { + fn mul_assign(&mut self, rhs: &Self) { for i in (0..N).rev() { self.coefficients[i] = self.coefficients[i] * rhs.coefficients[0]; for j in 0..i { diff --git a/node-graph/libraries/core-types/src/math/quad.rs b/node-graph/libraries/core-types/src/math/quad.rs index 8586bba1cf..dd3ffd6a7c 100644 --- a/node-graph/libraries/core-types/src/math/quad.rs +++ b/node-graph/libraries/core-types/src/math/quad.rs @@ -87,7 +87,7 @@ impl Quad { /// Expand a quad by a certain amount on all sides. /// /// Not currently very optimized - pub fn inflate(&self, offset: f64) -> Quad { + pub fn inflate(&self, offset: f64) -> Self { let offset = |index_before, index, index_after| { let [point_before, point, point_after]: [DVec2; 3] = [self.0[index_before], self.0[index], self.0[index_after]]; let [line_in, line_out] = [point - point_before, point_after - point]; @@ -129,7 +129,7 @@ impl Quad { (t.is_finite() && u.is_finite()).then(|| a + t * a_direction) } - pub fn intersects(&self, other: Quad) -> bool { + pub fn intersects(&self, other: Self) -> bool { let intersects = self .all_edges() .into_iter() diff --git a/node-graph/libraries/core-types/src/math/rect.rs b/node-graph/libraries/core-types/src/math/rect.rs index 4998eddb3a..31dff2aa00 100644 --- a/node-graph/libraries/core-types/src/math/rect.rs +++ b/node-graph/libraries/core-types/src/math/rect.rs @@ -114,6 +114,6 @@ impl std::ops::IndexMut for Rect { impl From for Quad { fn from(val: Rect) -> Self { - Quad::from_box(val.0) + Self::from_box(val.0) } } diff --git a/node-graph/libraries/core-types/src/misc.rs b/node-graph/libraries/core-types/src/misc.rs index 45012110d9..f9c2baac62 100644 --- a/node-graph/libraries/core-types/src/misc.rs +++ b/node-graph/libraries/core-types/src/misc.rs @@ -53,11 +53,11 @@ use glam::DVec2; impl Clampable for DVec2 { #[inline(always)] fn clamp_hard_min(self, min: f64) -> Self { - self.max(DVec2::splat(min)) + self.max(Self::splat(min)) } #[inline(always)] fn clamp_hard_max(self, max: f64) -> Self { - self.min(DVec2::splat(max)) + self.min(Self::splat(max)) } } diff --git a/node-graph/libraries/core-types/src/ops.rs b/node-graph/libraries/core-types/src/ops.rs index 9221f6dc6d..6e84c88151 100644 --- a/node-graph/libraries/core-types/src/ops.rs +++ b/node-graph/libraries/core-types/src/ops.rs @@ -73,8 +73,8 @@ impl + Send> Convert, ()> for Table { } } -impl Convert for DVec2 { - async fn convert(self, _: Footprint, _: ()) -> DVec2 { +impl Convert for DVec2 { + async fn convert(self, _: Footprint, _: ()) -> Self { self } } diff --git a/node-graph/libraries/core-types/src/table.rs b/node-graph/libraries/core-types/src/table.rs index 4a814aaf58..bbd15c5613 100644 --- a/node-graph/libraries/core-types/src/table.rs +++ b/node-graph/libraries/core-types/src/table.rs @@ -54,7 +54,7 @@ impl Table { self.source_node_id.push(row.source_node_id); } - pub fn extend(&mut self, table: Table) { + pub fn extend(&mut self, table: Self) { self.element.extend(table.element); self.transform.extend(table.transform); self.alpha_blending.extend(table.alpha_blending); diff --git a/node-graph/libraries/core-types/src/transform.rs b/node-graph/libraries/core-types/src/transform.rs index bf85f00e76..604d2aca2f 100644 --- a/node-graph/libraries/core-types/src/transform.rs +++ b/node-graph/libraries/core-types/src/transform.rs @@ -139,7 +139,7 @@ impl Footprint { impl From<()> for Footprint { fn from(_: ()) -> Self { - Footprint::default() + Self::default() } } diff --git a/node-graph/libraries/core-types/src/types.rs b/node-graph/libraries/core-types/src/types.rs index f964e1914b..1de24ae925 100644 --- a/node-graph/libraries/core-types/src/types.rs +++ b/node-graph/libraries/core-types/src/types.rs @@ -139,17 +139,17 @@ impl From for ProtoNodeIdentifier { impl From<&'static str> for ProtoNodeIdentifier { fn from(s: &'static str) -> Self { - ProtoNodeIdentifier { name: Cow::Borrowed(s) } + Self { name: Cow::Borrowed(s) } } } impl ProtoNodeIdentifier { pub const fn new(name: &'static str) -> Self { - ProtoNodeIdentifier { name: Cow::Borrowed(name) } + Self { name: Cow::Borrowed(name) } } pub const fn with_owned_string(name: String) -> Self { - ProtoNodeIdentifier { name: Cow::Owned(name) } + Self { name: Cow::Owned(name) } } } @@ -244,9 +244,9 @@ pub enum Type { /// A wrapper around the Rust type id for any concrete Rust type. Allows us to do equality comparisons, like checking if a String == a String. Concrete(TypeDescriptor), /// Runtime type information for a function. Given some input, gives some output. - Fn(Box, Box), + Fn(Box, Box), /// Represents a future which promises to return the inner type. - Future(Box), + Future(Box), } impl Default for Type { @@ -261,45 +261,45 @@ unsafe impl dyn_any::StaticType for Type { impl Type { pub fn is_generic(&self) -> bool { - matches!(self, Type::Generic(_)) + matches!(self, Self::Generic(_)) } pub fn is_concrete(&self) -> bool { - matches!(self, Type::Concrete(_)) + matches!(self, Self::Concrete(_)) } pub fn is_fn(&self) -> bool { - matches!(self, Type::Fn(_, _)) + matches!(self, Self::Fn(_, _)) } pub fn is_value(&self) -> bool { - matches!(self, Type::Fn(_, _) | Type::Concrete(_)) + matches!(self, Self::Fn(_, _) | Self::Concrete(_)) } pub fn is_unit(&self) -> bool { - matches!(self, Type::Fn(_, _) | Type::Concrete(_)) + matches!(self, Self::Fn(_, _) | Self::Concrete(_)) } pub fn is_generic_or_fn(&self) -> bool { - matches!(self, Type::Fn(_, _) | Type::Generic(_)) + matches!(self, Self::Fn(_, _) | Self::Generic(_)) } - pub fn fn_input(&self) -> Option<&Type> { + pub fn fn_input(&self) -> Option<&Self> { match self { - Type::Fn(first, _) => Some(first), + Self::Fn(first, _) => Some(first), _ => None, } } - pub fn fn_output(&self) -> Option<&Type> { + pub fn fn_output(&self) -> Option<&Self> { match self { - Type::Fn(_, second) => Some(second), + Self::Fn(_, second) => Some(second), _ => None, } } - pub fn function(input: &Type, output: &Type) -> Type { - Type::Fn(Box::new(input.clone()), Box::new(output.clone())) + pub fn function(input: &Self, output: &Self) -> Self { + Self::Fn(Box::new(input.clone()), Box::new(output.clone())) } } @@ -332,30 +332,27 @@ impl Type { } } - pub fn nested_type(&self) -> &Type { + pub fn nested_type(&self) -> &Self { match self { - Self::Generic(_) => self, - Self::Concrete(_) => self, - Self::Fn(_, output) => output.nested_type(), - Self::Future(output) => output.nested_type(), + Self::Generic(_) | Self::Concrete(_) => self, + Self::Fn(_, output) | Self::Future(output) => output.nested_type(), } } - pub fn replace_nested(&mut self, f: impl Fn(&Type) -> Option) -> Option { + pub fn replace_nested(&mut self, f: impl Fn(&Self) -> Option) -> Option { if let Some(replacement) = f(self) { return Some(std::mem::replace(self, replacement)); } match self { Self::Generic(_) => None, Self::Concrete(_) => None, - Self::Fn(_, output) => output.replace_nested(f), - Self::Future(output) => output.replace_nested(f), + Self::Fn(_, output) | Self::Future(output) => output.replace_nested(f), } } pub fn to_cow_string(&self) -> Cow<'static, str> { match self { - Type::Generic(name) => name.clone(), + Self::Generic(name) => name.clone(), _ => Cow::Owned(self.to_string()), } } @@ -391,10 +388,10 @@ impl std::fmt::Debug for Type { impl std::fmt::Display for Type { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let text = match self { - Type::Generic(name) => name.to_string(), - Type::Concrete(ty) => format_type(&ty.name), - Type::Fn(call_arg, return_value) => format!("{return_value} called with {call_arg}"), - Type::Future(ty) => ty.to_string(), + Self::Generic(name) => name.to_string(), + Self::Concrete(ty) => format_type(&ty.name), + Self::Fn(call_arg, return_value) => format!("{return_value} called with {call_arg}"), + Self::Future(ty) => ty.to_string(), }; let text = make_type_user_readable(&text); write!(f, "{text}") diff --git a/node-graph/libraries/core-types/src/value.rs b/node-graph/libraries/core-types/src/value.rs index 3cf1c0f6a6..d909c0e641 100644 --- a/node-graph/libraries/core-types/src/value.rs +++ b/node-graph/libraries/core-types/src/value.rs @@ -25,14 +25,14 @@ impl<'i, T: 'i, I> Node<'i, I> for ValueNode { } impl ValueNode { - pub const fn new(value: T) -> ValueNode { - ValueNode(value) + pub const fn new(value: T) -> Self { + Self(value) } } impl From for ValueNode { fn from(value: T) -> Self { - ValueNode::new(value) + Self::new(value) } } @@ -48,8 +48,8 @@ impl<'i, T: 'i + AsRef, U: 'i> Node<'i, ()> for AsRefNode { } impl, U> AsRefNode { - pub const fn new(value: T) -> AsRefNode { - AsRefNode(value, PhantomData) + pub const fn new(value: T) -> Self { + Self(value, PhantomData) } } @@ -65,8 +65,8 @@ impl<'i, T: 'i> Node<'i, ()> for RefCellMutNode { } impl RefCellMutNode { - pub const fn new(value: T) -> RefCellMutNode { - RefCellMutNode(RefCell::new(value)) + pub const fn new(value: T) -> Self { + Self(RefCell::new(value)) } } @@ -82,8 +82,8 @@ impl<'i, T: Default + 'i, I> Node<'i, I> for OnceCellNode { } impl OnceCellNode { - pub const fn new(value: T) -> OnceCellNode { - OnceCellNode(Cell::new(value)) + pub const fn new(value: T) -> Self { + Self(Cell::new(value)) } } @@ -99,14 +99,14 @@ impl<'i, T: Clone + 'i, I> Node<'i, I> for ClonedNode { } impl ClonedNode { - pub const fn new(value: T) -> ClonedNode { - ClonedNode(value) + pub const fn new(value: T) -> Self { + Self(value) } } impl From for ClonedNode { fn from(value: T) -> Self { - ClonedNode::new(value) + Self::new(value) } } @@ -127,8 +127,8 @@ impl<'i, T: Clone + 'i> Node<'i, ()> for DebugClonedNode { } impl DebugClonedNode { - pub const fn new(value: T) -> DebugClonedNode { - DebugClonedNode(value) + pub const fn new(value: T) -> Self { + Self(value) } } @@ -144,8 +144,8 @@ impl<'i, T: Copy + 'i, I> Node<'i, I> for CopiedNode { } impl CopiedNode { - pub const fn new(value: T) -> CopiedNode { - CopiedNode(value) + pub const fn new(value: T) -> Self { + Self(value) } } @@ -177,7 +177,7 @@ impl<'i, T: 'i> Node<'i, T> for ForgetNode { impl ForgetNode { pub const fn new() -> Self { - ForgetNode + Self } } diff --git a/node-graph/libraries/graphic-types/src/graphic.rs b/node-graph/libraries/graphic-types/src/graphic.rs index d5db099745..b87eced2f5 100644 --- a/node-graph/libraries/graphic-types/src/graphic.rs +++ b/node-graph/libraries/graphic-types/src/graphic.rs @@ -17,7 +17,7 @@ pub type Vector = vector_types::Vector>>; /// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax. #[derive(Clone, Debug, Hash, PartialEq, DynAny, serde::Serialize, serde::Deserialize)] pub enum Graphic { - Graphic(Table), + Graphic(Table), Vector(Table), RasterCPU(Table>), RasterGPU(Table>), @@ -32,21 +32,21 @@ impl Default for Graphic { } // Graphic -impl From> for Graphic { - fn from(graphic: Table) -> Self { - Graphic::Graphic(graphic) +impl From> for Graphic { + fn from(graphic: Table) -> Self { + Self::Graphic(graphic) } } // Vector impl From for Graphic { fn from(vector: Vector) -> Self { - Graphic::Vector(Table::new_from_element(vector)) + Self::Vector(Table::new_from_element(vector)) } } impl From> for Graphic { fn from(vector: Table) -> Self { - Graphic::Vector(vector) + Self::Vector(vector) } } @@ -55,12 +55,12 @@ impl From> for Graphic { // Raster impl From> for Graphic { fn from(raster: Raster) -> Self { - Graphic::RasterCPU(Table::new_from_element(raster)) + Self::RasterCPU(Table::new_from_element(raster)) } } impl From>> for Graphic { fn from(raster: Table>) -> Self { - Graphic::RasterCPU(raster) + Self::RasterCPU(raster) } } // Note: Table conversions handled by blanket impl in gcore @@ -68,12 +68,12 @@ impl From>> for Graphic { // Raster impl From> for Graphic { fn from(raster: Raster) -> Self { - Graphic::RasterGPU(Table::new_from_element(raster)) + Self::RasterGPU(Table::new_from_element(raster)) } } impl From>> for Graphic { fn from(raster: Table>) -> Self { - Graphic::RasterGPU(raster) + Self::RasterGPU(raster) } } // Note: Table conversions handled by blanket impl in gcore @@ -81,12 +81,12 @@ impl From>> for Graphic { // Color impl From for Graphic { fn from(color: Color) -> Self { - Graphic::Color(Table::new_from_element(color)) + Self::Color(Table::new_from_element(color)) } } impl From> for Graphic { fn from(color: Table) -> Self { - Graphic::Color(color) + Self::Color(color) } } // Note: Table conversions handled by blanket impl in gcore @@ -94,11 +94,7 @@ impl From> for Graphic { // Option impl From> for Graphic { fn from(color: Option) -> Self { - if let Some(color) = color { - Graphic::Color(Table::new_from_element(color)) - } else { - Graphic::default() - } + if let Some(color) = color { Self::Color(Table::new_from_element(color)) } else { Self::default() } } } // Note: Table conversions handled by blanket impl in gcore @@ -107,12 +103,12 @@ impl From> for Graphic { // GradientStops impl From for Graphic { fn from(gradient: GradientStops) -> Self { - Graphic::Gradient(Table::new_from_element(gradient)) + Self::Gradient(Table::new_from_element(gradient)) } } impl From> for Graphic { fn from(gradient: Table) -> Self { - Graphic::Gradient(gradient) + Self::Gradient(gradient) } } @@ -215,68 +211,68 @@ impl IntoGraphicTable for DAffine2 { // DAffine2 impl From for Graphic { fn from(_: DAffine2) -> Self { - Graphic::default() + Self::default() } } // Note: Table conversions handled by blanket impl in gcore impl Graphic { - pub fn as_graphic(&self) -> Option<&Table> { + pub fn as_graphic(&self) -> Option<&Table> { match self { - Graphic::Graphic(graphic) => Some(graphic), + Self::Graphic(graphic) => Some(graphic), _ => None, } } - pub fn as_graphic_mut(&mut self) -> Option<&mut Table> { + pub fn as_graphic_mut(&mut self) -> Option<&mut Table> { match self { - Graphic::Graphic(graphic) => Some(graphic), + Self::Graphic(graphic) => Some(graphic), _ => None, } } pub fn as_vector(&self) -> Option<&Table> { match self { - Graphic::Vector(vector) => Some(vector), + Self::Vector(vector) => Some(vector), _ => None, } } pub fn as_vector_mut(&mut self) -> Option<&mut Table> { match self { - Graphic::Vector(vector) => Some(vector), + Self::Vector(vector) => Some(vector), _ => None, } } pub fn as_raster(&self) -> Option<&Table>> { match self { - Graphic::RasterCPU(raster) => Some(raster), + Self::RasterCPU(raster) => Some(raster), _ => None, } } pub fn as_raster_mut(&mut self) -> Option<&mut Table>> { match self { - Graphic::RasterCPU(raster) => Some(raster), + Self::RasterCPU(raster) => Some(raster), _ => None, } } pub fn had_clip_enabled(&self) -> bool { match self { - Graphic::Vector(vector) => vector.iter().all(|row| row.alpha_blending.clip), - Graphic::Graphic(graphic) => graphic.iter().all(|row| row.alpha_blending.clip), - Graphic::RasterCPU(raster) => raster.iter().all(|row| row.alpha_blending.clip), - Graphic::RasterGPU(raster) => raster.iter().all(|row| row.alpha_blending.clip), - Graphic::Color(color) => color.iter().all(|row| row.alpha_blending.clip), - Graphic::Gradient(gradient) => gradient.iter().all(|row| row.alpha_blending.clip), + Self::Vector(vector) => vector.iter().all(|row| row.alpha_blending.clip), + Self::Graphic(graphic) => graphic.iter().all(|row| row.alpha_blending.clip), + Self::RasterCPU(raster) => raster.iter().all(|row| row.alpha_blending.clip), + Self::RasterGPU(raster) => raster.iter().all(|row| row.alpha_blending.clip), + Self::Color(color) => color.iter().all(|row| row.alpha_blending.clip), + Self::Gradient(gradient) => gradient.iter().all(|row| row.alpha_blending.clip), } } pub fn can_reduce_to_clip_path(&self) -> bool { match self { - Graphic::Vector(vector) => vector.iter().all(|row| { + Self::Vector(vector) => vector.iter().all(|row| { let style = &row.element.style; let alpha_blending = &row.alpha_blending; (alpha_blending.opacity > 1. - f32::EPSILON) && style.fill().is_opaque() && style.stroke().is_none_or(|stroke| !stroke.has_renderable_stroke()) @@ -289,12 +285,12 @@ impl Graphic { impl BoundingBox for Graphic { fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox { match self { - Graphic::Vector(vector) => vector.bounding_box(transform, include_stroke), - Graphic::RasterCPU(raster) => raster.bounding_box(transform, include_stroke), - Graphic::RasterGPU(raster) => raster.bounding_box(transform, include_stroke), - Graphic::Graphic(graphic) => graphic.bounding_box(transform, include_stroke), - Graphic::Color(color) => color.bounding_box(transform, include_stroke), - Graphic::Gradient(gradient) => gradient.bounding_box(transform, include_stroke), + Self::Vector(vector) => vector.bounding_box(transform, include_stroke), + Self::RasterCPU(raster) => raster.bounding_box(transform, include_stroke), + Self::RasterGPU(raster) => raster.bounding_box(transform, include_stroke), + Self::Graphic(graphic) => graphic.bounding_box(transform, include_stroke), + Self::Color(color) => color.bounding_box(transform, include_stroke), + Self::Gradient(gradient) => gradient.bounding_box(transform, include_stroke), } } } @@ -347,7 +343,7 @@ impl AtIndex for Vec { } } impl AtIndex for Table { - type Output = Table; + type Output = Self; fn at_index(&self, index: usize) -> Option { let mut result_table = Self::default(); diff --git a/node-graph/libraries/no-std-types/src/blending.rs b/node-graph/libraries/no-std-types/src/blending.rs index 747c4ba0a8..b044d2dc4a 100644 --- a/node-graph/libraries/no-std-types/src/blending.rs +++ b/node-graph/libraries/no-std-types/src/blending.rs @@ -54,7 +54,7 @@ impl AlphaBlending { pub fn lerp(&self, other: &Self, t: f32) -> Self { let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t; - AlphaBlending { + Self { opacity: lerp(self.opacity, other.opacity, t), fill: lerp(self.fill, other.fill, t), blend_mode: if t < 0.5 { self.blend_mode } else { other.blend_mode }, @@ -118,7 +118,7 @@ pub enum BlendMode { impl BlendMode { /// All standard blend modes ordered by group. - pub fn list() -> [&'static [BlendMode]; 6] { + pub fn list() -> [&'static [Self]; 6] { use BlendMode::*; [ // Normal group @@ -137,7 +137,7 @@ impl BlendMode { } /// The subset of [`BlendMode::list()`] that is supported by SVG. - pub fn list_svg_subset() -> [&'static [BlendMode]; 6] { + pub fn list_svg_subset() -> [&'static [Self]; 6] { use BlendMode::*; [ // Normal group @@ -168,27 +168,27 @@ impl BlendMode { pub fn to_svg_style_name(&self) -> Option<&'static str> { match self { // Normal group - BlendMode::Normal => Some("normal"), + Self::Normal => Some("normal"), // Darken group - BlendMode::Darken => Some("darken"), - BlendMode::Multiply => Some("multiply"), - BlendMode::ColorBurn => Some("color-burn"), + Self::Darken => Some("darken"), + Self::Multiply => Some("multiply"), + Self::ColorBurn => Some("color-burn"), // Lighten group - BlendMode::Lighten => Some("lighten"), - BlendMode::Screen => Some("screen"), - BlendMode::ColorDodge => Some("color-dodge"), + Self::Lighten => Some("lighten"), + Self::Screen => Some("screen"), + Self::ColorDodge => Some("color-dodge"), // Contrast group - BlendMode::Overlay => Some("overlay"), - BlendMode::SoftLight => Some("soft-light"), - BlendMode::HardLight => Some("hard-light"), + Self::Overlay => Some("overlay"), + Self::SoftLight => Some("soft-light"), + Self::HardLight => Some("hard-light"), // Inversion group - BlendMode::Difference => Some("difference"), - BlendMode::Exclusion => Some("exclusion"), + Self::Difference => Some("difference"), + Self::Exclusion => Some("exclusion"), // Component group - BlendMode::Hue => Some("hue"), - BlendMode::Saturation => Some("saturation"), - BlendMode::Color => Some("color"), - BlendMode::Luminosity => Some("luminosity"), + Self::Hue => Some("hue"), + Self::Saturation => Some("saturation"), + Self::Color => Some("color"), + Self::Luminosity => Some("luminosity"), _ => None, } } @@ -210,41 +210,41 @@ impl Display for BlendMode { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { // Normal group - BlendMode::Normal => write!(f, "Normal"), + Self::Normal => write!(f, "Normal"), // Darken group - BlendMode::Darken => write!(f, "Darken"), - BlendMode::Multiply => write!(f, "Multiply"), - BlendMode::ColorBurn => write!(f, "Color Burn"), - BlendMode::LinearBurn => write!(f, "Linear Burn"), - BlendMode::DarkerColor => write!(f, "Darker Color"), + Self::Darken => write!(f, "Darken"), + Self::Multiply => write!(f, "Multiply"), + Self::ColorBurn => write!(f, "Color Burn"), + Self::LinearBurn => write!(f, "Linear Burn"), + Self::DarkerColor => write!(f, "Darker Color"), // Lighten group - BlendMode::Lighten => write!(f, "Lighten"), - BlendMode::Screen => write!(f, "Screen"), - BlendMode::ColorDodge => write!(f, "Color Dodge"), - BlendMode::LinearDodge => write!(f, "Linear Dodge"), - BlendMode::LighterColor => write!(f, "Lighter Color"), + Self::Lighten => write!(f, "Lighten"), + Self::Screen => write!(f, "Screen"), + Self::ColorDodge => write!(f, "Color Dodge"), + Self::LinearDodge => write!(f, "Linear Dodge"), + Self::LighterColor => write!(f, "Lighter Color"), // Contrast group - BlendMode::Overlay => write!(f, "Overlay"), - BlendMode::SoftLight => write!(f, "Soft Light"), - BlendMode::HardLight => write!(f, "Hard Light"), - BlendMode::VividLight => write!(f, "Vivid Light"), - BlendMode::LinearLight => write!(f, "Linear Light"), - BlendMode::PinLight => write!(f, "Pin Light"), - BlendMode::HardMix => write!(f, "Hard Mix"), + Self::Overlay => write!(f, "Overlay"), + Self::SoftLight => write!(f, "Soft Light"), + Self::HardLight => write!(f, "Hard Light"), + Self::VividLight => write!(f, "Vivid Light"), + Self::LinearLight => write!(f, "Linear Light"), + Self::PinLight => write!(f, "Pin Light"), + Self::HardMix => write!(f, "Hard Mix"), // Inversion group - BlendMode::Difference => write!(f, "Difference"), - BlendMode::Exclusion => write!(f, "Exclusion"), - BlendMode::Subtract => write!(f, "Subtract"), - BlendMode::Divide => write!(f, "Divide"), + Self::Difference => write!(f, "Difference"), + Self::Exclusion => write!(f, "Exclusion"), + Self::Subtract => write!(f, "Subtract"), + Self::Divide => write!(f, "Divide"), // Component group - BlendMode::Hue => write!(f, "Hue"), - BlendMode::Saturation => write!(f, "Saturation"), - BlendMode::Color => write!(f, "Color"), - BlendMode::Luminosity => write!(f, "Luminosity"), + Self::Hue => write!(f, "Hue"), + Self::Saturation => write!(f, "Saturation"), + Self::Color => write!(f, "Color"), + Self::Luminosity => write!(f, "Luminosity"), // Other utility blend modes (hidden from the normal list) - BlendMode::Erase => write!(f, "Erase"), - BlendMode::Restore => write!(f, "Restore"), - BlendMode::MultiplyAlpha => write!(f, "Multiply Alpha"), + Self::Erase => write!(f, "Erase"), + Self::Restore => write!(f, "Restore"), + Self::MultiplyAlpha => write!(f, "Multiply Alpha"), } } } diff --git a/node-graph/libraries/no-std-types/src/color/color_traits.rs b/node-graph/libraries/no-std-types/src/color/color_traits.rs index 05b0242329..33e35e9d23 100644 --- a/node-graph/libraries/no-std-types/src/color/color_traits.rs +++ b/node-graph/libraries/no-std-types/src/color/color_traits.rs @@ -26,13 +26,13 @@ pub trait Linear { impl Linear for f32 { #[inline(always)] fn from_f32(x: f32) -> Self { x } #[inline(always)] fn to_f32(self) -> f32 { self } - #[inline(always)] fn from_f64(x: f64) -> Self { x as f32 } + #[inline(always)] fn from_f64(x: f64) -> Self { x as Self } #[inline(always)] fn to_f64(self) -> f64 { self as f64 } } #[rustfmt::skip] impl Linear for f64 { - #[inline(always)] fn from_f32(x: f32) -> Self { x as f64 } + #[inline(always)] fn from_f32(x: f32) -> Self { x as Self } #[inline(always)] fn to_f32(self) -> f32 { self as f32 } #[inline(always)] fn from_f64(x: f64) -> Self { x } #[inline(always)] fn to_f64(self) -> f64 { self } diff --git a/node-graph/libraries/no-std-types/src/color/color_types.rs b/node-graph/libraries/no-std-types/src/color/color_types.rs index 246be34f09..74d811ca59 100644 --- a/node-graph/libraries/no-std-types/src/color/color_types.rs +++ b/node-graph/libraries/no-std-types/src/color/color_types.rs @@ -76,7 +76,7 @@ impl Alpha for RGBA16F { self.alpha.to_f32() / 255. } - const TRANSPARENT: Self = RGBA16F { + const TRANSPARENT: Self = Self { red: f16::from_f32_const(0.), green: f16::from_f32_const(0.), blue: f16::from_f32_const(0.), @@ -162,7 +162,7 @@ impl Alpha for SRGBA8 { self.alpha as f32 / 255. } - const TRANSPARENT: Self = SRGBA8 { red: 0, green: 0, blue: 0, alpha: 0 }; + const TRANSPARENT: Self = Self { red: 0, green: 0, blue: 0, alpha: 0 }; fn multiplied_alpha(&self, alpha: Self::AlphaChannel) -> Self { let alpha = alpha * 255.; @@ -282,7 +282,7 @@ impl Pixel for Color { } fn from_bytes(bytes: &[u8]) -> Self { - Color::from_rgba8_srgb(bytes[0], bytes[1], bytes[2], bytes[3]) + Self::from_rgba8_srgb(bytes[0], bytes[1], bytes[2], bytes[3]) } fn byte_size() -> usize { 4 @@ -348,15 +348,15 @@ impl Rec709Primaries for Color {} impl SRGB for Color {} impl Color { - pub const BLACK: Color = Color::from_rgbf32_unchecked(0., 0., 0.); - pub const WHITE: Color = Color::from_rgbf32_unchecked(1., 1., 1.); - pub const RED: Color = Color::from_rgbf32_unchecked(1., 0., 0.); - pub const GREEN: Color = Color::from_rgbf32_unchecked(0., 1., 0.); - pub const BLUE: Color = Color::from_rgbf32_unchecked(0., 0., 1.); - pub const YELLOW: Color = Color::from_rgbf32_unchecked(1., 1., 0.); - pub const CYAN: Color = Color::from_rgbf32_unchecked(0., 1., 1.); - pub const MAGENTA: Color = Color::from_rgbf32_unchecked(1., 0., 1.); - pub const TRANSPARENT: Color = Self { + pub const BLACK: Self = Self::from_rgbf32_unchecked(0., 0., 0.); + pub const WHITE: Self = Self::from_rgbf32_unchecked(1., 1., 1.); + pub const RED: Self = Self::from_rgbf32_unchecked(1., 0., 0.); + pub const GREEN: Self = Self::from_rgbf32_unchecked(0., 1., 0.); + pub const BLUE: Self = Self::from_rgbf32_unchecked(0., 0., 1.); + pub const YELLOW: Self = Self::from_rgbf32_unchecked(1., 1., 0.); + pub const CYAN: Self = Self::from_rgbf32_unchecked(0., 1., 1.); + pub const MAGENTA: Self = Self::from_rgbf32_unchecked(1., 0., 1.); + pub const TRANSPARENT: Self = Self { red: 0., green: 0., blue: 0., @@ -376,30 +376,30 @@ impl Color { /// assert!(color == None); /// ``` #[inline(always)] - pub fn from_rgbaf32(red: f32, green: f32, blue: f32, alpha: f32) -> Option { + pub fn from_rgbaf32(red: f32, green: f32, blue: f32, alpha: f32) -> Option { if alpha > 1. || [red, green, blue, alpha].iter().any(|c| c.is_sign_negative() || !c.is_finite()) { return None; } - let color = Color { red, green, blue, alpha }; + let color = Self { red, green, blue, alpha }; Some(color) } /// Return an opaque `Color` from given `f32` RGB channels. #[inline(always)] - pub const fn from_rgbf32_unchecked(red: f32, green: f32, blue: f32) -> Color { - Color { red, green, blue, alpha: 1. } + pub const fn from_rgbf32_unchecked(red: f32, green: f32, blue: f32) -> Self { + Self { red, green, blue, alpha: 1. } } /// Return an opaque `Color` from given `f32` RGB channels. #[inline(always)] - pub const fn from_rgbaf32_unchecked(red: f32, green: f32, blue: f32, alpha: f32) -> Color { - Color { red, green, blue, alpha } + pub const fn from_rgbaf32_unchecked(red: f32, green: f32, blue: f32, alpha: f32) -> Self { + Self { red, green, blue, alpha } } /// Return an opaque `Color` from given `f32` RGB channels. #[inline(always)] - pub fn from_unassociated_alpha(red: f32, green: f32, blue: f32, alpha: f32) -> Color { - Color::from_rgbaf32_unchecked(red * alpha, green * alpha, blue * alpha, alpha) + pub fn from_unassociated_alpha(red: f32, green: f32, blue: f32, alpha: f32) -> Self { + Self::from_rgbaf32_unchecked(red * alpha, green * alpha, blue * alpha, alpha) } /// Return an opaque SDR `Color` given RGB channels from `0` to `255`, premultiplied by alpha. @@ -412,8 +412,8 @@ impl Color { /// assert_eq!(color, color2) /// ``` #[inline(always)] - pub fn from_rgb8_srgb(red: u8, green: u8, blue: u8) -> Color { - Color::from_rgba8_srgb(red, green, blue, 255) + pub fn from_rgb8_srgb(red: u8, green: u8, blue: u8) -> Self { + Self::from_rgba8_srgb(red, green, blue, 255) } // TODO: Should this be premult? @@ -425,14 +425,14 @@ impl Color { /// let color = Color::from_rgba8_srgb(0x72, 0x67, 0x62, 0x61); /// ``` #[inline(always)] - pub fn from_rgba8_srgb(red: u8, green: u8, blue: u8, alpha: u8) -> Color { + pub fn from_rgba8_srgb(red: u8, green: u8, blue: u8, alpha: u8) -> Self { let map_range = |int_color| int_color as f32 / 255.; let red = map_range(red); let green = map_range(green); let blue = map_range(blue); let alpha = map_range(alpha); - Color { red, green, blue, alpha }.to_linear_srgb().map_rgb(|channel| channel * alpha) + Self { red, green, blue, alpha }.to_linear_srgb().map_rgb(|channel| channel * alpha) } /// Create a [Color] from a hue, saturation, lightness and alpha (all between 0 and 1) @@ -442,7 +442,7 @@ impl Color { /// use core_types::color::Color; /// let color = Color::from_hsla(0.5, 0.2, 0.3, 1.); /// ``` - pub fn from_hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Color { + pub fn from_hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Self { let temp1 = if lightness < 0.5 { lightness * (saturation + 1.) } else { @@ -474,7 +474,7 @@ impl Color { map_channel(&mut green, temp2, temp1); map_channel(&mut blue, temp2, temp1); - Color { red, green, blue, alpha } + Self { red, green, blue, alpha } } /// Return the `red` component. @@ -580,8 +580,8 @@ impl Color { } #[inline(always)] - pub fn from_luminance(luminance: f32) -> Color { - Color { + pub fn from_luminance(luminance: f32) -> Self { + Self { red: luminance, green: luminance, blue: luminance, @@ -590,7 +590,7 @@ impl Color { } #[inline(always)] - pub fn with_luminance(&self, luminance: f32) -> Color { + pub fn with_luminance(&self, luminance: f32) -> Self { let delta = luminance - self.luminance_rec_601_rounded(); self.map_rgb(|c| (c + delta).clamp(0., 1.)) } @@ -604,13 +604,13 @@ impl Color { } #[inline(always)] - pub fn with_saturation(&self, saturation: f32) -> Color { + pub fn with_saturation(&self, saturation: f32) -> Self { let [hue, _, lightness, alpha] = self.to_hsla(); - Color::from_hsla(hue, saturation, lightness, alpha) + Self::from_hsla(hue, saturation, lightness, alpha) } - pub fn with_alpha(&self, alpha: f32) -> Color { - Color { + pub fn with_alpha(&self, alpha: f32) -> Self { + Self { red: self.red, green: self.green, blue: self.blue, @@ -618,8 +618,8 @@ impl Color { } } - pub fn with_red(&self, red: f32) -> Color { - Color { + pub fn with_red(&self, red: f32) -> Self { + Self { red, green: self.green, blue: self.blue, @@ -627,8 +627,8 @@ impl Color { } } - pub fn with_green(&self, green: f32) -> Color { - Color { + pub fn with_green(&self, green: f32) -> Self { + Self { red: self.red, green, blue: self.blue, @@ -636,8 +636,8 @@ impl Color { } } - pub fn with_blue(&self, blue: f32) -> Color { - Color { + pub fn with_blue(&self, blue: f32) -> Self { + Self { red: self.red, green: self.green, blue, @@ -677,7 +677,7 @@ impl Color { } #[inline(always)] - pub fn blend_darker_color(&self, other: Color) -> Color { + pub fn blend_darker_color(&self, other: Self) -> Self { if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other } } @@ -702,7 +702,7 @@ impl Color { } #[inline(always)] - pub fn blend_lighter_color(&self, other: Color) -> Color { + pub fn blend_lighter_color(&self, other: Self) -> Self { if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other } } @@ -717,38 +717,38 @@ impl Color { pub fn blend_hardlight(c_b: f32, c_s: f32) -> f32 { if c_s <= 0.5 { - Color::blend_multiply(2. * c_s, c_b) + Self::blend_multiply(2. * c_s, c_b) } else { - Color::blend_screen(2. * c_s - 1., c_b) + Self::blend_screen(2. * c_s - 1., c_b) } } pub fn blend_vivid_light(c_b: f32, c_s: f32) -> f32 { if c_s <= 0.5 { - Color::blend_color_burn(2. * c_s, c_b) + Self::blend_color_burn(2. * c_s, c_b) } else { - Color::blend_color_dodge(2. * c_s - 1., c_b) + Self::blend_color_dodge(2. * c_s - 1., c_b) } } pub fn blend_linear_light(c_b: f32, c_s: f32) -> f32 { if c_s <= 0.5 { - Color::blend_linear_burn(2. * c_s, c_b) + Self::blend_linear_burn(2. * c_s, c_b) } else { - Color::blend_linear_dodge(2. * c_s - 1., c_b) + Self::blend_linear_dodge(2. * c_s - 1., c_b) } } pub fn blend_pin_light(c_b: f32, c_s: f32) -> f32 { if c_s <= 0.5 { - Color::blend_darken(2. * c_s, c_b) + Self::blend_darken(2. * c_s, c_b) } else { - Color::blend_lighten(2. * c_s - 1., c_b) + Self::blend_lighten(2. * c_s - 1., c_b) } } pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 { - if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. } + if Self::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. } } pub fn blend_difference(c_b: f32, c_s: f32) -> f32 { @@ -767,26 +767,26 @@ impl Color { if c_b == 0. { 1. } else { c_b / c_s } } - pub fn blend_hue(&self, c_s: Color) -> Color { + pub fn blend_hue(&self, c_s: Self) -> Self { let sat_b = self.saturation(); let lum_b = self.luminance_rec_601(); c_s.with_saturation(sat_b).with_luminance(lum_b) } - pub fn blend_saturation(&self, c_s: Color) -> Color { + pub fn blend_saturation(&self, c_s: Self) -> Self { let sat_s = c_s.saturation(); let lum_b = self.luminance_rec_601(); self.with_saturation(sat_s).with_luminance(lum_b) } - pub fn blend_color(&self, c_s: Color) -> Color { + pub fn blend_color(&self, c_s: Self) -> Self { let lum_b = self.luminance_rec_601(); c_s.with_luminance(lum_b) } - pub fn blend_luminosity(&self, c_s: Color) -> Color { + pub fn blend_luminosity(&self, c_s: Self) -> Self { let lum_s = c_s.luminance_rec_601(); self.with_luminance(lum_s) @@ -919,7 +919,7 @@ impl Color { /// use core_types::color::Color; /// let color = Color::from_rgba_str("7C67FA61").unwrap(); /// ``` - pub fn from_rgba_str(color_str: &str) -> Option { + pub fn from_rgba_str(color_str: &str) -> Option { if color_str.len() != 8 { return None; } @@ -928,7 +928,7 @@ impl Color { let b = u8::from_str_radix(&color_str[4..6], 16).ok()?; let a = u8::from_str_radix(&color_str[6..8], 16).ok()?; - Some(Color::from_rgba8_srgb(r, g, b, a)) + Some(Self::from_rgba8_srgb(r, g, b, a)) } /// Creates a color from a 6-character RGB hex string (without a # prefix). @@ -937,7 +937,7 @@ impl Color { /// use core_types::color::Color; /// let color = Color::from_rgb_str("7C67FA").unwrap(); /// ``` - pub fn from_rgb_str(color_str: &str) -> Option { + pub fn from_rgb_str(color_str: &str) -> Option { if color_str.len() != 6 { return None; } @@ -945,16 +945,16 @@ impl Color { let g = u8::from_str_radix(&color_str[2..4], 16).ok()?; let b = u8::from_str_radix(&color_str[4..6], 16).ok()?; - Some(Color::from_rgb8_srgb(r, g, b)) + Some(Self::from_rgb8_srgb(r, g, b)) } /// Linearly interpolates between two colors based on t. /// /// T must be between 0 and 1. #[inline(always)] - pub fn lerp(&self, other: &Color, t: f32) -> Self { + pub fn lerp(&self, other: &Self, t: f32) -> Self { assert!((0. ..=1.).contains(&t)); - Color::from_rgbaf32_unchecked( + Self::from_rgbaf32_unchecked( self.red + ((other.red - self.red) * t), self.green + ((other.green - self.green) * t), self.blue + ((other.blue - self.blue) * t), @@ -963,7 +963,7 @@ impl Color { } #[inline(always)] - pub fn gamma(&self, gamma: f32) -> Color { + pub fn gamma(&self, gamma: f32) -> Self { let gamma = gamma.max(0.0001); // From https://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-6-gamma-correction/ @@ -1041,9 +1041,9 @@ impl Color { } #[inline(always)] - pub fn blend_rgb f32>(&self, other: Color, f: F) -> Self { + pub fn blend_rgb f32>(&self, other: Self, f: F) -> Self { let background = self.to_unassociated_alpha(); - Color { + Self { red: f(background.red, other.red).clamp(0., 1.), green: f(background.green, other.green).clamp(0., 1.), blue: f(background.blue, other.blue).clamp(0., 1.), @@ -1052,7 +1052,7 @@ impl Color { } #[inline(always)] - pub fn alpha_blend(&self, other: Color) -> Self { + pub fn alpha_blend(&self, other: Self) -> Self { let inv_alpha = 1. - other.alpha; Self { red: self.red * inv_alpha + other.red, @@ -1063,7 +1063,7 @@ impl Color { } #[inline(always)] - pub fn alpha_add(&self, other: Color) -> Self { + pub fn alpha_add(&self, other: Self) -> Self { Self { alpha: (self.alpha + other.alpha).clamp(0., 1.), ..*self @@ -1071,7 +1071,7 @@ impl Color { } #[inline(always)] - pub fn alpha_subtract(&self, other: Color) -> Self { + pub fn alpha_subtract(&self, other: Self) -> Self { Self { alpha: (self.alpha - other.alpha).clamp(0., 1.), ..*self @@ -1079,7 +1079,7 @@ impl Color { } #[inline(always)] - pub fn alpha_multiply(&self, other: Color) -> Self { + pub fn alpha_multiply(&self, other: Self) -> Self { Self { alpha: (self.alpha * other.alpha).clamp(0., 1.), ..*self diff --git a/node-graph/libraries/no-std-types/src/shaders/buffer_struct/glam.rs b/node-graph/libraries/no-std-types/src/shaders/buffer_struct/glam.rs index 568f017045..df9108c4a4 100644 --- a/node-graph/libraries/no-std-types/src/shaders/buffer_struct/glam.rs +++ b/node-graph/libraries/no-std-types/src/shaders/buffer_struct/glam.rs @@ -92,7 +92,7 @@ unsafe impl BufferStruct for glam::Vec3A { #[inline] fn read(from: Self::Buffer) -> Self { - glam::Vec3A::from_vec4(glam::Vec4::from_array(from)) + Self::from_vec4(glam::Vec4::from_array(from)) } } @@ -109,6 +109,6 @@ unsafe impl BufferStruct for glam::Mat3A { #[inline] fn read(from: Self::Buffer) -> Self { let a = from; - glam::Mat3A::from_cols_array(&[a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]]) + Self::from_cols_array(&[a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]]) } } diff --git a/node-graph/libraries/no-std-types/src/shaders/buffer_struct/primitive.rs b/node-graph/libraries/no-std-types/src/shaders/buffer_struct/primitive.rs index 84bc92d828..155936e7ff 100644 --- a/node-graph/libraries/no-std-types/src/shaders/buffer_struct/primitive.rs +++ b/node-graph/libraries/no-std-types/src/shaders/buffer_struct/primitive.rs @@ -67,21 +67,21 @@ where #[inline] fn read(from: Self::Buffer) -> Self { - Wrapping(T::read(from.0)) + Self(T::read(from.0)) } } unsafe impl BufferStruct for PhantomData { - type Buffer = PhantomData; + type Buffer = Self; #[inline] fn write(_: Self) -> Self::Buffer { - PhantomData {} + Self {} } #[inline] fn read(_: Self::Buffer) -> Self { - PhantomData {} + Self {} } } diff --git a/node-graph/libraries/raster-types/src/image.rs b/node-graph/libraries/raster-types/src/image.rs index 8c07e46567..f3df03b813 100644 --- a/node-graph/libraries/raster-types/src/image.rs +++ b/node-graph/libraries/raster-types/src/image.rs @@ -136,7 +136,7 @@ impl Image { /// Generate Image from some frontend image data (the canvas pixels as u8s in a flat array) pub fn from_image_data(image_data: &[u8], width: u32, height: u32) -> Self { let data = image_data.chunks_exact(4).map(|v| Color::from_rgba8_srgb(v[0], v[1], v[2], v[3])).collect(); - Image { + Self { width, height, data, @@ -162,7 +162,7 @@ where { /// Flattens each channel cast to a u8 pub fn to_flat_u8(&self) -> (Vec, u32, u32) { - let Image { width, height, data, .. } = self; + let Self { width, height, data, .. } = self; assert_eq!(data.len(), *width as usize * *height as usize); // Cache the last sRGB value we computed, speeds up fills. @@ -230,20 +230,20 @@ pub fn migrate_image_frame<'de, D: serde::Deserializer<'de>>(deserializer: D) -> } impl<'de> serde::Deserialize<'de> for RasterFrame { fn deserialize>(deserializer: D) -> Result { - Ok(RasterFrame::ImageFrame(Table::new_from_element(Image::deserialize(deserializer)?))) + Ok(Self::ImageFrame(Table::new_from_element(Image::deserialize(deserializer)?))) } } impl serde::Serialize for RasterFrame { fn serialize(&self, serializer: S) -> Result { match self { - RasterFrame::ImageFrame(table) => table.serialize(serializer), + Self::ImageFrame(table) => table.serialize(serializer), } } } #[derive(Clone, Debug, Hash, PartialEq, DynAny, serde::Serialize, serde::Deserialize)] pub enum GraphicElement { - GraphicGroup(Table), + GraphicGroup(Table), RasterFrame(RasterFrame), } @@ -253,7 +253,7 @@ pub fn migrate_image_frame<'de, D: serde::Deserializer<'de>>(deserializer: D) -> } impl From> for GraphicElement { fn from(image_frame: ImageFrame) -> Self { - GraphicElement::RasterFrame(RasterFrame::ImageFrame(Table::new_from_element(image_frame.image))) + Self::RasterFrame(RasterFrame::ImageFrame(Table::new_from_element(image_frame.image))) } } impl From for ImageFrame { @@ -383,13 +383,13 @@ pub fn migrate_image_frame_row<'de, D: serde::Deserializer<'de>>(deserializer: D } impl<'de> serde::Deserialize<'de> for RasterFrame { fn deserialize>(deserializer: D) -> Result { - Ok(RasterFrame::ImageFrame(Table::new_from_element(Image::deserialize(deserializer)?))) + Ok(Self::ImageFrame(Table::new_from_element(Image::deserialize(deserializer)?))) } } impl serde::Serialize for RasterFrame { fn serialize(&self, serializer: S) -> Result { match self { - RasterFrame::ImageFrame(table) => table.serialize(serializer), + Self::ImageFrame(table) => table.serialize(serializer), } } } @@ -397,7 +397,7 @@ pub fn migrate_image_frame_row<'de, D: serde::Deserializer<'de>>(deserializer: D #[derive(Clone, Debug, Hash, PartialEq, DynAny, serde::Serialize, serde::Deserialize)] pub enum GraphicElement { /// Equivalent to the SVG tag: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g - GraphicGroup(Table), + GraphicGroup(Table), RasterFrame(RasterFrame), } @@ -407,7 +407,7 @@ pub fn migrate_image_frame_row<'de, D: serde::Deserializer<'de>>(deserializer: D } impl From> for GraphicElement { fn from(image_frame: ImageFrame) -> Self { - GraphicElement::RasterFrame(RasterFrame::ImageFrame(Table::new_from_element(image_frame.image))) + Self::RasterFrame(RasterFrame::ImageFrame(Table::new_from_element(image_frame.image))) } } impl From for ImageFrame { @@ -494,8 +494,8 @@ impl Image

{ } } -impl AsRef> for Image

{ - fn as_ref(&self) -> &Image

{ +impl AsRef for Image

{ + fn as_ref(&self) -> &Self { self } } diff --git a/node-graph/libraries/raster-types/src/raster_types.rs b/node-graph/libraries/raster-types/src/raster_types.rs index 918df0cec8..6176e9be9c 100644 --- a/node-graph/libraries/raster-types/src/raster_types.rs +++ b/node-graph/libraries/raster-types/src/raster_types.rs @@ -19,21 +19,21 @@ pub trait Storage: __private::Sealed + Clone + Debug + 'static { #[derive(Clone, Debug, PartialEq, Hash, Default)] pub struct Raster where - Raster: Storage, + Self: Storage, { storage: T, } unsafe impl dyn_any::StaticType for Raster where - Raster: Storage, + Self: Storage, { - type Static = Raster; + type Static = Self; } impl Raster where - Raster: Storage, + Self: Storage, { pub fn new(t: T) -> Self { Self { storage: t } @@ -42,7 +42,7 @@ where impl Deref for Raster where - Raster: Storage, + Self: Storage, { type Target = T; @@ -53,7 +53,7 @@ where impl DerefMut for Raster where - Raster: Storage, + Self: Storage, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.storage @@ -114,7 +114,7 @@ mod cpu { where D: serde::Deserializer<'de>, { - Ok(Raster::new_cpu(Image::deserialize(deserializer)?)) + Ok(Self::new_cpu(Image::deserialize(deserializer)?)) } } @@ -200,7 +200,7 @@ mod gpu_common { impl BoundingBox for Raster where - Raster: Storage, + Self: Storage, { fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox { if self.is_empty() || transform.matrix2.determinant() == 0. { diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 3c765a91ad..6e7b6346ac 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -284,33 +284,33 @@ pub trait Render: BoundingBox + RenderComplexity { impl Render for Graphic { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { match self { - Graphic::Graphic(table) => table.render_svg(render, render_params), - Graphic::Vector(table) => table.render_svg(render, render_params), - Graphic::RasterCPU(table) => table.render_svg(render, render_params), - Graphic::RasterGPU(_) => (), - Graphic::Color(table) => table.render_svg(render, render_params), - Graphic::Gradient(table) => table.render_svg(render, render_params), + Self::Graphic(table) => table.render_svg(render, render_params), + Self::Vector(table) => table.render_svg(render, render_params), + Self::RasterCPU(table) => table.render_svg(render, render_params), + Self::RasterGPU(_) => (), + Self::Color(table) => table.render_svg(render, render_params), + Self::Gradient(table) => table.render_svg(render, render_params), } } fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) { match self { - Graphic::Graphic(table) => table.render_to_vello(scene, transform, context, render_params), - Graphic::Vector(table) => table.render_to_vello(scene, transform, context, render_params), - Graphic::RasterCPU(table) => table.render_to_vello(scene, transform, context, render_params), - Graphic::RasterGPU(table) => table.render_to_vello(scene, transform, context, render_params), - Graphic::Color(table) => table.render_to_vello(scene, transform, context, render_params), - Graphic::Gradient(table) => table.render_to_vello(scene, transform, context, render_params), + Self::Graphic(table) => table.render_to_vello(scene, transform, context, render_params), + Self::Vector(table) => table.render_to_vello(scene, transform, context, render_params), + Self::RasterCPU(table) => table.render_to_vello(scene, transform, context, render_params), + Self::RasterGPU(table) => table.render_to_vello(scene, transform, context, render_params), + Self::Color(table) => table.render_to_vello(scene, transform, context, render_params), + Self::Gradient(table) => table.render_to_vello(scene, transform, context, render_params), } } fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option) { if let Some(element_id) = element_id { match self { - Graphic::Graphic(_) => { + Self::Graphic(_) => { metadata.upstream_footprints.insert(element_id, footprint); } - Graphic::Vector(table) => { + Self::Vector(table) => { metadata.upstream_footprints.insert(element_id, footprint); // TODO: Find a way to handle more than the first row if let Some(row) = table.iter().next() { @@ -318,7 +318,7 @@ impl Render for Graphic { metadata.local_transforms.insert(element_id, *row.transform); } } - Graphic::RasterCPU(table) => { + Self::RasterCPU(table) => { metadata.upstream_footprints.insert(element_id, footprint); // TODO: Find a way to handle more than the first row @@ -326,7 +326,7 @@ impl Render for Graphic { metadata.local_transforms.insert(element_id, *row.transform); } } - Graphic::RasterGPU(table) => { + Self::RasterGPU(table) => { metadata.upstream_footprints.insert(element_id, footprint); // TODO: Find a way to handle more than the first row @@ -334,7 +334,7 @@ impl Render for Graphic { metadata.local_transforms.insert(element_id, *row.transform); } } - Graphic::Color(table) => { + Self::Color(table) => { metadata.upstream_footprints.insert(element_id, footprint); // TODO: Find a way to handle more than the first row @@ -342,7 +342,7 @@ impl Render for Graphic { metadata.local_transforms.insert(element_id, *row.transform); } } - Graphic::Gradient(table) => { + Self::Gradient(table) => { metadata.upstream_footprints.insert(element_id, footprint); // TODO: Find a way to handle more than the first row @@ -354,45 +354,45 @@ impl Render for Graphic { } match self { - Graphic::Graphic(table) => table.collect_metadata(metadata, footprint, element_id), - Graphic::Vector(table) => table.collect_metadata(metadata, footprint, element_id), - Graphic::RasterCPU(table) => table.collect_metadata(metadata, footprint, element_id), - Graphic::RasterGPU(table) => table.collect_metadata(metadata, footprint, element_id), - Graphic::Color(table) => table.collect_metadata(metadata, footprint, element_id), - Graphic::Gradient(table) => table.collect_metadata(metadata, footprint, element_id), + Self::Graphic(table) => table.collect_metadata(metadata, footprint, element_id), + Self::Vector(table) => table.collect_metadata(metadata, footprint, element_id), + Self::RasterCPU(table) => table.collect_metadata(metadata, footprint, element_id), + Self::RasterGPU(table) => table.collect_metadata(metadata, footprint, element_id), + Self::Color(table) => table.collect_metadata(metadata, footprint, element_id), + Self::Gradient(table) => table.collect_metadata(metadata, footprint, element_id), } } fn add_upstream_click_targets(&self, click_targets: &mut Vec) { match self { - Graphic::Graphic(table) => table.add_upstream_click_targets(click_targets), - Graphic::Vector(table) => table.add_upstream_click_targets(click_targets), - Graphic::RasterCPU(table) => table.add_upstream_click_targets(click_targets), - Graphic::RasterGPU(table) => table.add_upstream_click_targets(click_targets), - Graphic::Color(table) => table.add_upstream_click_targets(click_targets), - Graphic::Gradient(table) => table.add_upstream_click_targets(click_targets), + Self::Graphic(table) => table.add_upstream_click_targets(click_targets), + Self::Vector(table) => table.add_upstream_click_targets(click_targets), + Self::RasterCPU(table) => table.add_upstream_click_targets(click_targets), + Self::RasterGPU(table) => table.add_upstream_click_targets(click_targets), + Self::Color(table) => table.add_upstream_click_targets(click_targets), + Self::Gradient(table) => table.add_upstream_click_targets(click_targets), } } fn contains_artboard(&self) -> bool { match self { - Graphic::Graphic(table) => table.contains_artboard(), - Graphic::Vector(table) => table.contains_artboard(), - Graphic::RasterCPU(table) => table.contains_artboard(), - Graphic::RasterGPU(table) => table.contains_artboard(), - Graphic::Color(table) => table.contains_artboard(), - Graphic::Gradient(table) => table.contains_artboard(), + Self::Graphic(table) => table.contains_artboard(), + Self::Vector(table) => table.contains_artboard(), + Self::RasterCPU(table) => table.contains_artboard(), + Self::RasterGPU(table) => table.contains_artboard(), + Self::Color(table) => table.contains_artboard(), + Self::Gradient(table) => table.contains_artboard(), } } fn new_ids_from_hash(&mut self, reference: Option) { match self { - Graphic::Graphic(table) => table.new_ids_from_hash(reference), - Graphic::Vector(table) => table.new_ids_from_hash(reference), - Graphic::RasterCPU(_) => (), - Graphic::RasterGPU(_) => (), - Graphic::Color(_) => (), - Graphic::Gradient(_) => (), + Self::Graphic(table) => table.new_ids_from_hash(reference), + Self::Vector(table) => table.new_ids_from_hash(reference), + Self::RasterCPU(_) => (), + Self::RasterGPU(_) => (), + Self::Color(_) => (), + Self::Gradient(_) => (), } } } @@ -761,7 +761,7 @@ impl Render for Table { element.style.clear_stroke(); element.style.set_fill(Fill::solid(Color::BLACK)); - let vector_row = Table::new_from_row(TableRow { + let vector_row = Self::new_from_row(TableRow { element, alpha_blending: *row.alpha_blending, transform: *row.transform, @@ -1079,7 +1079,7 @@ impl Render for Table { element.style.clear_stroke(); element.style.set_fill(Fill::solid(Color::BLACK)); - let vector_table = Table::new_from_row(TableRow { + let vector_table = Self::new_from_row(TableRow { element, alpha_blending: *row.alpha_blending, transform: *row.transform, diff --git a/node-graph/libraries/rendering/src/to_peniko.rs b/node-graph/libraries/rendering/src/to_peniko.rs index c4dbfad450..9aad612871 100644 --- a/node-graph/libraries/rendering/src/to_peniko.rs +++ b/node-graph/libraries/rendering/src/to_peniko.rs @@ -9,27 +9,27 @@ impl BlendModeExt for BlendMode { fn to_peniko(&self) -> peniko::Mix { match self { // Normal group - BlendMode::Normal => peniko::Mix::Normal, + Self::Normal => peniko::Mix::Normal, // Darken group - BlendMode::Darken => peniko::Mix::Darken, - BlendMode::Multiply => peniko::Mix::Multiply, - BlendMode::ColorBurn => peniko::Mix::ColorBurn, + Self::Darken => peniko::Mix::Darken, + Self::Multiply => peniko::Mix::Multiply, + Self::ColorBurn => peniko::Mix::ColorBurn, // Lighten group - BlendMode::Lighten => peniko::Mix::Lighten, - BlendMode::Screen => peniko::Mix::Screen, - BlendMode::ColorDodge => peniko::Mix::ColorDodge, + Self::Lighten => peniko::Mix::Lighten, + Self::Screen => peniko::Mix::Screen, + Self::ColorDodge => peniko::Mix::ColorDodge, // Contrast group - BlendMode::Overlay => peniko::Mix::Overlay, - BlendMode::SoftLight => peniko::Mix::SoftLight, - BlendMode::HardLight => peniko::Mix::HardLight, + Self::Overlay => peniko::Mix::Overlay, + Self::SoftLight => peniko::Mix::SoftLight, + Self::HardLight => peniko::Mix::HardLight, // Inversion group - BlendMode::Difference => peniko::Mix::Difference, - BlendMode::Exclusion => peniko::Mix::Exclusion, + Self::Difference => peniko::Mix::Difference, + Self::Exclusion => peniko::Mix::Exclusion, // Component group - BlendMode::Hue => peniko::Mix::Hue, - BlendMode::Saturation => peniko::Mix::Saturation, - BlendMode::Color => peniko::Mix::Color, - BlendMode::Luminosity => peniko::Mix::Luminosity, + Self::Hue => peniko::Mix::Hue, + Self::Saturation => peniko::Mix::Saturation, + Self::Color => peniko::Mix::Color, + Self::Luminosity => peniko::Mix::Luminosity, _ => todo!(), } } diff --git a/node-graph/libraries/vector-types/src/subpath/core.rs b/node-graph/libraries/vector-types/src/subpath/core.rs index c5600d61a1..9aca5b574f 100644 --- a/node-graph/libraries/vector-types/src/subpath/core.rs +++ b/node-graph/libraries/vector-types/src/subpath/core.rs @@ -39,7 +39,7 @@ impl Subpath { /// Create a `Subpath` consisting of 2 manipulator groups from a `Bezier`. pub fn from_bezier(segment: PathSeg) -> Self { let PathSegPoints { p0, p1, p2, p3 } = pathseg_points(segment); - Subpath::new(vec![ManipulatorGroup::new(p0, None, p1), ManipulatorGroup::new(p3, p2, None)], false) + Self::new(vec![ManipulatorGroup::new(p0, None, p1), ManipulatorGroup::new(p3, p2, None)], false) } /// Creates a subpath from a slice of [Bezier]. When two consecutive Beziers do not share an end and start point, this function @@ -47,7 +47,7 @@ impl Subpath { pub fn from_beziers(beziers: &[PathSeg], closed: bool) -> Self { assert!(!closed || beziers.len() > 1, "A closed Subpath must contain at least 1 Bezier."); if beziers.is_empty() { - return Subpath::new(vec![], closed); + return Self::new(vec![], closed); } let beziers: Vec<_> = beziers.iter().map(|b| pathseg_points(*b)).collect(); @@ -78,11 +78,11 @@ impl Subpath { out_handle: None, id: PointId::new(), }); - return Subpath::new(manipulator_groups, false); + return Self::new(manipulator_groups, false); } manipulator_groups[0].in_handle = last.p2; - Subpath::new(manipulator_groups, true) + Self::new(manipulator_groups, true) } /// Returns true if the `Subpath` contains no [ManipulatorGroup]. diff --git a/node-graph/libraries/vector-types/src/subpath/solvers.rs b/node-graph/libraries/vector-types/src/subpath/solvers.rs index 409e336a93..86f099c17f 100644 --- a/node-graph/libraries/vector-types/src/subpath/solvers.rs +++ b/node-graph/libraries/vector-types/src/subpath/solvers.rs @@ -40,7 +40,7 @@ impl Subpath { } /// Returns `true` if this subpath is completely inside the `other` subpath. - pub fn is_inside_subpath(&self, other: &Subpath, accuracy: Option, minimum_separation: Option) -> bool { + pub fn is_inside_subpath(&self, other: &Self, accuracy: Option, minimum_separation: Option) -> bool { bezpath_is_inside_bezpath(&self.to_bezpath(), &other.to_bezpath(), accuracy, minimum_separation) } diff --git a/node-graph/libraries/vector-types/src/subpath/structs.rs b/node-graph/libraries/vector-types/src/subpath/structs.rs index d5f868be2b..531d3aae55 100644 --- a/node-graph/libraries/vector-types/src/subpath/structs.rs +++ b/node-graph/libraries/vector-types/src/subpath/structs.rs @@ -73,7 +73,7 @@ impl ManipulatorGroup { } /// Create a bezier curve that starts at the current manipulator group and finishes in the `end_group` manipulator group. - pub fn to_bezier(&self, end_group: &ManipulatorGroup) -> PathSeg { + pub fn to_bezier(&self, end_group: &Self) -> PathSeg { let start = self.anchor; let end = end_group.anchor; let out_handle = self.out_handle; @@ -153,9 +153,9 @@ impl std::hash::Hash for BezierHandles { fn hash(&self, state: &mut H) { std::mem::discriminant(self).hash(state); match self { - BezierHandles::Linear => {} - BezierHandles::Quadratic { handle } => handle.to_array().map(|v| v.to_bits()).hash(state), - BezierHandles::Cubic { handle_start, handle_end } => [handle_start, handle_end].map(|handle| handle.to_array().map(|v| v.to_bits())).hash(state), + Self::Linear => {} + Self::Quadratic { handle } => handle.to_array().map(|v| v.to_bits()).hash(state), + Self::Cubic { handle_start, handle_end } => [handle_start, handle_end].map(|handle| handle.to_array().map(|v| v.to_bits())).hash(state), } } } @@ -167,16 +167,16 @@ impl BezierHandles { pub fn is_finite(&self) -> bool { match self { - BezierHandles::Linear => true, - BezierHandles::Quadratic { handle } => handle.is_finite(), - BezierHandles::Cubic { handle_start, handle_end } => handle_start.is_finite() && handle_end.is_finite(), + Self::Linear => true, + Self::Quadratic { handle } => handle.is_finite(), + Self::Cubic { handle_start, handle_end } => handle_start.is_finite() && handle_end.is_finite(), } } /// Get the coordinates of the bezier segment's first handle point. This represents the only handle in a quadratic segment. pub fn start(&self) -> Option { match *self { - BezierHandles::Cubic { handle_start, .. } | BezierHandles::Quadratic { handle: handle_start } => Some(handle_start), + Self::Cubic { handle_start, .. } | Self::Quadratic { handle: handle_start } => Some(handle_start), _ => None, } } @@ -184,19 +184,19 @@ impl BezierHandles { /// Get the coordinates of the second handle point. This will return `None` for a quadratic segment. pub fn end(&self) -> Option { match *self { - BezierHandles::Cubic { handle_end, .. } => Some(handle_end), + Self::Cubic { handle_end, .. } => Some(handle_end), _ => None, } } pub fn move_start(&mut self, delta: DVec2) { - if let BezierHandles::Cubic { handle_start, .. } | BezierHandles::Quadratic { handle: handle_start } = self { + if let Self::Cubic { handle_start, .. } | Self::Quadratic { handle: handle_start } = self { *handle_start += delta } } pub fn move_end(&mut self, delta: DVec2) { - if let BezierHandles::Cubic { handle_end, .. } = self { + if let Self::Cubic { handle_end, .. } = self { *handle_end += delta } } @@ -205,12 +205,12 @@ impl BezierHandles { #[must_use] pub fn apply_transformation(&self, transformation_function: impl Fn(DVec2) -> DVec2) -> Self { match *self { - BezierHandles::Linear => Self::Linear, - BezierHandles::Quadratic { handle } => { + Self::Linear => Self::Linear, + Self::Quadratic { handle } => { let handle = transformation_function(handle); Self::Quadratic { handle } } - BezierHandles::Cubic { handle_start, handle_end } => { + Self::Cubic { handle_start, handle_end } => { let handle_start = transformation_function(handle_start); let handle_end = transformation_function(handle_end); Self::Cubic { handle_start, handle_end } @@ -221,7 +221,7 @@ impl BezierHandles { #[must_use] pub fn reversed(self) -> Self { match self { - BezierHandles::Cubic { handle_start, handle_end } => Self::Cubic { + Self::Cubic { handle_start, handle_end } => Self::Cubic { handle_start: handle_end, handle_end: handle_start, }, @@ -335,7 +335,7 @@ impl Bezier { // TODO: Consider removing this function /// Create a linear bezier using the provided coordinates as the start and end points. pub fn from_linear_coordinates(x1: f64, y1: f64, x2: f64, y2: f64) -> Self { - Bezier { + Self { start: DVec2::new(x1, y1), handles: BezierHandles::Linear, end: DVec2::new(x2, y2), @@ -344,7 +344,7 @@ impl Bezier { /// Create a linear bezier using the provided DVec2s as the start and end points. pub fn from_linear_dvec2(p1: DVec2, p2: DVec2) -> Self { - Bezier { + Self { start: p1, handles: BezierHandles::Linear, end: p2, @@ -354,7 +354,7 @@ impl Bezier { // TODO: Consider removing this function /// Create a quadratic bezier using the provided coordinates as the start, handle, and end points. pub fn from_quadratic_coordinates(x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) -> Self { - Bezier { + Self { start: DVec2::new(x1, y1), handles: BezierHandles::Quadratic { handle: DVec2::new(x2, y2) }, end: DVec2::new(x3, y3), @@ -363,7 +363,7 @@ impl Bezier { /// Create a quadratic bezier using the provided DVec2s as the start, handle, and end points. pub fn from_quadratic_dvec2(p1: DVec2, p2: DVec2, p3: DVec2) -> Self { - Bezier { + Self { start: p1, handles: BezierHandles::Quadratic { handle: p2 }, end: p3, @@ -374,7 +374,7 @@ impl Bezier { /// Create a cubic bezier using the provided coordinates as the start, handles, and end points. #[allow(clippy::too_many_arguments)] pub fn from_cubic_coordinates(x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) -> Self { - Bezier { + Self { start: DVec2::new(x1, y1), handles: BezierHandles::Cubic { handle_start: DVec2::new(x2, y2), @@ -386,7 +386,7 @@ impl Bezier { /// Create a cubic bezier using the provided DVec2s as the start, handles, and end points. pub fn from_cubic_dvec2(p1: DVec2, p2: DVec2, p3: DVec2, p4: DVec2) -> Self { - Bezier { + Self { start: p1, handles: BezierHandles::Cubic { handle_start: p2, handle_end: p3 }, end: p4, @@ -394,7 +394,7 @@ impl Bezier { } /// Returns a Bezier curve that results from applying the transformation function to each point in the Bezier. - pub fn apply_transformation(&self, transformation_function: impl Fn(DVec2) -> DVec2) -> Bezier { + pub fn apply_transformation(&self, transformation_function: impl Fn(DVec2) -> DVec2) -> Self { Self { start: transformation_function(self.start), end: transformation_function(self.end), @@ -402,7 +402,7 @@ impl Bezier { } } - pub fn intersections(&self, other: &Bezier, accuracy: Option, minimum_separation: Option) -> Vec { + pub fn intersections(&self, other: &Self, accuracy: Option, minimum_separation: Option) -> Vec { let this = handles_to_segment(self.start, self.handles, self.end); let other = handles_to_segment(other.start, other.handles, other.end); filtered_segment_intersections(this, other, accuracy, minimum_separation) diff --git a/node-graph/libraries/vector-types/src/subpath/transform.rs b/node-graph/libraries/vector-types/src/subpath/transform.rs index c4476a7388..0bc9a946ab 100644 --- a/node-graph/libraries/vector-types/src/subpath/transform.rs +++ b/node-graph/libraries/vector-types/src/subpath/transform.rs @@ -20,12 +20,12 @@ impl Subpath { /// Returns a [Subpath] with a reversed winding order. /// Note that a reversed closed subpath will start on the same manipulator group and simply wind the other direction - pub fn reverse(&self) -> Subpath { - let mut reversed = Subpath::reverse_manipulator_groups(self.manipulator_groups()); + pub fn reverse(&self) -> Self { + let mut reversed = Self::reverse_manipulator_groups(self.manipulator_groups()); if self.closed { reversed.rotate_right(1); }; - Subpath { + Self { manipulator_groups: reversed, closed: self.closed, } @@ -39,7 +39,7 @@ impl Subpath { } /// Returns a subpath that results from rotating this subpath around the origin by the given angle (in radians). - pub fn rotate(&self, angle: f64) -> Subpath { + pub fn rotate(&self, angle: f64) -> Self { let mut rotated_subpath = self.clone(); let affine_transform: DAffine2 = DAffine2::from_angle(angle); @@ -49,7 +49,7 @@ impl Subpath { } /// Returns a subpath that results from rotating this subpath around the provided point by the given angle (in radians). - pub fn rotate_about_point(&self, angle: f64, pivot: DVec2) -> Subpath { + pub fn rotate_about_point(&self, angle: f64, pivot: DVec2) -> Self { // Translate before and after the rotation to account for the pivot let translate: DAffine2 = DAffine2::from_translation(pivot); let rotate: DAffine2 = DAffine2::from_angle(angle); diff --git a/node-graph/libraries/vector-types/src/vector/misc.rs b/node-graph/libraries/vector-types/src/vector/misc.rs index 088e5daaff..8169d1e2ad 100644 --- a/node-graph/libraries/vector-types/src/vector/misc.rs +++ b/node-graph/libraries/vector-types/src/vector/misc.rs @@ -311,25 +311,25 @@ impl Tangent for T { impl Tangent for kurbo::PathSeg { fn tangent_at(&self, t: f64) -> DVec2 { match self { - PathSeg::Line(line) => line.tangent_at(t), - PathSeg::Quad(quad) => quad.tangent_at(t), - PathSeg::Cubic(cubic) => cubic.tangent_at(t), + Self::Line(line) => line.tangent_at(t), + Self::Quad(quad) => quad.tangent_at(t), + Self::Cubic(cubic) => cubic.tangent_at(t), } } fn tangent_at_start(&self) -> DVec2 { match self { - PathSeg::Line(line) => line.tangent_at_start(), - PathSeg::Quad(quad) => quad.tangent_at_start(), - PathSeg::Cubic(cubic) => cubic.tangent_at_start(), + Self::Line(line) => line.tangent_at_start(), + Self::Quad(quad) => quad.tangent_at_start(), + Self::Cubic(cubic) => cubic.tangent_at_start(), } } fn tangent_at_end(&self) -> DVec2 { match self { - PathSeg::Line(line) => line.tangent_at_end(), - PathSeg::Quad(quad) => quad.tangent_at_end(), - PathSeg::Cubic(cubic) => cubic.tangent_at_end(), + Self::Line(line) => line.tangent_at_end(), + Self::Quad(quad) => quad.tangent_at_end(), + Self::Cubic(cubic) => cubic.tangent_at_end(), } } } @@ -351,15 +351,15 @@ impl ManipulatorPointId { #[track_caller] pub fn get_position(&self, vector: &Vector) -> Option { match self { - ManipulatorPointId::Anchor(id) => vector.point_domain.position_from_id(*id), - ManipulatorPointId::PrimaryHandle(id) => vector.segment_from_id(*id).and_then(|bezier| bezier.handle_start()), - ManipulatorPointId::EndHandle(id) => vector.segment_from_id(*id).and_then(|bezier| bezier.handle_end()), + Self::Anchor(id) => vector.point_domain.position_from_id(*id), + Self::PrimaryHandle(id) => vector.segment_from_id(*id).and_then(|bezier| bezier.handle_start()), + Self::EndHandle(id) => vector.segment_from_id(*id).and_then(|bezier| bezier.handle_end()), } } pub fn get_anchor_position(&self, vector: &Vector) -> Option { match self { - ManipulatorPointId::EndHandle(_) | ManipulatorPointId::PrimaryHandle(_) => self.get_anchor(vector).and_then(|id| vector.point_domain.position_from_id(id)), + Self::EndHandle(_) | Self::PrimaryHandle(_) => self.get_anchor(vector).and_then(|id| vector.point_domain.position_from_id(id)), _ => self.get_position(vector), } } @@ -368,14 +368,14 @@ impl ManipulatorPointId { #[must_use] pub fn get_handle_pair(self, vector: &Vector) -> Option<[HandleId; 2]> { match self { - ManipulatorPointId::Anchor(point) => vector.all_connected(point).take(2).collect::>().try_into().ok(), - ManipulatorPointId::PrimaryHandle(segment) => { + Self::Anchor(point) => vector.all_connected(point).take(2).collect::>().try_into().ok(), + Self::PrimaryHandle(segment) => { let point = vector.segment_domain.segment_start_from_id(segment)?; let current = HandleId::primary(segment); let other = vector.segment_domain.all_connected(point).find(|&value| value != current); other.map(|other| [current, other]) } - ManipulatorPointId::EndHandle(segment) => { + Self::EndHandle(segment) => { let point = vector.segment_domain.segment_end_from_id(segment)?; let current = HandleId::end(segment); let other = vector.segment_domain.all_connected(point).find(|&value| value != current); @@ -389,17 +389,17 @@ impl ManipulatorPointId { /// For a handle it is all the handles connected to its corresponding anchor other than the current handle. pub fn get_all_connected_handles(self, vector: &Vector) -> Option> { match self { - ManipulatorPointId::Anchor(point) => { + Self::Anchor(point) => { let connected = vector.all_connected(point).collect::>(); Some(connected) } - ManipulatorPointId::PrimaryHandle(segment) => { + Self::PrimaryHandle(segment) => { let point = vector.segment_domain.segment_start_from_id(segment)?; let current = HandleId::primary(segment); let connected = vector.segment_domain.all_connected(point).filter(|&value| value != current).collect::>(); Some(connected) } - ManipulatorPointId::EndHandle(segment) => { + Self::EndHandle(segment) => { let point = vector.segment_domain.segment_end_from_id(segment)?; let current = HandleId::end(segment); let connected = vector.segment_domain.all_connected(point).filter(|&value| value != current).collect::>(); @@ -412,9 +412,9 @@ impl ManipulatorPointId { #[must_use] pub fn get_anchor(self, vector: &Vector) -> Option { match self { - ManipulatorPointId::Anchor(point) => Some(point), - ManipulatorPointId::PrimaryHandle(segment) => vector.segment_start_from_id(segment), - ManipulatorPointId::EndHandle(segment) => vector.segment_end_from_id(segment), + Self::Anchor(point) => Some(point), + Self::PrimaryHandle(segment) => vector.segment_start_from_id(segment), + Self::EndHandle(segment) => vector.segment_end_from_id(segment), } } @@ -422,9 +422,9 @@ impl ManipulatorPointId { #[must_use] pub fn as_handle(self) -> Option { match self { - ManipulatorPointId::PrimaryHandle(segment) => Some(HandleId::primary(segment)), - ManipulatorPointId::EndHandle(segment) => Some(HandleId::end(segment)), - ManipulatorPointId::Anchor(_) => None, + Self::PrimaryHandle(segment) => Some(HandleId::primary(segment)), + Self::EndHandle(segment) => Some(HandleId::end(segment)), + Self::Anchor(_) => None, } } @@ -432,14 +432,14 @@ impl ManipulatorPointId { #[must_use] pub fn as_anchor(self) -> Option { match self { - ManipulatorPointId::Anchor(point) => Some(point), + Self::Anchor(point) => Some(point), _ => None, } } pub fn get_segment(self) -> Option { match self { - ManipulatorPointId::PrimaryHandle(segment) | ManipulatorPointId::EndHandle(segment) => Some(segment), + Self::PrimaryHandle(segment) | Self::EndHandle(segment) => Some(segment), _ => None, } } diff --git a/node-graph/libraries/vector-types/src/vector/reference_point.rs b/node-graph/libraries/vector-types/src/vector/reference_point.rs index eb03412f5b..75399dd689 100644 --- a/node-graph/libraries/vector-types/src/vector/reference_point.rs +++ b/node-graph/libraries/vector-types/src/vector/reference_point.rs @@ -20,16 +20,16 @@ impl ReferencePoint { pub fn point_in_bounding_box(&self, bounding_box: AxisAlignedBbox) -> Option { let size = bounding_box.size(); let offset = match self { - ReferencePoint::None => return None, - ReferencePoint::TopLeft => DVec2::ZERO, - ReferencePoint::TopCenter => DVec2::new(size.x / 2., 0.), - ReferencePoint::TopRight => DVec2::new(size.x, 0.), - ReferencePoint::CenterLeft => DVec2::new(0., size.y / 2.), - ReferencePoint::Center => DVec2::new(size.x / 2., size.y / 2.), - ReferencePoint::CenterRight => DVec2::new(size.x, size.y / 2.), - ReferencePoint::BottomLeft => DVec2::new(0., size.y), - ReferencePoint::BottomCenter => DVec2::new(size.x / 2., size.y), - ReferencePoint::BottomRight => DVec2::new(size.x, size.y), + Self::None => return None, + Self::TopLeft => DVec2::ZERO, + Self::TopCenter => DVec2::new(size.x / 2., 0.), + Self::TopRight => DVec2::new(size.x, 0.), + Self::CenterLeft => DVec2::new(0., size.y / 2.), + Self::Center => DVec2::new(size.x / 2., size.y / 2.), + Self::CenterRight => DVec2::new(size.x, size.y / 2.), + Self::BottomLeft => DVec2::new(0., size.y), + Self::BottomCenter => DVec2::new(size.x / 2., size.y), + Self::BottomRight => DVec2::new(size.x, size.y), }; Some(bounding_box.start + offset) } @@ -38,16 +38,16 @@ impl ReferencePoint { impl From<&str> for ReferencePoint { fn from(input: &str) -> Self { match input { - "None" => ReferencePoint::None, - "TopLeft" => ReferencePoint::TopLeft, - "TopCenter" => ReferencePoint::TopCenter, - "TopRight" => ReferencePoint::TopRight, - "CenterLeft" => ReferencePoint::CenterLeft, - "Center" => ReferencePoint::Center, - "CenterRight" => ReferencePoint::CenterRight, - "BottomLeft" => ReferencePoint::BottomLeft, - "BottomCenter" => ReferencePoint::BottomCenter, - "BottomRight" => ReferencePoint::BottomRight, + "None" => Self::None, + "TopLeft" => Self::TopLeft, + "TopCenter" => Self::TopCenter, + "TopRight" => Self::TopRight, + "CenterLeft" => Self::CenterLeft, + "Center" => Self::Center, + "CenterRight" => Self::CenterRight, + "BottomLeft" => Self::BottomLeft, + "BottomCenter" => Self::BottomCenter, + "BottomRight" => Self::BottomRight, _ => panic!("Failed parsing unrecognized ReferencePosition enum value '{input}'"), } } @@ -75,29 +75,29 @@ impl From for ReferencePoint { const TOLERANCE: f64 = 1e-5_f64; if input.y.abs() < TOLERANCE { if input.x.abs() < TOLERANCE { - return ReferencePoint::TopLeft; + return Self::TopLeft; } else if (input.x - 0.5).abs() < TOLERANCE { - return ReferencePoint::TopCenter; + return Self::TopCenter; } else if (input.x - 1.).abs() < TOLERANCE { - return ReferencePoint::TopRight; + return Self::TopRight; } } else if (input.y - 0.5).abs() < TOLERANCE { if input.x.abs() < TOLERANCE { - return ReferencePoint::CenterLeft; + return Self::CenterLeft; } else if (input.x - 0.5).abs() < TOLERANCE { - return ReferencePoint::Center; + return Self::Center; } else if (input.x - 1.).abs() < TOLERANCE { - return ReferencePoint::CenterRight; + return Self::CenterRight; } } else if (input.y - 1.).abs() < TOLERANCE { if input.x.abs() < TOLERANCE { - return ReferencePoint::BottomLeft; + return Self::BottomLeft; } else if (input.x - 0.5).abs() < TOLERANCE { - return ReferencePoint::BottomCenter; + return Self::BottomCenter; } else if (input.x - 1.).abs() < TOLERANCE { - return ReferencePoint::BottomRight; + return Self::BottomRight; } } - ReferencePoint::None + Self::None } } diff --git a/node-graph/libraries/vector-types/src/vector/style.rs b/node-graph/libraries/vector-types/src/vector/style.rs index 10079efd4c..c7f7330724 100644 --- a/node-graph/libraries/vector-types/src/vector/style.rs +++ b/node-graph/libraries/vector-types/src/vector/style.rs @@ -97,9 +97,9 @@ impl Fill { /// Find if fill can be represented with only opaque colors pub fn is_opaque(&self) -> bool { match self { - Fill::Solid(color) => color.is_opaque(), - Fill::Gradient(gradient) => gradient.stops.iter().all(|(_, color)| color.is_opaque()), - Fill::None => true, + Self::Solid(color) => color.is_opaque(), + Self::Gradient(gradient) => gradient.stops.iter().all(|(_, color)| color.is_opaque()), + Self::None => true, } } @@ -110,26 +110,26 @@ impl Fill { } impl From for Fill { - fn from(color: Color) -> Fill { - Fill::Solid(color) + fn from(color: Color) -> Self { + Self::Solid(color) } } impl From> for Fill { - fn from(color: Option) -> Fill { - Fill::solid_or_none(color) + fn from(color: Option) -> Self { + Self::solid_or_none(color) } } impl From> for Fill { - fn from(color: Table) -> Fill { - Fill::solid_or_none(color.into()) + fn from(color: Table) -> Self { + Self::solid_or_none(color.into()) } } impl From> for Fill { - fn from(gradient: Table) -> Fill { - Fill::Gradient(Gradient { + fn from(gradient: Table) -> Self { + Self::Gradient(Gradient { stops: gradient.iter().nth(0).map(|row| row.element.clone()).unwrap_or_default(), ..Default::default() }) @@ -137,8 +137,8 @@ impl From> for Fill { } impl From for Fill { - fn from(gradient: Gradient) -> Fill { - Fill::Gradient(gradient) + fn from(gradient: Gradient) -> Self { + Self::Gradient(gradient) } } @@ -187,9 +187,9 @@ impl FillChoice { impl From for FillChoice { fn from(fill: Fill) -> Self { match fill { - Fill::None => FillChoice::None, - Fill::Solid(color) => FillChoice::Solid(color), - Fill::Gradient(gradient) => FillChoice::Gradient(gradient.stops), + Fill::None => Self::None, + Fill::Solid(color) => Self::Solid(color), + Fill::Gradient(gradient) => Self::Gradient(gradient.stops), } } } @@ -217,9 +217,9 @@ pub enum StrokeCap { impl StrokeCap { pub fn svg_name(&self) -> &'static str { match self { - StrokeCap::Butt => "butt", - StrokeCap::Round => "round", - StrokeCap::Square => "square", + Self::Butt => "butt", + Self::Round => "round", + Self::Square => "square", } } } @@ -237,9 +237,9 @@ pub enum StrokeJoin { impl StrokeJoin { pub fn svg_name(&self) -> &'static str { match self { - StrokeJoin::Bevel => "bevel", - StrokeJoin::Miter => "miter", - StrokeJoin::Round => "round", + Self::Bevel => "bevel", + Self::Miter => "miter", + Self::Round => "round", } } } diff --git a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs index b8cfff2304..f885b18857 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs @@ -670,10 +670,7 @@ impl FoundSubpath { } pub fn is_closed(&self) -> bool { - match (self.edges.first(), self.edges.last()) { - (Some(first), Some(last)) => first.start == last.end, - _ => false, - } + self.edges.first() == self.edges.last() } pub fn from_segment(segment: HalfEdge) -> Self { diff --git a/node-graph/libraries/wgpu-executor/src/lib.rs b/node-graph/libraries/wgpu-executor/src/lib.rs index 868c73f60e..3ad00277b8 100644 --- a/node-graph/libraries/wgpu-executor/src/lib.rs +++ b/node-graph/libraries/wgpu-executor/src/lib.rs @@ -60,7 +60,7 @@ pub type Window = web_sys::HtmlCanvasElement; pub type Window = Arc; unsafe impl StaticType for Surface { - type Static = Surface; + type Static = Self; } const VELLO_SURFACE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; diff --git a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs index f5613b0dd7..6cfaca28e1 100644 --- a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs +++ b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs @@ -135,8 +135,8 @@ impl RasterGpuToRasterCpuConverter { } /// Passthrough conversion for GPU tables - no conversion needed -impl<'i> Convert>, &'i WgpuExecutor> for Table> { - async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> Table> { +impl<'i> Convert for Table> { + async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> Self { self } } @@ -179,8 +179,8 @@ impl<'i> Convert, &'i WgpuExecutor> for Raster { } /// Passthrough conversion for CPU tables - no conversion needed -impl<'i> Convert>, &'i WgpuExecutor> for Table> { - async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> Table> { +impl<'i> Convert for Table> { + async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> Self { self } } diff --git a/node-graph/node-macro/src/parsing.rs b/node-graph/node-macro/src/parsing.rs index 74f547b95a..4983ac4528 100644 --- a/node-graph/node-macro/src/parsing.rs +++ b/node-graph/node-macro/src/parsing.rs @@ -83,16 +83,16 @@ impl Parse for ParsedWidgetOverride { let variant = &path.segments[1].ident; match variant.to_string().as_str() { - "Hidden" => Ok(ParsedWidgetOverride::Hidden), + "Hidden" => Ok(Self::Hidden), "String" => { input.parse::()?; let lit: LitStr = input.parse()?; - Ok(ParsedWidgetOverride::String(lit)) + Ok(Self::String(lit)) } "Custom" => { input.parse::()?; let lit: LitStr = input.parse()?; - Ok(ParsedWidgetOverride::Custom(lit)) + Ok(Self::Custom(lit)) } _ => Err(Error::new(variant.span(), "Unknown ParsedWidgetOverride variant")), } @@ -184,7 +184,7 @@ impl Parse for Implementation { ) })?; - Ok(Implementation { + Ok(Self { input: input_type, _arrow: arrow, output: output_type, @@ -287,7 +287,7 @@ impl Parse for NodeFnAttributes { } } - Ok(NodeFnAttributes { + Ok(Self { category, display_name, path, diff --git a/node-graph/node-macro/src/shader_nodes/mod.rs b/node-graph/node-macro/src/shader_nodes/mod.rs index 7ff3677d61..ea77c22aeb 100644 --- a/node-graph/node-macro/src/shader_nodes/mod.rs +++ b/node-graph/node-macro/src/shader_nodes/mod.rs @@ -43,8 +43,8 @@ impl Parse for ShaderNodeType { fn parse(input: ParseStream) -> syn::Result { let ident: Ident = input.parse()?; Ok(match ident.to_string().as_str() { - "None" => ShaderNodeType::None, - "PerPixelAdjust" => ShaderNodeType::PerPixelAdjust(PerPixelAdjust::parse(input)?), + "None" => Self::None, + "PerPixelAdjust" => Self::PerPixelAdjust(PerPixelAdjust::parse(input)?), _ => return Err(Error::new_spanned(&ident, format!("attr 'shader_node' must be one of {:?}", Self::VARIANTS))), }) } @@ -57,7 +57,7 @@ pub trait ShaderCodegen { impl ShaderCodegen for ShaderNodeType { fn codegen(&self, crate_ident: &CrateIdent, parsed: &ParsedNodeFn) -> syn::Result { match self { - ShaderNodeType::None | ShaderNodeType::ShaderNode => (), + Self::None | Self::ShaderNode => (), _ => { if parsed.is_async { return Err(Error::new_spanned(&parsed.fn_name, "Shader nodes must not be async")); @@ -66,8 +66,8 @@ impl ShaderCodegen for ShaderNodeType { } match self { - ShaderNodeType::None | ShaderNodeType::ShaderNode => Ok(ShaderTokens::default()), - ShaderNodeType::PerPixelAdjust(x) => x.codegen(crate_ident, parsed), + Self::None | Self::ShaderNode => Ok(ShaderTokens::default()), + Self::PerPixelAdjust(x) => x.codegen(crate_ident, parsed), } } } diff --git a/node-graph/nodes/blending/src/lib.rs b/node-graph/nodes/blending/src/lib.rs index 6c07eb5490..0520e2f3ac 100644 --- a/node-graph/nodes/blending/src/lib.rs +++ b/node-graph/nodes/blending/src/lib.rs @@ -12,7 +12,7 @@ pub(crate) trait MultiplyAlpha { impl MultiplyAlpha for Color { fn multiply_alpha(&mut self, factor: f64) { - *self = Color::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.)) + *self = Self::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.)) } } impl MultiplyAlpha for Table { @@ -56,7 +56,7 @@ pub(crate) trait MultiplyFill { } impl MultiplyFill for Color { fn multiply_fill(&mut self, factor: f64) { - *self = Color::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.)) + *self = Self::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.)) } } impl MultiplyFill for Table { diff --git a/node-graph/nodes/gcore/src/memo.rs b/node-graph/nodes/gcore/src/memo.rs index fcb4b637d3..6d094d2a2e 100644 --- a/node-graph/nodes/gcore/src/memo.rs +++ b/node-graph/nodes/gcore/src/memo.rs @@ -51,8 +51,8 @@ where } impl MemoNode { - pub fn new(node: CachedNode) -> MemoNode { - MemoNode { cache: Default::default(), node } + pub fn new(node: CachedNode) -> Self { + Self { cache: Default::default(), node } } } @@ -95,8 +95,8 @@ where } impl MonitorNode { - pub fn new(node: N) -> MonitorNode { - MonitorNode { io: Arc::new(Mutex::new(None)), node } + pub fn new(node: N) -> Self { + Self { io: Arc::new(Mutex::new(None)), node } } } diff --git a/node-graph/nodes/math/src/lib.rs b/node-graph/nodes/math/src/lib.rs index 2185a0b334..0e86fe8bfb 100644 --- a/node-graph/nodes/math/src/lib.rs +++ b/node-graph/nodes/math/src/lib.rs @@ -329,13 +329,13 @@ pub trait TangentInverse { fn atan(self, radians: bool) -> Self::Output; } impl TangentInverse for f32 { - type Output = f32; + type Output = Self; fn atan(self, radians: bool) -> Self::Output { if radians { self.atan() } else { self.atan().to_degrees() } } } impl TangentInverse for f64 { - type Output = f64; + type Output = Self; fn atan(self, radians: bool) -> Self::Output { if radians { self.atan() } else { self.atan().to_degrees() } } @@ -476,7 +476,7 @@ trait AbsoluteValue { } impl AbsoluteValue for DVec2 { fn abs(self) -> Self { - DVec2::new(self.x.abs(), self.y.abs()) + Self::new(self.x.abs(), self.y.abs()) } } impl AbsoluteValue for f32 { diff --git a/node-graph/nodes/raster/src/adjust.rs b/node-graph/nodes/raster/src/adjust.rs index 0390c6da47..921dc8e020 100644 --- a/node-graph/nodes/raster/src/adjust.rs +++ b/node-graph/nodes/raster/src/adjust.rs @@ -3,8 +3,8 @@ use no_std_types::color::Color; pub trait Adjust

{ fn adjust(&mut self, map_fn: impl Fn(&P) -> P); } -impl Adjust for Color { - fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) { +impl Adjust for Color { + fn adjust(&mut self, map_fn: impl Fn(&Self) -> Self) { *self = map_fn(self); } } diff --git a/node-graph/nodes/raster/src/blending_nodes.rs b/node-graph/nodes/raster/src/blending_nodes.rs index f4ee1473ed..3ec86155d3 100644 --- a/node-graph/nodes/raster/src/blending_nodes.rs +++ b/node-graph/nodes/raster/src/blending_nodes.rs @@ -13,8 +13,8 @@ use vector_types::GradientStops; pub trait Blend { fn blend(&self, under: &Self, blend_fn: impl Fn(P, P) -> P) -> Self; } -impl Blend for Color { - fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self { +impl Blend for Color { + fn blend(&self, under: &Self, blend_fn: impl Fn(Self, Self) -> Self) -> Self { blend_fn(*self, *under) } } @@ -75,7 +75,7 @@ mod blend_std { (position, color) }) .collect::>(); - GradientStops::new(stops) + Self::new(stops) } } } diff --git a/node-graph/nodes/raster/src/std_nodes.rs b/node-graph/nodes/raster/src/std_nodes.rs index 2d0b6a62cd..f47aacdbf0 100644 --- a/node-graph/nodes/raster/src/std_nodes.rs +++ b/node-graph/nodes/raster/src/std_nodes.rs @@ -25,7 +25,7 @@ pub enum Error { impl From for Error { fn from(e: std::io::Error) -> Self { - Error::IO(e) + Self::IO(e) } } diff --git a/node-graph/nodes/text/src/lib.rs b/node-graph/nodes/text/src/lib.rs index b4ac6f4566..18eaeac08c 100644 --- a/node-graph/nodes/text/src/lib.rs +++ b/node-graph/nodes/text/src/lib.rs @@ -32,10 +32,10 @@ pub enum TextAlign { impl From for parley::Alignment { fn from(val: TextAlign) -> Self { match val { - TextAlign::Left => parley::Alignment::Left, - TextAlign::Center => parley::Alignment::Center, - TextAlign::Right => parley::Alignment::Right, - TextAlign::JustifyLeft => parley::Alignment::Justify, + TextAlign::Left => Self::Left, + TextAlign::Center => Self::Center, + TextAlign::Right => Self::Right, + TextAlign::JustifyLeft => Self::Justify, } } } diff --git a/node-graph/nodes/text/src/text_context.rs b/node-graph/nodes/text/src/text_context.rs index fc49ecd602..d8a78a6727 100644 --- a/node-graph/nodes/text/src/text_context.rs +++ b/node-graph/nodes/text/src/text_context.rs @@ -27,7 +27,7 @@ impl TextContext { /// Access the thread-local TextContext instance for text processing operations pub fn with_thread_local(f: F) -> R where - F: FnOnce(&mut TextContext) -> R, + F: FnOnce(&mut Self) -> R, { THREAD_TEXT.with_borrow_mut(f) } diff --git a/node-graph/nodes/vector/src/vector_nodes.rs b/node-graph/nodes/vector/src/vector_nodes.rs index a979db669f..fa32652c37 100644 --- a/node-graph/nodes/vector/src/vector_nodes.rs +++ b/node-graph/nodes/vector/src/vector_nodes.rs @@ -686,10 +686,10 @@ pub mod extrude_algorithms { impl Found { fn update(&mut self, value: f64) { *self = match (*self, value > 0.) { - (Found::None, true) => Found::Positive, - (Found::None, false) => Found::Negative, - (Found::Positive, true) | (Found::Negative, false) => Found::Both, - _ => Found::Invalid, + (Self::None, true) => Self::Positive, + (Self::None, false) => Self::Negative, + (Self::Positive, true) | (Self::Negative, false) => Self::Both, + _ => Self::Invalid, }; } }