Clear the workspace clippy warnings and shrink the message enum by boxing the mounted working copy

This commit is contained in:
Dennis Kobert committed 2026-09-22 14:12:17 +00:00
1 parent 6c52714194
commit fee15b9048
25 files changed
+125 -114

No files matched your search

+4 -4
View File
@@ -20,10 +20,10 @@ pub(crate) fn clear_dir(path: &PathBuf) {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file() {
if let Err(e) = fs::remove_file(&entry_path) {
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file()
&& let Err(e) = fs::remove_file(&entry_path)
{
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
+5 -4
View File
@@ -71,10 +71,11 @@ fn garbage_collect_document_files(state: &PersistedState) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && !valid_paths.contains(&path) {
if let Err(e) = std::fs::remove_file(&path) {
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
if path.is_file()
&& !valid_paths.contains(&path)
&& let Err(e) = std::fs::remove_file(&path)
{
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
}
}
+4 -4
View File
@@ -44,10 +44,10 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
pub(super) fn poll_node_graph_evaluation(&mut self) {
let mut responses = VecDeque::new();
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) {
if e != "No active document" {
tracing::error!("Error poling node graph: {}", e);
}
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
&& e != "No active document"
{
tracing::error!("Error poling node graph: {}", e);
}
while let Some(message) = responses.pop_front() {
self.queue_editor_message(message);
+4 -8
View File
@@ -496,15 +496,11 @@ mod test {
if let FrontendMessage::UpdateLayout {
layout_target: LayoutTarget::DialogColumn1,
diff,
} = response
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
{
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
print_problem_to_terminal_on_failure(value);
}
}
}
print_problem_to_terminal_on_failure(value);
}
}
}
@@ -95,7 +95,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
.network_interface
.node_metadata(&layer.to_node(), &[])
.map(|node| node.persistent_metadata.display_name.clone())
.and_then(|name| if name.is_empty() { None } else { Some(name) })
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "Artboard".to_string());
(layer, name)
})
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
];
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones()));
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
for sublist in list {
@@ -4106,10 +4106,11 @@ mod document_message_handler_tests {
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
let document = editor.active_document();
for layer in document.metadata().all_layers() {
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
return Some(layer);
}
if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
&& (bbox[0].x - min_x).abs() < 1.
&& (bbox[0].y - min_y).abs() < 1.
{
return Some(layer);
}
}
None
@@ -4166,7 +4167,6 @@ mod document_message_handler_tests {
// The operation completed without crashing
// Verifying application still functions by performing another operation
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
assert!(true, "Application didn't crash after folder move operation");
}
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
@@ -543,7 +543,7 @@ impl NodeNetworkInterface {
return;
};
// Initialize all output connectors for nodes
for (node_id, _) in network.nodes.iter() {
for node_id in network.nodes.keys() {
let number_of_outputs = self.number_of_outputs(node_id, network_path);
for output_index in 0..number_of_outputs {
outward_wires.insert(OutputConnector::node(*node_id, output_index), Vec::new());
@@ -321,7 +321,7 @@ impl NodeNetworkInterface {
})
.collect::<Vec<(NodeId, i32)>>();
node_ids_with_position.sort_unstable_by(|a, b| a.1.cmp(&b.1));
node_ids_with_position.sort_unstable_by_key(|a| a.1);
Some(node_ids_with_position.into_iter().map(|(node_id, _)| node_id).collect::<Vec<_>>())
}
@@ -156,7 +156,11 @@ impl NodeNetworkInterface {
};
let locator = NodeLocator::new(node_id, &encapsulating_network_path);
let inserted_index = if insert_index == -1 { self.number_of_inputs(&node_id, &encapsulating_network_path) } else { insert_index as usize };
let inserted_index = if insert_index == -1 {
self.number_of_inputs(&node_id, &encapsulating_network_path)
} else {
insert_index as usize
};
if !self.insert_input_slot(locator, inserted_index, NodeInput::value(default_value, exposed), (input_name, input_description).into()) {
return;
}
@@ -540,7 +544,9 @@ impl NodeNetworkInterface {
return;
}
let Some(old_input) = self.set_input_slot(input_connector, network_path, new_input.clone()) else { return };
let Some(old_input) = self.set_input_slot(input_connector, network_path, new_input.clone()) else {
return;
};
self.transaction_modified();
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
@@ -608,7 +614,9 @@ impl NodeNetworkInterface {
}
}
let Some(old_input) = self.set_input_slot(input_connector, network_path, new_input.clone()) else { return };
let Some(old_input) = self.set_input_slot(input_connector, network_path, new_input.clone()) else {
return;
};
if old_input == new_input {
return;
@@ -1037,7 +1045,7 @@ impl NodeNetworkInterface {
if !(matches!(reconnect_to_input, Some(NodeInput::Import { .. })) && matches!(downstream_input, InputConnector::Export(_)))
&& let Some(reconnect_input) = &reconnect_to_input
{
reconnect_node = reconnect_input.as_node().and_then(|node_id| if self.is_stack(&node_id, network_path) { Some(node_id) } else { None });
reconnect_node = reconnect_input.as_node().filter(|&node_id| self.is_stack(&node_id, network_path));
self.disconnect_input(&InputConnector::primary_input(*node_id), network_path);
self.set_input(downstream_input, reconnect_input.clone(), network_path);
}
@@ -389,7 +389,9 @@ impl NodeNetworkInterface {
},
);
previous_node.zip(previous_metadata).map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
previous_node
.zip(previous_metadata)
.map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Removes a node and its metadata, returning them joined as a template.
@@ -227,7 +227,13 @@ impl<'a, 'p> NetworkView<'a, 'p> {
/// Input rows the node displays: every exposed input, plus the primary input, whose row is shown even when it is not exposed.
pub fn input_row_count(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(self.node(node_id)?.inputs.iter().enumerate().filter(|(input_index, input)| *input_index == 0 || input.is_exposed()).count())
Ok(self
.node(node_id)?
.inputs
.iter()
.enumerate()
.filter(|(input_index, input)| *input_index == 0 || input.is_exposed())
.count())
}
/// Grid rows the node body spans, which is the greater of its input rows and its output count.
@@ -55,7 +55,7 @@ pub enum PortfolioMessage {
reopened: bool,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<document_format::GddV1>,
gdd: Option<Box<document_format::GddV1>>,
},
DestroyAllDocuments,
EditorPreferences,
@@ -314,7 +314,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Document was closed before its working copy finished mounting.
return;
};
document.set_storage(gdd);
document.set_storage(gdd.map(|gdd| *gdd));
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
@@ -1325,7 +1325,7 @@ impl PortfolioMessageHandler {
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
document_id,
reopened,
gdd: Some(gdd),
gdd: Some(Box::new(gdd)),
})
};
future.into()
@@ -68,6 +68,7 @@ impl SpiralTurns {
self.handle_state == SpiralTurnsState::Dragging
}
#[expect(clippy::too_many_arguments, reason = "the gizmo records one value per spiral parameter, so grouping them would only move the argument list")]
pub fn store_initial_parameters(
&mut self,
layer: LayerNodeIdentifier,
@@ -865,7 +865,7 @@ impl ShapeState {
/// Deselects all the anchors across every selected layer.
pub fn deselect_all_anchors(&mut self) {
for (_, state) in self.selected_shape_state.iter_mut() {
for state in self.selected_shape_state.values_mut() {
let selected_anchor_points: Vec<ManipulatorPointId> = state.selected_points.iter().filter(|selected_point| selected_point.as_anchor().is_some()).cloned().collect();
for point in selected_anchor_points {
@@ -876,7 +876,7 @@ impl ShapeState {
/// Deselects all the handles across every selected layer.
pub fn deselect_all_handles(&mut self) {
for (_, state) in self.selected_shape_state.iter_mut() {
for state in self.selected_shape_state.values_mut() {
let selected_handle_points: Vec<ManipulatorPointId> = state.selected_points.iter().filter(|selected_point| selected_point.as_handle().is_some()).cloned().collect();
for point in selected_handle_points {
@@ -89,11 +89,8 @@ impl ShapeType {
}
pub fn tooltip_description(&self) -> String {
(match self {
// TODO: Add descriptions to all the shape tools
_ => "",
})
.into()
// TODO: Add descriptions to all the shape tools
String::new()
}
pub fn icon_name(&self) -> String {
@@ -677,7 +677,6 @@ mod tests {
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
..Default::default()
};
let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.);
let snap_results = &mut SnapResults::default();
+1 -3
View File
@@ -939,10 +939,8 @@ mod test {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Output>>() {
Some(x.output.clone())
} else {
None
dynamic.downcast_ref::<IORecord<Context, Output>>().map(|x| x.output.clone())
}
}
-1
View File
@@ -7,7 +7,6 @@ use document_format::{GddV1, GddV1Layout};
use fern::colors::{Color, ColoredLevelConfig};
use futures::executor::block_on;
use graph_craft::application_io::EditorPreferences;
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::*;
use graph_craft::graphene_compiler::Compiler;
@@ -18,6 +18,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
(executor, proto_network)
}
#[allow(dead_code, reason = "shared by the bench targets, only some of which call it, and each compiles this module separately")]
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
where
F: Fn(&str, &mut BenchmarkGroup<M>),
@@ -219,7 +219,7 @@ impl SvgRender {
let (size_x, size_y) = (bounds_max - bounds_min).into();
let svg_header = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:graphite="https://graphite.art" viewBox="{x} {y} {size_x} {size_y}"><defs>{defs}</defs>"#,
defs = &self.svg_defs
defs = self.svg_defs
);
self.svg_defs = String::new();
self.svg.insert(0, svg_header.into());
@@ -237,7 +237,7 @@ impl SvgRender {
let svg_header = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:graphite="https://graphite.art" {view_box}><defs>{defs}</defs><g{transform}>"#,
defs = &self.svg_defs
defs = self.svg_defs
);
self.svg_defs = String::new();
self.svg.insert(0, svg_header.into());
+3 -3
View File
@@ -3708,7 +3708,7 @@ mod test {
let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).await;
let vector = result.element();
assert!(vector.use_face_fill());
assert!(vector.segment_domain.ids().len() > 0);
assert!(!vector.segment_domain.ids().is_empty());
}
#[tokio::test]
@@ -3739,8 +3739,8 @@ mod test {
assert_eq!(vector.point_domain.ids().len(), points.len());
assert_ne!(vector.point_domain.positions(), &points[..]);
// The convex-hull corners are pinned.
for i in 0..4 {
assert_eq!(vector.point_domain.positions()[i], points[i], "hull corner {i} should be pinned");
for (corner, (&position, &point)) in vector.point_domain.positions().iter().zip(&points).take(4).enumerate() {
assert_eq!(position, point, "hull corner {corner} should be pinned");
}
for &point in vector.point_domain.positions() {
assert!(point.x >= -1e-6 && point.x <= 10. + 1e-6);
+58 -58
View File
@@ -29,76 +29,76 @@ pub fn message_handler_data_attr_impl(attr: TokenStream, input_item: TokenStream
if segment.ident != "MessageHandler" {
return Err(syn::Error::new(segment.ident.span(), "Expected MessageHandler trait"));
}
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
if args.args.len() >= 2 {
// Extract the message type (M) and context struct type (C) from the trait params
let message_type = &args.args[0];
let data_type = &args.args[1];
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
&& args.args.len() >= 2
{
// Extract the message type (M) and context struct type (C) from the trait params
let message_type = &args.args[0];
let data_type = &args.args[1];
let impl_item = match data_type {
syn::GenericArgument::Type(t) => {
match t {
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
// Get just the base identifier (ToolMessageData) without generics
let type_name = &type_path.path.segments.first().unwrap().ident;
let impl_item = match data_type {
syn::GenericArgument::Type(t) => {
match t {
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
// Get just the base identifier (ToolMessageData) without generics
let type_name = &type_path.path.segments.first().unwrap().ident;
let handler_data_line_number = type_name.span().start().line;
let handler_data_line_number = type_name.span().start().line;
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
}
}
syn::Type::Tuple(_) => quote! {
quote! {
#input_item
impl #message_type {
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
}
},
syn::Type::Reference(type_reference) => {
let message_type = call_site_ident(format!("{input_type}Message"));
let type_ident = match &*type_reference.elem {
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
};
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
let type_line_number = type_ident.span().start().line;
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
}
}
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
}
}
syn::Type::Tuple(_) => quote! {
#input_item
impl #message_type {
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
},
syn::Type::Reference(type_reference) => {
let message_type = call_site_ident(format!("{input_type}Message"));
let type_ident = match &*type_reference.elem {
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
};
_ => quote! {
#input_item
},
};
return Ok(impl_item);
}
let type_line_number = type_ident.span().start().line;
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
}
}
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
}
}
_ => quote! {
#input_item
},
};
return Ok(impl_item);
}
}
Ok(input_item)
+4 -1
View File
@@ -249,6 +249,9 @@ fn dot_to_svg(dot: &str) -> Result<String> {
String::from_utf8(output.stdout).with_context(|| "SVG output was not valid UTF-8")
}
/// A Graphviz subgraph cluster: its id, its label, its fill color, and which crates belong to it.
type Cluster = (&'static str, &'static str, &'static str, Box<dyn Fn(&CrateInfo) -> bool>);
fn generate_dot(crates: &[CrateInfo]) -> String {
let mut out = String::new();
out.push_str("digraph CrateHierarchy {\n");
@@ -257,7 +260,7 @@ fn generate_dot(crates: &[CrateInfo]) -> String {
out.push_str(" edge [color=gray];\n\n");
// Define subgraph clusters
let clusters: &[(&str, &str, &str, Box<dyn Fn(&CrateInfo) -> bool>)] = &[
let clusters: &[Cluster] = &[
(
"cluster_core",
"Core Components",