diff --git a/editor/src/dispatcher.rs b/editor/src/dispatcher.rs index 79bda1b3..4601f4d3 100644 --- a/editor/src/dispatcher.rs +++ b/editor/src/dispatcher.rs @@ -442,7 +442,7 @@ mod test { assert_eq!(layers_before_copy.len(), 3); assert_eq!(layers_after_copy.len(), 6); - println!("{:?} {:?}", layers_after_copy, layers_before_copy); + println!("{layers_after_copy:?} {layers_before_copy:?}"); assert_eq!(layers_after_copy[5], shape_id); } diff --git a/editor/src/messages/input_mapper/utility_types/input_keyboard.rs b/editor/src/messages/input_mapper/utility_types/input_keyboard.rs index 99a26755..5528d438 100644 --- a/editor/src/messages/input_mapper/utility_types/input_keyboard.rs +++ b/editor/src/messages/input_mapper/utility_types/input_keyboard.rs @@ -479,7 +479,7 @@ impl Iterator for BitVectorIter<'_, LENGTH> { impl Display for BitVector { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { for storage in self.0.iter().rev() { - write!(f, "{:0width$b}", storage, width = STORAGE_SIZE_BITS)?; + write!(f, "{storage:0STORAGE_SIZE_BITS$b}")?; } Ok(()) diff --git a/editor/src/messages/message.rs b/editor/src/messages/message.rs index a60ca681..b23d530e 100644 --- a/editor/src/messages/message.rs +++ b/editor/src/messages/message.rs @@ -70,13 +70,11 @@ mod test { fn print_tree_node(tree: &DebugMessageTree, prefix: &str, is_last: bool, file: &mut std::fs::File) { // Print the current node let (branch, child_prefix) = if tree.message_handler_data_fields().is_some() || tree.message_handler_fields().is_some() { - ("├── ", format!("{}│ ", prefix)) + ("├── ", format!("{prefix}│ ")) + } else if is_last { + ("└── ", format!("{prefix} ")) } else { - if is_last { - ("└── ", format!("{} ", prefix)) - } else { - ("├── ", format!("{}│ ", prefix)) - } + ("├── ", format!("{prefix}│ ")) }; if tree.path().is_empty() { @@ -101,7 +99,7 @@ mod test { let is_last_field = i == len - 1; let branch = if is_last_field { "└── " } else { "├── " }; - file.write_all(format!("{}{}{}\n", child_prefix, branch, field).as_bytes()).unwrap(); + file.write_all(format!("{child_prefix}{branch}{field}\n").as_bytes()).unwrap(); } } @@ -109,9 +107,9 @@ mod test { if let Some(data) = tree.message_handler_fields() { let len = data.fields().len(); let (branch, child_prefix) = if tree.message_handler_data_fields().is_some() { - ("├── ", format!("{}│ ", prefix)) + ("├── ", format!("{prefix}│ ")) } else { - ("└── ", format!("{} ", prefix)) + ("└── ", format!("{prefix} ")) }; const FRONTEND_MESSAGE_STR: &str = "FrontendMessage"; diff --git a/editor/src/messages/portfolio/document/graph_operation/transform_utils.rs b/editor/src/messages/portfolio/document/graph_operation/transform_utils.rs index 7d11ccfe..387b5502 100644 --- a/editor/src/messages/portfolio/document/graph_operation/transform_utils.rs +++ b/editor/src/messages/portfolio/document/graph_operation/transform_utils.rs @@ -91,6 +91,32 @@ pub fn get_current_normalized_pivot(inputs: &[NodeInput]) -> DVec2 { if let Some(&TaggedValue::DVec2(pivot)) = inputs[5].as_value() { pivot } else { DVec2::splat(0.5) } } +/// Expand a bounds to avoid div zero errors +fn clamp_bounds(bounds_min: DVec2, mut bounds_max: DVec2) -> [DVec2; 2] { + let bounds_size = bounds_max - bounds_min; + if bounds_size.x < 1e-10 { + bounds_max.x = bounds_min.x + 1.; + } + if bounds_size.y < 1e-10 { + bounds_max.y = bounds_min.y + 1.; + } + [bounds_min, bounds_max] +} +/// Returns corners of all subpaths +fn subpath_bounds(subpaths: &[Subpath]) -> [DVec2; 2] { + subpaths + .iter() + .filter_map(|subpath| subpath.bounding_box()) + .reduce(|b1, b2| [b1[0].min(b2[0]), b1[1].max(b2[1])]) + .unwrap_or_default() +} + +/// Returns corners of all subpaths (but expanded to avoid division-by-zero errors) +pub fn nonzero_subpath_bounds(subpaths: &[Subpath]) -> [DVec2; 2] { + let [bounds_min, bounds_max] = subpath_bounds(subpaths); + clamp_bounds(bounds_min, bounds_max) +} + #[cfg(test)] mod tests { use super::*; @@ -138,29 +164,3 @@ mod tests { } } } - -/// Expand a bounds to avoid div zero errors -fn clamp_bounds(bounds_min: DVec2, mut bounds_max: DVec2) -> [DVec2; 2] { - let bounds_size = bounds_max - bounds_min; - if bounds_size.x < 1e-10 { - bounds_max.x = bounds_min.x + 1.; - } - if bounds_size.y < 1e-10 { - bounds_max.y = bounds_min.y + 1.; - } - [bounds_min, bounds_max] -} -/// Returns corners of all subpaths -fn subpath_bounds(subpaths: &[Subpath]) -> [DVec2; 2] { - subpaths - .iter() - .filter_map(|subpath| subpath.bounding_box()) - .reduce(|b1, b2| [b1[0].min(b2[0]), b1[1].max(b2[1])]) - .unwrap_or_default() -} - -/// Returns corners of all subpaths (but expanded to avoid division-by-zero errors) -pub fn nonzero_subpath_bounds(subpaths: &[Subpath]) -> [DVec2; 2] { - let [bounds_min, bounds_max] = subpath_bounds(subpaths); - clamp_bounds(bounds_min, bounds_max) -} diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index d1888c96..b623c67f 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -46,7 +46,7 @@ impl NodePropertiesContext<'_> { return None; }; widget_override_lambda(*node_id, index, self) - .map_err(|error| log::error!("Error in widget override lambda: {}", error)) + .map_err(|error| log::error!("Error in widget override lambda: {error}")) .ok() } else { None @@ -1944,10 +1944,10 @@ fn static_input_properties() -> InputProperties { "string".to_string(), Box::new(|node_id, index, context| { let Some(value) = context.network_interface.input_data(&node_id, index, "string_properties", context.selection_network_path) else { - return Err(format!("Could not get string properties for node {}", node_id)); + return Err(format!("Could not get string properties for node {node_id}")); }; let Some(string) = value.as_str() else { - return Err(format!("Could not downcast string properties for node {}", node_id)); + return Err(format!("Could not downcast string properties for node {node_id}")); }; Ok(node_properties::string_properties(string)) }), diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs index 85ce4b51..c788a059 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs @@ -60,7 +60,7 @@ pub(super) fn post_process_nodes(mut custom: Vec) -> Vec document_node: DocumentNode { inputs, manual_composition: Some(input_type.clone()), - implementation: DocumentNodeImplementation::ProtoNode(id.clone().into()), + implementation: DocumentNodeImplementation::ProtoNode(id.clone()), visible: true, skip_deduplication: false, ..Default::default() diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs index 6f189833..c044c25a 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs @@ -1516,7 +1516,7 @@ impl<'a> MessageHandler> for NodeG let mut nodes = Vec::new(); for node_id in &self.frontend_nodes { let Some(node_bbox) = network_interface.node_bounding_box(node_id, breadcrumb_network_path) else { - log::error!("Could not get bbox for node: {:?}", node_id); + log::error!("Could not get bbox for node: {node_id:?}"); continue; }; @@ -1721,7 +1721,7 @@ impl<'a> MessageHandler> for NodeG } NodeGraphMessage::ToggleLocked { node_id } => { let Some(node_metadata) = network_interface.document_network_metadata().persistent_metadata.node_metadata.get(&node_id) else { - log::error!("Cannot get node {:?} in NodeGraphMessage::ToggleLocked", node_id); + log::error!("Cannot get node {node_id:?} in NodeGraphMessage::ToggleLocked"); return; }; @@ -2486,7 +2486,7 @@ impl NodeGraphMessageHandler { data_type: frontend_data_type, name: "Output 1".to_string(), description: String::new(), - resolved_type: format!("{:?}", output_type), + resolved_type: format!("{output_type:?}"), connected_to, }) } else { @@ -2518,7 +2518,7 @@ impl NodeGraphMessageHandler { data_type, name: output_name, description: String::new(), - resolved_type: format!("{:?}", output_type), + resolved_type: format!("{output_type:?}"), connected_to, }); } diff --git a/editor/src/messages/portfolio/document/overlays/utility_types_vello.rs b/editor/src/messages/portfolio/document/overlays/utility_types_vello.rs index 479f6a37..1a752226 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_types_vello.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_types_vello.rs @@ -1156,7 +1156,7 @@ impl OverlayContextInternal { let move_to = last_point != Some(start_id); last_point = Some(end_id); - self.bezier_to_path(bezier, row.transform.clone(), move_to, &mut path); + self.bezier_to_path(bezier, *row.transform, move_to, &mut path); } // Render the path 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 93ad244c..237a5f8e 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -73,10 +73,8 @@ impl NodeNetworkInterface { fix_network(network); } if let DocumentNodeImplementation::ProtoNode(protonode) = &node.implementation { - if protonode.name.contains("PathModifyNode") { - if node.inputs.len() < 3 { - node.inputs.push(NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)); - } + if protonode.name.contains("PathModifyNode") && node.inputs.len() < 3 { + node.inputs.push(NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)); } } } @@ -821,7 +819,7 @@ impl NodeNetworkInterface { data_type, name, description, - resolved_type: format!("{:?}", input_type), + resolved_type: format!("{input_type:?}"), connected_to, }, click_target, @@ -1069,7 +1067,7 @@ impl NodeNetworkInterface { pub fn reference(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&Option> { let Some(node_metadata) = self.node_metadata(node_id, network_path) else { - log::error!("Could not get reference for node: {:?}", node_id); + log::error!("Could not get reference for node: {node_id:?}"); return None; }; Some(&node_metadata.persistent_metadata.reference) @@ -2522,7 +2520,7 @@ impl NodeNetworkInterface { InputConnector::Node { node_id, input_index } => { let input_metadata = self.transient_input_metadata(node_id, *input_index, network_path)?; let TransientMetadata::Loaded(wire) = &input_metadata.wire else { - log::error!("Could not load wire for input: {:?}", input); + log::error!("Could not load wire for input: {input:?}"); return None; }; wire.clone() @@ -2530,7 +2528,7 @@ impl NodeNetworkInterface { InputConnector::Export(export_index) => { let network_metadata = self.network_metadata(network_path)?; let Some(TransientMetadata::Loaded(wire)) = network_metadata.transient_metadata.wires.get(*export_index) else { - log::error!("Could not load wire for input: {:?}", input); + log::error!("Could not load wire for input: {input:?}"); return None; }; wire.clone() @@ -2701,12 +2699,12 @@ impl NodeNetworkInterface { return None; } let Some(input_position) = self.get_input_center(&input, network_path) else { - log::error!("Could not get dom rect for wire end in root node: {:?}", input); + log::error!("Could not get dom rect for wire end in root node: {input:?}"); return None; }; let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index); let Some(output_position) = self.get_output_center(&upstream_output, network_path) else { - log::error!("Could not get dom rect for wire start in root node: {:?}", upstream_output); + log::error!("Could not get dom rect for wire start in root node: {upstream_output:?}"); return None; }; let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0); @@ -2733,7 +2731,7 @@ impl NodeNetworkInterface { /// Returns the vector subpath and a boolean of whether the wire should be thick. pub fn vector_wire_from_input(&mut self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, bool)> { let Some(input_position) = self.get_input_center(input, network_path) else { - log::error!("Could not get dom rect for wire end: {:?}", input); + log::error!("Could not get dom rect for wire end: {input:?}"); return None; }; // An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector @@ -2741,7 +2739,7 @@ impl NodeNetworkInterface { return Some((BezPath::new(), false)); }; let Some(output_position) = self.get_output_center(&upstream_output, network_path) else { - log::error!("Could not get dom rect for wire start: {:?}", upstream_output); + log::error!("Could not get dom rect for wire start: {upstream_output:?}"); return None; }; let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0); @@ -3357,7 +3355,7 @@ impl NodeNetworkInterface { self.selected_nodes() .0 .iter() - .filter(|node| self.is_layer(&node, &[])) + .filter(|node| self.is_layer(node, &[])) .filter_map(|layer| self.document_metadata.bounding_box_viewport(LayerNodeIdentifier::new(*layer, self))) .reduce(Quad::combine_bounds) } @@ -3366,7 +3364,7 @@ impl NodeNetworkInterface { self.selected_nodes() .0 .iter() - .filter(|node| self.is_layer(&node, &[]) && !self.is_locked(&node, &[])) + .filter(|node| self.is_layer(node, &[]) && !self.is_locked(node, &[])) .filter_map(|layer| self.document_metadata.bounding_box_viewport(LayerNodeIdentifier::new(*layer, self))) .reduce(Quad::combine_bounds) } @@ -4138,7 +4136,7 @@ impl NodeNetworkInterface { if let DocumentNodeImplementation::Network(network) = &node.implementation { let number_of_exports = network.exports.len(); let Some(metadata) = self.node_metadata_mut(node_id, network_path) else { - log::error!("Could not get metadata for node: {:?}", node_id); + log::error!("Could not get metadata for node: {node_id:?}"); return; }; metadata.persistent_metadata.output_names.resize(number_of_exports, "".to_string()); diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index cf95889a..a8f70850 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -1083,8 +1083,8 @@ mod tests { *hashmap.entry(node.node.clone()).or_default() += 1; }); let duplicates = hashmap.iter().filter(|(_, count)| **count > 1).map(|(node, _)| &node.name).collect::>(); - if duplicates.len() > 0 { - panic!("Duplicate entries in `NODE_REPLACEMENTS`: {:?}", duplicates); + if !duplicates.is_empty() { + panic!("Duplicate entries in `NODE_REPLACEMENTS`: {duplicates:?}"); } } } diff --git a/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs b/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs index 1e58f872..d6229502 100644 --- a/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs @@ -101,14 +101,9 @@ impl Circle { }; let dimensions = (start - end).abs(); - let radius: f64; // We keep the smaller dimension's scale at 1 and scale the other dimension accordingly - if dimensions.x > dimensions.y { - radius = dimensions.y / 2.; - } else { - radius = dimensions.x / 2.; - } + let radius: f64 = if dimensions.x > dimensions.y { dimensions.y / 2. } else { dimensions.x / 2. }; responses.add(NodeGraphMessage::SetInput { input_connector: InputConnector::node(node_id, 1), diff --git a/editor/src/messages/tool/common_functionality/shapes/line_shape.rs b/editor/src/messages/tool/common_functionality/shapes/line_shape.rs index 8bd22b0b..f7975f77 100644 --- a/editor/src/messages/tool/common_functionality/shapes/line_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/line_shape.rs @@ -210,18 +210,18 @@ mod test_line_tool { async fn get_line_node_inputs(editor: &mut EditorTestUtils) -> Option<(DVec2, DVec2)> { let document = editor.active_document(); let network_interface = &document.network_interface; - let node_id = network_interface + + network_interface .selected_nodes() .selected_visible_and_unlocked_layers(network_interface) .filter_map(|layer| { - let node_inputs = NodeGraphLayer::new(layer, &network_interface).find_node_inputs("Line")?; + let node_inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs("Line")?; let (Some(&TaggedValue::DVec2(start)), Some(&TaggedValue::DVec2(end))) = (node_inputs[1].as_value(), node_inputs[2].as_value()) else { return None; }; Some((start, end)) }) - .next(); - node_id + .next() } #[tokio::test] @@ -245,11 +245,7 @@ mod test_line_tool { editor.new_document().await; editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 2. }).await; editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(100., 50.) }).await; - editor - .handle_message(NavigationMessage::CanvasTiltSet { - angle_radians: (30. as f64).to_radians(), - }) - .await; + editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 30_f64.to_radians() }).await; editor.drag_tool(ToolType::Line, 0., 0., 100., 100., ModifierKeys::empty()).await; if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await { let document = editor.active_document(); @@ -261,15 +257,11 @@ mod test_line_tool { assert!( (start_input - expected_start).length() < 1., - "Start point should match expected document coordinates. Got {:?}, expected {:?}", - start_input, - expected_start + "Start point should match expected document coordinates. Got {start_input:?}, expected {expected_start:?}" ); assert!( (end_input - expected_end).length() < 1., - "End point should match expected document coordinates. Got {:?}, expected {:?}", - end_input, - expected_end + "End point should match expected document coordinates. Got {end_input:?}, expected {expected_end:?}" ); } else { panic!("Line was not created successfully with transformed viewport"); @@ -292,8 +284,8 @@ mod test_line_tool { (updated_start, updated_end) => { let updated_line_vec = updated_end - updated_start; let updated_angle = updated_line_vec.angle_to(DVec2::X); - print!("{:?}", original_angle); - print!("{:?}", updated_angle); + print!("{original_angle:?}"); + print!("{updated_angle:?}"); assert!( line_vec.normalize().dot(updated_line_vec.normalize()).abs() - 1. < 1e-6, "Line angle should be locked when Ctrl is kept pressed" diff --git a/editor/src/messages/tool/tool_messages/artboard_tool.rs b/editor/src/messages/tool/tool_messages/artboard_tool.rs index 63404b45..bd3c4e6c 100644 --- a/editor/src/messages/tool/tool_messages/artboard_tool.rs +++ b/editor/src/messages/tool/tool_messages/artboard_tool.rs @@ -569,7 +569,7 @@ mod test_artboard { async fn get_artboards(editor: &mut EditorTestUtils) -> Table { let instrumented = match editor.eval_graph().await { Ok(instrumented) => instrumented, - Err(e) => panic!("Failed to evaluate graph: {}", e), + Err(e) => panic!("Failed to evaluate graph: {e}"), }; instrumented .grab_all_input::>(&editor.runtime) diff --git a/editor/src/messages/tool/tool_messages/freehand_tool.rs b/editor/src/messages/tool/tool_messages/freehand_tool.rs index b22ca676..f33b0435 100644 --- a/editor/src/messages/tool/tool_messages/freehand_tool.rs +++ b/editor/src/messages/tool/tool_messages/freehand_tool.rs @@ -416,7 +416,10 @@ mod test_freehand { fn verify_path_points(vector_and_transform_list: &[(Vector, DAffine2)], expected_captured_points: &[DVec2], tolerance: f64) -> Result<(), String> { assert_eq!(vector_and_transform_list.len(), 1, "There should be one row of Vector geometry"); - let (vector, transform) = vector_and_transform_list.iter().find(|(data, _)| data.point_domain.ids().len() > 0).ok_or("Could not find path data")?; + let (vector, transform) = vector_and_transform_list + .iter() + .find(|(data, _)| !data.point_domain.ids().is_empty()) + .ok_or("Could not find path data")?; let point_count = vector.point_domain.ids().len(); let segment_count = vector.segment_domain.ids().len(); @@ -424,7 +427,7 @@ mod test_freehand { let actual_positions: Vec = vector.point_domain.positions().iter().map(|&position| transform.transform_point2(position)).collect(); if segment_count != point_count - 1 { - return Err(format!("Expected segments to be one less than points, got {} segments for {} points", segment_count, point_count)); + return Err(format!("Expected segments to be one less than points, got {segment_count} segments for {point_count} points")); } if point_count != expected_captured_points.len() { @@ -434,7 +437,7 @@ mod test_freehand { for (i, (&expected, &actual)) in expected_captured_points.iter().zip(actual_positions.iter()).enumerate() { let distance = (expected - actual).length(); if distance >= tolerance { - return Err(format!("Point {} position mismatch: expected {:?}, got {:?} (distance: {})", i, expected, actual, distance)); + return Err(format!("Point {i} position mismatch: expected {expected:?}, got {actual:?} (distance: {distance})")); } } @@ -508,7 +511,7 @@ mod test_freehand { let initial_point_count = initial_vector.point_domain.ids().len(); let initial_segment_count = initial_vector.segment_domain.ids().len(); - assert!(initial_point_count >= 2, "Expected at least 2 points in initial path, found {}", initial_point_count); + assert!(initial_point_count >= 2, "Expected at least 2 points in initial path, found {initial_point_count}"); assert_eq!( initial_segment_count, initial_point_count - 1, @@ -569,17 +572,13 @@ mod test_freehand { assert!( extended_point_count > initial_point_count, - "Expected more points after extension, initial: {}, after extension: {}", - initial_point_count, - extended_point_count + "Expected more points after extension, initial: {initial_point_count}, after extension: {extended_point_count}" ); assert_eq!( extended_segment_count, extended_point_count - 1, - "Expected segments to be one less than points, points: {}, segments: {}", - extended_point_count, - extended_segment_count + "Expected segments to be one less than points, points: {extended_point_count}, segments: {extended_segment_count}" ); let layer_count = { @@ -627,8 +626,8 @@ mod test_freehand { let existing_layer_id = { let document = editor.active_document(); - let layer = document.metadata().all_layers().next().unwrap(); - layer + + document.metadata().all_layers().next().unwrap() }; editor @@ -685,9 +684,7 @@ mod test_freehand { assert!( final_point_count > initial_point_count, - "Expected more points after appending to layer, initial: {}, after append: {}", - initial_point_count, - final_point_count + "Expected more points after appending to layer, initial: {initial_point_count}, after append: {final_point_count}" ); let expected_new_points = second_path_points.len(); diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index 0b12abe6..848dfaf6 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -552,7 +552,7 @@ mod test_gradient { async fn get_fills(editor: &mut EditorTestUtils) -> Vec<(Fill, DAffine2)> { let instrumented = match editor.eval_graph().await { Ok(instrumented) => instrumented, - Err(e) => panic!("Failed to evaluate graph: {}", e), + Err(e) => panic!("Failed to evaluate graph: {e}"), }; let document = editor.active_document(); @@ -573,7 +573,7 @@ mod test_gradient { let (fill, transform) = fills.first().unwrap(); let gradient = fill.as_gradient().expect("Expected gradient fill type"); - (gradient.clone(), transform.clone()) + (gradient.clone(), *transform) } fn assert_stops_at_positions(actual_positions: &[f64], expected_positions: &[f64], tolerance: f64) { @@ -586,7 +586,7 @@ mod test_gradient { ); for (i, (actual, expected)) in actual_positions.iter().zip(expected_positions.iter()).enumerate() { - assert!((actual - expected).abs() < tolerance, "Stop {}: Expected position near {}, got {}", i, expected, actual); + assert!((actual - expected).abs() < tolerance, "Stop {i}: Expected position near {expected}, got {actual}"); } } @@ -713,8 +713,7 @@ mod test_gradient { let positions: Vec = updated_gradient.stops.iter().map(|(pos, _)| *pos).collect(); assert!( positions.iter().any(|pos| (pos - 0.5).abs() < 0.1), - "Expected to find a stop near position 0.5, but found: {:?}", - positions + "Expected to find a stop near position 0.5, but found: {positions:?}" ); } @@ -782,7 +781,7 @@ mod test_gradient { // Verify the end point has been updated to the new position let updated_end = transform.transform_point2(updated_gradient.end); - assert!(updated_end.abs_diff_eq(DVec2::new(100., 50.), 1e-10), "Expected end point at (100, 50), got {:?}", updated_end); + assert!(updated_end.abs_diff_eq(DVec2::new(100., 50.), 1e-10), "Expected end point at (100, 50), got {updated_end:?}"); } #[tokio::test] diff --git a/editor/src/messages/tool/tool_messages/select_tool.rs b/editor/src/messages/tool/tool_messages/select_tool.rs index 8f8e1344..f6321129 100644 --- a/editor/src/messages/tool/tool_messages/select_tool.rs +++ b/editor/src/messages/tool/tool_messages/select_tool.rs @@ -202,11 +202,11 @@ impl SelectTool { let list = ::list(); list.iter().flat_map(|i| i.iter()).map(move |(operation, info)| { let mut tooltip = info.label.to_string(); - if let Some(doc) = info.docstring.as_deref() { + if let Some(doc) = info.docstring { tooltip.push_str("\n\n"); tooltip.push_str(doc); } - IconButton::new(info.icon.as_deref().unwrap(), 24) + IconButton::new(info.icon.unwrap(), 24) .tooltip(tooltip) .disabled(selected_count == 0) .on_update(move |_| { @@ -852,7 +852,13 @@ impl Fsm for SelectToolFsmState { if let Some(pivot) = pivot { let offset = tool_data .pivot_gizmo_start - .map(|offset| tool_data.pivot_gizmo.pivot_disconnected().then_some(tool_data.drag_current - offset).unwrap_or_default()) + .map(|offset| { + if tool_data.pivot_gizmo.pivot_disconnected() { + tool_data.drag_current - offset + } else { + Default::default() + } + }) .unwrap_or_default(); let shift = tool_data.pivot_gizmo_shift.unwrap_or_default(); overlay_context.pivot(pivot + offset + shift, angle); @@ -895,7 +901,7 @@ impl Fsm for SelectToolFsmState { color } else { let color_string = &graphene_std::Color::from_rgb_str(color.strip_prefix('#').unwrap()).unwrap().with_alpha(0.25).to_rgba_hex_srgb(); - &format!("#{}", color_string) + &format!("#{color_string}") }; let line_center = tool_data.line_center; overlay_context.line(line_center - direction * viewport_diagonal, line_center + direction * viewport_diagonal, Some(color), None); @@ -1455,7 +1461,11 @@ impl Fsm for SelectToolFsmState { tool_data.select_single_layer = None; if let Some(start) = tool_data.pivot_gizmo_start { - let offset = tool_data.pivot_gizmo.pivot_disconnected().then_some(tool_data.drag_current - start).unwrap_or_default(); + let offset = if tool_data.pivot_gizmo.pivot_disconnected() { + tool_data.drag_current - start + } else { + Default::default() + }; if let Some(v) = tool_data.pivot_gizmo.pivot.pivot.as_mut() { *v += offset; } @@ -1649,7 +1659,9 @@ impl Fsm for SelectToolFsmState { } (_, SelectToolMessage::PivotShift { offset, flush }) => { if flush { - tool_data.pivot_gizmo.pivot.pivot.as_mut().map(|v| *v += tool_data.pivot_gizmo_shift.take().unwrap_or_default()); + if let Some(v) = tool_data.pivot_gizmo.pivot.pivot.as_mut() { + *v += tool_data.pivot_gizmo_shift.take().unwrap_or_default(); + } let pivot_gizmo = tool_data.pivot_gizmo(); responses.add(TransformLayerMessage::SetPivotGizmo { pivot_gizmo }); return self; diff --git a/editor/src/messages/tool/tool_messages/spline_tool.rs b/editor/src/messages/tool/tool_messages/spline_tool.rs index 268890f5..0de3ac6e 100644 --- a/editor/src/messages/tool/tool_messages/spline_tool.rs +++ b/editor/src/messages/tool/tool_messages/spline_tool.rs @@ -606,11 +606,7 @@ mod test_spline_tool { assert!( distance < epsilon, - "Point {} position mismatch: expected {:?}, got {:?} (distance: {})", - i, - expected_point, - actual_point, - distance + "Point {i} position mismatch: expected {expected_point:?}, got {actual_point:?} (distance: {distance})" ); } } @@ -644,8 +640,8 @@ mod test_spline_tool { // Verify initial spline has correct number of points and segments let initial_point_count = first_vector.point_domain.ids().len(); let initial_segment_count = first_vector.segment_domain.ids().len(); - assert_eq!(initial_point_count, 3, "Expected 3 points in initial spline, found {}", initial_point_count); - assert_eq!(initial_segment_count, 2, "Expected 2 segments in initial spline, found {}", initial_segment_count); + assert_eq!(initial_point_count, 3, "Expected 3 points in initial spline, found {initial_point_count}"); + assert_eq!(initial_segment_count, 2, "Expected 2 segments in initial spline, found {initial_segment_count}"); let layer_to_viewport = document.metadata().transform_to_viewport(spline_layer); @@ -679,8 +675,8 @@ mod test_spline_tool { let extended_point_count = extended_vector.point_domain.ids().len(); let extended_segment_count = extended_vector.segment_domain.ids().len(); - assert_eq!(extended_point_count, 5, "Expected 5 points in extended spline, found {}", extended_point_count); - assert_eq!(extended_segment_count, 4, "Expected 4 segments in extended spline, found {}", extended_segment_count); + assert_eq!(extended_point_count, 5, "Expected 5 points in extended spline, found {extended_point_count}"); + assert_eq!(extended_segment_count, 4, "Expected 4 segments in extended spline, found {extended_segment_count}"); // Verify the spline node is still the same let extended_spline_node = find_spline(document, spline_layer).expect("Spline node not found after extension"); @@ -715,7 +711,7 @@ mod test_spline_tool { // Evaluate the graph to ensure everything is processed if let Err(e) = editor.eval_graph().await { - panic!("Graph evaluation failed: {}", e); + panic!("Graph evaluation failed: {e}"); } // Get the layer and vector data @@ -755,7 +751,7 @@ mod test_spline_tool { // Evaluating the graph to ensure everything is processed if let Err(e) = editor.eval_graph().await { - panic!("Graph evaluation failed: {}", e); + panic!("Graph evaluation failed: {e}"); } // Get the layer and vector data @@ -793,7 +789,7 @@ mod test_spline_tool { // Evaluating the graph to ensure everything is processed if let Err(e) = editor.eval_graph().await { - panic!("Graph evaluation failed: {}", e); + panic!("Graph evaluation failed: {e}"); } // Get the layer and vector data @@ -832,7 +828,7 @@ mod test_spline_tool { editor.handle_message(SplineToolMessage::Confirm).await; if let Err(e) = editor.eval_graph().await { - panic!("Graph evaluation failed: {}", e); + panic!("Graph evaluation failed: {e}"); } // Get the layer and vector data @@ -889,8 +885,8 @@ mod test_spline_tool { let point_count = vector.point_domain.ids().len(); let segment_count = vector.segment_domain.ids().len(); - assert_eq!(point_count, 3, "Expected 3 points in the spline, found {}", point_count); - assert_eq!(segment_count, 2, "Expected 2 segments in the spline, found {}", segment_count); + assert_eq!(point_count, 3, "Expected 3 points in the spline, found {point_count}"); + assert_eq!(segment_count, 2, "Expected 2 segments in the spline, found {segment_count}"); let layer_to_viewport = document.metadata().transform_to_viewport(spline_layer); diff --git a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs index d07cc31d..e971c3f3 100644 --- a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs +++ b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs @@ -189,7 +189,7 @@ impl MessageHandler> for let format_rounded = |value: f64, precision: usize| { if self.typing.digits.is_empty() || !self.transform_operation.can_begin_typing() { - format!("{:.*}", precision, value).trim_end_matches('0').trim_end_matches('.').to_string() + format!("{value:.precision$}").trim_end_matches('0').trim_end_matches('.').to_string() } else { self.typing.string.clone() } @@ -892,7 +892,7 @@ mod test_transform_layer { let final_transform = get_layer_transform(&mut editor, layer).await.unwrap(); let translation_diff = (final_transform.translation - original_transform.translation).length(); - assert!(translation_diff > 10., "Transform should have changed after applying transformation. Diff: {}", translation_diff); + assert!(translation_diff > 10., "Transform should have changed after applying transformation. Diff: {translation_diff}"); } #[tokio::test] @@ -927,9 +927,7 @@ mod test_transform_layer { // Verify transform is either restored to original OR reset to identity assert!( (final_translation - original_translation).length() < 5. || final_translation.length() < 0.001, - "Transform neither restored to original nor reset to identity. Original: {:?}, Final: {:?}", - original_translation, - final_translation + "Transform neither restored to original nor reset to identity. Original: {original_translation:?}, Final: {final_translation:?}" ); } @@ -958,11 +956,11 @@ mod test_transform_layer { editor.handle_message(TransformLayerMessage::ApplyTransformOperation { final_transform: true }).await; let final_transform = get_layer_transform(&mut editor, layer).await.unwrap(); - println!("Final transform: {:?}", final_transform); + println!("Final transform: {final_transform:?}"); // Check matrix components have changed (rotation affects matrix2) let matrix_diff = (final_transform.matrix2.x_axis - original_transform.matrix2.x_axis).length(); - assert!(matrix_diff > 0.1, "Rotation should have changed the transform matrix. Diff: {}", matrix_diff); + assert!(matrix_diff > 0.1, "Rotation should have changed the transform matrix. Diff: {matrix_diff}"); } #[tokio::test] @@ -984,7 +982,7 @@ mod test_transform_layer { assert!(!after_cancel.translation.y.is_nan(), "Transform is NaN after cancel"); let translation_diff = (after_cancel.translation - original_transform.translation).length(); - assert!(translation_diff < 1., "Translation component changed too much: {}", translation_diff); + assert!(translation_diff < 1., "Translation component changed too much: {translation_diff}"); } #[tokio::test] @@ -1019,9 +1017,7 @@ mod test_transform_layer { assert!( scale_diff_x > 0.1 || scale_diff_y > 0.1, - "Scaling should have changed the transform matrix. Diffs: x={}, y={}", - scale_diff_x, - scale_diff_y + "Scaling should have changed the transform matrix. Diffs: x={scale_diff_x}, y={scale_diff_y}" ); } @@ -1050,7 +1046,7 @@ mod test_transform_layer { // Also check translation component is similar let translation_diff = (after_cancel.translation - original_transform.translation).length(); - assert!(translation_diff < 1., "Translation component changed too much: {}", translation_diff); + assert!(translation_diff < 1., "Translation component changed too much: {translation_diff}"); } #[tokio::test] @@ -1077,9 +1073,7 @@ mod test_transform_layer { let actual_translation = after_grab_transform.translation - original_transform.translation; assert!( (actual_translation - expected_translation).length() < 1e-5, - "Expected translation of {:?}, got {:?}", - expected_translation, - actual_translation + "Expected translation of {expected_translation:?}, got {actual_translation:?}" ); // 2. Chain to rotation - from current position to create ~45 degree rotation @@ -1115,9 +1109,7 @@ mod test_transform_layer { let after_scale_det = after_scale_transform.matrix2.determinant(); assert!( after_scale_det >= 2. * before_scale_det, - "Scale should increase the determinant of the matrix (before: {}, after: {})", - before_scale_det, - after_scale_det + "Scale should increase the determinant of the matrix (before: {before_scale_det}, after: {after_scale_det})" ); editor.handle_message(TransformLayerMessage::ApplyTransformOperation { final_transform: true }).await; @@ -1149,8 +1141,8 @@ mod test_transform_layer { let scale_x = final_transform.matrix2.x_axis.length() / original_transform.matrix2.x_axis.length(); let scale_y = final_transform.matrix2.y_axis.length() / original_transform.matrix2.y_axis.length(); - assert!((scale_x - 2.).abs() < 0.1, "Expected scale factor X of 2, got: {}", scale_x); - assert!((scale_y - 2.).abs() < 0.1, "Expected scale factor Y of 2, got: {}", scale_y); + assert!((scale_x - 2.).abs() < 0.1, "Expected scale factor X of 2, got: {scale_x}"); + assert!((scale_y - 2.).abs() < 0.1, "Expected scale factor Y of 2, got: {scale_y}"); } #[tokio::test] @@ -1175,8 +1167,8 @@ mod test_transform_layer { let scale_x = final_transform.matrix2.x_axis.length() / original_transform.matrix2.x_axis.length(); let scale_y = final_transform.matrix2.y_axis.length() / original_transform.matrix2.y_axis.length(); - assert!((scale_x - 2.).abs() < 0.1, "Expected scale factor X of 2, got: {}", scale_x); - assert!((scale_y - 2.).abs() < 0.1, "Expected scale factor Y of 2, got: {}", scale_y); + assert!((scale_x - 2.).abs() < 0.1, "Expected scale factor X of 2, got: {scale_x}"); + assert!((scale_y - 2.).abs() < 0.1, "Expected scale factor Y of 2, got: {scale_y}"); } #[tokio::test] @@ -1191,11 +1183,7 @@ mod test_transform_layer { // Rotate the document view (45 degrees) editor.handle_message(NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: false }).await; - editor - .handle_message(NavigationMessage::CanvasTiltSet { - angle_radians: (45. as f64).to_radians(), - }) - .await; + editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 45_f64.to_radians() }).await; editor.handle_message(TransformLayerMessage::BeginRotate).await; editor.handle_message(TransformLayerMessage::TypeDigit { digit: 9 }).await; @@ -1210,7 +1198,7 @@ mod test_transform_layer { // Normalize angle between 0 and 360 let angle_change = ((angle_change % 360.) + 360.) % 360.; - assert!((angle_change - 90.).abs() < 0.1, "Expected rotation of 90 degrees, got: {}", angle_change); + assert!((angle_change - 90.).abs() < 0.1, "Expected rotation of 90 degrees, got: {angle_change}"); } #[tokio::test] @@ -1265,8 +1253,8 @@ mod test_transform_layer { // Verify scale is near zero. let scale_x = near_zero_transform.matrix2.x_axis.length(); let scale_y = near_zero_transform.matrix2.y_axis.length(); - assert!(scale_x < 0.001, "Scale factor X should be near zero, got: {}", scale_x); - assert!(scale_y < 0.001, "Scale factor Y should be near zero, got: {}", scale_y); + assert!(scale_x < 0.001, "Scale factor X should be near zero, got: {scale_x}"); + assert!(scale_y < 0.001, "Scale factor Y should be near zero, got: {scale_y}"); assert!(scale_x > 0., "Scale factor X should not be exactly zero"); assert!(scale_y > 0., "Scale factor Y should not be exactly zero"); diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index 6e09445f..b490cbb9 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -432,7 +432,7 @@ pub struct InspectResult { impl InspectResult { pub fn take_data(&mut self) -> Option> { - return self.introspected_data.clone(); + self.introspected_data.clone() } } diff --git a/libraries/dyn-any/derive/src/lib.rs b/libraries/dyn-any/derive/src/lib.rs index 0bfe526d..23fa506f 100644 --- a/libraries/dyn-any/derive/src/lib.rs +++ b/libraries/dyn-any/derive/src/lib.rs @@ -53,7 +53,7 @@ pub fn system_desc_derive(input: TokenStream) -> TokenStream { } fn replace_lifetimes(generics: &syn::Generics, replacement: &str) -> Vec { - let params = generics + generics .params .iter() .map(|param| { @@ -72,6 +72,5 @@ fn replace_lifetimes(generics: &syn::Generics, replacement: &str) -> Vec>(); - params + .collect::>() } diff --git a/libraries/math-parser/src/parser.rs b/libraries/math-parser/src/parser.rs index 101995d8..e707b500 100644 --- a/libraries/math-parser/src/parser.rs +++ b/libraries/math-parser/src/parser.rs @@ -135,7 +135,7 @@ fn parse_lit(mut pairs: Pairs) -> Result<(Literal, Unit), ParseError> { let unit_pairs = unit_pair.into_inner(); // Get the inner pairs for the unit let (unit, scale) = parse_unit(unit_pairs)?; - println!("found unit: {:?}", unit); + println!("found unit: {unit:?}"); Ok(( match literal { diff --git a/libraries/path-bool/src/parsing/path_data.rs b/libraries/path-bool/src/parsing/path_data.rs index 6e6ed2a7..076f4247 100644 --- a/libraries/path-bool/src/parsing/path_data.rs +++ b/libraries/path-bool/src/parsing/path_data.rs @@ -45,7 +45,7 @@ pub fn commands_from_path_data(d: &str) -> Result, BooleanError *i += cap[0].len(); &cap[1] == "1" } else { - panic!("Invalid path data. Expected a flag at index {}", i); + panic!("Invalid path data. Expected a flag at index {i}"); } }; @@ -128,8 +128,8 @@ pub fn path_to_path_data(path: &Path, eps: f64) -> String { path_to_commands(path.iter(), eps) .map(|cmd| match cmd { PathCommand::Absolute(abs_cmd) => match abs_cmd { - AbsolutePathCommand::H(dx) => format!("H {:.12}", dx), - AbsolutePathCommand::V(dy) => format!("V {:.12}", dy), + AbsolutePathCommand::H(dx) => format!("H {dx:.12}"), + AbsolutePathCommand::V(dy) => format!("V {dy:.12}"), AbsolutePathCommand::M(p) => format!("M {:.12},{:.12}", p.x, p.y), AbsolutePathCommand::L(p) => format!("L {:.12},{:.12}", p.x, p.y), AbsolutePathCommand::C(p1, p2, p3) => format!("C {:.12},{:.12} {:.12},{:.12} {:.12},{:.12}", p1.x, p1.y, p2.x, p2.y, p3.x, p3.y), @@ -146,18 +146,18 @@ pub fn path_to_path_data(path: &Path, eps: f64) -> String { AbsolutePathCommand::Z => "Z".to_string(), }, PathCommand::Relative(rel_cmd) => match rel_cmd { - RelativePathCommand::M(dx, dy) => format!("m {:.12},{:.12}", dx, dy), - RelativePathCommand::L(dx, dy) => format!("l {:.12},{:.12}", dx, dy), - RelativePathCommand::H(dx) => format!("h {:.12}", dx), - RelativePathCommand::V(dy) => format!("v {:.12}", dy), - RelativePathCommand::C(dx1, dy1, dx2, dy2, dx, dy) => format!("c{:.12},{:.12} {:.12},{:.12} {:.12},{:.12}", dx1, dy1, dx2, dy2, dx, dy), + RelativePathCommand::M(dx, dy) => format!("m {dx:.12},{dy:.12}"), + RelativePathCommand::L(dx, dy) => format!("l {dx:.12},{dy:.12}"), + RelativePathCommand::H(dx) => format!("h {dx:.12}"), + RelativePathCommand::V(dy) => format!("v {dy:.12}"), + RelativePathCommand::C(dx1, dy1, dx2, dy2, dx, dy) => format!("c{dx1:.12},{dy1:.12} {dx2:.12},{dy2:.12} {dx:.12},{dy:.12}"), RelativePathCommand::S(dx2, dy2, dx, dy) => { - format!("s {:.12},{:.12} {:.12},{:.12}", dx2, dy2, dx, dy) + format!("s {dx2:.12},{dy2:.12} {dx:.12},{dy:.12}") } RelativePathCommand::Q(dx1, dy1, dx, dy) => { - format!("q {:.12},{:.12} {:.12},{:.12}", dx1, dy1, dx, dy) + format!("q {dx1:.12},{dy1:.12} {dx:.12},{dy:.12}") } - RelativePathCommand::T(dx, dy) => format!("t{:.12},{:.12}", dx, dy), + RelativePathCommand::T(dx, dy) => format!("t{dx:.12},{dy:.12}"), RelativePathCommand::A(rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, dx, dy) => { format!("a {:.12} {:.12} {:.12} {} {} {:.12},{:.12}", rx, ry, x_axis_rotation, large_arc_flag as u8, sweep_flag as u8, dx, dy) } diff --git a/libraries/path-bool/src/path_boolean.rs b/libraries/path-bool/src/path_boolean.rs index 8c54b29c..34d17855 100644 --- a/libraries/path-bool/src/path_boolean.rs +++ b/libraries/path-bool/src/path_boolean.rs @@ -551,13 +551,15 @@ fn round_point(point: DVec2) -> I64Vec2 { (point * ROUNDING_FACTOR).round().as_i64vec2() } +type Edges = SmallVec<[(PathSegment, u8, MajorEdgeKey, MajorEdgeKey); 2]>; + fn find_vertices(edges: &[MajorGraphEdgeStage1]) -> MajorGraph { let mut graph = MajorGraph { edges: SlotMap::with_capacity_and_key(edges.len() * 2), vertices: SlotMap::with_capacity_and_key(edges.len()), }; - let mut vertex_pair_id_to_edges: HashMap<_, SmallVec<[(PathSegment, u8, MajorEdgeKey, MajorEdgeKey); 2]>> = new_hash_map(edges.len()); + let mut vertex_pair_id_to_edges: HashMap<_, Edges> = new_hash_map(edges.len()); let mut vertex_hashmap: HashMap = new_hash_map(edges.len() * 2); for (seg, parent) in edges { diff --git a/node-graph/gapplication-io/src/lib.rs b/node-graph/gapplication-io/src/lib.rs index b371b95e..b9d072d2 100644 --- a/node-graph/gapplication-io/src/lib.rs +++ b/node-graph/gapplication-io/src/lib.rs @@ -249,7 +249,7 @@ struct Logger; impl NodeGraphUpdateSender for Logger { fn send(&self, message: NodeGraphUpdateMessage) { - log::warn!("dispatching message with fallback node graph update sender {:?}", message); + log::warn!("dispatching message with fallback node graph update sender {message:?}"); } } diff --git a/node-graph/gcore-shaders/src/color/color.rs b/node-graph/gcore-shaders/src/color/color_types.rs similarity index 100% rename from node-graph/gcore-shaders/src/color/color.rs rename to node-graph/gcore-shaders/src/color/color_types.rs diff --git a/node-graph/gcore-shaders/src/color/mod.rs b/node-graph/gcore-shaders/src/color/mod.rs index 3b286c51..0a983229 100644 --- a/node-graph/gcore-shaders/src/color/mod.rs +++ b/node-graph/gcore-shaders/src/color/mod.rs @@ -1,7 +1,7 @@ -mod color; mod color_traits; +mod color_types; mod discrete_srgb; -pub use color::*; pub use color_traits::*; +pub use color_types::*; pub use discrete_srgb::*; diff --git a/node-graph/gcore/src/math/polynomial.rs b/node-graph/gcore/src/math/polynomial.rs index 9ac798f5..8af2f090 100644 --- a/node-graph/gcore/src/math/polynomial.rs +++ b/node-graph/gcore/src/math/polynomial.rs @@ -287,6 +287,6 @@ mod test { fn display() { let p = Polynomial::new([1., 2., 0., 3.]); - assert_eq!(format!("{:.2}", p), "3.00x^3 + 2.00x + 1.00"); + assert_eq!(format!("{p:.2}"), "3.00x^3 + 2.00x + 1.00"); } } diff --git a/node-graph/gcore/src/memo.rs b/node-graph/gcore/src/memo.rs index 1a124d20..81f4a735 100644 --- a/node-graph/gcore/src/memo.rs +++ b/node-graph/gcore/src/memo.rs @@ -50,6 +50,7 @@ impl MemoNode { } } +#[allow(clippy::module_inception)] pub mod memo { pub const IDENTIFIER: crate::ProtoNodeIdentifier = crate::ProtoNodeIdentifier::new("graphene_core::memo::MemoNode"); } diff --git a/node-graph/gcore/src/raster/image.rs b/node-graph/gcore/src/raster/image.rs index 9a485490..c58d493a 100644 --- a/node-graph/gcore/src/raster/image.rs +++ b/node-graph/gcore/src/raster/image.rs @@ -258,7 +258,7 @@ pub fn migrate_image_frame<'de, D: serde::Deserializer<'de>>(deserializer: D) -> GraphicElement::RasterFrame(RasterFrame::ImageFrame(image)) => Self { image: image.iter().next().unwrap().element.clone(), }, - _ => panic!("Expected Image, found {:?}", element), + _ => panic!("Expected Image, found {element:?}"), } } } @@ -478,9 +478,9 @@ mod test { }; let serialized = serde_json::to_string(&image).unwrap(); - println!("{}", serialized); + println!("{serialized}"); let deserialized: Image = serde_json::from_str(&serialized).unwrap(); - println!("{:?}", deserialized); + println!("{deserialized:?}"); assert_eq!(image, deserialized); } diff --git a/node-graph/gcore/src/registry.rs b/node-graph/gcore/src/registry.rs index e8a0a4e5..3553c030 100644 --- a/node-graph/gcore/src/registry.rs +++ b/node-graph/gcore/src/registry.rs @@ -234,7 +234,7 @@ where }; match dyn_any::downcast(input) { Ok(input) => Box::pin(output(*input)), - Err(e) => panic!("DynAnyNode Input, {0} in:\n{1}", e, node_name), + Err(e) => panic!("DynAnyNode Input, {e} in:\n{node_name}"), } } diff --git a/node-graph/gcore/src/types.rs b/node-graph/gcore/src/types.rs index 486470c3..f8a1b1b9 100644 --- a/node-graph/gcore/src/types.rs +++ b/node-graph/gcore/src/types.rs @@ -367,7 +367,7 @@ impl std::fmt::Debug for Type { Self::Future(ty) => format!("{ty:?}"), }; let result = result.replace("Option>", "Context"); - write!(f, "{}", result) + write!(f, "{result}") } } @@ -380,6 +380,6 @@ impl std::fmt::Display for Type { Type::Future(ty) => ty.to_string(), }; let result = result.replace("Option>", "Context"); - write!(f, "{}", result) + write!(f, "{result}") } } diff --git a/node-graph/gcore/src/value.rs b/node-graph/gcore/src/value.rs index 185aa22d..3cf1c0f6 100644 --- a/node-graph/gcore/src/value.rs +++ b/node-graph/gcore/src/value.rs @@ -60,8 +60,7 @@ impl<'i, T: 'i> Node<'i, ()> for RefCellMutNode { type Output = RefMut<'i, T>; #[inline(always)] fn eval(&'i self, _input: ()) -> Self::Output { - let a = self.0.borrow_mut(); - a + self.0.borrow_mut() } } diff --git a/node-graph/gcore/src/vector/algorithms/bezpath_algorithms.rs b/node-graph/gcore/src/vector/algorithms/bezpath_algorithms.rs index cd75ea76..6a1213d5 100644 --- a/node-graph/gcore/src/vector/algorithms/bezpath_algorithms.rs +++ b/node-graph/gcore/src/vector/algorithms/bezpath_algorithms.rs @@ -225,7 +225,7 @@ pub fn pathseg_find_tvalues_for_x(segment: PathSeg, x: f64) -> impl Iterator { let a = p3.x - 3.0 * p2.x + 3.0 * p1.x - p0.x; @@ -233,7 +233,7 @@ pub fn pathseg_find_tvalues_for_x(segment: PathSeg, x: f64) -> impl Iterator, subpath: &Subpath { diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 3bd200e9..56f3c963 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -301,13 +301,13 @@ impl TaggedValue { "MAGENTA" => Color::MAGENTA, "TRANSPARENT" => Color::TRANSPARENT, _ => { - log::error!("Invalid default value color constant: {}", input); + log::error!("Invalid default value color constant: {input}"); return None; } }); } - log::error!("Invalid default value color: {}", input); + log::error!("Invalid default value color: {input}"); None } @@ -327,13 +327,13 @@ impl TaggedValue { "BottomCenter" => ReferencePoint::BottomCenter, "BottomRight" => ReferencePoint::BottomRight, _ => { - log::error!("Invalid ReferencePoint default type variant: {}", input); + log::error!("Invalid ReferencePoint default type variant: {input}"); return None; } }); } - log::error!("Invalid ReferencePoint default type: {}", input); + log::error!("Invalid ReferencePoint default type: {input}"); None } diff --git a/node-graph/graphene-cli/src/main.rs b/node-graph/graphene-cli/src/main.rs index 049878cc..39de026c 100644 --- a/node-graph/graphene-cli/src/main.rs +++ b/node-graph/graphene-cli/src/main.rs @@ -88,10 +88,7 @@ async fn main() -> Result<(), Box> { } let device = application_io.gpu_executor().unwrap().context.device.clone(); - let preferences = EditorPreferences { - use_vello: true, - ..Default::default() - }; + let preferences = EditorPreferences { use_vello: true }; let editor_api = Arc::new(WasmEditorApi { font_cache: FontCache::default(), application_io: Some(application_io.into()), @@ -104,7 +101,7 @@ async fn main() -> Result<(), Box> { match app.command { Command::Compile { print_proto, .. } => { if print_proto { - println!("{}", proto_graph); + println!("{proto_graph}"); } } Command::Run { run_loop, .. } => { @@ -120,7 +117,7 @@ async fn main() -> Result<(), Box> { loop { let result = (&executor).execute(render_config).await?; if !run_loop { - println!("{:?}", result); + println!("{result:?}"); break; } tokio::time::sleep(std::time::Duration::from_millis(16)).await; diff --git a/node-graph/gsvg-renderer/src/renderer.rs b/node-graph/gsvg-renderer/src/renderer.rs index f470e628..d8351fb8 100644 --- a/node-graph/gsvg-renderer/src/renderer.rs +++ b/node-graph/gsvg-renderer/src/renderer.rs @@ -1209,7 +1209,7 @@ impl Render for Table> { } } -const LAZY_ARC_VEC_ZERO_U8: LazyLock>> = LazyLock::new(|| Arc::new(Vec::new())); +static LAZY_ARC_VEC_ZERO_U8: LazyLock>> = LazyLock::new(|| Arc::new(Vec::new())); impl Render for Table> { fn render_svg(&self, _render: &mut SvgRender, _render_params: &RenderParams) { diff --git a/node-graph/interpreted-executor/src/dynamic_executor.rs b/node-graph/interpreted-executor/src/dynamic_executor.rs index cca13cb3..f105b2e8 100644 --- a/node-graph/interpreted-executor/src/dynamic_executor.rs +++ b/node-graph/interpreted-executor/src/dynamic_executor.rs @@ -150,8 +150,8 @@ 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::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"), } diff --git a/node-graph/node-macro/src/codegen.rs b/node-graph/node-macro/src/codegen.rs index ced865e1..57a8b75c 100644 --- a/node-graph/node-macro/src/codegen.rs +++ b/node-graph/node-macro/src/codegen.rs @@ -293,7 +293,7 @@ pub(crate) fn generate_node_code(parsed: &ParsedNodeFn) -> syn::Result syn::Result syn::Result { - let attributes = syn::parse2::(attr.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node_fn attributes: {}", e)))?; - let input_fn = syn::parse2::(item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse function: {}. Make sure it's a valid Rust function.", e)))?; + let attributes = syn::parse2::(attr.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node_fn attributes: {e}")))?; + let input_fn = syn::parse2::(item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse function: {e}. Make sure it's a valid Rust function.")))?; let vis = input_fn.vis; let fn_name = input_fn.sig.ident.clone(); @@ -312,7 +312,7 @@ fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result syn::Result::parse_terminated; parser.parse2(content.clone()).map_err(|e| { let span = e.span(); // Get the span of the error - Error::new(span, format!("Failed to parse implementations for argument '{}': {}", name, e)) + Error::new(span, format!("Failed to parse implementations for argument '{name}': {e}")) }) } @@ -431,27 +431,21 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul let ident = &pat_ident.ident; let default_value = extract_attribute(attrs, "default") - .map(|attr| { - attr.parse_args() - .map_err(|e| Error::new_spanned(attr, format!("Invalid `default` value for argument '{}': {}", ident, e))) - }) + .map(|attr| attr.parse_args().map_err(|e| Error::new_spanned(attr, format!("Invalid `default` value for argument '{ident}': {e}")))) .transpose()?; let scope = extract_attribute(attrs, "scope") - .map(|attr| { - attr.parse_args() - .map_err(|e| Error::new_spanned(attr, format!("Invalid `scope` value for argument '{}': {}", ident, e))) - }) + .map(|attr| attr.parse_args().map_err(|e| Error::new_spanned(attr, format!("Invalid `scope` value for argument '{ident}': {e}")))) .transpose()?; let name = extract_attribute(attrs, "name") - .map(|attr| attr.parse_args().map_err(|e| Error::new_spanned(attr, format!("Invalid `name` value for argument '{}': {}", ident, e)))) + .map(|attr| attr.parse_args().map_err(|e| Error::new_spanned(attr, format!("Invalid `name` value for argument '{ident}': {e}")))) .transpose()?; let widget_override = extract_attribute(attrs, "widget") .map(|attr| { attr.parse_args() - .map_err(|e| Error::new_spanned(attr, format!("Invalid `widget override` value for argument '{}': {}", ident, e))) + .map_err(|e| Error::new_spanned(attr, format!("Invalid `widget override` value for argument '{ident}': {e}"))) }) .transpose()? .unwrap_or_default(); @@ -468,26 +462,26 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul let number_soft_min = extract_attribute(attrs, "soft_min") .map(|attr| { attr.parse_args() - .map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `soft_min` value for argument '{}': {}", ident, e))) + .map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `soft_min` value for argument '{ident}': {e}"))) }) .transpose()?; let number_soft_max = extract_attribute(attrs, "soft_max") .map(|attr| { attr.parse_args() - .map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `soft_max` value for argument '{}': {}", ident, e))) + .map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `soft_max` value for argument '{ident}': {e}"))) }) .transpose()?; let number_hard_min = extract_attribute(attrs, "hard_min") .map(|attr| { attr.parse_args() - .map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `hard_min` value for argument '{}': {}", ident, e))) + .map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `hard_min` value for argument '{ident}': {e}"))) }) .transpose()?; let number_hard_max = extract_attribute(attrs, "hard_max") .map(|attr| { attr.parse_args() - .map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `hard_max` value for argument '{}': {}", ident, e))) + .map_err(|e| Error::new_spanned(attr, format!("Invalid numerical `hard_max` value for argument '{ident}': {e}"))) }) .transpose()?; @@ -496,10 +490,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul attr.parse_args::().map_err(|e| { Error::new_spanned( attr, - format!( - "Invalid `range` tuple of min and max range slider values for argument '{}': {}\nUSAGE EXAMPLE: #[range((0., 100.))]", - ident, e - ), + format!("Invalid `range` tuple of min and max range slider values for argument '{ident}': {e}\nUSAGE EXAMPLE: #[range((0., 100.))]"), ) }) }) @@ -511,7 +502,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul } let unit = extract_attribute(attrs, "unit") - .map(|attr| attr.parse_args::().map_err(|_e| Error::new_spanned(attr, format!("Expected a unit type as string")))) + .map(|attr| attr.parse_args::().map_err(|_e| Error::new_spanned(attr, "Expected a unit type as string".to_string()))) .transpose()?; let number_display_decimal_places = extract_attribute(attrs, "display_decimal_places") @@ -519,14 +510,14 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul attr.parse_args::().map_err(|e| { Error::new_spanned( attr, - format!("Invalid `integer` for number of decimals for argument '{}': {}\nUSAGE EXAMPLE: #[display_decimal_places(2)]", ident, e), + format!("Invalid `integer` for number of decimals for argument '{ident}': {e}\nUSAGE EXAMPLE: #[display_decimal_places(2)]"), ) }) }) .transpose()? .map(|f| { if let Err(e) = f.base10_parse::() { - Err(Error::new_spanned(f, format!("Expected a `u32` for `display_decimal_places` for '{}': {}", ident, e))) + Err(Error::new_spanned(f, format!("Expected a `u32` for `display_decimal_places` for '{ident}': {e}"))) } else { Ok(f) } @@ -535,7 +526,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul let number_step = extract_attribute(attrs, "step") .map(|attr| { attr.parse_args::() - .map_err(|e| Error::new_spanned(attr, format!("Invalid `step` for argument '{}': {}\nUSAGE EXAMPLE: #[step(2.)]", ident, e))) + .map_err(|e| Error::new_spanned(attr, format!("Invalid `step` for argument '{ident}': {e}\nUSAGE EXAMPLE: #[step(2.)]"))) }) .transpose()?; @@ -660,7 +651,7 @@ pub fn new_node_fn(attr: TokenStream2, item: TokenStream2) -> TokenStream2 { Ok(parsed) => parsed, Err(e) => { // Return the error as a compile error - Error::new(e.span(), format!("Failed to parse node function: {}", e)).to_compile_error() + Error::new(e.span(), format!("Failed to parse node function: {e}")).to_compile_error() } } } @@ -757,7 +748,7 @@ mod tests { } _ => panic!("Mismatched default values"), } - assert_eq!(format!("{:?}", p_ty), format!("{:?}", e_ty)); + assert_eq!(format!("{p_ty:?}"), format!("{:?}", e_ty)); } ( ParsedField { @@ -780,8 +771,8 @@ mod tests { }, ) => { assert_eq!(p_name, e_name); - assert_eq!(format!("{:?}", p_input), format!("{:?}", e_input)); - assert_eq!(format!("{:?}", p_output), format!("{:?}", e_output)); + assert_eq!(format!("{p_input:?}"), format!("{:?}", e_input)); + assert_eq!(format!("{p_output:?}"), format!("{:?}", e_output)); } _ => panic!("Mismatched field types"), } diff --git a/node-graph/preprocessor/src/lib.rs b/node-graph/preprocessor/src/lib.rs index e0b4a016..2809d8c6 100644 --- a/node-graph/preprocessor/src/lib.rs +++ b/node-graph/preprocessor/src/lib.rs @@ -108,7 +108,7 @@ pub fn generate_node_substitutions() -> HashMap syn::Result, Vec<_>>(); #[cfg(feature = "serde-discriminant")] diff --git a/proc-macros/src/helpers.rs b/proc-macros/src/helpers.rs index 4beb44f4..5f5c22fd 100644 --- a/proc-macros/src/helpers.rs +++ b/proc-macros/src/helpers.rs @@ -55,7 +55,7 @@ pub fn clean_rust_type_syntax(input: String) -> String { } } '<' => { - while let Some(' ') = result.chars().rev().next() { + while let Some(' ') = result.chars().next_back() { result.pop(); } result.push('<'); @@ -64,7 +64,7 @@ pub fn clean_rust_type_syntax(input: String) -> String { } } '>' => { - while let Some(' ') = result.chars().rev().next() { + while let Some(' ') = result.chars().next_back() { result.pop(); } result.push('>'); @@ -74,7 +74,7 @@ pub fn clean_rust_type_syntax(input: String) -> String { } '-' => { if let Some('>') = chars.peek() { - while let Some(' ') = result.chars().rev().next() { + while let Some(' ') = result.chars().next_back() { result.pop(); } result.push_str(" -> "); @@ -88,7 +88,7 @@ pub fn clean_rust_type_syntax(input: String) -> String { } ':' => { if let Some(':') = chars.peek() { - while let Some(' ') = result.chars().rev().next() { + while let Some(' ') = result.chars().next_back() { result.pop(); } } diff --git a/proc-macros/src/hierarchical_tree.rs b/proc-macros/src/hierarchical_tree.rs index fb7ae34f..a37f8e41 100644 --- a/proc-macros/src/hierarchical_tree.rs +++ b/proc-macros/src/hierarchical_tree.rs @@ -47,22 +47,20 @@ pub fn generate_hierarchical_tree(input: TokenStream) -> syn::Result format!("Remove the unnecessary `()` from the `{}` message enum variant.", variant_type), + 0 => format!("Remove the unnecessary `()` from the `{variant_type}` message enum variant."), 1 => { let field_type = &fields.unnamed.first().unwrap().ty; format!( - "The `{}` message should be defined as a struct-style (not tuple-style) enum variant to maintain consistent formatting across all editor messages.\n\ + "The `{variant_type}` message should be defined as a struct-style (not tuple-style) enum variant to maintain consistent formatting across all editor messages.\n\ Replace `{}` with a named field using {{curly braces}} instead of a positional field using (parentheses).", - variant_type, field_type.to_token_stream() ) } _ => { let field_types = fields.unnamed.iter().map(|f| f.ty.to_token_stream().to_string()).collect::>().join(", "); format!( - "The `{}` message should be defined as a struct-style (not tuple-style) enum variant to maintain consistent formatting across all editor messages.\n\ - Replace `{}` with named fields using {{curly braces}} instead of positional fields using (parentheses).", - variant_type, field_types + "The `{variant_type}` message should be defined as a struct-style (not tuple-style) enum variant to maintain consistent formatting across all editor messages.\n\ + Replace `{field_types}` with named fields using {{curly braces}} instead of positional fields using (parentheses)." ) } };