diff --git a/editor/Cargo.toml b/editor/Cargo.toml index 3e2658fd0..64c5659ec 100644 --- a/editor/Cargo.toml +++ b/editor/Cargo.toml @@ -2,9 +2,9 @@ name = "graphite-editor" publish = false version = "0.0.0" -rust-version = "1.82" +rust-version = "1.85" authors = ["Graphite Authors "] -edition = "2021" +edition = "2024" readme = "../README.md" homepage = "https://graphite.rs" repository = "https://github.com/GraphiteEditor/Graphite" diff --git a/editor/src/application.rs b/editor/src/application.rs index 2af1a5a70..60487be2d 100644 --- a/editor/src/application.rs +++ b/editor/src/application.rs @@ -1,6 +1,5 @@ use crate::dispatcher::Dispatcher; use crate::messages::prelude::*; - pub use graphene_core::uuid::*; // TODO: serialize with serde to save the current editor state diff --git a/editor/src/dispatcher.rs b/editor/src/dispatcher.rs index 67db03571..5392b50c6 100644 --- a/editor/src/dispatcher.rs +++ b/editor/src/dispatcher.rs @@ -303,11 +303,7 @@ impl Dispatcher { fn create_indents(queues: &[VecDeque]) -> String { String::from_iter(queues.iter().enumerate().skip(1).map(|(index, queue)| { if index == queues.len() - 1 { - if queue.is_empty() { - "└── " - } else { - "├── " - } + if queue.is_empty() { "└── " } else { "├── " } } else if queue.is_empty() { " " } else { diff --git a/editor/src/macros.rs b/editor/src/macros.rs index fa3f10866..a5b43b4a3 100644 --- a/editor/src/macros.rs +++ b/editor/src/macros.rs @@ -25,7 +25,7 @@ /// ``` /// macro_rules! actions { - ($($v:expr),* $(,)?) => {{ + ($($v:expr_2021),* $(,)?) => {{ vec![$(vec![$v.into()]),*] }}; @@ -42,7 +42,7 @@ macro_rules! actions { /// } /// ``` macro_rules! advertise_actions { - ($($v:expr),* $(,)?) => { + ($($v:expr_2021),* $(,)?) => { fn actions(&self) -> $crate::utility_traits::ActionList { actions!($($v),*) } diff --git a/editor/src/messages/dialog/new_document_dialog/new_document_dialog_message_handler.rs b/editor/src/messages/dialog/new_document_dialog/new_document_dialog_message_handler.rs index 08c20df8a..fd095df90 100644 --- a/editor/src/messages/dialog/new_document_dialog/new_document_dialog_message_handler.rs +++ b/editor/src/messages/dialog/new_document_dialog/new_document_dialog_message_handler.rs @@ -1,9 +1,7 @@ use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::prelude::*; - -use graph_craft::document::NodeId; - use glam::{IVec2, UVec2}; +use graph_craft::document::NodeId; /// A dialog to allow users to set some initial options about a new document. #[derive(Debug, Clone, Default)] diff --git a/editor/src/messages/dialog/simple_dialogs/coming_soon_dialog.rs b/editor/src/messages/dialog/simple_dialogs/coming_soon_dialog.rs index f486dfc1a..b72c2301a 100644 --- a/editor/src/messages/dialog/simple_dialogs/coming_soon_dialog.rs +++ b/editor/src/messages/dialog/simple_dialogs/coming_soon_dialog.rs @@ -26,16 +26,18 @@ impl LayoutHolder for ComingSoonDialog { if let Some(issue) = self.issue { let row2 = vec![TextLabel::new("But you can help build it! Visit its issue:").widget_holder()]; - let row3 = vec![TextButton::new(format!("GitHub Issue #{issue}")) - .icon(Some("Website".into())) - .flush(true) - .on_update(move |_| { - FrontendMessage::TriggerVisitLink { - url: format!("https://github.com/GraphiteEditor/Graphite/issues/{issue}"), - } - .into() - }) - .widget_holder()]; + let row3 = vec![ + TextButton::new(format!("GitHub Issue #{issue}")) + .icon(Some("Website".into())) + .flush(true) + .on_update(move |_| { + FrontendMessage::TriggerVisitLink { + url: format!("https://github.com/GraphiteEditor/Graphite/issues/{issue}"), + } + .into() + }) + .widget_holder(), + ]; rows.push(LayoutGroup::Row { widgets: row2 }); rows.push(LayoutGroup::Row { widgets: row3 }); diff --git a/editor/src/messages/dialog/simple_dialogs/demo_artwork_dialog.rs b/editor/src/messages/dialog/simple_dialogs/demo_artwork_dialog.rs index 49d1e3f58..83084d0fd 100644 --- a/editor/src/messages/dialog/simple_dialogs/demo_artwork_dialog.rs +++ b/editor/src/messages/dialog/simple_dialogs/demo_artwork_dialog.rs @@ -32,11 +32,13 @@ impl LayoutHolder for DemoArtworkDialog { .flat_map(|chunk| { fn make_dialog(name: &str, filename: &str) -> Message { DialogMessage::CloseDialogAndThen { - followups: vec![FrontendMessage::TriggerFetchAndOpenDocument { - name: name.to_string(), - filename: filename.to_string(), - } - .into()], + followups: vec![ + FrontendMessage::TriggerFetchAndOpenDocument { + name: name.to_string(), + filename: filename.to_string(), + } + .into(), + ], } .into() } diff --git a/editor/src/messages/dialog/simple_dialogs/mod.rs b/editor/src/messages/dialog/simple_dialogs/mod.rs index fad483ef0..a330efac2 100644 --- a/editor/src/messages/dialog/simple_dialogs/mod.rs +++ b/editor/src/messages/dialog/simple_dialogs/mod.rs @@ -10,8 +10,7 @@ pub use about_graphite_dialog::AboutGraphiteDialog; pub use close_all_documents_dialog::CloseAllDocumentsDialog; pub use close_document_dialog::CloseDocumentDialog; pub use coming_soon_dialog::ComingSoonDialog; +pub use demo_artwork_dialog::ARTWORK; pub use demo_artwork_dialog::DemoArtworkDialog; pub use error_dialog::ErrorDialog; pub use licenses_dialog::LicensesDialog; - -pub use demo_artwork_dialog::ARTWORK; diff --git a/editor/src/messages/frontend/frontend_message.rs b/editor/src/messages/frontend/frontend_message.rs index 89306b211..7e1eaa951 100644 --- a/editor/src/messages/frontend/frontend_message.rs +++ b/editor/src/messages/frontend/frontend_message.rs @@ -6,7 +6,6 @@ use crate::messages::portfolio::document::node_graph::utility_types::{ use crate::messages::portfolio::document::utility_types::nodes::{JsRawBuffer, LayerPanelEntry, RawBuffer}; use crate::messages::prelude::*; use crate::messages::tool::utility_types::HintData; - use graph_craft::document::NodeId; use graphene_core::raster::color::Color; use graphene_core::text::Font; diff --git a/editor/src/messages/globals/global_variables.rs b/editor/src/messages/globals/global_variables.rs index 436985ba4..b3fb71da0 100644 --- a/editor/src/messages/globals/global_variables.rs +++ b/editor/src/messages/globals/global_variables.rs @@ -1,5 +1,4 @@ use crate::messages::portfolio::utility_types::Platform; - use std::sync::OnceLock; pub static GLOBAL_PLATFORM: OnceLock = OnceLock::new(); diff --git a/editor/src/messages/input_mapper/input_mapper_message_handler.rs b/editor/src/messages/input_mapper/input_mapper_message_handler.rs index 87e38346c..744f86d97 100644 --- a/editor/src/messages/input_mapper/input_mapper_message_handler.rs +++ b/editor/src/messages/input_mapper/input_mapper_message_handler.rs @@ -3,7 +3,6 @@ use super::utility_types::misc::Mapping; use crate::messages::input_mapper::utility_types::input_keyboard::{self, Key}; use crate::messages::portfolio::utility_types::KeyboardPlatformLayout; use crate::messages::prelude::*; - use std::fmt::Write; pub struct InputMapperMessageData<'a> { diff --git a/editor/src/messages/input_mapper/input_mappings.rs b/editor/src/messages/input_mapper/input_mappings.rs index 4d6936c43..939e85353 100644 --- a/editor/src/messages/input_mapper/input_mappings.rs +++ b/editor/src/messages/input_mapper/input_mappings.rs @@ -11,7 +11,6 @@ use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; use crate::messages::prelude::*; use crate::messages::tool::tool_messages::brush_tool::BrushToolMessageOptionsUpdate; use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys; - use glam::DVec2; impl From for Mapping { 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 39d568ca4..99a267550 100644 --- a/editor/src/messages/input_mapper/utility_types/input_keyboard.rs +++ b/editor/src/messages/input_mapper/utility_types/input_keyboard.rs @@ -1,8 +1,6 @@ use crate::messages::portfolio::utility_types::KeyboardPlatformLayout; use crate::messages::prelude::*; - use bitflags::bitflags; - use std::fmt::{self, Display, Formatter}; use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign}; diff --git a/editor/src/messages/input_mapper/utility_types/input_mouse.rs b/editor/src/messages/input_mapper/utility_types/input_mouse.rs index 8302345fa..00635587f 100644 --- a/editor/src/messages/input_mapper/utility_types/input_mouse.rs +++ b/editor/src/messages/input_mapper/utility_types/input_mouse.rs @@ -1,6 +1,5 @@ use crate::consts::DRAG_THRESHOLD; use crate::messages::prelude::*; - use bitflags::bitflags; use glam::DVec2; use std::collections::VecDeque; diff --git a/editor/src/messages/input_mapper/utility_types/macros.rs b/editor/src/messages/input_mapper/utility_types/macros.rs index fa40e2def..8371f2585 100644 --- a/editor/src/messages/input_mapper/utility_types/macros.rs +++ b/editor/src/messages/input_mapper/utility_types/macros.rs @@ -24,7 +24,7 @@ macro_rules! modifiers { /// Each handler adds or removes actions in the form of message discriminants. Here, we tie an input condition (such as a hotkey) to an action's full message. /// When an action is currently available, and the user enters that input, the action's message is dispatched on the message bus. macro_rules! entry { - ($input:expr; $(modifiers=[$($modifier:ident),*],)? $(refresh_keys=[$($refresh:ident),* $(,)?],)? action_dispatch=$action_dispatch:expr$(,)?) => { + ($input:expr_2021; $(modifiers=[$($modifier:ident),*],)? $(refresh_keys=[$($refresh:ident),* $(,)?],)? action_dispatch=$action_dispatch:expr_2021$(,)?) => { &[&[ // Cause the `action_dispatch` message to be sent when the specified input occurs. MappingEntry { @@ -72,7 +72,7 @@ macro_rules! entry { /// (key_up, key_down, double_click, wheel_scroll, pointer_move) /// ``` macro_rules! mapping { - [$($entry:expr),* $(,)?] => {{ + [$($entry:expr_2021),* $(,)?] => {{ let mut key_up = KeyMappingEntries::key_array(); let mut key_down = KeyMappingEntries::key_array(); let mut key_up_no_repeat = KeyMappingEntries::key_array(); @@ -107,7 +107,7 @@ macro_rules! mapping { /// Constructs an `ActionKeys` macro with a certain `Action` variant, conveniently wrapped in `Some()`. macro_rules! action_keys { - ($action:expr) => { + ($action:expr_2021) => { Some(crate::messages::input_mapper::utility_types::misc::ActionKeys::Action($action.into())) }; } diff --git a/editor/src/messages/input_mapper/utility_types/misc.rs b/editor/src/messages/input_mapper/utility_types/misc.rs index 97b60f07a..461734987 100644 --- a/editor/src/messages/input_mapper/utility_types/misc.rs +++ b/editor/src/messages/input_mapper/utility_types/misc.rs @@ -1,9 +1,8 @@ -use super::input_keyboard::{all_required_modifiers_pressed, Key, KeysGroup, LayoutKeysGroup}; +use super::input_keyboard::{Key, KeysGroup, LayoutKeysGroup, all_required_modifiers_pressed}; use crate::messages::input_mapper::key_mapping::MappingVariant; use crate::messages::input_mapper::utility_types::input_keyboard::{KeyStates, NUMBER_OF_KEYS}; use crate::messages::input_mapper::utility_types::input_mouse::NUMBER_OF_MOUSE_BUTTONS; use crate::messages::prelude::*; - use core::time::Duration; #[derive(Debug, Clone)] diff --git a/editor/src/messages/input_preprocessor/input_preprocessor_message.rs b/editor/src/messages/input_preprocessor/input_preprocessor_message.rs index b7059d419..ec5d7a4bf 100644 --- a/editor/src/messages/input_preprocessor/input_preprocessor_message.rs +++ b/editor/src/messages/input_preprocessor/input_preprocessor_message.rs @@ -1,7 +1,6 @@ use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys}; use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ViewportBounds}; use crate::messages::prelude::*; - use core::time::Duration; #[impl_message(Message, InputPreprocessor)] diff --git a/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs b/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs index 14963b589..cd36f3f65 100644 --- a/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs +++ b/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs @@ -3,7 +3,6 @@ use crate::messages::input_mapper::utility_types::input_mouse::{MouseButton, Mou use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo; use crate::messages::portfolio::utility_types::KeyboardPlatformLayout; use crate::messages::prelude::*; - use glam::DVec2; pub struct InputPreprocessorMessageData { diff --git a/editor/src/messages/layout/layout_message_handler.rs b/editor/src/messages/layout/layout_message_handler.rs index a5b130b52..4fbe4b273 100644 --- a/editor/src/messages/layout/layout_message_handler.rs +++ b/editor/src/messages/layout/layout_message_handler.rs @@ -1,11 +1,9 @@ use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::prelude::*; - use graphene_core::raster::color::Color; use graphene_core::text::Font; use graphene_std::vector::style::{FillChoice, GradientStops}; - use serde_json::Value; #[derive(Debug, Clone, Default)] diff --git a/editor/src/messages/layout/utility_types/layout_widget.rs b/editor/src/messages/layout/utility_types/layout_widget.rs index 9b580b1b7..c21c61fea 100644 --- a/editor/src/messages/layout/utility_types/layout_widget.rs +++ b/editor/src/messages/layout/utility_types/layout_widget.rs @@ -6,7 +6,6 @@ use crate::application::generate_uuid; use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup; use crate::messages::input_mapper::utility_types::misc::ActionKeys; use crate::messages::prelude::*; - use std::sync::Arc; #[repr(transparent)] @@ -348,11 +347,7 @@ impl LayoutGroup { val.clone_from(&tooltip); } } - if is_col { - Self::Column { widgets } - } else { - Self::Row { widgets } - } + if is_col { Self::Column { widgets } } else { Self::Row { widgets } } } /// Diffing updates self (where self is old) based on new, updating the list of modifications as it does so. diff --git a/editor/src/messages/layout/utility_types/widgets/button_widgets.rs b/editor/src/messages/layout/utility_types/widgets/button_widgets.rs index 8854667ec..6c5d28d62 100644 --- a/editor/src/messages/layout/utility_types/widgets/button_widgets.rs +++ b/editor/src/messages/layout/utility_types/widgets/button_widgets.rs @@ -2,12 +2,10 @@ use crate::messages::input_mapper::utility_types::misc::ActionKeys; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType; use crate::messages::tool::tool_messages::tool_prelude::WidgetCallback; - +use derivative::*; use graphene_std::vector::style::FillChoice; use graphite_proc_macros::WidgetBuilder; -use derivative::*; - #[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)] #[derivative(Debug, PartialEq)] pub struct IconButton { diff --git a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs index a7f0a843d..56bf475df 100644 --- a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs +++ b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs @@ -1,11 +1,10 @@ use crate::messages::input_mapper::utility_types::misc::ActionKeys; use crate::messages::layout::utility_types::widget_prelude::*; - -use graphene_core::{raster::curve::Curve, Color}; -use graphite_proc_macros::WidgetBuilder; - use derivative::*; use glam::DVec2; +use graphene_core::Color; +use graphene_core::raster::curve::Curve; +use graphite_proc_macros::WidgetBuilder; #[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)] #[derivative(Debug, PartialEq)] diff --git a/editor/src/messages/layout/utility_types/widgets/menu_widgets.rs b/editor/src/messages/layout/utility_types/widgets/menu_widgets.rs index 20aafd24b..db6de59e1 100644 --- a/editor/src/messages/layout/utility_types/widgets/menu_widgets.rs +++ b/editor/src/messages/layout/utility_types/widgets/menu_widgets.rs @@ -1,10 +1,9 @@ +use super::input_widgets::InvisibleStandinInput; use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup; use crate::messages::input_mapper::utility_types::misc::ActionKeys; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::prelude::*; -use super::input_widgets::InvisibleStandinInput; - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Default, specta::Type)] pub struct MenuBarEntryChildren(pub Vec>); diff --git a/editor/src/messages/message.rs b/editor/src/messages/message.rs index 8372f6935..446d04bc0 100644 --- a/editor/src/messages/message.rs +++ b/editor/src/messages/message.rs @@ -1,5 +1,4 @@ use crate::messages::prelude::*; - use graphite_proc_macros::*; #[impl_message] diff --git a/editor/src/messages/portfolio/document/document_message.rs b/editor/src/messages/portfolio/document/document_message.rs index 6bffba39f..56377be79 100644 --- a/editor/src/messages/portfolio/document/document_message.rs +++ b/editor/src/messages/portfolio/document/document_message.rs @@ -5,17 +5,15 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GridSnapping}; use crate::messages::portfolio::utility_types::PanelType; use crate::messages::prelude::*; - +use glam::DAffine2; use graph_craft::document::NodeId; +use graphene_core::Color; use graphene_core::raster::BlendMode; use graphene_core::raster::Image; use graphene_core::vector::style::ViewMode; -use graphene_core::Color; use graphene_std::renderer::ClickTarget; use graphene_std::transform::Footprint; -use glam::DAffine2; - #[impl_message(Message, PortfolioMessage, Document)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] pub enum DocumentMessage { diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 5a2b15976..f32ae795b 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -2,10 +2,10 @@ use super::node_graph::document_node_definitions; use super::node_graph::utility_types::Transform; use super::overlays::utility_types::Pivot; use super::utility_types::error::EditorError; -use super::utility_types::misc::{GroupFolderType, SnappingOptions, SnappingState, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS}; +use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS, SnappingOptions, SnappingState}; use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus}; use super::utility_types::nodes::{CollapsedLayers, SelectedNodes}; -use crate::application::{generate_uuid, GRAPHITE_GIT_COMMIT_HASH}; +use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid}; use crate::consts::{ASYMPTOTIC_EFFECT, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_SAVE_SUFFIX, SCALE_EFFECT, SCROLLBAR_SPACING, VIEWPORT_ROTATE_SNAP_INTERVAL}; use crate::messages::input_mapper::utility_types::macros::action_keys; use crate::messages::layout::utility_types::widget_prelude::*; @@ -24,17 +24,15 @@ use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys; use crate::messages::tool::tool_messages::tool_prelude::Key; use crate::messages::tool::utility_types::ToolType; use crate::node_graph_executor::NodeGraphExecutor; - use bezier_rs::Subpath; +use glam::{DAffine2, DVec2, IVec2}; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork}; -use graphene_core::raster::image::ImageFrameTable; use graphene_core::raster::BlendMode; +use graphene_core::raster::image::ImageFrameTable; use graphene_core::vector::style::ViewMode; use graphene_std::renderer::{ClickTarget, Quad}; -use graphene_std::vector::{path_bool_lib, PointId}; - -use glam::{DAffine2, DVec2, IVec2}; +use graphene_std::vector::{PointId, path_bool_lib}; pub struct DocumentMessageData<'a> { pub document_id: DocumentId, @@ -1497,7 +1495,7 @@ impl MessageHandler> for DocumentMessag impl DocumentMessageHandler { /// Runs an intersection test with all layers and a viewport space quad - pub fn intersect_quad<'a>(&'a self, viewport_quad: graphene_core::renderer::Quad, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + 'a { + pub fn intersect_quad<'a>(&'a self, viewport_quad: graphene_core::renderer::Quad, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + use<'a> { let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz); let document_quad = document_to_viewport.inverse() * viewport_quad; @@ -1505,12 +1503,12 @@ impl DocumentMessageHandler { } /// Runs an intersection test with all layers and a viewport space quad; ignoring artboards - pub fn intersect_quad_no_artboards<'a>(&'a self, viewport_quad: graphene_core::renderer::Quad, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + 'a { + pub fn intersect_quad_no_artboards<'a>(&'a self, viewport_quad: graphene_core::renderer::Quad, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + use<'a> { self.intersect_quad(viewport_quad, ipp).filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[])) } /// Runs an intersection test with all layers and a viewport space subpath - pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: Subpath, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + 'a { + pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: Subpath, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + use<'a> { let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz); viewport_polygon.apply_transform(document_to_viewport.inverse()); @@ -1518,7 +1516,7 @@ impl DocumentMessageHandler { } /// Runs an intersection test with all layers and a viewport space subpath; ignoring artboards - pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: Subpath, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + 'a { + pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: Subpath, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + use<'a> { self.intersect_polygon(viewport_polygon, ipp).filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[])) } @@ -1562,7 +1560,7 @@ impl DocumentMessageHandler { } /// Find all of the layers that were clicked on from a viewport space location - pub fn click_xray(&self, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + '_ { + pub fn click_xray(&self, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + use<'_> { let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz); let point = document_to_viewport.inverse().transform_point2(ipp.mouse.position); ClickXRayIter::new(&self.network_interface, XRayTarget::Point(point)) @@ -1584,7 +1582,7 @@ impl DocumentMessageHandler { } /// Find layers under the location in viewport space that was clicked, listed by their depth in the layer tree hierarchy. - pub fn click_list<'a>(&'a self, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + 'a { + pub fn click_list<'a>(&'a self, ipp: &InputPreprocessorMessageHandler) -> impl Iterator + use<'a> { self.click_xray(ipp) .filter(move |&layer| !self.network_interface.is_artboard(&layer.to_node(), &[])) .skip_while(|&layer| layer == LayerNodeIdentifier::ROOT_PARENT) diff --git a/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs b/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs index 7b04e9f98..a6e3fb38e 100644 --- a/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs +++ b/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs @@ -2,20 +2,18 @@ use super::utility_types::TransformIn; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate; use crate::messages::prelude::*; - use bezier_rs::Subpath; +use glam::{DAffine2, DVec2, IVec2}; use graph_craft::document::NodeId; -use graphene_core::raster::image::ImageFrameTable; use graphene_core::raster::BlendMode; +use graphene_core::raster::image::ImageFrameTable; use graphene_core::text::{Font, TypesettingConfig}; -use graphene_core::vector::brush_stroke::BrushStroke; -use graphene_core::vector::style::{Fill, Stroke}; use graphene_core::vector::PointId; use graphene_core::vector::VectorModificationType; +use graphene_core::vector::brush_stroke::BrushStroke; +use graphene_core::vector::style::{Fill, Stroke}; use graphene_core::{Artboard, Color}; -use glam::{DAffine2, DVec2, IVec2}; - #[impl_message(Message, DocumentMessage, GraphOperation)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] pub enum GraphOperationMessage { diff --git a/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs b/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs index 0c9e7c819..cea12c3e5 100644 --- a/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs +++ b/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs @@ -5,16 +5,14 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector}; use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers; use crate::messages::prelude::*; - +use glam::{DAffine2, DVec2}; use graph_craft::document::{NodeId, NodeInput}; +use graphene_core::Color; use graphene_core::renderer::Quad; use graphene_core::text::{Font, TypesettingConfig}; use graphene_core::vector::style::{Fill, Gradient, GradientStops, GradientType, LineCap, LineJoin, Stroke}; -use graphene_core::Color; use graphene_std::vector::convert_usvg_path; -use glam::{DAffine2, DVec2}; - #[derive(Debug, Clone)] struct ArtboardInfo { input_node: NodeInput, @@ -262,10 +260,9 @@ impl MessageHandler> for Gr // Modify upstream connections for outward_wire in &artboard.1.output_nodes { let input = NodeInput::node(artboard_data[artboard.0].merge_node, 0); - let input_connector = if let Some(artboard_info) = artboard_data.get(&outward_wire.node_id().unwrap_or_default()) { - InputConnector::node(artboard_info.merge_node, outward_wire.input_index()) - } else { - *outward_wire + let input_connector = match artboard_data.get(&outward_wire.node_id().unwrap_or_default()) { + Some(artboard_info) => InputConnector::node(artboard_info.merge_node, outward_wire.input_index()), + _ => *outward_wire, }; responses.add(NodeGraphMessage::SetInput { input_connector, input }); } 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 64ae4577f..586389166 100644 --- a/editor/src/messages/portfolio/document/graph_operation/transform_utils.rs +++ b/editor/src/messages/portfolio/document/graph_operation/transform_utils.rs @@ -1,10 +1,9 @@ use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface}; - use bezier_rs::Subpath; -use graph_craft::document::{value::TaggedValue, NodeId, NodeInput}; -use graphene_core::vector::PointId; - use glam::{DAffine2, DVec2}; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{NodeId, NodeInput}; +use graphene_core::vector::PointId; /// Convert an affine transform into the tuple `(scale, angle, translation, shear)` assuming `shear.y = 0`. pub fn compute_scale_angle_translation_shear(transform: DAffine2) -> (DVec2, f64, DVec2, DVec2) { @@ -89,11 +88,7 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 { /// Extract the current normalized pivot from the layer 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) - } + if let Some(&TaggedValue::DVec2(pivot)) = inputs[5].as_value() { pivot } else { DVec2::splat(0.5) } } /// ![](https://files.keavon.com/-/OptimisticSpotlessTinamou/capture.png) diff --git a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs index ab9a1eade..aec230d88 100644 --- a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs +++ b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs @@ -3,22 +3,20 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions: use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::{self, InputConnector, NodeNetworkInterface, OutputConnector}; use crate::messages::prelude::*; - use bezier_rs::Subpath; +use glam::{DAffine2, DVec2, IVec2}; use graph_craft::concrete; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeInput}; -use graphene_core::raster::image::ImageFrameTable; use graphene_core::raster::BlendMode; +use graphene_core::raster::image::ImageFrameTable; use graphene_core::text::{Font, TypesettingConfig}; use graphene_core::vector::brush_stroke::BrushStroke; use graphene_core::vector::style::{Fill, Stroke}; use graphene_core::vector::{PointId, VectorModificationType}; use graphene_core::{Artboard, Color}; -use graphene_std::vector::{VectorData, VectorDataTable}; use graphene_std::GraphicGroupTable; - -use glam::{DAffine2, DVec2, IVec2}; +use graphene_std::vector::{VectorData, VectorDataTable}; #[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)] pub enum TransformIn { @@ -82,10 +80,9 @@ impl<'a> ModifyInputsContext<'a> { if current_index == insert_index { break; } - let next_node_in_stack_id = - network_interface - .input_from_connector(&post_node_input_connector, &[]) - .and_then(|input_from_connector| if let NodeInput::Node { node_id, .. } = input_from_connector { Some(node_id) } else { None }); + let next_node_in_stack_id = network_interface + .input_from_connector(&post_node_input_connector, &[]) + .and_then(|input_from_connector| if let NodeInput::Node { node_id, .. } = input_from_connector { Some(node_id) } else { None }); if let Some(next_node_in_stack_id) = next_node_in_stack_id { // Only increment index for layer nodes diff --git a/editor/src/messages/portfolio/document/navigation/navigation_message.rs b/editor/src/messages/portfolio/document/navigation/navigation_message.rs index b5c409522..8a1a0cdce 100644 --- a/editor/src/messages/portfolio/document/navigation/navigation_message.rs +++ b/editor/src/messages/portfolio/document/navigation/navigation_message.rs @@ -1,6 +1,5 @@ use crate::messages::input_mapper::utility_types::input_keyboard::Key; use crate::messages::prelude::*; - use glam::DVec2; #[impl_message(Message, DocumentMessage, Navigation)] diff --git a/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs b/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs index 10e4564a2..9d1ca39e4 100644 --- a/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs +++ b/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs @@ -10,10 +10,8 @@ use crate::messages::portfolio::document::utility_types::misc::PTZ; use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface; use crate::messages::prelude::*; use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo}; - -use graph_craft::document::NodeId; - use glam::{DAffine2, DVec2}; +use graph_craft::document::NodeId; pub struct NavigationMessageData<'a> { pub network_interface: &'a mut NodeNetworkInterface, 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 351aac510..693ca468f 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 @@ -8,12 +8,12 @@ use crate::messages::portfolio::document::utility_types::network_interface::{ use crate::messages::portfolio::utility_types::PersistentData; use crate::messages::prelude::Message; use crate::node_graph_executor::NodeGraphExecutor; - +use glam::DVec2; +use graph_craft::ProtoNodeIdentifier; use graph_craft::concrete; use graph_craft::document::value::*; use graph_craft::document::*; use graph_craft::imaginate_input::ImaginateSamplingMethod; -use graph_craft::ProtoNodeIdentifier; use graphene_core::raster::brush_cache::BrushCache; use graphene_core::raster::image::ImageFrameTable; use graphene_core::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlue, RedGreenBlueAlpha}; @@ -22,12 +22,10 @@ use graphene_core::transform::Footprint; use graphene_core::vector::VectorDataTable; use graphene_core::*; use graphene_std::wasm_application_io::WasmEditorApi; -#[cfg(feature = "gpu")] -use wgpu_executor::{Bindgroup, CommandBuffer, PipelineLayout, ShaderHandle, ShaderInputFrame, WgpuShaderInput}; - -use glam::DVec2; use once_cell::sync::Lazy; use std::collections::{HashMap, HashSet, VecDeque}; +#[cfg(feature = "gpu")] +use wgpu_executor::{Bindgroup, CommandBuffer, PipelineLayout, ShaderHandle, ShaderInputFrame, WgpuShaderInput}; pub struct NodePropertiesContext<'a> { pub persistent_data: &'a PersistentData, @@ -52,10 +50,9 @@ impl NodePropertiesContext<'_> { log::error!("Could not get input properties row in call_widget_override"); return Vec::new(); }; - if let Some(tooltip) = &input_properties_row.input_data.get("tooltip").and_then(|tooltip| tooltip.as_str()) { - layout_group.into_iter().map(|widget| widget.with_tooltip(*tooltip)).collect::>() - } else { - layout_group + match &input_properties_row.input_data.get("tooltip").and_then(|tooltip| tooltip.as_str()) { + Some(tooltip) => layout_group.into_iter().map(|widget| widget.with_tooltip(*tooltip)).collect::>(), + _ => layout_group, } }) .map_err(|error| { diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs index 5d38de58a..45674a82a 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs @@ -3,7 +3,6 @@ use crate::messages::input_mapper::utility_types::input_keyboard::Key; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::{ImportOrExport, InputConnector, NodeTemplate, OutputConnector}; use crate::messages::prelude::*; - use glam::IVec2; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeInput}; 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 5b5349bf3..27b6ee2dd 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 @@ -15,13 +15,11 @@ use crate::messages::portfolio::document::utility_types::network_interface::{ use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelEntry}; use crate::messages::prelude::*; use crate::messages::tool::common_functionality::auto_panning::AutoPanning; - +use glam::{DAffine2, DVec2, IVec2}; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput}; use graph_craft::proto::GraphErrors; use graphene_core::*; use renderer::Quad; - -use glam::{DAffine2, DVec2, IVec2}; use std::cmp::Ordering; #[derive(Debug)] @@ -1141,11 +1139,7 @@ impl<'a> MessageHandler> for NodeGrap let mut node_wires = Vec::new(); let mut stack_wires = Vec::new(); for wire in overlapping_wires { - if is_stack_wire(&wire) { - stack_wires.push(wire) - } else { - node_wires.push(wire) - } + if is_stack_wire(&wire) { stack_wires.push(wire) } else { node_wires.push(wire) } } // Auto convert node to layer when inserting on a single stack wire @@ -2068,26 +2062,23 @@ impl NodeGraphMessageHandler { .iter() .flat_map(|(wire_end, node)| node.inputs.iter().filter(|input| input.is_exposed()).enumerate().map(move |(index, input)| (input, wire_end, index))) .filter_map(|(input, &wire_end, wire_end_input_index)| { - if let NodeInput::Node { - node_id: wire_start, - output_index: wire_start_output_index, - // TODO: add ui for lambdas - lambda: _, - } = *input - { - Some(FrontendNodeWire { + match *input { + NodeInput::Node { + node_id: wire_start, + output_index: wire_start_output_index, + // TODO: add ui for lambdas + lambda: _, + } => Some(FrontendNodeWire { wire_start: OutputConnector::node(wire_start, wire_start_output_index), wire_end: InputConnector::node(wire_end, wire_end_input_index), dashed: false, - }) - } else if let NodeInput::Network { import_index, .. } = *input { - Some(FrontendNodeWire { + }), + NodeInput::Network { import_index, .. } => Some(FrontendNodeWire { wire_start: OutputConnector::Import(import_index), wire_end: InputConnector::node(wire_end, wire_end_input_index), dashed: false, - }) - } else { - None + }), + _ => None, } }) .collect::>(); @@ -2281,16 +2272,12 @@ impl NodeGraphMessageHandler { let mut current_network = network_interface.nested_network(¤t_network_path).unwrap(); let mut subgraph_names = vec!["Document".to_string()]; for node_id in breadcrumb_network_path { - if let Some(node) = current_network.nodes.get(node_id) { - if let Some(network) = node.implementation.get_network() { - current_network = network; - }; - subgraph_names.push(network_interface.frontend_display_name(node_id, ¤t_network_path)); - current_network_path.push(*node_id) - } else { - // Could not get node in network in breadcrumb_network_path - return None; + let node = current_network.nodes.get(node_id)?; + if let Some(network) = node.implementation.get_network() { + current_network = network; }; + subgraph_names.push(network_interface.frontend_display_name(node_id, ¤t_network_path)); + current_network_path.push(*node_id) } Some(subgraph_names) } diff --git a/editor/src/messages/portfolio/document/node_graph/node_properties.rs b/editor/src/messages/portfolio/document/node_graph/node_properties.rs index f053592c1..40dc2f96c 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_properties.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_properties.rs @@ -1,16 +1,16 @@ #![allow(clippy::too_many_arguments)] -use super::document_node_definitions::{NodePropertiesContext, NODE_OVERRIDES}; +use super::document_node_definitions::{NODE_OVERRIDES, NodePropertiesContext}; use super::utility_types::FrontendGraphDataType; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::prelude::*; - use dyn_any::DynAny; +use glam::{DAffine2, DVec2, IVec2, UVec2}; +use graph_craft::Type; use graph_craft::document::value::TaggedValue; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput}; use graph_craft::imaginate_input::{ImaginateMaskStartingFill, ImaginateSamplingMethod}; -use graph_craft::Type; use graphene_core::raster::curve::Curve; use graphene_core::raster::image::ImageFrameTable; use graphene_core::raster::{ @@ -22,25 +22,20 @@ use graphene_core::vector::misc::CentroidType; use graphene_core::vector::style::{GradientType, LineCap, LineJoin}; use graphene_std::application_io::TextureFrameTable; use graphene_std::transform::Footprint; +use graphene_std::vector::VectorDataTable; use graphene_std::vector::misc::BooleanOperation; use graphene_std::vector::style::{Fill, FillChoice, FillType, GradientStops}; -use graphene_std::vector::VectorDataTable; use graphene_std::{GraphicGroupTable, RasterFrame}; -use glam::{DAffine2, DVec2, IVec2, UVec2}; - pub(crate) fn string_properties(text: &str) -> Vec { let widget = TextLabel::new(text).widget_holder(); vec![LayoutGroup::Row { widgets: vec![widget] }] } fn optionally_update_value(value: impl Fn(&T) -> Option + 'static + Send + Sync, node_id: NodeId, input_index: usize) -> impl Fn(&T) -> Message + 'static + Send + Sync { - move |input_value: &T| { - if let Some(value) = value(input_value) { - NodeGraphMessage::SetInputValue { node_id, input_index, value }.into() - } else { - Message::NoOp - } + move |input_value: &T| match value(input_value) { + Some(value) => NodeGraphMessage::SetInputValue { node_id, input_index, value }.into(), + _ => Message::NoOp, } } @@ -177,68 +172,78 @@ pub(crate) fn property_from_type( Some(x) if x == TypeId::of::() => cellular_distance_function(document_node, node_id, index, name, true, false), Some(x) if x == TypeId::of::() => cellular_return_type(document_node, node_id, index, name, true, false), Some(x) if x == TypeId::of::() => domain_warp_type(document_node, node_id, index, name, true, false), - Some(x) if x == TypeId::of::() => vec![DropdownInput::new(vec![vec![ - MenuListEntry::new("Relative") - .label("Relative") - .on_update(update_value(|_| TaggedValue::RelativeAbsolute(RelativeAbsolute::Relative), node_id, index)), - MenuListEntry::new("Absolute") - .label("Absolute") - .on_update(update_value(|_| TaggedValue::RelativeAbsolute(RelativeAbsolute::Absolute), node_id, index)), - ]]) - .widget_holder()] + Some(x) if x == TypeId::of::() => vec![ + DropdownInput::new(vec![vec![ + MenuListEntry::new("Relative") + .label("Relative") + .on_update(update_value(|_| TaggedValue::RelativeAbsolute(RelativeAbsolute::Relative), node_id, index)), + MenuListEntry::new("Absolute") + .label("Absolute") + .on_update(update_value(|_| TaggedValue::RelativeAbsolute(RelativeAbsolute::Absolute), node_id, index)), + ]]) + .widget_holder(), + ] .into(), Some(x) if x == TypeId::of::() => line_cap_widget(document_node, node_id, index, name, true), Some(x) if x == TypeId::of::() => line_join_widget(document_node, node_id, index, name, true), - Some(x) if x == TypeId::of::() => vec![DropdownInput::new(vec![vec![ - MenuListEntry::new("Solid") - .label("Solid") - .on_update(update_value(|_| TaggedValue::FillType(FillType::Solid), node_id, index)), - MenuListEntry::new("Gradient") - .label("Gradient") - .on_update(update_value(|_| TaggedValue::FillType(FillType::Gradient), node_id, index)), - ]]) - .widget_holder()] + Some(x) if x == TypeId::of::() => vec![ + DropdownInput::new(vec![vec![ + MenuListEntry::new("Solid") + .label("Solid") + .on_update(update_value(|_| TaggedValue::FillType(FillType::Solid), node_id, index)), + MenuListEntry::new("Gradient") + .label("Gradient") + .on_update(update_value(|_| TaggedValue::FillType(FillType::Gradient), node_id, index)), + ]]) + .widget_holder(), + ] .into(), - Some(x) if x == TypeId::of::() => vec![DropdownInput::new(vec![vec![ - MenuListEntry::new("Linear") - .label("Linear") - .on_update(update_value(|_| TaggedValue::GradientType(GradientType::Linear), node_id, index)), - MenuListEntry::new("Radial") - .label("Radial") - .on_update(update_value(|_| TaggedValue::GradientType(GradientType::Radial), node_id, index)), - ]]) - .widget_holder()] + Some(x) if x == TypeId::of::() => vec![ + DropdownInput::new(vec![vec![ + MenuListEntry::new("Linear") + .label("Linear") + .on_update(update_value(|_| TaggedValue::GradientType(GradientType::Linear), node_id, index)), + MenuListEntry::new("Radial") + .label("Radial") + .on_update(update_value(|_| TaggedValue::GradientType(GradientType::Radial), node_id, index)), + ]]) + .widget_holder(), + ] .into(), Some(x) if x == TypeId::of::() => boolean_operation_radio_buttons(document_node, node_id, index, name, true), Some(x) if x == TypeId::of::() => centroid_widget(document_node, node_id, index), Some(x) if x == TypeId::of::() => luminance_calculation(document_node, node_id, index, name, true), - Some(x) if x == TypeId::of::() => vec![DropdownInput::new( - ImaginateSamplingMethod::list() - .into_iter() - .map(|method| { - vec![MenuListEntry::new(format!("{:?}", method)).label(method.to_string()).on_update(update_value( - move |_| TaggedValue::ImaginateSamplingMethod(method), - node_id, - index, - ))] - }) - .collect(), - ) - .widget_holder()] + Some(x) if x == TypeId::of::() => vec![ + DropdownInput::new( + ImaginateSamplingMethod::list() + .into_iter() + .map(|method| { + vec![MenuListEntry::new(format!("{:?}", method)).label(method.to_string()).on_update(update_value( + move |_| TaggedValue::ImaginateSamplingMethod(method), + node_id, + index, + ))] + }) + .collect(), + ) + .widget_holder(), + ] .into(), - Some(x) if x == TypeId::of::() => vec![DropdownInput::new( - ImaginateMaskStartingFill::list() - .into_iter() - .map(|fill| { - vec![MenuListEntry::new(format!("{:?}", fill)).label(fill.to_string()).on_update(update_value( - move |_| TaggedValue::ImaginateMaskStartingFill(fill), - node_id, - index, - ))] - }) - .collect(), - ) - .widget_holder()] + Some(x) if x == TypeId::of::() => vec![ + DropdownInput::new( + ImaginateMaskStartingFill::list() + .into_iter() + .map(|fill| { + vec![MenuListEntry::new(format!("{:?}", fill)).label(fill.to_string()).on_update(update_value( + move |_| TaggedValue::ImaginateMaskStartingFill(fill), + node_id, + index, + ))] + }) + .collect(), + ) + .widget_holder(), + ] .into(), _ => { let mut widgets = start_widgets(document_node, node_id, index, name, FrontendGraphDataType::General, true); @@ -313,7 +318,7 @@ pub fn bool_widget(document_node: &DocumentNode, node_id: NodeId, index: usize, log::warn!("A widget failed to be built because its node's input index is invalid."); return vec![]; }; - if let Some(&TaggedValue::Bool(x)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::Bool(x)) = input.as_non_exposed_value() { widgets.extend_from_slice(&[ Separator::new(SeparatorType::Unrelated).widget_holder(), checkbox_input @@ -342,7 +347,7 @@ pub fn footprint_widget(document_node: &DocumentNode, node_id: NodeId, index: us log::warn!("A widget failed to be built because its node's input index is invalid."); return vec![]; }; - if let Some(&TaggedValue::Footprint(footprint)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::Footprint(footprint)) = input.as_non_exposed_value() { let top_left = footprint.transform.transform_point2(DVec2::ZERO); let bounds = footprint.scale(); let oversample = footprint.resolution.as_dvec2() / bounds; @@ -752,7 +757,7 @@ pub fn color_channel(document_node: &DocumentNode, node_id: NodeId, index: usize log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::RedGreenBlue(mode)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::RedGreenBlue(mode)) = input.as_non_exposed_value() { let calculation_modes = [RedGreenBlue::Red, RedGreenBlue::Green, RedGreenBlue::Blue]; let mut entries = Vec::with_capacity(calculation_modes.len()); for method in calculation_modes { @@ -779,7 +784,7 @@ pub fn rgba_channel(document_node: &DocumentNode, node_id: NodeId, index: usize, log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::RedGreenBlueAlpha(mode)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::RedGreenBlueAlpha(mode)) = input.as_non_exposed_value() { let calculation_modes = [RedGreenBlueAlpha::Red, RedGreenBlueAlpha::Green, RedGreenBlueAlpha::Blue, RedGreenBlueAlpha::Alpha]; let mut entries = Vec::with_capacity(calculation_modes.len()); for method in calculation_modes { @@ -807,7 +812,7 @@ pub fn noise_type(document_node: &DocumentNode, node_id: NodeId, index: usize, n log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::NoiseType(noise_type)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::NoiseType(noise_type)) = input.as_non_exposed_value() { let entries = NoiseType::list() .iter() .map(|noise_type| { @@ -833,7 +838,7 @@ pub fn fractal_type(document_node: &DocumentNode, node_id: NodeId, index: usize, log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::FractalType(fractal_type)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::FractalType(fractal_type)) = input.as_non_exposed_value() { let entries = FractalType::list() .iter() .map(|fractal_type| { @@ -859,7 +864,7 @@ pub fn cellular_distance_function(document_node: &DocumentNode, node_id: NodeId, log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::CellularDistanceFunction(cellular_distance_function)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::CellularDistanceFunction(cellular_distance_function)) = input.as_non_exposed_value() { let entries = CellularDistanceFunction::list() .iter() .map(|cellular_distance_function| { @@ -888,7 +893,7 @@ pub fn cellular_return_type(document_node: &DocumentNode, node_id: NodeId, index log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::CellularReturnType(cellular_return_type)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::CellularReturnType(cellular_return_type)) = input.as_non_exposed_value() { let entries = CellularReturnType::list() .iter() .map(|cellular_return_type| { @@ -914,7 +919,7 @@ pub fn domain_warp_type(document_node: &DocumentNode, node_id: NodeId, index: us log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::DomainWarpType(domain_warp_type)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::DomainWarpType(domain_warp_type)) = input.as_non_exposed_value() { let entries = DomainWarpType::list() .iter() .map(|domain_warp_type| { @@ -940,7 +945,7 @@ pub fn blend_mode(document_node: &DocumentNode, node_id: NodeId, index: usize, n log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::BlendMode(blend_mode)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() { let entries = BlendMode::list_svg_subset() .iter() .map(|category| { @@ -973,7 +978,7 @@ pub fn luminance_calculation(document_node: &DocumentNode, node_id: NodeId, inde log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::LuminanceCalculation(calculation)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::LuminanceCalculation(calculation)) = input.as_non_exposed_value() { let calculation_modes = LuminanceCalculation::list(); let mut entries = Vec::with_capacity(calculation_modes.len()); for method in calculation_modes { @@ -1001,7 +1006,7 @@ pub fn boolean_operation_radio_buttons(document_node: &DocumentNode, node_id: No log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::BooleanOperation(calculation)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::BooleanOperation(calculation)) = input.as_non_exposed_value() { let operations = BooleanOperation::list(); let icons = BooleanOperation::icons(); let mut entries = Vec::with_capacity(operations.len()); @@ -1030,7 +1035,7 @@ pub fn line_cap_widget(document_node: &DocumentNode, node_id: NodeId, index: usi log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::LineCap(line_cap)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::LineCap(line_cap)) = input.as_non_exposed_value() { let entries = [("Butt", LineCap::Butt), ("Round", LineCap::Round), ("Square", LineCap::Square)] .into_iter() .map(|(name, val)| { @@ -1055,7 +1060,7 @@ pub fn line_join_widget(document_node: &DocumentNode, node_id: NodeId, index: us log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::LineJoin(line_join)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::LineJoin(line_join)) = input.as_non_exposed_value() { let entries = [("Miter", LineJoin::Miter), ("Bevel", LineJoin::Bevel), ("Round", LineJoin::Round)] .into_iter() .map(|(name, val)| { @@ -1101,7 +1106,7 @@ pub fn color_widget(document_node: &DocumentNode, node_id: NodeId, index: usize, .on_commit(commit_value) .widget_holder(), ), - TaggedValue::GradientStops(ref x) => widgets.push( + TaggedValue::GradientStops(x) => widgets.push( color_button .value(FillChoice::Gradient(x.clone())) .on_update(update_value( @@ -1143,7 +1148,7 @@ pub fn centroid_widget(document_node: &DocumentNode, node_id: NodeId, index: usi log::warn!("A widget failed to be built because its node's input index is invalid."); return LayoutGroup::Row { widgets: vec![] }; }; - if let Some(&TaggedValue::CentroidType(centroid_type)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::CentroidType(centroid_type)) = input.as_non_exposed_value() { let entries = vec![ RadioEntryData::new("area") .label("Area") @@ -1223,13 +1228,10 @@ pub fn query_assign_colors_randomize(node_id: NodeId, context: &NodePropertiesCo let document_node = get_document_node(node_id, context)?; // This is safe since the node is a proto node and the implementation cannot be changed. let randomize_index = 5; - Ok( - if let Some(&TaggedValue::Bool(randomize_enabled)) = &document_node.inputs.get(randomize_index).and_then(|input| input.as_value()) { - randomize_enabled - } else { - false - }, - ) + Ok(match document_node.inputs.get(randomize_index).and_then(|input| input.as_value()) { + Some(TaggedValue::Bool(randomize_enabled)) => *randomize_enabled, + _ => false, + }) } pub(crate) fn channel_mixer_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec { @@ -1244,10 +1246,9 @@ pub(crate) fn channel_mixer_properties(node_id: NodeId, context: &mut NodeProper // Monochrome let monochrome_index = 1; let monochrome = bool_widget(document_node, node_id, monochrome_index, "Monochrome", CheckboxInput::default(), true); - let is_monochrome = if let Some(&TaggedValue::Bool(monochrome_choice)) = &document_node.inputs[monochrome_index].as_value() { - monochrome_choice - } else { - false + let is_monochrome = match document_node.inputs[monochrome_index].as_value() { + Some(TaggedValue::Bool(monochrome_choice)) => *monochrome_choice, + _ => false, }; // Output channel choice @@ -1277,11 +1278,12 @@ pub(crate) fn channel_mixer_properties(node_id: NodeId, context: &mut NodeProper output_channel.extend([RadioInput::new(entries).selected_index(Some(choice as u32)).widget_holder()]); }; - let is_output_channel = if let Some(&TaggedValue::RedGreenBlue(choice)) = &document_node.inputs[output_channel_index].as_value() { - choice - } else { - warn!("Channel Mixer node properties panel could not be displayed."); - return vec![]; + let is_output_channel = match &document_node.inputs[output_channel_index].as_value() { + Some(TaggedValue::RedGreenBlue(choice)) => choice, + _ => { + warn!("Channel Mixer node properties panel could not be displayed."); + return vec![]; + } }; // Channel values @@ -1376,11 +1378,12 @@ pub(crate) fn selective_color_properties(node_id: NodeId, context: &mut NodeProp colors.extend([DropdownInput::new(entries).selected_index(Some(choice as u32)).widget_holder()]); } - let colors_choice_index = if let Some(&TaggedValue::SelectiveColorChoice(choice)) = &document_node.inputs[colors_index].as_value() { - choice - } else { - warn!("Selective Color node properties panel could not be displayed."); - return vec![]; + let colors_choice_index = match &document_node.inputs[colors_index].as_value() { + Some(TaggedValue::SelectiveColorChoice(choice)) => choice, + _ => { + warn!("Selective Color node properties panel could not be displayed."); + return vec![]; + } }; // CMYK @@ -1409,7 +1412,7 @@ pub(crate) fn selective_color_properties(node_id: NodeId, context: &mut NodeProp log::warn!("A widget failed to be built because its node's input index is invalid."); return vec![]; }; - if let Some(&TaggedValue::RelativeAbsolute(relative_or_absolute)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::RelativeAbsolute(relative_or_absolute)) = input.as_non_exposed_value() { let entries = vec![ RadioEntryData::new("relative") .label("Relative") @@ -1495,7 +1498,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties log::warn!("A widget failed to be built because its node's input index is invalid."); return vec![]; }; - if let Some(&TaggedValue::Bool(is_individual)) = &input.as_non_exposed_value() { + if let Some(&TaggedValue::Bool(is_individual)) = input.as_non_exposed_value() { // Values let Some(input) = document_node.inputs.get(corner_radius_index) else { log::warn!("A widget failed to be built because its node's input index is invalid."); @@ -2216,7 +2219,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte let mut widgets_first_row = start_widgets(document_node, node_id, fill_index, "Fill", FrontendGraphDataType::General, true); - let (fill, backup_color, backup_gradient) = if let (Some(TaggedValue::Fill(fill)), Some(&TaggedValue::OptionalColor(backup_color)), Some(TaggedValue::Gradient(backup_gradient))) = ( + let (fill, backup_color, backup_gradient) = if let (Some(TaggedValue::Fill(fill)), &Some(&TaggedValue::OptionalColor(backup_color)), Some(TaggedValue::Gradient(backup_gradient))) = ( &document_node.inputs[fill_index].as_value(), &document_node.inputs[backup_color_index].as_value(), &document_node.inputs[backup_gradient_index].as_value(), diff --git a/editor/src/messages/portfolio/document/node_graph/utility_types.rs b/editor/src/messages/portfolio/document/node_graph/utility_types.rs index fc15dd16f..1c380a49b 100644 --- a/editor/src/messages/portfolio/document/node_graph/utility_types.rs +++ b/editor/src/messages/portfolio/document/node_graph/utility_types.rs @@ -1,8 +1,7 @@ -use graph_craft::document::value::TaggedValue; -use graph_craft::document::NodeId; -use graphene_core::Type; - use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector, TypeSource}; +use graph_craft::document::NodeId; +use graph_craft::document::value::TaggedValue; +use graphene_core::Type; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, specta::Type)] pub enum FrontendGraphDataType { diff --git a/editor/src/messages/portfolio/document/overlays/grid_overlays.rs b/editor/src/messages/portfolio/document/overlays/grid_overlays.rs index 2bf84526c..8a685a05d 100644 --- a/editor/src/messages/portfolio/document/overlays/grid_overlays.rs +++ b/editor/src/messages/portfolio/document/overlays/grid_overlays.rs @@ -2,11 +2,9 @@ use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::misc::{GridSnapping, GridType}; use crate::messages::prelude::*; - +use glam::DVec2; use graphene_core::raster::color::Color; use graphene_core::renderer::Quad; - -use glam::DVec2; use graphene_std::vector::style::FillChoice; fn grid_overlay_rectangular(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, spacing: DVec2) { @@ -211,7 +209,7 @@ pub fn grid_overlay(document: &DocumentMessageHandler, overlay_context: &mut Ove pub fn overlay_options(grid: &GridSnapping) -> Vec { let mut widgets = Vec::new(); - fn update_val(grid: &GridSnapping, update: impl Fn(&mut GridSnapping, &I)) -> impl Fn(&I) -> Message { + fn update_val(grid: &GridSnapping, update: F) -> impl Fn(&I) -> Message + use { let grid = grid.clone(); move |input: &I| { let mut grid = grid.clone(); @@ -220,7 +218,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec { } } let update_origin = |grid, update: fn(&mut GridSnapping) -> Option<&mut f64>| { - update_val::(grid, move |grid, val| { + update_val::(grid, move |grid, val| { if let Some(val) = val.value { if let Some(update) = update(grid) { *update = val; @@ -229,7 +227,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec { }) }; let update_color = |grid, update: fn(&mut GridSnapping) -> Option<&mut Color>| { - update_val::(grid, move |grid, color| { + update_val::(grid, move |grid, color| { if let FillChoice::Solid(color) = color.value { if let Some(update_color) = update(grid) { *update_color = color; @@ -238,7 +236,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec { }) }; let update_display = |grid, update: fn(&mut GridSnapping) -> Option<&mut bool>| { - update_val::(grid, move |grid, checkbox| { + update_val::(grid, move |grid, checkbox| { if let Some(update) = update(grid) { *update = checkbox.checked; } diff --git a/editor/src/messages/portfolio/document/overlays/overlays_message.rs b/editor/src/messages/portfolio/document/overlays/overlays_message.rs index 6716e17db..431c08eb5 100644 --- a/editor/src/messages/portfolio/document/overlays/overlays_message.rs +++ b/editor/src/messages/portfolio/document/overlays/overlays_message.rs @@ -1,4 +1,4 @@ -use super::utility_types::{empty_provider, OverlayProvider}; +use super::utility_types::{OverlayProvider, empty_provider}; use crate::messages::prelude::*; #[impl_message(Message, DocumentMessage, Overlays)] diff --git a/editor/src/messages/portfolio/document/overlays/utility_functions.rs b/editor/src/messages/portfolio/document/overlays/utility_functions.rs index a8a5c55e3..b8697cb5d 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_functions.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_functions.rs @@ -2,12 +2,10 @@ use super::utility_types::{DrawHandles, OverlayContext}; use crate::consts::HIDE_HANDLE_DISTANCE; use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState}; use crate::messages::tool::tool_messages::tool_prelude::{DocumentMessageHandler, PreferencesMessageHandler}; - -use graphene_core::vector::ManipulatorPointId; -use graphene_std::vector::{PointId, SegmentId}; - use bezier_rs::{Bezier, BezierHandles}; use glam::{DAffine2, DVec2}; +use graphene_core::vector::ManipulatorPointId; +use graphene_std::vector::{PointId, SegmentId}; use wasm_bindgen::JsCast; pub fn overlay_canvas_element() -> Option { diff --git a/editor/src/messages/portfolio/document/overlays/utility_types.rs b/editor/src/messages/portfolio/document/overlays/utility_types.rs index 3d29f4d15..bac8d6835 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_types.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_types.rs @@ -4,14 +4,12 @@ use crate::consts::{ COMPASS_ROSE_RING_INNER_DIAMETER, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, }; use crate::messages::prelude::Message; - use bezier_rs::{Bezier, Subpath}; -use graphene_core::renderer::Quad; -use graphene_std::vector::{PointId, SegmentId, VectorData}; - use core::borrow::Borrow; use core::f64::consts::{FRAC_PI_2, TAU}; use glam::{DAffine2, DVec2}; +use graphene_core::renderer::Quad; +use graphene_std::vector::{PointId, SegmentId, VectorData}; use std::collections::HashMap; use wasm_bindgen::JsValue; diff --git a/editor/src/messages/portfolio/document/properties_panel/utility_types.rs b/editor/src/messages/portfolio/document/properties_panel/utility_types.rs index e2ffdacdf..ee2553a1e 100644 --- a/editor/src/messages/portfolio/document/properties_panel/utility_types.rs +++ b/editor/src/messages/portfolio/document/properties_panel/utility_types.rs @@ -1,7 +1,6 @@ -use graph_craft::document::NodeId; - use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface; use crate::node_graph_executor::NodeGraphExecutor; +use graph_craft::document::NodeId; pub struct PropertiesPanelMessageHandlerData<'a> { pub network_interface: &'a mut NodeNetworkInterface, diff --git a/editor/src/messages/portfolio/document/utility_types/clipboards.rs b/editor/src/messages/portfolio/document/utility_types/clipboards.rs index 59afc9a14..158372cd4 100644 --- a/editor/src/messages/portfolio/document/utility_types/clipboards.rs +++ b/editor/src/messages/portfolio/document/utility_types/clipboards.rs @@ -1,5 +1,4 @@ use super::network_interface::NodeTemplate; - use graph_craft::document::NodeId; #[repr(u8)] diff --git a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs index dc4bdc7cf..d5bffa4b2 100644 --- a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs +++ b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs @@ -1,14 +1,12 @@ +use super::network_interface::NodeNetworkInterface; use crate::messages::portfolio::document::graph_operation::transform_utils; use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext; - -use super::network_interface::NodeNetworkInterface; +use glam::{DAffine2, DVec2}; use graph_craft::document::NodeId; use graphene_core::renderer::ClickTarget; use graphene_core::renderer::Quad; use graphene_core::transform::Footprint; use graphene_std::vector::{PointId, VectorData}; - -use glam::{DAffine2, DVec2}; use std::collections::{HashMap, HashSet}; use std::num::NonZeroU64; diff --git a/editor/src/messages/portfolio/document/utility_types/error.rs b/editor/src/messages/portfolio/document/utility_types/error.rs index 6858ce14f..41c257e58 100644 --- a/editor/src/messages/portfolio/document/utility_types/error.rs +++ b/editor/src/messages/portfolio/document/utility_types/error.rs @@ -1,5 +1,4 @@ use graphene_core::raster::color::Color; - use thiserror::Error; /// The error type used by the Graphite editor. diff --git a/editor/src/messages/portfolio/document/utility_types/misc.rs b/editor/src/messages/portfolio/document/utility_types/misc.rs index 02f26d51f..c24682fff 100644 --- a/editor/src/messages/portfolio/document/utility_types/misc.rs +++ b/editor/src/messages/portfolio/document/utility_types/misc.rs @@ -1,8 +1,6 @@ use crate::consts::COLOR_OVERLAY_GRAY; - -use graphene_core::raster::Color; - use glam::DVec2; +use graphene_core::raster::Color; use std::fmt; #[repr(transparent)] 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 b8539a17a..ee9d469eb 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -3,21 +3,21 @@ use super::misc::PTZ; use super::nodes::SelectedNodes; use crate::consts::{EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP}; use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext; -use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_document_node_type, DocumentNodeDefinition}; +use crate::messages::portfolio::document::node_graph::document_node_definitions::{DocumentNodeDefinition, resolve_document_node_type}; use crate::messages::portfolio::document::node_graph::utility_types::{Direction, FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput}; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode; - use bezier_rs::Subpath; -use graph_craft::document::{value::TaggedValue, DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork}; -use graph_craft::{concrete, Type}; +use glam::{DAffine2, DVec2, IVec2}; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork}; +use graph_craft::{Type, concrete}; use graphene_std::renderer::{ClickTarget, Quad}; use graphene_std::transform::Footprint; use graphene_std::vector::{PointId, VectorData, VectorModificationType}; -use interpreted_executor::{dynamic_executor::ResolvedDocumentNodeTypes, node_registry::NODE_REGISTRY}; - -use glam::{DAffine2, DVec2, IVec2}; -use serde_json::{json, Value}; +use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypes; +use interpreted_executor::node_registry::NODE_REGISTRY; +use serde_json::{Value, json}; use std::collections::{HashMap, HashSet, VecDeque}; use std::hash::{DefaultHasher, Hash, Hasher}; @@ -656,11 +656,7 @@ impl NodeNetworkInterface { // For example a node input of (Footprint) -> VectorData would not be compatible with () -> VectorData node_io.inputs[iterator_index].clone().nested_type() == input_type || node_io.inputs[iterator_index] == input_type }); - if valid_implementation { - node_io.inputs.get(*input_index).cloned() - } else { - None - } + if valid_implementation { node_io.inputs.get(*input_index).cloned() } else { None } }) .collect::>() } @@ -1339,7 +1335,7 @@ impl NodeNetworkInterface { /// Layers excluding ones that are children of other layers in the list. // TODO: Cache this - pub fn shallowest_unique_layers(&self, network_path: &[NodeId]) -> impl Iterator { + pub fn shallowest_unique_layers(&self, network_path: &[NodeId]) -> impl Iterator + use<> { let mut sorted_layers = if let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) { selected_nodes .selected_layers(self.document_metadata()) @@ -2528,10 +2524,9 @@ impl NodeNetworkInterface { } } - let number_of_outputs = if let DocumentNodeImplementation::Network(network) = &document_node.implementation { - network.exports.len() - } else { - 1 + let number_of_outputs = match &document_node.implementation { + DocumentNodeImplementation::Network(network) => network.exports.len(), + _ => 1, }; // If the node does not have a primary output, shift all ports down a row let mut output_row_count = if !node_metadata.persistent_metadata.has_primary_output { 1 } else { 0 }; @@ -2682,11 +2677,7 @@ impl NodeNetworkInterface { let Some(downstream_node_id) = downstream_node_connectors.iter().find_map(|input_connector| { if let InputConnector::Node { node_id, input_index } = input_connector { let downstream_input_index = if self.is_layer(node_id, network_path) { 1 } else { 0 }; - if *input_index == downstream_input_index { - Some(node_id) - } else { - None - } + if *input_index == downstream_input_index { Some(node_id) } else { None } } else { None } @@ -2933,11 +2924,7 @@ impl NodeNetworkInterface { log::error!("Could not get node_metadata for node {node_id}"); return None; }; - if !node_metadata.persistent_metadata.is_layer() { - Some(*node_id) - } else { - None - } + if !node_metadata.persistent_metadata.is_layer() { Some(*node_id) } else { None } }) .or_else(|| clicked_nodes.into_iter().next()) } @@ -3168,13 +3155,10 @@ impl NodeNetworkInterface { // Only load structure if there is a root node let Some(root_node) = self.root_node(&[]) else { return }; - let Some(first_root_layer) = self.upstream_flow_back_from_nodes(vec![root_node.node_id], &[], FlowType::PrimaryFlow).find_map(|node_id| { - if self.is_layer(&node_id, &[]) { - Some(LayerNodeIdentifier::new(node_id, self, &[])) - } else { - None - } - }) else { + let Some(first_root_layer) = self + .upstream_flow_back_from_nodes(vec![root_node.node_id], &[], FlowType::PrimaryFlow) + .find_map(|node_id| if self.is_layer(&node_id, &[]) { Some(LayerNodeIdentifier::new(node_id, self, &[])) } else { None }) + else { return; }; // Should refer to output node @@ -3329,7 +3313,7 @@ impl NodeNetworkInterface { }; { let mut value = node.inputs.get_mut(1).and_then(|input| input.as_value_mut()); - let Some(TaggedValue::VectorModification(ref mut modification)) = value.as_deref_mut() else { + let Some(TaggedValue::VectorModification(modification)) = value.as_deref_mut() else { panic!("Path node does not have modification input"); }; @@ -3846,10 +3830,9 @@ impl NodeNetworkInterface { } } - let previous_metadata = if let NodeInput::Node { node_id, .. } = &previous_input { - self.position(node_id, network_path).map(|position| (*node_id, position)) - } else { - None + let previous_metadata = match &previous_input { + NodeInput::Node { node_id, .. } => self.position(node_id, network_path).map(|position| (*node_id, position)), + _ => None, }; let Some(network) = self.network_mut(network_path) else { @@ -4701,14 +4684,17 @@ impl NodeNetworkInterface { log::error!("Could not get node_metadata for node {node_id}"); return; }; - if let NodeTypePersistentMetadata::Layer(layer_metadata) = &mut node_metadata.persistent_metadata.node_type_metadata { - if layer_metadata.position == LayerPosition::Stack(y_offset) { - return; + match &mut node_metadata.persistent_metadata.node_type_metadata { + NodeTypePersistentMetadata::Layer(layer_metadata) => { + if layer_metadata.position == LayerPosition::Stack(y_offset) { + return; + } + layer_metadata.position = LayerPosition::Stack(y_offset); + self.transaction_modified(); + } + _ => { + log::error!("Could not set stack position for non layer node {node_id}"); } - layer_metadata.position = LayerPosition::Stack(y_offset); - self.transaction_modified(); - } else { - log::error!("Could not set stack position for non layer node {node_id}"); } } @@ -5128,16 +5114,12 @@ impl NodeNetworkInterface { stack_dependents_with_position.sort_unstable_by(|a, b| { a.1.signum().cmp(&b.1.signum()).then_with(|| { // If the node has a positive offset, then it is shifted up, so shift the top nodes first - if a.1.signum() == 1 { - a.2.cmp(&b.2) - } else { - b.2.cmp(&a.2) - } + if a.1.signum() == 1 { a.2.cmp(&b.2) } else { b.2.cmp(&a.2) } }) }); // Try shift every node that is offset from its original position - for (node_id, mut offset, _) in stack_dependents_with_position.iter() { + for &(ref node_id, mut offset, _) in stack_dependents_with_position.iter() { while offset != 0 { if self.check_collision_with_stack_dependents(node_id, -offset.signum(), network_path).is_empty() { self.vertical_shift_with_push(node_id, -offset.signum(), &mut HashSet::new(), network_path); @@ -5302,6 +5284,7 @@ impl NodeNetworkInterface { self.transaction_modified(); } else if let LayerPosition::Stack(y_offset) = &mut layer_metadata.position { let shifted_y_offset = *y_offset as i32 + shift.y; + // A layer can only be shifted to a positive y_offset if shifted_y_offset < 0 { log::error!( @@ -5312,6 +5295,7 @@ impl NodeNetworkInterface { if shift.x != 0 { log::error!("Stack layer {node_id} cannot be shifted horizontally."); } + let new_y_offset = shifted_y_offset.max(0) as u32; if *y_offset == new_y_offset { return; diff --git a/editor/src/messages/portfolio/document/utility_types/nodes.rs b/editor/src/messages/portfolio/document/utility_types/nodes.rs index 7f579679f..2cac92257 100644 --- a/editor/src/messages/portfolio/document/utility_types/nodes.rs +++ b/editor/src/messages/portfolio/document/utility_types/nodes.rs @@ -1,8 +1,6 @@ use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier}; use super::network_interface::NodeNetworkInterface; - use graph_craft::document::{NodeId, NodeNetwork}; - use serde::ser::SerializeStruct; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, specta::Type)] diff --git a/editor/src/messages/portfolio/document/utility_types/transformation.rs b/editor/src/messages/portfolio/document/utility_types/transformation.rs index 888567c9b..9058f18ce 100644 --- a/editor/src/messages/portfolio/document/utility_types/transformation.rs +++ b/editor/src/messages/portfolio/document/utility_types/transformation.rs @@ -7,13 +7,11 @@ use crate::messages::prelude::*; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::shape_editor::ShapeState; use crate::messages::tool::utility_types::ToolType; - +use glam::{DAffine2, DMat2, DVec2}; use graphene_core::renderer::Quad; use graphene_core::vector::ManipulatorPointId; use graphene_core::vector::VectorModificationType; use graphene_std::vector::{HandleId, PointId}; - -use glam::{DAffine2, DMat2, DVec2}; use std::collections::{HashMap, VecDeque}; use std::f64::consts::PI; @@ -136,11 +134,7 @@ impl Axis { return (target, false); } - if local { - (Axis::Both, false) - } else { - (self, true) - } + if local { (Axis::Both, false) } else { (self, true) } } } @@ -167,11 +161,7 @@ impl Translation { } }; let displacement = transform.inverse().transform_vector2(displacement); - if increment_mode { - displacement.round() - } else { - displacement - } + if increment_mode { displacement.round() } else { displacement } } #[must_use] @@ -259,11 +249,7 @@ impl Default for Scale { impl Scale { pub fn to_f64(self, increment: bool) -> f64 { let factor = if let Some(value) = self.typed_factor { value } else { self.dragged_factor }; - if increment { - (factor / SCALE_INCREMENT).round() * SCALE_INCREMENT - } else { - factor - } + if increment { (factor / SCALE_INCREMENT).round() * SCALE_INCREMENT } else { factor } } pub fn to_dvec(self, increment_mode: bool) -> DVec2 { diff --git a/editor/src/messages/portfolio/menu_bar/menu_bar_message_handler.rs b/editor/src/messages/portfolio/menu_bar/menu_bar_message_handler.rs index 1cb0a9f95..a8fb69e57 100644 --- a/editor/src/messages/portfolio/menu_bar/menu_bar_message_handler.rs +++ b/editor/src/messages/portfolio/menu_bar/menu_bar_message_handler.rs @@ -1,11 +1,10 @@ -use graphene_std::vector::misc::BooleanOperation; - use crate::messages::debug::utility_types::MessageLoggingVerbosity; use crate::messages::input_mapper::utility_types::macros::action_keys; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::utility_types::clipboards::Clipboard; use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GroupFolderType}; use crate::messages::prelude::*; +use graphene_std::vector::misc::BooleanOperation; pub struct MenuBarMessageData { pub has_active_document: bool, diff --git a/editor/src/messages/portfolio/portfolio_message.rs b/editor/src/messages/portfolio/portfolio_message.rs index f60f98d7c..4bdf98089 100644 --- a/editor/src/messages/portfolio/portfolio_message.rs +++ b/editor/src/messages/portfolio/portfolio_message.rs @@ -3,10 +3,9 @@ use super::utility_types::PanelType; use crate::messages::frontend::utility_types::{ExportBounds, FileType}; use crate::messages::portfolio::document::utility_types::clipboards::Clipboard; use crate::messages::prelude::*; - +use graphene_core::Color; use graphene_core::raster::Image; use graphene_core::text::Font; -use graphene_core::Color; #[impl_message(Message, Portfolio)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index fbe31e539..5dec445b3 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -7,15 +7,14 @@ use crate::messages::debug::utility_types::MessageLoggingVerbosity; use crate::messages::dialog::simple_dialogs; use crate::messages::frontend::utility_types::FrontendDocumentDetails; use crate::messages::layout::utility_types::widget_prelude::*; +use crate::messages::portfolio::document::DocumentMessageData; use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type; use crate::messages::portfolio::document::utility_types::clipboards::{Clipboard, CopyBufferEntry, INTERNAL_CLIPBOARD_COUNT}; use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes; -use crate::messages::portfolio::document::DocumentMessageData; use crate::messages::preferences::SelectionMode; use crate::messages::prelude::*; use crate::messages::tool::utility_types::{HintData, HintGroup, ToolType}; use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor}; - use bezier_rs::Subpath; use glam::IVec2; use graph_craft::document::value::TaggedValue; @@ -24,7 +23,6 @@ use graphene_core::text::{Font, TypesettingConfig}; use graphene_std::vector::style::{Fill, FillType, Gradient}; use graphene_std::vector::{VectorData, VectorDataTable}; use interpreted_executor::dynamic_executor::IntrospectError; - use std::sync::Arc; use std::vec; diff --git a/editor/src/messages/preferences/preferences_message_handler.rs b/editor/src/messages/preferences/preferences_message_handler.rs index 2b51aa281..a4ddb3ecc 100644 --- a/editor/src/messages/preferences/preferences_message_handler.rs +++ b/editor/src/messages/preferences/preferences_message_handler.rs @@ -2,7 +2,6 @@ use crate::messages::input_mapper::key_mapping::MappingVariant; use crate::messages::portfolio::document::node_graph::utility_types::GraphWireStyle; use crate::messages::preferences::SelectionMode; use crate::messages::prelude::*; - use graph_craft::wasm_application_io::EditorPreferences; #[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, specta::Type)] diff --git a/editor/src/messages/prelude.rs b/editor/src/messages/prelude.rs index 894ef6791..9218e06df 100644 --- a/editor/src/messages/prelude.rs +++ b/editor/src/messages/prelude.rs @@ -51,9 +51,7 @@ pub use crate::messages::tool::tool_messages::text_tool::{TextToolMessage, TextT // Helper pub use crate::messages::globals::global_variables::*; pub use crate::messages::portfolio::document::utility_types::misc::DocumentId; - pub use graphite_proc_macros::*; - pub use std::collections::{HashMap, HashSet, VecDeque}; pub trait Responses { diff --git a/editor/src/messages/tool/common_functionality/color_selector.rs b/editor/src/messages/tool/common_functionality/color_selector.rs index 2b73b4f1f..e1ec64a1d 100644 --- a/editor/src/messages/tool/common_functionality/color_selector.rs +++ b/editor/src/messages/tool/common_functionality/color_selector.rs @@ -1,7 +1,6 @@ use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::prelude::*; - use graphene_core::Color; use graphene_std::vector::style::FillChoice; diff --git a/editor/src/messages/tool/common_functionality/compass_rose.rs b/editor/src/messages/tool/common_functionality/compass_rose.rs index 56692074d..fe9a052e7 100644 --- a/editor/src/messages/tool/common_functionality/compass_rose.rs +++ b/editor/src/messages/tool/common_functionality/compass_rose.rs @@ -1,7 +1,6 @@ use crate::consts::{COMPASS_ROSE_ARROW_CLICK_TARGET_ANGLE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER}; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::prelude::DocumentMessageHandler; - use glam::{DAffine2, DVec2}; use std::f64::consts::FRAC_PI_2; diff --git a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs index 87d30c12e..0b55ed94b 100644 --- a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs +++ b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs @@ -3,18 +3,17 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate}; use crate::messages::prelude::*; - use bezier_rs::Subpath; +use glam::DVec2; use graph_craft::concrete; -use graph_craft::document::{value::TaggedValue, NodeId, NodeInput}; -use graphene_core::raster::image::ImageFrameTable; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{NodeId, NodeInput}; +use graphene_core::Color; use graphene_core::raster::BlendMode; +use graphene_core::raster::image::ImageFrameTable; use graphene_core::text::{Font, TypesettingConfig}; use graphene_core::vector::style::Gradient; -use graphene_core::Color; use graphene_std::vector::{ManipulatorPointId, PointId, SegmentId, VectorModificationType}; - -use glam::DVec2; use std::collections::VecDeque; /// Returns the ID of the first Spline node in the horizontal flow which is not followed by a `Path` node, or `None` if none exists. @@ -385,7 +384,7 @@ impl<'a> NodeGraphLayer<'a> { } /// Return an iterator up the horizontal flow of the layer - pub fn horizontal_layer_flow(&self) -> impl Iterator + 'a { + pub fn horizontal_layer_flow(&self) -> impl Iterator + use<'a> { self.network_interface.upstream_flow_back_from_nodes(vec![self.layer_node], &[], FlowType::HorizontalFlow) } diff --git a/editor/src/messages/tool/common_functionality/pivot.rs b/editor/src/messages/tool/common_functionality/pivot.rs index d4b95e4cf..ac68bad62 100644 --- a/editor/src/messages/tool/common_functionality/pivot.rs +++ b/editor/src/messages/tool/common_functionality/pivot.rs @@ -6,7 +6,6 @@ use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::prelude::*; - use glam::{DAffine2, DVec2}; use std::collections::VecDeque; diff --git a/editor/src/messages/tool/common_functionality/resize.rs b/editor/src/messages/tool/common_functionality/resize.rs index 1a684727a..b11aad741 100644 --- a/editor/src/messages/tool/common_functionality/resize.rs +++ b/editor/src/messages/tool/common_functionality/resize.rs @@ -1,7 +1,8 @@ +use crate::messages::input_mapper::utility_types::input_keyboard::Key; +use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::prelude::*; use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration}; -use crate::messages::{input_mapper::utility_types::input_keyboard::Key, portfolio::document::graph_operation::utility_types::TransformIn}; use glam::{DAffine2, DVec2, Vec2Swizzles}; #[derive(Clone, Debug, Default)] diff --git a/editor/src/messages/tool/common_functionality/shape_editor.rs b/editor/src/messages/tool/common_functionality/shape_editor.rs index dc6646816..561b9601e 100644 --- a/editor/src/messages/tool/common_functionality/shape_editor.rs +++ b/editor/src/messages/tool/common_functionality/shape_editor.rs @@ -6,12 +6,10 @@ use crate::messages::portfolio::document::utility_types::network_interface::Node use crate::messages::prelude::*; use crate::messages::tool::common_functionality::snapping::SnapTypeConfiguration; use crate::messages::tool::tool_messages::path_tool::PointSelectState; - use bezier_rs::{Bezier, BezierHandles, Subpath, TValue}; +use glam::{DAffine2, DVec2}; use graphene_core::transform::Transform; use graphene_core::vector::{ManipulatorPointId, PointId, VectorData, VectorModificationType}; - -use glam::{DAffine2, DVec2}; use graphene_std::vector::{HandleId, SegmentId}; #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -586,7 +584,7 @@ impl ShapeState { .flat_map(|(data, selection_state)| { selection_state.selected_points.iter().filter_map(move |&point| { let Some(data) = &data else { return None }; - let Some(_) = point.get_handle_pair(&data) else { return None }; // ignores the endpoints. + let _ = point.get_handle_pair(data)?; // ignores the endpoints. Some(data.colinear(point)) }) }); @@ -1289,10 +1287,13 @@ impl ShapeState { for point in self.selected_points().filter(|point| point.as_handle().is_some()) { let anchor = point.get_anchor(&vector_data); - if let Some(handles) = point.get_handle_pair(&vector_data) { - points_to_select.push((layer, anchor, Some(handles[1].to_manipulator_point()))); - } else { - points_to_select.push((layer, anchor, None)); + match point.get_handle_pair(&vector_data) { + Some(handles) => { + points_to_select.push((layer, anchor, Some(handles[1].to_manipulator_point()))); + } + _ => { + points_to_select.push((layer, anchor, None)); + } } } } diff --git a/editor/src/messages/tool/common_functionality/snapping.rs b/editor/src/messages/tool/common_functionality/snapping.rs index 28c1a6673..4220ad73e 100644 --- a/editor/src/messages/tool/common_functionality/snapping.rs +++ b/editor/src/messages/tool/common_functionality/snapping.rs @@ -3,21 +3,23 @@ mod distribution_snapper; mod grid_snapper; mod layer_snapper; mod snap_results; -pub use {alignment_snapper::*, distribution_snapper::*, grid_snapper::*, layer_snapper::*, snap_results::*}; use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_LABEL_BACKGROUND, COLOR_OVERLAY_WHITE}; use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, Pivot}; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::misc::{GridSnapTarget, PathSnapTarget, SnapTarget}; use crate::messages::prelude::*; - +pub use alignment_snapper::*; use bezier_rs::TValue; +pub use distribution_snapper::*; +use glam::{DAffine2, DVec2}; use graphene_core::renderer::Quad; use graphene_core::vector::PointId; use graphene_std::renderer::Rect; - -use glam::{DAffine2, DVec2}; use graphene_std::vector::NoHashBuilder; +pub use grid_snapper::*; +pub use layer_snapper::*; +pub use snap_results::*; use std::cmp::Ordering; /// Configuration for the relevant snap type diff --git a/editor/src/messages/tool/common_functionality/snapping/alignment_snapper.rs b/editor/src/messages/tool/common_functionality/snapping/alignment_snapper.rs index 32d56318e..7fa16fe4b 100644 --- a/editor/src/messages/tool/common_functionality/snapping/alignment_snapper.rs +++ b/editor/src/messages/tool/common_functionality/snapping/alignment_snapper.rs @@ -1,9 +1,7 @@ use super::*; use crate::messages::portfolio::document::utility_types::misc::*; - -use graphene_core::renderer::Quad; - use glam::{DAffine2, DVec2}; +use graphene_core::renderer::Quad; #[derive(Clone, Debug, Default)] pub struct AlignmentSnapper { diff --git a/editor/src/messages/tool/common_functionality/snapping/distribution_snapper.rs b/editor/src/messages/tool/common_functionality/snapping/distribution_snapper.rs index 17a670d23..9207e958e 100644 --- a/editor/src/messages/tool/common_functionality/snapping/distribution_snapper.rs +++ b/editor/src/messages/tool/common_functionality/snapping/distribution_snapper.rs @@ -2,10 +2,8 @@ use super::*; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::misc::*; use crate::messages::prelude::*; - -use graphene_core::renderer::Quad; - use glam::DVec2; +use graphene_core::renderer::Quad; #[derive(Clone, Debug, Default)] pub struct DistributionSnapper { diff --git a/editor/src/messages/tool/common_functionality/snapping/grid_snapper.rs b/editor/src/messages/tool/common_functionality/snapping/grid_snapper.rs index 9acae9095..00751884f 100644 --- a/editor/src/messages/tool/common_functionality/snapping/grid_snapper.rs +++ b/editor/src/messages/tool/common_functionality/snapping/grid_snapper.rs @@ -1,7 +1,5 @@ use super::*; - use crate::messages::portfolio::document::utility_types::misc::{GridSnapTarget, GridSnapping, GridType, SnapTarget}; - use glam::DVec2; use graphene_core::renderer::Quad; diff --git a/editor/src/messages/tool/common_functionality/snapping/layer_snapper.rs b/editor/src/messages/tool/common_functionality/snapping/layer_snapper.rs index f289d6aa5..091a26aec 100644 --- a/editor/src/messages/tool/common_functionality/snapping/layer_snapper.rs +++ b/editor/src/messages/tool/common_functionality/snapping/layer_snapper.rs @@ -3,13 +3,11 @@ use crate::consts::HIDE_HANDLE_DISTANCE; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::misc::*; use crate::messages::prelude::*; - use bezier_rs::{Bezier, Identifier, Subpath, TValue}; +use glam::{DAffine2, DVec2}; use graphene_core::renderer::Quad; use graphene_core::vector::PointId; -use glam::{DAffine2, DVec2}; - #[derive(Clone, Debug, Default)] pub struct LayerSnapper { points_to_snap: Vec, diff --git a/editor/src/messages/tool/common_functionality/snapping/snap_results.rs b/editor/src/messages/tool/common_functionality/snapping/snap_results.rs index 34bbc039b..16d6a65ce 100644 --- a/editor/src/messages/tool/common_functionality/snapping/snap_results.rs +++ b/editor/src/messages/tool/common_functionality/snapping/snap_results.rs @@ -1,5 +1,4 @@ -use std::collections::VecDeque; - +use super::DistributionMatch; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::misc::{DistributionSnapTarget, SnapSource, SnapTarget}; use crate::messages::tool::common_functionality::snapping::SnapCandidatePoint; @@ -8,8 +7,7 @@ use glam::DVec2; use graphene_core::renderer::Quad; use graphene_core::vector::PointId; use graphene_std::renderer::Rect; - -use super::DistributionMatch; +use std::collections::VecDeque; #[derive(Clone, Debug, Default)] pub struct SnapResults { diff --git a/editor/src/messages/tool/common_functionality/transformation_cage.rs b/editor/src/messages/tool/common_functionality/transformation_cage.rs index f01dc2bd7..7f049bb76 100644 --- a/editor/src/messages/tool/common_functionality/transformation_cage.rs +++ b/editor/src/messages/tool/common_functionality/transformation_cage.rs @@ -1,3 +1,4 @@ +use super::snapping::{self, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnappedPoint}; use crate::consts::{ BOUNDS_ROTATE_THRESHOLD, BOUNDS_SELECT_THRESHOLD, COLOR_OVERLAY_WHITE, MAXIMUM_ALT_SCALE_FACTOR, MIN_LENGTH_FOR_CORNERS_VISIBILITY, MIN_LENGTH_FOR_EDGE_RESIZE_PRIORITY_OVER_CORNERS, MIN_LENGTH_FOR_MIDPOINT_VISIBILITY, MIN_LENGTH_FOR_RESIZE_TO_INCLUDE_INTERIOR, MIN_LENGTH_FOR_SKEW_TRIANGLE_VISIBILITY, RESIZE_HANDLE_SIZE, SELECTION_DRAG_ANGLE, SKEW_TRIANGLE_OFFSET, @@ -8,14 +9,10 @@ use crate::messages::portfolio::document::overlays::utility_types::OverlayContex use crate::messages::portfolio::document::utility_types::transformation::OriginalTransforms; use crate::messages::prelude::*; use crate::messages::tool::common_functionality::snapping::SnapTypeConfiguration; - +use glam::{DAffine2, DMat2, DVec2}; use graphene_core::renderer::Quad; use graphene_std::renderer::Rect; -use glam::{DAffine2, DMat2, DVec2}; - -use super::snapping::{self, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnappedPoint}; - /// (top, bottom, left, right) pub type EdgeBool = (bool, bool, bool, bool); diff --git a/editor/src/messages/tool/common_functionality/utility_functions.rs b/editor/src/messages/tool/common_functionality/utility_functions.rs index e3332a8ff..80123347f 100644 --- a/editor/src/messages/tool/common_functionality/utility_functions.rs +++ b/editor/src/messages/tool/common_functionality/utility_functions.rs @@ -1,12 +1,10 @@ use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::prelude::*; use crate::messages::tool::common_functionality::graph_modification_utils::get_text; - -use graphene_core::renderer::Quad; -use graphene_core::text::{load_face, FontCache}; -use graphene_std::vector::PointId; - use glam::DVec2; +use graphene_core::renderer::Quad; +use graphene_core::text::{FontCache, load_face}; +use graphene_std::vector::PointId; /// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable. pub fn should_extend( diff --git a/editor/src/messages/tool/tool_message.rs b/editor/src/messages/tool/tool_message.rs index f812f63a2..a5c138242 100644 --- a/editor/src/messages/tool/tool_message.rs +++ b/editor/src/messages/tool/tool_message.rs @@ -1,7 +1,6 @@ use super::utility_types::ToolType; use crate::messages::preferences::SelectionMode; use crate::messages::prelude::*; - use graphene_core::raster::color::Color; #[impl_message(Message, Tool)] diff --git a/editor/src/messages/tool/tool_message_handler.rs b/editor/src/messages/tool/tool_message_handler.rs index 4d4d9d374..5cb258461 100644 --- a/editor/src/messages/tool/tool_message_handler.rs +++ b/editor/src/messages/tool/tool_message_handler.rs @@ -1,5 +1,5 @@ use super::common_functionality::shape_editor::ShapeState; -use super::utility_types::{tool_message_to_tool_type, ToolActionHandlerData, ToolFsmState}; +use super::utility_types::{ToolActionHandlerData, ToolFsmState, tool_message_to_tool_type}; use crate::application::generate_uuid; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::overlays::utility_types::OverlayProvider; @@ -7,7 +7,6 @@ use crate::messages::portfolio::utility_types::PersistentData; use crate::messages::prelude::*; use crate::messages::tool::utility_types::ToolType; use crate::node_graph_executor::NodeGraphExecutor; - use graphene_core::raster::color::Color; const ARTBOARD_OVERLAY_PROVIDER: OverlayProvider = |context| DocumentMessage::DrawArtboardOverlays(context).into(); diff --git a/editor/src/messages/tool/tool_messages/artboard_tool.rs b/editor/src/messages/tool/tool_messages/artboard_tool.rs index e7278167a..947185a7b 100644 --- a/editor/src/messages/tool/tool_messages/artboard_tool.rs +++ b/editor/src/messages/tool/tool_messages/artboard_tool.rs @@ -9,7 +9,6 @@ use crate::messages::tool::common_functionality::snapping::SnapCandidatePoint; use crate::messages::tool::common_functionality::snapping::SnapData; use crate::messages::tool::common_functionality::snapping::SnapManager; use crate::messages::tool::common_functionality::transformation_cage::*; - use graph_craft::document::NodeId; use graphene_core::renderer::Quad; @@ -277,7 +276,7 @@ impl Fsm for ArtboardToolFsmState { ArtboardToolFsmState::ResizingBounds } (ArtboardToolFsmState::Dragging, ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }) => { - if let Some(ref mut bounds) = &mut tool_data.bounding_box_manager { + if let Some(bounds) = &mut tool_data.bounding_box_manager { let axis_align = input.keyboard.get(constrain_axis_or_aspect as usize); let ignore = tool_data.selected_artboard.map_or(Vec::new(), |layer| vec![layer]); diff --git a/editor/src/messages/tool/tool_messages/brush_tool.rs b/editor/src/messages/tool/tool_messages/brush_tool.rs index aba64776e..ab6be8abf 100644 --- a/editor/src/messages/tool/tool_messages/brush_tool.rs +++ b/editor/src/messages/tool/tool_messages/brush_tool.rs @@ -5,12 +5,11 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions: use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::FlowType; use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType}; - -use graph_craft::document::value::TaggedValue; use graph_craft::document::NodeId; +use graph_craft::document::value::TaggedValue; +use graphene_core::Color; use graphene_core::raster::BlendMode; use graphene_core::vector::brush_stroke::{BrushInputSample, BrushStroke, BrushStyle}; -use graphene_core::Color; const BRUSH_MAX_SIZE: f64 = 5000.; diff --git a/editor/src/messages/tool/tool_messages/ellipse_tool.rs b/editor/src/messages/tool/tool_messages/ellipse_tool.rs index a91f7f72c..4a835b561 100644 --- a/editor/src/messages/tool/tool_messages/ellipse_tool.rs +++ b/editor/src/messages/tool/tool_messages/ellipse_tool.rs @@ -9,8 +9,8 @@ use crate::messages::tool::common_functionality::color_selector::{ToolColorOptio use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::resize::Resize; use crate::messages::tool::common_functionality::snapping::SnapData; - -use graph_craft::document::{value::TaggedValue, NodeId, NodeInput}; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{NodeId, NodeInput}; use graphene_core::Color; #[derive(Default)] diff --git a/editor/src/messages/tool/tool_messages/freehand_tool.rs b/editor/src/messages/tool/tool_messages/freehand_tool.rs index 5413210d6..4a67fb3e4 100644 --- a/editor/src/messages/tool/tool_messages/freehand_tool.rs +++ b/editor/src/messages/tool/tool_messages/freehand_tool.rs @@ -7,13 +7,11 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType}; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::utility_functions::should_extend; - -use graph_craft::document::NodeId; -use graphene_core::vector::VectorModificationType; -use graphene_core::Color; -use graphene_std::vector::{PointId, SegmentId}; - use glam::DVec2; +use graph_craft::document::NodeId; +use graphene_core::Color; +use graphene_core::vector::VectorModificationType; +use graphene_std::vector::{PointId, SegmentId}; #[derive(Default)] pub struct FreehandTool { diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index bc3238e3e..164b06ae6 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -5,7 +5,6 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::tool::common_functionality::auto_panning::AutoPanning; use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient; use crate::messages::tool::common_functionality::snapping::SnapManager; - use graphene_core::vector::style::{Fill, Gradient, GradientType}; #[derive(Default)] diff --git a/editor/src/messages/tool/tool_messages/line_tool.rs b/editor/src/messages/tool/tool_messages/line_tool.rs index 02f11931d..1d22a0fb0 100644 --- a/editor/src/messages/tool/tool_messages/line_tool.rs +++ b/editor/src/messages/tool/tool_messages/line_tool.rs @@ -2,13 +2,14 @@ use super::tool_prelude::*; use crate::consts::{BOUNDS_SELECT_THRESHOLD, DEFAULT_STROKE_WIDTH, LINE_ROTATE_SNAP_ANGLE}; use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; -use crate::messages::portfolio::document::utility_types::{document_metadata::LayerNodeIdentifier, network_interface::InputConnector}; +use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; +use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::tool::common_functionality::auto_panning::AutoPanning; use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType}; use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer}; use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration}; - -use graph_craft::document::{value::TaggedValue, NodeId, NodeInput}; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{NodeId, NodeInput}; use graphene_core::Color; #[derive(Default)] diff --git a/editor/src/messages/tool/tool_messages/mod.rs b/editor/src/messages/tool/tool_messages/mod.rs index faa5840c5..94889560f 100644 --- a/editor/src/messages/tool/tool_messages/mod.rs +++ b/editor/src/messages/tool/tool_messages/mod.rs @@ -23,6 +23,5 @@ pub mod tool_prelude { pub use crate::messages::prelude::*; pub use crate::messages::tool::utility_types::{EventToMessageMap, Fsm, ToolActionHandlerData, ToolMetadata, ToolTransition, ToolType}; pub use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo}; - pub use glam::{DAffine2, DVec2}; } diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs index e41d05f61..3d903ddb7 100644 --- a/editor/src/messages/tool/tool_messages/path_tool.rs +++ b/editor/src/messages/tool/tool_messages/path_tool.rs @@ -13,11 +13,9 @@ use crate::messages::tool::common_functionality::shape_editor::{ ClosestSegment, ManipulatorAngle, OpposingHandleLengths, SelectedPointsInfo, SelectionChange, SelectionShape, SelectionShapeType, ShapeState, }; use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager}; - use graphene_core::renderer::Quad; use graphene_core::vector::{ManipulatorPointId, PointId}; use graphene_std::vector::{NoHashBuilder, SegmentId}; - use std::vec; #[derive(Default)] diff --git a/editor/src/messages/tool/tool_messages/pen_tool.rs b/editor/src/messages/tool/tool_messages/pen_tool.rs index 5e39e8122..2c8c7b386 100644 --- a/editor/src/messages/tool/tool_messages/pen_tool.rs +++ b/editor/src/messages/tool/tool_messages/pen_tool.rs @@ -9,11 +9,10 @@ use crate::messages::tool::common_functionality::color_selector::{ToolColorOptio use crate::messages::tool::common_functionality::graph_modification_utils::{self, merge_layers}; use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration}; use crate::messages::tool::common_functionality::utility_functions::{closest_point, should_extend}; - use bezier_rs::{Bezier, BezierHandles}; use graph_craft::document::NodeId; -use graphene_core::vector::{PointId, VectorModificationType}; use graphene_core::Color; +use graphene_core::vector::{PointId, VectorModificationType}; use graphene_std::vector::{HandleId, ManipulatorPointId, NoHashBuilder, SegmentId, VectorData}; #[derive(Default)] @@ -461,6 +460,7 @@ impl PenToolData { Some(if close_subpath { PenToolFsmState::Ready } else { PenToolFsmState::PlacingAnchor }) } + #[allow(clippy::too_many_arguments)] /// Calculates snap position delta while moving anchor and its handles. fn space_anchor_handle_snap( &mut self, @@ -493,7 +493,7 @@ impl PenToolData { // Otherwise use either primary or end handle based on is_start flag if is_start { let primary_handle_id = ManipulatorPointId::PrimaryHandle(self.end_point_segment.unwrap()); - match primary_handle_id.get_position(&vector_data) { + match primary_handle_id.get_position(vector_data) { Some(primary_handle) => { let handle_offset = transform.transform_point2(primary_handle - self.next_handle_start); let handle_snap = SnapCandidatePoint::handle(document_pos + handle_offset); @@ -502,7 +502,7 @@ impl PenToolData { None => None, } } else { - let end_handle = self.end_point_segment.map(|handle| ManipulatorPointId::EndHandle(handle).get_position(&vector_data)).flatten(); + let end_handle = self.end_point_segment.and_then(|handle| ManipulatorPointId::EndHandle(handle).get_position(vector_data)); match end_handle { Some(end_handle) => { let handle_offset = transform.transform_point2(end_handle - self.next_handle_start); @@ -690,10 +690,10 @@ impl PenToolData { return Some((handle - self.next_point).length()); } - return self.handle_end.map(|handle| (handle - self.next_point).length()).or_else(|| { + self.handle_end.map(|handle| (handle - self.next_point).length()).or_else(|| { self.end_point_segment .and_then(|segment| Some((ManipulatorPointId::EndHandle(segment).get_position(vector_data)? - self.next_point).length())) - }); + }) } fn adjust_equidistant_handle(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector_data: &VectorData, is_start: bool) { @@ -755,12 +755,10 @@ impl PenToolData { if let Some(handle) = self.handle_end.as_mut() { *handle = new_position; - return; } else { let Some(segment) = self.end_point_segment else { return }; let modification_type = VectorModificationType::SetEndHandle { segment, relative_position }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); - return; } } @@ -1455,7 +1453,7 @@ impl Fsm for PenToolFsmState { } let state = tool_data - .drag_handle(snap_data, transform, input.mouse.position, responses, layer, &input) + .drag_handle(snap_data, transform, input.mouse.position, responses, layer, input) .unwrap_or(PenToolFsmState::Ready); // Auto-panning diff --git a/editor/src/messages/tool/tool_messages/polygon_tool.rs b/editor/src/messages/tool/tool_messages/polygon_tool.rs index 287a53e29..12b0299bb 100644 --- a/editor/src/messages/tool/tool_messages/polygon_tool.rs +++ b/editor/src/messages/tool/tool_messages/polygon_tool.rs @@ -10,8 +10,8 @@ use crate::messages::tool::common_functionality::color_selector::{ToolColorOptio use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer}; use crate::messages::tool::common_functionality::resize::Resize; use crate::messages::tool::common_functionality::snapping::SnapData; - -use graph_craft::document::{value::TaggedValue, NodeId, NodeInput}; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{NodeId, NodeInput}; use graphene_core::Color; #[derive(Default)] diff --git a/editor/src/messages/tool/tool_messages/rectangle_tool.rs b/editor/src/messages/tool/tool_messages/rectangle_tool.rs index cd146e882..834afb83a 100644 --- a/editor/src/messages/tool/tool_messages/rectangle_tool.rs +++ b/editor/src/messages/tool/tool_messages/rectangle_tool.rs @@ -1,14 +1,16 @@ use super::tool_prelude::*; use crate::consts::DEFAULT_STROKE_WIDTH; +use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type; -use crate::messages::portfolio::document::{graph_operation::utility_types::TransformIn, overlays::utility_types::OverlayContext, utility_types::network_interface::InputConnector}; +use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; +use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::tool::common_functionality::auto_panning::AutoPanning; use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType}; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::resize::Resize; use crate::messages::tool::common_functionality::snapping::SnapData; - -use graph_craft::document::{value::TaggedValue, NodeId, NodeInput}; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{NodeId, NodeInput}; use graphene_core::Color; #[derive(Default)] diff --git a/editor/src/messages/tool/tool_messages/select_tool.rs b/editor/src/messages/tool/tool_messages/select_tool.rs index 8f58c57a3..9d5de9ee4 100644 --- a/editor/src/messages/tool/tool_messages/select_tool.rs +++ b/editor/src/messages/tool/tool_messages/select_tool.rs @@ -14,22 +14,21 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Flo use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes; use crate::messages::portfolio::document::utility_types::transformation::Selected; use crate::messages::preferences::SelectionMode; +use crate::messages::tool::common_functionality::auto_panning::AutoPanning; use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose}; use crate::messages::tool::common_functionality::graph_modification_utils::is_layer_fed_by_node_of_name; +use crate::messages::tool::common_functionality::measure; use crate::messages::tool::common_functionality::pivot::Pivot; use crate::messages::tool::common_functionality::shape_editor::SelectionShapeType; use crate::messages::tool::common_functionality::snapping::{self, SnapCandidatePoint, SnapData, SnapManager}; use crate::messages::tool::common_functionality::transformation_cage::*; use crate::messages::tool::common_functionality::utility_functions::text_bounding_box; -use crate::messages::tool::common_functionality::{auto_panning::AutoPanning, measure}; - use bezier_rs::Subpath; +use glam::DMat2; use graph_craft::document::NodeId; use graphene_core::renderer::Quad; use graphene_std::renderer::Rect; use graphene_std::vector::misc::BooleanOperation; - -use glam::DMat2; use std::fmt; #[derive(Default)] @@ -137,7 +136,7 @@ impl SelectTool { .widget_holder() } - fn alignment_widgets(&self, disabled: bool) -> impl Iterator { + fn alignment_widgets(&self, disabled: bool) -> impl Iterator + use<> { [AlignAxis::X, AlignAxis::Y] .into_iter() .flat_map(|axis| [(axis, AlignAggregate::Min), (axis, AlignAggregate::Center), (axis, AlignAggregate::Max)]) @@ -158,7 +157,7 @@ impl SelectTool { }) } - fn flip_widgets(&self, disabled: bool) -> impl Iterator { + fn flip_widgets(&self, disabled: bool) -> impl Iterator + use<> { [(FlipAxis::X, "Horizontal"), (FlipAxis::Y, "Vertical")].into_iter().map(move |(flip_axis, name)| { IconButton::new("Flip".to_string() + name, 24) .tooltip("Flip ".to_string() + name) @@ -168,7 +167,7 @@ impl SelectTool { }) } - fn turn_widgets(&self, disabled: bool) -> impl Iterator { + fn turn_widgets(&self, disabled: bool) -> impl Iterator + use<> { [(-90., "TurnNegative90", "Turn -90°"), (90., "TurnPositive90", "Turn 90°")] .into_iter() .map(move |(degrees, icon, name)| { @@ -180,7 +179,7 @@ impl SelectTool { }) } - fn boolean_widgets(&self, selected_count: usize) -> impl Iterator { + fn boolean_widgets(&self, selected_count: usize) -> impl Iterator + use<> { let operations = BooleanOperation::list(); let icons = BooleanOperation::icons(); operations.into_iter().zip(icons).map(move |(operation, icon)| { @@ -1030,7 +1029,7 @@ impl Fsm for SelectToolFsmState { } } (SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove(modifier_keys)) => { - if let Some(ref mut bounds) = &mut tool_data.bounding_box_manager { + if let Some(bounds) = &mut tool_data.bounding_box_manager { if let Some(movement) = &mut bounds.selected_edges { let (center, constrain) = (input.keyboard.key(modifier_keys.center), input.keyboard.key(modifier_keys.axis_align)); @@ -1079,7 +1078,7 @@ impl Fsm for SelectToolFsmState { SelectToolFsmState::ResizingBounds } (SelectToolFsmState::SkewingBounds { skew }, SelectToolMessage::PointerMove(_)) => { - if let Some(ref mut bounds) = &mut tool_data.bounding_box_manager { + if let Some(bounds) = &mut tool_data.bounding_box_manager { if let Some(movement) = &mut bounds.selected_edges { let free_movement = input.keyboard.key(skew); let transformation = movement.skew_transform(input.mouse.position, bounds.original_bound_transform, free_movement); @@ -1227,7 +1226,7 @@ impl Fsm for SelectToolFsmState { (SelectToolFsmState::ResizingBounds | SelectToolFsmState::SkewingBounds { .. }, SelectToolMessage::PointerOutsideViewport(_)) => { // AutoPanning if let Some(shift) = tool_data.auto_panning.shift_viewport(input, responses) { - if let Some(ref mut bounds) = &mut tool_data.bounding_box_manager { + if let Some(bounds) = &mut tool_data.bounding_box_manager { bounds.center_of_transformation += shift; bounds.original_bound_transform.translation += shift; } @@ -1631,12 +1630,14 @@ fn drag_shallowest_manipulation(responses: &mut VecDeque, selected: Vec } fn drag_deepest_manipulation(responses: &mut VecDeque, selected: Vec, tool_data: &mut SelectToolData, document: &DocumentMessageHandler) { - tool_data.layers_dragging.append(&mut vec![document.find_deepest(&selected).unwrap_or( - LayerNodeIdentifier::ROOT_PARENT - .children(document.metadata()) - .next() - .expect("ROOT_PARENT should have a layer child when clicking"), - )]); + tool_data.layers_dragging.append(&mut vec![ + document.find_deepest(&selected).unwrap_or( + LayerNodeIdentifier::ROOT_PARENT + .children(document.metadata()) + .next() + .expect("ROOT_PARENT should have a layer child when clicking"), + ), + ]); responses.add(NodeGraphMessage::SelectedNodesSet { nodes: tool_data .layers_dragging diff --git a/editor/src/messages/tool/tool_messages/spline_tool.rs b/editor/src/messages/tool/tool_messages/spline_tool.rs index a86cfccb5..9f29d3403 100644 --- a/editor/src/messages/tool/tool_messages/spline_tool.rs +++ b/editor/src/messages/tool/tool_messages/spline_tool.rs @@ -9,7 +9,6 @@ use crate::messages::tool::common_functionality::color_selector::{ToolColorOptio use crate::messages::tool::common_functionality::graph_modification_utils::{self, find_spline, merge_layers, merge_points}; use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapData, SnapManager, SnapTypeConfiguration, SnappedPoint}; use crate::messages::tool::common_functionality::utility_functions::{closest_point, should_extend}; - use graph_craft::document::{NodeId, NodeInput}; use graphene_core::Color; use graphene_std::vector::{PointId, SegmentId, VectorModificationType}; diff --git a/editor/src/messages/tool/tool_messages/text_tool.rs b/editor/src/messages/tool/tool_messages/text_tool.rs index a366f62ac..d6227b2af 100644 --- a/editor/src/messages/tool/tool_messages/text_tool.rs +++ b/editor/src/messages/tool/tool_messages/text_tool.rs @@ -6,18 +6,20 @@ use crate::messages::portfolio::document::graph_operation::utility_types::Transf use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; +use crate::messages::tool::common_functionality::auto_panning::AutoPanning; use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType}; use crate::messages::tool::common_functionality::graph_modification_utils::{self, is_layer_fed_by_node_of_name}; +use crate::messages::tool::common_functionality::pivot::Pivot; +use crate::messages::tool::common_functionality::resize::Resize; use crate::messages::tool::common_functionality::snapping::{self, SnapCandidatePoint, SnapData}; use crate::messages::tool::common_functionality::transformation_cage::*; -use crate::messages::tool::common_functionality::{auto_panning::AutoPanning, pivot::Pivot, resize::Resize, utility_functions::text_bounding_box}; - +use crate::messages::tool::common_functionality::utility_functions::text_bounding_box; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeInput}; -use graphene_core::renderer::Quad; -use graphene_core::text::{lines_clipping, load_face, Font, FontCache, TypesettingConfig}; -use graphene_core::vector::style::Fill; use graphene_core::Color; +use graphene_core::renderer::Quad; +use graphene_core::text::{Font, FontCache, TypesettingConfig, lines_clipping, load_face}; +use graphene_core::vector::style::Fill; #[derive(Default)] pub struct TextTool { @@ -514,7 +516,7 @@ impl Fsm for TextToolFsmState { // The angle is choosen to be parallel to the X axis in the bounds transform. let angle = bounding_box_manager.transform.transform_vector2(DVec2::X).to_angle(); // Update pivot - tool_data.pivot.update_pivot(&document, &mut overlay_context, angle); + tool_data.pivot.update_pivot(document, &mut overlay_context, angle); } else { tool_data.bounding_box_manager.take(); } @@ -607,7 +609,7 @@ impl Fsm for TextToolFsmState { TextToolFsmState::Dragging } (TextToolFsmState::ResizingBounds, TextToolMessage::PointerMove { center, lock_ratio }) => { - if let Some(ref mut bounds) = &mut tool_data.bounding_box_manager { + if let Some(bounds) = &mut tool_data.bounding_box_manager { if let Some(movement) = &mut bounds.selected_edges { let (center_bool, lock_ratio_bool) = (input.keyboard.key(center), input.keyboard.key(lock_ratio)); let center_position = center_bool.then_some(bounds.center_of_transformation); @@ -682,7 +684,7 @@ impl Fsm for TextToolFsmState { (TextToolFsmState::ResizingBounds, TextToolMessage::PointerOutsideViewport { .. }) => { // AutoPanning if let Some(shift) = tool_data.auto_panning.shift_viewport(input, responses) { - if let Some(ref mut bounds) = &mut tool_data.bounding_box_manager { + if let Some(bounds) = &mut tool_data.bounding_box_manager { bounds.center_of_transformation += shift; bounds.original_bound_transform.translation += shift; } diff --git a/editor/src/messages/tool/transform_layer/transform_layer_message.rs b/editor/src/messages/tool/transform_layer/transform_layer_message.rs index 864eeb172..fd11dbf90 100644 --- a/editor/src/messages/tool/transform_layer/transform_layer_message.rs +++ b/editor/src/messages/tool/transform_layer/transform_layer_message.rs @@ -1,7 +1,6 @@ use crate::messages::input_mapper::utility_types::input_keyboard::Key; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::prelude::*; - use glam::DVec2; #[impl_message(Message, ToolMessage, TransformLayer)] 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 32cd612e0..c9bd177c4 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 @@ -8,12 +8,10 @@ use crate::messages::prelude::*; use crate::messages::tool::common_functionality::shape_editor::ShapeState; use crate::messages::tool::tool_messages::tool_prelude::Key; use crate::messages::tool::utility_types::{ToolData, ToolType}; - +use glam::{DAffine2, DVec2}; use graphene_core::renderer::Quad; use graphene_core::vector::ManipulatorPointId; use graphene_std::vector::{VectorData, VectorModificationType}; - -use glam::{DAffine2, DVec2}; use std::f64::consts::TAU; const TRANSFORM_GRS_OVERLAY_PROVIDER: OverlayProvider = |context| TransformLayerMessage::Overlays(context).into(); diff --git a/editor/src/messages/tool/utility_types.rs b/editor/src/messages/tool/utility_types.rs index d16f2cdb3..fd8420a3d 100644 --- a/editor/src/messages/tool/utility_types.rs +++ b/editor/src/messages/tool/utility_types.rs @@ -2,8 +2,8 @@ use super::common_functionality::shape_editor::ShapeState; use super::tool_messages::*; -use crate::messages::broadcast::broadcast_event::BroadcastEvent; use crate::messages::broadcast::BroadcastMessage; +use crate::messages::broadcast::broadcast_event::BroadcastEvent; use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeysGroup, LayoutKeysGroup, MouseMotion}; use crate::messages::input_mapper::utility_types::macros::action_keys; use crate::messages::input_mapper::utility_types::misc::ActionKeys; @@ -12,10 +12,8 @@ use crate::messages::portfolio::document::overlays::utility_types::OverlayProvid use crate::messages::preferences::PreferencesMessageHandler; use crate::messages::prelude::*; use crate::node_graph_executor::NodeGraphExecutor; - use graphene_core::raster::color::Color; use graphene_core::text::FontCache; - use std::borrow::Cow; use std::fmt::{self, Debug}; diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index 3bf7a5e16..32e22276a 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -1,13 +1,14 @@ use crate::consts::FILE_SAVE_SUFFIX; use crate::messages::frontend::utility_types::{ExportBounds, FileType}; use crate::messages::prelude::*; - +use glam::{DAffine2, DVec2, UVec2}; use graph_craft::concrete; use graph_craft::document::value::{RenderOutput, TaggedValue}; -use graph_craft::document::{generate_uuid, DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork}; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, generate_uuid}; use graph_craft::graphene_compiler::Compiler; use graph_craft::proto::GraphErrors; use graph_craft::wasm_application_io::EditorPreferences; +use graphene_core::Context; use graphene_core::application_io::{NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig}; use graphene_core::memo::IORecord; use graphene_core::renderer::{GraphicElementRendered, RenderParams, SvgRender}; @@ -15,18 +16,15 @@ use graphene_core::renderer::{RenderSvgSegmentList, SvgSegment}; use graphene_core::text::FontCache; use graphene_core::transform::Footprint; use graphene_core::vector::style::ViewMode; -use graphene_core::Context; -use graphene_std::renderer::{format_transform_matrix, RenderMetadata}; +use graphene_std::renderer::{RenderMetadata, format_transform_matrix}; use graphene_std::vector::{VectorData, VectorDataTable}; use graphene_std::wasm_application_io::{WasmApplicationIo, WasmEditorApi}; use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::util::wrap_network_in_scope; - -use glam::{DAffine2, DVec2, UVec2}; use once_cell::sync::Lazy; use spin::Mutex; -use std::sync::mpsc::{Receiver, Sender}; use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender}; /// Persistent data between graph executions. It's updated via message passing from the editor thread with [`NodeRuntimeMessage`]`. /// Some of these fields are put into a [`WasmEditorApi`] which is passed to the final compiled graph network upon each execution. diff --git a/editor/src/test_utils.rs b/editor/src/test_utils.rs index eac5dcc9a..be17b4d23 100644 --- a/editor/src/test_utils.rs +++ b/editor/src/test_utils.rs @@ -1,5 +1,5 @@ -use crate::application::set_uuid_seed; use crate::application::Editor; +use crate::application::set_uuid_seed; use crate::messages::input_mapper::utility_types::input_keyboard::ModifierKeys; use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta, ViewportPosition}; use crate::messages::portfolio::utility_types::Platform; @@ -8,12 +8,10 @@ use crate::messages::tool::tool_messages::tool_prelude::Key; use crate::messages::tool::utility_types::ToolType; use crate::node_graph_executor::Instrumented; use crate::node_graph_executor::NodeRuntime; - -use graph_craft::document::DocumentNode; -use graphene_core::raster::color::Color; -use graphene_core::InputAccessor; - use glam::DVec2; +use graph_craft::document::DocumentNode; +use graphene_core::InputAccessor; +use graphene_core::raster::color::Color; /// A set of utility functions to make the writing of editor test more declarative pub struct EditorTestUtils { @@ -256,7 +254,7 @@ pub mod test_prelude { pub use crate::messages::portfolio::document::utility_types::clipboards::Clipboard; pub use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; pub use crate::messages::prelude::*; - pub use crate::messages::tool::common_functionality::graph_modification_utils::{is_layer_fed_by_node_of_name, NodeGraphLayer}; + pub use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, is_layer_fed_by_node_of_name}; pub use crate::messages::tool::utility_types::ToolType; pub use crate::node_graph_executor::NodeRuntime; pub use crate::test_utils::EditorTestUtils; diff --git a/frontend/src-tauri/build.rs b/frontend/src-tauri/build.rs index 15c7bcce0..59fdfbea6 100644 --- a/frontend/src-tauri/build.rs +++ b/frontend/src-tauri/build.rs @@ -1,4 +1,5 @@ -use std::{fs, path::PathBuf}; +use std::fs; +use std::path::PathBuf; fn main() { // Directory required for compilation, but not tracked by git if empty. diff --git a/frontend/wasm/Cargo.toml b/frontend/wasm/Cargo.toml index d3783858e..5cd82877b 100644 --- a/frontend/wasm/Cargo.toml +++ b/frontend/wasm/Cargo.toml @@ -2,9 +2,9 @@ name = "graphite-wasm" publish = false version = "0.0.0" -rust-version = "1.79" +rust-version = "1.85" authors = ["Graphite Authors "] -edition = "2021" +edition = "2024" readme = "../../README.md" homepage = "https://graphite.rs" repository = "https://github.com/GraphiteEditor/Graphite" diff --git a/frontend/wasm/src/editor_api.rs b/frontend/wasm/src/editor_api.rs index ec824b0cb..922b9ebd0 100644 --- a/frontend/wasm/src/editor_api.rs +++ b/frontend/wasm/src/editor_api.rs @@ -5,8 +5,7 @@ // on the dispatcher messaging system and more complex Rust data types. // use crate::helpers::translate_key; -use crate::{Error, EDITOR, EDITOR_HANDLE, EDITOR_HAS_CRASHED}; - +use crate::{EDITOR, EDITOR_HANDLE, EDITOR_HAS_CRASHED, Error}; use editor::application::Editor; use editor::consts::FILE_SAVE_SUFFIX; use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys; @@ -18,7 +17,6 @@ use editor::messages::prelude::*; use editor::messages::tool::tool_messages::tool_prelude::WidgetId; use graph_craft::document::NodeId; use graphene_core::raster::color::Color; - use serde::Serialize; use serde_wasm_bindgen::{self, from_value}; use std::cell::RefCell; @@ -757,10 +755,11 @@ impl EditorHandle { use editor::messages::portfolio::document::graph_operation::transform_utils::*; use editor::messages::portfolio::document::graph_operation::utility_types::*; use editor::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type; - use editor::node_graph_executor::replace_node_runtime; use editor::node_graph_executor::NodeRuntime; + use editor::node_graph_executor::replace_node_runtime; + use graph_craft::document::DocumentNodeImplementation; use graph_craft::document::NodeInput; - use graph_craft::document::{value::TaggedValue, DocumentNodeImplementation}; + use graph_craft::document::value::TaggedValue; use graphene_core::vector::*; let (_, request_receiver) = std::sync::mpsc::channel(); @@ -989,7 +988,7 @@ fn set_timeout(f: &Closure, delay: Duration) { fn editor(callback: impl FnOnce(&mut editor::application::Editor) -> T) -> T { EDITOR.with(|editor| { let mut guard = editor.try_lock(); - let Ok(Some(ref mut editor)) = guard.as_deref_mut() else { return T::default() }; + let Ok(Some(editor)) = guard.as_deref_mut() else { return T::default() }; callback(editor) }) @@ -1000,7 +999,7 @@ pub(crate) fn editor_and_handle(mut callback: impl FnMut(&mut Editor, &mut Edito EDITOR_HANDLE.with(|editor_handle| { editor(|editor| { let mut guard = editor_handle.try_lock(); - let Ok(Some(ref mut editor_handle)) = guard.as_deref_mut() else { + let Ok(Some(editor_handle)) = guard.as_deref_mut() else { log::error!("Failed to borrow editor handle"); return; }; diff --git a/frontend/wasm/src/lib.rs b/frontend/wasm/src/lib.rs index 6cc7edd29..730fb4215 100644 --- a/frontend/wasm/src/lib.rs +++ b/frontend/wasm/src/lib.rs @@ -8,10 +8,9 @@ pub mod editor_api; pub mod helpers; use editor::messages::prelude::*; - use std::panic; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; use wasm_bindgen::prelude::*; // Set up the persistent editor backend state @@ -72,7 +71,7 @@ pub fn panic_hook(info: &panic::PanicHookInfo) { EDITOR_HANDLE.with(|editor_handle| { let mut guard = editor_handle.lock(); - if let Ok(Some(ref mut handle)) = guard.as_deref_mut() { + if let Ok(Some(handle)) = guard.as_deref_mut() { handle.send_frontend_message_to_js_rust_proxy(FrontendMessage::DisplayDialogPanic { panic_info: info.to_string() }); } }); diff --git a/libraries/bezier-rs/Cargo.toml b/libraries/bezier-rs/Cargo.toml index ce92dbe31..57a5c676f 100644 --- a/libraries/bezier-rs/Cargo.toml +++ b/libraries/bezier-rs/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "bezier-rs" version = "0.4.0" -rust-version = "1.79" -edition = "2021" +rust-version = "1.85" +edition = "2024" authors = ["Graphite Authors "] description = "Computational geometry algorithms for Bézier segments and shapes useful in the context of 2D graphics" license = "MIT OR Apache-2.0" diff --git a/libraries/bezier-rs/src/bezier/core.rs b/libraries/bezier-rs/src/bezier/core.rs index 7aeb07b46..123cfe458 100644 --- a/libraries/bezier-rs/src/bezier/core.rs +++ b/libraries/bezier-rs/src/bezier/core.rs @@ -1,7 +1,6 @@ use super::*; -use utils::format_point; - use std::fmt::Write; +use utils::format_point; /// Functionality relating to core `Bezier` operations, such as constructors and `abs_diff_eq`. impl Bezier { diff --git a/libraries/bezier-rs/src/bezier/lookup.rs b/libraries/bezier-rs/src/bezier/lookup.rs index c86cef65e..499c933f0 100644 --- a/libraries/bezier-rs/src/bezier/lookup.rs +++ b/libraries/bezier-rs/src/bezier/lookup.rs @@ -1,6 +1,5 @@ -use crate::utils::{TValue, TValueType}; - use super::*; +use crate::utils::{TValue, TValueType}; /// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`. impl Bezier { diff --git a/libraries/bezier-rs/src/bezier/manipulators.rs b/libraries/bezier-rs/src/bezier/manipulators.rs index e56e8d921..1b70f3586 100644 --- a/libraries/bezier-rs/src/bezier/manipulators.rs +++ b/libraries/bezier-rs/src/bezier/manipulators.rs @@ -69,7 +69,7 @@ impl Bezier { /// - For a linear segment, the order of the points will be: `start`, `end`. /// - For a quadratic segment, the order of the points will be: `start`, `handle`, `end`. /// - For a cubic segment, the order of the points will be: `start`, `handle_start`, `handle_end`, `end`. - pub fn get_points(&self) -> impl Iterator { + pub fn get_points(&self) -> impl Iterator + use<> { match self.handles { BezierHandles::Linear => [self.start, self.end, DVec2::ZERO, DVec2::ZERO].into_iter().take(2), BezierHandles::Quadratic { handle } => [self.start, handle, self.end, DVec2::ZERO].into_iter().take(3), diff --git a/libraries/bezier-rs/src/bezier/mod.rs b/libraries/bezier-rs/src/bezier/mod.rs index fb2c11b6a..57c320fd2 100644 --- a/libraries/bezier-rs/src/bezier/mod.rs +++ b/libraries/bezier-rs/src/bezier/mod.rs @@ -7,11 +7,9 @@ mod transform; use crate::consts::*; use crate::utils; - -pub use structs::*; - use glam::DVec2; use std::fmt::{Debug, Formatter, Result}; +pub use structs::*; /// Representation of the handle point(s) in a bezier segment. #[derive(Copy, Clone, PartialEq, Debug)] diff --git a/libraries/bezier-rs/src/bezier/solvers.rs b/libraries/bezier-rs/src/bezier/solvers.rs index 62fc1b002..320e772d9 100644 --- a/libraries/bezier-rs/src/bezier/solvers.rs +++ b/libraries/bezier-rs/src/bezier/solvers.rs @@ -1,8 +1,7 @@ use super::*; use crate::polynomial::Polynomial; -use crate::utils::{solve_cubic, solve_quadratic, TValue}; -use crate::{to_symmetrical_basis_pair, SymmetricalBasis}; - +use crate::utils::{TValue, solve_cubic, solve_quadratic}; +use crate::{SymmetricalBasis, to_symmetrical_basis_pair}; use glam::DMat2; use std::ops::Range; @@ -99,11 +98,7 @@ impl Bezier { pub fn tangent(&self, t: TValue) -> DVec2 { let t = self.t_value_to_parametric(t); let tangent = self.non_normalized_tangent(t); - if tangent.length() > 0. { - tangent.normalize() - } else { - tangent - } + if tangent.length() > 0. { tangent.normalize() } else { tangent } } /// Find the `t`-value(s) such that the tangent(s) at `t` pass through the specified point. @@ -147,11 +142,7 @@ impl Bezier { let numerator = d.x * dd.y - d.y * dd.x; let denominator = (d.x.powf(2.) + d.y.powf(2.)).powf(1.5); - if denominator.abs() < MAX_ABSOLUTE_DIFFERENCE { - 0. - } else { - numerator / denominator - } + if denominator.abs() < MAX_ABSOLUTE_DIFFERENCE { 0. } else { numerator / denominator } } /// Returns two lists of `t`-values representing the local extrema of the `x` and `y` parametric curves respectively. @@ -228,7 +219,7 @@ impl Bezier { } /// Returns an `Iterator` containing all possible parametric `t`-values at the given `x`-coordinate. - pub fn find_tvalues_for_x(&self, x: f64) -> impl Iterator { + pub fn find_tvalues_for_x(&self, x: f64) -> impl Iterator + use<> { // Compute the roots of the resulting bezier curve match self.handles { BezierHandles::Linear => { diff --git a/libraries/bezier-rs/src/bezier/transform.rs b/libraries/bezier-rs/src/bezier/transform.rs index d65cfb74e..6a48dc73b 100644 --- a/libraries/bezier-rs/src/bezier/transform.rs +++ b/libraries/bezier-rs/src/bezier/transform.rs @@ -1,9 +1,7 @@ use super::*; - use crate::compare::compare_points; -use crate::utils::{f64_compare, Cap, TValue}; +use crate::utils::{Cap, TValue, f64_compare}; use crate::{AppendType, ManipulatorGroup, Subpath}; - use glam::DMat2; use std::f64::consts::PI; @@ -476,11 +474,7 @@ impl Bezier { error, max_iterations, }); - if final_low_t != 1. { - [auto_arcs, arc_approximations].concat() - } else { - auto_arcs - } + if final_low_t != 1. { [auto_arcs, arc_approximations].concat() } else { auto_arcs } } ArcStrategy::FavorLargerArcs => self.approximate_curve_with_arcs(0., 1., error, max_iterations, false).0, ArcStrategy::FavorCorrectness => self @@ -620,9 +614,9 @@ impl Bezier { #[cfg(test)] mod tests { use super::*; + use crate::EmptyId; use crate::compare::{compare_arcs, compare_points}; use crate::utils::{Cap, TValue}; - use crate::EmptyId; #[test] fn test_split() { @@ -777,14 +771,18 @@ mod tests { // Check that the reduce helper is correct let (helper_curves, helper_t_values) = bezier.reduced_curves_and_t_values(None); - assert!(reduced_curves - .iter() - .zip(helper_curves.iter()) - .all(|(bezier1, bezier2)| bezier1.abs_diff_eq(bezier2, MAX_ABSOLUTE_DIFFERENCE))); - assert!(reduced_curves - .iter() - .zip(helper_t_values.iter()) - .all(|(curve, t_pair)| curve.abs_diff_eq(&bezier.trim(TValue::Parametric(t_pair[0]), TValue::Parametric(t_pair[1])), MAX_ABSOLUTE_DIFFERENCE))) + assert!( + reduced_curves + .iter() + .zip(helper_curves.iter()) + .all(|(bezier1, bezier2)| bezier1.abs_diff_eq(bezier2, MAX_ABSOLUTE_DIFFERENCE)) + ); + assert!( + reduced_curves + .iter() + .zip(helper_t_values.iter()) + .all(|(curve, t_pair)| curve.abs_diff_eq(&bezier.trim(TValue::Parametric(t_pair[0]), TValue::Parametric(t_pair[1])), MAX_ABSOLUTE_DIFFERENCE)) + ) } fn assert_valid_offset(bezier: &Bezier, offset: &Subpath, expected_distance: f64) { diff --git a/libraries/bezier-rs/src/compare.rs b/libraries/bezier-rs/src/compare.rs index 2580ac22e..55b6b55e9 100644 --- a/libraries/bezier-rs/src/compare.rs +++ b/libraries/bezier-rs/src/compare.rs @@ -1,11 +1,9 @@ /// Comparison functions used for tests in the bezier module #[cfg(test)] use super::{CircleArc, Subpath}; +use crate::consts::MAX_ABSOLUTE_DIFFERENCE; #[cfg(test)] use crate::utils::f64_compare; - -use crate::consts::MAX_ABSOLUTE_DIFFERENCE; - use glam::DVec2; // Compare two f64s with some maximum absolute difference to account for floating point errors diff --git a/libraries/bezier-rs/src/polynomial.rs b/libraries/bezier-rs/src/polynomial.rs index 4e8fdb206..1deee9ce9 100644 --- a/libraries/bezier-rs/src/polynomial.rs +++ b/libraries/bezier-rs/src/polynomial.rs @@ -102,7 +102,7 @@ impl Default for Polynomial { impl Display for Polynomial { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut first = true; - for (index, coefficient) in self.coefficients.iter().enumerate().rev().filter(|(_, &coefficient)| coefficient != 0.) { + for (index, coefficient) in self.coefficients.iter().enumerate().rev().filter(|&(_, &coefficient)| coefficient != 0.) { if first { first = false; } else { diff --git a/libraries/bezier-rs/src/subpath/core.rs b/libraries/bezier-rs/src/subpath/core.rs index 0164419aa..2c217d705 100644 --- a/libraries/bezier-rs/src/subpath/core.rs +++ b/libraries/bezier-rs/src/subpath/core.rs @@ -1,7 +1,6 @@ use super::*; use crate::consts::*; use crate::utils::format_point; - use glam::DVec2; use std::fmt::Write; diff --git a/libraries/bezier-rs/src/subpath/manipulators.rs b/libraries/bezier-rs/src/subpath/manipulators.rs index 011d0fb76..4faf28d26 100644 --- a/libraries/bezier-rs/src/subpath/manipulators.rs +++ b/libraries/bezier-rs/src/subpath/manipulators.rs @@ -124,7 +124,6 @@ impl Subpath { mod tests { use super::*; use crate::utils::SubpathTValue; - use glam::DVec2; fn set_up_open_subpath() -> Subpath { diff --git a/libraries/bezier-rs/src/subpath/mod.rs b/libraries/bezier-rs/src/subpath/mod.rs index 3fb0649c6..e299afd86 100644 --- a/libraries/bezier-rs/src/subpath/mod.rs +++ b/libraries/bezier-rs/src/subpath/mod.rs @@ -4,13 +4,12 @@ mod manipulators; mod solvers; mod structs; mod transform; -pub use core::*; -pub use structs::*; use crate::Bezier; - +pub use core::*; use std::fmt::{Debug, Formatter, Result}; use std::ops::{Index, IndexMut}; +pub use structs::*; /// Structure used to represent a path composed of [Bezier] curves. #[derive(Clone, PartialEq, Hash)] diff --git a/libraries/bezier-rs/src/subpath/solvers.rs b/libraries/bezier-rs/src/subpath/solvers.rs index 2393aa55d..a148ebce7 100644 --- a/libraries/bezier-rs/src/subpath/solvers.rs +++ b/libraries/bezier-rs/src/subpath/solvers.rs @@ -1,8 +1,7 @@ use super::*; -use crate::consts::MAX_ABSOLUTE_DIFFERENCE; -use crate::utils::{compute_circular_subpath_details, is_rectangle_inside_other, line_intersection, SubpathTValue}; use crate::TValue; - +use crate::consts::MAX_ABSOLUTE_DIFFERENCE; +use crate::utils::{SubpathTValue, compute_circular_subpath_details, is_rectangle_inside_other, line_intersection}; use glam::{DAffine2, DMat2, DVec2}; use std::f64::consts::PI; @@ -539,10 +538,9 @@ impl Subpath { #[cfg(test)] mod tests { use super::*; + use crate::Bezier; use crate::consts::MAX_ABSOLUTE_DIFFERENCE; use crate::utils; - use crate::Bezier; - use glam::DVec2; fn normalize_t(n: i64, t: f64) -> f64 { @@ -629,44 +627,54 @@ mod tests { let mut n = (subpath.len() as i64) - 1; let t0 = 0.; - assert!(utils::dvec2_compare( - subpath.evaluate(SubpathTValue::GlobalParametric(t0)), - linear_bezier.evaluate(TValue::Parametric(normalize_t(n, t0))), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + subpath.evaluate(SubpathTValue::GlobalParametric(t0)), + linear_bezier.evaluate(TValue::Parametric(normalize_t(n, t0))), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); let t1 = 0.25; - assert!(utils::dvec2_compare( - subpath.evaluate(SubpathTValue::GlobalParametric(t1)), - linear_bezier.evaluate(TValue::Parametric(normalize_t(n, t1))), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + subpath.evaluate(SubpathTValue::GlobalParametric(t1)), + linear_bezier.evaluate(TValue::Parametric(normalize_t(n, t1))), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); let t2 = 0.50; - assert!(utils::dvec2_compare( - subpath.evaluate(SubpathTValue::GlobalParametric(t2)), - quadratic_bezier.evaluate(TValue::Parametric(normalize_t(n, t2))), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + subpath.evaluate(SubpathTValue::GlobalParametric(t2)), + quadratic_bezier.evaluate(TValue::Parametric(normalize_t(n, t2))), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); let t3 = 0.75; - assert!(utils::dvec2_compare( - subpath.evaluate(SubpathTValue::GlobalParametric(t3)), - quadratic_bezier.evaluate(TValue::Parametric(normalize_t(n, t3))), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + subpath.evaluate(SubpathTValue::GlobalParametric(t3)), + quadratic_bezier.evaluate(TValue::Parametric(normalize_t(n, t3))), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); let t4 = 1.; - assert!(utils::dvec2_compare( - subpath.evaluate(SubpathTValue::GlobalParametric(t4)), - quadratic_bezier.evaluate(TValue::Parametric(1.)), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + subpath.evaluate(SubpathTValue::GlobalParametric(t4)), + quadratic_bezier.evaluate(TValue::Parametric(1.)), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); // Test closed subpath @@ -674,20 +682,24 @@ mod tests { n = subpath.len() as i64; let t5 = 2. / 3.; - assert!(utils::dvec2_compare( - subpath.evaluate(SubpathTValue::GlobalParametric(t5)), - cubic_bezier.evaluate(TValue::Parametric(normalize_t(n, t5))), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + subpath.evaluate(SubpathTValue::GlobalParametric(t5)), + cubic_bezier.evaluate(TValue::Parametric(normalize_t(n, t5))), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); let t6 = 1.; - assert!(utils::dvec2_compare( - subpath.evaluate(SubpathTValue::GlobalParametric(t6)), - cubic_bezier.evaluate(TValue::Parametric(1.)), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + subpath.evaluate(SubpathTValue::GlobalParametric(t6)), + cubic_bezier.evaluate(TValue::Parametric(1.)), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); } #[test] @@ -737,35 +749,41 @@ mod tests { let quadratic_1_intersections = quadratic_bezier_1.intersections(&line, None, None); let subpath_intersections = subpath.intersections(&line, None, None); - assert!(utils::dvec2_compare( - cubic_bezier.evaluate(TValue::Parametric(cubic_intersections[0])), - subpath.evaluate(SubpathTValue::Parametric { - segment_index: subpath_intersections[0].0, - t: subpath_intersections[0].1 - }), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + cubic_bezier.evaluate(TValue::Parametric(cubic_intersections[0])), + subpath.evaluate(SubpathTValue::Parametric { + segment_index: subpath_intersections[0].0, + t: subpath_intersections[0].1 + }), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); - assert!(utils::dvec2_compare( - quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[0])), - subpath.evaluate(SubpathTValue::Parametric { - segment_index: subpath_intersections[1].0, - t: subpath_intersections[1].1 - }), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[0])), + subpath.evaluate(SubpathTValue::Parametric { + segment_index: subpath_intersections[1].0, + t: subpath_intersections[1].1 + }), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); - assert!(utils::dvec2_compare( - quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[1])), - subpath.evaluate(SubpathTValue::Parametric { - segment_index: subpath_intersections[2].0, - t: subpath_intersections[2].1 - }), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[1])), + subpath.evaluate(SubpathTValue::Parametric { + segment_index: subpath_intersections[2].0, + t: subpath_intersections[2].1 + }), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); } #[test] @@ -816,25 +834,29 @@ mod tests { let quadratic_1_intersections = quadratic_bezier_1.intersections(&line, None, None); let subpath_intersections = subpath.intersections(&line, None, None); - assert!(utils::dvec2_compare( - cubic_bezier.evaluate(TValue::Parametric(cubic_intersections[0])), - subpath.evaluate(SubpathTValue::Parametric { - segment_index: subpath_intersections[0].0, - t: subpath_intersections[0].1 - }), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + cubic_bezier.evaluate(TValue::Parametric(cubic_intersections[0])), + subpath.evaluate(SubpathTValue::Parametric { + segment_index: subpath_intersections[0].0, + t: subpath_intersections[0].1 + }), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); - assert!(utils::dvec2_compare( - quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[0])), - subpath.evaluate(SubpathTValue::Parametric { - segment_index: subpath_intersections[1].0, - t: subpath_intersections[1].1 - }), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[0])), + subpath.evaluate(SubpathTValue::Parametric { + segment_index: subpath_intersections[1].0, + t: subpath_intersections[1].1 + }), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); } #[test] @@ -884,35 +906,41 @@ mod tests { let quadratic_1_intersections = quadratic_bezier_1.intersections(&line, None, None); let subpath_intersections = subpath.intersections(&line, None, None); - assert!(utils::dvec2_compare( - cubic_bezier.evaluate(TValue::Parametric(cubic_intersections[0])), - subpath.evaluate(SubpathTValue::Parametric { - segment_index: subpath_intersections[0].0, - t: subpath_intersections[0].1 - }), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + cubic_bezier.evaluate(TValue::Parametric(cubic_intersections[0])), + subpath.evaluate(SubpathTValue::Parametric { + segment_index: subpath_intersections[0].0, + t: subpath_intersections[0].1 + }), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); - assert!(utils::dvec2_compare( - quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[0])), - subpath.evaluate(SubpathTValue::Parametric { - segment_index: subpath_intersections[1].0, - t: subpath_intersections[1].1 - }), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[0])), + subpath.evaluate(SubpathTValue::Parametric { + segment_index: subpath_intersections[1].0, + t: subpath_intersections[1].1 + }), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); - assert!(utils::dvec2_compare( - quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[1])), - subpath.evaluate(SubpathTValue::Parametric { - segment_index: subpath_intersections[2].0, - t: subpath_intersections[2].1 - }), - MAX_ABSOLUTE_DIFFERENCE - ) - .all()); + assert!( + utils::dvec2_compare( + quadratic_bezier_1.evaluate(TValue::Parametric(quadratic_1_intersections[1])), + subpath.evaluate(SubpathTValue::Parametric { + segment_index: subpath_intersections[2].0, + t: subpath_intersections[2].1 + }), + MAX_ABSOLUTE_DIFFERENCE + ) + .all() + ); } // TODO: add more intersection tests @@ -924,19 +952,19 @@ mod tests { let curve = Bezier::from_quadratic_dvec2(DVec2::new(189., 289.), DVec2::new(9., 286.), DVec2::new(45., 410.)); let curve_intersecting = Subpath::::from_bezier(&curve); - assert_eq!(curve_intersecting.is_inside_subpath(&boundary_polygon, None, None), false); + assert!(!curve_intersecting.is_inside_subpath(&boundary_polygon, None, None)); let curve = Bezier::from_quadratic_dvec2(DVec2::new(115., 37.), DVec2::new(51.4, 91.8), DVec2::new(76.5, 242.)); let curve_outside = Subpath::::from_bezier(&curve); - assert_eq!(curve_outside.is_inside_subpath(&boundary_polygon, None, None), false); + assert!(!curve_outside.is_inside_subpath(&boundary_polygon, None, None)); let curve = Bezier::from_cubic_dvec2(DVec2::new(210.1, 133.5), DVec2::new(150.2, 436.9), DVec2::new(436., 285.), DVec2::new(247.6, 240.7)); let curve_inside = Subpath::::from_bezier(&curve); - assert_eq!(curve_inside.is_inside_subpath(&boundary_polygon, None, None), true); + assert!(curve_inside.is_inside_subpath(&boundary_polygon, None, None)); let line = Bezier::from_linear_dvec2(DVec2::new(101., 101.5), DVec2::new(150.2, 499.)); let line_inside = Subpath::::from_bezier(&line); - assert_eq!(line_inside.is_inside_subpath(&boundary_polygon, None, None), true); + assert!(line_inside.is_inside_subpath(&boundary_polygon, None, None)); } #[test] diff --git a/libraries/bezier-rs/src/subpath/structs.rs b/libraries/bezier-rs/src/subpath/structs.rs index 63912bf42..faf0a98a8 100644 --- a/libraries/bezier-rs/src/subpath/structs.rs +++ b/libraries/bezier-rs/src/subpath/structs.rs @@ -1,10 +1,7 @@ use super::Bezier; - use glam::{DAffine2, DVec2}; -use std::{ - fmt::{Debug, Formatter, Result}, - hash::Hash, -}; +use std::fmt::{Debug, Formatter, Result}; +use std::hash::Hash; /// An id type used for each [ManipulatorGroup]. pub trait Identifier: Sized + Clone + PartialEq + Hash + 'static { @@ -113,7 +110,7 @@ impl ManipulatorGroup { /// Are all handles at finite positions pub fn is_finite(&self) -> bool { - self.anchor.is_finite() && self.in_handle.map_or(true, |handle| handle.is_finite()) && self.out_handle.map_or(true, |handle| handle.is_finite()) + self.anchor.is_finite() && self.in_handle.is_none_or(|handle| handle.is_finite()) && self.out_handle.is_none_or(|handle| handle.is_finite()) } /// Reverse directions of handles diff --git a/libraries/bezier-rs/src/subpath/transform.rs b/libraries/bezier-rs/src/subpath/transform.rs index 82b6309cf..20b2fd857 100644 --- a/libraries/bezier-rs/src/subpath/transform.rs +++ b/libraries/bezier-rs/src/subpath/transform.rs @@ -1,20 +1,14 @@ -use std::vec; - use super::*; use crate::consts::MAX_ABSOLUTE_DIFFERENCE; use crate::utils::{Cap, Join, SubpathTValue, TValue}; - use glam::{DAffine2, DVec2}; +use std::vec; /// Helper function to ensure the index and t value pair is mapped within a maximum index value. /// Allows for the point to be fetched without needing to handle an additional edge case. /// - Ex. Via `subpath.iter().nth(index).evaluate(t);` fn map_index_within_range(index: usize, t: f64, max_size: usize) -> (usize, f64) { - if max_size > 0 && index == max_size && t == 0. { - (index - 1, 1.) - } else { - (index, t) - } + if max_size > 0 && index == max_size && t == 0. { (index - 1, 1.) } else { (index, t) } } /// Functionality that transforms Subpaths, such as split, reduce, offset, etc. @@ -549,10 +543,10 @@ impl Subpath { #[cfg(test)] mod tests { use super::{Cap, Join, ManipulatorGroup, Subpath}; + use crate::EmptyId; use crate::compare::{compare_points, compare_subpaths, compare_vec_of_points}; use crate::consts::MAX_ABSOLUTE_DIFFERENCE; use crate::utils::{SubpathTValue, TValue}; - use crate::EmptyId; use glam::DVec2; fn set_up_open_subpath() -> Subpath { diff --git a/libraries/bezier-rs/src/symmetrical_basis.rs b/libraries/bezier-rs/src/symmetrical_basis.rs index 571af3bdb..800de69d9 100644 --- a/libraries/bezier-rs/src/symmetrical_basis.rs +++ b/libraries/bezier-rs/src/symmetrical_basis.rs @@ -38,7 +38,6 @@ */ use crate::{Bezier, BezierHandles}; - use glam::DVec2; impl std::ops::Index for Bezier { diff --git a/libraries/bezier-rs/src/utils.rs b/libraries/bezier-rs/src/utils.rs index bccdb0707..2e80b80e8 100644 --- a/libraries/bezier-rs/src/utils.rs +++ b/libraries/bezier-rs/src/utils.rs @@ -1,6 +1,5 @@ use crate::consts::{MAX_ABSOLUTE_DIFFERENCE, STRICT_MAX_ABSOLUTE_DIFFERENCE}; use crate::{ManipulatorGroup, Subpath}; - use glam::{BVec2, DMat2, DVec2}; use std::fmt::Write; @@ -94,11 +93,7 @@ pub fn compute_abc_for_cubic_through_points(start_point: DVec2, point_on_curve: /// Find the roots of the linear equation `ax + b`. pub fn solve_linear(a: f64, b: f64) -> [Option; 3] { // There exist roots when `a` is not 0 - if a.abs() > MAX_ABSOLUTE_DIFFERENCE { - [Some(-b / a), None, None] - } else { - [None; 3] - } + if a.abs() > MAX_ABSOLUTE_DIFFERENCE { [Some(-b / a), None, None] } else { [None; 3] } } /// Find the roots of the linear equation `ax^2 + bx + c`. @@ -310,7 +305,8 @@ pub fn format_point(svg: &mut String, prefix: &str, x: f64, y: f64) -> std::fmt: #[cfg(test)] mod tests { use super::*; - use crate::{consts::MAX_ABSOLUTE_DIFFERENCE, Bezier, EmptyId}; + use crate::consts::MAX_ABSOLUTE_DIFFERENCE; + use crate::{Bezier, EmptyId}; /// Compare vectors of `f64`s with a provided max absolute value difference. fn f64_compare_vector(a: Vec, b: Vec, max_abs_diff: f64) -> bool { diff --git a/libraries/dyn-any/Cargo.toml b/libraries/dyn-any/Cargo.toml index f07c3d115..9672a5a31 100644 --- a/libraries/dyn-any/Cargo.toml +++ b/libraries/dyn-any/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "dyn-any" version = "0.3.1" -rust-version = "1.79" -edition = "2021" +rust-version = "1.85" +edition = "2024" authors = ["Graphite Authors "] description = "An Any trait that works for arbitrary lifetimes" license = "MIT OR Apache-2.0" diff --git a/libraries/dyn-any/derive/Cargo.toml b/libraries/dyn-any/derive/Cargo.toml index cf1025a30..4e5de0030 100644 --- a/libraries/dyn-any/derive/Cargo.toml +++ b/libraries/dyn-any/derive/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "dyn-any-derive" version = "0.3.0" -edition = "2021" +edition = "2024" authors = ["Graphite Authors "] description = "#[derive(DynAny)]" diff --git a/libraries/dyn-any/derive/src/lib.rs b/libraries/dyn-any/derive/src/lib.rs index c18c56096..0bfe526de 100644 --- a/libraries/dyn-any/derive/src/lib.rs +++ b/libraries/dyn-any/derive/src/lib.rs @@ -5,7 +5,7 @@ extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::Span; use quote::quote; -use syn::{parse_macro_input, DeriveInput, GenericParam, Lifetime, LifetimeParam, TypeParamBound}; +use syn::{DeriveInput, GenericParam, Lifetime, LifetimeParam, TypeParamBound, parse_macro_input}; /// Derives an implementation for the [`DynAny`] trait. /// @@ -62,7 +62,7 @@ fn replace_lifetimes(generics: &syn::Generics, replacement: &str) -> Vec { let mut t = t.clone(); t.bounds.iter_mut().for_each(|bond| { - if let TypeParamBound::Lifetime(ref mut t) = bond { + if let TypeParamBound::Lifetime(t) = bond { *t = Lifetime::new(replacement, Span::call_site()) } }); diff --git a/libraries/dyn-any/src/lib.rs b/libraries/dyn-any/src/lib.rs index 2da3cd93b..57bb10a79 100644 --- a/libraries/dyn-any/src/lib.rs +++ b/libraries/dyn-any/src/lib.rs @@ -187,7 +187,6 @@ macro_rules! impl_slice { mod slice { use super::*; - use core::slice::*; impl_slice!(Iter, IterMut, Chunks, ChunksMut, RChunks, RChunksMut, Windows); @@ -249,24 +248,24 @@ impl From<()> for Box> { } #[cfg(feature = "alloc")] -use alloc::{ - borrow::Cow, - boxed::Box, - collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}, - string::String, - vec::Vec, -}; +use alloc::borrow::Cow; +#[cfg(feature = "alloc")] +use alloc::boxed::Box; +#[cfg(feature = "alloc")] +use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; +#[cfg(feature = "alloc")] +use alloc::string::String; +#[cfg(feature = "alloc")] +use alloc::vec::Vec; +use core::cell::{Cell, RefCell, UnsafeCell}; +use core::iter::Empty; +use core::marker::{PhantomData, PhantomPinned}; +use core::mem::{ManuallyDrop, MaybeUninit}; +use core::num::Wrapping; +use core::ops::Range; +use core::pin::Pin; use core::sync::atomic::*; -use core::{ - cell::{Cell, RefCell, UnsafeCell}, - iter::Empty, - marker::{PhantomData, PhantomPinned}, - mem::{ManuallyDrop, MaybeUninit}, - num::Wrapping, - ops::Range, - pin::Pin, - time::Duration, -}; +use core::time::Duration; impl_type!( Option, Result, Cell, UnsafeCell, RefCell, MaybeUninit, @@ -286,10 +285,9 @@ impl_type!( ); #[cfg(feature = "std")] -use std::{ - collections::{HashMap, HashSet}, - sync::*, -}; +use std::collections::{HashMap, HashSet}; +#[cfg(feature = "std")] +use std::sync::*; #[cfg(feature = "std")] impl_type!(Once, Mutex, RwLock, HashSet, HashMap); diff --git a/libraries/math-parser/Cargo.toml b/libraries/math-parser/Cargo.toml index 7c00b2133..66b8f8410 100644 --- a/libraries/math-parser/Cargo.toml +++ b/libraries/math-parser/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "math-parser" version = "0.0.0" -rust-version = "1.79" -edition = "2021" +rust-version = "1.85" +edition = "2024" authors = ["Graphite Authors "] description = "Parser for Graphite style mathematics expressions" license = "MIT OR Apache-2.0" diff --git a/libraries/math-parser/benches/bench.rs b/libraries/math-parser/benches/bench.rs index 91af51f63..a1952bc2f 100644 --- a/libraries/math-parser/benches/bench.rs +++ b/libraries/math-parser/benches/bench.rs @@ -1,10 +1,9 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; - +use criterion::{Criterion, black_box, criterion_group, criterion_main}; use math_parser::ast; use math_parser::context::EvalContext; macro_rules! generate_benchmarks { - ($( $input:expr ),* $(,)?) => { + ($( $input:expr_2021 ),* $(,)?) => { fn parsing_bench(c: &mut Criterion) { $( c.bench_function(concat!("parse ", $input), |b| { diff --git a/libraries/math-parser/src/constants.rs b/libraries/math-parser/src/constants.rs index 1ef16831b..c010d1325 100644 --- a/libraries/math-parser/src/constants.rs +++ b/libraries/math-parser/src/constants.rs @@ -1,9 +1,9 @@ -use std::{collections::HashMap, f64::consts::PI}; - +use crate::value::{Number, Value}; use lazy_static::lazy_static; use num_complex::{Complex, ComplexFloat}; +use std::collections::HashMap; +use std::f64::consts::PI; -use crate::value::{Number, Value}; type FunctionImplementation = Box Option + Send + Sync>; lazy_static! { pub static ref DEFAULT_FUNCTIONS: HashMap<&'static str, FunctionImplementation> = { diff --git a/libraries/math-parser/src/context.rs b/libraries/math-parser/src/context.rs index b34dc6fbd..d6e4fe628 100644 --- a/libraries/math-parser/src/context.rs +++ b/libraries/math-parser/src/context.rs @@ -1,9 +1,6 @@ -use std::{ - collections::HashMap, - ops::{Deref, DerefMut}, -}; - use crate::value::Value; +use std::collections::HashMap; +use std::ops::{Deref, DerefMut}; //TODO: editor integration, implement these traits for whatever is needed, maybe merge them if needed pub trait ValueProvider { diff --git a/libraries/math-parser/src/executer.rs b/libraries/math-parser/src/executer.rs index ebac537b9..9d6180f1a 100644 --- a/libraries/math-parser/src/executer.rs +++ b/libraries/math-parser/src/executer.rs @@ -1,12 +1,9 @@ +use crate::ast::{Literal, Node}; +use crate::constants::DEFAULT_FUNCTIONS; +use crate::context::{EvalContext, FunctionProvider, ValueProvider}; +use crate::value::{Number, Value}; use thiserror::Error; -use crate::{ - ast::{Literal, Node}, - constants::DEFAULT_FUNCTIONS, - context::{EvalContext, FunctionProvider, ValueProvider}, - value::{Number, Value}, -}; - #[derive(Debug, Error)] pub enum EvalError { #[error("Missing value: {0}")] @@ -49,14 +46,12 @@ impl Node { #[cfg(test)] mod tests { - use crate::{ - ast::{BinaryOp, Literal, Node, UnaryOp}, - context::{EvalContext, ValueMap}, - value::Value, - }; + use crate::ast::{BinaryOp, Literal, Node, UnaryOp}; + use crate::context::{EvalContext, ValueMap}; + use crate::value::Value; macro_rules! eval_tests { - ($($name:ident: $expected:expr => $expr:expr),* $(,)?) => { + ($($name:ident: $expected:expr_2021 => $expr:expr_2021),* $(,)?) => { $( #[test] fn $name() { diff --git a/libraries/math-parser/src/lib.rs b/libraries/math-parser/src/lib.rs index e164de214..e596d78df 100644 --- a/libraries/math-parser/src/lib.rs +++ b/libraries/math-parser/src/lib.rs @@ -21,16 +21,14 @@ pub fn evaluate(expression: &str) -> Result<(Result, Unit), Pa #[cfg(test)] mod tests { - use value::Number; - - use ast::Unit; - use super::*; + use ast::Unit; + use value::Number; const EPSILON: f64 = 1e-10_f64; macro_rules! test_end_to_end{ - ($($name:ident: $input:expr => ($expected_value:expr, $expected_unit:expr)),* $(,)?) => { + ($($name:ident: $input:expr_2021 => ($expected_value:expr_2021, $expected_unit:expr_2021)),* $(,)?) => { $( #[test] fn $name() { diff --git a/libraries/math-parser/src/parser.rs b/libraries/math-parser/src/parser.rs index 796f19c53..101995d87 100644 --- a/libraries/math-parser/src/parser.rs +++ b/libraries/math-parser/src/parser.rs @@ -1,21 +1,15 @@ -use std::num::{ParseFloatError, ParseIntError}; - +use crate::ast::{BinaryOp, Literal, Node, UnaryOp, Unit}; +use crate::context::EvalContext; +use crate::value::{Complex, Number, Value}; use lazy_static::lazy_static; use num_complex::ComplexFloat; -use pest::{ - iterators::{Pair, Pairs}, - pratt_parser::{Assoc, Op, PrattParser}, - Parser, -}; +use pest::Parser; +use pest::iterators::{Pair, Pairs}; +use pest::pratt_parser::{Assoc, Op, PrattParser}; use pest_derive::Parser; +use std::num::{ParseFloatError, ParseIntError}; use thiserror::Error; -use crate::{ - ast::{BinaryOp, Literal, Node, UnaryOp, Unit}, - context::EvalContext, - value::{Complex, Number, Value}, -}; - #[derive(Parser)] #[grammar = "./grammer.pest"] // Point to the grammar file struct ExprParser; @@ -321,7 +315,7 @@ fn parse_expr(pairs: Pairs) -> Result<(Node, NodeMetadata), ParseError> { mod tests { use super::*; macro_rules! test_parser { - ($($name:ident: $input:expr => $expected:expr),* $(,)?) => { + ($($name:ident: $input:expr_2021 => $expected:expr_2021),* $(,)?) => { $( #[test] fn $name() { diff --git a/libraries/math-parser/src/value.rs b/libraries/math-parser/src/value.rs index 959c36c15..3577f3ea6 100644 --- a/libraries/math-parser/src/value.rs +++ b/libraries/math-parser/src/value.rs @@ -1,8 +1,6 @@ -use std::f64::consts::PI; - -use num_complex::ComplexFloat; - use crate::ast::{BinaryOp, UnaryOp}; +use num_complex::ComplexFloat; +use std::f64::consts::PI; pub type Complex = num_complex::Complex; diff --git a/libraries/path-bool/Cargo.toml b/libraries/path-bool/Cargo.toml index 72eb97b75..40a779c56 100644 --- a/libraries/path-bool/Cargo.toml +++ b/libraries/path-bool/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "path-bool" version = "0.1.0" -rust-version = "1.81" +rust-version = "1.85" authors = ["Graphite Authors ", "Adam Platkevič"] -edition = "2021" +edition = "2024" keywords = [ "bezier", "curve", diff --git a/libraries/path-bool/benches/painted_dreams.rs b/libraries/path-bool/benches/painted_dreams.rs index c619143ff..8eb544028 100644 --- a/libraries/path-bool/benches/painted_dreams.rs +++ b/libraries/path-bool/benches/painted_dreams.rs @@ -1,4 +1,4 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; use path_bool::*; pub fn criterion_benchmark(c: &mut Criterion) { diff --git a/libraries/path-bool/benches/path_segment_intersection.rs b/libraries/path-bool/benches/path_segment_intersection.rs index 27519cf8e..227fb7ce0 100644 --- a/libraries/path-bool/benches/path_segment_intersection.rs +++ b/libraries/path-bool/benches/path_segment_intersection.rs @@ -1,4 +1,4 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; use glam::DVec2; use path_bool::*; diff --git a/libraries/path-bool/src/lib.rs b/libraries/path-bool/src/lib.rs index ba58a94a3..6aad88965 100644 --- a/libraries/path-bool/src/lib.rs +++ b/libraries/path-bool/src/lib.rs @@ -24,7 +24,7 @@ pub(crate) use util::*; pub use intersection_path_segment::path_segment_intersection; #[cfg(feature = "parsing")] pub use parsing::path_data::{path_from_path_data, path_to_path_data}; -pub use path_boolean::{path_boolean, BooleanError, FillRule, PathBooleanOperation, EPS}; +pub use path_boolean::{BooleanError, EPS, FillRule, PathBooleanOperation, path_boolean}; pub use path_segment::PathSegment; #[cfg(test)] diff --git a/libraries/path-bool/src/parsing/path_data.rs b/libraries/path-bool/src/parsing/path_data.rs index afc2f5e4a..6e6ed2a7d 100644 --- a/libraries/path-bool/src/parsing/path_data.rs +++ b/libraries/path-bool/src/parsing/path_data.rs @@ -1,6 +1,6 @@ -use crate::path::{path_from_commands, path_to_commands, Path}; -use crate::path_command::{AbsolutePathCommand, PathCommand, RelativePathCommand}; use crate::BooleanError; +use crate::path::{Path, path_from_commands, path_to_commands}; +use crate::path_command::{AbsolutePathCommand, PathCommand, RelativePathCommand}; use glam::DVec2; use regex::Regex; diff --git a/libraries/path-bool/src/path.rs b/libraries/path-bool/src/path.rs index 0654506df..283f22e28 100644 --- a/libraries/path-bool/src/path.rs +++ b/libraries/path-bool/src/path.rs @@ -7,7 +7,7 @@ pub(crate) mod path_segment; use glam::DVec2; #[cfg(feature = "parsing")] -use crate::path_command::{to_absolute_commands, AbsolutePathCommand, PathCommand}; +use crate::path_command::{AbsolutePathCommand, PathCommand, to_absolute_commands}; use crate::path_segment::PathSegment; pub type Path = Vec; @@ -107,7 +107,7 @@ where let start = seg.start(); let mut commands = Vec::new(); - if last_point.map_or(true, |lp| !start.abs_diff_eq(lp, eps)) { + if last_point.is_none_or(|lp| !start.abs_diff_eq(lp, eps)) { if last_point.is_some() { commands.push(PathCommand::Absolute(AbsolutePathCommand::Z)); } diff --git a/libraries/path-bool/src/path/intersection_path_segment.rs b/libraries/path-bool/src/path/intersection_path_segment.rs index 4a4b53bf7..74559fd5f 100644 --- a/libraries/path-bool/src/path/intersection_path_segment.rs +++ b/libraries/path-bool/src/path/intersection_path_segment.rs @@ -1,10 +1,9 @@ -use crate::aabb::{bounding_box_max_extent, bounding_boxes_overlap, Aabb}; +use crate::aabb::{Aabb, bounding_box_max_extent, bounding_boxes_overlap}; use crate::epsilons::Epsilons; use crate::line_segment::{line_segment_intersection, line_segments_intersect}; use crate::line_segment_aabb::line_segment_aabb_intersect; use crate::math::lerp; use crate::path_segment::PathSegment; - use glam::DVec2; #[derive(Clone)] diff --git a/libraries/path-bool/src/path/line_segment.rs b/libraries/path-bool/src/path/line_segment.rs index ecabd1ebf..6b76a09f7 100644 --- a/libraries/path-bool/src/path/line_segment.rs +++ b/libraries/path-bool/src/path/line_segment.rs @@ -21,11 +21,7 @@ pub fn line_segment_intersection([p1, p2]: LineSegment, [p3, p4]: LineSegment, e let s = (c.x * b.y - c.y * b.x) / denom; let t = (a.x * c.y - a.y * c.x) / denom; - if (-eps..=1. + eps).contains(&s) && (-eps..=1. + eps).contains(&t) { - Some((s, t)) - } else { - None - } + if (-eps..=1. + eps).contains(&s) && (-eps..=1. + eps).contains(&t) { Some((s, t)) } else { None } } pub fn line_segments_intersect(seg1: LineSegment, seg2: LineSegment, eps: f64) -> bool { diff --git a/libraries/path-bool/src/path/path_segment.rs b/libraries/path-bool/src/path/path_segment.rs index 532e1c078..f3246d8f1 100644 --- a/libraries/path-bool/src/path/path_segment.rs +++ b/libraries/path-bool/src/path/path_segment.rs @@ -9,13 +9,12 @@ //! The implementations in this module closely follow the SVG path specification, //! making it suitable for use in vector graphics applications. +use crate::EPS; +use crate::aabb::{Aabb, bounding_box_around_point, expand_bounding_box, extend_bounding_box, merge_bounding_boxes}; +use crate::math::{lerp, vector_angle}; use glam::{DMat2, DMat3, DVec2}; use std::f64::consts::{PI, TAU}; -use crate::aabb::{bounding_box_around_point, expand_bounding_box, extend_bounding_box, merge_bounding_boxes, Aabb}; -use crate::math::{lerp, vector_angle}; -use crate::EPS; - /// Represents a segment of a path in a 2D space, based on the SVG path specification. /// /// This enum closely follows the path segment types defined in the SVG 2 specification. @@ -155,11 +154,7 @@ impl PathSegment { let b = 6. * b; let numerator = a.x * b.y - a.y * b.x; let denominator = a.length_squared() * a.length(); - if denominator == 0. { - 0. - } else { - numerator / denominator - } + if denominator == 0. { 0. } else { numerator / denominator } } PathSegment::Quadratic(start, control, end) => { // First derivative @@ -168,11 +163,7 @@ impl PathSegment { let b = 2. * (start - 2. * control + end); let numerator = a.x * b.y - a.y * b.x; let denominator = a.length_squared() * a.length(); - if denominator == 0. { - 0. - } else { - numerator / denominator - } + if denominator == 0. { 0. } else { numerator / denominator } } PathSegment::Arc(..) => self.arc_segment_to_cubics(0.001)[0].start_curvature(), } diff --git a/libraries/path-bool/src/path_boolean.rs b/libraries/path-bool/src/path_boolean.rs index f8c89271c..c426b0db8 100644 --- a/libraries/path-bool/src/path_boolean.rs +++ b/libraries/path-bool/src/path_boolean.rs @@ -63,7 +63,7 @@ new_key_type! { // // SPDX-License-Identifier: MIT -use crate::aabb::{bounding_box_around_point, bounding_box_max_extent, merge_bounding_boxes, Aabb}; +use crate::aabb::{Aabb, bounding_box_around_point, bounding_box_max_extent, merge_bounding_boxes}; use crate::epsilons::Epsilons; use crate::intersection_path_segment::{path_segment_intersection, segments_equal}; use crate::path::Path; @@ -72,9 +72,8 @@ use crate::path_segment::PathSegment; #[cfg(feature = "logging")] use crate::path_to_path_data; use crate::quad_tree::QuadTree; - use glam::DVec2; -use slotmap::{new_key_type, SlotMap}; +use slotmap::{SlotMap, new_key_type}; use std::cmp::Ordering; use std::collections::{HashMap, HashSet, VecDeque}; use std::fmt::Display; @@ -1090,7 +1089,11 @@ fn compute_dual(minor_graph: &MinorGraph) -> Result { let (key, _) = *areas.iter().max_by_key(|(_, area)| ((area.abs() * 1000.) as u64)).unwrap(); *key } else { - *windings.iter().find(|(&_, winding)| (winding < &0) ^ reverse_winding).expect("No outer face of a component found.").0 + *windings + .iter() + .find(|&&(&_, ref winding)| (winding < &0) ^ reverse_winding) + .expect("No outer face of a component found.") + .0 }; #[cfg(feature = "logging")] dbg!(outer_face_key); @@ -1338,7 +1341,7 @@ fn get_selected_faces<'a>(predicate: &'a impl Fn(u8) -> bool, flags: &'a HashMap flags.iter().filter_map(|(key, &flag)| predicate(flag).then_some(*key)) } -fn walk_faces<'a>(faces: &'a [DualVertexKey], edges: &SlotMap, vertices: &SlotMap) -> impl Iterator + 'a { +fn walk_faces<'a>(faces: &'a [DualVertexKey], edges: &SlotMap, vertices: &SlotMap) -> impl Iterator + use<'a> { let face_set: HashSet<_> = faces.iter().copied().collect(); // TODO: Try using a binary search to avoid the hashset construction let is_removed_edge = |edge: &DualGraphHalfEdge| face_set.contains(&edge.incident_vertex) == face_set.contains(&edges[edge.twin.unwrap()].incident_vertex); diff --git a/libraries/path-bool/src/visual_tests.rs b/libraries/path-bool/src/visual_tests.rs index 2c9aa9f40..e765768aa 100644 --- a/libraries/path-bool/src/visual_tests.rs +++ b/libraries/path-bool/src/visual_tests.rs @@ -1,6 +1,5 @@ use crate::path_boolean::{self, FillRule, PathBooleanOperation}; use crate::path_data::{path_from_path_data, path_to_path_data}; - use core::panic; use glob::glob; use image::{DynamicImage, GenericImageView, RgbaImage}; diff --git a/libraries/rawkit/Cargo.toml b/libraries/rawkit/Cargo.toml index 646fa5ba1..30a0d2d0a 100644 --- a/libraries/rawkit/Cargo.toml +++ b/libraries/rawkit/Cargo.toml @@ -9,7 +9,7 @@ syn = "2.0.87" [package] name = "rawkit" version = "0.1.0" -edition = "2021" +edition = "2024" authors = ["Graphite Authors "] description = "A library to extract images from camera raw files" license = "MIT OR Apache-2.0" diff --git a/libraries/rawkit/rawkit-proc-macros/Cargo.toml b/libraries/rawkit/rawkit-proc-macros/Cargo.toml index 5e1ede3cf..6fd8a540c 100644 --- a/libraries/rawkit/rawkit-proc-macros/Cargo.toml +++ b/libraries/rawkit/rawkit-proc-macros/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rawkit-proc-macros" version = "0.1.0" -edition = "2021" +edition = "2024" authors = ["Graphite Authors "] description = "Procedural macros for Rawkit" license = "MIT OR Apache-2.0" diff --git a/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs b/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs index ccbfdf45b..214835283 100644 --- a/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs +++ b/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs @@ -1,9 +1,8 @@ use proc_macro::TokenStream; -use quote::{quote, ToTokens}; -use toml::{Table, Value}; - +use quote::{ToTokens, quote}; use std::fs; use std::path::Path; +use toml::{Table, Value}; enum CustomValue { String(String), diff --git a/libraries/rawkit/rawkit-proc-macros/src/tag_derive.rs b/libraries/rawkit/rawkit-proc-macros/src/tag_derive.rs index 00c818fdb..ddfed688b 100644 --- a/libraries/rawkit/rawkit-proc-macros/src/tag_derive.rs +++ b/libraries/rawkit/rawkit-proc-macros/src/tag_derive.rs @@ -24,7 +24,7 @@ pub fn tag_derive(input: TokenStream) -> TokenStream { let new_name = format_ident!("_{}", name); - let gen = quote! { + let r#gen = quote! { struct #new_name { #( #struct_idents: <#struct_types as Tag>::Output ),* } @@ -39,5 +39,5 @@ pub fn tag_derive(input: TokenStream) -> TokenStream { } }; - gen.into() + r#gen.into() } diff --git a/libraries/rawkit/src/decoder/arw1.rs b/libraries/rawkit/src/decoder/arw1.rs index 9023796a4..7bf668254 100644 --- a/libraries/rawkit/src/decoder/arw1.rs +++ b/libraries/rawkit/src/decoder/arw1.rs @@ -1,9 +1,8 @@ +use crate::tiff::Ifd; use crate::tiff::file::TiffRead; use crate::tiff::tags::SonyDataOffset; -use crate::tiff::Ifd; use crate::{RawImage, SubtractBlack, Transform}; - -use bitstream_io::{BitRead, BitReader, Endianness, BE}; +use bitstream_io::{BE, BitRead, BitReader, Endianness}; use std::io::{Read, Seek}; pub fn decode_a100(ifd: Ifd, file: &mut TiffRead) -> RawImage { @@ -63,11 +62,7 @@ fn ljpeg_diff(huff: &[u16], file: &mut BitReader< let diff = read_n_bits_from_file(length, file) as i32; - if length == 0 || (diff & (1 << (length - 1))) == 0 { - diff - (1 << length) - 1 - } else { - diff - } + if length == 0 || (diff & (1 << (length - 1))) == 0 { diff - (1 << length) - 1 } else { diff } } fn sony_arw_load_raw(width: usize, height: usize, file: &mut BitReader) -> Option> { diff --git a/libraries/rawkit/src/decoder/arw2.rs b/libraries/rawkit/src/decoder/arw2.rs index 0e677b7ef..676880f1f 100644 --- a/libraries/rawkit/src/decoder/arw2.rs +++ b/libraries/rawkit/src/decoder/arw2.rs @@ -3,7 +3,6 @@ use crate::tiff::tags::{BitsPerSample, CfaPattern, CfaPatternDim, Compression, I use crate::tiff::values::CurveLookupTable; use crate::tiff::{Ifd, TiffError}; use crate::{RawImage, SubtractBlack, Transform}; - use rawkit_proc_macros::Tag; use std::io::{Read, Seek}; diff --git a/libraries/rawkit/src/decoder/uncompressed.rs b/libraries/rawkit/src/decoder/uncompressed.rs index 48f4831d4..cd8ca51f5 100644 --- a/libraries/rawkit/src/decoder/uncompressed.rs +++ b/libraries/rawkit/src/decoder/uncompressed.rs @@ -2,7 +2,6 @@ use crate::tiff::file::TiffRead; use crate::tiff::tags::{BitsPerSample, BlackLevel, CfaPattern, CfaPatternDim, Compression, ImageLength, ImageWidth, RowsPerStrip, StripByteCounts, StripOffsets, Tag, WhiteBalanceRggbLevels}; use crate::tiff::{Ifd, TiffError}; use crate::{RawImage, SubtractBlack, Transform}; - use rawkit_proc_macros::Tag; use std::io::{Read, Seek}; diff --git a/libraries/rawkit/src/lib.rs b/libraries/rawkit/src/lib.rs index acc84ae1e..d20c5f9b4 100644 --- a/libraries/rawkit/src/lib.rs +++ b/libraries/rawkit/src/lib.rs @@ -7,17 +7,15 @@ pub mod processing; pub mod tiff; use crate::metadata::identify::CameraModel; - use processing::{Pixel, PixelTransform, RawPixel, RawPixelTransform}; use rawkit_proc_macros::Tag; +use std::io::{Read, Seek}; +use thiserror::Error; use tiff::file::TiffRead; use tiff::tags::{Compression, ImageLength, ImageWidth, Orientation, StripByteCounts, SubIfd, Tag}; use tiff::values::Transform; use tiff::{Ifd, TiffError}; -use std::io::{Read, Seek}; -use thiserror::Error; - pub(crate) const CHANNELS_IN_RGB: usize = 3; pub(crate) type Histogram = [[usize; 0x2000]; CHANNELS_IN_RGB]; diff --git a/libraries/rawkit/src/metadata/identify.rs b/libraries/rawkit/src/metadata/identify.rs index 6d57da34b..f9bc28632 100644 --- a/libraries/rawkit/src/metadata/identify.rs +++ b/libraries/rawkit/src/metadata/identify.rs @@ -1,7 +1,6 @@ use crate::tiff::file::TiffRead; use crate::tiff::tags::{Make, Model, Tag}; use crate::tiff::{Ifd, TiffError}; - use rawkit_proc_macros::Tag; use std::io::{Read, Seek}; diff --git a/libraries/rawkit/src/postprocessing/convert_to_rgb.rs b/libraries/rawkit/src/postprocessing/convert_to_rgb.rs index 75918f8b2..50f95f051 100644 --- a/libraries/rawkit/src/postprocessing/convert_to_rgb.rs +++ b/libraries/rawkit/src/postprocessing/convert_to_rgb.rs @@ -1,7 +1,7 @@ -use crate::{Pixel, RawImage, CHANNELS_IN_RGB}; +use crate::{CHANNELS_IN_RGB, Pixel, RawImage}; impl RawImage { - pub fn convert_to_rgb_fn(&self) -> impl Fn(Pixel) -> [u16; CHANNELS_IN_RGB] { + pub fn convert_to_rgb_fn(&self) -> impl Fn(Pixel) -> [u16; CHANNELS_IN_RGB] + use<> { let Some(camera_to_rgb) = self.camera_to_rgb else { todo!() }; move |pixel: Pixel| { diff --git a/libraries/rawkit/src/postprocessing/gamma_correction.rs b/libraries/rawkit/src/postprocessing/gamma_correction.rs index 99110602c..86f5d6725 100644 --- a/libraries/rawkit/src/postprocessing/gamma_correction.rs +++ b/libraries/rawkit/src/postprocessing/gamma_correction.rs @@ -1,8 +1,8 @@ -use crate::{Histogram, Image, Pixel, CHANNELS_IN_RGB}; +use crate::{CHANNELS_IN_RGB, Histogram, Image, Pixel}; use std::f64::consts::E; impl Image { - pub fn gamma_correction_fn(&self, histogram: &Histogram) -> impl Fn(Pixel) -> [u16; CHANNELS_IN_RGB] { + pub fn gamma_correction_fn(&self, histogram: &Histogram) -> impl Fn(Pixel) -> [u16; CHANNELS_IN_RGB] + use<> { let percentage = self.width * self.height; let mut white = 0; diff --git a/libraries/rawkit/src/postprocessing/record_histogram.rs b/libraries/rawkit/src/postprocessing/record_histogram.rs index d484b7bd5..3b22a3ffb 100644 --- a/libraries/rawkit/src/postprocessing/record_histogram.rs +++ b/libraries/rawkit/src/postprocessing/record_histogram.rs @@ -1,4 +1,4 @@ -use crate::{Histogram, Pixel, PixelTransform, RawImage, CHANNELS_IN_RGB}; +use crate::{CHANNELS_IN_RGB, Histogram, Pixel, PixelTransform, RawImage}; impl RawImage { pub fn record_histogram_fn(&self) -> RecordHistogram { diff --git a/libraries/rawkit/src/preprocessing/scale_to_16bit.rs b/libraries/rawkit/src/preprocessing/scale_to_16bit.rs index 7f7ad87cd..bf7fce70b 100644 --- a/libraries/rawkit/src/preprocessing/scale_to_16bit.rs +++ b/libraries/rawkit/src/preprocessing/scale_to_16bit.rs @@ -1,7 +1,7 @@ use crate::{RawImage, RawPixel, SubtractBlack}; impl RawImage { - pub fn scale_to_16bit_fn(&self) -> impl Fn(RawPixel) -> u16 { + pub fn scale_to_16bit_fn(&self) -> impl Fn(RawPixel) -> u16 + use<> { let black_level = match self.black { SubtractBlack::CfaGrid(x) => x, _ => unreachable!(), diff --git a/libraries/rawkit/src/preprocessing/scale_white_balance.rs b/libraries/rawkit/src/preprocessing/scale_white_balance.rs index f81660a7c..34ce6a114 100644 --- a/libraries/rawkit/src/preprocessing/scale_white_balance.rs +++ b/libraries/rawkit/src/preprocessing/scale_white_balance.rs @@ -1,7 +1,7 @@ use crate::{RawImage, RawPixel}; impl RawImage { - pub fn scale_white_balance_fn(&self) -> impl Fn(RawPixel) -> u16 { + pub fn scale_white_balance_fn(&self) -> impl Fn(RawPixel) -> u16 + use<> { let Some(mut white_balance) = self.white_balance else { todo!() }; if white_balance[1] == 0. { diff --git a/libraries/rawkit/src/preprocessing/subtract_black.rs b/libraries/rawkit/src/preprocessing/subtract_black.rs index b4e368eb3..8a28c5676 100644 --- a/libraries/rawkit/src/preprocessing/subtract_black.rs +++ b/libraries/rawkit/src/preprocessing/subtract_black.rs @@ -2,7 +2,7 @@ use crate::RawPixel; use crate::{RawImage, SubtractBlack}; impl RawImage { - pub fn subtract_black_fn(&self) -> impl Fn(RawPixel) -> u16 { + pub fn subtract_black_fn(&self) -> impl Fn(RawPixel) -> u16 + use<> { match self.black { SubtractBlack::CfaGrid(black_levels) => move |pixel: RawPixel| pixel.value.saturating_sub(black_levels[2 * (pixel.row % 2) + (pixel.column % 2)]), _ => todo!(), diff --git a/libraries/rawkit/src/tiff/mod.rs b/libraries/rawkit/src/tiff/mod.rs index 0eff5b619..f9a366a2b 100644 --- a/libraries/rawkit/src/tiff/mod.rs +++ b/libraries/rawkit/src/tiff/mod.rs @@ -4,11 +4,10 @@ mod types; pub mod values; use file::TiffRead; -use tags::Tag; - use num_enum::{FromPrimitive, IntoPrimitive}; use std::fmt::Display; use std::io::{Read, Seek}; +use tags::Tag; use thiserror::Error; #[derive(Copy, Clone, Debug, PartialEq, Eq, FromPrimitive, IntoPrimitive)] diff --git a/libraries/rawkit/src/tiff/tags.rs b/libraries/rawkit/src/tiff/tags.rs index 8d3e6f669..76eebb918 100644 --- a/libraries/rawkit/src/tiff/tags.rs +++ b/libraries/rawkit/src/tiff/tags.rs @@ -1,6 +1,5 @@ use super::types::{Array, ConstArray, TagType, TypeByte, TypeIfd, TypeLong, TypeNumber, TypeOrientation, TypeSRational, TypeSShort, TypeShort, TypeSonyToneCurve, TypeString}; use super::{Ifd, TagId, TiffError, TiffRead}; - use std::io::{Read, Seek}; pub trait SimpleTag { diff --git a/libraries/rawkit/src/tiff/types.rs b/libraries/rawkit/src/tiff/types.rs index 4533f6b38..1bac61a79 100644 --- a/libraries/rawkit/src/tiff/types.rs +++ b/libraries/rawkit/src/tiff/types.rs @@ -1,8 +1,7 @@ -use std::io::{Read, Seek}; - use super::file::TiffRead; use super::values::{CurveLookupTable, Rational, Transform}; use super::{Ifd, IfdTagType, TiffError}; +use std::io::{Read, Seek}; pub struct TypeAscii; pub struct TypeByte; @@ -41,11 +40,7 @@ impl PrimitiveType for TypeAscii { fn read_primitive(_: IfdTagType, file: &mut TiffRead) -> Result { let value = file.read_ascii()?; - if value.is_ascii() { - Ok(value) - } else { - Err(TiffError::InvalidValue) - } + if value.is_ascii() { Ok(value) } else { Err(TiffError::InvalidValue) } } } diff --git a/libraries/rawkit/tests/tests.rs b/libraries/rawkit/tests/tests.rs index dfb0c0984..7cdc5d32c 100644 --- a/libraries/rawkit/tests/tests.rs +++ b/libraries/rawkit/tests/tests.rs @@ -1,15 +1,14 @@ // Only compile this file if the feature "rawkit-tests" is enabled #![cfg(feature = "rawkit-tests")] -use rawkit::RawImage; - use image::codecs::png::{CompressionType, FilterType, PngEncoder}; use image::{ColorType, ImageEncoder}; use libraw::Processor; +use rawkit::RawImage; use rayon::prelude::*; use std::collections::HashMap; use std::fmt::Write; -use std::fs::{create_dir, metadata, read_dir, File}; +use std::fs::{File, create_dir, metadata, read_dir}; use std::io::{BufWriter, Cursor, Read}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -338,10 +337,10 @@ fn extract_data_from_dng_images() { } fn extract_data_from_dng_image(path: &Path) { + use rawkit::tiff::Ifd; use rawkit::tiff::file::TiffRead; use rawkit::tiff::tags::{ColorMatrix2, Make, Model}; use rawkit::tiff::values::ToFloat; - use rawkit::tiff::Ifd; use std::io::{BufReader, Write}; let reader = BufReader::new(File::open(path).unwrap()); diff --git a/node-graph/compilation-client/Cargo.toml b/node-graph/compilation-client/Cargo.toml index eec701d04..466f8110f 100644 --- a/node-graph/compilation-client/Cargo.toml +++ b/node-graph/compilation-client/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "compilation-client" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" [dependencies] diff --git a/node-graph/compilation-client/src/lib.rs b/node-graph/compilation-client/src/lib.rs index 2e2e83e8a..192ef53d5 100644 --- a/node-graph/compilation-client/src/lib.rs +++ b/node-graph/compilation-client/src/lib.rs @@ -1,5 +1,6 @@ use gpu_compiler_bin_wrapper::CompileRequest; -use graph_craft::{proto::ProtoNetwork, Type}; +use graph_craft::Type; +use graph_craft::proto::ProtoNetwork; use wgpu_executor::ShaderIO; pub async fn compile(networks: Vec, inputs: Vec, outputs: Vec, io: ShaderIO) -> Result { diff --git a/node-graph/compilation-client/src/main.rs b/node-graph/compilation-client/src/main.rs index 7d1dc662a..0c7a771ac 100644 --- a/node-graph/compilation-client/src/main.rs +++ b/node-graph/compilation-client/src/main.rs @@ -2,11 +2,10 @@ use gpu_compiler_bin_wrapper::CompileRequest; use graph_craft::concrete; use graph_craft::document::value::TaggedValue; use graph_craft::document::*; -use graphene_core::raster::adjustments::BlendMode; use graphene_core::Color; -use wgpu_executor::{ShaderIO, ShaderInput}; - +use graphene_core::raster::adjustments::BlendMode; use std::time::Duration; +use wgpu_executor::{ShaderIO, ShaderInput}; fn main() { let client = reqwest::blocking::Client::new(); diff --git a/node-graph/compilation-server/Cargo.toml b/node-graph/compilation-server/Cargo.toml index 4059c399a..4dbf81b9e 100644 --- a/node-graph/compilation-server/Cargo.toml +++ b/node-graph/compilation-server/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "compilation-server" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" [dependencies] diff --git a/node-graph/compilation-server/src/main.rs b/node-graph/compilation-server/src/main.rs index 54379de50..0ad46e847 100644 --- a/node-graph/compilation-server/src/main.rs +++ b/node-graph/compilation-server/src/main.rs @@ -1,15 +1,13 @@ -use std::{collections::HashMap, sync::Arc, sync::RwLock}; - +use axum::Router; +use axum::extract::{Json, State}; +use axum::http::StatusCode; +use axum::routing::{get, post}; use gpu_compiler_bin_wrapper::CompileRequest; +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::RwLock; use tower_http::cors::CorsLayer; -use axum::{ - extract::{Json, State}, - http::StatusCode, - routing::{get, post}, - Router, -}; - struct AppState { compile_dir: tempfile::TempDir, cache: RwLock, StatusCode>>>, diff --git a/node-graph/gcore/Cargo.toml b/node-graph/gcore/Cargo.toml index 8543e6ad2..d9c450194 100644 --- a/node-graph/gcore/Cargo.toml +++ b/node-graph/gcore/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "graphene-core" version = "0.1.0" -edition = "2021" +edition = "2024" description = "API definitions for Graphene" authors = ["Graphite Authors "] license = "MIT OR Apache-2.0" diff --git a/node-graph/gcore/src/application_io.rs b/node-graph/gcore/src/application_io.rs index e7787a8ca..a47373cb0 100644 --- a/node-graph/gcore/src/application_io.rs +++ b/node-graph/gcore/src/application_io.rs @@ -2,15 +2,13 @@ use crate::instances::Instances; use crate::text::FontCache; use crate::transform::{Footprint, Transform, TransformMut}; use crate::vector::style::ViewMode; - -use dyn_any::{DynAny, StaticType, StaticTypeSized}; - use alloc::sync::Arc; use core::fmt::Debug; use core::future::Future; use core::hash::{Hash, Hasher}; use core::pin::Pin; use core::ptr::addr_of; +use dyn_any::{DynAny, StaticType, StaticTypeSized}; use glam::{DAffine2, UVec2}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/node-graph/gcore/src/context.rs b/node-graph/gcore/src/context.rs index 3e21d722a..7448cd901 100644 --- a/node-graph/gcore/src/context.rs +++ b/node-graph/gcore/src/context.rs @@ -1,6 +1,7 @@ use crate::transform::Footprint; - -use core::{any::Any, borrow::Borrow, panic::Location}; +use core::any::Any; +use core::borrow::Borrow; +use core::panic::Location; use std::sync::Arc; pub trait Ctx: Clone + Send {} @@ -87,12 +88,12 @@ impl ExtractIndex for Option { } impl ExtractVarArgs for Option { fn vararg(&self, index: usize) -> Result, VarArgsResult> { - let Some(ref inner) = self else { return Err(VarArgsResult::NoVarArgs) }; + let Some(inner) = self else { return Err(VarArgsResult::NoVarArgs) }; inner.vararg(index) } fn varargs_len(&self) -> Result { - let Some(ref inner) = self else { return Err(VarArgsResult::NoVarArgs) }; + let Some(inner) = self else { return Err(VarArgsResult::NoVarArgs) }; inner.varargs_len() } } diff --git a/node-graph/gcore/src/generic.rs b/node-graph/gcore/src/generic.rs index bd82d3f08..c3a289a35 100644 --- a/node-graph/gcore/src/generic.rs +++ b/node-graph/gcore/src/generic.rs @@ -1,6 +1,5 @@ -use core::marker::PhantomData; - use crate::Node; +use core::marker::PhantomData; #[derive(Clone)] pub struct FnNode O, I, O>(T, PhantomData<(I, O)>); diff --git a/node-graph/gcore/src/gpu.rs b/node-graph/gcore/src/gpu.rs index c6405818a..1bc59f21e 100644 --- a/node-graph/gcore/src/gpu.rs +++ b/node-graph/gcore/src/gpu.rs @@ -1,5 +1,5 @@ -use crate::{raster::Sample, Color}; - +use crate::Color; +use crate::raster::Sample; use bytemuck::{Pod, Zeroable}; use spirv_std::image::{Image2d, SampledImage}; diff --git a/node-graph/gcore/src/graphic_element.rs b/node-graph/gcore/src/graphic_element.rs index ad7e75ada..030ccc8d6 100644 --- a/node-graph/gcore/src/graphic_element.rs +++ b/node-graph/gcore/src/graphic_element.rs @@ -1,14 +1,12 @@ use crate::application_io::{ImageTexture, TextureFrameTable}; use crate::instances::Instances; -use crate::raster::image::{Image, ImageFrameTable}; use crate::raster::BlendMode; +use crate::raster::image::{Image, ImageFrameTable}; use crate::transform::TransformMut; use crate::uuid::NodeId; use crate::vector::{VectorData, VectorDataTable}; use crate::{CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl}; - use dyn_any::DynAny; - use glam::{DAffine2, IVec2}; use std::hash::Hash; diff --git a/node-graph/gcore/src/graphic_element/renderer.rs b/node-graph/gcore/src/graphic_element/renderer.rs index 270b3299c..7a4fa7beb 100644 --- a/node-graph/gcore/src/graphic_element/renderer.rs +++ b/node-graph/gcore/src/graphic_element/renderer.rs @@ -1,22 +1,20 @@ mod quad; mod rect; -pub use quad::Quad; -pub use rect::Rect; use crate::raster::image::ImageFrameTable; use crate::raster::{BlendMode, Image}; use crate::transform::{Footprint, Transform}; -use crate::uuid::{generate_uuid, NodeId}; +use crate::uuid::{NodeId, generate_uuid}; use crate::vector::style::{Fill, Stroke, ViewMode}; use crate::vector::{PointId, VectorDataTable}; use crate::{Artboard, ArtboardGroupTable, Color, GraphicElement, GraphicGroupTable, RasterFrame}; - +use base64::Engine; use bezier_rs::Subpath; use dyn_any::DynAny; - -use base64::Engine; use glam::{DAffine2, DMat2, DVec2}; use num_traits::Zero; +pub use quad::Quad; +pub use rect::Rect; use std::collections::{HashMap, HashSet}; use std::fmt::Write; #[cfg(feature = "vello")] @@ -883,7 +881,7 @@ impl GraphicElementRendered for ImageFrameTable { impl GraphicElementRendered for RasterFrame { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { match self { - RasterFrame::ImageFrame(ref image) => image.render_svg(render, render_params), + RasterFrame::ImageFrame(image) => image.render_svg(render, render_params), RasterFrame::TextureFrame(_) => unimplemented!(), } } diff --git a/node-graph/gcore/src/graphic_element/renderer/rect.rs b/node-graph/gcore/src/graphic_element/renderer/rect.rs index f3af91ad3..a2e9bcf5c 100644 --- a/node-graph/gcore/src/graphic_element/renderer/rect.rs +++ b/node-graph/gcore/src/graphic_element/renderer/rect.rs @@ -1,6 +1,5 @@ -use glam::{DAffine2, DVec2}; - use super::Quad; +use glam::{DAffine2, DVec2}; #[derive(Debug, Clone, Default, Copy, PartialEq)] /// An axis aligned rect defined by two vertices. diff --git a/node-graph/gcore/src/instances.rs b/node-graph/gcore/src/instances.rs index 9a1f7ebe9..c11e29627 100644 --- a/node-graph/gcore/src/instances.rs +++ b/node-graph/gcore/src/instances.rs @@ -1,13 +1,11 @@ use crate::application_io::TextureFrameTable; -use crate::raster::image::{Image, ImageFrameTable}; use crate::raster::Pixel; +use crate::raster::image::{Image, ImageFrameTable}; use crate::transform::{Transform, TransformMut}; use crate::uuid::NodeId; use crate::vector::{InstanceId, VectorDataTable}; use crate::{AlphaBlending, GraphicElement, RasterFrame}; - use dyn_any::StaticType; - use glam::DAffine2; use std::hash::Hash; diff --git a/node-graph/gcore/src/logic.rs b/node-graph/gcore/src/logic.rs index 2abdc723e..e3a798d20 100644 --- a/node-graph/gcore/src/logic.rs +++ b/node-graph/gcore/src/logic.rs @@ -1,6 +1,6 @@ -use crate::vector::VectorDataTable; use crate::Context; use crate::Ctx; +use crate::vector::VectorDataTable; use glam::{DAffine2, DVec2}; #[node_macro::node(category("Debug"))] diff --git a/node-graph/gcore/src/memo.rs b/node-graph/gcore/src/memo.rs index 83193b709..cdea7b634 100644 --- a/node-graph/gcore/src/memo.rs +++ b/node-graph/gcore/src/memo.rs @@ -1,11 +1,9 @@ use crate::{Node, WasmNotSend}; - -use dyn_any::DynFuture; - #[cfg(feature = "alloc")] use alloc::sync::Arc; use core::future::Future; use core::ops::Deref; +use dyn_any::DynFuture; use std::hash::DefaultHasher; use std::sync::Mutex; diff --git a/node-graph/gcore/src/ops.rs b/node-graph/gcore/src/ops.rs index 36bdd0070..3dc9f6a28 100644 --- a/node-graph/gcore/src/ops.rs +++ b/node-graph/gcore/src/ops.rs @@ -1,17 +1,15 @@ -use crate::raster::image::ImageFrameTable; +use crate::Ctx; use crate::raster::BlendMode; +use crate::raster::image::ImageFrameTable; use crate::registry::types::Percentage; use crate::vector::style::GradientStops; -use crate::Ctx; use crate::{Color, Node}; - -use math_parser::ast; -use math_parser::context::{EvalContext, NothingMap, ValueProvider}; -use math_parser::value::{Number, Value}; - use core::marker::PhantomData; use core::ops::{Add, Div, Mul, Rem, Sub}; use glam::DVec2; +use math_parser::ast; +use math_parser::context::{EvalContext, NothingMap, ValueProvider}; +use math_parser::value::{Number, Value}; use num_traits::Pow; use rand::{Rng, SeedableRng}; @@ -136,11 +134,7 @@ fn modulo>>, T: Copy modulus: T, always_positive: bool, ) -> >::Output { - if always_positive { - (numerator % modulus + modulus) % modulus - } else { - numerator % modulus - } + if always_positive { (numerator % modulus + modulus) % modulus } else { numerator % modulus } } /// The exponent operation (^) calculates the result of raising a number to a power. @@ -198,61 +192,37 @@ fn logarithm( /// The sine trigonometric function (sin) calculates the ratio of the angle's opposite side length to its hypotenuse length. #[node_macro::node(category("Math: Trig"))] fn sine(_: impl Ctx, #[implementations(f64, f32)] theta: U, radians: bool) -> U { - if radians { - theta.sin() - } else { - theta.to_radians().sin() - } + if radians { theta.sin() } else { theta.to_radians().sin() } } /// The cosine trigonometric function (cos) calculates the ratio of the angle's adjacent side length to its hypotenuse length. #[node_macro::node(category("Math: Trig"))] fn cosine(_: impl Ctx, #[implementations(f64, f32)] theta: U, radians: bool) -> U { - if radians { - theta.cos() - } else { - theta.to_radians().cos() - } + if radians { theta.cos() } else { theta.to_radians().cos() } } /// The tangent trigonometric function (tan) calculates the ratio of the angle's opposite side length to its adjacent side length. #[node_macro::node(category("Math: Trig"))] fn tangent(_: impl Ctx, #[implementations(f64, f32)] theta: U, radians: bool) -> U { - if radians { - theta.tan() - } else { - theta.to_radians().tan() - } + if radians { theta.tan() } else { theta.to_radians().tan() } } /// The inverse sine trigonometric function (asin) calculates the angle whose sine is the specified value. #[node_macro::node(category("Math: Trig"))] fn sine_inverse(_: impl Ctx, #[implementations(f64, f32)] value: U, radians: bool) -> U { - if radians { - value.asin() - } else { - value.asin().to_degrees() - } + if radians { value.asin() } else { value.asin().to_degrees() } } /// The inverse cosine trigonometric function (acos) calculates the angle whose cosine is the specified value. #[node_macro::node(category("Math: Trig"))] fn cosine_inverse(_: impl Ctx, #[implementations(f64, f32)] value: U, radians: bool) -> U { - if radians { - value.acos() - } else { - value.acos().to_degrees() - } + if radians { value.acos() } else { value.acos().to_degrees() } } /// The inverse tangent trigonometric function (atan) calculates the angle whose tangent is the specified value. #[node_macro::node(category("Math: Trig"))] fn tangent_inverse(_: impl Ctx, #[implementations(f64, f32)] value: U, radians: bool) -> U { - if radians { - value.atan() - } else { - value.atan().to_degrees() - } + if radians { value.atan() } else { value.atan().to_degrees() } } /// The inverse tangent trigonometric function (atan2) calculates the angle whose tangent is the ratio of the two specified values. @@ -265,11 +235,7 @@ fn tangent_inverse_2_argument( x: U, radians: bool, ) -> U { - if radians { - y.atan2(x) - } else { - y.atan2(x).to_degrees() - } + if radians { y.atan2(x) } else { y.atan2(x).to_degrees() } } /// The random function (rand) converts a seed into a random number within the specified range, inclusive of the minimum and exclusive of the maximum. The minimum and maximum values are automatically swapped if they are reversed. diff --git a/node-graph/gcore/src/raster.rs b/node-graph/gcore/src/raster.rs index 0d34f0b0d..fbff52fe4 100644 --- a/node-graph/gcore/src/raster.rs +++ b/node-graph/gcore/src/raster.rs @@ -1,10 +1,9 @@ pub use self::color::{Color, Luma, SRGBA8}; +use crate::Ctx; +use crate::GraphicGroupTable; use crate::raster::image::ImageFrameTable; use crate::registry::types::Percentage; use crate::vector::VectorDataTable; -use crate::Ctx; -use crate::GraphicGroupTable; - use bytemuck::{Pod, Zeroable}; use core::fmt::Debug; use glam::DVec2; @@ -22,6 +21,7 @@ pub mod color; #[cfg(not(target_arch = "spirv"))] pub mod curve; pub mod discrete_srgb; + pub use adjustments::*; pub trait Linear { @@ -95,11 +95,7 @@ impl Channel for SRGBGammaFloat { #[inline(always)] fn from_linear(linear: In) -> Self { let x = linear.to_f32(); - if x <= 0.0031308 { - Self(x * 12.92) - } else { - Self(1.055 * x.powf(1. / 2.4) - 0.055) - } + if x <= 0.0031308 { Self(x * 12.92) } else { Self(1.055 * x.powf(1. / 2.4) - 0.055) } } } pub trait RGBPrimaries { diff --git a/node-graph/gcore/src/raster/adjustments.rs b/node-graph/gcore/src/raster/adjustments.rs index f96bc93fe..53cd412f5 100644 --- a/node-graph/gcore/src/raster/adjustments.rs +++ b/node-graph/gcore/src/raster/adjustments.rs @@ -6,15 +6,13 @@ use crate::raster::curve::{Curve, CurveManipulatorGroup, ValueMapperNode}; use crate::raster::image::{Image, ImageFrameTable}; use crate::raster::{Channel, Color, Pixel}; use crate::registry::types::{Angle, Percentage, SignedPercentage}; -use crate::vector::style::GradientStops; use crate::vector::VectorDataTable; +use crate::vector::style::GradientStops; use crate::{Ctx, Node}; use crate::{GraphicElement, GraphicGroupTable}; - -use dyn_any::DynAny; - use core::cmp::Ordering; use core::fmt::Debug; +use dyn_any::DynAny; #[cfg(feature = "serde")] #[cfg(target_arch = "spirv")] use spirv_std::num_traits::float::Float; @@ -574,11 +572,7 @@ async fn threshold>( LuminanceCalculation::MaximumChannels => color.maximum_rgb_channels(), }; - if luminance >= min_luminance && luminance <= max_luminance { - Color::WHITE - } else { - Color::BLACK - } + if luminance >= min_luminance && luminance <= max_luminance { Color::WHITE } else { Color::BLACK } }); image } @@ -720,7 +714,7 @@ impl Adjust for Color { } impl Adjust for Option { fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) { - if let Some(ref mut v) = self { + if let Some(v) = self { *v = map_fn(v) } } diff --git a/node-graph/gcore/src/raster/bbox.rs b/node-graph/gcore/src/raster/bbox.rs index 96c832314..9a0d90976 100644 --- a/node-graph/gcore/src/raster/bbox.rs +++ b/node-graph/gcore/src/raster/bbox.rs @@ -1,5 +1,4 @@ use dyn_any::DynAny; - use glam::{DAffine2, DVec2}; #[cfg_attr(not(target_arch = "spirv"), derive(Debug))] diff --git a/node-graph/gcore/src/raster/brush_cache.rs b/node-graph/gcore/src/raster/brush_cache.rs index 9db6f8ab4..29f0945e2 100644 --- a/node-graph/gcore/src/raster/brush_cache.rs +++ b/node-graph/gcore/src/raster/brush_cache.rs @@ -1,12 +1,10 @@ +use crate::Color; use crate::graphene_core::raster::image::ImageFrameTable; use crate::raster::Image; use crate::vector::brush_stroke::BrushStroke; use crate::vector::brush_stroke::BrushStyle; -use crate::Color; - -use dyn_any::DynAny; - use core::hash::Hash; +use dyn_any::DynAny; use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; diff --git a/node-graph/gcore/src/raster/color.rs b/node-graph/gcore/src/raster/color.rs index ac10430ae..4fcea6de4 100644 --- a/node-graph/gcore/src/raster/color.rs +++ b/node-graph/gcore/src/raster/color.rs @@ -1,16 +1,14 @@ use super::discrete_srgb::{float_to_srgb_u8, srgb_u8_to_float}; -use super::{Alpha, AlphaMut, AssociatedAlpha, Luminance, LuminanceMut, Pixel, RGBMut, Rec709Primaries, RGB, SRGB}; - +use super::{Alpha, AlphaMut, AssociatedAlpha, Luminance, LuminanceMut, Pixel, RGB, RGBMut, Rec709Primaries, SRGB}; +use bytemuck::{Pod, Zeroable}; +use core::hash::Hash; use dyn_any::DynAny; +use half::f16; +#[cfg(target_arch = "spirv")] +use spirv_std::num_traits::Euclid; #[cfg(feature = "serde")] #[cfg(target_arch = "spirv")] use spirv_std::num_traits::float::Float; -#[cfg(target_arch = "spirv")] -use spirv_std::num_traits::Euclid; - -use bytemuck::{Pod, Zeroable}; -use core::hash::Hash; -use half::f16; use std::fmt::Write; #[repr(C)] @@ -663,11 +661,7 @@ impl Color { #[inline(always)] pub fn blend_darker_color(&self, other: Color) -> Color { - if self.average_rgb_channels() <= other.average_rgb_channels() { - *self - } else { - other - } + if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other } } #[inline(always)] @@ -682,11 +676,7 @@ impl Color { #[inline(always)] pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 { - if c_s == 1. { - 1. - } else { - (c_b / (1. - c_s)).min(1.) - } + if c_s == 1. { 1. } else { (c_b / (1. - c_s)).min(1.) } } #[inline(always)] @@ -696,11 +686,7 @@ impl Color { #[inline(always)] pub fn blend_lighter_color(&self, other: Color) -> Color { - if self.average_rgb_channels() >= other.average_rgb_channels() { - *self - } else { - other - } + if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other } } pub fn blend_softlight(c_b: f32, c_s: f32) -> f32 { @@ -745,11 +731,7 @@ impl Color { } pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 { - if Color::blend_linear_light(c_b, c_s) < 0.5 { - 0. - } else { - 1. - } + if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. } } pub fn blend_difference(c_b: f32, c_s: f32) -> f32 { @@ -765,11 +747,7 @@ impl Color { } pub fn blend_divide(c_b: f32, c_s: f32) -> f32 { - if c_b == 0. { - 1. - } else { - c_b / c_s - } + if c_b == 0. { 1. } else { c_b / c_s } } pub fn blend_hue(&self, c_s: Color) -> Color { @@ -988,20 +966,12 @@ impl Color { #[inline(always)] pub fn srgb_to_linear(channel: f32) -> f32 { - if channel <= 0.04045 { - channel / 12.92 - } else { - ((channel + 0.055) / 1.055).powf(2.4) - } + if channel <= 0.04045 { channel / 12.92 } else { ((channel + 0.055) / 1.055).powf(2.4) } } #[inline(always)] pub fn linear_to_srgb(channel: f32) -> f32 { - if channel <= 0.0031308 { - channel * 12.92 - } else { - 1.055 * channel.powf(1. / 2.4) - 0.055 - } + if channel <= 0.0031308 { channel * 12.92 } else { 1.055 * channel.powf(1. / 2.4) - 0.055 } } #[inline(always)] diff --git a/node-graph/gcore/src/raster/curve.rs b/node-graph/gcore/src/raster/curve.rs index e6b8076da..74342e234 100644 --- a/node-graph/gcore/src/raster/curve.rs +++ b/node-graph/gcore/src/raster/curve.rs @@ -1,9 +1,7 @@ use super::{Channel, Linear, LuminanceMut}; use crate::Node; - -use dyn_any::{DynAny, StaticType, StaticTypeSized}; - use core::ops::{Add, Mul, Sub}; +use dyn_any::{DynAny, StaticType, StaticTypeSized}; #[derive(Debug, Clone, PartialEq, DynAny, specta::Type)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] diff --git a/node-graph/gcore/src/raster/discrete_srgb.rs b/node-graph/gcore/src/raster/discrete_srgb.rs index 108608a4b..13a06e30a 100644 --- a/node-graph/gcore/src/raster/discrete_srgb.rs +++ b/node-graph/gcore/src/raster/discrete_srgb.rs @@ -85,11 +85,7 @@ pub fn float_to_srgb_u8(mut f: f32) -> u8 { let lerp = bias.wrapping_add(mult * lerp_idx) >> 24; // Adjust linear interpolation to the correct value. - if f > CRITICAL_POINTS[lerp as usize] { - lerp as u8 + 1 - } else { - lerp as u8 - } + if f > CRITICAL_POINTS[lerp as usize] { lerp as u8 + 1 } else { lerp as u8 } } #[rustfmt::skip] @@ -156,11 +152,7 @@ mod tests { // https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#SRGBtoFLOAT fn srgb_to_float_ref(f: f32) -> f32 { - if f <= 0.04045f32 { - f / 12.92f32 - } else { - ((f + 0.055f32) / 1.055f32).powf(2.4_f32) - } + if f <= 0.04045f32 { f / 12.92f32 } else { ((f + 0.055f32) / 1.055f32).powf(2.4_f32) } } fn srgb_u8_to_float_ref(c: u8) -> f32 { diff --git a/node-graph/gcore/src/raster/image.rs b/node-graph/gcore/src/raster/image.rs index 1f12f3691..60ecbbfe1 100644 --- a/node-graph/gcore/src/raster/image.rs +++ b/node-graph/gcore/src/raster/image.rs @@ -1,9 +1,9 @@ -use super::discrete_srgb::float_to_srgb_u8; use super::Color; -use crate::instances::Instances; -use crate::transform::TransformMut; +use super::discrete_srgb::float_to_srgb_u8; use crate::AlphaBlending; use crate::GraphicElement; +use crate::instances::Instances; +use crate::transform::TransformMut; use alloc::vec::Vec; use core::hash::{Hash, Hasher}; use dyn_any::StaticType; diff --git a/node-graph/gcore/src/registry.rs b/node-graph/gcore/src/registry.rs index 38bef7a07..883973ef1 100644 --- a/node-graph/gcore/src/registry.rs +++ b/node-graph/gcore/src/registry.rs @@ -1,8 +1,6 @@ use crate::transform::Footprint; use crate::{Node, NodeIO, NodeIOTypes, Type, WasmNotSend}; - use dyn_any::{DynAny, StaticType}; - use std::collections::HashMap; use std::marker::PhantomData; use std::ops::Deref; @@ -150,7 +148,9 @@ impl NodeContainer { #[cfg(feature = "dealloc_nodes")] unsafe fn dealloc_unchecked(&mut self) { - std::mem::drop(Box::from_raw(self.node as *mut TypeErasedNode)); + unsafe { + std::mem::drop(Box::from_raw(self.node as *mut TypeErasedNode)); + } } } diff --git a/node-graph/gcore/src/structural.rs b/node-graph/gcore/src/structural.rs index 5fc7c5da6..8ac833d1d 100644 --- a/node-graph/gcore/src/structural.rs +++ b/node-graph/gcore/src/structural.rs @@ -1,6 +1,5 @@ -use core::marker::PhantomData; - use crate::Node; +use core::marker::PhantomData; /// This is how we can generically define composition of two nodes. /// This is done generically as shown: diff --git a/node-graph/gcore/src/text/font_cache.rs b/node-graph/gcore/src/text/font_cache.rs index 470888172..de7581a8c 100644 --- a/node-graph/gcore/src/text/font_cache.rs +++ b/node-graph/gcore/src/text/font_cache.rs @@ -1,5 +1,4 @@ use dyn_any::DynAny; - use std::collections::HashMap; /// A font type (storing font family and font style and an optional preview URL) diff --git a/node-graph/gcore/src/text/to_path.rs b/node-graph/gcore/src/text/to_path.rs index 14d111bd3..a238b4834 100644 --- a/node-graph/gcore/src/text/to_path.rs +++ b/node-graph/gcore/src/text/to_path.rs @@ -1,7 +1,5 @@ use crate::vector::PointId; - use bezier_rs::{ManipulatorGroup, Subpath}; - use glam::DVec2; use rustybuzz::ttf_parser::{GlyphId, OutlineBuilder}; use rustybuzz::{GlyphBuffer, UnicodeBuffer}; diff --git a/node-graph/gcore/src/transform.rs b/node-graph/gcore/src/transform.rs index 23743e962..35ceba75a 100644 --- a/node-graph/gcore/src/transform.rs +++ b/node-graph/gcore/src/transform.rs @@ -4,7 +4,6 @@ use crate::raster::bbox::AxisAlignedBbox; use crate::raster::image::ImageFrameTable; use crate::vector::VectorDataTable; use crate::{Artboard, ArtboardGroupTable, CloneVarArgs, Color, Context, Ctx, ExtractAll, GraphicGroupTable, OwnedContextImpl}; - use glam::{DAffine2, DVec2}; pub trait Transform { diff --git a/node-graph/gcore/src/types.rs b/node-graph/gcore/src/types.rs index 221ea6cd2..2a3004f95 100644 --- a/node-graph/gcore/src/types.rs +++ b/node-graph/gcore/src/types.rs @@ -29,7 +29,7 @@ macro_rules! concrete { #[macro_export] macro_rules! concrete_with_name { - ($type:ty, $name:expr) => { + ($type:ty, $name:expr_2021) => { $crate::Type::Concrete($crate::TypeDescriptor { id: Some(core::any::TypeId::of::<$type>()), name: $crate::Cow::Borrowed($name), @@ -42,16 +42,12 @@ macro_rules! concrete_with_name { #[macro_export] macro_rules! generic { - ($type:ty) => {{ - $crate::Type::Generic($crate::Cow::Borrowed(stringify!($type))) - }}; + ($type:ty) => {{ $crate::Type::Generic($crate::Cow::Borrowed(stringify!($type))) }}; } #[macro_export] macro_rules! future { - ($type:ty) => {{ - $crate::Type::Future(Box::new(concrete!($type))) - }}; + ($type:ty) => {{ $crate::Type::Future(Box::new(concrete!($type))) }}; ($type:ty, $name:ty) => { $crate::Type::Future(Box::new(concrete!($type, $name))) }; diff --git a/node-graph/gcore/src/uuid.rs b/node-graph/gcore/src/uuid.rs index 93ca73f0a..420f2388d 100644 --- a/node-graph/gcore/src/uuid.rs +++ b/node-graph/gcore/src/uuid.rs @@ -1,6 +1,5 @@ -pub use uuid_generation::*; - use dyn_any::DynAny; +pub use uuid_generation::*; #[derive(Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type)] pub struct Uuid( @@ -45,8 +44,8 @@ mod u64_string { mod uuid_generation { use core::cell::Cell; - use rand_chacha::rand_core::{RngCore, SeedableRng}; use rand_chacha::ChaCha20Rng; + use rand_chacha::rand_core::{RngCore, SeedableRng}; use std::sync::Mutex; static RNG: Mutex> = Mutex::new(None); diff --git a/node-graph/gcore/src/value.rs b/node-graph/gcore/src/value.rs index e63ad453c..cc7bc471f 100644 --- a/node-graph/gcore/src/value.rs +++ b/node-graph/gcore/src/value.rs @@ -1,9 +1,6 @@ use crate::Node; - -use core::{ - cell::{Cell, RefCell, RefMut}, - marker::PhantomData, -}; +use core::cell::{Cell, RefCell, RefMut}; +use core::marker::PhantomData; #[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct IntNode; diff --git a/node-graph/gcore/src/vector/brush_stroke.rs b/node-graph/gcore/src/vector/brush_stroke.rs index afe01530a..1e5b06a92 100644 --- a/node-graph/gcore/src/vector/brush_stroke.rs +++ b/node-graph/gcore/src/vector/brush_stroke.rs @@ -1,9 +1,7 @@ -use crate::raster::bbox::AxisAlignedBbox; -use crate::raster::BlendMode; use crate::Color; - +use crate::raster::BlendMode; +use crate::raster::bbox::AxisAlignedBbox; use dyn_any::DynAny; - use glam::DVec2; use std::hash::{Hash, Hasher}; diff --git a/node-graph/gcore/src/vector/generator_nodes.rs b/node-graph/gcore/src/vector/generator_nodes.rs index b4a528702..c1ff93378 100644 --- a/node-graph/gcore/src/vector/generator_nodes.rs +++ b/node-graph/gcore/src/vector/generator_nodes.rs @@ -1,6 +1,5 @@ -use crate::vector::{HandleId, VectorData, VectorDataTable}; use crate::Ctx; - +use crate::vector::{HandleId, VectorData, VectorDataTable}; use bezier_rs::Subpath; use glam::DVec2; diff --git a/node-graph/gcore/src/vector/mod.rs b/node-graph/gcore/src/vector/mod.rs index e729eede5..a4757c259 100644 --- a/node-graph/gcore/src/vector/mod.rs +++ b/node-graph/gcore/src/vector/mod.rs @@ -1,14 +1,11 @@ pub mod brush_stroke; pub mod generator_nodes; pub mod misc; - pub mod style; -pub use style::PathStyle; - mod vector_data; -pub use vector_data::*; - mod vector_nodes; -pub use vector_nodes::*; pub use bezier_rs; +pub use style::PathStyle; +pub use vector_data::*; +pub use vector_nodes::*; diff --git a/node-graph/gcore/src/vector/style.rs b/node-graph/gcore/src/vector/style.rs index b2b9201f2..03386719c 100644 --- a/node-graph/gcore/src/vector/style.rs +++ b/node-graph/gcore/src/vector/style.rs @@ -1,11 +1,9 @@ //! Contains stylistic options for SVG elements. +use crate::Color; use crate::consts::{LAYER_OUTLINE_STROKE_COLOR, LAYER_OUTLINE_STROKE_WEIGHT}; use crate::renderer::format_transform_matrix; -use crate::Color; - use dyn_any::DynAny; - use glam::{DAffine2, DVec2}; use std::fmt::{self, Display, Write}; diff --git a/node-graph/gcore/src/vector/vector_data.rs b/node-graph/gcore/src/vector/vector_data.rs index e22d525f5..30eb88a2f 100644 --- a/node-graph/gcore/src/vector/vector_data.rs +++ b/node-graph/gcore/src/vector/vector_data.rs @@ -1,17 +1,15 @@ mod attributes; mod modification; -pub use attributes::*; -pub use modification::*; use super::style::{PathStyle, Stroke}; use crate::instances::Instances; use crate::{AlphaBlending, Color, GraphicGroupTable}; - +pub use attributes::*; use bezier_rs::ManipulatorGroup; -use dyn_any::DynAny; - use core::borrow::Borrow; +use dyn_any::DynAny; use glam::{DAffine2, DVec2}; +pub use modification::*; use std::collections::HashMap; // TODO: Eventually remove this migration document upgrade code diff --git a/node-graph/gcore/src/vector/vector_data/attributes.rs b/node-graph/gcore/src/vector/vector_data/attributes.rs index eeadc0590..57c5289f8 100644 --- a/node-graph/gcore/src/vector/vector_data/attributes.rs +++ b/node-graph/gcore/src/vector/vector_data/attributes.rs @@ -1,7 +1,5 @@ use crate::vector::vector_data::{HandleId, VectorData}; - use dyn_any::DynAny; - use glam::{DAffine2, DVec2}; use std::collections::HashMap; use std::hash::{Hash, Hasher}; @@ -218,7 +216,7 @@ impl SegmentDomain { .zip(&self.start_point) .zip(&self.end_point) .filter(|((_, start), end)| **start >= points_length || **end >= points_length) - .map(|x| *x.0 .0) + .map(|x| *x.0.0) .collect::>(); let can_delete = || { diff --git a/node-graph/gcore/src/vector/vector_data/modification.rs b/node-graph/gcore/src/vector/vector_data/modification.rs index 9251f6db9..724d178e8 100644 --- a/node-graph/gcore/src/vector/vector_data/modification.rs +++ b/node-graph/gcore/src/vector/vector_data/modification.rs @@ -1,12 +1,10 @@ use super::*; +use crate::Ctx; use crate::transform::TransformMut; use crate::uuid::generate_uuid; -use crate::Ctx; - use bezier_rs::BezierHandles; -use dyn_any::DynAny; - use core::hash::BuildHasher; +use dyn_any::DynAny; use std::collections::{HashMap, HashSet}; /// Represents a procedural change to the [`PointDomain`] in [`VectorData`]. diff --git a/node-graph/gcore/src/vector/vector_nodes.rs b/node-graph/gcore/src/vector/vector_nodes.rs index 2a68bdca6..10115d27a 100644 --- a/node-graph/gcore/src/vector/vector_nodes.rs +++ b/node-graph/gcore/src/vector/vector_nodes.rs @@ -5,10 +5,9 @@ use crate::instances::{InstanceMut, Instances}; use crate::registry::types::{Angle, Fraction, IntegerCount, Length, SeedValue}; use crate::renderer::GraphicElementRendered; use crate::transform::{Footprint, Transform, TransformMut}; -use crate::vector::style::LineJoin; use crate::vector::PointDomain; +use crate::vector::style::LineJoin; use crate::{CloneVarArgs, Color, Context, Ctx, ExtractAll, GraphicElement, GraphicGroupTable, OwnedContextImpl}; - use bezier_rs::{Cap, Join, Subpath, SubpathTValue, TValue}; use glam::{DAffine2, DVec2}; use rand::{Rng, SeedableRng}; @@ -1067,9 +1066,7 @@ async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, vector_data: impl N mod test { use super::*; use crate::Node; - use bezier_rs::Bezier; - use std::pin::Pin; #[derive(Clone)] diff --git a/node-graph/gpu-compiler/Cargo.toml b/node-graph/gpu-compiler/Cargo.toml index 2458fc381..bcbede7f0 100644 --- a/node-graph/gpu-compiler/Cargo.toml +++ b/node-graph/gpu-compiler/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "gpu-compiler" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" [features] diff --git a/node-graph/gpu-compiler/gpu-compiler-bin-wrapper/Cargo.toml b/node-graph/gpu-compiler/gpu-compiler-bin-wrapper/Cargo.toml index 36d3b7ab2..b0662d675 100644 --- a/node-graph/gpu-compiler/gpu-compiler-bin-wrapper/Cargo.toml +++ b/node-graph/gpu-compiler/gpu-compiler-bin-wrapper/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "gpu-compiler-bin-wrapper" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" [features] diff --git a/node-graph/gpu-compiler/gpu-compiler-bin-wrapper/src/lib.rs b/node-graph/gpu-compiler/gpu-compiler-bin-wrapper/src/lib.rs index b4e636972..6ffb79988 100644 --- a/node-graph/gpu-compiler/gpu-compiler-bin-wrapper/src/lib.rs +++ b/node-graph/gpu-compiler/gpu-compiler-bin-wrapper/src/lib.rs @@ -1,7 +1,7 @@ -use graph_craft::{proto::ProtoNetwork, Type}; -use wgpu_executor::ShaderIO; - +use graph_craft::Type; +use graph_craft::proto::ProtoNetwork; use std::io::Write; +use wgpu_executor::ShaderIO; pub fn compile_spirv(request: &CompileRequest, compile_dir: Option<&str>, manifest_path: &str) -> anyhow::Result> { let serialized_graph = serde_json::to_string(&graph_craft::graphene_compiler::CompileRequest { diff --git a/node-graph/gpu-compiler/src/lib.rs b/node-graph/gpu-compiler/src/lib.rs index 67a2dbaad..75905c9fe 100644 --- a/node-graph/gpu-compiler/src/lib.rs +++ b/node-graph/gpu-compiler/src/lib.rs @@ -1,7 +1,6 @@ use gpu_executor::{GPUConstant, ShaderIO, ShaderInput, SpirVCompiler}; use graph_craft::proto::*; use graphene_core::Cow; - use std::path::{Path, PathBuf}; use tera::Context; @@ -242,7 +241,7 @@ mod test { name = "project-node" version = "0.1.0" authors = ["Example ", "smith.john@example.com", ] -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" publish = false diff --git a/node-graph/gpu-compiler/src/templates/Cargo-template.toml b/node-graph/gpu-compiler/src/templates/Cargo-template.toml index 9f878376a..ffe746dc6 100644 --- a/node-graph/gpu-compiler/src/templates/Cargo-template.toml +++ b/node-graph/gpu-compiler/src/templates/Cargo-template.toml @@ -2,7 +2,7 @@ authors = [{% for author in authors %}"{{author}}", {% endfor %}] name = "{{name}}-node" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" publish = false diff --git a/node-graph/gpu-executor/Cargo.toml b/node-graph/gpu-executor/Cargo.toml index 2af7d5313..38c6b77b3 100644 --- a/node-graph/gpu-executor/Cargo.toml +++ b/node-graph/gpu-executor/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "gpu-executor" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" [features] diff --git a/node-graph/gpu-executor/src/lib.rs b/node-graph/gpu-executor/src/lib.rs index f87a7ece9..ca5aedbc1 100644 --- a/node-graph/gpu-executor/src/lib.rs +++ b/node-graph/gpu-executor/src/lib.rs @@ -1,9 +1,9 @@ -use graphene_core::raster::{color::RGBA16F, Image, Pixel, SRGBA8}; -use graphene_core::*; - use bytemuck::{Pod, Zeroable}; use dyn_any::{StaticType, StaticTypeSized}; use glam::UVec3; +use graphene_core::raster::color::RGBA16F; +use graphene_core::raster::{Image, Pixel, SRGBA8}; +use graphene_core::*; use std::borrow::Cow; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, dyn_any::DynAny)] diff --git a/node-graph/graph-craft/Cargo.toml b/node-graph/graph-craft/Cargo.toml index d8ec3fe82..35faf2861 100644 --- a/node-graph/graph-craft/Cargo.toml +++ b/node-graph/graph-craft/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "graph-craft" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" [features] diff --git a/node-graph/graph-craft/benches/compile_demo_art_criterion.rs b/node-graph/graph-craft/benches/compile_demo_art_criterion.rs index 5e3264cd5..c559e738b 100644 --- a/node-graph/graph-craft/benches/compile_demo_art_criterion.rs +++ b/node-graph/graph-craft/benches/compile_demo_art_criterion.rs @@ -1,4 +1,4 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; use graph_craft::util::DEMO_ART; fn compile_to_proto(c: &mut Criterion) { use graph_craft::util::{compile, load_from_name}; diff --git a/node-graph/graph-craft/src/document.rs b/node-graph/graph-craft/src/document.rs index 65d1af8c5..d81458617 100644 --- a/node-graph/graph-craft/src/document.rs +++ b/node-graph/graph-craft/src/document.rs @@ -1,18 +1,17 @@ -use crate::document::value::TaggedValue; -use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode, ProtoNodeInput}; - -use dyn_any::DynAny; -use graphene_core::memo::MemoHashGuard; -pub use graphene_core::uuid::generate_uuid; -pub use graphene_core::uuid::NodeId; -use graphene_core::{Cow, MemoHash, ProtoNodeIdentifier, Type}; pub mod value; +use crate::document::value::TaggedValue; +use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode, ProtoNodeInput}; +use dyn_any::DynAny; use glam::IVec2; +use graphene_core::memo::MemoHashGuard; +pub use graphene_core::uuid::NodeId; +pub use graphene_core::uuid::generate_uuid; +use graphene_core::{Cow, MemoHash, ProtoNodeIdentifier, Type}; use log::Metadata; use rustc_hash::FxHashMap; -use std::collections::hash_map::DefaultHasher; use std::collections::HashMap; +use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; /// Hash two IDs together, returning a new ID that is always consistent for two input IDs in a specific order. @@ -455,33 +454,17 @@ impl NodeInput { } pub fn as_value(&self) -> Option<&TaggedValue> { - if let NodeInput::Value { tagged_value, .. } = self { - Some(tagged_value) - } else { - None - } + if let NodeInput::Value { tagged_value, .. } = self { Some(tagged_value) } else { None } } pub fn as_value_mut(&mut self) -> Option> { - if let NodeInput::Value { tagged_value, .. } = self { - Some(tagged_value.inner_mut()) - } else { - None - } + if let NodeInput::Value { tagged_value, .. } = self { Some(tagged_value.inner_mut()) } else { None } } pub fn as_non_exposed_value(&self) -> Option<&TaggedValue> { - if let NodeInput::Value { tagged_value, exposed: false } = self { - Some(tagged_value) - } else { - None - } + if let NodeInput::Value { tagged_value, exposed: false } = self { Some(tagged_value) } else { None } } pub fn as_node(&self) -> Option { - if let NodeInput::Node { node_id, .. } = self { - Some(*node_id) - } else { - None - } + if let NodeInput::Node { node_id, .. } = self { Some(*node_id) } else { None } } } @@ -942,12 +925,7 @@ impl NodeNetwork { fn replace_node_inputs(&mut self, node_id: NodeId, old_input: (NodeId, usize), new_input: (NodeId, usize)) { let Some(node) = self.nodes.get_mut(&node_id) else { return }; node.inputs.iter_mut().for_each(|input| { - if let NodeInput::Node { - node_id: ref mut input_id, - ref mut output_index, - .. - } = input - { + if let NodeInput::Node { node_id: input_id, output_index, .. } = input { if (*input_id, *output_index) == old_input { (*input_id, *output_index) = new_input; } @@ -1241,12 +1219,7 @@ impl NodeNetwork { } } for node_input in self.exports.iter_mut() { - if let NodeInput::Node { - ref mut node_id, - ref mut output_index, - .. - } = node_input - { + if let NodeInput::Node { node_id, output_index, .. } = node_input { if *node_id == id { *node_id = input_node_id; *output_index = node_input_output_index; @@ -1382,9 +1355,7 @@ impl<'a> Iterator for RecursiveNodeIter<'a> { mod test { use super::*; use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode, ProtoNodeInput}; - use graphene_core::ProtoNodeIdentifier; - use std::sync::atomic::AtomicU64; fn gen_node_id() -> NodeId { @@ -1478,7 +1449,7 @@ mod test { assert_eq!(extraction_network.nodes.len(), 1); let inputs = extraction_network.nodes.get(&NodeId(1)).unwrap().inputs.clone(); assert_eq!(inputs.len(), 1); - assert!(matches!(&inputs[0].as_value(), &Some(TaggedValue::DocumentNode(ref network), ..) if network == &id_node)); + assert!(matches!(&inputs[0].as_value(), &Some(TaggedValue::DocumentNode(network), ..) if network == &id_node)); } #[test] diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 0db4eb826..283446971 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -2,17 +2,15 @@ use super::DocumentNode; pub use crate::imaginate_input::{ImaginateCache, ImaginateController, ImaginateMaskStartingFill, ImaginateSamplingMethod}; use crate::proto::{Any as DAny, FutureAny}; use crate::wasm_application_io::WasmEditorApi; - use dyn_any::DynAny; pub use dyn_any::StaticType; +pub use glam::{DAffine2, DVec2, IVec2, UVec2}; use graphene_core::raster::brush_cache::BrushCache; use graphene_core::raster::{BlendMode, LuminanceCalculation}; use graphene_core::renderer::RenderMetadata; use graphene_core::uuid::NodeId; use graphene_core::vector::style::Fill; use graphene_core::{Color, MemoHash, Node, Type}; - -pub use glam::{DAffine2, DVec2, IVec2, UVec2}; use std::fmt::Display; use std::hash::Hash; use std::marker::PhantomData; diff --git a/node-graph/graph-craft/src/graphene_compiler.rs b/node-graph/graph-craft/src/graphene_compiler.rs index 41a818201..0c3f77935 100644 --- a/node-graph/graph-craft/src/graphene_compiler.rs +++ b/node-graph/graph-craft/src/graphene_compiler.rs @@ -1,7 +1,6 @@ -use std::error::Error; - use crate::document::NodeNetwork; use crate::proto::{LocalFuture, ProtoNetwork}; +use std::error::Error; pub struct Compiler {} diff --git a/node-graph/graph-craft/src/imaginate_input.rs b/node-graph/graph-craft/src/imaginate_input.rs index 383280cf4..b73eb12e4 100644 --- a/node-graph/graph-craft/src/imaginate_input.rs +++ b/node-graph/graph-craft/src/imaginate_input.rs @@ -1,6 +1,5 @@ use dyn_any::DynAny; use graphene_core::Color; - use std::borrow::Cow; use std::fmt::Debug; use std::sync::atomic::{AtomicBool, Ordering}; diff --git a/node-graph/graph-craft/src/lib.rs b/node-graph/graph-craft/src/lib.rs index dec83329d..ee4f30e5c 100644 --- a/node-graph/graph-craft/src/lib.rs +++ b/node-graph/graph-craft/src/lib.rs @@ -3,7 +3,7 @@ extern crate log; #[macro_use] extern crate graphene_core; -pub use graphene_core::{concrete, generic, ProtoNodeIdentifier, Type, TypeDescriptor}; +pub use graphene_core::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, generic}; pub mod document; pub mod proto; diff --git a/node-graph/graph-craft/src/proto.rs b/node-graph/graph-craft/src/proto.rs index 0f1c7e025..e8087515e 100644 --- a/node-graph/graph-craft/src/proto.rs +++ b/node-graph/graph-craft/src/proto.rs @@ -1,9 +1,7 @@ -use crate::document::{value, InlineRust}; +use crate::document::{InlineRust, value}; use crate::document::{NodeId, OriginalLocation}; - pub use graphene_core::registry::*; use graphene_core::*; - use rustc_hash::FxHashMap; #[cfg(feature = "serde")] use std::borrow::Cow; diff --git a/node-graph/graph-craft/src/wasm_application_io.rs b/node-graph/graph-craft/src/wasm_application_io.rs index 13d96e70f..fcead8f19 100644 --- a/node-graph/graph-craft/src/wasm_application_io.rs +++ b/node-graph/graph-craft/src/wasm_application_io.rs @@ -1,16 +1,12 @@ +use dyn_any::StaticType; use graphene_core::application_io::SurfaceHandleFrame; use graphene_core::application_io::{ApplicationError, ApplicationIo, ResourceFuture, SurfaceHandle, SurfaceId}; -use wgpu_executor::WgpuExecutor; - -use dyn_any::StaticType; #[cfg(target_arch = "wasm32")] use js_sys::{Object, Reflect}; use std::collections::HashMap; +use std::sync::Arc; #[cfg(target_arch = "wasm32")] use std::sync::atomic::AtomicU64; -use std::sync::Arc; -// #[cfg(not(target_arch = "wasm32"))] -// use std::sync::Mutex; #[cfg(feature = "tokio")] use tokio::io::AsyncReadExt; #[cfg(target_arch = "wasm32")] @@ -18,9 +14,10 @@ use wasm_bindgen::JsCast; #[cfg(target_arch = "wasm32")] use wasm_bindgen::JsValue; #[cfg(target_arch = "wasm32")] -use web_sys::window; -#[cfg(target_arch = "wasm32")] use web_sys::HtmlCanvasElement; +#[cfg(target_arch = "wasm32")] +use web_sys::window; +use wgpu_executor::WgpuExecutor; #[derive(Debug)] struct WindowWrapper { diff --git a/node-graph/graphene-cli/Cargo.toml b/node-graph/graphene-cli/Cargo.toml index 42ccaabd4..40f52e707 100644 --- a/node-graph/graphene-cli/Cargo.toml +++ b/node-graph/graphene-cli/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "graphene-cli" version = "0.1.0" -edition = "2021" +edition = "2024" description = "CLI interface for the graphene language" authors = ["Graphite Authors "] license = "MIT OR Apache-2.0" diff --git a/node-graph/graphene-cli/src/main.rs b/node-graph/graphene-cli/src/main.rs index fa10cba0d..9a932b416 100644 --- a/node-graph/graphene-cli/src/main.rs +++ b/node-graph/graphene-cli/src/main.rs @@ -1,3 +1,6 @@ +use clap::{Args, Parser, Subcommand}; +use fern::colors::{Color, ColoredLevelConfig}; +use futures::executor::block_on; use graph_craft::document::*; use graph_craft::graphene_compiler::{Compiler, Executor}; use graph_craft::proto::ProtoNetwork; @@ -7,12 +10,10 @@ use graphene_core::application_io::{ApplicationIo, NodeGraphUpdateSender}; use graphene_core::text::FontCache; use graphene_std::wasm_application_io::{WasmApplicationIo, WasmEditorApi}; use interpreted_executor::dynamic_executor::DynamicExecutor; - -use clap::{Args, Parser, Subcommand}; -use fern::colors::{Color, ColoredLevelConfig}; -use futures::executor::block_on; use interpreted_executor::util::wrap_network_in_scope; -use std::{error::Error, path::PathBuf, sync::Arc}; +use std::error::Error; +use std::path::PathBuf; +use std::sync::Arc; struct UpdateLogger {} @@ -107,9 +108,11 @@ async fn main() -> Result<(), Box> { } } Command::Run { run_loop, .. } => { - std::thread::spawn(move || loop { - std::thread::sleep(std::time::Duration::from_nanos(10)); - device.poll(wgpu::Maintain::Poll); + std::thread::spawn(move || { + loop { + std::thread::sleep(std::time::Duration::from_nanos(10)); + device.poll(wgpu::Maintain::Poll); + } }); let executor = create_executor(proto_graph)?; let render_config = graphene_core::application_io::RenderConfig::default(); diff --git a/node-graph/gstd/Cargo.toml b/node-graph/gstd/Cargo.toml index cdc6ae761..f144b9f68 100644 --- a/node-graph/gstd/Cargo.toml +++ b/node-graph/gstd/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "graphene-std" version = "0.1.0" -edition = "2021" +edition = "2024" description = "Graphene standard library" authors = ["Graphite Authors "] license = "MIT OR Apache-2.0" diff --git a/node-graph/gstd/src/any.rs b/node-graph/gstd/src/any.rs index 5b118f78a..1a38d65b3 100644 --- a/node-graph/gstd/src/any.rs +++ b/node-graph/gstd/src/any.rs @@ -1,10 +1,10 @@ use dyn_any::StaticType; pub use graph_craft::proto::{Any, NodeContainer, TypeErasedBox, TypeErasedNode}; use graph_craft::proto::{DynFuture, FutureAny, SharedNodeContainer}; -pub use graphene_core::registry::{DowncastBothNode, DynAnyNode, FutureWrapperNode, PanicNode}; use graphene_core::NodeIO; use graphene_core::WasmNotSend; -pub use graphene_core::{generic, ops, Node}; +pub use graphene_core::registry::{DowncastBothNode, DynAnyNode, FutureWrapperNode, PanicNode}; +pub use graphene_core::{Node, generic, ops}; pub trait IntoTypeErasedNode<'n> { fn into_type_erased(self) -> TypeErasedBox<'n>; diff --git a/node-graph/gstd/src/brush.rs b/node-graph/gstd/src/brush.rs index b74f3c906..646aabe87 100644 --- a/node-graph/gstd/src/brush.rs +++ b/node-graph/gstd/src/brush.rs @@ -1,5 +1,5 @@ -use crate::raster::{blend_image_closure, BlendImageTupleNode, ExtendImageToBoundsNode}; - +use crate::raster::{BlendImageTupleNode, ExtendImageToBoundsNode, blend_image_closure}; +use glam::{DAffine2, DVec2}; use graph_craft::generic::FnNode; use graph_craft::proto::FutureWrapperNode; use graphene_core::raster::adjustments::blend_colors; @@ -9,12 +9,10 @@ use graphene_core::raster::image::{Image, ImageFrameTable}; use graphene_core::raster::{Alpha, Bitmap, BlendMode, Color, Pixel, Sample}; use graphene_core::transform::{Transform, TransformMut}; use graphene_core::value::{ClonedNode, CopiedNode, ValueNode}; -use graphene_core::vector::brush_stroke::{BrushStroke, BrushStyle}; use graphene_core::vector::VectorDataTable; +use graphene_core::vector::brush_stroke::{BrushStroke, BrushStyle}; use graphene_core::{Ctx, GraphicElement, Node}; -use glam::{DAffine2, DVec2}; - #[node_macro::node(category("Debug"))] fn vector_points(_: impl Ctx, vector_data: VectorDataTable) -> Vec { let vector_data = vector_data.one_instance().instance; @@ -335,12 +333,10 @@ async fn brush(_: impl Ctx, image_frame_table: ImageFrameTable, bounds: I #[cfg(test)] mod test { use super::*; - + use glam::DAffine2; use graphene_core::raster::Bitmap; use graphene_core::transform::Transform; - use glam::DAffine2; - #[test] fn test_brush_texture() { let size = 20.; diff --git a/node-graph/gstd/src/cache.rs b/node-graph/gstd/src/cache.rs index 6740c25c6..2a3bbe27d 100644 --- a/node-graph/gstd/src/cache.rs +++ b/node-graph/gstd/src/cache.rs @@ -1,14 +1,12 @@ use parking_lot::RawRwLock; -use std::{ - any::Any, - borrow::Borrow, - cell::RefCell, - collections::{hash_map::DefaultHasher, HashMap}, - hash::{Hash, Hasher}, - iter, - iter::Sum, - marker::PhantomData, -}; +use std::any::Any; +use std::borrow::Borrow; +use std::cell::RefCell; +use std::collections::hash_map::DefaultHasher; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::iter::{self, Sum}; +use std::marker::PhantomData; use storage_map::{StorageMap, StorageMapGuard}; /// Caches the output of a given Node and acts as a proxy @@ -21,8 +19,16 @@ impl<'n: 'c, 'c, NODE: Node + 'c> Node for SmartCacheNode<'n, 'c, NODE> where for<'a> NODE::Input<'a>: Hash, { - type Input<'a> = NODE::Input<'a> where Self: 'a, 'c : 'a; - type Output<'a> = StorageMapGuard<'a, RawRwLock, CacheNode<'n, 'c, NODE>> where Self: 'a, 'c: 'a; + type Input<'a> + = NODE::Input<'a> + where + Self: 'a, + 'c: 'a; + type Output<'a> + = StorageMapGuard<'a, RawRwLock, CacheNode<'n, 'c, NODE>> + where + Self: 'a, + 'c: 'a; fn eval<'a, I: Borrow>>(&'a self, input: I) -> Self::Output<'a> { let mut hasher = DefaultHasher::new(); input.borrow().hash(&mut hasher); diff --git a/node-graph/gstd/src/dehaze.rs b/node-graph/gstd/src/dehaze.rs index eca6f9017..502ed2f81 100644 --- a/node-graph/gstd/src/dehaze.rs +++ b/node-graph/gstd/src/dehaze.rs @@ -2,7 +2,6 @@ use graph_craft::proto::types::Percentage; use graphene_core::raster::image::{Image, ImageFrameTable}; use graphene_core::transform::{Transform, TransformMut}; use graphene_core::{Color, Ctx}; - use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage}; use ndarray::{Array2, ArrayBase, Dim, OwnedRepr}; use std::cmp::{max, min}; diff --git a/node-graph/gstd/src/gpu_nodes.rs b/node-graph/gstd/src/gpu_nodes.rs index 7a0c5925f..8e07bc47b 100644 --- a/node-graph/gstd/src/gpu_nodes.rs +++ b/node-graph/gstd/src/gpu_nodes.rs @@ -1,4 +1,6 @@ +use crate::wasm_application_io::WasmApplicationIo; use dyn_any::StaticTypeSized; +use glam::{DAffine2, DVec2, Mat2, Vec2}; use gpu_executor::{ComputePassDimensions, StorageBufferOptions}; use graph_craft::document::value::TaggedValue; use graph_craft::document::*; @@ -9,14 +11,9 @@ use graphene_core::raster::{BlendMode, Pixel}; use graphene_core::transform::Transform; use graphene_core::transform::TransformMut; use graphene_core::*; -use wgpu_executor::{Bindgroup, PipelineLayout, Shader, ShaderIO, ShaderInput, WgpuExecutor, WgpuShaderInput}; - -use glam::{DAffine2, DVec2, Mat2, Vec2}; - use std::collections::HashMap; use std::sync::{Arc, Mutex}; - -use crate::wasm_application_io::WasmApplicationIo; +use wgpu_executor::{Bindgroup, PipelineLayout, Shader, ShaderIO, ShaderInput, WgpuExecutor, WgpuShaderInput}; // TODO: Move to graph-craft #[node_macro::node(category("Debug: GPU"))] diff --git a/node-graph/gstd/src/image_color_palette.rs b/node-graph/gstd/src/image_color_palette.rs index 9dac3e3b3..bd6ce2832 100644 --- a/node-graph/gstd/src/image_color_palette.rs +++ b/node-graph/gstd/src/image_color_palette.rs @@ -29,7 +29,7 @@ async fn image_color_palette( colors[bin].push(pixel.to_gamma_srgb()); } - let shorted = histogram.iter().enumerate().filter(|(_, &count)| count > 0).map(|(i, _)| i).collect::>(); + let shorted = histogram.iter().enumerate().filter(|&(_, &count)| count > 0).map(|(i, _)| i).collect::>(); let mut palette = vec![]; @@ -64,7 +64,6 @@ async fn image_color_palette( #[cfg(test)] mod test { use super::*; - use graphene_core::raster::image::{Image, ImageFrameTable}; #[test] diff --git a/node-graph/gstd/src/imaginate.rs b/node-graph/gstd/src/imaginate.rs index 39e44c355..57296611a 100644 --- a/node-graph/gstd/src/imaginate.rs +++ b/node-graph/gstd/src/imaginate.rs @@ -1,7 +1,8 @@ use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; -use futures::{future::Either, TryFutureExt}; +use futures::TryFutureExt; +use futures::future::Either; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginateSamplingMethod, ImaginateServerStatus, ImaginateStatus, ImaginateTerminationHandle}; use graph_craft::wasm_application_io::EditorPreferences; diff --git a/node-graph/gstd/src/raster.rs b/node-graph/gstd/src/raster.rs index 8b16832cb..8384c2e92 100644 --- a/node-graph/gstd/src/raster.rs +++ b/node-graph/gstd/src/raster.rs @@ -1,4 +1,6 @@ use dyn_any::DynAny; +use fastnoise_lite; +use glam::{DAffine2, DVec2, Vec2}; use graphene_core::raster::bbox::Bbox; use graphene_core::raster::image::{Image, ImageFrameTable}; use graphene_core::raster::{ @@ -6,9 +8,6 @@ use graphene_core::raster::{ }; use graphene_core::transform::{Transform, TransformMut}; use graphene_core::{AlphaBlending, Color, Ctx, ExtractFootprint, GraphicElement, Node}; - -use fastnoise_lite; -use glam::{DAffine2, DVec2, Vec2}; use rand::prelude::*; use rand_chacha::ChaCha8Rng; use std::fmt::Debug; diff --git a/node-graph/gstd/src/text.rs b/node-graph/gstd/src/text.rs index 3139307cc..999e6bb73 100644 --- a/node-graph/gstd/src/text.rs +++ b/node-graph/gstd/src/text.rs @@ -1,9 +1,8 @@ use crate::vector::{VectorData, VectorDataTable}; - use graph_craft::wasm_application_io::WasmEditorApi; -use graphene_core::text::TypesettingConfig; -pub use graphene_core::text::{bounding_box, load_face, to_path, Font, FontCache}; use graphene_core::Ctx; +use graphene_core::text::TypesettingConfig; +pub use graphene_core::text::{Font, FontCache, bounding_box, load_face, to_path}; #[node_macro::node(category(""))] fn text<'i: 'n>( diff --git a/node-graph/gstd/src/value.rs b/node-graph/gstd/src/value.rs index fcca52cd7..8fdf5f34e 100644 --- a/node-graph/gstd/src/value.rs +++ b/node-graph/gstd/src/value.rs @@ -1,7 +1,6 @@ use core::marker::PhantomData; pub use graphene_core::value::*; use graphene_core::Node; - use dyn_any::DynAny; pub struct AnyRefNode<'n, N: Node<'n>>(N, PhantomData<&'n ()>); diff --git a/node-graph/gstd/src/vector.rs b/node-graph/gstd/src/vector.rs index 639aa562b..f7939c26d 100644 --- a/node-graph/gstd/src/vector.rs +++ b/node-graph/gstd/src/vector.rs @@ -1,4 +1,5 @@ use bezier_rs::{ManipulatorGroup, Subpath}; +use glam::{DAffine2, DVec2}; use graphene_core::transform::Transform; use graphene_core::transform::TransformMut; use graphene_core::vector::misc::BooleanOperation; @@ -7,8 +8,6 @@ pub use graphene_core::vector::*; use graphene_core::{Color, Ctx, GraphicElement, GraphicGroupTable}; pub use path_bool as path_bool_lib; use path_bool::{FillRule, PathBooleanOperation}; - -use glam::{DAffine2, DVec2}; use std::ops::Mul; #[node_macro::node(category(""))] diff --git a/node-graph/gstd/src/wasm_application_io.rs b/node-graph/gstd/src/wasm_application_io.rs index 1545bbfda..0bee4e770 100644 --- a/node-graph/gstd/src/wasm_application_io.rs +++ b/node-graph/gstd/src/wasm_application_io.rs @@ -10,7 +10,7 @@ use graphene_core::instances::Instances; use graphene_core::raster::bbox::Bbox; use graphene_core::raster::image::{Image, ImageFrameTable}; use graphene_core::renderer::RenderMetadata; -use graphene_core::renderer::{format_transform_matrix, GraphicElementRendered, RenderParams, RenderSvgSegmentList, SvgRender}; +use graphene_core::renderer::{GraphicElementRendered, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix}; use graphene_core::transform::Footprint; #[cfg(target_arch = "wasm32")] use graphene_core::transform::TransformMut; diff --git a/node-graph/interpreted-executor/Cargo.toml b/node-graph/interpreted-executor/Cargo.toml index 2f19df4ac..bafdf68ff 100644 --- a/node-graph/interpreted-executor/Cargo.toml +++ b/node-graph/interpreted-executor/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "interpreted-executor" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" [features] diff --git a/node-graph/interpreted-executor/benches/benchmark_util.rs b/node-graph/interpreted-executor/benches/benchmark_util.rs index 1d4ef4330..f35d5c4da 100644 --- a/node-graph/interpreted-executor/benches/benchmark_util.rs +++ b/node-graph/interpreted-executor/benches/benchmark_util.rs @@ -1,9 +1,8 @@ -use criterion::{measurement::Measurement, BenchmarkGroup}; +use criterion::BenchmarkGroup; +use criterion::measurement::Measurement; use futures::executor::block_on; -use graph_craft::{ - proto::ProtoNetwork, - util::{compile, load_from_name, DEMO_ART}, -}; +use graph_craft::proto::ProtoNetwork; +use graph_craft::util::{DEMO_ART, compile, load_from_name}; use interpreted_executor::dynamic_executor::DynamicExecutor; pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) { diff --git a/node-graph/interpreted-executor/benches/run_cached.rs b/node-graph/interpreted-executor/benches/run_cached.rs index c44a1fc74..9ee575821 100644 --- a/node-graph/interpreted-executor/benches/run_cached.rs +++ b/node-graph/interpreted-executor/benches/run_cached.rs @@ -1,10 +1,10 @@ -use criterion::{criterion_group, criterion_main, Criterion}; +mod benchmark_util; + +use benchmark_util::{bench_for_each_demo, setup_network}; +use criterion::{Criterion, criterion_group, criterion_main}; use graph_craft::graphene_compiler::Executor; use graphene_std::transform::Footprint; -mod benchmark_util; -use benchmark_util::{bench_for_each_demo, setup_network}; - fn subsequent_evaluations(c: &mut Criterion) { let mut group = c.benchmark_group("Subsequent Evaluations"); let footprint = Footprint::default(); diff --git a/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs b/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs index 76789ae5d..fb0cf3409 100644 --- a/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs +++ b/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs @@ -1,9 +1,8 @@ -use criterion::{black_box, criterion_group, criterion_main, measurement::Measurement, BenchmarkGroup, Criterion}; -use graph_craft::{ - graphene_compiler::Executor, - proto::ProtoNetwork, - util::{compile, load_from_name, DEMO_ART}, -}; +use criterion::measurement::Measurement; +use criterion::{BenchmarkGroup, Criterion, black_box, criterion_group, criterion_main}; +use graph_craft::graphene_compiler::Executor; +use graph_craft::proto::ProtoNetwork; +use graph_craft::util::{DEMO_ART, compile, load_from_name}; use graphene_std::transform::Footprint; use interpreted_executor::dynamic_executor::DynamicExecutor; diff --git a/node-graph/interpreted-executor/benches/run_once.rs b/node-graph/interpreted-executor/benches/run_once.rs index f4350a692..33d9ba31b 100644 --- a/node-graph/interpreted-executor/benches/run_once.rs +++ b/node-graph/interpreted-executor/benches/run_once.rs @@ -1,10 +1,10 @@ -use criterion::{criterion_group, criterion_main, Criterion}; +mod benchmark_util; + +use benchmark_util::{bench_for_each_demo, setup_network}; +use criterion::{Criterion, criterion_group, criterion_main}; use graph_craft::graphene_compiler::Executor; use graphene_std::transform::Footprint; -mod benchmark_util; -use benchmark_util::{bench_for_each_demo, setup_network}; - fn run_once(c: &mut Criterion) { let mut group = c.benchmark_group("Run Once"); let footprint = Footprint::default(); diff --git a/node-graph/interpreted-executor/benches/update_executor.rs b/node-graph/interpreted-executor/benches/update_executor.rs index ede31cc3f..102dcdd02 100644 --- a/node-graph/interpreted-executor/benches/update_executor.rs +++ b/node-graph/interpreted-executor/benches/update_executor.rs @@ -1,10 +1,10 @@ -use criterion::{criterion_group, criterion_main, Criterion}; +mod benchmark_util; + +use benchmark_util::{bench_for_each_demo, setup_network}; +use criterion::{Criterion, criterion_group, criterion_main}; use graph_craft::proto::ProtoNetwork; use interpreted_executor::dynamic_executor::DynamicExecutor; -mod benchmark_util; -use benchmark_util::{bench_for_each_demo, setup_network}; - fn update_executor(c: &mut Criterion) { let mut group = c.benchmark_group("Update Executor"); bench_for_each_demo(&mut group, |name, g| { diff --git a/node-graph/interpreted-executor/src/dynamic_executor.rs b/node-graph/interpreted-executor/src/dynamic_executor.rs index 89071b6b7..b3e521bf5 100644 --- a/node-graph/interpreted-executor/src/dynamic_executor.rs +++ b/node-graph/interpreted-executor/src/dynamic_executor.rs @@ -1,13 +1,11 @@ use crate::node_registry; - use dyn_any::StaticType; -use graph_craft::document::value::{TaggedValue, UpcastAsRefNode, UpcastNode}; +use graph_craft::Type; use graph_craft::document::NodeId; +use graph_craft::document::value::{TaggedValue, UpcastAsRefNode, UpcastNode}; use graph_craft::graphene_compiler::Executor; use graph_craft::proto::{ConstructionArgs, GraphError, LocalFuture, NodeContainer, ProtoNetwork, ProtoNode, SharedNodeContainer, TypeErasedBox, TypingContext}; use graph_craft::proto::{GraphErrorType, GraphErrors}; -use graph_craft::Type; - use std::collections::{HashMap, HashSet}; use std::error::Error; use std::panic::UnwindSafe; @@ -266,8 +264,10 @@ impl BorrowTree { /// /// ```rust /// use std::collections::HashMap; - /// use graph_craft::{proto::*, document::*}; - /// use interpreted_executor::{node_registry, dynamic_executor::BorrowTree}; + /// use graph_craft::document::*; + /// use graph_craft::proto::*; + /// use interpreted_executor::dynamic_executor::BorrowTree; + /// use interpreted_executor::node_registry; /// /// /// async fn example() -> Result<(), GraphErrors> { @@ -409,7 +409,6 @@ impl BorrowTree { #[cfg(test)] mod test { use super::*; - use graph_craft::document::value::TaggedValue; #[test] diff --git a/node-graph/interpreted-executor/src/lib.rs b/node-graph/interpreted-executor/src/lib.rs index 5a87a995f..097653c2a 100644 --- a/node-graph/interpreted-executor/src/lib.rs +++ b/node-graph/interpreted-executor/src/lib.rs @@ -4,9 +4,8 @@ pub mod util; #[cfg(test)] mod tests { - use graphene_core::*; - use futures::executor::block_on; + use graphene_core::*; #[test] fn double_number() { diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index 8564f36ae..211f76e15 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -1,4 +1,5 @@ use dyn_any::StaticType; +use glam::{DVec2, UVec2}; use graph_craft::document::value::RenderOutput; use graph_craft::proto::{NodeConstructor, TypeErasedBox}; use graphene_core::fn_type; @@ -7,23 +8,21 @@ use graphene_core::raster::image::ImageFrameTable; use graphene_core::raster::*; use graphene_core::value::{ClonedNode, ValueNode}; use graphene_core::vector::VectorDataTable; -use graphene_core::{concrete, generic, Artboard, GraphicGroupTable}; -use graphene_core::{fn_type_fut, future}; +use graphene_core::{Artboard, GraphicGroupTable, concrete, generic}; use graphene_core::{Cow, ProtoNodeIdentifier, Type}; use graphene_core::{Node, NodeIO, NodeIOTypes}; +use graphene_core::{fn_type_fut, future}; +use graphene_std::Context; +use graphene_std::GraphicElement; use graphene_std::any::{ComposeTypeErased, DowncastBothNode, DynAnyNode, FutureWrapperNode, IntoTypeErasedNode}; use graphene_std::application_io::ImageTexture; use graphene_std::wasm_application_io::*; -use graphene_std::Context; -use graphene_std::GraphicElement; -#[cfg(feature = "gpu")] -use wgpu_executor::{ShaderInputFrame, WgpuExecutor}; -use wgpu_executor::{WgpuSurface, WindowHandle}; - -use glam::{DVec2, UVec2}; use once_cell::sync::Lazy; use std::collections::HashMap; use std::sync::Arc; +#[cfg(feature = "gpu")] +use wgpu_executor::{ShaderInputFrame, WgpuExecutor}; +use wgpu_executor::{WgpuSurface, WindowHandle}; macro_rules! async_node { // TODO: we currently need to annotate the type here because the compiler would otherwise (correctly) @@ -193,7 +192,8 @@ fn node_registry() -> HashMap = DowncastBothNode::new(args[0].clone()); // Box::pin(async move { // let curve = ClonedNode::new(curve.eval(()).await); @@ -211,7 +211,8 @@ fn node_registry() -> HashMap = DowncastBothNode::new(args[0].clone()); // Box::pin(async move { // let curve = ValueNode::new(ClonedNode::new(curve.eval(()).await)); diff --git a/node-graph/interpreted-executor/src/util.rs b/node-graph/interpreted-executor/src/util.rs index 4e88b41a5..c0244acec 100644 --- a/node-graph/interpreted-executor/src/util.rs +++ b/node-graph/interpreted-executor/src/util.rs @@ -1,12 +1,12 @@ -use std::sync::Arc; - +use graph_craft::ProtoNodeIdentifier; use graph_craft::concrete; -use graph_craft::document::{value::TaggedValue, DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork}; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork}; use graph_craft::generic; use graph_craft::wasm_application_io::WasmEditorApi; -use graph_craft::ProtoNodeIdentifier; -use graphene_std::uuid::NodeId; use graphene_std::Context; +use graphene_std::uuid::NodeId; +use std::sync::Arc; // TODO: this is copy pasta from the editor (and does get out of sync) pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc) -> NodeNetwork { diff --git a/node-graph/node-macro/Cargo.toml b/node-graph/node-macro/Cargo.toml index 2892be34b..2356bcb2b 100644 --- a/node-graph/node-macro/Cargo.toml +++ b/node-graph/node-macro/Cargo.toml @@ -2,9 +2,9 @@ name = "node-macro" publish = false version = "0.0.0" -rust-version = "1.79" +rust-version = "1.85" authors = ["Graphite Authors "] -edition = "2021" +edition = "2024" readme = "../../README.md" homepage = "https://graphite.rs" repository = "https://github.com/GraphiteEditor/Graphite" diff --git a/node-graph/node-macro/src/codegen.rs b/node-graph/node-macro/src/codegen.rs index 81f82f8c2..af04dd8a0 100644 --- a/node-graph/node-macro/src/codegen.rs +++ b/node-graph/node-macro/src/codegen.rs @@ -1,14 +1,13 @@ -use std::sync::atomic::AtomicU64; - use crate::parsing::*; use convert_case::{Case, Casing}; -use proc_macro2::TokenStream as TokenStream2; use proc_macro_crate::FoundCrate; +use proc_macro2::TokenStream as TokenStream2; use quote::{format_ident, quote}; +use std::sync::atomic::AtomicU64; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::token::Comma; -use syn::{parse_quote, Error, Ident, PatIdent, Token, WhereClause, WherePredicate}; +use syn::{Error, Ident, PatIdent, Token, WhereClause, WherePredicate, parse_quote}; static NODE_ID: AtomicU64 = AtomicU64::new(0); pub(crate) fn generate_node_code(parsed: &ParsedNodeFn) -> syn::Result { @@ -68,8 +67,8 @@ pub(crate) fn generate_node_code(parsed: &ParsedNodeFn) -> syn::Result syn::Result (bool, Option, Option) { let input_type = args.args.iter().find_map(|arg| if let syn::GenericArgument::Type(ty) = arg { Some(ty.clone()) } else { None }); let output_type = args.args.iter().find_map(|arg| { if let syn::GenericArgument::AssocType(assoc_type) = arg { - if assoc_type.ident == "Output" { - Some(assoc_type.ty.clone()) - } else { - None - } + if assoc_type.ident == "Output" { Some(assoc_type.ty.clone()) } else { None } } else { None } @@ -597,8 +593,8 @@ impl ParsedNodeFn { #[cfg(test)] mod tests { use super::*; - use proc_macro2::Span; use proc_macro_crate::FoundCrate; + use proc_macro2::Span; use quote::{quote, quote_spanned}; use syn::parse_quote; fn pat_ident(name: &str) -> PatIdent { diff --git a/node-graph/node-macro/src/validation.rs b/node-graph/node-macro/src/validation.rs index bec5a8325..e6eece212 100644 --- a/node-graph/node-macro/src/validation.rs +++ b/node-graph/node-macro/src/validation.rs @@ -1,8 +1,8 @@ use crate::parsing::{Implementation, ParsedField, ParsedNodeFn}; - use proc_macro_error2::emit_error; use quote::quote; -use syn::{spanned::Spanned, GenericParam, Type}; +use syn::spanned::Spanned; +use syn::{GenericParam, Type}; pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> { let validators: &[fn(&ParsedNodeFn)] = &[ diff --git a/node-graph/wgpu-executor/Cargo.toml b/node-graph/wgpu-executor/Cargo.toml index 8d716e5f0..fd5361713 100644 --- a/node-graph/wgpu-executor/Cargo.toml +++ b/node-graph/wgpu-executor/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "wgpu-executor" version = "0.1.0" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" [features] diff --git a/node-graph/wgpu-executor/src/executor.rs b/node-graph/wgpu-executor/src/executor.rs index db489efcf..82b0f8193 100644 --- a/node-graph/wgpu-executor/src/executor.rs +++ b/node-graph/wgpu-executor/src/executor.rs @@ -1,8 +1,6 @@ use super::context::Context; - -use dyn_any::StaticTypeSized; - use bytemuck::Pod; +use dyn_any::StaticTypeSized; use std::borrow::Cow; use std::error::Error; use std::pin::Pin; diff --git a/node-graph/wgpu-executor/src/lib.rs b/node-graph/wgpu-executor/src/lib.rs index 1f62cdf62..415c577dc 100644 --- a/node-graph/wgpu-executor/src/lib.rs +++ b/node-graph/wgpu-executor/src/lib.rs @@ -1,20 +1,18 @@ mod context; mod executor; +use anyhow::{Result, bail}; pub use context::Context; -pub use executor::GpuExecutor; - use dyn_any::{DynAny, StaticType}; +pub use executor::GpuExecutor; +use futures::Future; +use glam::{DAffine2, UVec2}; use gpu_executor::{ComputePassDimensions, GPUConstant, StorageBufferOptions, TextureBufferOptions, TextureBufferType, ToStorageBuffer, ToUniformBuffer}; use graphene_core::application_io::{ApplicationIo, EditorApi, ImageTexture, SurfaceHandle}; use graphene_core::raster::image::ImageFrameTable; use graphene_core::raster::{Image, SRGBA8}; use graphene_core::transform::{Footprint, Transform}; use graphene_core::{Color, Cow, Ctx, ExtractFootprint, Node, SurfaceFrame, Type}; - -use anyhow::{bail, Result}; -use futures::Future; -use glam::{DAffine2, UVec2}; use std::pin::Pin; use std::sync::Arc; use vello::{AaConfig, AaSupport, RenderParams, Renderer, RendererOptions, Scene}; @@ -473,39 +471,38 @@ impl WgpuExecutor { pub fn read_output_buffer(&self, buffer: Arc) -> Pin>> + Send>> { Box::pin(async move { - if let ShaderInput::ReadBackBuffer(buffer, _) = buffer.as_ref() { - let buffer_slice = buffer.slice(..); - - // Sets the buffer up for mapping, sending over the result of the mapping back to us when it is finished. - let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel(); - buffer_slice.map_async(wgpu::MapMode::Read, move |v| sender.send(v).unwrap()); - - // Wait for the mapping to finish. - #[cfg(feature = "profiling")] - nvtx::range_push!("compute"); - let result = receiver.receive().await; - #[cfg(feature = "profiling")] - nvtx::range_pop!(); - - if result == Some(Ok(())) { - // Gets contents of buffer - let data = buffer_slice.get_mapped_range(); - // Since contents are got in bytes, this converts these bytes back to u32 - let result = bytemuck::cast_slice(&data).to_vec(); - - // With the current interface, we have to make sure all mapped views are - // dropped before we unmap the buffer. - drop(data); - buffer.unmap(); // Unmaps buffer from memory - - // Returns data from buffer - Ok(result) - } else { - bail!("failed to run compute on gpu!") - } - } else { + let ShaderInput::ReadBackBuffer(buffer, _) = buffer.as_ref() else { bail!("Tried to read a non readback buffer") + }; + + let buffer_slice = buffer.slice(..); + + // Sets the buffer up for mapping, sending over the result of the mapping back to us when it is finished. + let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel(); + buffer_slice.map_async(wgpu::MapMode::Read, move |v| sender.send(v).unwrap()); + + // Wait for the mapping to finish. + #[cfg(feature = "profiling")] + nvtx::range_push!("compute"); + let result = receiver.receive().await; + #[cfg(feature = "profiling")] + nvtx::range_pop!(); + + if result.is_none_or(|x| x.is_err()) { + bail!("failed to run compute on gpu!") } + // Gets contents of buffer + let data = buffer_slice.get_mapped_range(); + // Since contents are got in bytes, this converts these bytes back to u32 + let result = bytemuck::cast_slice(&data).to_vec(); + + // With the current interface, we have to make sure all mapped views are + // dropped before we unmap the buffer. + drop(data); + buffer.unmap(); // Unmaps buffer from memory + + // Returns data from buffer + Ok(result) }) } diff --git a/proc-macros/Cargo.toml b/proc-macros/Cargo.toml index 59f5e5382..084226a0a 100644 --- a/proc-macros/Cargo.toml +++ b/proc-macros/Cargo.toml @@ -2,9 +2,9 @@ name = "graphite-proc-macros" publish = false version = "0.0.0" -rust-version = "1.79" +rust-version = "1.85" authors = ["Graphite Authors "] -edition = "2021" +edition = "2024" readme = "../README.md" homepage = "https://graphite.rs" repository = "https://github.com/GraphiteEditor/Graphite" diff --git a/proc-macros/src/combined_message_attrs.rs b/proc-macros/src/combined_message_attrs.rs index a17112619..aadca6384 100644 --- a/proc-macros/src/combined_message_attrs.rs +++ b/proc-macros/src/combined_message_attrs.rs @@ -2,8 +2,8 @@ use crate::helpers::call_site_ident; use proc_macro2::Ident; use proc_macro2::TokenStream; use quote::ToTokens; -use syn::parse::{Parse, ParseStream}; use syn::Token; +use syn::parse::{Parse, ParseStream}; use syn::{ItemEnum, TypePath}; struct MessageArgs { diff --git a/proc-macros/src/helper_structs.rs b/proc-macros/src/helper_structs.rs index 3de2f7a98..52321e759 100644 --- a/proc-macros/src/helper_structs.rs +++ b/proc-macros/src/helper_structs.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::token::Paren; -use syn::{parenthesized, LitStr, Token}; +use syn::{LitStr, Token, parenthesized}; pub struct IdentList { pub parts: Punctuated, diff --git a/proc-macros/src/helpers.rs b/proc-macros/src/helpers.rs index 31ba51d94..11c18c8b4 100644 --- a/proc-macros/src/helpers.rs +++ b/proc-macros/src/helpers.rs @@ -45,7 +45,6 @@ pub fn two_segment_path(left_ident: Ident, right_ident: Ident) -> Path { #[cfg(test)] mod tests { use super::*; - use quote::ToTokens; use syn::spanned::Spanned; diff --git a/proc-macros/src/lib.rs b/proc-macros/src/lib.rs index 0485176bb..88ded95c6 100644 --- a/proc-macros/src/lib.rs +++ b/proc-macros/src/lib.rs @@ -16,7 +16,6 @@ use crate::helper_structs::AttrInnerSingleString; use crate::hint::derive_hint_impl; use crate::transitive_child::derive_transitive_child_impl; use crate::widget_builder::derive_widget_builder_impl; - use proc_macro::TokenStream; /// Derive the `ToDiscriminant` trait and create a `Discriminant` enum @@ -285,7 +284,6 @@ pub fn derive_widget_builder(input_item: TokenStream) -> TokenStream { #[cfg(test)] mod tests { use super::*; - use proc_macro2::TokenStream as TokenStream2; fn ts_assert_eq(l: TokenStream2, r: TokenStream2) { diff --git a/rustfmt.toml b/rustfmt.toml index ed63ba3cd..37f82403e 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,4 +1,4 @@ -edition = "2021" +edition = "2024" hard_tabs = true max_width = 200 newline_style = "Unix" diff --git a/shell.nix b/shell.nix index cf7070fd3..9f158c4e6 100644 --- a/shell.nix +++ b/shell.nix @@ -33,7 +33,7 @@ let rustc-wasm = pkgs.rust-bin.stable.latest.default.override { targets = [ "wasm32-unknown-unknown" ]; # wasm-pack needs this - extensions = [ "rust-src" "rust-analyzer" "clippy"]; + extensions = [ "rust-src" "rust-analyzer" "clippy" "cargo"]; }; in # Make a shell with the dependencies we need @@ -41,7 +41,6 @@ in packages = with pkgs; [ rustc-wasm nodejs - cargo cargo-watch cargo-nextest cargo-expand diff --git a/website/content/volunteer/guide/starting-a-task/code-quality-guidelines.md b/website/content/volunteer/guide/starting-a-task/code-quality-guidelines.md index b64dc2b00..375c8cf18 100644 --- a/website/content/volunteer/guide/starting-a-task/code-quality-guidelines.md +++ b/website/content/volunteer/guide/starting-a-task/code-quality-guidelines.md @@ -39,14 +39,9 @@ Please make a habit of grouping together related lines of code in blocks separat ## Imports -Our imports used to be a mess before we tamed the chaos with these rules. +Our imports used to be a mess before we tamed the chaos with a formatting rule that has to be applied manually, since `rustfmt` doesn't support it. -At the top of Rust files, use the convention of separating imports into three blocks, ordered as: -1. Local (`use super::` and `use crate::`) -2. First-party crates (e.g. `use editor::` or `bezier_rs::`) -3. Third-party libraries (e.g. `use std::` or `use glam::`) - -Combine related imports with common paths at the same depth. For example: +We always combine imports with common paths, but only at the same depth. For example: ```rs use crate::A::B::C; @@ -58,4 +53,13 @@ use crate::A::B::C::Bar; use crate::A::B::C::{self, Foo, Bar}; ``` -But do not combine imports at mixed path depths. For example, `use crate::A::{B::C::Foo, X::Hello};` should be split into two separate import lines— avoid having `::` inside `{}`. +But we do not combine imports at mixed path depths. In other words, never put `::` inside `{}`. For example: + +```rs +use crate::A::{B::C::Foo, X::Hello}; + +// Should be separated into: + +use crate::A::B::C::Foo; +use crate::A::X::Hello; +``` diff --git a/website/other/bezier-rs-demos/wasm/Cargo.toml b/website/other/bezier-rs-demos/wasm/Cargo.toml index 36e1694cd..c9b1d7f66 100644 --- a/website/other/bezier-rs-demos/wasm/Cargo.toml +++ b/website/other/bezier-rs-demos/wasm/Cargo.toml @@ -2,9 +2,9 @@ name = "bezier-rs-wasm" publish = false version = "0.0.0" -rust-version = "1.79" +rust-version = "1.85" authors = ["Graphite Authors "] -edition = "2021" +edition = "2024" readme = "../../README.md" homepage = "https://graphite.rs" repository = "https://github.com/GraphiteEditor/Graphite" diff --git a/website/other/bezier-rs-demos/wasm/src/bezier.rs b/website/other/bezier-rs-demos/wasm/src/bezier.rs index 1bb9b0470..50275b3c7 100644 --- a/website/other/bezier-rs-demos/wasm/src/bezier.rs +++ b/website/other/bezier-rs-demos/wasm/src/bezier.rs @@ -1,8 +1,6 @@ use crate::svg_drawing::*; use crate::utils::{parse_cap, parse_point}; - use bezier_rs::{ArcStrategy, ArcsOptions, Bezier, Identifier, TValue, TValueType}; - use glam::DVec2; use js_sys::Array; use wasm_bindgen::prelude::*; diff --git a/website/other/bezier-rs-demos/wasm/src/subpath.rs b/website/other/bezier-rs-demos/wasm/src/subpath.rs index 026c7b3fa..39b545aca 100644 --- a/website/other/bezier-rs-demos/wasm/src/subpath.rs +++ b/website/other/bezier-rs-demos/wasm/src/subpath.rs @@ -1,8 +1,6 @@ use crate::svg_drawing::*; use crate::utils::{parse_cap, parse_join, parse_point}; - use bezier_rs::{Bezier, ManipulatorGroup, Subpath, SubpathTValue, TValueType}; - use glam::DVec2; use js_sys::Array; use js_sys::Math;