Fix clippy lints (#1327)

* Fix clippy lints

* Update formatting

* Remove unsafe send impls

* New type for Rc<NodeContainer>
This commit is contained in:
0HyperCube
2023-07-19 16:38:23 +01:00
committed by Keavon Chambers
parent 743803ce04
commit 80cc5bee73
80 changed files with 549 additions and 445 deletions
+3 -3
View File
@@ -534,15 +534,15 @@ mod test {
editor.handle_message(DocumentMessage::SelectedLayersRaise);
let (all, non_selected, selected) = verify_order(editor.dispatcher.message_handlers.portfolio_message_handler.active_document_mut().unwrap());
assert_eq!(all, non_selected.into_iter().chain(selected.into_iter()).collect::<Vec<_>>());
assert_eq!(all, non_selected.into_iter().chain(selected).collect::<Vec<_>>());
editor.handle_message(DocumentMessage::SelectedLayersLower);
let (all, non_selected, selected) = verify_order(editor.dispatcher.message_handlers.portfolio_message_handler.active_document_mut().unwrap());
assert_eq!(all, selected.into_iter().chain(non_selected.into_iter()).collect::<Vec<_>>());
assert_eq!(all, selected.into_iter().chain(non_selected).collect::<Vec<_>>());
editor.handle_message(DocumentMessage::SelectedLayersRaiseToFront);
let (all, non_selected, selected) = verify_order(editor.dispatcher.message_handlers.portfolio_message_handler.active_document_mut().unwrap());
assert_eq!(all, non_selected.into_iter().chain(selected.into_iter()).collect::<Vec<_>>());
assert_eq!(all, non_selected.into_iter().chain(selected).collect::<Vec<_>>());
}
#[test]
+11 -10
View File
@@ -7,28 +7,29 @@ fn generate_ts_types() {
use crate::messages::prelude::FrontendMessage;
use specta::{
ts::{export_datatype, BigIntExportBehavior, ExportConfiguration},
DefOpts, Type, TypeDefs,
DefOpts, NamedType, Type, TypeDefs,
};
use std::fs::File;
use std::io::Write;
let config = ExportConfiguration {
bigint: BigIntExportBehavior::Number,
..Default::default()
};
let config = ExportConfiguration::new().bigint(BigIntExportBehavior::Number);
let mut type_map = TypeDefs::new();
let datatype = FrontendMessage::definition(DefOpts {
parent_inline: false,
type_map: &mut type_map,
});
let datatype = FrontendMessage::named_data_type(
DefOpts {
parent_inline: false,
type_map: &mut type_map,
},
&FrontendMessage::definition_generics().into_iter().map(Into::into).collect::<Vec<_>>(),
)
.unwrap();
let mut export = String::new();
export += &export_datatype(&config, &datatype).unwrap();
type_map.values().flat_map(|v| export_datatype(&config, v)).for_each(|e| export += &format!("\n\n{e}"));
type_map.values().flatten().flat_map(|v| export_datatype(&config, v)).for_each(|e| export += &format!("\n\n{e}"));
let mut file = File::create("../types.ts").unwrap();
@@ -33,8 +33,9 @@ pub enum KeyPosition {
}
bitflags! {
#[derive(Default, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
#[repr(transparent)]
#[serde(transparent)]
pub struct ModifierKeys: u8 {
const SHIFT = 0b_0000_0001;
const ALT = 0b_0000_0010;
@@ -138,12 +138,11 @@ impl EditorMouseState {
}
bitflags! {
#[derive(Default, Serialize, Deserialize)]
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[repr(transparent)]
pub struct MouseKeys: u8 {
const LEFT = 0b0000_0001;
const RIGHT = 0b0000_0010;
const MIDDLE = 0b0000_0100;
const NONE = 0b0000_0000;
}
}
@@ -116,7 +116,7 @@ impl InputPreprocessorMessageHandler {
let old_down = self.mouse.mouse_keys & bit_flag == bit_flag;
let new_down = new_state.mouse_keys & bit_flag == bit_flag;
if !old_down && new_down {
if allow_first_button_down || self.mouse.mouse_keys != MouseKeys::NONE {
if allow_first_button_down || self.mouse.mouse_keys != MouseKeys::empty() {
responses.add(InputMapperMessage::KeyDown(key));
} else {
// Required to stop a keyup being emitted for a keydown outside canvas
@@ -221,7 +221,7 @@ impl WidgetLayout {
return;
}
// Diff all of the children
for (index, (current_child, new_child)) in self.layout.iter_mut().zip(new.layout.into_iter()).enumerate() {
for (index, (current_child, new_child)) in self.layout.iter_mut().zip(new.layout).enumerate() {
widget_path.push(index);
current_child.diff(new_child, widget_path, widget_diffs);
widget_path.pop();
@@ -394,7 +394,7 @@ impl LayoutGroup {
return;
}
// Diff all of the children
for (index, (current_child, new_child)) in current_widgets.iter_mut().zip(new_widgets.into_iter()).enumerate() {
for (index, (current_child, new_child)) in current_widgets.iter_mut().zip(new_widgets).enumerate() {
widget_path.push(index);
current_child.diff(new_child, widget_path, widget_diffs);
widget_path.pop();
@@ -421,7 +421,7 @@ impl LayoutGroup {
return;
}
// Diff all of the children
for (index, (current_child, new_child)) in current_layout.iter_mut().zip(new_layout.into_iter()).enumerate() {
for (index, (current_child, new_child)) in current_layout.iter_mut().zip(new_layout).enumerate() {
widget_path.push(index);
current_child.diff(new_child, widget_path, widget_diffs);
widget_path.pop();
@@ -58,7 +58,7 @@ pub struct PopoverButton {
#[derive(Clone, Serialize, Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
#[serde(rename_all(serialize = "camelCase", deserialize = "camelCase"))]
#[serde(rename_all = "camelCase")]
pub struct ParameterExposeButton {
pub exposed: bool,
@@ -78,7 +78,7 @@ pub struct ParameterExposeButton {
#[derive(Clone, Serialize, Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
#[serde(rename_all(serialize = "camelCase", deserialize = "camelCase"))]
#[serde(rename_all = "camelCase")]
pub struct TextButton {
#[widget_builder(constructor)]
pub label: String,
@@ -105,7 +105,7 @@ pub struct TextButton {
#[derive(Clone, Serialize, Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
#[serde(rename_all(serialize = "camelCase", deserialize = "camelCase"))]
#[serde(rename_all = "camelCase")]
pub struct BreadcrumbTrailButtons {
#[widget_builder(constructor)]
pub labels: Vec<String>,
@@ -202,13 +202,15 @@ impl<'a> ModifyInputsContext<'a> {
let NodeInput::Value {
tagged_value: TaggedValue::Subpaths(subpaths),
..
} = subpaths else {
} = subpaths
else {
return;
};
let NodeInput::Value {
tagged_value: TaggedValue::ManipulatorGroupIds(mirror_angle_groups),
..
} = mirror_angle_groups else {
} = mirror_angle_groups
else {
return;
};
@@ -375,7 +375,7 @@ impl NodeGraphMessageHandler {
continue;
}
for (input_index, input) in node.inputs.iter_mut().enumerate() {
let NodeInput::Node{ node_id, .. } = input else {
let NodeInput::Node { node_id, .. } = input else {
continue;
};
if *node_id != deleting_node_id {
@@ -383,9 +383,9 @@ impl NodeGraphMessageHandler {
}
let Some(node_type) = document_node_types::resolve_document_node_type(&node.name) else {
warn!("Removing input of invalid node type '{}'", node.name);
return false;
};
warn!("Removing input of invalid node type '{}'", node.name);
return false;
};
if let NodeInput::Value { tagged_value, .. } = &node_type.inputs[input_index].default {
*input = NodeInput::value(tagged_value.clone(), true);
}
@@ -444,12 +444,12 @@ impl MessageHandler<NodeGraphMessage, (&mut Document, &NodeGraphExecutor, u64)>
let Some(network) = self.get_active_network(document) else {
error!("No network");
return;
};
};
let Some(input_node) = network.nodes.get(&input_node) else {
error!("No to");
return;
};
let Some((input_index, _)) = input_node.inputs.iter().enumerate().filter(|input|input.1.is_exposed()).nth(input_node_connector_index) else {
let Some((input_index, _)) = input_node.inputs.iter().enumerate().filter(|input| input.1.is_exposed()).nth(input_node_connector_index) else {
error!("Failed to find actual index of connector index {input_node_connector_index} on node {input_node:#?}");
return;
};
@@ -482,7 +482,10 @@ impl MessageHandler<NodeGraphMessage, (&mut Document, &NodeGraphExecutor, u64)>
let node_id = node_id.unwrap_or_else(crate::application::generate_uuid);
let Some(document_node_type) = document_node_types::resolve_document_node_type(&node_type) else {
responses.add(DialogMessage::DisplayDialogError { title: "Cannot insert node".to_string(), description: format!("The document node '{node_type}' does not exist in the document node list") });
responses.add(DialogMessage::DisplayDialogError {
title: "Cannot insert node".to_string(),
description: format!("The document node '{node_type}' does not exist in the document node list"),
});
return;
};
@@ -1051,7 +1051,11 @@ pub fn imaginate_properties(document_node: &DocumentNode, node_id: NodeId, conte
LayoutGroup::Row { widgets }.with_tooltip("Connection status to the server that computes generated images")
};
let &NodeInput::Value {tagged_value: TaggedValue::ImaginateController(ref controller),..} = controller else {
let &NodeInput::Value {
tagged_value: TaggedValue::ImaginateController(ref controller),
..
} = controller
else {
panic!("Invalid output status input")
};
let imaginate_status = controller.get_status();
@@ -1085,7 +1089,7 @@ pub fn imaginate_properties(document_node: &DocumentNode, node_id: NodeId, conte
})
};
let image_controls: _ = {
let image_controls = {
let mut widgets = vec![WidgetHolder::text_widget("Image"), WidgetHolder::unrelated_separator()];
let assist_separators = [
WidgetHolder::unrelated_separator(), // TODO: These three separators add up to 24px,
@@ -98,12 +98,8 @@ pub fn register_artboard_layer_properties(layer: &Layer, responses: &mut VecDequ
}];
let properties_body = {
let LayerDataType::Shape(shape) = &layer.data else {
panic!("Artboards can only be shapes")
};
let Fill::Solid(color) = shape.style.fill() else {
panic!("Artboard must have a solid fill")
};
let LayerDataType::Shape(shape) = &layer.data else { panic!("Artboards can only be shapes") };
let Fill::Solid(color) = shape.style.fill() else { panic!("Artboard must have a solid fill") };
let render_data = RenderData::new(&persistent_data.font_cache, ViewMode::default(), None);
let pivot = layer.transform.transform_vector2(layer.layerspace_pivot(&render_data));
@@ -21,5 +21,5 @@ where
V: Deserialize<'de>,
{
let container: Vec<_> = serde::Deserialize::deserialize(deserializer)?;
Ok(T::from_iter(container.into_iter()))
Ok(T::from_iter(container))
}
@@ -644,7 +644,11 @@ impl PortfolioMessageHandler {
}))),
LayerDataType::Layer(layer) => {
let input_is_font = |input: &NodeInput| {
let NodeInput::Value { tagged_value: TaggedValue::Font(font), .. } = input else {
let NodeInput::Value {
tagged_value: TaggedValue::Font(font),
..
} = input
else {
return false;
};
font == target_font
@@ -152,7 +152,7 @@ impl OverlayRenderer {
let Some(manipulator_groups) = self.manipulator_group_overlay_cache.get(layer_id) else { return };
if visibility {
let Ok(layer) = document.layer(&layer_path) else { return };
let Some(vector_data) = layer.as_vector_data() else { return };
let Some(vector_data) = layer.as_vector_data() else { return };
for manipulator_group in vector_data.manipulator_groups() {
let id = manipulator_group.id;
if let Some(manipulator_group_overlays) = manipulator_groups.get(&id) {
@@ -194,7 +194,9 @@ impl ShapeState {
}
if mirror {
let Some(mut original_handle_position) = point.manipulator_type.get_position(group) else { continue };
let Some(mut original_handle_position) = point.manipulator_type.get_position(group) else {
continue;
};
original_handle_position += delta;
let point = ManipulatorPointId::new(point.group, point.manipulator_type.opposite());
@@ -318,7 +320,9 @@ impl ShapeState {
continue;
}
let Some(opposing_handle_length) = opposing_handle_lengths.get(&manipulator_group.id) else { continue };
let Some(opposing_handle_length) = opposing_handle_lengths.get(&manipulator_group.id) else {
continue;
};
let in_handle_selected = state.is_selected(ManipulatorPointId::new(manipulator_group.id, SelectedType::InHandle));
let out_handle_selected = state.is_selected(ManipulatorPointId::new(manipulator_group.id, SelectedType::OutHandle));
@@ -344,7 +348,9 @@ impl ShapeState {
continue;
};
let Some(opposing_handle) = single_selected_handle.opposite().get_position(manipulator_group) else { continue };
let Some(opposing_handle) = single_selected_handle.opposite().get_position(manipulator_group) else {
continue;
};
let Some(offset) = (opposing_handle - manipulator_group.anchor).try_normalize() else { continue };
@@ -627,14 +633,14 @@ impl ShapeState {
state.clear_points()
}
let Ok(layer) = document.layer(&layer_path) else {continue};
let Some(vector_data) = layer.as_vector_data() else {continue};
let Ok(layer) = document.layer(layer_path) else { continue };
let Some(vector_data) = layer.as_vector_data() else { continue };
let transform = document.multiply_transforms(layer_path).unwrap_or_default();
for manipulator_group in vector_data.manipulator_groups() {
for selected_type in [SelectedType::Anchor, SelectedType::InHandle, SelectedType::OutHandle] {
let Some(position) = selected_type.get_position(manipulator_group) else {continue};
let Some(position) = selected_type.get_position(manipulator_group) else { continue };
let transformed_position = transform.transform_point2(position);
if quad[0].min(quad[1]).cmple(transformed_position).all() && quad[0].max(quad[1]).cmpge(transformed_position).all() {
@@ -315,7 +315,11 @@ impl BrushToolData {
for (node, _node_id) in network.primary_flow() {
if node.name == "Brush" {
let points_input = node.inputs.get(2)?;
let NodeInput::Value { tagged_value: TaggedValue::BrushStrokes(strokes), .. } = points_input else {
let NodeInput::Value {
tagged_value: TaggedValue::BrushStrokes(strokes),
..
} = points_input
else {
continue;
};
self.strokes = strokes.clone();
@@ -210,7 +210,7 @@ impl Fsm for EllipseToolFsmState {
use EllipseToolFsmState::*;
use EllipseToolMessage::*;
let mut shape_data = &mut tool_data.data;
let shape_data = &mut tool_data.data;
if let ToolMessage::Ellipse(event) = event {
match (self, event) {
@@ -114,7 +114,7 @@ impl Fsm for NodeGraphToolFsmState {
use FrameToolMessage::*;
use NodeGraphToolFsmState::*;
let mut shape_data = &mut tool_data.data;
let shape_data = &mut tool_data.data;
if let ToolMessage::Frame(event) = event {
match (self, event) {
@@ -289,7 +289,7 @@ impl SelectedGradient {
inner_gradient.transform = gradient_space_transform(&inner_gradient.path, layer, document, render_data);
// Clear if no longer a gradient
let Some(gradient) = layer.style().ok().and_then(|style|style.fill().as_gradient()) else {
let Some(gradient) = layer.style().ok().and_then(|style| style.fill().as_gradient()) else {
responses.add(ToolMessage::RefreshToolOptions);
*gradient = None;
return;
@@ -114,7 +114,7 @@ impl Fsm for ImaginateToolFsmState {
use ImaginateToolFsmState::*;
use ImaginateToolMessage::*;
let mut shape_data = &mut tool_data.data;
let shape_data = &mut tool_data.data;
if let ToolMessage::Imaginate(event) = event {
match (self, event) {
@@ -351,7 +351,7 @@ impl Fsm for PathToolFsmState {
}
.into(),
));
return PathToolFsmState::Ready;
PathToolFsmState::Ready
}
(_, PathToolMessage::DragStop { shift_mirror_distance }) => {
let shift_pressed = input.keyboard.get(shift_mirror_distance as usize);
@@ -232,7 +232,9 @@ impl PenToolData {
// Stop the handles on the first point from mirroring
let Some(subpaths) = get_subpaths(layer, document) else { return };
let manipulator_groups = subpaths[subpath_index].manipulator_groups();
let Some(last_handle) = (if from_start { manipulator_groups.first() } else { manipulator_groups.last() }) else { return };
let Some(last_handle) = (if from_start { manipulator_groups.first() } else { manipulator_groups.last() }) else {
return;
};
responses.add(GraphOperationMessage::Vector {
layer: layer.to_vec(),
@@ -765,7 +767,9 @@ fn should_extend(document: &DocumentMessageHandler, pos: DVec2, tolerance: f64)
let mut best_distance_squared = tolerance * tolerance;
for layer_path in document.selected_layers() {
let Ok(viewspace) = document.document_legacy.generate_transform_relative_to_viewport(layer_path) else { continue };
let Ok(viewspace) = document.document_legacy.generate_transform_relative_to_viewport(layer_path) else {
continue;
};
let subpaths = get_subpaths(layer_path, document)?;
for (subpath_index, subpath) in subpaths.iter().enumerate() {
@@ -795,7 +799,11 @@ fn get_subpaths<'a>(layer_path: &[LayerId], document: &'a DocumentMessageHandler
for (node, _node_id) in network.primary_flow() {
if node.name == "Path Generator" {
let subpaths_input = node.inputs.get(0)?;
let NodeInput::Value { tagged_value: TaggedValue::Subpaths(subpaths), .. } = subpaths_input else {
let NodeInput::Value {
tagged_value: TaggedValue::Subpaths(subpaths),
..
} = subpaths_input
else {
continue;
};
@@ -209,7 +209,7 @@ impl Fsm for RectangleToolFsmState {
use RectangleToolFsmState::*;
use RectangleToolMessage::*;
let mut shape_data = &mut tool_data.data;
let shape_data = &mut tool_data.data;
if let ToolMessage::Rectangle(event) = event {
match (self, event) {
@@ -503,7 +503,7 @@ impl Fsm for SelectToolFsmState {
tool_data.drag_start = input.mouse.position;
tool_data.drag_current = input.mouse.position;
let dragging_bounds = tool_data.bounding_box_overlays.as_mut().and_then(|mut bounding_box| {
let dragging_bounds = tool_data.bounding_box_overlays.as_mut().and_then(|bounding_box| {
let edges = bounding_box.check_selected_edges(input.mouse.position);
bounding_box.selected_edges = edges.map(|(top, bottom, left, right)| {
@@ -250,7 +250,7 @@ impl Fsm for ShapeToolFsmState {
use ShapeToolFsmState::*;
use ShapeToolMessage::*;
let mut shape_data = &mut tool_data.data;
let shape_data = &mut tool_data.data;
if let ToolMessage::Shape(event) = event {
match (self, event) {
@@ -299,9 +299,27 @@ impl TextToolData {
}
fn extract_text_node_inputs(node: &DocumentNode) -> Option<(&String, &Font, f64)> {
let NodeInput::Value { tagged_value: TaggedValue::String(text), .. } = &node.inputs[1] else { return None; };
let NodeInput::Value { tagged_value: TaggedValue::Font(font), .. } = &node.inputs[2] else { return None; };
let NodeInput::Value { tagged_value: TaggedValue::F64(font_size), .. } = &node.inputs[3] else { return None; };
let NodeInput::Value {
tagged_value: TaggedValue::String(text),
..
} = &node.inputs[1]
else {
return None;
};
let NodeInput::Value {
tagged_value: TaggedValue::Font(font),
..
} = &node.inputs[2]
else {
return None;
};
let NodeInput::Value {
tagged_value: TaggedValue::F64(font_size),
..
} = &node.inputs[3]
else {
return None;
};
Some((text, font, *font_size))
}
@@ -456,7 +474,9 @@ fn get_text_node_id(network: &NodeNetwork) -> Option<NodeId> {
}
fn is_text_layer(document: &DocumentMessageHandler, layer_path: &[LayerId]) -> bool {
let Some(network) = get_network(layer_path, document) else { return false; };
let Some(network) = get_network(layer_path, document) else {
return false;
};
get_text_node_id(network).is_some()
}
+8 -4
View File
@@ -157,7 +157,7 @@ impl NodeRuntime {
let editor_api = WasmEditorApi {
font_cache: &self.font_cache,
image_frame,
application_io: &self.wasm_io.as_ref().unwrap(),
application_io: self.wasm_io.as_ref().unwrap(),
node_graph_message_sender: &self.sender,
imaginate_preferences: &self.imaginate_preferences,
};
@@ -185,7 +185,9 @@ impl NodeRuntime {
let old_id = self.canvas_cache.insert(path.to_vec(), surface_id);
if let Some(old_id) = old_id {
if old_id != surface_id {
self.wasm_io.as_ref().map(|io| io.destroy_surface(old_id));
if let Some(io) = self.wasm_io.as_ref() {
io.destroy_surface(old_id)
}
}
}
}
@@ -338,8 +340,10 @@ impl NodeGraphExecutor {
extract_data: F2,
) -> Option<U> {
let wrapping_document_node = network.nodes.get(node_path.last()?)?;
let DocumentNodeImplementation::Network(wrapped_network) = &wrapping_document_node.implementation else { return None; };
let introspection_node = find_node(&wrapped_network)?;
let DocumentNodeImplementation::Network(wrapped_network) = &wrapping_document_node.implementation else {
return None;
};
let introspection_node = find_node(wrapped_network)?;
let introspection = self.introspect_node(&[node_path, &[introspection_node]].concat())?;
let downcasted: &T = <dyn std::any::Any>::downcast_ref(introspection.as_ref())?;
Some(extract_data(downcasted))