repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/utility_traits.rs | editor/src/utility_traits.rs | pub use crate::dispatcher::*;
use crate::messages::prelude::*;
/// Implements a message handler struct for a separate message struct.
/// - The first type argument (`M`) is that message struct type, representing a message enum variant to be matched and handled in `process_message()`.
/// - The second type argument (`C`) is the type of the context struct that can be passed along by the caller to `process_message()`.
pub trait MessageHandler<M: ToDiscriminant, C>
where
M::Discriminant: AsMessage,
<M::Discriminant as TransitiveChild>::TopParent: TransitiveChild<Parent = <M::Discriminant as TransitiveChild>::TopParent, TopParent = <M::Discriminant as TransitiveChild>::TopParent> + AsMessage,
{
fn process_message(&mut self, message: M, responses: &mut VecDeque<Message>, context: C);
fn actions(&self) -> ActionList;
}
pub type ActionList = Vec<Vec<MessageDiscriminant>>;
pub trait AsMessage: TransitiveChild
where
Self::TopParent: TransitiveChild<Parent = Self::TopParent, TopParent = Self::TopParent> + AsMessage,
{
fn local_name(self) -> String;
fn global_name(self) -> String {
<Self as Into<Self::TopParent>>::into(self).local_name()
}
}
// TODO: Add Send + Sync requirement
// Use something like rw locks for synchronization
pub trait MessageHandlerData {}
pub trait ToDiscriminant {
type Discriminant;
fn to_discriminant(&self) -> Self::Discriminant;
}
pub trait TransitiveChild: Into<Self::Parent> + Into<Self::TopParent> {
type TopParent;
type Parent;
}
pub trait Hint {
fn hints(&self) -> HashMap<String, String>;
}
pub trait HierarchicalTree {
fn build_message_tree() -> DebugMessageTree;
fn message_handler_data_str() -> MessageData {
MessageData::new(String::new(), Vec::new(), "")
}
fn message_handler_str() -> MessageData {
MessageData::new(String::new(), Vec::new(), "")
}
fn path() -> &'static str {
""
}
}
pub trait ExtractField {
fn field_types() -> Vec<(String, usize)>;
fn path() -> &'static str;
fn print_field_types();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/node_graph_executor/runtime.rs | editor/src/node_graph_executor/runtime.rs | use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use glam::{DAffine2, DVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::GraphErrors;
use graph_craft::wasm_application_io::EditorPreferences;
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::application_io::{ApplicationIo, ExportFormat, ImageTexture, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::memo::IORecord;
use graphene_std::ops::Convert;
use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, SvgRender};
use graphene_std::renderer::{RenderSvgSegmentList, SvgSegment};
use graphene_std::table::{Table, TableRow};
use graphene_std::text::FontCache;
use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector;
use graphene_std::wasm_application_io::{RenderOutputType, WasmApplicationIo, WasmEditorApi};
use graphene_std::{Artboard, Context, Graphic};
use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use once_cell::sync::Lazy;
use spin::Mutex;
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 [`GraphRuntimeRequest`]`.
/// Some of these fields are put into a [`WasmEditorApi`] which is passed to the final compiled graph network upon each execution.
/// Once the implementation is finished, this will live in a separate thread. Right now it's part of the main JS thread, but its own separate JS stack frame independent from the editor.
pub struct NodeRuntime {
#[cfg(test)]
pub(super) executor: DynamicExecutor,
#[cfg(not(test))]
executor: DynamicExecutor,
receiver: Receiver<GraphRuntimeRequest>,
sender: InternalNodeGraphUpdateSender,
editor_preferences: EditorPreferences,
old_graph: Option<NodeNetwork>,
update_thumbnails: bool,
editor_api: Arc<WasmEditorApi>,
node_graph_errors: GraphErrors,
monitor_nodes: Vec<Vec<NodeId>>,
/// Which node is inspected and which monitor node is used (if any) for the current execution.
inspect_state: Option<InspectState>,
/// Mapping of the fully-qualified node paths to their preprocessor substitutions.
substitutions: HashMap<ProtoNodeIdentifier, DocumentNode>,
// TODO: Remove, it doesn't need to be persisted anymore
/// The current renders of the thumbnails for layer nodes.
thumbnail_renders: HashMap<NodeId, Vec<SvgSegment>>,
vector_modify: HashMap<NodeId, Vector>,
/// Cached surface for WASM viewport rendering (reused across frames)
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_viewport_surface: Option<wgpu_executor::WgpuSurface>,
}
/// Messages passed from the editor thread to the node runtime thread.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest),
FontCacheUpdate(FontCache),
EditorPreferencesUpdate(EditorPreferences),
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GraphUpdate {
pub(super) network: NodeNetwork,
/// The node that should be temporary inspected during execution
pub(super) node_to_inspect: Option<NodeId>,
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportConfig {
pub name: String,
pub file_type: FileType,
pub scale_factor: f64,
pub bounds: ExportBounds,
pub transparent_background: bool,
pub size: DVec2,
}
#[derive(Clone)]
struct InternalNodeGraphUpdateSender(Sender<NodeGraphUpdate>);
impl InternalNodeGraphUpdateSender {
fn send_generation_response(&self, response: CompilationResponse) {
self.0.send(NodeGraphUpdate::CompilationResponse(response)).expect("Failed to send response")
}
fn send_execution_response(&self, response: ExecutionResponse) {
self.0.send(NodeGraphUpdate::ExecutionResponse(response)).expect("Failed to send response")
}
}
impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender {
fn send(&self, message: NodeGraphUpdateMessage) {
self.0.send(NodeGraphUpdate::NodeGraphUpdateMessage(message)).expect("Failed to send response")
}
}
pub static NODE_RUNTIME: Lazy<Mutex<Option<NodeRuntime>>> = Lazy::new(|| Mutex::new(None));
impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
Self {
executor: DynamicExecutor::default(),
receiver,
sender: InternalNodeGraphUpdateSender(sender.clone()),
editor_preferences: EditorPreferences::default(),
old_graph: None,
update_thumbnails: true,
editor_api: WasmEditorApi {
font_cache: FontCache::default(),
editor_preferences: Box::new(EditorPreferences::default()),
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
application_io: None,
}
.into(),
node_graph_errors: Vec::new(),
monitor_nodes: Vec::new(),
substitutions: preprocessor::generate_node_substitutions(),
thumbnail_renders: Default::default(),
vector_modify: Default::default(),
inspect_state: None,
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_viewport_surface: None,
}
}
pub async fn run(&mut self) -> Option<ImageTexture> {
if self.editor_api.application_io.is_none() {
self.editor_api = WasmEditorApi {
#[cfg(all(not(test), target_family = "wasm"))]
application_io: Some(WasmApplicationIo::new().await.into()),
#[cfg(any(test, not(target_family = "wasm")))]
application_io: Some(WasmApplicationIo::new_offscreen().await.into()),
font_cache: self.editor_api.font_cache.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()),
}
.into();
}
let mut font = None;
let mut preferences = None;
let mut graph = None;
let mut execution = None;
for request in self.receiver.try_iter() {
match request {
GraphRuntimeRequest::GraphUpdate(_) => graph = Some(request),
GraphRuntimeRequest::ExecutionRequest(ref execution_request) => {
let for_export = execution_request.render_config.for_export;
execution = Some(request);
// If we get an export request we always execute it immedeatly otherwise it could get deduplicated
if for_export {
break;
}
}
GraphRuntimeRequest::FontCacheUpdate(_) => font = Some(request),
GraphRuntimeRequest::EditorPreferencesUpdate(_) => preferences = Some(request),
}
}
let requests = [font, preferences, graph, execution].into_iter().flatten();
for request in requests {
match request {
GraphRuntimeRequest::FontCacheUpdate(font_cache) => {
self.editor_api = WasmEditorApi {
font_cache,
application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()),
}
.into();
if let Some(graph) = self.old_graph.clone() {
// We ignore this result as compilation errors should have been reported in an earlier iteration
let _ = self.update_network(graph).await;
}
}
GraphRuntimeRequest::EditorPreferencesUpdate(preferences) => {
self.editor_preferences = preferences.clone();
self.editor_api = WasmEditorApi {
font_cache: self.editor_api.font_cache.clone(),
application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(preferences),
}
.into();
if let Some(graph) = self.old_graph.clone() {
// We ignore this result as compilation errors should have been reported in an earlier iteration
let _ = self.update_network(graph).await;
}
}
GraphRuntimeRequest::GraphUpdate(GraphUpdate { mut network, node_to_inspect }) => {
// Insert the monitor node to manage the inspection
self.inspect_state = node_to_inspect.map(|inspect| InspectState::monitor_inspect_node(&mut network, inspect));
self.old_graph = Some(network.clone());
self.node_graph_errors.clear();
let result = self.update_network(network).await;
let node_graph_errors = self.node_graph_errors.clone();
self.update_thumbnails = true;
self.sender.send_generation_response(CompilationResponse { result, node_graph_errors });
}
GraphRuntimeRequest::ExecutionRequest(ExecutionRequest { execution_id, mut render_config, .. }) => {
// There are cases where we want to export via the svg pipeline eventhough raster was requested.
if matches!(render_config.export_format, ExportFormat::Raster) {
let vello_available = self.editor_api.application_io.as_ref().unwrap().gpu_executor().is_some();
let use_vello = vello_available && self.editor_api.editor_preferences.use_vello();
// On web when the user has disabled vello rendering in the preferences or we are exporting.
// And on all platforms when vello is not supposed to be used.
if !use_vello || cfg!(target_family = "wasm") && render_config.for_export {
render_config.export_format = ExportFormat::Svg;
}
}
let result = self.execute_network(render_config).await;
let mut responses = VecDeque::new();
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
self.process_monitor_nodes(&mut responses, self.update_thumbnails);
self.update_thumbnails = false;
// Resolve the result from the inspection by accessing the monitor node
let inspect_result = self.inspect_state.and_then(|state| state.access(&self.executor));
let (result, texture) = match result {
Ok(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Texture(image_texture),
metadata,
})) if render_config.for_export => {
let executor = self
.editor_api
.application_io
.as_ref()
.unwrap()
.gpu_executor()
.expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(image_texture.texture).convert(Footprint::BOUNDLESS, executor).await;
let (data, width, height) = raster_cpu.to_flat_u8();
(
Ok(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Buffer { data, width, height },
metadata,
})),
None,
)
}
#[cfg(all(target_family = "wasm", feature = "gpu"))]
Ok(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Texture(image_texture),
metadata,
})) if !render_config.for_export => {
// On WASM, for viewport rendering, blit the texture to a surface and return a CanvasFrame
let app_io = self.editor_api.application_io.as_ref().unwrap();
let executor = app_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
// Get or create the cached surface
if self.wasm_viewport_surface.is_none() {
let surface_handle = app_io.create_window();
let wasm_surface = executor
.create_surface(graphene_std::wasm_application_io::WasmSurfaceHandle {
surface: surface_handle.surface.clone(),
window_id: surface_handle.window_id,
})
.expect("Failed to create surface");
self.wasm_viewport_surface = Some(Arc::new(wasm_surface));
}
let surface = self.wasm_viewport_surface.as_ref().unwrap();
// Use logical resolution for CSS sizing, physical resolution for the actual surface/texture
let physical_resolution = render_config.viewport.resolution;
let logical_resolution = physical_resolution.as_dvec2() / render_config.scale;
// Blit the texture to the surface
let mut encoder = executor.context.device.create_command_encoder(&vello::wgpu::CommandEncoderDescriptor {
label: Some("Texture to Surface Blit"),
});
// Configure the surface at physical resolution (for HiDPI displays)
let surface_inner = &surface.surface.inner;
let surface_caps = surface_inner.get_capabilities(&executor.context.adapter);
surface_inner.configure(
&executor.context.device,
&vello::wgpu::SurfaceConfiguration {
usage: vello::wgpu::TextureUsages::RENDER_ATTACHMENT | vello::wgpu::TextureUsages::COPY_DST,
format: vello::wgpu::TextureFormat::Rgba8Unorm,
width: physical_resolution.x,
height: physical_resolution.y,
present_mode: surface_caps.present_modes[0],
alpha_mode: vello::wgpu::CompositeAlphaMode::Opaque,
view_formats: vec![],
desired_maximum_frame_latency: 2,
},
);
let surface_texture = surface_inner.get_current_texture().expect("Failed to get surface texture");
// Blit the rendered texture to the surface
surface.surface.blitter.copy(
&executor.context.device,
&mut encoder,
&image_texture.texture.create_view(&vello::wgpu::TextureViewDescriptor::default()),
&surface_texture.texture.create_view(&vello::wgpu::TextureViewDescriptor::default()),
);
executor.context.queue.submit([encoder.finish()]);
surface_texture.present();
let frame = graphene_std::application_io::SurfaceFrame {
surface_id: surface.window_id,
resolution: logical_resolution,
transform: glam::DAffine2::IDENTITY,
};
(
Ok(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::CanvasFrame(frame),
metadata,
})),
None,
)
}
Ok(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Texture(texture),
metadata,
})) => (
Ok(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Texture(texture.clone()),
metadata,
})),
Some(texture),
),
r => (r, None),
};
self.sender.send_execution_response(ExecutionResponse {
execution_id,
result,
responses,
vector_modify: self.vector_modify.clone(),
inspect_result,
});
return texture;
}
}
}
None
}
async fn update_network(&mut self, mut graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
preprocessor::expand_network(&mut graph, &self.substitutions);
let scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
// We assume only one output
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let c = Compiler {};
let proto_network = match c.compile_single(scoped_network) {
Ok(network) => network,
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
};
self.monitor_nodes = proto_network
.nodes
.iter()
.filter(|(_, node)| node.identifier == graphene_std::memo::monitor::IDENTIFIER)
.map(|(_, node)| node.original_location.path.clone().unwrap_or_default())
.collect::<Vec<_>>();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
self.executor.update(proto_network).await.map_err(|(types, e)| {
self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}"))
})
}
async fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
use graph_craft::graphene_compiler::Executor;
match self.executor.input_type() {
Some(t) if t == concrete!(RenderConfig) => (&self.executor).execute(render_config).await.map_err(|e| e.to_string()),
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()),
Some(t) => Err(format!("Invalid input type {t:?}")),
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)),
}
}
/// Updates state data
pub fn process_monitor_nodes(&mut self, responses: &mut VecDeque<FrontendMessage>, update_thumbnails: bool) {
// TODO: Consider optimizing this since it's currently O(m*n^2), with a sort it could be made O(m * n*log(n))
self.thumbnail_renders.retain(|id, _| self.monitor_nodes.iter().any(|monitor_node_path| monitor_node_path.contains(id)));
for monitor_node_path in &self.monitor_nodes {
// Skip the inspect monitor node
if self.inspect_state.is_some_and(|inspect_state| monitor_node_path.last().copied() == Some(inspect_state.monitor_node)) {
continue;
}
// The monitor nodes are located within a document node, and are thus children in that network, so this gets the parent document node's ID
let Some(parent_network_node_id) = monitor_node_path.len().checked_sub(2).and_then(|index| monitor_node_path.get(index)).copied() else {
warn!("Monitor node has invalid node id");
continue;
};
// Extract the monitor node's stored `Graphic` data
let Ok(introspected_data) = self.executor.introspect(monitor_node_path) else {
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
#[cfg(debug_assertions)]
warn!("Failed to introspect monitor node {}", self.executor.introspect(monitor_node_path).unwrap_err());
continue;
};
// Graphic table: thumbnail
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Table<Graphic>>>() {
if update_thumbnails {
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, responses)
}
}
// Artboard table: thumbnail
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Table<Artboard>>>() {
if update_thumbnails {
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, responses)
}
}
// Vector table: vector modifications
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Table<Vector>>>() {
// Insert the vector modify
let default = TableRow::default();
self.vector_modify
.insert(parent_network_node_id, io.output.iter().next().unwrap_or_else(|| default.as_ref()).element.clone());
}
// Other
else {
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
}
}
}
/// If this is `Graphic` data, regenerate click targets and thumbnails for the layers in the graph, modifying the state and updating the UI.
fn render_thumbnail(thumbnail_renders: &mut HashMap<NodeId, Vec<SvgSegment>>, parent_network_node_id: NodeId, graphic: &impl Render, responses: &mut VecDeque<FrontendMessage>) {
// Skip thumbnails if the layer is too complex (for performance)
if graphic.render_complexity() > 1000 {
let old = thumbnail_renders.insert(parent_network_node_id, Vec::new());
if old.is_none_or(|v| !v.is_empty()) {
responses.push_back(FrontendMessage::UpdateNodeThumbnail {
id: parent_network_node_id,
value: "<svg viewBox=\"0 0 10 10\" data-tooltip-description=\"Dense thumbnail omitted for performance.\"><line x1=\"0\" y1=\"10\" x2=\"10\" y2=\"0\" stroke=\"red\" /></svg>"
.to_string(),
});
}
return;
}
let bounds = match graphic.bounding_box(DAffine2::IDENTITY, true) {
RenderBoundingBox::None => return,
RenderBoundingBox::Infinite => [DVec2::ZERO, DVec2::new(300., 200.)],
RenderBoundingBox::Rectangle(bounds) => bounds,
};
let footprint = Footprint {
transform: DAffine2::from_translation(DVec2::new(bounds[0].x, bounds[0].y)),
resolution: UVec2::new((bounds[1].x - bounds[0].x).abs() as u32, (bounds[1].y - bounds[0].y).abs() as u32),
quality: RenderQuality::Full,
};
// Render the thumbnail from a `Graphic` into an SVG string
let render_params = RenderParams {
footprint,
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
graphic.render_svg(&mut render, &render_params);
// And give the SVG a viewbox and outer <svg>...</svg> wrapper tag
render.format_svg(bounds[0], bounds[1]);
// UPDATE FRONTEND THUMBNAIL
let new_thumbnail_svg = render.svg;
let old_thumbnail_svg = thumbnail_renders.entry(parent_network_node_id).or_default();
if old_thumbnail_svg != &new_thumbnail_svg {
responses.push_back(FrontendMessage::UpdateNodeThumbnail {
id: parent_network_node_id,
value: new_thumbnail_svg.to_svg_string(),
});
*old_thumbnail_svg = new_thumbnail_svg;
}
}
}
pub async fn introspect_node(path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
let runtime = NODE_RUNTIME.lock();
if let Some(ref mut runtime) = runtime.as_ref() {
return runtime.executor.introspect(path);
}
Err(IntrospectError::RuntimeNotReady)
}
pub async fn run_node_graph() -> (bool, Option<ImageTexture>) {
let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) };
if let Some(ref mut runtime) = runtime.as_mut() {
return (true, runtime.run().await);
}
(false, None)
}
pub async fn replace_node_runtime(runtime: NodeRuntime) -> Option<NodeRuntime> {
let mut node_runtime = NODE_RUNTIME.lock();
node_runtime.replace(runtime)
}
pub async fn replace_application_io(application_io: WasmApplicationIo) {
let mut node_runtime = NODE_RUNTIME.lock();
if let Some(node_runtime) = &mut *node_runtime {
node_runtime.editor_api = WasmEditorApi {
font_cache: node_runtime.editor_api.font_cache.clone(),
application_io: Some(application_io.into()),
node_graph_message_sender: Box::new(node_runtime.sender.clone()),
editor_preferences: Box::new(node_runtime.editor_preferences.clone()),
}
.into();
}
}
/// Which node is inspected and which monitor node is used (if any) for the current execution
#[derive(Debug, Clone, Copy)]
struct InspectState {
inspect_node: NodeId,
monitor_node: NodeId,
}
/// The resulting value from the temporary inspected during execution
#[derive(Clone, Debug, Default)]
pub struct InspectResult {
introspected_data: Option<Arc<dyn std::any::Any + Send + Sync + 'static>>,
pub inspect_node: NodeId,
}
impl InspectResult {
pub fn take_data(&mut self) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
self.introspected_data.clone()
}
}
// This is very ugly but is required to be inside a message
impl PartialEq for InspectResult {
fn eq(&self, other: &Self) -> bool {
self.inspect_node == other.inspect_node
}
}
impl InspectState {
/// Insert the monitor node to manage the inspection
pub fn monitor_inspect_node(network: &mut NodeNetwork, inspect_node: NodeId) -> Self {
let monitor_id = NodeId::new();
// It is necessary to replace the inputs before inserting the monitor node to avoid changing the input of the new monitor node
for input in network.nodes.values_mut().flat_map(|node| node.inputs.iter_mut()).chain(&mut network.exports) {
let NodeInput::Node { node_id, output_index, .. } = input else { continue };
// We only care about the primary output of our inspect node
if *output_index != 0 || *node_id != inspect_node {
continue;
}
*node_id = monitor_id;
}
let monitor_node = DocumentNode {
inputs: vec![NodeInput::node(inspect_node, 0)], // Connect to the primary output of the inspect node
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER),
call_argument: graph_craft::generic!(T),
skip_deduplication: true,
..Default::default()
};
network.nodes.insert(monitor_id, monitor_node);
Self {
inspect_node,
monitor_node: monitor_id,
}
}
/// Resolve the result from the inspection by accessing the monitor node
fn access(&self, executor: &DynamicExecutor) -> Option<InspectResult> {
let introspected_data = executor.introspect(&[self.monitor_node]).inspect_err(|e| warn!("Failed to introspect monitor node {e}")).ok();
// TODO: Consider displaying the error instead of ignoring it
Some(InspectResult {
inspect_node: self.inspect_node,
introspected_data,
})
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/node_graph_executor/runtime_io.rs | editor/src/node_graph_executor/runtime_io.rs | use super::*;
use std::sync::mpsc::{Receiver, Sender};
/// Handles communication with the NodeRuntime
#[derive(Debug)]
pub struct NodeRuntimeIO {
// Send to
sender: Sender<GraphRuntimeRequest>,
receiver: Receiver<NodeGraphUpdate>,
}
impl Default for NodeRuntimeIO {
fn default() -> Self {
Self::new()
}
}
impl NodeRuntimeIO {
/// Creates a new NodeRuntimeIO instance
pub fn new() -> Self {
let (response_sender, response_receiver) = std::sync::mpsc::channel();
let (request_sender, request_receiver) = std::sync::mpsc::channel();
futures::executor::block_on(replace_node_runtime(NodeRuntime::new(request_receiver, response_sender)));
Self {
sender: request_sender,
receiver: response_receiver,
}
}
#[cfg(test)]
pub fn with_channels(sender: Sender<GraphRuntimeRequest>, receiver: Receiver<NodeGraphUpdate>) -> Self {
Self { sender, receiver }
}
/// Sends a message to the NodeRuntime
pub fn send(&self, message: GraphRuntimeRequest) -> Result<(), String> {
self.sender.send(message).map_err(|e| e.to_string())
}
/// Receives any pending updates from the NodeRuntime
pub fn receive(&self) -> impl Iterator<Item = NodeGraphUpdate> + use<'_> {
self.receiver.try_iter()
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/prelude.rs | editor/src/messages/prelude.rs | // Message-related
pub use crate::utility_traits::{ActionList, AsMessage, ExtractField, HierarchicalTree, MessageHandler, ToDiscriminant, TransitiveChild};
pub use crate::utility_types::{DebugMessageTree, MessageData};
// Message, MessageData, MessageDiscriminant, MessageHandler
pub use crate::messages::animation::{AnimationMessage, AnimationMessageDiscriminant, AnimationMessageHandler};
pub use crate::messages::app_window::{AppWindowMessage, AppWindowMessageDiscriminant, AppWindowMessageHandler};
pub use crate::messages::broadcast::event::{EventMessage, EventMessageContext, EventMessageDiscriminant, EventMessageHandler};
pub use crate::messages::broadcast::{BroadcastMessage, BroadcastMessageDiscriminant, BroadcastMessageHandler};
pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageDiscriminant, ClipboardMessageHandler};
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler};
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
pub use crate::messages::dialog::{DialogMessage, DialogMessageContext, DialogMessageDiscriminant, DialogMessageHandler};
pub use crate::messages::frontend::{FrontendMessage, FrontendMessageDiscriminant};
pub use crate::messages::globals::{GlobalsMessage, GlobalsMessageDiscriminant, GlobalsMessageHandler};
pub use crate::messages::input_mapper::key_mapping::{KeyMappingMessage, KeyMappingMessageContext, KeyMappingMessageDiscriminant, KeyMappingMessageHandler};
pub use crate::messages::input_mapper::{InputMapperMessage, InputMapperMessageContext, InputMapperMessageDiscriminant, InputMapperMessageHandler};
pub use crate::messages::input_preprocessor::{InputPreprocessorMessage, InputPreprocessorMessageContext, InputPreprocessorMessageDiscriminant, InputPreprocessorMessageHandler};
pub use crate::messages::layout::{LayoutMessage, LayoutMessageDiscriminant, LayoutMessageHandler};
pub use crate::messages::menu_bar::{MenuBarMessage, MenuBarMessageDiscriminant, MenuBarMessageHandler};
pub use crate::messages::portfolio::document::data_panel::{DataPanelMessage, DataPanelMessageDiscriminant};
pub use crate::messages::portfolio::document::graph_operation::{GraphOperationMessage, GraphOperationMessageContext, GraphOperationMessageDiscriminant, GraphOperationMessageHandler};
pub use crate::messages::portfolio::document::navigation::{NavigationMessage, NavigationMessageContext, NavigationMessageDiscriminant, NavigationMessageHandler};
pub use crate::messages::portfolio::document::node_graph::{NodeGraphMessage, NodeGraphMessageDiscriminant, NodeGraphMessageHandler};
pub use crate::messages::portfolio::document::overlays::{OverlaysMessage, OverlaysMessageContext, OverlaysMessageDiscriminant, OverlaysMessageHandler};
pub use crate::messages::portfolio::document::properties_panel::{PropertiesPanelMessage, PropertiesPanelMessageDiscriminant, PropertiesPanelMessageHandler};
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
pub use crate::messages::portfolio::{PortfolioMessage, PortfolioMessageContext, PortfolioMessageDiscriminant, PortfolioMessageHandler};
pub use crate::messages::preferences::{PreferencesMessage, PreferencesMessageDiscriminant, PreferencesMessageHandler};
pub use crate::messages::tool::transform_layer::{TransformLayerMessage, TransformLayerMessageDiscriminant, TransformLayerMessageHandler};
pub use crate::messages::tool::{ToolMessage, ToolMessageContext, ToolMessageDiscriminant, ToolMessageHandler};
pub use crate::messages::viewport::{ViewportMessage, ViewportMessageDiscriminant, ViewportMessageHandler};
// Message, MessageDiscriminant
pub use crate::messages::message::{Message, MessageDiscriminant};
pub use crate::messages::tool::tool_messages::artboard_tool::{ArtboardToolMessage, ArtboardToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::brush_tool::{BrushToolMessage, BrushToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::eyedropper_tool::{EyedropperToolMessage, EyedropperToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::fill_tool::{FillToolMessage, FillToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::freehand_tool::{FreehandToolMessage, FreehandToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::gradient_tool::{GradientToolMessage, GradientToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::navigate_tool::{NavigateToolMessage, NavigateToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::path_tool::{PathToolMessage, PathToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::pen_tool::{PenToolMessage, PenToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::select_tool::{SelectToolMessage, SelectToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::shape_tool::{ShapeToolMessage, ShapeToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::spline_tool::{SplineToolMessage, SplineToolMessageDiscriminant};
pub use crate::messages::tool::tool_messages::text_tool::{TextToolMessage, TextToolMessageDiscriminant};
// Helper/miscellaneous
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 {
fn add(&mut self, message: impl Into<Message>);
fn add_front(&mut self, message: impl Into<Message>);
fn try_add(&mut self, message: Option<impl Into<Message>>) {
if let Some(message) = message {
self.add(message);
}
}
}
impl Responses for VecDeque<Message> {
#[inline(always)]
fn add(&mut self, message: impl Into<Message>) {
self.push_back(message.into());
}
#[inline(always)]
fn add_front(&mut self, message: impl Into<Message>) {
self.push_front(message.into());
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/mod.rs | editor/src/messages/mod.rs | //! The root-level messages forming the first layer of the message system architecture.
pub mod animation;
pub mod app_window;
pub mod broadcast;
pub mod clipboard;
pub mod debug;
pub mod defer;
pub mod dialog;
pub mod frontend;
pub mod globals;
pub mod input_mapper;
pub mod input_preprocessor;
pub mod layout;
pub mod menu_bar;
pub mod message;
pub mod portfolio;
pub mod preferences;
pub mod prelude;
pub mod tool;
pub mod viewport;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/message.rs | editor/src/messages/message.rs | use crate::messages::prelude::*;
use graphite_proc_macros::*;
#[impl_message]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Message {
// Sub-messages
#[child]
Animation(AnimationMessage),
#[child]
AppWindow(AppWindowMessage),
#[child]
Broadcast(BroadcastMessage),
#[child]
Clipboard(ClipboardMessage),
#[child]
Debug(DebugMessage),
#[child]
Defer(DeferMessage),
#[child]
Dialog(DialogMessage),
#[child]
Frontend(FrontendMessage),
#[child]
Globals(GlobalsMessage),
#[child]
InputPreprocessor(InputPreprocessorMessage),
#[child]
KeyMapping(KeyMappingMessage),
#[child]
Layout(LayoutMessage),
#[child]
MenuBar(MenuBarMessage),
#[child]
Portfolio(PortfolioMessage),
#[child]
Preferences(PreferencesMessage),
#[child]
Tool(ToolMessage),
#[child]
Viewport(ViewportMessage),
// Messages
Batched {
messages: Box<[Message]>,
},
NoOp,
}
/// Provides an impl of `specta::Type` for `MessageDiscriminant`, the struct created by `impl_message`.
/// Specta isn't integrated with `impl_message`, so a remote impl must be provided using this struct.
impl specta::Type for MessageDiscriminant {
fn inline(_type_map: &mut specta::TypeCollection, _generics: specta::Generics) -> specta::DataType {
specta::DataType::Any
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::Write;
#[test]
fn generate_message_tree() {
let result = Message::build_message_tree();
let mut file = std::fs::File::create("../hierarchical_message_system_tree.txt").unwrap();
file.write_all(format!("{} `{}`\n", result.name(), result.path()).as_bytes()).unwrap();
if let Some(variants) = result.variants() {
for (i, variant) in variants.iter().enumerate() {
let is_last = i == variants.len() - 1;
print_tree_node(variant, "", is_last, &mut file);
}
}
}
fn print_tree_node(tree: &DebugMessageTree, prefix: &str, is_last: bool, file: &mut std::fs::File) {
// Print the current node
let (branch, child_prefix) = if tree.message_handler_data_fields().is_some() || tree.message_handler_fields().is_some() {
("βββ ", format!("{prefix}β "))
} else if is_last {
("βββ ", format!("{prefix} "))
} else {
("βββ ", format!("{prefix}β "))
};
if tree.path().is_empty() {
file.write_all(format!("{}{}{}\n", prefix, branch, tree.name()).as_bytes()).unwrap();
} else {
file.write_all(format!("{}{}{} `{}`\n", prefix, branch, tree.name(), tree.path()).as_bytes()).unwrap();
}
// Print children if any
if let Some(variants) = tree.variants() {
let len = variants.len();
for (i, variant) in variants.iter().enumerate() {
let is_last_child = i == len - 1;
print_tree_node(variant, &child_prefix, is_last_child, file);
}
}
// Print message field if any
if let Some(fields) = tree.fields() {
let len = fields.len();
for (i, field) in fields.iter().enumerate() {
let is_last_field = i == len - 1;
let branch = if is_last_field { "βββ " } else { "βββ " };
file.write_all(format!("{child_prefix}{branch}{field}\n").as_bytes()).unwrap();
}
}
// Print handler field if any
if let Some(data) = tree.message_handler_fields() {
let len = data.fields().len();
let (branch, child_prefix) = if tree.message_handler_data_fields().is_some() {
("βββ ", format!("{prefix}β "))
} else {
("βββ ", format!("{prefix} "))
};
const FRONTEND_MESSAGE_STR: &str = "FrontendMessage";
if data.name().is_empty() && tree.name() != FRONTEND_MESSAGE_STR {
panic!("{}'s MessageHandler is missing #[message_handler_data]", tree.name());
} else if tree.name() != FRONTEND_MESSAGE_STR {
file.write_all(format!("{}{}{} `{}`\n", prefix, branch, data.name(), data.path()).as_bytes()).unwrap();
for (i, field) in data.fields().iter().enumerate() {
let is_last_field = i == len - 1;
let branch = if is_last_field { "βββ " } else { "βββ " };
file.write_all(format!("{}{}{}\n", child_prefix, branch, field.0).as_bytes()).unwrap();
}
}
}
// Print data field if any
if let Some(data) = tree.message_handler_data_fields() {
let len = data.fields().len();
if data.path().is_empty() {
file.write_all(format!("{}{}{}\n", prefix, "βββ ", data.name()).as_bytes()).unwrap();
} else {
file.write_all(format!("{}{}{} `{}`\n", prefix, "βββ ", data.name(), data.path()).as_bytes()).unwrap();
}
for (i, field) in data.fields().iter().enumerate() {
let is_last_field = i == len - 1;
let branch = if is_last_field { "βββ " } else { "βββ " };
file.write_all(format!("{}{}{}\n", format!("{} ", prefix), branch, field.0).as_bytes()).unwrap();
}
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/menu_bar/menu_bar_message_handler.rs | editor/src/messages/menu_bar/menu_bar_message_handler.rs | use crate::messages::debug::utility_types::MessageLoggingVerbosity;
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GroupFolderType};
use crate::messages::prelude::*;
use graphene_std::path_bool::BooleanOperation;
#[derive(Debug, Clone, Default, ExtractField)]
pub struct MenuBarMessageHandler {
pub has_active_document: bool,
pub canvas_tilted: bool,
pub canvas_flipped: bool,
pub rulers_visible: bool,
pub node_graph_open: bool,
pub has_selected_nodes: bool,
pub has_selected_layers: bool,
pub has_selection_history: (bool, bool),
pub message_logging_verbosity: MessageLoggingVerbosity,
pub reset_node_definitions_on_open: bool,
pub make_path_editable_is_allowed: bool,
pub data_panel_open: bool,
pub layers_panel_open: bool,
pub properties_panel_open: bool,
}
#[message_handler_data]
impl MessageHandler<MenuBarMessage, ()> for MenuBarMessageHandler {
fn process_message(&mut self, message: MenuBarMessage, responses: &mut VecDeque<Message>, _: ()) {
match message {
MenuBarMessage::SendLayout => {
self.send_layout(responses, LayoutTarget::MenuBar);
}
}
}
fn actions(&self) -> ActionList {
actions!(MenuBarMessageDiscriminant;)
}
}
impl LayoutHolder for MenuBarMessageHandler {
fn layout(&self) -> Layout {
let no_active_document = !self.has_active_document;
let node_graph_open = self.node_graph_open;
let has_selected_nodes = self.has_selected_nodes;
let has_selected_layers = self.has_selected_layers;
let has_selection_history = self.has_selection_history;
let message_logging_verbosity_off = self.message_logging_verbosity == MessageLoggingVerbosity::Off;
let message_logging_verbosity_names = self.message_logging_verbosity == MessageLoggingVerbosity::Names;
let message_logging_verbosity_contents = self.message_logging_verbosity == MessageLoggingVerbosity::Contents;
let reset_node_definitions_on_open = self.reset_node_definitions_on_open;
let make_path_editable_is_allowed = self.make_path_editable_is_allowed;
let about = MenuListEntry::new("About Graphiteβ¦")
.label({
#[cfg(not(target_os = "macos"))]
{
"About Graphiteβ¦"
}
#[cfg(target_os = "macos")]
{
"About Graphite"
}
})
.icon("GraphiteLogo")
.on_commit(|_| DialogMessage::RequestAboutGraphiteDialog.into());
let preferences = MenuListEntry::new("Preferencesβ¦")
.label("Preferencesβ¦")
.icon("Settings")
.tooltip_shortcut(action_shortcut!(DialogMessageDiscriminant::RequestPreferencesDialog))
.on_commit(|_| DialogMessage::RequestPreferencesDialog.into());
let menu_bar_buttons = vec![
#[cfg(not(target_os = "macos"))]
TextButton::new("Graphite")
.label("")
.flush(true)
.icon(Some("GraphiteLogo".into()))
.on_commit(|_| FrontendMessage::TriggerVisitLink { url: "https://graphite.art".into() }.into())
.widget_instance(),
#[cfg(target_os = "macos")]
TextButton::new("Graphite")
.label("")
.flush(true)
.menu_list_children(vec![
vec![about],
vec![preferences],
vec![
MenuListEntry::new("Hide Graphite")
.label("Hide Graphite")
.tooltip_shortcut(action_shortcut!(AppWindowMessageDiscriminant::Hide))
.on_commit(|_| AppWindowMessage::Hide.into()),
MenuListEntry::new("Hide Others")
.label("Hide Others")
.tooltip_shortcut(action_shortcut!(AppWindowMessageDiscriminant::HideOthers))
.on_commit(|_| AppWindowMessage::HideOthers.into()),
MenuListEntry::new("Show All")
.label("Show All")
.tooltip_shortcut(action_shortcut!(AppWindowMessageDiscriminant::ShowAll))
.on_commit(|_| AppWindowMessage::ShowAll.into()),
],
vec![
MenuListEntry::new("Quit Graphite")
.label("Quit Graphite")
.tooltip_shortcut(action_shortcut!(AppWindowMessageDiscriminant::Close))
.on_commit(|_| AppWindowMessage::Close.into()),
],
])
.widget_instance(),
TextButton::new("File")
.label("File")
.flush(true)
.menu_list_children(vec![
vec![
MenuListEntry::new("Newβ¦")
.label("Newβ¦")
.icon("File")
.on_commit(|_| DialogMessage::RequestNewDocumentDialog.into())
.tooltip_shortcut(action_shortcut!(DialogMessageDiscriminant::RequestNewDocumentDialog)),
MenuListEntry::new("Openβ¦")
.label("Openβ¦")
.icon("Folder")
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::OpenDocument))
.on_commit(|_| PortfolioMessage::OpenDocument.into()),
MenuListEntry::new("Open Demo Artworkβ¦")
.label("Open Demo Artworkβ¦")
.icon("Image")
.on_commit(|_| DialogMessage::RequestDemoArtworkDialog.into()),
],
vec![
MenuListEntry::new("Close")
.label("Close")
.icon("Close")
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::CloseActiveDocumentWithConfirmation))
.on_commit(|_| PortfolioMessage::CloseActiveDocumentWithConfirmation.into())
.disabled(no_active_document),
MenuListEntry::new("Close All")
.label("Close All")
.icon("CloseAll")
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::CloseAllDocumentsWithConfirmation))
.on_commit(|_| PortfolioMessage::CloseAllDocumentsWithConfirmation.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Save")
.label("Save")
.icon("Save")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SaveDocument))
.on_commit(|_| DocumentMessage::SaveDocument.into())
.disabled(no_active_document),
#[cfg(not(target_family = "wasm"))]
MenuListEntry::new("Save Asβ¦")
.label("Save Asβ¦")
.icon("Save")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SaveDocumentAs))
.on_commit(|_| DocumentMessage::SaveDocumentAs.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Importβ¦")
.label("Importβ¦")
.icon("FileImport")
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::Import))
.on_commit(|_| PortfolioMessage::Import.into()),
MenuListEntry::new("Exportβ¦")
.label("Exportβ¦")
.icon("FileExport")
.tooltip_shortcut(action_shortcut!(DialogMessageDiscriminant::RequestExportDialog))
.on_commit(|_| DialogMessage::RequestExportDialog.into())
.disabled(no_active_document),
],
#[cfg(not(target_os = "macos"))]
vec![preferences],
])
.widget_instance(),
TextButton::new("Edit")
.label("Edit")
.flush(true)
.menu_list_children(vec![
vec![
MenuListEntry::new("Undo")
.label("Undo")
.icon("HistoryUndo")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::Undo))
.on_commit(|_| DocumentMessage::Undo.into())
.disabled(no_active_document),
MenuListEntry::new("Redo")
.label("Redo")
.icon("HistoryRedo")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::Redo))
.on_commit(|_| DocumentMessage::Redo.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Cut")
.label("Cut")
.icon("Cut")
.tooltip_shortcut(action_shortcut!(ClipboardMessageDiscriminant::Cut))
.on_commit(|_| ClipboardMessage::Cut.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Copy")
.label("Copy")
.icon("Copy")
.tooltip_shortcut(action_shortcut!(ClipboardMessageDiscriminant::Copy))
.on_commit(|_| ClipboardMessage::Copy.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Paste")
.label("Paste")
.icon("Paste")
.tooltip_shortcut(action_shortcut!(ClipboardMessageDiscriminant::Paste))
.on_commit(|_| ClipboardMessage::Paste.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Duplicate")
.label("Duplicate")
.icon("Copy")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DuplicateSelectedLayers))
.on_commit(|_| DocumentMessage::DuplicateSelectedLayers.into())
.disabled(no_active_document || !has_selected_nodes),
MenuListEntry::new("Delete")
.label("Delete")
.icon("Trash")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DeleteSelectedLayers))
.on_commit(|_| DocumentMessage::DeleteSelectedLayers.into())
.disabled(no_active_document || !has_selected_nodes),
],
vec![
MenuListEntry::new("Convert to Infinite Canvas")
.label("Convert to Infinite Canvas")
.icon("Artboard")
.on_commit(|_| DocumentMessage::RemoveArtboards.into())
.disabled(no_active_document),
],
])
.widget_instance(),
TextButton::new("Layer")
.label("Layer")
.flush(true)
.menu_list_children(vec![
vec![
MenuListEntry::new("New")
.label("New")
.icon("NewLayer")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::CreateEmptyFolder))
.on_commit(|_| DocumentMessage::CreateEmptyFolder.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Group")
.label("Group")
.icon("Folder")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::GroupSelectedLayers))
.on_commit(|_| {
DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
}
.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Ungroup")
.label("Ungroup")
.icon("FolderOpen")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::UngroupSelectedLayers))
.on_commit(|_| DocumentMessage::UngroupSelectedLayers.into())
.disabled(no_active_document || !has_selected_layers),
],
vec![
MenuListEntry::new("Hide/Show")
.label("Hide/Show")
.icon("EyeHide")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedVisibility))
.on_commit(|_| DocumentMessage::ToggleSelectedVisibility.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Lock/Unlock")
.label("Lock/Unlock")
.icon("PadlockLocked")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedLocked))
.on_commit(|_| DocumentMessage::ToggleSelectedLocked.into())
.disabled(no_active_document || !has_selected_layers),
],
vec![
MenuListEntry::new("Grab")
.label("Grab")
.icon("TransformationGrab")
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginGrab))
.on_commit(|_| TransformLayerMessage::BeginGrab.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Rotate")
.label("Rotate")
.icon("TransformationRotate")
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginRotate))
.on_commit(|_| TransformLayerMessage::BeginRotate.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Scale")
.label("Scale")
.icon("TransformationScale")
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginScale))
.on_commit(|_| TransformLayerMessage::BeginScale.into())
.disabled(no_active_document || !has_selected_layers),
],
vec![
MenuListEntry::new("Arrange")
.label("Arrange")
.icon("StackHollow")
.disabled(no_active_document || !has_selected_layers)
.children(vec![
vec![
MenuListEntry::new("Raise To Front")
.label("Raise To Front")
.icon("Stack")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectedLayersRaiseToFront))
.on_commit(|_| DocumentMessage::SelectedLayersRaiseToFront.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Raise")
.label("Raise")
.icon("StackRaise")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectedLayersRaise))
.on_commit(|_| DocumentMessage::SelectedLayersRaise.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Lower")
.label("Lower")
.icon("StackLower")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectedLayersLower))
.on_commit(|_| DocumentMessage::SelectedLayersLower.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Lower to Back")
.label("Lower to Back")
.icon("StackBottom")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectedLayersLowerToBack))
.on_commit(|_| DocumentMessage::SelectedLayersLowerToBack.into())
.disabled(no_active_document || !has_selected_layers),
],
vec![
MenuListEntry::new("Reverse")
.label("Reverse")
.icon("StackReverse")
.on_commit(|_| DocumentMessage::SelectedLayersReverse.into())
.disabled(no_active_document || !has_selected_layers),
],
]),
MenuListEntry::new("Align")
.label("Align")
.icon("AlignVerticalCenter")
.disabled(no_active_document || !has_selected_layers)
.children(vec![
vec![
MenuListEntry::new("Align Left")
.label("Align Left")
.icon("AlignLeft")
.on_commit(|_| {
DocumentMessage::AlignSelectedLayers {
axis: AlignAxis::X,
aggregate: AlignAggregate::Min,
}
.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Align Horizontal Center")
.label("Align Horizontal Center")
.icon("AlignHorizontalCenter")
.on_commit(|_| {
DocumentMessage::AlignSelectedLayers {
axis: AlignAxis::X,
aggregate: AlignAggregate::Center,
}
.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Align Right")
.label("Align Right")
.icon("AlignRight")
.on_commit(|_| {
DocumentMessage::AlignSelectedLayers {
axis: AlignAxis::X,
aggregate: AlignAggregate::Max,
}
.into()
})
.disabled(no_active_document || !has_selected_layers),
],
vec![
MenuListEntry::new("Align Top")
.label("Align Top")
.icon("AlignTop")
.on_commit(|_| {
DocumentMessage::AlignSelectedLayers {
axis: AlignAxis::Y,
aggregate: AlignAggregate::Min,
}
.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Align Vertical Center")
.label("Align Vertical Center")
.icon("AlignVerticalCenter")
.on_commit(|_| {
DocumentMessage::AlignSelectedLayers {
axis: AlignAxis::Y,
aggregate: AlignAggregate::Center,
}
.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Align Bottom")
.label("Align Bottom")
.icon("AlignBottom")
.on_commit(|_| {
DocumentMessage::AlignSelectedLayers {
axis: AlignAxis::Y,
aggregate: AlignAggregate::Max,
}
.into()
})
.disabled(no_active_document || !has_selected_layers),
],
]),
MenuListEntry::new("Flip")
.label("Flip")
.icon("FlipVertical")
.disabled(no_active_document || !has_selected_layers)
.children(vec![vec![
MenuListEntry::new("Flip Horizontal")
.label("Flip Horizontal")
.icon("FlipHorizontal")
.on_commit(|_| DocumentMessage::FlipSelectedLayers { flip_axis: FlipAxis::X }.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Flip Vertical")
.label("Flip Vertical")
.icon("FlipVertical")
.on_commit(|_| DocumentMessage::FlipSelectedLayers { flip_axis: FlipAxis::Y }.into())
.disabled(no_active_document || !has_selected_layers),
]]),
MenuListEntry::new("Turn")
.label("Turn")
.icon("TurnPositive90")
.disabled(no_active_document || !has_selected_layers)
.children(vec![vec![
MenuListEntry::new("Turn -90Β°")
.label("Turn -90Β°")
.icon("TurnNegative90")
.on_commit(|_| DocumentMessage::RotateSelectedLayers { degrees: -90. }.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Turn 90Β°")
.label("Turn 90Β°")
.icon("TurnPositive90")
.on_commit(|_| DocumentMessage::RotateSelectedLayers { degrees: 90. }.into())
.disabled(no_active_document || !has_selected_layers),
]]),
MenuListEntry::new("Boolean")
.label("Boolean")
.icon("BooleanSubtractFront")
.disabled(no_active_document || !has_selected_layers)
.children(vec![vec![
MenuListEntry::new("Union")
.label("Union")
.icon("BooleanUnion")
.on_commit(|_| {
let group_folder_type = GroupFolderType::BooleanOperation(BooleanOperation::Union);
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Subtract Front")
.label("Subtract Front")
.icon("BooleanSubtractFront")
.on_commit(|_| {
let group_folder_type = GroupFolderType::BooleanOperation(BooleanOperation::SubtractFront);
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Subtract Back")
.label("Subtract Back")
.icon("BooleanSubtractBack")
.on_commit(|_| {
let group_folder_type = GroupFolderType::BooleanOperation(BooleanOperation::SubtractBack);
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Intersect")
.label("Intersect")
.icon("BooleanIntersect")
.on_commit(|_| {
let group_folder_type = GroupFolderType::BooleanOperation(BooleanOperation::Intersect);
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
})
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Difference")
.label("Difference")
.icon("BooleanDifference")
.on_commit(|_| {
let group_folder_type = GroupFolderType::BooleanOperation(BooleanOperation::Difference);
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
})
.disabled(no_active_document || !has_selected_layers),
]]),
],
vec![
MenuListEntry::new("Make Path Editable")
.label("Make Path Editable")
.icon("NodeShape")
.on_commit(|_| NodeGraphMessage::AddPathNode.into())
.disabled(!make_path_editable_is_allowed),
],
])
.widget_instance(),
TextButton::new("Select")
.label("Select")
.flush(true)
.menu_list_children(vec![
vec![
MenuListEntry::new("Select All")
.label("Select All")
.icon("SelectAll")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectAllLayers))
.on_commit(|_| DocumentMessage::SelectAllLayers.into())
.disabled(no_active_document),
MenuListEntry::new("Deselect All")
.label("Deselect All")
.icon("DeselectAll")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DeselectAllLayers))
.on_commit(|_| DocumentMessage::DeselectAllLayers.into())
.disabled(no_active_document || !has_selected_nodes),
MenuListEntry::new("Select Parent")
.label("Select Parent")
.icon("SelectParent")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectParentLayer))
.on_commit(|_| DocumentMessage::SelectParentLayer.into())
.disabled(no_active_document || !has_selected_nodes),
],
vec![
MenuListEntry::new("Previous Selection")
.label("Previous Selection")
.icon("HistoryUndo")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectionStepBack))
.on_commit(|_| DocumentMessage::SelectionStepBack.into())
.disabled(!has_selection_history.0),
MenuListEntry::new("Next Selection")
.label("Next Selection")
.icon("HistoryRedo")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectionStepForward))
.on_commit(|_| DocumentMessage::SelectionStepForward.into())
.disabled(!has_selection_history.1),
],
])
.widget_instance(),
TextButton::new("View")
.label("View")
.flush(true)
.menu_list_children(vec![
vec![
MenuListEntry::new("Tilt")
.label("Tilt")
.icon("Tilt")
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::BeginCanvasTilt))
.on_commit(|_| NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: true }.into())
.disabled(no_active_document || node_graph_open),
MenuListEntry::new("Reset Tilt")
.label("Reset Tilt")
.icon("TiltReset")
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::CanvasTiltSet))
.on_commit(|_| NavigationMessage::CanvasTiltSet { angle_radians: 0.into() }.into())
.disabled(no_active_document || node_graph_open || !self.canvas_tilted),
],
vec![
MenuListEntry::new("Zoom In")
.label("Zoom In")
.icon("ZoomIn")
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::CanvasZoomIncrease))
.on_commit(|_| NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }.into())
.disabled(no_active_document),
MenuListEntry::new("Zoom Out")
.label("Zoom Out")
.icon("ZoomOut")
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::CanvasZoomDecrease))
.on_commit(|_| NavigationMessage::CanvasZoomDecrease { center_on_mouse: false }.into())
.disabled(no_active_document),
MenuListEntry::new("Zoom to Selection")
.label("Zoom to Selection")
.icon("FrameSelected")
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::FitViewportToSelection))
.on_commit(|_| NavigationMessage::FitViewportToSelection.into())
.disabled(no_active_document || !has_selected_layers),
MenuListEntry::new("Zoom to Fit")
.label("Zoom to Fit")
.icon("FrameAll")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ZoomCanvasToFitAll))
.on_commit(|_| DocumentMessage::ZoomCanvasToFitAll.into())
.disabled(no_active_document),
MenuListEntry::new("Zoom to 100%")
.label("Zoom to 100%")
.icon("Zoom1x")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ZoomCanvasTo100Percent))
.on_commit(|_| DocumentMessage::ZoomCanvasTo100Percent.into())
.disabled(no_active_document),
MenuListEntry::new("Zoom to 200%")
.label("Zoom to 200%")
.icon("Zoom2x")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ZoomCanvasTo200Percent))
.on_commit(|_| DocumentMessage::ZoomCanvasTo200Percent.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Flip")
.label("Flip")
.icon(if self.canvas_flipped { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::CanvasFlip))
.on_commit(|_| NavigationMessage::CanvasFlip.into())
.disabled(no_active_document || node_graph_open),
],
vec![
MenuListEntry::new("Rulers")
.label("Rulers")
.icon(if self.rulers_visible { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleRulers))
.on_commit(|_| PortfolioMessage::ToggleRulers.into())
.disabled(no_active_document),
],
])
.widget_instance(),
TextButton::new("Window")
.label("Window")
.flush(true)
.menu_list_children(vec![
vec![
MenuListEntry::new("Properties")
.label("Properties")
.icon(if self.properties_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::TogglePropertiesPanelOpen))
.on_commit(|_| PortfolioMessage::TogglePropertiesPanelOpen.into()),
MenuListEntry::new("Layers")
.label("Layers")
.icon(if self.layers_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleLayersPanelOpen))
.on_commit(|_| PortfolioMessage::ToggleLayersPanelOpen.into()),
],
vec![
MenuListEntry::new("Data")
.label("Data")
.icon(if self.data_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleDataPanelOpen))
.on_commit(|_| PortfolioMessage::ToggleDataPanelOpen.into()),
],
])
.widget_instance(),
TextButton::new("Help")
.label("Help")
.flush(true)
.menu_list_children(vec![
#[cfg(not(target_os = "macos"))]
vec![about],
vec![
MenuListEntry::new("Donate to Graphite").label("Donate to Graphite").icon("Heart").on_commit(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.art/donate/".into(),
}
.into()
}),
MenuListEntry::new("User Manual").label("User Manual").icon("UserManual").on_commit(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.art/learn/".into(),
}
.into()
}),
MenuListEntry::new("Report a Bug").label("Report a Bug").icon("Bug").on_commit(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://github.com/GraphiteEditor/Graphite/issues/new".into(),
}
.into()
}),
MenuListEntry::new("Visit on GitHub").label("Visit on GitHub").icon("Website").on_commit(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://github.com/GraphiteEditor/Graphite".into(),
}
.into()
}),
],
vec![MenuListEntry::new("Developer Debug").label("Developer Debug").icon("Code").children(vec![
vec![
MenuListEntry::new("Reset Nodes to Definitions on Open")
.label("Reset Nodes to Definitions on Open")
.icon(if reset_node_definitions_on_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen.into()),
],
vec![
MenuListEntry::new("Print Trace Logs")
.label("Print Trace Logs")
.icon(if log::max_level() == log::LevelFilter::Trace { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| DebugMessage::ToggleTraceLogs.into()),
MenuListEntry::new("Print Messages: Off")
.label("Print Messages: Off")
.icon(if message_logging_verbosity_off {
#[cfg(not(target_os = "macos"))]
{
"SmallDot".to_string()
}
#[cfg(target_os = "macos")]
{
"CheckboxChecked".to_string()
}
} else { Default::default() })
.tooltip_shortcut(action_shortcut!(DebugMessageDiscriminant::MessageOff))
.on_commit(|_| DebugMessage::MessageOff.into()),
MenuListEntry::new("Print Messages: Only Names")
.label("Print Messages: Only Names")
.icon(if message_logging_verbosity_names {
#[cfg(not(target_os = "macos"))]
{
"SmallDot".to_string()
}
#[cfg(target_os = "macos")]
{
"CheckboxChecked".to_string()
}
} else { Default::default() })
.tooltip_shortcut(action_shortcut!(DebugMessageDiscriminant::MessageNames))
.on_commit(|_| DebugMessage::MessageNames.into()),
MenuListEntry::new("Print Messages: Full Contents")
.label("Print Messages: Full Contents")
.icon(if message_logging_verbosity_contents {
#[cfg(not(target_os = "macos"))]
{
"SmallDot".to_string()
}
#[cfg(target_os = "macos")]
{
"CheckboxChecked".to_string()
}
} else { Default::default() })
.tooltip_shortcut(action_shortcut!(DebugMessageDiscriminant::MessageContents))
.on_commit(|_| DebugMessage::MessageContents.into()),
],
vec![MenuListEntry::new("Trigger a Crash").label("Trigger a Crash").icon("Warning").on_commit(|_| panic!())],
])],
])
.widget_instance(),
];
Layout(vec![LayoutGroup::Row { widgets: menu_bar_buttons }])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/menu_bar/mod.rs | editor/src/messages/menu_bar/mod.rs | mod menu_bar_message;
mod menu_bar_message_handler;
#[doc(inline)]
pub use menu_bar_message::{MenuBarMessage, MenuBarMessageDiscriminant};
#[doc(inline)]
pub use menu_bar_message_handler::MenuBarMessageHandler;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/menu_bar/menu_bar_message.rs | editor/src/messages/menu_bar/menu_bar_message.rs | use crate::messages::prelude::*;
#[impl_message(Message, MenuBar)]
#[derive(PartialEq, Eq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize)]
pub enum MenuBarMessage {
// Messages
SendLayout,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/broadcast/broadcast_message_handler.rs | editor/src/messages/broadcast/broadcast_message_handler.rs | use crate::messages::prelude::*;
#[derive(Debug, Clone, Default, ExtractField)]
pub struct BroadcastMessageHandler {
event: EventMessageHandler,
listeners: HashMap<EventMessage, Vec<Message>>,
}
#[message_handler_data]
impl MessageHandler<BroadcastMessage, ()> for BroadcastMessageHandler {
fn process_message(&mut self, message: BroadcastMessage, responses: &mut VecDeque<Message>, _: ()) {
match message {
// Sub-messages
BroadcastMessage::TriggerEvent(message) => self.event.process_message(message, responses, EventMessageContext { listeners: &mut self.listeners }),
// Messages
BroadcastMessage::SubscribeEvent { on, send } => self.listeners.entry(on).or_default().push(*send),
BroadcastMessage::UnsubscribeEvent { on, send } => self.listeners.entry(on).or_default().retain(|msg| *msg != *send),
}
}
fn actions(&self) -> ActionList {
actions!(EventMessageDiscriminant;)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/broadcast/mod.rs | editor/src/messages/broadcast/mod.rs | mod broadcast_message;
mod broadcast_message_handler;
pub mod event;
#[doc(inline)]
pub use broadcast_message::{BroadcastMessage, BroadcastMessageDiscriminant};
#[doc(inline)]
pub use broadcast_message_handler::BroadcastMessageHandler;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/broadcast/broadcast_message.rs | editor/src/messages/broadcast/broadcast_message.rs | use crate::messages::prelude::*;
#[impl_message(Message, Broadcast)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum BroadcastMessage {
// Sub-messages
#[child]
TriggerEvent(EventMessage),
// Messages
SubscribeEvent {
on: EventMessage,
send: Box<Message>,
},
UnsubscribeEvent {
on: EventMessage,
send: Box<Message>,
},
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/broadcast/event/event_message.rs | editor/src/messages/broadcast/event/event_message.rs | use crate::messages::prelude::*;
#[impl_message(Message, BroadcastMessage, TriggerEvent)]
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize, Hash)]
pub enum EventMessage {
/// Triggered by requestAnimationFrame in JS
AnimationFrame,
CanvasTransformed,
ToolAbort,
SelectionChanged,
WorkingColorChanged,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/broadcast/event/event_message_handler.rs | editor/src/messages/broadcast/event/event_message_handler.rs | use crate::messages::prelude::*;
#[derive(ExtractField)]
pub struct EventMessageContext<'a> {
pub listeners: &'a mut HashMap<EventMessage, Vec<Message>>,
}
#[derive(Debug, Clone, Default, ExtractField)]
pub struct EventMessageHandler {}
#[message_handler_data]
impl MessageHandler<EventMessage, EventMessageContext<'_>> for EventMessageHandler {
fn process_message(&mut self, message: EventMessage, responses: &mut VecDeque<Message>, context: EventMessageContext) {
for message in context.listeners.entry(message).or_default() {
responses.add_front(message.clone())
}
}
fn actions(&self) -> ActionList {
actions!(EventMessageDiscriminant;)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/broadcast/event/mod.rs | editor/src/messages/broadcast/event/mod.rs | mod event_message;
mod event_message_handler;
#[doc(inline)]
pub use event_message::{EventMessage, EventMessageDiscriminant};
#[doc(inline)]
pub use event_message_handler::{EventMessageContext, EventMessageHandler};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/mod.rs | editor/src/messages/dialog/mod.rs | //! Handles dialogs that appear as floating menus in the center of the editor window.
//!
//! Dialogs are represented as structs that implement the `DialogLayoutHolder` trait.
//!
//! To open a dialog, call the function `send_dialog_to_frontend()` on the dialog struct.
//! Then dialog can be opened by sending the `FrontendMessage::DisplayDialog` message;
mod dialog_message;
mod dialog_message_handler;
pub mod export_dialog;
pub mod new_document_dialog;
pub mod preferences_dialog;
pub mod simple_dialogs;
#[doc(inline)]
pub use dialog_message::{DialogMessage, DialogMessageDiscriminant};
#[doc(inline)]
pub use dialog_message_handler::{DialogMessageContext, DialogMessageHandler};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/dialog_message_handler.rs | editor/src/messages/dialog/dialog_message_handler.rs | use super::simple_dialogs::{self, AboutGraphiteDialog, DemoArtworkDialog, LicensesDialog};
use crate::messages::dialog::simple_dialogs::LicensesThirdPartyDialog;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
#[derive(ExtractField)]
pub struct DialogMessageContext<'a> {
pub portfolio: &'a PortfolioMessageHandler,
pub preferences: &'a PreferencesMessageHandler,
}
/// Stores the dialogs which require state. These are the ones that have their own message handlers, and are not the ones defined in `simple_dialogs`.
#[derive(Debug, Default, Clone, ExtractField)]
pub struct DialogMessageHandler {
export_dialog: ExportDialogMessageHandler,
new_document_dialog: NewDocumentDialogMessageHandler,
preferences_dialog: PreferencesDialogMessageHandler,
}
#[message_handler_data]
impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHandler {
fn process_message(&mut self, message: DialogMessage, responses: &mut VecDeque<Message>, context: DialogMessageContext) {
let DialogMessageContext { portfolio, preferences } = context;
match message {
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
DialogMessage::CloseAllDocumentsWithConfirmation => {
let dialog = simple_dialogs::CloseAllDocumentsDialog {
unsaved_document_names: portfolio.unsaved_document_names(),
};
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::CloseDialogAndThen { followups } => {
for message in followups.into_iter() {
responses.add(message);
}
// This come after followups, so that the followups (which can cause the dialog to open) happen first, then we close it afterwards.
// If it comes before, the dialog reopens (and appears to not close at all).
responses.add(FrontendMessage::DisplayDialogDismiss);
}
DialogMessage::DisplayDialogError { title, description } => {
let dialog = simple_dialogs::ErrorDialog { title, description };
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestAboutGraphiteDialog => {
responses.add(FrontendMessage::TriggerAboutGraphiteLocalizedCommitDate {
commit_date: env!("GRAPHITE_GIT_COMMIT_DATE").into(),
});
}
DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date,
localized_commit_year,
} => {
let dialog = AboutGraphiteDialog {
localized_commit_date,
localized_commit_year,
};
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestDemoArtworkDialog => {
let dialog = DemoArtworkDialog;
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestExportDialog => {
if let Some(document) = portfolio.active_document() {
let artboards = document
.metadata()
.all_layers()
.filter(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[]))
.map(|layer| {
let name = document
.network_interface
.node_metadata(&layer.to_node(), &[])
.map(|node| node.persistent_metadata.display_name.clone())
.and_then(|name| if name.is_empty() { None } else { Some(name) })
.unwrap_or_else(|| "Artboard".to_string());
(layer, name)
})
.collect();
self.export_dialog.artboards = artboards;
self.export_dialog.has_selection = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some();
self.export_dialog.send_dialog_to_frontend(responses);
}
}
DialogMessage::RequestLicensesDialogWithLocalizedCommitDate { localized_commit_year } => {
let dialog = LicensesDialog { localized_commit_year };
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text } => {
let dialog = LicensesThirdPartyDialog { license_text };
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestNewDocumentDialog => {
self.new_document_dialog = NewDocumentDialogMessageHandler {
name: portfolio.generate_new_document_name(),
infinite: false,
dimensions: glam::UVec2::new(1920, 1080),
};
self.new_document_dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestPreferencesDialog => {
self.preferences_dialog = PreferencesDialogMessageHandler {};
self.preferences_dialog.send_dialog_to_frontend(responses, preferences);
}
}
}
advertise_actions!(DialogMessageDiscriminant;
CloseAllDocumentsWithConfirmation,
RequestExportDialog,
RequestNewDocumentDialog,
RequestPreferencesDialog,
);
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/dialog_message.rs | editor/src/messages/dialog/dialog_message.rs | use crate::messages::prelude::*;
#[impl_message(Message, Dialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum DialogMessage {
// Sub-messages
#[child]
ExportDialog(ExportDialogMessage),
#[child]
NewDocumentDialog(NewDocumentDialogMessage),
#[child]
PreferencesDialog(PreferencesDialogMessage),
// Messages
CloseAllDocumentsWithConfirmation,
CloseDialogAndThen {
followups: Vec<Message>,
},
DisplayDialogError {
title: String,
description: String,
},
RequestAboutGraphiteDialog,
RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date: String,
localized_commit_year: String,
},
RequestDemoArtworkDialog,
RequestExportDialog,
RequestLicensesDialogWithLocalizedCommitDate {
localized_commit_year: String,
},
RequestLicensesThirdPartyDialogWithLicenseText {
license_text: String,
},
RequestNewDocumentDialog,
RequestPreferencesDialog,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/preferences_dialog/preferences_dialog_message.rs | editor/src/messages/dialog/preferences_dialog/preferences_dialog_message.rs | use crate::messages::prelude::*;
#[impl_message(Message, DialogMessage, PreferencesDialog)]
#[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum PreferencesDialogMessage {
Confirm,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/preferences_dialog/mod.rs | editor/src/messages/dialog/preferences_dialog/mod.rs | mod preferences_dialog_message;
mod preferences_dialog_message_handler;
#[doc(inline)]
pub use preferences_dialog_message::{PreferencesDialogMessage, PreferencesDialogMessageDiscriminant};
#[doc(inline)]
pub use preferences_dialog_message_handler::{PreferencesDialogMessageContext, PreferencesDialogMessageHandler};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/preferences_dialog/preferences_dialog_message_handler.rs | editor/src/messages/dialog/preferences_dialog/preferences_dialog_message_handler.rs | use crate::consts::{VIEWPORT_ZOOM_WHEEL_RATE, VIEWPORT_ZOOM_WHEEL_RATE_CHANGE};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
#[derive(ExtractField)]
pub struct PreferencesDialogMessageContext<'a> {
pub preferences: &'a PreferencesMessageHandler,
}
/// A dialog to allow users to customize Graphite editor options
#[derive(Debug, Clone, Default, ExtractField)]
pub struct PreferencesDialogMessageHandler {}
#[message_handler_data]
impl MessageHandler<PreferencesDialogMessage, PreferencesDialogMessageContext<'_>> for PreferencesDialogMessageHandler {
fn process_message(&mut self, message: PreferencesDialogMessage, responses: &mut VecDeque<Message>, context: PreferencesDialogMessageContext) {
let PreferencesDialogMessageContext { preferences } = context;
match message {
PreferencesDialogMessage::Confirm => {}
}
self.send_dialog_to_frontend(responses, preferences);
}
advertise_actions! {PreferencesDialogUpdate;}
}
// This doesn't actually implement the `DialogLayoutHolder` trait like the other dialog message handlers.
// That's because we need to give `send_layout` the `preferences` argument, which is not part of the trait.
// However, it's important to keep the methods in sync with those from the trait for consistency.
impl PreferencesDialogMessageHandler {
const ICON: &'static str = "Settings";
const TITLE: &'static str = "Editor Preferences";
fn layout(&self, preferences: &PreferencesMessageHandler) -> Layout {
let mut rows = Vec::new();
// ==========
// NAVIGATION
// ==========
{
let header = vec![TextLabel::new("Navigation").italic(true).widget_instance()];
let zoom_rate_description = "Adjust how fast zooming occurs when using the scroll wheel or pinch gesture (relative to a default of 50).";
let zoom_rate_label = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Zoom Rate").tooltip_label("Zoom Rate").tooltip_description(zoom_rate_description).widget_instance(),
];
let zoom_rate = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(map_zoom_rate_to_display(preferences.viewport_zoom_wheel_rate)))
.tooltip_label("Zoom Rate")
.tooltip_description(zoom_rate_description)
.mode_range()
.int()
.min(1.)
.max(100.)
.on_update(|number_input: &NumberInput| {
if let Some(display_value) = number_input.value {
let actual_rate = map_display_to_zoom_rate(display_value);
PreferencesMessage::ViewportZoomWheelRate { rate: actual_rate }.into()
} else {
PreferencesMessage::ViewportZoomWheelRate { rate: VIEWPORT_ZOOM_WHEEL_RATE }.into()
}
})
.widget_instance(),
];
let checkbox_id = CheckboxId::new();
let zoom_with_scroll_description = "Use the scroll wheel for zooming instead of vertically panning (not recommended for trackpads).";
let zoom_with_scroll = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.zoom_with_scroll)
.tooltip_label("Zoom with Scroll")
.tooltip_description(zoom_with_scroll_description)
.on_update(|checkbox_input: &CheckboxInput| {
PreferencesMessage::ModifyLayout {
zoom_with_scroll: checkbox_input.checked,
}
.into()
})
.for_label(checkbox_id)
.widget_instance(),
TextLabel::new("Zoom with Scroll")
.tooltip_label("Zoom with Scroll")
.tooltip_description(zoom_with_scroll_description)
.for_checkbox(checkbox_id)
.widget_instance(),
];
rows.extend_from_slice(&[header, zoom_rate_label, zoom_rate, zoom_with_scroll]);
}
// =======
// EDITING
// =======
{
let header = vec![TextLabel::new("Editing").italic(true).widget_instance()];
let selection_label = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Selection")
.tooltip_label("Selection")
.tooltip_description("Choose how targets are selected within dragged rectangular and lasso areas.")
.widget_instance(),
];
let selection_mode = RadioInput::new(vec![
RadioEntryData::new(SelectionMode::Touched.to_string())
.label(SelectionMode::Touched.to_string())
.tooltip_label(SelectionMode::Touched.to_string())
.tooltip_description(SelectionMode::Touched.tooltip_description())
.on_update(move |_| {
PreferencesMessage::SelectionMode {
selection_mode: SelectionMode::Touched,
}
.into()
}),
RadioEntryData::new(SelectionMode::Enclosed.to_string())
.label(SelectionMode::Enclosed.to_string())
.tooltip_label(SelectionMode::Enclosed.to_string())
.tooltip_description(SelectionMode::Enclosed.tooltip_description())
.on_update(move |_| {
PreferencesMessage::SelectionMode {
selection_mode: SelectionMode::Enclosed,
}
.into()
}),
RadioEntryData::new(SelectionMode::Directional.to_string())
.label(SelectionMode::Directional.to_string())
.tooltip_label(SelectionMode::Directional.to_string())
.tooltip_description(SelectionMode::Directional.tooltip_description())
.on_update(move |_| {
PreferencesMessage::SelectionMode {
selection_mode: SelectionMode::Directional,
}
.into()
}),
])
.selected_index(Some(preferences.selection_mode as u32))
.widget_instance();
let selection_mode = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
selection_mode,
];
rows.extend_from_slice(&[header, selection_label, selection_mode]);
}
// =========
// INTERFACE
// =========
#[cfg(not(target_family = "wasm"))]
{
let header = vec![TextLabel::new("Interface").italic(true).widget_instance()];
let scale_description = "Adjust the scale of the entire user interface (100% is default).";
let scale_label = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Scale").tooltip_label("Scale").tooltip_description(scale_description).widget_instance(),
];
let scale = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(ui_scale_to_display(preferences.ui_scale)))
.tooltip_label("Scale")
.tooltip_description(scale_description)
.mode_range()
.int()
.min(ui_scale_to_display(crate::consts::UI_SCALE_MIN))
.max(ui_scale_to_display(crate::consts::UI_SCALE_MAX))
.unit("%")
.on_update(|number_input: &NumberInput| {
if let Some(display_value) = number_input.value {
let scale = map_display_to_ui_scale(display_value);
PreferencesMessage::UIScale { scale }.into()
} else {
PreferencesMessage::UIScale {
scale: crate::consts::UI_SCALE_DEFAULT,
}
.into()
}
})
.widget_instance(),
];
rows.extend_from_slice(&[header, scale_label, scale]);
}
// ============
// EXPERIMENTAL
// ============
{
let header = vec![TextLabel::new("Experimental").italic(true).widget_instance()];
let node_graph_section_description = "Configure the appearance of the wires running between node connections in the graph.";
let node_graph_wires_label = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Node Graph Wires")
.tooltip_label("Node Graph Wires")
.tooltip_description(node_graph_section_description)
.widget_instance(),
];
let graph_wire_style = RadioInput::new(vec![
RadioEntryData::new(GraphWireStyle::Direct.to_string())
.label(GraphWireStyle::Direct.to_string())
.tooltip_label(GraphWireStyle::Direct.to_string())
.tooltip_description(GraphWireStyle::Direct.tooltip_description())
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::Direct }.into()),
RadioEntryData::new(GraphWireStyle::GridAligned.to_string())
.label(GraphWireStyle::GridAligned.to_string())
.tooltip_label(GraphWireStyle::GridAligned.to_string())
.tooltip_description(GraphWireStyle::GridAligned.tooltip_description())
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()),
])
.selected_index(Some(preferences.graph_wire_style as u32))
.widget_instance();
let graph_wire_style = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
graph_wire_style,
];
let checkbox_id = CheckboxId::new();
let vello_description = "Use the experimental Vello renderer instead of SVG-based rendering.".to_string();
#[cfg(target_family = "wasm")]
let mut vello_description = vello_description;
#[cfg(target_family = "wasm")]
vello_description.push_str("\n\n(Your browser must support WebGPU.)");
let use_vello = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.use_vello && preferences.supports_wgpu())
.tooltip_label("Vello Renderer")
.tooltip_description(vello_description.clone())
.disabled(!preferences.supports_wgpu())
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::UseVello { use_vello: checkbox_input.checked }.into())
.for_label(checkbox_id)
.widget_instance(),
TextLabel::new("Vello Renderer")
.tooltip_label("Vello Renderer")
.tooltip_description(vello_description)
.disabled(!preferences.supports_wgpu())
.for_checkbox(checkbox_id)
.widget_instance(),
];
let checkbox_id = CheckboxId::new();
let brush_tool_description = "
Enable the Brush tool to support basic raster-based layer painting.\n\
\n\
This legacy experimental tool has performance and quality limitations and is slated for replacement in future versions of Graphite that will focus on raster graphics editing.\n\
\n\
Content created with the Brush tool may not be compatible with future versions of Graphite.
"
.trim();
let brush_tool = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.brush_tool)
.tooltip_label("Brush Tool")
.tooltip_description(brush_tool_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::BrushTool { enabled: checkbox_input.checked }.into())
.for_label(checkbox_id)
.widget_instance(),
TextLabel::new("Brush Tool")
.tooltip_label("Brush Tool")
.tooltip_description(brush_tool_description)
.for_checkbox(checkbox_id)
.widget_instance(),
];
rows.extend_from_slice(&[header, node_graph_wires_label, graph_wire_style, use_vello, brush_tool]);
}
Layout(rows.into_iter().map(|r| LayoutGroup::Row { widgets: r }).collect())
}
pub fn send_layout(&self, responses: &mut VecDeque<Message>, layout_target: LayoutTarget, preferences: &PreferencesMessageHandler) {
responses.add(LayoutMessage::SendLayout {
layout: self.layout(preferences),
layout_target,
})
}
fn layout_column_2(&self) -> Layout {
Layout::default()
}
fn send_layout_column_2(&self, responses: &mut VecDeque<Message>, layout_target: LayoutTarget) {
responses.add(LayoutMessage::SendLayout {
layout: self.layout_column_2(),
layout_target,
});
}
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("OK")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseDialogAndThen {
followups: vec![PreferencesDialogMessage::Confirm.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Reset to Defaults").on_update(|_| PreferencesMessage::ResetToDefaults.into()).widget_instance(),
];
Layout(vec![LayoutGroup::Row { widgets }])
}
fn send_layout_buttons(&self, responses: &mut VecDeque<Message>, layout_target: LayoutTarget) {
responses.add(LayoutMessage::SendLayout {
layout: self.layout_buttons(),
layout_target,
});
}
pub fn send_dialog_to_frontend(&self, responses: &mut VecDeque<Message>, preferences: &PreferencesMessageHandler) {
self.send_layout(responses, LayoutTarget::DialogColumn1, preferences);
self.send_layout_column_2(responses, LayoutTarget::DialogColumn2);
self.send_layout_buttons(responses, LayoutTarget::DialogButtons);
responses.add(FrontendMessage::DisplayDialog {
icon: Self::ICON.into(),
title: Self::TITLE.into(),
});
}
}
/// Maps display values (1-100) to actual zoom rates.
fn map_display_to_zoom_rate(display: f64) -> f64 {
// Calculate the relative distance from the reference point (50)
let distance_from_reference = display - 50.;
let scaling_factor = (VIEWPORT_ZOOM_WHEEL_RATE_CHANGE * distance_from_reference / 50.).exp();
VIEWPORT_ZOOM_WHEEL_RATE * scaling_factor
}
/// Maps actual zoom rates back to display values (1-100).
fn map_zoom_rate_to_display(rate: f64) -> f64 {
// Calculate the scaling factor from the reference rate
let scaling_factor = rate / VIEWPORT_ZOOM_WHEEL_RATE;
let distance_from_reference = 50. * scaling_factor.ln() / VIEWPORT_ZOOM_WHEEL_RATE_CHANGE;
let display = 50. + distance_from_reference;
display.clamp(1., 100.).round()
}
/// Maps display values in percent to actual ui scale.
#[cfg(not(target_family = "wasm"))]
fn map_display_to_ui_scale(display: f64) -> f64 {
display / 100.
}
/// Maps actual ui scale back to display values in percent.
#[cfg(not(target_family = "wasm"))]
fn ui_scale_to_display(scale: f64) -> f64 {
scale * 100.
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/simple_dialogs/error_dialog.rs | editor/src/messages/dialog/simple_dialogs/error_dialog.rs | use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
/// A dialog to notify users of a non-fatal error.
pub struct ErrorDialog {
pub title: String,
pub description: String,
}
impl DialogLayoutHolder for ErrorDialog {
const ICON: &'static str = "Warning";
const TITLE: &'static str = "Error";
fn layout_buttons(&self) -> Layout {
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance()];
Layout(vec![LayoutGroup::Row { widgets }])
}
}
impl LayoutHolder for ErrorDialog {
fn layout(&self) -> Layout {
Layout(vec![
LayoutGroup::Row {
widgets: vec![TextLabel::new(&self.title).bold(true).widget_instance()],
},
LayoutGroup::Row {
widgets: vec![TextLabel::new(&self.description).multiline(true).widget_instance()],
},
])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/simple_dialogs/close_all_documents_dialog.rs | editor/src/messages/dialog/simple_dialogs/close_all_documents_dialog.rs | use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
/// A dialog for confirming the closing of all documents viewable via `File -> Close All` in the menu bar.
pub struct CloseAllDocumentsDialog {
pub unsaved_document_names: Vec<String>,
}
impl DialogLayoutHolder for CloseAllDocumentsDialog {
const ICON: &'static str = "Warning";
const TITLE: &'static str = "Closing All Documents";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("Discard All")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseDialogAndThen {
followups: vec![PortfolioMessage::CloseAllDocuments.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance(),
];
Layout(vec![LayoutGroup::Row { widgets }])
}
}
impl LayoutHolder for CloseAllDocumentsDialog {
fn layout(&self) -> Layout {
let unsaved_list = "β’ ".to_string() + &self.unsaved_document_names.join("\nβ’ ");
Layout(vec![
LayoutGroup::Row {
widgets: vec![TextLabel::new("Save documents before closing them?").bold(true).multiline(true).widget_instance()],
},
LayoutGroup::Row {
widgets: vec![TextLabel::new(format!("Documents with unsaved changes:\n{unsaved_list}")).multiline(true).widget_instance()],
},
])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/simple_dialogs/demo_artwork_dialog.rs | editor/src/messages/dialog/simple_dialogs/demo_artwork_dialog.rs | use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
/// A dialog to let the user browse a gallery of demo artwork that can be opened.
pub struct DemoArtworkDialog;
/// `(name, thumbnail, filename)`
pub const ARTWORK: [(&str, &str, &str); 7] = [
("Isometric Fountain", "ThumbnailIsometricFountain", "isometric-fountain.graphite"),
("Changing Seasons", "ThumbnailChangingSeasons", "changing-seasons.graphite"),
("Painted Dreams", "ThumbnailPaintedDreams", "painted-dreams.graphite"),
("Parametric Dunescape", "ThumbnailParametricDunescape", "parametric-dunescape.graphite"),
("Red Dress", "ThumbnailRedDress", "red-dress.graphite"),
("Procedural String Lights", "ThumbnailProceduralStringLights", "procedural-string-lights.graphite"),
("Valley of Spires", "ThumbnailValleyOfSpires", "valley-of-spires.graphite"),
];
impl DialogLayoutHolder for DemoArtworkDialog {
const ICON: &'static str = "Image";
const TITLE: &'static str = "Demo Artwork";
fn layout_buttons(&self) -> Layout {
let widgets = vec![TextButton::new("Close").emphasized(true).on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance()];
Layout(vec![LayoutGroup::Row { widgets }])
}
}
impl LayoutHolder for DemoArtworkDialog {
fn layout(&self) -> Layout {
let mut rows_of_images_with_buttons: Vec<_> = ARTWORK
.chunks(4)
.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(),
],
}
.into()
}
let images = chunk
.iter()
.map(|(name, thumbnail, filename)| ImageButton::new(*thumbnail).width(Some("256px".into())).on_update(|_| make_dialog(name, filename)).widget_instance())
.collect();
let buttons = chunk
.iter()
.map(|(name, _, filename)| TextButton::new(*name).min_width(256).flush(true).on_update(|_| make_dialog(name, filename)).widget_instance())
.collect();
vec![LayoutGroup::Row { widgets: images }, LayoutGroup::Row { widgets: buttons }, LayoutGroup::Row { widgets: vec![] }]
})
.collect();
let _ = rows_of_images_with_buttons.pop();
Layout(rows_of_images_with_buttons)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/simple_dialogs/mod.rs | editor/src/messages/dialog/simple_dialogs/mod.rs | mod about_graphite_dialog;
mod close_all_documents_dialog;
mod close_document_dialog;
mod demo_artwork_dialog;
mod error_dialog;
mod licenses_dialog;
mod licenses_third_party_dialog;
pub use about_graphite_dialog::AboutGraphiteDialog;
pub use close_all_documents_dialog::CloseAllDocumentsDialog;
pub use close_document_dialog::CloseDocumentDialog;
pub use demo_artwork_dialog::ARTWORK;
pub use demo_artwork_dialog::DemoArtworkDialog;
pub use error_dialog::ErrorDialog;
pub use licenses_dialog::LicensesDialog;
pub use licenses_third_party_dialog::LicensesThirdPartyDialog;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/simple_dialogs/licenses_third_party_dialog.rs | editor/src/messages/dialog/simple_dialogs/licenses_third_party_dialog.rs | use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
pub struct LicensesThirdPartyDialog {
pub license_text: String,
}
impl DialogLayoutHolder for LicensesThirdPartyDialog {
const ICON: &'static str = "License12px";
const TITLE: &'static str = "Third-Party Software License Notices";
fn layout_buttons(&self) -> Layout {
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance()];
Layout(vec![LayoutGroup::Row { widgets }])
}
}
impl LayoutHolder for LicensesThirdPartyDialog {
fn layout(&self) -> Layout {
// Remove the header and begin with the line containing the first license section (we otherwise keep the title for standalone viewing of the licenses text file)
let license_text = if let Some(first_underscore_line) = self.license_text.lines().position(|line| line.contains('_')) {
// Find the byte position where the line with underscore starts
let char_position = self.license_text.split('\n').take(first_underscore_line).map(|line| line.len() + '\n'.len_utf8()).sum();
self.license_text[char_position..].to_string()
} else {
// This shouldn't be encountered, but if no underscore line is found, we use the full text as a safety fallback
self.license_text.clone()
};
// Two characters (one before, one after) the sequence of underscore characters, plus one additional column to provide a space between the text and the scrollbar
let non_wrapping_column_width = license_text.split('\n').map(|line| line.chars().filter(|&c| c == '_').count() as u32).max().unwrap_or(0) + 2 + 1;
Layout(vec![LayoutGroup::Row {
widgets: vec![
TextLabel::new(license_text)
.monospace(true)
.multiline(true)
.min_width_characters(non_wrapping_column_width)
.widget_instance(),
],
}])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/simple_dialogs/licenses_dialog.rs | editor/src/messages/dialog/simple_dialogs/licenses_dialog.rs | use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
pub struct LicensesDialog {
pub localized_commit_year: String,
}
impl DialogLayoutHolder for LicensesDialog {
const ICON: &'static str = "License12px";
const TITLE: &'static str = "Licenses";
fn layout_buttons(&self) -> Layout {
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance()];
Layout(vec![LayoutGroup::Row { widgets }])
}
fn layout_column_2(&self) -> Layout {
#[allow(clippy::type_complexity)]
let button_definitions: &[(&str, &str, fn() -> Message)] = &[
("Code", "Source Code License", || {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.art/license#source-code".into(),
}
.into()
}),
("GraphiteLogo", "Branding License", || {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.art/license#branding".into(),
}
.into()
}),
("IconsGrid", "Dependency Licenses", || FrontendMessage::TriggerDisplayThirdPartyLicensesDialog.into()),
];
let widgets = button_definitions
.iter()
.map(|&(icon, label, message_factory)| TextButton::new(label).icon(Some((icon).into())).flush(true).on_update(move |_| message_factory()).widget_instance())
.collect();
Layout(vec![LayoutGroup::Column { widgets }])
}
}
impl LayoutHolder for LicensesDialog {
fn layout(&self) -> Layout {
let year = &self.localized_commit_year;
let description = format!(
"
Graphite source code is copyright Β© {year} Graphite contrib-\nutors and is available under the Apache License 2.0. See\n\"Source Code License\" for details.\n\
\n\
The Graphite logo, icons, and visual identity are copyright Β©\n{year} Graphite Labs, LLC. See \"Branding License\" for details.\n\
\n\
Graphite is distributed with third-party open source code\ndependencies. See \"Dependency Licenses\" for details.
"
);
let description = description.trim();
Layout(vec![
LayoutGroup::Row {
widgets: vec![TextLabel::new("Graphite is free, open source software").bold(true).widget_instance()],
},
LayoutGroup::Row {
widgets: vec![TextLabel::new(description).multiline(true).widget_instance()],
},
])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/simple_dialogs/close_document_dialog.rs | editor/src/messages/dialog/simple_dialogs/close_document_dialog.rs | use crate::messages::broadcast::event::EventMessage;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
/// A dialog for confirming the closing a document with unsaved changes.
pub struct CloseDocumentDialog {
pub document_name: String,
pub document_id: DocumentId,
}
impl DialogLayoutHolder for CloseDocumentDialog {
const ICON: &'static str = "Warning";
const TITLE: &'static str = "Closing Document";
fn layout_buttons(&self) -> Layout {
let document_id = self.document_id;
let widgets = vec![
TextButton::new("Save")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseDialogAndThen {
followups: vec![DocumentMessage::SaveDocument.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Discard")
.on_update(move |_| {
DialogMessage::CloseDialogAndThen {
followups: vec![EventMessage::ToolAbort.into(), PortfolioMessage::CloseDocument { document_id }.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance(),
];
Layout(vec![LayoutGroup::Row { widgets }])
}
}
impl LayoutHolder for CloseDocumentDialog {
fn layout(&self) -> Layout {
let max_length = 60;
let max_one_line_length = 40;
let mut name = self.document_name.clone();
name.truncate(max_length);
let ellipsis = if self.document_name.len() > max_length { "β¦" } else { "" };
let break_lines = if self.document_name.len() > max_one_line_length { '\n' } else { ' ' };
Layout(vec![
LayoutGroup::Row {
widgets: vec![TextLabel::new("Save document before closing it?").bold(true).widget_instance()],
},
LayoutGroup::Row {
widgets: vec![TextLabel::new(format!("\"{name}{ellipsis}\"{break_lines}has unsaved changes")).multiline(true).widget_instance()],
},
])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/simple_dialogs/about_graphite_dialog.rs | editor/src/messages/dialog/simple_dialogs/about_graphite_dialog.rs | use crate::application::commit_info_localized;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
/// A dialog for displaying information on [BuildMetadata] viewable via *Help* > *About Graphite* in the menu bar.
pub struct AboutGraphiteDialog {
pub localized_commit_date: String,
pub localized_commit_year: String,
}
impl DialogLayoutHolder for AboutGraphiteDialog {
const ICON: &'static str = "GraphiteLogo";
const TITLE: &'static str = "About Graphite";
fn layout_buttons(&self) -> Layout {
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance()];
Layout(vec![LayoutGroup::Row { widgets }])
}
fn layout_column_2(&self) -> Layout {
let links = [
("Heart", "Donate", "https://graphite.art/donate/"),
("GraphiteLogo", "Website", "https://graphite.art"),
("Volunteer", "Volunteer", "https://graphite.art/volunteer/"),
("Credits", "Credits", "https://github.com/GraphiteEditor/Graphite/graphs/contributors"),
];
let mut widgets = links
.into_iter()
.map(|(icon, label, url)| {
TextButton::new(label)
.icon(Some(icon.into()))
.flush(true)
.on_update(|_| FrontendMessage::TriggerVisitLink { url: url.into() }.into())
.widget_instance()
})
.collect::<Vec<_>>();
// Cloning here and below seems to be necessary to appease the borrow checker, as far as I can tell.
let localized_commit_year = self.localized_commit_year.clone();
widgets.push(
TextButton::new("Licenses")
.icon(Some("License".into()))
.flush(true)
.on_update(move |_| {
DialogMessage::RequestLicensesDialogWithLocalizedCommitDate {
localized_commit_year: localized_commit_year.clone(),
}
.into()
})
.widget_instance(),
);
Layout(vec![LayoutGroup::Column { widgets }])
}
}
impl LayoutHolder for AboutGraphiteDialog {
fn layout(&self) -> Layout {
Layout(vec![
LayoutGroup::Row {
widgets: vec![TextLabel::new("About this release").bold(true).widget_instance()],
},
LayoutGroup::Row {
widgets: vec![TextLabel::new(commit_info_localized(&self.localized_commit_date)).multiline(true).widget_instance()],
},
LayoutGroup::Row {
widgets: vec![TextLabel::new(format!("Copyright Β© {} Graphite contributors", self.localized_commit_year)).widget_instance()],
},
])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/new_document_dialog/new_document_dialog_message_handler.rs | editor/src/messages/dialog/new_document_dialog/new_document_dialog_message_handler.rs | use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
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, ExtractField)]
pub struct NewDocumentDialogMessageHandler {
pub name: String,
pub infinite: bool,
pub dimensions: UVec2,
}
#[message_handler_data]
impl<'a> MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHandler {
fn process_message(&mut self, message: NewDocumentDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
match message {
NewDocumentDialogMessage::Name { name } => self.name = name,
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
NewDocumentDialogMessage::DimensionsX { width } => self.dimensions.x = width as u32,
NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
NewDocumentDialogMessage::Submit => {
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
let create_artboard = !self.infinite && self.dimensions.x > 0 && self.dimensions.y > 0;
if create_artboard {
responses.add(GraphOperationMessage::NewArtboard {
id: NodeId::new(),
artboard: graphene_std::Artboard::new(IVec2::ZERO, self.dimensions.as_ivec2()),
});
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(ViewportMessage::RepropagateUpdate);
responses.add(DeferMessage::AfterNavigationReady {
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into(), DocumentMessage::DeselectAllLayers.into()],
});
}
responses.add(DocumentMessage::MarkAsSaved);
}
}
self.send_dialog_to_frontend(responses);
}
advertise_actions! {NewDocumentDialogUpdate;}
}
impl DialogLayoutHolder for NewDocumentDialogMessageHandler {
const ICON: &'static str = "File";
const TITLE: &'static str = "New Document";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("OK")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseDialogAndThen {
followups: vec![NewDocumentDialogMessage::Submit.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance(),
];
Layout(vec![LayoutGroup::Row { widgets }])
}
}
impl LayoutHolder for NewDocumentDialogMessageHandler {
fn layout(&self) -> Layout {
let name = vec![
TextLabel::new("Name").table_align(true).min_width(90).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(&self.name)
.on_update(|text_input: &TextInput| NewDocumentDialogMessage::Name { name: text_input.value.clone() }.into())
.min_width(204) // Matches the 100px of both NumberInputs below + the 4px of the Unrelated-type separator
.widget_instance(),
];
let checkbox_id = CheckboxId::new();
let infinite = vec![
TextLabel::new("Infinite Canvas").table_align(true).min_width(90).for_checkbox(checkbox_id).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(self.infinite)
.on_update(|checkbox_input: &CheckboxInput| NewDocumentDialogMessage::Infinite { infinite: checkbox_input.checked }.into())
.for_label(checkbox_id)
.widget_instance(),
];
let scale = vec![
TextLabel::new("Dimensions").table_align(true).min_width(90).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(self.dimensions.x as f64))
.label("W")
.unit(" px")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(true)
.disabled(self.infinite)
.min_width(100)
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(self.dimensions.y as f64))
.label("H")
.unit(" px")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(true)
.disabled(self.infinite)
.min_width(100)
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
.widget_instance(),
];
Layout(vec![LayoutGroup::Row { widgets: name }, LayoutGroup::Row { widgets: infinite }, LayoutGroup::Row { widgets: scale }])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/new_document_dialog/mod.rs | editor/src/messages/dialog/new_document_dialog/mod.rs | mod new_document_dialog_message;
mod new_document_dialog_message_handler;
#[doc(inline)]
pub use new_document_dialog_message::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant};
#[doc(inline)]
pub use new_document_dialog_message_handler::NewDocumentDialogMessageHandler;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/new_document_dialog/new_document_dialog_message.rs | editor/src/messages/dialog/new_document_dialog/new_document_dialog_message.rs | use crate::messages::prelude::*;
#[impl_message(Message, DialogMessage, NewDocumentDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum NewDocumentDialogMessage {
Name { name: String },
Infinite { infinite: bool },
DimensionsX { width: f64 },
DimensionsY { height: f64 },
Submit,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/export_dialog/export_dialog_message.rs | editor/src/messages/dialog/export_dialog/export_dialog_message.rs | use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::prelude::*;
#[impl_message(Message, DialogMessage, ExportDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ExportDialogMessage {
FileType { file_type: FileType },
ScaleFactor { factor: f64 },
TransparentBackground { transparent: bool },
ExportBounds { bounds: ExportBounds },
Submit,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/export_dialog/mod.rs | editor/src/messages/dialog/export_dialog/mod.rs | mod export_dialog_message;
mod export_dialog_message_handler;
#[doc(inline)]
pub use export_dialog_message::{ExportDialogMessage, ExportDialogMessageDiscriminant};
#[doc(inline)]
pub use export_dialog_message_handler::{ExportDialogMessageContext, ExportDialogMessageHandler};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/dialog/export_dialog/export_dialog_message_handler.rs | editor/src/messages/dialog/export_dialog/export_dialog_message_handler.rs | use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::*;
#[derive(ExtractField)]
pub struct ExportDialogMessageContext<'a> {
pub portfolio: &'a PortfolioMessageHandler,
}
/// A dialog to allow users to customize their file export.
#[derive(Debug, Clone, ExtractField)]
pub struct ExportDialogMessageHandler {
pub file_type: FileType,
pub scale_factor: f64,
pub bounds: ExportBounds,
pub transparent_background: bool,
pub artboards: HashMap<LayerNodeIdentifier, String>,
pub has_selection: bool,
}
impl Default for ExportDialogMessageHandler {
fn default() -> Self {
Self {
file_type: Default::default(),
scale_factor: 1.,
bounds: Default::default(),
transparent_background: false,
artboards: Default::default(),
has_selection: false,
}
}
}
#[message_handler_data]
impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for ExportDialogMessageHandler {
fn process_message(&mut self, message: ExportDialogMessage, responses: &mut VecDeque<Message>, context: ExportDialogMessageContext) {
let ExportDialogMessageContext { portfolio } = context;
match message {
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
ExportDialogMessage::TransparentBackground { transparent } => self.transparent_background = transparent,
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
ExportDialogMessage::Submit => responses.add_front(PortfolioMessage::SubmitDocumentExport {
name: portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default(),
file_type: self.file_type,
scale_factor: self.scale_factor,
bounds: self.bounds,
transparent_background: self.file_type != FileType::Jpg && self.transparent_background,
}),
}
self.send_dialog_to_frontend(responses);
}
advertise_actions! {ExportDialogUpdate;}
}
impl DialogLayoutHolder for ExportDialogMessageHandler {
const ICON: &'static str = "File";
const TITLE: &'static str = "Export";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("Export")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseDialogAndThen {
followups: vec![ExportDialogMessage::Submit.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| FrontendMessage::DisplayDialogDismiss.into()).widget_instance(),
];
Layout(vec![LayoutGroup::Row { widgets }])
}
}
impl LayoutHolder for ExportDialogMessageHandler {
fn layout(&self) -> Layout {
let entries = [(FileType::Png, "PNG"), (FileType::Jpg, "JPG"), (FileType::Svg, "SVG")]
.into_iter()
.map(|(file_type, name)| {
RadioEntryData::new(format!("{file_type:?}"))
.label(name)
.on_update(move |_| ExportDialogMessage::FileType { file_type }.into())
})
.collect();
let export_type = vec![
TextLabel::new("File Type").table_align(true).min_width(100).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(entries).selected_index(Some(self.file_type as u32)).widget_instance(),
];
let resolution = vec![
TextLabel::new("Scale Factor").table_align(true).min_width(100).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(self.scale_factor))
.unit("")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.disabled(self.file_type == FileType::Svg)
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
.min_width(200)
.widget_instance(),
];
let standard_bounds = vec![
(ExportBounds::AllArtwork, "All Artwork".to_string(), false),
(ExportBounds::Selection, "Selection".to_string(), !self.has_selection),
];
let artboards = self.artboards.iter().map(|(&layer, name)| (ExportBounds::Artboard(layer), name.to_string(), false)).collect();
let choices = [standard_bounds, artboards];
let current_bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
ExportBounds::AllArtwork
} else {
self.bounds
};
let index = choices.iter().flatten().position(|(bounds, _, _)| *bounds == current_bounds).unwrap();
let mut entries = choices
.into_iter()
.map(|choice| {
choice
.into_iter()
.map(|(bounds, name, disabled)| {
MenuListEntry::new(format!("{bounds:?}"))
.label(name)
.on_commit(move |_| ExportDialogMessage::ExportBounds { bounds }.into())
.disabled(disabled)
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
if entries[1].is_empty() {
entries.remove(1);
}
let export_area = vec![
TextLabel::new("Bounds").table_align(true).min_width(100).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
];
let checkbox_id = CheckboxId::new();
let transparent_background = vec![
TextLabel::new("Transparency").table_align(true).min_width(100).for_checkbox(checkbox_id).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(self.transparent_background)
.disabled(self.file_type == FileType::Jpg)
.on_update(move |value: &CheckboxInput| ExportDialogMessage::TransparentBackground { transparent: value.checked }.into())
.for_label(checkbox_id)
.widget_instance(),
];
Layout(vec![
LayoutGroup::Row { widgets: export_type },
LayoutGroup::Row { widgets: resolution },
LayoutGroup::Row { widgets: export_area },
LayoutGroup::Row { widgets: transparent_background },
])
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/clipboard/utility_types.rs | editor/src/messages/clipboard/utility_types.rs | #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ClipboardContentRaw {
Text(String),
Svg(String),
Image { data: Vec<u8>, width: u32, height: u32 },
}
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ClipboardContent {
Layer(String),
Nodes(String),
Vector(String),
Text(String),
Svg(String),
Image { data: Vec<u8>, width: u32, height: u32 },
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/clipboard/mod.rs | editor/src/messages/clipboard/mod.rs | mod clipboard_message;
pub mod clipboard_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use clipboard_message::{ClipboardMessage, ClipboardMessageDiscriminant};
#[doc(inline)]
pub use clipboard_message_handler::ClipboardMessageHandler;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/clipboard/clipboard_message.rs | editor/src/messages/clipboard/clipboard_message.rs | use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw};
use crate::messages::prelude::*;
#[impl_message(Message, Clipboard)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ClipboardMessage {
Cut,
Copy,
Paste,
ReadClipboard { content: ClipboardContentRaw },
ReadSelection { content: Option<String>, cut: bool },
Write { content: ClipboardContent },
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/clipboard/clipboard_message_handler.rs | editor/src/messages/clipboard/clipboard_message_handler.rs | use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw};
use crate::messages::prelude::*;
use graphene_std::raster::Image;
use graphite_proc_macros::{ExtractField, message_handler_data};
const CLIPBOARD_PREFIX_LAYER: &str = "graphite/layer: ";
const CLIPBOARD_PREFIX_NODES: &str = "graphite/nodes: ";
const CLIPBOARD_PREFIX_VECTOR: &str = "graphite/vector: ";
#[derive(Debug, Clone, Default, ExtractField)]
pub struct ClipboardMessageHandler {}
#[message_handler_data]
impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
fn process_message(&mut self, message: ClipboardMessage, responses: &mut std::collections::VecDeque<Message>, _: ()) {
match message {
ClipboardMessage::Cut => responses.add(FrontendMessage::TriggerSelectionRead { cut: true }),
ClipboardMessage::Copy => responses.add(FrontendMessage::TriggerSelectionRead { cut: false }),
ClipboardMessage::Paste => responses.add(FrontendMessage::TriggerClipboardRead),
ClipboardMessage::ReadClipboard { content } => match content {
ClipboardContentRaw::Text(text) => {
if let Some(layer) = text.strip_prefix(CLIPBOARD_PREFIX_LAYER) {
responses.add(PortfolioMessage::PasteSerializedData { data: layer.to_string() });
} else if let Some(nodes) = text.strip_prefix(CLIPBOARD_PREFIX_NODES) {
responses.add(NodeGraphMessage::PasteNodes { serialized_nodes: nodes.to_string() });
} else if let Some(vector) = text.strip_prefix(CLIPBOARD_PREFIX_VECTOR) {
responses.add(PortfolioMessage::PasteSerializedVector { data: vector.to_string() });
} else {
responses.add(FrontendMessage::TriggerSelectionWrite { content: text });
}
}
ClipboardContentRaw::Svg(svg) => {
responses.add(PortfolioMessage::PasteSvg {
svg,
name: None,
mouse: None,
parent_and_insert_index: None,
});
}
ClipboardContentRaw::Image { data, width, height } => {
responses.add(PortfolioMessage::PasteImage {
image: Image::from_image_data(&data, width, height),
name: None,
mouse: None,
parent_and_insert_index: None,
});
}
},
ClipboardMessage::ReadSelection { content, cut } => {
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
if let Some(text) = content {
responses.add(ClipboardMessage::Write {
content: ClipboardContent::Text(text),
});
} else if cut {
responses.add(PortfolioMessage::Cut { clipboard: Clipboard::Device });
} else {
responses.add(PortfolioMessage::Copy { clipboard: Clipboard::Device });
}
}
ClipboardMessage::Write { content } => {
let text = match content {
ClipboardContent::Svg(_) => {
log::error!("SVG copying is not yet supported");
return;
}
ClipboardContent::Image { .. } => {
log::error!("Image copying is not yet supported");
return;
}
ClipboardContent::Layer(layer) => format!("{CLIPBOARD_PREFIX_LAYER}{layer}"),
ClipboardContent::Nodes(nodes) => format!("{CLIPBOARD_PREFIX_NODES}{nodes}"),
ClipboardContent::Vector(vector) => format!("{CLIPBOARD_PREFIX_VECTOR}{vector}"),
ClipboardContent::Text(text) => text,
};
responses.add(FrontendMessage::TriggerClipboardWrite { content: text });
}
}
}
advertise_actions!(ClipboardMessageDiscriminant;
Cut,
Copy,
Paste,
);
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/globals/globals_message.rs | editor/src/messages/globals/globals_message.rs | use crate::messages::portfolio::utility_types::Platform;
use crate::messages::prelude::*;
#[impl_message(Message, Globals)]
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum GlobalsMessage {
SetPlatform { platform: Platform },
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/globals/globals_message_handler.rs | editor/src/messages/globals/globals_message_handler.rs | use crate::messages::prelude::*;
#[derive(Debug, Default, ExtractField)]
pub struct GlobalsMessageHandler {}
#[message_handler_data]
impl MessageHandler<GlobalsMessage, ()> for GlobalsMessageHandler {
fn process_message(&mut self, message: GlobalsMessage, _responses: &mut VecDeque<Message>, _: ()) {
match message {
GlobalsMessage::SetPlatform { platform } => {
if GLOBAL_PLATFORM.get() != Some(&platform) {
GLOBAL_PLATFORM.set(platform).expect("Failed to set GLOBAL_PLATFORM");
}
}
}
}
advertise_actions!(GlobalsMessageDiscriminant;
);
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/globals/global_variables.rs | editor/src/messages/globals/global_variables.rs | use crate::messages::portfolio::utility_types::Platform;
use std::sync::OnceLock;
pub static GLOBAL_PLATFORM: OnceLock<Platform> = OnceLock::new();
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/globals/mod.rs | editor/src/messages/globals/mod.rs | mod globals_message;
mod globals_message_handler;
pub mod global_variables;
#[doc(inline)]
pub use globals_message::{GlobalsMessage, GlobalsMessageDiscriminant};
#[doc(inline)]
pub use globals_message_handler::GlobalsMessageHandler;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs | editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs | use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates, ModifierKeys};
use crate::messages::input_mapper::utility_types::input_mouse::{MouseButton, MouseKeys, MouseState};
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
use crate::messages::prelude::*;
use std::time::Duration;
#[derive(ExtractField)]
pub struct InputPreprocessorMessageContext<'a> {
pub keyboard_platform: KeyboardPlatformLayout,
pub viewport: &'a ViewportMessageHandler,
}
#[derive(Debug, Default, ExtractField)]
pub struct InputPreprocessorMessageHandler {
pub frame_time: FrameTimeInfo,
pub time: u64,
pub keyboard: KeyStates,
pub mouse: MouseState,
}
#[message_handler_data]
impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext<'a>> for InputPreprocessorMessageHandler {
fn process_message(&mut self, message: InputPreprocessorMessage, responses: &mut VecDeque<Message>, context: InputPreprocessorMessageContext<'a>) {
let InputPreprocessorMessageContext { keyboard_platform, viewport } = context;
match message {
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
for key in mouse_state.mouse_keys {
responses.add(InputMapperMessage::DoubleClick(match key {
MouseKeys::LEFT => MouseButton::Left,
MouseKeys::RIGHT => MouseButton::Right,
MouseKeys::MIDDLE => MouseButton::Middle,
MouseKeys::BACK => MouseButton::Back,
MouseKeys::FORWARD => MouseButton::Forward,
_ => unimplemented!(),
}));
}
}
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.keyboard.set(key as usize);
if !key_repeat {
responses.add(InputMapperMessage::KeyDownNoRepeat(key));
}
responses.add(InputMapperMessage::KeyDown(key));
}
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.keyboard.unset(key as usize);
if !key_repeat {
responses.add(InputMapperMessage::KeyUpNoRepeat(key));
}
responses.add(InputMapperMessage::KeyUp(key));
}
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
self.translate_mouse_event(mouse_state, true, responses);
}
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
responses.add(InputMapperMessage::PointerMove);
// While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events
self.translate_mouse_event(mouse_state, false, responses);
}
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
self.translate_mouse_event(mouse_state, false, responses);
}
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
responses.add(InputMapperMessage::PointerShake);
}
InputPreprocessorMessage::CurrentTime { timestamp } => {
responses.add(AnimationMessage::SetTime { time: timestamp as f64 });
self.time = timestamp;
self.frame_time.advance_timestamp(Duration::from_millis(timestamp));
}
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
self.mouse.scroll_delta = mouse_state.scroll_delta;
responses.add(InputMapperMessage::WheelScroll);
}
};
}
// Clean user input and if possible reconstruct it.
// Store the changes in the keyboard if it is a key event.
// Transform canvas coordinates to document coordinates.
advertise_actions!();
}
impl InputPreprocessorMessageHandler {
fn translate_mouse_event(&mut self, mut new_state: MouseState, allow_first_button_down: bool, responses: &mut VecDeque<Message>) {
let click_mappings = [
(MouseKeys::LEFT, Key::MouseLeft),
(MouseKeys::RIGHT, Key::MouseRight),
(MouseKeys::MIDDLE, Key::MouseMiddle),
(MouseKeys::BACK, Key::MouseBack),
(MouseKeys::FORWARD, Key::MouseForward),
];
for (bit_flag, key) in click_mappings {
// Calculate the intersection between the two key states
let old_down = self.mouse.mouse_keys & bit_flag == bit_flag;
let new_down = new_state.mouse_keys & bit_flag == bit_flag;
if !old_down && new_down {
if allow_first_button_down || self.mouse.mouse_keys != MouseKeys::empty() {
self.keyboard.set(key as usize);
responses.add(InputMapperMessage::KeyDown(key));
} else {
// Required to stop a keyup being emitted for a keydown outside canvas
new_state.mouse_keys ^= bit_flag;
}
}
if old_down && !new_down {
self.keyboard.unset(key as usize);
responses.add(InputMapperMessage::KeyUp(key));
}
}
self.mouse = new_state;
}
fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, keyboard_platform: KeyboardPlatformLayout, responses: &mut VecDeque<Message>) {
let is_key_pressed = |key_to_check: ModifierKeys| pressed_modifier_keys.contains(key_to_check);
// Update the state of the concrete modifier keys based on the source state
self.update_modifier_key(Key::Shift, is_key_pressed(ModifierKeys::SHIFT), responses);
self.update_modifier_key(Key::Alt, is_key_pressed(ModifierKeys::ALT), responses);
self.update_modifier_key(Key::Control, is_key_pressed(ModifierKeys::CONTROL), responses);
// Update the state of either the concrete Meta or the Command keys based on which one is applicable for this platform
let meta_or_command = match keyboard_platform {
KeyboardPlatformLayout::Mac => Key::Command,
KeyboardPlatformLayout::Standard => Key::Meta,
};
self.update_modifier_key(meta_or_command, is_key_pressed(ModifierKeys::META_OR_COMMAND), responses);
// Update the state of the virtual Accel key (the primary accelerator key) based on the source state of the Control or Command key, whichever is relevant on this platform
let accel_virtual_key_state = match keyboard_platform {
KeyboardPlatformLayout::Mac => is_key_pressed(ModifierKeys::META_OR_COMMAND),
KeyboardPlatformLayout::Standard => is_key_pressed(ModifierKeys::CONTROL),
};
self.update_modifier_key(Key::Accel, accel_virtual_key_state, responses);
}
fn update_modifier_key(&mut self, key: Key, key_is_down: bool, responses: &mut VecDeque<Message>) {
let key_was_down = self.keyboard.get(key as usize);
if key_was_down && !key_is_down {
self.keyboard.unset(key as usize);
responses.add(InputMapperMessage::KeyUp(key));
} else if !key_was_down && key_is_down {
self.keyboard.set(key as usize);
responses.add(InputMapperMessage::KeyDown(key));
}
}
}
#[cfg(test)]
mod test {
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
use crate::messages::prelude::*;
#[test]
fn process_action_mouse_move_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
let editor_mouse_state = EditorMouseState {
editor_position: (4., 809.).into(),
mouse_keys: MouseKeys::default(),
scroll_delta: ScrollDelta::default(),
};
let modifier_keys = ModifierKeys::ALT;
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
assert!(input_preprocessor.keyboard.get(Key::Alt as usize));
assert_eq!(responses.pop_front(), Some(InputMapperMessage::KeyDown(Key::Alt).into()));
}
#[test]
fn process_action_mouse_down_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
let editor_mouse_state = EditorMouseState::default();
let modifier_keys = ModifierKeys::CONTROL;
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
assert!(input_preprocessor.keyboard.get(Key::Control as usize));
assert_eq!(responses.pop_front(), Some(InputMapperMessage::KeyDown(Key::Control).into()));
}
#[test]
fn process_action_mouse_up_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
let editor_mouse_state = EditorMouseState::default();
let modifier_keys = ModifierKeys::SHIFT;
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
assert!(input_preprocessor.keyboard.get(Key::Shift as usize));
assert_eq!(responses.pop_front(), Some(InputMapperMessage::KeyDown(Key::Shift).into()));
}
#[test]
fn process_action_key_down_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
input_preprocessor.keyboard.set(Key::Control as usize);
let key = Key::KeyA;
let key_repeat = false;
let modifier_keys = ModifierKeys::empty();
let message = InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys };
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
assert!(!input_preprocessor.keyboard.get(Key::Control as usize));
assert_eq!(responses.pop_front(), Some(InputMapperMessage::KeyUp(Key::Control).into()));
}
#[test]
fn process_action_key_up_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
let key = Key::KeyS;
let key_repeat = false;
let modifier_keys = ModifierKeys::CONTROL | ModifierKeys::SHIFT;
let message = InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys };
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
assert!(input_preprocessor.keyboard.get(Key::Control as usize));
assert!(input_preprocessor.keyboard.get(Key::Shift as usize));
assert!(responses.contains(&InputMapperMessage::KeyDown(Key::Control).into()));
assert!(responses.contains(&InputMapperMessage::KeyDown(Key::Control).into()));
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/input_preprocessor/mod.rs | editor/src/messages/input_preprocessor/mod.rs | mod input_preprocessor_message;
mod input_preprocessor_message_handler;
#[doc(inline)]
pub use input_preprocessor_message::{InputPreprocessorMessage, InputPreprocessorMessageDiscriminant};
#[doc(inline)]
pub use input_preprocessor_message_handler::{InputPreprocessorMessageContext, InputPreprocessorMessageHandler};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/input_preprocessor/input_preprocessor_message.rs | editor/src/messages/input_preprocessor/input_preprocessor_message.rs | use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
use crate::messages::input_mapper::utility_types::input_mouse::EditorMouseState;
use crate::messages::prelude::*;
#[impl_message(Message, InputPreprocessor)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum InputPreprocessorMessage {
DoubleClick { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
KeyDown { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
KeyUp { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
PointerDown { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
PointerMove { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
PointerUp { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
PointerShake { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
CurrentTime { timestamp: u64 },
WheelScroll { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/layout_message.rs | editor/src/messages/layout/layout_message.rs | use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
#[impl_message(Message, Layout)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum LayoutMessage {
ResendActiveWidget {
layout_target: LayoutTarget,
widget_id: WidgetId,
},
SendLayout {
layout: Layout,
layout_target: LayoutTarget,
},
DestroyLayout {
layout_target: LayoutTarget,
},
WidgetValueCommit {
layout_target: LayoutTarget,
widget_id: WidgetId,
value: serde_json::Value,
},
WidgetValueUpdate {
layout_target: LayoutTarget,
widget_id: WidgetId,
value: serde_json::Value,
},
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/layout_message_handler.rs | editor/src/messages/layout/layout_message_handler.rs | use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::{FillChoice, GradientStops};
use serde_json::Value;
use std::collections::HashMap;
#[derive(ExtractField)]
pub struct LayoutMessageContext<'a> {
pub action_input_mapping: &'a dyn Fn(&MessageDiscriminant) -> Option<KeysGroup>,
}
#[derive(Debug, Clone, Default, ExtractField)]
pub struct LayoutMessageHandler {
layouts: [Layout; LayoutTarget::_LayoutTargetLength as usize],
}
#[message_handler_data]
impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHandler {
fn process_message(&mut self, message: LayoutMessage, responses: &mut std::collections::VecDeque<Message>, context: LayoutMessageContext) {
let action_input_mapping = &context.action_input_mapping;
match message {
LayoutMessage::ResendActiveWidget { layout_target, widget_id } => {
// Find the updated diff based on the specified layout target
let Some(diff) = Self::get_widget_path(&self.layouts[layout_target as usize], widget_id).map(|(widget, widget_path)| {
// Create a widget update diff for the relevant id
let new_value = DiffUpdate::Widget(widget.clone());
WidgetDiff { widget_path, new_value }
}) else {
return;
};
// Resend that diff
self.send_diff(vec![diff], layout_target, responses, action_input_mapping);
}
LayoutMessage::SendLayout { layout, layout_target } => {
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
}
LayoutMessage::DestroyLayout { layout_target } => {
if let Some(layout) = self.layouts.get_mut(layout_target as usize) {
*layout = Layout::default();
}
}
LayoutMessage::WidgetValueCommit { layout_target, widget_id, value } => {
self.handle_widget_callback(layout_target, widget_id, value, WidgetValueAction::Commit, responses);
}
LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value } => {
self.handle_widget_callback(layout_target, widget_id, value, WidgetValueAction::Update, responses);
}
}
}
fn actions(&self) -> ActionList {
actions!(LayoutMessageDiscriminant;)
}
}
impl LayoutMessageHandler {
/// Get the widget path for the widget with the specified id
fn get_widget_path(widget_layout: &Layout, widget_id: WidgetId) -> Option<(&WidgetInstance, Vec<usize>)> {
let mut stack = widget_layout.0.iter().enumerate().map(|(index, val)| (vec![index], val)).collect::<Vec<_>>();
while let Some((mut widget_path, layout_group)) = stack.pop() {
match layout_group {
// Check if any of the widgets in the current column or row have the correct id
LayoutGroup::Column { widgets } | LayoutGroup::Row { widgets } => {
for (index, widget) in widgets.iter().enumerate() {
// Return if this is the correct ID
if widget.widget_id == widget_id {
widget_path.push(index);
return Some((widget, widget_path));
}
if let Widget::PopoverButton(popover) = &*widget.widget {
stack.extend(
popover
.popover_layout
.0
.iter()
.enumerate()
.map(|(child, val)| ([widget_path.as_slice(), &[index, child]].concat(), val)),
);
}
}
}
// A section contains more LayoutGroups which we add to the stack.
LayoutGroup::Section { layout, .. } => {
stack.extend(layout.0.iter().enumerate().map(|(index, val)| ([widget_path.as_slice(), &[index]].concat(), val)));
}
LayoutGroup::Table { rows, .. } => {
for (row_index, row) in rows.iter().enumerate() {
for (cell_index, cell) in row.iter().enumerate() {
// Return if this is the correct ID
if cell.widget_id == widget_id {
widget_path.push(row_index);
widget_path.push(cell_index);
return Some((cell, widget_path));
}
if let Widget::PopoverButton(popover) = &*cell.widget {
stack.extend(
popover
.popover_layout
.0
.iter()
.enumerate()
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, cell_index, child]].concat(), val)),
);
}
}
}
}
}
}
None
}
fn handle_widget_callback(&mut self, layout_target: LayoutTarget, widget_id: WidgetId, value: Value, action: WidgetValueAction, responses: &mut std::collections::VecDeque<Message>) {
let Some(layout) = self.layouts.get_mut(layout_target as usize) else {
warn!("handle_widget_callback was called referencing an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`",);
return;
};
let Some(widget_instance) = layout.iter_mut().find(|widget| widget.widget_id == widget_id) else {
warn!("handle_widget_callback was called referencing an invalid widget ID, although the layout target was valid. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`",);
return;
};
match &mut *widget_instance.widget {
Widget::BreadcrumbTrailButtons(breadcrumb_trail_buttons) => {
let callback_message = match action {
WidgetValueAction::Commit => (breadcrumb_trail_buttons.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Some(update_value) = value.as_u64() else {
error!("BreadcrumbTrailButtons update was not of type: u64");
return;
};
(breadcrumb_trail_buttons.on_update.callback)(&update_value)
}
};
responses.add(callback_message);
}
Widget::CheckboxInput(checkbox_input) => {
let callback_message = match action {
WidgetValueAction::Commit => (checkbox_input.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Some(update_value) = value.as_bool() else {
error!("CheckboxInput update was not of type: bool");
return;
};
checkbox_input.checked = update_value;
(checkbox_input.on_update.callback)(checkbox_input)
}
};
responses.add(callback_message);
}
Widget::ColorInput(color_button) => {
let callback_message = match action {
WidgetValueAction::Commit => (color_button.on_commit.callback)(&()),
WidgetValueAction::Update => {
// Decodes the colors in gamma, not linear
let decode_color = |color: &serde_json::map::Map<String, serde_json::value::Value>| -> Option<Color> {
let red = color.get("red").and_then(|x| x.as_f64()).map(|x| x as f32);
let green = color.get("green").and_then(|x| x.as_f64()).map(|x| x as f32);
let blue = color.get("blue").and_then(|x| x.as_f64()).map(|x| x as f32);
let alpha = color.get("alpha").and_then(|x| x.as_f64()).map(|x| x as f32);
if let (Some(red), Some(green), Some(blue), Some(alpha)) = (red, green, blue, alpha)
&& let Some(color) = Color::from_rgbaf32(red, green, blue, alpha)
{
return Some(color);
}
None
};
(|| {
let Some(update_value) = value.as_object() else {
warn!("ColorInput update was not of type: object");
return Message::NoOp;
};
// None
let is_none = update_value.get("none").and_then(|x| x.as_bool());
if is_none == Some(true) {
color_button.value = FillChoice::None;
return (color_button.on_update.callback)(color_button);
}
// Solid
if let Some(color) = decode_color(update_value) {
color_button.value = FillChoice::Solid(color);
return (color_button.on_update.callback)(color_button);
}
// Gradient
let gradient = update_value.get("stops").and_then(|x| x.as_array());
if let Some(stops) = gradient {
let gradient_stops = stops
.iter()
.filter_map(|stop| {
stop.as_object().and_then(|stop| {
let position = stop.get("position").and_then(|x| x.as_f64());
let color = stop.get("color").and_then(|x| x.as_object()).and_then(decode_color);
if let (Some(position), Some(color)) = (position, color) { Some((position, color)) } else { None }
})
})
.collect::<Vec<_>>();
color_button.value = FillChoice::Gradient(GradientStops::new(gradient_stops));
return (color_button.on_update.callback)(color_button);
}
warn!("ColorInput update was not able to be parsed with color data: {color_button:?}");
Message::NoOp
})()
}
};
responses.add(callback_message);
}
Widget::CurveInput(curve_input) => {
let callback_message = match action {
WidgetValueAction::Commit => (curve_input.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Some(curve) = serde_json::from_value(value).ok() else {
error!("CurveInput event data could not be deserialized");
return;
};
curve_input.value = curve;
(curve_input.on_update.callback)(curve_input)
}
};
responses.add(callback_message);
}
Widget::DropdownInput(dropdown_input) => {
let callback_message = match action {
WidgetValueAction::Commit => {
let Some(update_value) = value.as_u64() else {
error!("DropdownInput commit was not of type `u64`, found {value:?}");
return;
};
let Some(entry) = dropdown_input.entries.iter().flatten().nth(update_value as usize) else {
error!("DropdownInput commit was not able to find entry for index {update_value}");
return;
};
(entry.on_commit.callback)(&())
}
WidgetValueAction::Update => {
let Some(update_value) = value.as_u64() else {
error!("DropdownInput update was not of type `u64`, found {value:?}");
return;
};
dropdown_input.selected_index = Some(update_value as u32);
let Some(entry) = dropdown_input.entries.iter().flatten().nth(update_value as usize) else {
error!("DropdownInput update was not able to find entry for index {update_value}");
return;
};
(entry.on_update.callback)(&())
}
};
responses.add(callback_message);
}
Widget::IconButton(icon_button) => {
let callback_message = match action {
WidgetValueAction::Commit => (icon_button.on_commit.callback)(&()),
WidgetValueAction::Update => (icon_button.on_update.callback)(icon_button),
};
responses.add(callback_message);
}
Widget::ImageButton(image_label) => {
let callback_message = match action {
WidgetValueAction::Commit => (image_label.on_commit.callback)(&()),
WidgetValueAction::Update => (image_label.on_update.callback)(&()),
};
responses.add(callback_message);
}
Widget::ImageLabel(_) => {}
Widget::ShortcutLabel(_) => {}
Widget::IconLabel(_) => {}
Widget::NodeCatalog(node_type_input) => match action {
WidgetValueAction::Commit => {
let callback_message = (node_type_input.on_commit.callback)(&());
responses.add(callback_message);
}
WidgetValueAction::Update => {
let Some(value) = value.as_str().map(|s| s.to_string()) else {
error!("NodeCatalog update was not of type String");
return;
};
let callback_message = (node_type_input.on_update.callback)(&value);
responses.add(callback_message);
}
},
Widget::NumberInput(number_input) => match action {
WidgetValueAction::Commit => {
let callback_message = (number_input.on_commit.callback)(&());
responses.add(callback_message);
}
WidgetValueAction::Update => match value {
Value::Number(ref num) => {
let Some(update_value) = num.as_f64() else {
error!("NumberInput update was not of type: f64, found {value:?}");
return;
};
number_input.value = Some(update_value);
let callback_message = (number_input.on_update.callback)(number_input);
responses.add(callback_message);
}
// TODO: This crashes when the cursor is in a text box, such as in the Text node, and the transform node is clicked (https://github.com/GraphiteEditor/Graphite/issues/1761)
Value::String(str) => match str.as_str() {
"Increment" => responses.add((number_input.increment_callback_increase.callback)(number_input)),
"Decrement" => responses.add((number_input.increment_callback_decrease.callback)(number_input)),
_ => panic!("Invalid string found when updating `NumberInput`"),
},
_ => {}
},
},
Widget::ParameterExposeButton(parameter_expose_button) => {
let callback_message = match action {
WidgetValueAction::Commit => (parameter_expose_button.on_commit.callback)(&()),
WidgetValueAction::Update => (parameter_expose_button.on_update.callback)(parameter_expose_button),
};
responses.add(callback_message);
}
Widget::ReferencePointInput(reference_point_input) => {
let callback_message = match action {
WidgetValueAction::Commit => (reference_point_input.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Some(update_value) = value.as_str() else {
error!("ReferencePointInput update was not of type: u64");
return;
};
reference_point_input.value = update_value.into();
(reference_point_input.on_update.callback)(reference_point_input)
}
};
responses.add(callback_message);
}
Widget::PopoverButton(_) => {}
Widget::RadioInput(radio_input) => {
let Some(update_value) = value.as_u64() else {
error!("RadioInput update was not of type: u64");
return;
};
radio_input.selected_index = Some(update_value as u32);
let callback_message = match action {
WidgetValueAction::Commit => (radio_input.entries[update_value as usize].on_commit.callback)(&()),
WidgetValueAction::Update => (radio_input.entries[update_value as usize].on_update.callback)(&()),
};
responses.add(callback_message);
}
Widget::Separator(_) => {}
Widget::TextAreaInput(text_area_input) => {
let callback_message = match action {
WidgetValueAction::Commit => (text_area_input.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Some(update_value) = value.as_str() else {
error!("TextAreaInput update was not of type: string");
return;
};
text_area_input.value = update_value.into();
(text_area_input.on_update.callback)(text_area_input)
}
};
responses.add(callback_message);
}
Widget::TextButton(text_button) => {
let callback_message = match action {
WidgetValueAction::Commit => (text_button.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Some(value_path) = value.as_array() else {
error!("TextButton update was not of type: array");
return;
};
// Process the text button click, since no menu is involved if we're given an empty array.
if value_path.is_empty() {
(text_button.on_update.callback)(text_button)
}
// Process the text button's menu list entry click, since we have a path to the value of the contained menu entry.
else {
let mut current_submenu = &text_button.menu_list_children;
let mut final_entry: Option<&MenuListEntry> = None;
// Loop through all menu entry value strings in the path until we reach the final entry (which we store).
// Otherwise we exit early if we can't traverse the full path.
for value in value_path.iter().filter_map(|v| v.as_str().map(|s| s.to_string())) {
let Some(next_entry) = current_submenu.iter().flatten().find(|e| e.value == value) else { return };
current_submenu = &next_entry.children;
final_entry = Some(next_entry);
}
// If we've reached here without returning early, we have a final entry in the path and we should now execute its callback.
(final_entry.unwrap().on_commit.callback)(&())
}
}
};
responses.add(callback_message);
}
Widget::TextInput(text_input) => {
let callback_message = match action {
WidgetValueAction::Commit => (text_input.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Some(update_value) = value.as_str() else {
error!("TextInput update was not of type: string");
return;
};
text_input.value = update_value.into();
(text_input.on_update.callback)(text_input)
}
};
responses.add(callback_message);
}
Widget::TextLabel(_) => {}
Widget::WorkingColorsInput(_) => {}
};
}
/// Diff the update and send to the frontend where necessary
fn diff_and_send_layout_to_frontend(
&mut self,
layout_target: LayoutTarget,
mut new_layout: Layout,
responses: &mut VecDeque<Message>,
action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>,
) {
// Step 1: Collect CheckboxId mappings from new layout
let mut checkbox_map = HashMap::new();
new_layout.collect_checkbox_ids(layout_target, &mut Vec::new(), &mut checkbox_map);
// Step 2: Replace all IDs in new layout with deterministic ones
new_layout.replace_widget_ids(layout_target, &mut Vec::new(), &checkbox_map);
// Step 3: Diff with deterministic IDs
let mut widget_diffs = Vec::new();
self.layouts[layout_target as usize].diff(new_layout, &mut Vec::new(), &mut widget_diffs);
// Skip sending if no diff
if widget_diffs.is_empty() {
return;
}
// On Mac we need the full MenuBar layout to construct the native menu
#[cfg(target_os = "macos")]
if layout_target == LayoutTarget::MenuBar {
widget_diffs = vec![WidgetDiff {
widget_path: Vec::new(),
new_value: DiffUpdate::Layout(self.layouts[LayoutTarget::MenuBar as usize].clone()),
}];
}
self.send_diff(widget_diffs, layout_target, responses, action_input_mapping);
}
/// Send a diff to the frontend based on the layout target.
fn send_diff(&self, mut diff: Vec<WidgetDiff>, layout_target: LayoutTarget, responses: &mut VecDeque<Message>, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
diff.iter_mut().for_each(|diff| diff.new_value.apply_keyboard_shortcut(action_input_mapping));
let message = match layout_target {
LayoutTarget::DataPanel => FrontendMessage::UpdateDataPanelLayout { diff },
LayoutTarget::DialogButtons => FrontendMessage::UpdateDialogButtons { diff },
LayoutTarget::DialogColumn1 => FrontendMessage::UpdateDialogColumn1 { diff },
LayoutTarget::DialogColumn2 => FrontendMessage::UpdateDialogColumn2 { diff },
LayoutTarget::DocumentBar => FrontendMessage::UpdateDocumentBarLayout { diff },
LayoutTarget::LayersPanelBottomBar => FrontendMessage::UpdateLayersPanelBottomBarLayout { diff },
LayoutTarget::LayersPanelControlLeftBar => FrontendMessage::UpdateLayersPanelControlBarLeftLayout { diff },
LayoutTarget::LayersPanelControlRightBar => FrontendMessage::UpdateLayersPanelControlBarRightLayout { diff },
LayoutTarget::MenuBar => FrontendMessage::UpdateMenuBarLayout { diff },
LayoutTarget::NodeGraphControlBar => FrontendMessage::UpdateNodeGraphControlBarLayout { diff },
LayoutTarget::PropertiesPanel => FrontendMessage::UpdatePropertiesPanelLayout { diff },
LayoutTarget::StatusBarHints => FrontendMessage::UpdateStatusBarHintsLayout { diff },
LayoutTarget::StatusBarInfo => FrontendMessage::UpdateStatusBarInfoLayout { diff },
LayoutTarget::ToolOptions => FrontendMessage::UpdateToolOptionsLayout { diff },
LayoutTarget::ToolShelf => FrontendMessage::UpdateToolShelfLayout { diff },
LayoutTarget::WelcomeScreenButtons => FrontendMessage::UpdateWelcomeScreenButtonsLayout { diff },
LayoutTarget::WorkingColors => FrontendMessage::UpdateWorkingColorsLayout { diff },
// KEEP THIS ENUM LAST
LayoutTarget::_LayoutTargetLength => panic!("`_LayoutTargetLength` is not a valid `LayoutTarget` and is used for array indexing"),
};
responses.add(message);
}
}
enum WidgetValueAction {
Commit,
Update,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/mod.rs | editor/src/messages/layout/mod.rs | mod layout_message;
pub mod layout_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use layout_message::{LayoutMessage, LayoutMessageDiscriminant};
#[doc(inline)]
pub use layout_message_handler::LayoutMessageHandler;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/utility_types/layout_widget.rs | editor/src/messages/layout/utility_types/layout_widget.rs | use super::widgets::button_widgets::*;
use super::widgets::input_widgets::*;
use super::widgets::label_widgets::*;
use crate::application::generate_uuid;
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::prelude::*;
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct WidgetId(pub u64);
impl core::fmt::Display for WidgetId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize, specta::Type)]
#[repr(u8)]
pub enum LayoutTarget {
/// The spreadsheet panel allows for the visualisation of data in the graph.
DataPanel,
/// Contains the action buttons at the bottom of the dialog. Must be shown with the `FrontendMessage::DisplayDialog` message.
DialogButtons,
/// Contains the contents of the dialog's primary column. Must be shown with the `FrontendMessage::DisplayDialog` message.
DialogColumn1,
/// Contains the contents of the dialog's secondary column (often blank). Must be shown with the `FrontendMessage::DisplayDialog` message.
DialogColumn2,
/// Contains the widgets located directly above the canvas to the right, for example the zoom in and out buttons.
DocumentBar,
/// Controls for adding, grouping, and deleting layers at the bottom of the Layers panel.
LayersPanelBottomBar,
/// Blending options at the top of the Layers panel.
LayersPanelControlLeftBar,
/// Selected layer status (locked/hidden) at the top of the Layers panel.
LayersPanelControlRightBar,
/// The dropdown menu at the very top of the application: File, Edit, etc.
MenuBar,
/// Bar at the top of the node graph containing the location and the "Preview" and "Hide" buttons.
NodeGraphControlBar,
/// The body of the Properties panel containing many collapsable sections.
PropertiesPanel,
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
StatusBarHints,
/// The version information shown in the status bar at the bottom right of the window.
StatusBarInfo,
/// The left side of the control bar directly above the canvas.
ToolOptions,
/// The vertical buttons for all of the tools on the left of the canvas.
ToolShelf,
/// The quick access buttons found on the welcome screen, shown when no documents are open.
WelcomeScreenButtons,
/// The color swatch for the working colors and a flip and reset button found at the bottom of the tool shelf.
WorkingColors,
// KEEP THIS ENUM LAST
// This is a marker that is used to define an array that is used to hold widgets
_LayoutTargetLength,
}
/// For use by structs that define a UI widget layout by implementing the layout() function belonging to this trait.
/// The send_layout() function can then be called by other code which is a part of the same struct so as to send the layout to the frontend.
pub trait LayoutHolder {
fn layout(&self) -> Layout;
fn send_layout(&self, responses: &mut VecDeque<Message>, layout_target: LayoutTarget) {
responses.add(LayoutMessage::SendLayout { layout: self.layout(), layout_target });
}
}
/// Structs implementing this hold the layout (like [`LayoutHolder`]) for dialog content, but it also requires defining the dialog's title, icon, and action buttons.
pub trait DialogLayoutHolder: LayoutHolder {
const ICON: &'static str;
const TITLE: &'static str;
fn layout_buttons(&self) -> Layout;
fn send_layout_buttons(&self, responses: &mut VecDeque<Message>, layout_target: LayoutTarget) {
responses.add(LayoutMessage::SendLayout {
layout: self.layout_buttons(),
layout_target,
});
}
fn layout_column_2(&self) -> Layout {
Layout::default()
}
fn send_layout_column_2(&self, responses: &mut VecDeque<Message>, layout_target: LayoutTarget) {
responses.add(LayoutMessage::SendLayout {
layout: self.layout_column_2(),
layout_target,
});
}
fn send_dialog_to_frontend(&self, responses: &mut VecDeque<Message>) {
self.send_layout(responses, LayoutTarget::DialogColumn1);
self.send_layout_column_2(responses, LayoutTarget::DialogColumn2);
self.send_layout_buttons(responses, LayoutTarget::DialogButtons);
responses.add(FrontendMessage::DisplayDialog {
icon: Self::ICON.into(),
title: Self::TITLE.into(),
});
}
}
/// Trait for types that can compute incremental diffs for UI updates.
///
/// This trait unifies the diffing behavior across Layout, LayoutGroup, and WidgetInstance,
/// allowing each type to specify how it should be represented in a DiffUpdate.
pub trait Diffable: Clone + PartialEq {
/// Converts this value into a DiffUpdate variant.
fn into_diff_update(self) -> DiffUpdate;
/// Computes the diff between self (old) and new, updating self and recording changes.
fn diff(&mut self, new: Self, widget_path: &mut Vec<usize>, widget_diffs: &mut Vec<WidgetDiff>);
/// Collects all CheckboxIds currently in use in this layout, computing stable replacements.
fn collect_checkbox_ids(&self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &mut HashMap<CheckboxId, CheckboxId>);
/// Replaces all widget IDs with deterministic IDs based on position and type.
/// Also replaces CheckboxIds using the provided mapping.
fn replace_widget_ids(&mut self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &HashMap<CheckboxId, CheckboxId>);
}
/// Computes a deterministic WidgetId based on layout target, path, and widget type.
fn compute_widget_id(layout_target: LayoutTarget, widget_path: &[usize], widget: &Widget) -> WidgetId {
let mut hasher = DefaultHasher::new();
(layout_target as u8).hash(&mut hasher);
widget_path.hash(&mut hasher);
std::mem::discriminant(widget).hash(&mut hasher);
WidgetId(hasher.finish())
}
/// Computes a deterministic CheckboxId based on the same WidgetId algorithm.
fn compute_checkbox_id(layout_target: LayoutTarget, widget_path: &[usize], widget: &Widget) -> CheckboxId {
let mut hasher = DefaultHasher::new();
(layout_target as u8).hash(&mut hasher);
widget_path.hash(&mut hasher);
std::mem::discriminant(widget).hash(&mut hasher);
// Add extra salt for checkbox to differentiate from widget ID
"checkbox".hash(&mut hasher);
CheckboxId(hasher.finish())
}
/// Contains an arrangement of widgets mounted somewhere specific in the frontend.
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, PartialEq, specta::Type)]
pub struct Layout(pub Vec<LayoutGroup>);
impl Layout {
pub fn iter(&self) -> WidgetIter<'_> {
WidgetIter {
stack: self.0.iter().collect(),
..Default::default()
}
}
pub fn iter_mut(&mut self) -> WidgetIterMut<'_> {
WidgetIterMut {
stack: self.0.iter_mut().collect(),
..Default::default()
}
}
}
impl Diffable for Layout {
fn into_diff_update(self) -> DiffUpdate {
DiffUpdate::Layout(self)
}
fn diff(&mut self, new: Self, widget_path: &mut Vec<usize>, widget_diffs: &mut Vec<WidgetDiff>) {
// Check if the length of items is different
// TODO: Diff insersion and deletion of items
if self.0.len() != new.0.len() {
// Update the layout to the new layout
self.0.clone_from(&new.0);
// Push an update sublayout to the diff
widget_diffs.push(WidgetDiff {
widget_path: widget_path.to_vec(),
new_value: new.into_diff_update(),
});
return;
}
// Diff all of the children
for (index, (current_child, new_child)) in self.0.iter_mut().zip(new.0).enumerate() {
widget_path.push(index);
current_child.diff(new_child, widget_path, widget_diffs);
widget_path.pop();
}
}
fn collect_checkbox_ids(&self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &mut HashMap<CheckboxId, CheckboxId>) {
for (index, child) in self.0.iter().enumerate() {
widget_path.push(index);
child.collect_checkbox_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
}
}
fn replace_widget_ids(&mut self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &HashMap<CheckboxId, CheckboxId>) {
for (index, child) in self.0.iter_mut().enumerate() {
widget_path.push(index);
child.replace_widget_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
}
}
}
#[derive(Debug, Default)]
pub struct WidgetIter<'a> {
pub stack: Vec<&'a LayoutGroup>,
pub table: Vec<&'a WidgetInstance>,
pub current_slice: Option<&'a [WidgetInstance]>,
}
impl<'a> Iterator for WidgetIter<'a> {
type Item = &'a WidgetInstance;
fn next(&mut self) -> Option<Self::Item> {
let widget = self.table.pop().or_else(|| {
let (first, rest) = self.current_slice.take()?.split_first()?;
self.current_slice = Some(rest);
Some(first)
});
if let Some(instance) = widget {
if let Widget::PopoverButton(popover_button) = &*instance.widget {
self.stack.extend(popover_button.popover_layout.0.iter());
return self.next();
}
return Some(instance);
}
match self.stack.pop() {
Some(LayoutGroup::Column { widgets }) => {
self.current_slice = Some(widgets);
self.next()
}
Some(LayoutGroup::Row { widgets }) => {
self.current_slice = Some(widgets);
self.next()
}
Some(LayoutGroup::Table { rows, .. }) => {
self.table.extend(rows.iter().flatten().rev());
self.next()
}
Some(LayoutGroup::Section { layout, .. }) => {
for layout_row in &layout.0 {
self.stack.push(layout_row);
}
self.next()
}
None => None,
}
}
}
#[derive(Debug, Default)]
pub struct WidgetIterMut<'a> {
pub stack: Vec<&'a mut LayoutGroup>,
pub table: Vec<&'a mut WidgetInstance>,
pub current_slice: Option<&'a mut [WidgetInstance]>,
}
impl<'a> Iterator for WidgetIterMut<'a> {
type Item = &'a mut WidgetInstance;
fn next(&mut self) -> Option<Self::Item> {
let widget = self.table.pop().or_else(|| {
let (first, rest) = self.current_slice.take()?.split_first_mut()?;
self.current_slice = Some(rest);
Some(first)
});
if let Some(instance) = widget {
// We have to check that we're not a popover and return first, then extract the popover with an unreachable else condition second, to satisfy the borrow checker.
// After Rust's Polonius is stable, we can reverse that order of steps to avoid the redundancy and unreachable statement.
if !matches!(*instance.widget, Widget::PopoverButton(_)) {
return Some(instance);
}
let Widget::PopoverButton(popover_button) = &mut *instance.widget else { unreachable!() };
self.stack.extend(popover_button.popover_layout.0.iter_mut());
return self.next();
}
match self.stack.pop() {
Some(LayoutGroup::Column { widgets }) => {
self.current_slice = Some(widgets);
self.next()
}
Some(LayoutGroup::Row { widgets }) => {
self.current_slice = Some(widgets);
self.next()
}
Some(LayoutGroup::Table { rows, .. }) => {
self.table.extend(rows.iter_mut().flatten().rev());
self.next()
}
Some(LayoutGroup::Section { layout, .. }) => {
for layout_row in &mut layout.0 {
self.stack.push(layout_row);
}
self.next()
}
None => None,
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum LayoutGroup {
#[serde(rename = "column")]
Column {
#[serde(rename = "columnWidgets")]
widgets: Vec<WidgetInstance>,
},
#[serde(rename = "row")]
Row {
#[serde(rename = "rowWidgets")]
widgets: Vec<WidgetInstance>,
},
#[serde(rename = "table")]
Table {
#[serde(rename = "tableWidgets")]
rows: Vec<Vec<WidgetInstance>>,
unstyled: bool,
},
#[serde(rename = "section")]
Section {
name: String,
description: String,
visible: bool,
pinned: bool,
id: u64,
layout: Layout,
},
}
impl Default for LayoutGroup {
fn default() -> Self {
Self::Row { widgets: Vec::new() }
}
}
impl From<Vec<WidgetInstance>> for LayoutGroup {
fn from(widgets: Vec<WidgetInstance>) -> LayoutGroup {
LayoutGroup::Row { widgets }
}
}
impl LayoutGroup {
/// Applies a tooltip description to all widgets without a tooltip in this row or column.
pub fn with_tooltip_description(self, description: impl Into<String>) -> Self {
let (is_col, mut widgets) = match self {
LayoutGroup::Column { widgets } => (true, widgets),
LayoutGroup::Row { widgets } => (false, widgets),
_ => unimplemented!(),
};
let description = description.into();
for widget in &mut widgets {
let val = match &mut *widget.widget {
Widget::CheckboxInput(x) => &mut x.tooltip_description,
Widget::ColorInput(x) => &mut x.tooltip_description,
Widget::CurveInput(x) => &mut x.tooltip_description,
Widget::DropdownInput(x) => &mut x.tooltip_description,
Widget::IconButton(x) => &mut x.tooltip_description,
Widget::IconLabel(x) => &mut x.tooltip_description,
Widget::ImageButton(x) => &mut x.tooltip_description,
Widget::ImageLabel(x) => &mut x.tooltip_description,
Widget::NumberInput(x) => &mut x.tooltip_description,
Widget::PopoverButton(x) => &mut x.tooltip_description,
Widget::TextAreaInput(x) => &mut x.tooltip_description,
Widget::TextButton(x) => &mut x.tooltip_description,
Widget::TextInput(x) => &mut x.tooltip_description,
Widget::TextLabel(x) => &mut x.tooltip_description,
Widget::BreadcrumbTrailButtons(x) => &mut x.tooltip_description,
Widget::ReferencePointInput(_)
| Widget::RadioInput(_)
| Widget::Separator(_)
| Widget::ShortcutLabel(_)
| Widget::WorkingColorsInput(_)
| Widget::NodeCatalog(_)
| Widget::ParameterExposeButton(_) => continue,
};
if val.is_empty() {
val.clone_from(&description);
}
}
if is_col { Self::Column { widgets } } else { Self::Row { widgets } }
}
pub fn iter_mut(&mut self) -> WidgetIterMut<'_> {
WidgetIterMut {
stack: vec![self],
..Default::default()
}
}
}
impl Diffable for LayoutGroup {
fn into_diff_update(self) -> DiffUpdate {
DiffUpdate::LayoutGroup(self)
}
fn diff(&mut self, new: Self, widget_path: &mut Vec<usize>, widget_diffs: &mut Vec<WidgetDiff>) {
let is_column = matches!(new, Self::Column { .. });
match (self, new) {
(Self::Column { widgets: current_widgets }, Self::Column { widgets: new_widgets }) | (Self::Row { widgets: current_widgets }, Self::Row { widgets: new_widgets }) => {
// If the lengths are different then resend the entire panel
// TODO: Diff insersion and deletion of items
if current_widgets.len() != new_widgets.len() {
// Update to the new value
current_widgets.clone_from(&new_widgets);
// Push back a LayoutGroup update to the diff
let new_value = (if is_column { Self::Column { widgets: new_widgets } } else { Self::Row { widgets: new_widgets } }).into_diff_update();
let widget_path = widget_path.to_vec();
widget_diffs.push(WidgetDiff { widget_path, new_value });
return;
}
// Diff all of the children
for (index, (current_child, new_child)) in current_widgets.iter_mut().zip(new_widgets).enumerate() {
widget_path.push(index);
current_child.diff(new_child, widget_path, widget_diffs);
widget_path.pop();
}
}
(
Self::Section {
name: current_name,
description: current_description,
visible: current_visible,
pinned: current_pinned,
id: current_id,
layout: current_layout,
},
Self::Section {
name: new_name,
description: new_description,
visible: new_visible,
pinned: new_pinned,
id: new_id,
layout: new_layout,
},
) => {
// Resend the entire panel if the lengths, names, visibility, or node IDs are different
// TODO: Diff insersion and deletion of items
if current_layout.0.len() != new_layout.0.len()
|| *current_name != new_name
|| *current_description != new_description
|| *current_visible != new_visible
|| *current_pinned != new_pinned
|| *current_id != new_id
{
// Update self to reflect new changes
current_name.clone_from(&new_name);
current_description.clone_from(&new_description);
*current_visible = new_visible;
*current_pinned = new_pinned;
*current_id = new_id;
current_layout.clone_from(&new_layout);
// Push an update layout group to the diff
let new_value = Self::Section {
name: new_name,
description: new_description,
visible: new_visible,
pinned: new_pinned,
id: new_id,
layout: new_layout,
}
.into_diff_update();
let widget_path = widget_path.to_vec();
widget_diffs.push(WidgetDiff { widget_path, new_value });
}
// Diff all of the children
else {
for (index, (current_child, new_child)) in current_layout.0.iter_mut().zip(new_layout.0).enumerate() {
widget_path.push(index);
current_child.diff(new_child, widget_path, widget_diffs);
widget_path.pop();
}
}
}
(current, new) => {
*current = new.clone();
let new_value = new.into_diff_update();
let widget_path = widget_path.to_vec();
widget_diffs.push(WidgetDiff { widget_path, new_value });
}
}
}
fn collect_checkbox_ids(&self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &mut HashMap<CheckboxId, CheckboxId>) {
match self {
Self::Column { widgets } | Self::Row { widgets } => {
for (index, widget) in widgets.iter().enumerate() {
widget_path.push(index);
widget.collect_checkbox_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
}
}
Self::Table { rows, .. } => {
for (row_idx, row) in rows.iter().enumerate() {
for (col_idx, widget) in row.iter().enumerate() {
widget_path.push(row_idx);
widget_path.push(col_idx);
widget.collect_checkbox_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
widget_path.pop();
}
}
}
Self::Section { layout, .. } => {
layout.collect_checkbox_ids(layout_target, widget_path, checkbox_map);
}
}
}
fn replace_widget_ids(&mut self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &HashMap<CheckboxId, CheckboxId>) {
match self {
Self::Column { widgets } | Self::Row { widgets } => {
for (index, widget) in widgets.iter_mut().enumerate() {
widget_path.push(index);
widget.replace_widget_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
}
}
Self::Table { rows, .. } => {
for (row_idx, row) in rows.iter_mut().enumerate() {
for (col_idx, widget) in row.iter_mut().enumerate() {
widget_path.push(row_idx);
widget_path.push(col_idx);
widget.replace_widget_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
widget_path.pop();
}
}
}
Self::Section { layout, .. } => {
layout.replace_widget_ids(layout_target, widget_path, checkbox_map);
}
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct WidgetInstance {
#[serde(rename = "widgetId")]
pub widget_id: WidgetId,
pub widget: Box<Widget>,
}
impl PartialEq for WidgetInstance {
fn eq(&self, other: &Self) -> bool {
self.widget_id == other.widget_id && self.widget == other.widget
}
}
impl WidgetInstance {
#[deprecated(since = "0.0.0", note = "Please use the builder pattern, e.g. TextLabel::new(\"hello\").widget_instance()")]
pub fn new(widget: Widget) -> Self {
Self {
widget_id: WidgetId(generate_uuid()),
widget: Box::new(widget),
}
}
}
impl Diffable for WidgetInstance {
fn into_diff_update(self) -> DiffUpdate {
DiffUpdate::Widget(self)
}
fn diff(&mut self, new: Self, widget_path: &mut Vec<usize>, widget_diffs: &mut Vec<WidgetDiff>) {
if self == &new {
// Still need to update callbacks since PartialEq skips them
self.widget = new.widget;
return;
}
// Special handling for PopoverButton: recursively diff nested layout if only the layout changed
if let (Widget::PopoverButton(button1), Widget::PopoverButton(button2)) = (&mut *self.widget, &*new.widget) {
// Check if only the popover layout changed (all other fields are the same)
if self.widget_id == new.widget_id
&& button1.disabled == button2.disabled
&& button1.style == button2.style
&& button1.menu_direction == button2.menu_direction
&& button1.icon == button2.icon
&& button1.tooltip_label == button2.tooltip_label
&& button1.tooltip_description == button2.tooltip_description
&& button1.tooltip_shortcut == button2.tooltip_shortcut
&& button1.popover_min_width == button2.popover_min_width
{
// Only the popover layout differs, diff it recursively
for (i, (a, b)) in button1.popover_layout.0.iter_mut().zip(button2.popover_layout.0.iter()).enumerate() {
widget_path.push(i);
a.diff(b.clone(), widget_path, widget_diffs);
widget_path.pop();
}
return;
}
}
// Widget or ID changed, send full update
*self = new.clone();
let new_value = new.into_diff_update();
let widget_path = widget_path.to_vec();
widget_diffs.push(WidgetDiff { widget_path, new_value });
}
fn collect_checkbox_ids(&self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &mut HashMap<CheckboxId, CheckboxId>) {
match &*self.widget {
Widget::CheckboxInput(checkbox) => {
// Compute stable ID based on position and insert mapping
let checkbox_id = checkbox.for_label;
let stable_id = compute_checkbox_id(layout_target, widget_path, &self.widget);
checkbox_map.entry(checkbox_id).or_insert(stable_id);
}
Widget::TextLabel(label) => {
// Compute stable ID based on position and insert mapping
let checkbox_id = label.for_checkbox;
let stable_id = compute_checkbox_id(layout_target, widget_path, &self.widget);
checkbox_map.entry(checkbox_id).or_insert(stable_id);
}
Widget::PopoverButton(button) => {
// Recursively collect from nested popover layout
for (index, child) in button.popover_layout.0.iter().enumerate() {
widget_path.push(index);
child.collect_checkbox_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
}
}
_ => {}
}
}
fn replace_widget_ids(&mut self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &HashMap<CheckboxId, CheckboxId>) {
// 1. Generate deterministic WidgetId
self.widget_id = compute_widget_id(layout_target, widget_path, &self.widget);
// 2. Replace CheckboxIds if present
match &mut *self.widget {
Widget::CheckboxInput(checkbox) => {
let old_id = checkbox.for_label;
if let Some(&new_id) = checkbox_map.get(&old_id) {
checkbox.for_label = new_id;
}
}
Widget::TextLabel(label) => {
let old_id = label.for_checkbox;
if let Some(&new_id) = checkbox_map.get(&old_id) {
label.for_checkbox = new_id;
}
}
Widget::PopoverButton(button) => {
// Recursively replace in nested popover layout
for (index, child) in button.popover_layout.0.iter_mut().enumerate() {
widget_path.push(index);
child.replace_widget_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
}
}
_ => {}
}
}
}
#[derive(Clone, specta::Type)]
pub struct WidgetCallback<T> {
#[specta(skip)]
pub callback: Arc<dyn Fn(&T) -> Message + 'static + Send + Sync>,
}
impl<T> WidgetCallback<T> {
pub fn new(callback: impl Fn(&T) -> Message + 'static + Send + Sync) -> Self {
Self { callback: Arc::new(callback) }
}
}
impl<T> Default for WidgetCallback<T> {
fn default() -> Self {
Self::new(|_| Message::NoOp)
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum Widget {
BreadcrumbTrailButtons(BreadcrumbTrailButtons),
CheckboxInput(CheckboxInput),
ColorInput(ColorInput),
CurveInput(CurveInput),
DropdownInput(DropdownInput),
IconButton(IconButton),
IconLabel(IconLabel),
ImageButton(ImageButton),
ImageLabel(ImageLabel),
ShortcutLabel(ShortcutLabel),
NodeCatalog(NodeCatalog),
NumberInput(NumberInput),
ParameterExposeButton(ParameterExposeButton),
ReferencePointInput(ReferencePointInput),
PopoverButton(PopoverButton),
RadioInput(RadioInput),
Separator(Separator),
TextAreaInput(TextAreaInput),
TextButton(TextButton),
TextInput(TextInput),
TextLabel(TextLabel),
WorkingColorsInput(WorkingColorsInput),
}
/// A single change to part of the UI, containing the location of the change and the new value.
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct WidgetDiff {
/// A path to the change
/// e.g. [0, 1, 2] in the properties panel is the first section, second row and third widget.
/// An empty path [] shows that the entire panel has changed and is sent when the UI is first created.
#[serde(rename = "widgetPath")]
pub widget_path: Vec<usize>,
/// What the specified part of the UI has changed to.
#[serde(rename = "newValue")]
pub new_value: DiffUpdate,
}
/// The new value of the UI, sent as part of a diff.
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum DiffUpdate {
#[serde(rename = "layout")]
Layout(Layout),
#[serde(rename = "layoutGroup")]
LayoutGroup(LayoutGroup),
#[serde(rename = "widget")]
Widget(WidgetInstance),
}
impl DiffUpdate {
/// Append the keyboard shortcut to the tooltip where applicable
pub fn apply_keyboard_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
// Go through each widget to convert `ActionShortcut::Action` to `ActionShortcut::Shortcut` and append the key combination to the widget tooltip
let convert_tooltip = |widget_instance: &mut WidgetInstance| {
// Handle all the widgets that have tooltips
let tooltip_shortcut = match &mut *widget_instance.widget {
Widget::BreadcrumbTrailButtons(widget) => widget.tooltip_shortcut.as_mut(),
Widget::CheckboxInput(widget) => widget.tooltip_shortcut.as_mut(),
Widget::ColorInput(widget) => widget.tooltip_shortcut.as_mut(),
Widget::DropdownInput(widget) => widget.tooltip_shortcut.as_mut(),
Widget::IconButton(widget) => widget.tooltip_shortcut.as_mut(),
Widget::NumberInput(widget) => widget.tooltip_shortcut.as_mut(),
Widget::ParameterExposeButton(widget) => widget.tooltip_shortcut.as_mut(),
Widget::PopoverButton(widget) => widget.tooltip_shortcut.as_mut(),
Widget::TextButton(widget) => widget.tooltip_shortcut.as_mut(),
Widget::ImageButton(widget) => widget.tooltip_shortcut.as_mut(),
Widget::ShortcutLabel(widget) => widget.shortcut.as_mut(),
Widget::IconLabel(_)
| Widget::ImageLabel(_)
| Widget::CurveInput(_)
| Widget::NodeCatalog(_)
| Widget::ReferencePointInput(_)
| Widget::RadioInput(_)
| Widget::Separator(_)
| Widget::TextAreaInput(_)
| Widget::TextInput(_)
| Widget::TextLabel(_)
| Widget::WorkingColorsInput(_) => None,
};
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
if let Some(tooltip_shortcut) = tooltip_shortcut {
tooltip_shortcut.realize_shortcut(action_input_mapping);
}
// Handle RadioInput separately because its tooltips are children of the widget
if let Widget::RadioInput(radio_input) = &mut *widget_instance.widget {
for radio_entry_data in &mut radio_input.entries {
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
if let Some(tooltip_shortcut) = radio_entry_data.tooltip_shortcut.as_mut() {
tooltip_shortcut.realize_shortcut(action_input_mapping);
}
}
}
};
// Recursively fill menu list entries with their realized shortcut keys specific to the current bindings and platform
let apply_action_shortcut_to_menu_lists = |entry_sections: &mut MenuListEntrySections| {
struct RecursiveWrapper<'a>(&'a dyn Fn(&mut MenuListEntrySections, &RecursiveWrapper));
let recursive_wrapper = RecursiveWrapper(&|entry_sections: &mut MenuListEntrySections, recursive_wrapper| {
for entries in entry_sections {
for entry in entries {
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
if let Some(tooltip_shortcut) = &mut entry.tooltip_shortcut {
tooltip_shortcut.realize_shortcut(action_input_mapping);
}
// Recursively call this inner closure on the menu's children
(recursive_wrapper.0)(&mut entry.children, recursive_wrapper);
}
}
});
(recursive_wrapper.0)(entry_sections, &recursive_wrapper)
};
// Hash the menu list entry sections for caching purposes
let hash_menu_list_entry_sections = |entry_sections: &MenuListEntrySections| {
struct RecursiveHasher<'a> {
hasher: DefaultHasher,
hash_fn: &'a dyn Fn(&mut RecursiveHasher, &MenuListEntrySections),
}
let mut recursive_hasher = RecursiveHasher {
hasher: DefaultHasher::new(),
hash_fn: &|recursive_hasher, entry_sections| {
for (index, entries) in entry_sections.iter().enumerate() {
index.hash(&mut recursive_hasher.hasher);
for entry in entries {
entry.hash(&mut recursive_hasher.hasher);
(recursive_hasher.hash_fn)(recursive_hasher, &entry.children);
}
}
},
};
(recursive_hasher.hash_fn)(&mut recursive_hasher, entry_sections);
recursive_hasher.hasher.finish()
};
// Apply shortcut conversions to all widgets that have menu lists
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget {
Widget::DropdownInput(dropdown_input) => {
apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries);
dropdown_input.entries_hash = hash_menu_list_entry_sections(&dropdown_input.entries);
}
Widget::TextButton(text_button) => {
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children);
text_button.menu_list_children_hash = hash_menu_list_entry_sections(&text_button.menu_list_children);
}
_ => {}
};
match self {
Self::Layout(layout) => layout.0.iter_mut().flat_map(|layout_group| layout_group.iter_mut()).for_each(|widget_instance| {
convert_tooltip(widget_instance);
convert_menu_lists(widget_instance);
}),
Self::LayoutGroup(layout_group) => layout_group.iter_mut().for_each(|widget_instance| {
convert_tooltip(widget_instance);
convert_menu_lists(widget_instance);
}),
Self::Widget(widget_instance) => {
convert_tooltip(widget_instance);
convert_menu_lists(widget_instance);
}
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/utility_types/mod.rs | editor/src/messages/layout/utility_types/mod.rs | pub mod layout_widget;
pub mod widgets;
pub mod widget_prelude {
pub use super::layout_widget::*;
pub use super::widgets::button_widgets::*;
pub use super::widgets::input_widgets::*;
pub use super::widgets::label_widgets::*;
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/utility_types/widgets/label_widgets.rs | editor/src/messages/layout/utility_types/widgets/label_widgets.rs | use super::input_widgets::CheckboxId;
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use derivative::*;
use graphite_proc_macros::WidgetBuilder;
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Debug, Default, PartialEq, Eq, WidgetBuilder, specta::Type)]
pub struct IconLabel {
// Content
#[widget_builder(constructor)]
pub icon: String,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
pub struct Separator {
// Content
pub direction: SeparatorDirection,
#[widget_builder(constructor)]
pub style: SeparatorStyle,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum SeparatorDirection {
#[default]
Horizontal,
Vertical,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum SeparatorStyle {
Related,
#[default]
Unrelated,
Section,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Debug, Eq, Default, WidgetBuilder, specta::Type)]
#[derivative(PartialEq)]
pub struct TextLabel {
// Content
#[widget_builder(constructor)]
pub value: String,
pub disabled: bool,
#[serde(rename = "forCheckbox")]
pub for_checkbox: CheckboxId,
// Styling
pub narrow: bool,
pub bold: bool,
pub italic: bool,
pub monospace: bool,
pub multiline: bool,
#[serde(rename = "centerAlign")]
pub center_align: bool,
#[serde(rename = "tableAlign")]
pub table_align: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "minWidthCharacters")]
pub min_width_characters: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ImageLabel {
// Content
#[widget_builder(constructor)]
pub url: String,
pub width: Option<String>,
pub height: Option<String>,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ShortcutLabel {
// Content
// This is wrapped in an Option to satisfy the requirement that widgets implement Default
#[widget_builder(constructor)]
pub shortcut: Option<ActionShortcut>,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/utility_types/widgets/input_widgets.rs | editor/src/messages/layout/utility_types/widgets/input_widgets.rs | use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use derivative::*;
use graphene_std::Color;
use graphene_std::raster::curve::Curve;
use graphene_std::transform::ReferencePoint;
use graphite_proc_macros::WidgetBuilder;
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, Default, PartialEq)]
pub struct CheckboxInput {
// Content
#[widget_builder(constructor)]
pub checked: bool,
#[derivative(Default(value = "\"Checkmark\".to_string()"))]
pub icon: String,
#[serde(rename = "forLabel")]
pub for_label: CheckboxId,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<CheckboxInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct CheckboxId(pub u64);
impl CheckboxId {
pub fn new() -> Self {
Self(graphene_std::uuid::generate_uuid())
}
}
impl Default for CheckboxId {
fn default() -> Self {
Self::new()
}
}
impl specta::Type for CheckboxId {
fn inline(_type_map: &mut specta::TypeCollection, _generics: specta::Generics) -> specta::datatype::DataType {
// TODO: This might not be right, but it works for now. We just need the type `bigint | undefined`.
specta::datatype::DataType::Primitive(specta::datatype::PrimitiveType::u64)
}
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct DropdownInput {
// Content
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (we can replace this with `usize` if we switch to a Rust-based GUI)
#[serde(rename = "selectedIndex")]
pub selected_index: Option<u32>,
#[serde(rename = "drawIcon")]
pub draw_icon: bool,
pub disabled: bool,
// Children
#[widget_builder(constructor)]
pub entries: MenuListEntrySections,
#[serde(rename = "entriesHash")]
#[widget_builder(skip)]
pub entries_hash: u64,
// Styling
pub narrow: bool,
// Behavior
#[serde(rename = "virtualScrolling")]
pub virtual_scrolling: bool,
#[derivative(Default(value = "true"))]
pub interactive: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "maxWidth")]
pub max_width: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
//
// Callbacks exists on the `MenuListEntry` children, not this parent `DropdownInput`
}
pub type MenuListEntrySections = Vec<Vec<MenuListEntry>>;
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
#[widget_builder(not_widget_instance)]
pub struct MenuListEntry {
// Content
#[widget_builder(constructor)]
pub value: String,
pub label: String,
pub icon: String,
pub disabled: bool,
// Children
pub children: MenuListEntrySections,
#[serde(rename = "childrenHash")]
#[widget_builder(skip)]
pub children_hash: u64,
// Styling
pub font: String,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<()>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
impl std::hash::Hash for MenuListEntry {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.value.hash(state);
self.label.hash(state);
self.icon.hash(state);
self.disabled.hash(state);
}
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct NumberInput {
// Content
#[widget_builder(constructor)]
pub value: Option<f64>,
pub label: String,
pub disabled: bool,
// Styling
pub narrow: bool,
// Behavior
pub mode: NumberInputMode,
#[widget_builder(skip)]
pub min: Option<f64>,
#[widget_builder(skip)]
pub max: Option<f64>,
// TODO: Make this (and range_max) apply to both Range and Increment modes when dragging with the mouse
#[serde(rename = "rangeMin")]
pub range_min: Option<f64>,
#[serde(rename = "rangeMax")]
pub range_max: Option<f64>,
#[derivative(Default(value = "1."))]
pub step: f64,
#[serde(rename = "isInteger")]
pub is_integer: bool,
#[serde(rename = "incrementBehavior")]
pub increment_behavior: NumberInputIncrementBehavior,
#[serde(rename = "displayDecimalPlaces")]
#[derivative(Default(value = "2"))]
pub display_decimal_places: u32,
pub unit: String,
#[serde(rename = "unitIsHiddenWhenEditing")]
#[derivative(Default(value = "true"))]
pub unit_is_hidden_when_editing: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "maxWidth")]
pub max_width: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub increment_callback_increase: WidgetCallback<NumberInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub increment_callback_decrease: WidgetCallback<NumberInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<NumberInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
impl NumberInput {
pub fn int(mut self) -> Self {
self.is_integer = true;
self
}
pub fn min(mut self, val: f64) -> Self {
self.min = Some(val);
self.range_min = Some(val);
self
}
pub fn max(mut self, val: f64) -> Self {
self.max = Some(val);
self.range_max = Some(val);
self
}
pub fn mode_range(mut self) -> Self {
self.mode = NumberInputMode::Range;
self
}
pub fn mode_increment(mut self) -> Self {
self.mode = NumberInputMode::Increment;
self
}
pub fn increment_step(mut self, step: f64) -> Self {
self.step = step;
self
}
pub fn percentage(self) -> Self {
self.min(0.).max(100.).mode_range().unit("%").display_decimal_places(2)
}
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug, Default, PartialEq, Eq, specta::Type)]
pub enum NumberInputIncrementBehavior {
#[default]
Add,
Multiply,
Callback,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug, Default, PartialEq, Eq, specta::Type)]
pub enum NumberInputMode {
#[default]
Increment,
Range,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct NodeCatalog {
// Content
pub disabled: bool,
// Behavior
#[serde(rename = "initialSearchTerm")]
pub intial_search: String,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<String>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct RadioInput {
// Content
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (replace this with `usize` after switching to a Rust-based GUI)
#[serde(rename = "selectedIndex")]
pub selected_index: Option<u32>,
pub disabled: bool,
// Children
#[widget_builder(constructor)]
pub entries: Vec<RadioEntryData>,
// Styling
pub narrow: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
//
// Callbacks exists on the `RadioEntryData` children, not this parent `RadioInput`
}
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
#[widget_builder(not_widget_instance)]
pub struct RadioEntryData {
// Content
#[widget_builder(constructor)]
pub value: String,
pub label: String,
pub icon: String,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<()>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct WorkingColorsInput {
// Content
#[widget_builder(constructor)]
pub primary: Color,
#[widget_builder(constructor)]
pub secondary: Color,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct TextAreaInput {
// Content
#[widget_builder(constructor)]
pub value: String,
pub label: Option<String>,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<TextAreaInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct TextInput {
// Content
#[widget_builder(constructor)]
pub value: String,
pub label: Option<String>,
pub placeholder: Option<String>,
pub disabled: bool,
// Styling
pub narrow: bool,
pub centered: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "maxWidth")]
pub max_width: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<TextInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct CurveInput {
// Content
#[widget_builder(constructor)]
pub value: Curve,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<CurveInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ReferencePointInput {
// Content
#[widget_builder(constructor)]
pub value: ReferencePoint,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<ReferencePointInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/utility_types/widgets/button_widgets.rs | editor/src/messages/layout/utility_types/widgets/button_widgets.rs | use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
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;
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct IconButton {
// Content
#[widget_builder(constructor)]
pub icon: String,
#[serde(rename = "hoverIcon")]
pub hover_icon: Option<String>,
#[widget_builder(constructor)]
pub size: u32, // TODO: Convert to an `IconSize` enum
pub disabled: bool,
// Styling
pub emphasized: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<IconButton>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct PopoverButton {
// Content
pub style: Option<String>,
pub icon: Option<String>,
pub disabled: bool,
// Children
#[serde(rename = "popoverLayout")]
pub popover_layout: Layout,
#[serde(rename = "popoverMinWidth")]
pub popover_min_width: Option<u32>,
#[serde(rename = "menuDirection")]
pub menu_direction: Option<MenuDirection>,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
}
#[derive(Clone, Default, Debug, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum MenuDirection {
Top,
#[default]
Bottom,
Left,
Right,
TopLeft,
TopRight,
BottomLeft,
BottomRight,
Center,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ParameterExposeButton {
// Content
pub exposed: bool,
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<ParameterExposeButton>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct TextButton {
// Content
#[widget_builder(constructor)]
pub label: String,
pub icon: Option<String>,
#[serde(rename = "hoverIcon")]
pub hover_icon: Option<String>,
pub disabled: bool,
// Children
#[serde(rename = "menuListChildren")]
pub menu_list_children: MenuListEntrySections,
#[serde(rename = "menuListChildrenHash")]
#[widget_builder(skip)]
pub menu_list_children_hash: u64,
// Styling
pub emphasized: bool,
pub flush: bool,
pub narrow: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<TextButton>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ImageButton {
// Content
#[widget_builder(constructor)]
pub image: String,
pub width: Option<String>,
pub height: Option<String>,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<()>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct ColorInput {
// Content
/// WARNING: The colors are gamma, not linear!
#[widget_builder(constructor)]
pub value: FillChoice,
#[serde(rename = "allowNone")]
#[derivative(Default(value = "true"))]
pub allow_none: bool,
// #[serde(rename = "allowTransparency")] pub allow_transparency: bool, // TODO: Implement
#[serde(rename = "menuDirection")]
pub menu_direction: Option<MenuDirection>,
pub disabled: bool,
// Styling
pub narrow: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<ColorInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct BreadcrumbTrailButtons {
// Content
#[widget_builder(constructor)]
pub labels: Vec<String>,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<u64>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/layout/utility_types/widgets/mod.rs | editor/src/messages/layout/utility_types/widgets/mod.rs | pub mod button_widgets;
pub mod input_widgets;
pub mod label_widgets;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/viewport/mod.rs | editor/src/messages/viewport/mod.rs | mod viewport_message;
mod viewport_message_handler;
#[doc(inline)]
pub use viewport_message::{ViewportMessage, ViewportMessageDiscriminant};
#[doc(inline)]
pub use viewport_message_handler::*;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/viewport/viewport_message_handler.rs | editor/src/messages/viewport/viewport_message_handler.rs | use std::ops::{Add, Div, Mul, Sub};
use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::tool_prelude::DVec2;
#[derive(Debug, PartialEq, Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type, ExtractField)]
pub struct ViewportMessageHandler {
bounds: Bounds,
// Ratio of logical pixels to physical pixels
scale: f64,
}
impl Default for ViewportMessageHandler {
fn default() -> Self {
Self {
bounds: Bounds {
offset: Point { x: 0.0, y: 0.0 },
size: Point { x: 0.0, y: 0.0 },
},
scale: 1.0,
}
}
}
#[message_handler_data]
impl MessageHandler<ViewportMessage, ()> for ViewportMessageHandler {
fn process_message(&mut self, message: ViewportMessage, responses: &mut VecDeque<Message>, _: ()) {
match message {
ViewportMessage::Update { x, y, width, height, scale } => {
assert_ne!(scale, 0.0, "Viewport scale cannot be zero");
self.scale = scale;
self.bounds = Bounds {
offset: Point { x, y },
size: Point { x: width, y: height },
};
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
}
ViewportMessage::RepropagateUpdate => {}
}
#[cfg(not(target_family = "wasm"))]
{
let physical_bounds = self.bounds().to_physical();
responses.add(FrontendMessage::UpdateViewportPhysicalBounds {
x: physical_bounds.x(),
y: physical_bounds.y(),
width: physical_bounds.width(),
height: physical_bounds.height(),
});
}
responses.add(NavigationMessage::CanvasPan { delta: DVec2::ZERO });
responses.add(DeferMessage::AfterGraphRun {
messages: vec![
DeferMessage::AfterGraphRun {
messages: vec![DeferMessage::TriggerNavigationReady.into()],
}
.into(),
],
});
}
advertise_actions!(ViewportMessageDiscriminant;);
}
impl ViewportMessageHandler {
pub fn scale(&self) -> f64 {
self.scale
}
pub fn bounds(&self) -> LogicalBounds {
self.bounds.into_scaled(self.scale)
}
pub fn offset(&self) -> LogicalPoint {
self.bounds.offset.into_scaled(self.scale)
}
pub fn size(&self) -> LogicalPoint {
self.bounds.size().into_scaled(self.scale)
}
#[expect(private_bounds)]
pub fn logical<T: Into<Point>>(&self, point: T) -> LogicalPoint {
point.into().convert_to_logical(self.scale)
}
#[expect(private_bounds)]
pub fn physical<T: Into<Point>>(&self, point: T) -> PhysicalPoint {
point.into().convert_to_physical(self.scale)
}
pub fn center_in_viewport_space(&self) -> LogicalPoint {
let size = self.size();
LogicalPoint {
inner: Point { x: size.x() / 2.0, y: size.y() / 2.0 },
scale: size.scale,
}
}
pub fn center_in_window_space(&self) -> LogicalPoint {
let size = self.size();
let offset = self.offset();
LogicalPoint {
inner: Point {
x: (size.x() / 2.0) + offset.x(),
y: (size.y() / 2.0) + offset.y(),
},
scale: size.scale,
}
}
pub(crate) fn is_in_bounds(&self, point: LogicalPoint) -> bool {
point.x() >= self.bounds.x() && point.y() >= self.bounds.y() && point.x() <= self.bounds.x() + self.bounds.width() && point.y() <= self.bounds.y() + self.bounds.height()
}
}
pub trait ToLogical<L: ToPhysical<Self> + ?Sized> {
fn to_logical(self) -> L;
}
pub trait ToPhysical<P: ToLogical<Self> + ?Sized> {
fn to_physical(self) -> P;
}
trait IntoScaled<T: Scaled>: Sized {
fn into_scaled(self, scale: f64) -> T;
}
trait FromWithScale<T>: Sized {
fn from_with_scale(value: T, scale: f64) -> Self;
}
impl<T, U: Scaled> IntoScaled<U> for T
where
U: FromWithScale<T>,
{
fn into_scaled(self, scale: f64) -> U {
U::from_with_scale(self, scale)
}
}
trait AsPoint {
fn as_point(&self) -> Point;
}
trait Scaled {
fn scale(&self) -> f64;
}
pub trait Position {
fn x(&self) -> f64;
fn y(&self) -> f64;
}
#[derive(Debug, PartialEq, Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type)]
struct Point {
x: f64,
y: f64,
}
impl Point {
fn convert_to_logical(&self, scale: f64) -> LogicalPoint {
Point { x: self.x(), y: self.y() }.into_scaled(scale)
}
fn convert_to_physical(&self, scale: f64) -> PhysicalPoint {
Point {
x: self.x() / scale,
y: self.y() / scale,
}
.into_scaled(scale)
}
}
impl Position for Point {
fn x(&self) -> f64 {
self.x
}
fn y(&self) -> f64 {
self.y
}
}
#[derive(Debug, PartialEq, Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct LogicalPoint {
inner: Point,
scale: f64,
}
impl AsPoint for LogicalPoint {
fn as_point(&self) -> Point {
self.inner
}
}
impl Scaled for LogicalPoint {
fn scale(&self) -> f64 {
self.scale
}
}
impl Position for LogicalPoint {
fn x(&self) -> f64 {
self.inner.x()
}
fn y(&self) -> f64 {
self.inner.y()
}
}
impl ToPhysical<PhysicalPoint> for LogicalPoint {
fn to_physical(self) -> PhysicalPoint {
PhysicalPoint { inner: self.inner, scale: self.scale }
}
}
impl FromWithScale<Point> for LogicalPoint {
fn from_with_scale(value: Point, scale: f64) -> Self {
Self { inner: value, scale }
}
}
#[derive(Debug, PartialEq, Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct PhysicalPoint {
inner: Point,
scale: f64,
}
impl AsPoint for PhysicalPoint {
fn as_point(&self) -> Point {
self.inner
}
}
impl Scaled for PhysicalPoint {
fn scale(&self) -> f64 {
self.scale
}
}
impl Position for PhysicalPoint {
fn x(&self) -> f64 {
self.inner.x() * self.scale
}
fn y(&self) -> f64 {
self.inner.y() * self.scale
}
}
impl ToLogical<LogicalPoint> for PhysicalPoint {
fn to_logical(self) -> LogicalPoint {
LogicalPoint { inner: self.inner, scale: self.scale }
}
}
impl FromWithScale<Point> for PhysicalPoint {
fn from_with_scale(value: Point, scale: f64) -> Self {
Self { inner: value, scale }
}
}
pub trait Rect<P: Position>: Position {
fn offset(&self) -> P;
fn size(&self) -> P;
fn width(&self) -> f64;
fn height(&self) -> f64;
}
#[derive(Debug, PartialEq, Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type, ExtractField)]
struct Bounds {
offset: Point,
size: Point,
}
impl Position for Bounds {
fn x(&self) -> f64 {
self.offset.x()
}
fn y(&self) -> f64 {
self.offset.y()
}
}
impl Rect<Point> for Bounds {
fn offset(&self) -> Point {
self.offset
}
fn size(&self) -> Point {
self.size
}
fn width(&self) -> f64 {
self.size.x()
}
fn height(&self) -> f64 {
self.size.y()
}
}
#[derive(Debug, PartialEq, Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct LogicalBounds {
offset: Point,
size: Point,
scale: f64,
}
impl Scaled for LogicalBounds {
fn scale(&self) -> f64 {
self.scale
}
}
impl Position for LogicalBounds {
fn x(&self) -> f64 {
self.offset.x()
}
fn y(&self) -> f64 {
self.offset.y()
}
}
impl Rect<LogicalPoint> for LogicalBounds {
fn offset(&self) -> LogicalPoint {
self.offset.into_scaled(self.scale)
}
fn size(&self) -> LogicalPoint {
self.size.into_scaled(self.scale)
}
fn width(&self) -> f64 {
self.size.x()
}
fn height(&self) -> f64 {
self.size.y()
}
}
impl ToPhysical<PhysicalBounds> for LogicalBounds {
fn to_physical(self) -> PhysicalBounds {
PhysicalBounds {
offset: self.offset,
size: self.size,
scale: self.scale,
}
}
}
impl FromWithScale<Bounds> for LogicalBounds {
fn from_with_scale(value: Bounds, scale: f64) -> Self {
Self {
offset: value.offset(),
size: value.size(),
scale,
}
}
}
#[derive(Debug, PartialEq, Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct PhysicalBounds {
offset: Point,
size: Point,
scale: f64,
}
impl Scaled for PhysicalBounds {
fn scale(&self) -> f64 {
self.scale
}
}
impl Position for PhysicalBounds {
fn x(&self) -> f64 {
self.offset.x() * self.scale
}
fn y(&self) -> f64 {
self.offset.y() * self.scale
}
}
impl Rect<PhysicalPoint> for PhysicalBounds {
fn offset(&self) -> PhysicalPoint {
self.offset.into_scaled(self.scale)
}
fn size(&self) -> PhysicalPoint {
self.size.into_scaled(self.scale)
}
fn width(&self) -> f64 {
self.size.x() * self.scale
}
fn height(&self) -> f64 {
self.size.y() * self.scale
}
}
impl ToLogical<LogicalBounds> for PhysicalBounds {
fn to_logical(self) -> LogicalBounds {
LogicalBounds {
offset: self.offset,
size: self.size,
scale: self.scale,
}
}
}
impl FromWithScale<Bounds> for PhysicalBounds {
fn from_with_scale(value: Bounds, scale: f64) -> Self {
Self {
offset: value.offset(),
size: value.size(),
scale,
}
}
}
impl Mul<f64> for Point {
type Output = Point;
fn mul(self, rhs: f64) -> Self::Output {
assert_ne!(rhs, 0.0, "Cannot multiply point by zero");
Point { x: self.x * rhs, y: self.y * rhs }
}
}
impl Div<f64> for Point {
type Output = Point;
fn div(self, rhs: f64) -> Self::Output {
assert_ne!(rhs, 0.0, "Cannot divide point by zero");
Point { x: self.x / rhs, y: self.y / rhs }
}
}
impl Add<f64> for Point {
type Output = Point;
fn add(self, rhs: f64) -> Self::Output {
Point { x: self.x + rhs, y: self.y + rhs }
}
}
impl Sub<f64> for Point {
type Output = Point;
fn sub(self, rhs: f64) -> Self::Output {
Point { x: self.x - rhs, y: self.y - rhs }
}
}
impl Mul<Point> for Point {
type Output = Point;
fn mul(self, rhs: Point) -> Self::Output {
assert_ne!(rhs.x, 0.0, "Cannot multiply point by zero");
assert_ne!(rhs.y, 0.0, "Cannot multiply point by zero");
Point { x: self.x * rhs.x, y: self.y * rhs.y }
}
}
impl Div<Point> for Point {
type Output = Point;
fn div(self, rhs: Point) -> Self::Output {
assert_ne!(rhs.x, 0.0, "Cannot multiply point by zero");
assert_ne!(rhs.y, 0.0, "Cannot multiply point by zero");
Point { x: self.x / rhs.x, y: self.y / rhs.y }
}
}
impl Add<Point> for Point {
type Output = Point;
fn add(self, rhs: Point) -> Self::Output {
Point { x: self.x + rhs.x, y: self.y + rhs.y }
}
}
impl Sub<Point> for Point {
type Output = Point;
fn sub(self, rhs: Point) -> Self::Output {
Point { x: self.x - rhs.x, y: self.y - rhs.y }
}
}
impl Mul<f64> for Bounds {
type Output = Bounds;
fn mul(self, rhs: f64) -> Self::Output {
assert_ne!(rhs, 0.0, "Cannot multiply bounds by zero");
Bounds {
offset: self.offset * rhs,
size: self.size * rhs,
}
}
}
impl Div<f64> for Bounds {
type Output = Bounds;
fn div(self, rhs: f64) -> Self::Output {
assert_ne!(rhs, 0.0, "Cannot divide bounds by zero");
Bounds {
offset: self.offset / rhs,
size: self.size / rhs,
}
}
}
impl Mul<LogicalPoint> for LogicalPoint {
type Output = LogicalPoint;
fn mul(self, rhs: LogicalPoint) -> Self::Output {
assert_scale(&self, &rhs);
(self.as_point() * rhs.as_point()).into_scaled(self.scale())
}
}
impl Div<LogicalPoint> for LogicalPoint {
type Output = LogicalPoint;
fn div(self, rhs: LogicalPoint) -> Self::Output {
assert_scale(&self, &rhs);
(self.as_point() / rhs.as_point()).into_scaled(self.scale())
}
}
impl Add<LogicalPoint> for LogicalPoint {
type Output = LogicalPoint;
fn add(self, rhs: LogicalPoint) -> Self::Output {
assert_scale(&self, &rhs);
(self.as_point() + rhs.as_point()).into_scaled(self.scale())
}
}
impl Sub<LogicalPoint> for LogicalPoint {
type Output = LogicalPoint;
fn sub(self, rhs: LogicalPoint) -> Self::Output {
assert_scale(&self, &rhs);
(self.as_point() - rhs.as_point()).into_scaled(self.scale())
}
}
impl Mul<PhysicalPoint> for PhysicalPoint {
type Output = PhysicalPoint;
fn mul(self, rhs: PhysicalPoint) -> Self::Output {
assert_scale(&self, &rhs);
(self.as_point() * rhs.as_point()).into_scaled(self.scale())
}
}
impl Div<PhysicalPoint> for PhysicalPoint {
type Output = PhysicalPoint;
fn div(self, rhs: PhysicalPoint) -> Self::Output {
assert_scale(&self, &rhs);
(self.as_point() / rhs.as_point()).into_scaled(self.scale())
}
}
impl Add<PhysicalPoint> for PhysicalPoint {
type Output = PhysicalPoint;
fn add(self, rhs: PhysicalPoint) -> Self::Output {
assert_scale(&self, &rhs);
(self.as_point() + rhs.as_point()).into_scaled(self.scale())
}
}
impl Sub<PhysicalPoint> for PhysicalPoint {
type Output = PhysicalPoint;
fn sub(self, rhs: PhysicalPoint) -> Self::Output {
assert_scale(&self, &rhs);
(self.as_point() - rhs.as_point()).into_scaled(self.scale())
}
}
fn assert_scale<T: Scaled>(a: &T, b: &T) {
assert_eq!(a.scale(), b.scale(), "Cannot multiply with diffent scale");
}
impl From<(f64, f64)> for Point {
fn from((x, y): (f64, f64)) -> Self {
Self { x, y }
}
}
impl From<(f64, f64, f64, f64)> for Bounds {
fn from((x, y, width, height): (f64, f64, f64, f64)) -> Self {
Self {
offset: Point { x, y },
size: Point { x: width, y: height },
}
}
}
impl From<LogicalPoint> for (f64, f64) {
fn from(point: LogicalPoint) -> Self {
(point.x(), point.y())
}
}
impl From<PhysicalPoint> for (f64, f64) {
fn from(point: PhysicalPoint) -> Self {
(point.x(), point.y())
}
}
impl From<LogicalBounds> for (f64, f64, f64, f64) {
fn from(bounds: LogicalBounds) -> Self {
(bounds.x(), bounds.y(), bounds.width(), bounds.height())
}
}
impl From<PhysicalBounds> for (f64, f64, f64, f64) {
fn from(bounds: PhysicalBounds) -> Self {
(bounds.x(), bounds.y(), bounds.width(), bounds.height())
}
}
impl From<glam::DVec2> for Point {
fn from(vec: glam::DVec2) -> Self {
Self { x: vec.x, y: vec.y }
}
}
impl From<LogicalPoint> for glam::DVec2 {
fn from(val: LogicalPoint) -> Self {
glam::DVec2::new(val.x(), val.y())
}
}
impl From<PhysicalPoint> for glam::DVec2 {
fn from(val: PhysicalPoint) -> Self {
glam::DVec2::new(val.x(), val.y())
}
}
impl From<[glam::DVec2; 2]> for Bounds {
fn from(bounds: [glam::DVec2; 2]) -> Self {
Self {
offset: bounds[0].into(),
size: Point {
x: bounds[1].x - bounds[0].x,
y: bounds[1].y - bounds[0].y,
},
}
}
}
impl From<LogicalBounds> for [glam::DVec2; 2] {
fn from(bounds: LogicalBounds) -> Self {
[glam::DVec2::new(bounds.x(), bounds.y()), glam::DVec2::new(bounds.x() + bounds.width(), bounds.y() + bounds.height())]
}
}
impl From<PhysicalBounds> for [glam::DVec2; 2] {
fn from(bounds: PhysicalBounds) -> Self {
[glam::DVec2::new(bounds.x(), bounds.y()), glam::DVec2::new(bounds.x() + bounds.width(), bounds.y() + bounds.height())]
}
}
impl LogicalPoint {
pub fn into_dvec2(self) -> DVec2 {
DVec2::new(self.x(), self.y())
}
}
impl PhysicalPoint {
pub fn into_dvec2(self) -> DVec2 {
DVec2::new(self.x(), self.y())
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/viewport/viewport_message.rs | editor/src/messages/viewport/viewport_message.rs | use crate::messages::prelude::*;
#[impl_message(Message, Viewport)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ViewportMessage {
Update { x: f64, y: f64, width: f64, height: f64, scale: f64 },
RepropagateUpdate,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/app_window/app_window_message_handler.rs | editor/src/messages/app_window/app_window_message_handler.rs | use crate::messages::app_window::AppWindowMessage;
use crate::messages::prelude::*;
use graphite_proc_macros::{ExtractField, message_handler_data};
#[derive(Debug, Clone, Default, ExtractField)]
pub struct AppWindowMessageHandler {
platform: AppWindowPlatform,
}
#[message_handler_data]
impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
fn process_message(&mut self, message: AppWindowMessage, responses: &mut std::collections::VecDeque<Message>, _: ()) {
match message {
AppWindowMessage::UpdatePlatform { platform } => {
self.platform = platform;
responses.add(FrontendMessage::UpdatePlatform { platform: self.platform });
}
AppWindowMessage::Close => {
responses.add(FrontendMessage::WindowClose);
}
AppWindowMessage::Minimize => {
responses.add(FrontendMessage::WindowMinimize);
}
AppWindowMessage::Maximize => {
responses.add(FrontendMessage::WindowMaximize);
}
AppWindowMessage::Drag => {
responses.add(FrontendMessage::WindowDrag);
}
AppWindowMessage::Hide => {
responses.add(FrontendMessage::WindowHide);
}
AppWindowMessage::HideOthers => {
responses.add(FrontendMessage::WindowHideOthers);
}
AppWindowMessage::ShowAll => {
responses.add(FrontendMessage::WindowShowAll);
}
}
}
advertise_actions!(AppWindowMessageDiscriminant;
Close,
Minimize,
Maximize,
Drag,
Hide,
HideOthers,
);
}
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum AppWindowPlatform {
#[default]
Web,
Windows,
Mac,
Linux,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/app_window/app_window_message.rs | editor/src/messages/app_window/app_window_message.rs | use crate::messages::prelude::*;
use super::app_window_message_handler::AppWindowPlatform;
#[impl_message(Message, AppWindow)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum AppWindowMessage {
UpdatePlatform { platform: AppWindowPlatform },
Close,
Minimize,
Maximize,
Drag,
Hide,
HideOthers,
ShowAll,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/app_window/mod.rs | editor/src/messages/app_window/mod.rs | mod app_window_message;
pub mod app_window_message_handler;
#[doc(inline)]
pub use app_window_message::{AppWindowMessage, AppWindowMessageDiscriminant};
#[doc(inline)]
pub use app_window_message_handler::AppWindowMessageHandler;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/preferences/utility_types.rs | editor/src/messages/preferences/utility_types.rs | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type, Hash)]
pub enum SelectionMode {
#[default]
Touched = 0,
Enclosed = 1,
Directional = 2,
}
impl std::fmt::Display for SelectionMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SelectionMode::Touched => write!(f, "Touched"),
SelectionMode::Enclosed => write!(f, "Enclosed"),
SelectionMode::Directional => write!(f, "Directional"),
}
}
}
impl SelectionMode {
pub fn tooltip_description(&self) -> &'static str {
match self {
SelectionMode::Touched => "Select all layers at least partially covered by the dragged selection area.",
SelectionMode::Enclosed => "Select only layers fully enclosed by the dragged selection area.",
SelectionMode::Directional => r#""Touched" for leftward drags, "Enclosed" for rightward drags."#,
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/preferences/preferences_message_handler.rs | editor/src/messages/preferences/preferences_message_handler.rs | use crate::consts::{UI_SCALE_DEFAULT, VIEWPORT_ZOOM_WHEEL_RATE};
use crate::messages::input_mapper::key_mapping::MappingVariant;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use crate::messages::tool::utility_types::ToolType;
use graph_craft::wasm_application_io::EditorPreferences;
#[derive(ExtractField)]
pub struct PreferencesMessageContext<'a> {
pub tool_message_handler: &'a ToolMessageHandler,
}
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, specta::Type, ExtractField)]
#[serde(default)]
pub struct PreferencesMessageHandler {
pub selection_mode: SelectionMode,
pub zoom_with_scroll: bool,
pub use_vello: bool,
pub brush_tool: bool,
pub graph_wire_style: GraphWireStyle,
pub viewport_zoom_wheel_rate: f64,
pub ui_scale: f64,
}
impl PreferencesMessageHandler {
pub fn get_selection_mode(&self) -> SelectionMode {
self.selection_mode
}
pub fn editor_preferences(&self) -> EditorPreferences {
EditorPreferences {
use_vello: self.use_vello && self.supports_wgpu(),
}
}
pub fn supports_wgpu(&self) -> bool {
graph_craft::wasm_application_io::wgpu_available().unwrap_or_default()
}
}
impl Default for PreferencesMessageHandler {
fn default() -> Self {
Self {
selection_mode: SelectionMode::Touched,
zoom_with_scroll: matches!(MappingVariant::default(), MappingVariant::ZoomWithScroll),
use_vello: EditorPreferences::default().use_vello,
brush_tool: false,
graph_wire_style: GraphWireStyle::default(),
viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE,
ui_scale: UI_SCALE_DEFAULT,
}
}
}
#[message_handler_data]
impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for PreferencesMessageHandler {
fn process_message(&mut self, message: PreferencesMessage, responses: &mut VecDeque<Message>, context: PreferencesMessageContext) {
let PreferencesMessageContext { tool_message_handler } = context;
match message {
// Management messages
PreferencesMessage::Load { preferences } => {
if let Some(preferences) = preferences {
*self = preferences;
}
responses.add(PortfolioMessage::EditorPreferences);
responses.add(PortfolioMessage::UpdateVelloPreference);
responses.add(PreferencesMessage::ModifyLayout {
zoom_with_scroll: self.zoom_with_scroll,
});
responses.add(FrontendMessage::UpdateUIScale { scale: self.ui_scale });
}
PreferencesMessage::ResetToDefaults => {
refresh_dialog(responses);
responses.add(KeyMappingMessage::ModifyMapping { mapping: MappingVariant::Default });
*self = Self::default()
}
// Per-preference messages
PreferencesMessage::UseVello { use_vello } => {
self.use_vello = use_vello;
responses.add(PortfolioMessage::UpdateVelloPreference);
responses.add(PortfolioMessage::EditorPreferences);
}
PreferencesMessage::BrushTool { enabled } => {
self.brush_tool = enabled;
if !enabled && tool_message_handler.tool_state.tool_data.active_tool_type == ToolType::Brush {
responses.add(ToolMessage::ActivateToolSelect);
}
responses.add(ToolMessage::RefreshToolShelf);
}
PreferencesMessage::ModifyLayout { zoom_with_scroll } => {
self.zoom_with_scroll = zoom_with_scroll;
let variant = if zoom_with_scroll { MappingVariant::ZoomWithScroll } else { MappingVariant::Default };
responses.add(KeyMappingMessage::ModifyMapping { mapping: variant });
}
PreferencesMessage::SelectionMode { selection_mode } => {
self.selection_mode = selection_mode;
}
PreferencesMessage::GraphWireStyle { style } => {
self.graph_wire_style = style;
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
}
PreferencesMessage::ViewportZoomWheelRate { rate } => {
self.viewport_zoom_wheel_rate = rate;
}
PreferencesMessage::UIScale { scale } => {
self.ui_scale = scale;
responses.add(FrontendMessage::UpdateUIScale { scale: self.ui_scale });
}
}
responses.add(FrontendMessage::TriggerSavePreferences { preferences: self.clone() });
}
advertise_actions!(PreferencesMessageDiscriminant;
);
}
fn refresh_dialog(responses: &mut VecDeque<Message>) {
responses.add(DialogMessage::CloseDialogAndThen {
followups: vec![DialogMessage::RequestPreferencesDialog.into()],
});
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/preferences/mod.rs | editor/src/messages/preferences/mod.rs | mod preferences_message;
pub mod preferences_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use preferences_message::{PreferencesMessage, PreferencesMessageDiscriminant};
#[doc(inline)]
pub use preferences_message_handler::PreferencesMessageHandler;
#[doc(inline)]
pub use utility_types::SelectionMode;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/preferences/preferences_message.rs | editor/src/messages/preferences/preferences_message.rs | use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
#[impl_message(Message, Preferences)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum PreferencesMessage {
// Management messages
Load { preferences: Option<PreferencesMessageHandler> },
ResetToDefaults,
// Per-preference messages
UseVello { use_vello: bool },
SelectionMode { selection_mode: SelectionMode },
BrushTool { enabled: bool },
ModifyLayout { zoom_with_scroll: bool },
GraphWireStyle { style: GraphWireStyle },
ViewportZoomWheelRate { rate: f64 },
UIScale { scale: f64 },
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/frontend/frontend_message.rs | editor/src/messages/frontend/frontend_message.rs | use super::utility_types::{DocumentDetails, MouseCursorIcon, OpenDocument};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic, Transform,
};
use crate::messages::portfolio::document::utility_types::nodes::{JsRawBuffer, LayerPanelEntry, RawBuffer};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
use crate::messages::prelude::*;
use glam::IVec2;
use graph_craft::document::NodeId;
use graphene_std::raster::Image;
use graphene_std::raster::color::Color;
use graphene_std::text::{Font, TextAlign};
use std::path::PathBuf;
#[cfg(not(target_family = "wasm"))]
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
#[impl_message(Message, Frontend)]
#[derive(derivative::Derivative, Clone, serde::Serialize, serde::Deserialize, specta::Type)]
#[derivative(Debug, PartialEq)]
pub enum FrontendMessage {
// Display prefix: make the frontend show something, like a dialog
DisplayDialog {
title: String,
icon: String,
},
DisplayDialogDismiss,
DisplayDialogPanic {
#[serde(rename = "panicInfo")]
panic_info: String,
},
DisplayEditableTextbox {
text: String,
#[serde(rename = "lineHeightRatio")]
line_height_ratio: f64,
#[serde(rename = "fontSize")]
font_size: f64,
color: Color,
#[serde(rename = "fontData")]
font_data: Vec<u8>,
transform: [f64; 6],
#[serde(rename = "maxWidth")]
max_width: Option<f64>,
#[serde(rename = "maxHeight")]
max_height: Option<f64>,
align: TextAlign,
},
DisplayEditableTextboxUpdateFontData {
#[serde(rename = "fontData")]
font_data: Vec<u8>,
},
DisplayEditableTextboxTransform {
transform: [f64; 6],
},
DisplayRemoveEditableTextbox,
// Send prefix: Send global, static data to the frontend that is never updated
SendUIMetadata {
#[serde(rename = "nodeDescriptions")]
node_descriptions: Vec<(String, String)>,
#[serde(rename = "nodeTypes")]
node_types: Vec<FrontendNodeType>,
},
SendShortcutF11 {
shortcut: Option<ActionShortcut>,
},
SendShortcutAltClick {
shortcut: Option<ActionShortcut>,
},
SendShortcutShiftClick {
shortcut: Option<ActionShortcut>,
},
// Trigger prefix: cause a frontend specific API to do something
TriggerAboutGraphiteLocalizedCommitDate {
#[serde(rename = "commitDate")]
commit_date: String,
},
TriggerDisplayThirdPartyLicensesDialog,
TriggerSaveDocument {
document_id: DocumentId,
name: String,
path: Option<PathBuf>,
content: Vec<u8>,
},
TriggerSaveFile {
name: String,
content: Vec<u8>,
},
TriggerExportImage {
svg: String,
name: String,
mime: String,
size: (f64, f64),
},
TriggerFetchAndOpenDocument {
name: String,
filename: String,
},
TriggerFontCatalogLoad,
TriggerFontDataLoad {
font: Font,
url: String,
},
TriggerImport,
TriggerPersistenceRemoveDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerPersistenceWriteDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
document: String,
details: DocumentDetails,
},
TriggerLoadFirstAutoSaveDocument,
TriggerLoadRestAutoSaveDocuments,
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerOpenDocument,
TriggerSavePreferences {
preferences: PreferencesMessageHandler,
},
TriggerSaveActiveDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
TriggerTextCommit,
TriggerVisitLink {
url: String,
},
TriggerClipboardRead,
TriggerClipboardWrite {
content: String,
},
TriggerSelectionRead {
cut: bool,
},
TriggerSelectionWrite {
content: String,
},
// Update prefix: give the frontend a new value or state for it to use
UpdateActiveDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
},
UpdateImportsExports {
/// If the primary import is not visible, then it is None.
imports: Vec<Option<FrontendGraphOutput>>,
/// If the primary export is not visible, then it is None.
exports: Vec<Option<FrontendGraphInput>>,
/// The primary import location.
#[serde(rename = "importPosition")]
import_position: IVec2,
/// The primary export location.
#[serde(rename = "exportPosition")]
export_position: IVec2,
/// The document network does not have an add import or export button.
#[serde(rename = "addImportExport")]
add_import_export: bool,
},
UpdateInSelectedNetwork {
#[serde(rename = "inSelectedNetwork")]
in_selected_network: bool,
},
UpdateBox {
#[serde(rename = "box")]
box_selection: Option<BoxSelection>,
},
UpdateContextMenuInformation {
#[serde(rename = "contextMenuInformation")]
context_menu_information: Option<ContextMenuInformation>,
},
UpdateClickTargets {
#[serde(rename = "clickTargets")]
click_targets: Option<FrontendClickTargets>,
},
UpdateGraphViewOverlay {
open: bool,
},
UpdateDataPanelState {
open: bool,
},
UpdatePropertiesPanelState {
open: bool,
},
UpdateLayersPanelState {
open: bool,
},
UpdateDataPanelLayout {
diff: Vec<WidgetDiff>,
},
UpdateImportReorderIndex {
#[serde(rename = "importIndex")]
index: Option<usize>,
},
UpdateExportReorderIndex {
#[serde(rename = "exportIndex")]
index: Option<usize>,
},
UpdateLayerWidths {
#[serde(rename = "layerWidths")]
layer_widths: HashMap<NodeId, u32>,
#[serde(rename = "chainWidths")]
chain_widths: HashMap<NodeId, u32>,
#[serde(rename = "hasLeftInputWire")]
has_left_input_wire: HashMap<NodeId, bool>,
},
UpdateDialogButtons {
diff: Vec<WidgetDiff>,
},
UpdateDialogColumn1 {
diff: Vec<WidgetDiff>,
},
UpdateDialogColumn2 {
diff: Vec<WidgetDiff>,
},
UpdateDocumentArtwork {
svg: String,
},
UpdateImageData {
image_data: Vec<(u64, Image<Color>)>,
},
UpdateDocumentBarLayout {
diff: Vec<WidgetDiff>,
},
UpdateDocumentLayerDetails {
data: LayerPanelEntry,
},
UpdateDocumentLayerStructure {
#[serde(rename = "dataBuffer")]
data_buffer: RawBuffer,
},
UpdateDocumentLayerStructureJs {
#[serde(rename = "dataBuffer")]
data_buffer: JsRawBuffer,
},
UpdateDocumentRulers {
origin: (f64, f64),
spacing: f64,
interval: f64,
visible: bool,
},
UpdateDocumentScrollbars {
position: (f64, f64),
size: (f64, f64),
multiplier: (f64, f64),
},
UpdateEyedropperSamplingState {
#[serde(rename = "mousePosition")]
mouse_position: Option<(f64, f64)>,
#[serde(rename = "primaryColor")]
primary_color: String,
#[serde(rename = "secondaryColor")]
secondary_color: String,
#[serde(rename = "setColorChoice")]
set_color_choice: Option<String>,
},
UpdateGraphFadeArtwork {
percentage: f64,
},
UpdateLayersPanelControlBarLeftLayout {
diff: Vec<WidgetDiff>,
},
UpdateLayersPanelControlBarRightLayout {
diff: Vec<WidgetDiff>,
},
UpdateLayersPanelBottomBarLayout {
diff: Vec<WidgetDiff>,
},
UpdateMenuBarLayout {
diff: Vec<WidgetDiff>,
},
UpdateMouseCursor {
cursor: MouseCursorIcon,
},
UpdateNodeGraphNodes {
nodes: Vec<FrontendNode>,
},
UpdateNodeGraphErrorDiagnostic {
error: Option<NodeGraphErrorDiagnostic>,
},
UpdateVisibleNodes {
nodes: Vec<NodeId>,
},
UpdateNodeGraphWires {
wires: Vec<WirePathUpdate>,
},
ClearAllNodeGraphWires,
UpdateNodeGraphControlBarLayout {
diff: Vec<WidgetDiff>,
},
UpdateNodeGraphSelection {
selected: Vec<NodeId>,
},
UpdateNodeGraphTransform {
transform: Transform,
},
UpdateNodeThumbnail {
id: NodeId,
value: String,
},
UpdateOpenDocumentsList {
#[serde(rename = "openDocuments")]
open_documents: Vec<OpenDocument>,
},
UpdatePropertiesPanelLayout {
diff: Vec<WidgetDiff>,
},
UpdateToolOptionsLayout {
diff: Vec<WidgetDiff>,
},
UpdateToolShelfLayout {
diff: Vec<WidgetDiff>,
},
UpdateWirePathInProgress {
#[serde(rename = "wirePath")]
wire_path: Option<WirePath>,
},
UpdateWelcomeScreenButtonsLayout {
diff: Vec<WidgetDiff>,
},
UpdateStatusBarHintsLayout {
diff: Vec<WidgetDiff>,
},
UpdateStatusBarInfoLayout {
diff: Vec<WidgetDiff>,
},
UpdateWorkingColorsLayout {
diff: Vec<WidgetDiff>,
},
UpdatePlatform {
platform: AppWindowPlatform,
},
UpdateMaximized {
maximized: bool,
},
UpdateFullscreen {
fullscreen: bool,
},
UpdateViewportHolePunch {
active: bool,
},
UpdateViewportPhysicalBounds {
x: f64,
y: f64,
width: f64,
height: f64,
},
UpdateUIScale {
scale: f64,
},
#[cfg(not(target_family = "wasm"))]
RenderOverlays {
#[serde(skip, default = "OverlayContext::default")]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
context: OverlayContext,
},
// Window prefix: cause the application window to do something
WindowClose,
WindowMinimize,
WindowMaximize,
WindowDrag,
WindowHide,
WindowHideOthers,
WindowShowAll,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/frontend/utility_types.rs | editor/src/messages/frontend/utility_types.rs | use std::path::PathBuf;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::*;
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct OpenDocument {
pub id: DocumentId,
pub details: DocumentDetails,
}
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct DocumentDetails {
pub name: String,
pub path: Option<PathBuf>,
#[serde(rename = "isSaved")]
pub is_saved: bool,
#[serde(rename = "isAutoSaved")]
pub is_auto_saved: bool,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum MouseCursorIcon {
#[default]
Default,
None,
ZoomIn,
ZoomOut,
Grabbing,
Crosshair,
Text,
Move,
NSResize,
EWResize,
NESWResize,
NWSEResize,
Rotate,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum FileType {
#[default]
Png,
Jpg,
Svg,
}
impl FileType {
pub fn to_mime(self) -> &'static str {
match self {
FileType::Png => "image/png",
FileType::Jpg => "image/jpeg",
FileType::Svg => "image/svg+xml",
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum ExportBounds {
#[default]
AllArtwork,
Selection,
Artboard(LayerNodeIdentifier),
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/frontend/mod.rs | editor/src/messages/frontend/mod.rs | mod frontend_message;
pub mod utility_types;
#[doc(inline)]
pub use frontend_message::{FrontendMessage, FrontendMessageDiscriminant};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/utility_types.rs | editor/src/messages/portfolio/utility_types.rs | use graphene_std::text::{Font, FontCache};
#[derive(Debug, Default)]
pub struct PersistentData {
pub font_cache: FontCache,
pub font_catalog: FontCatalog,
pub use_vello: bool,
}
// TODO: Should this be a BTreeMap instead?
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalog(pub Vec<FontCatalogFamily>);
impl FontCatalog {
pub fn find_font_style_in_catalog(&self, font: &Font) -> Option<FontCatalogStyle> {
let family = self.0.iter().find(|family| family.name == font.font_family);
let found_style = family.map(|family| {
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
family.closest_style(weight, italic).clone()
});
if found_style.is_none() {
log::warn!("Font not found in catalog: {:?}", font);
}
found_style
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogFamily {
/// The font family name.
pub name: String,
/// The font styles (variants) available for the font family.
pub styles: Vec<FontCatalogStyle>,
}
impl FontCatalogFamily {
/// Finds the closest style to the given weight and italic setting.
/// Aims to find the nearest weight while maintaining the italic setting if possible, but italic may change if no other option is available.
pub fn closest_style(&self, weight: u32, italic: bool) -> &FontCatalogStyle {
self.styles
.iter()
.map(|style| ((style.weight as i32 - weight as i32).unsigned_abs() + 10000 * (style.italic != italic) as u32, style))
.min_by_key(|(distance, _)| *distance)
.map(|(_, style)| style)
.unwrap_or(&self.styles[0])
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogStyle {
pub weight: u32,
pub italic: bool,
pub url: String,
}
impl FontCatalogStyle {
pub fn to_named_style(&self) -> String {
let weight = self.weight;
let italic = self.italic;
let named_weight = Font::named_weight(weight);
let maybe_italic = if italic { " Italic" } else { "" };
format!("{named_weight}{maybe_italic} ({weight})")
}
pub fn from_named_style(named_style: &str, url: impl Into<String>) -> FontCatalogStyle {
let weight = named_style.split_terminator(['(', ')']).next_back().and_then(|x| x.parse::<u32>().ok()).unwrap_or(400);
let italic = named_style.contains("Italic (");
FontCatalogStyle { weight, italic, url: url.into() }
}
/// Get the URL for the stylesheet for loading a font preview for this style of the given family name, subsetted to only the letters in the family name.
pub fn preview_url(&self, family: impl Into<String>) -> String {
let name = family.into().replace(' ', "+");
let italic = if self.italic { "ital," } else { "" };
let weight = self.weight;
format!("https://fonts.googleapis.com/css2?display=swap&family={name}:{italic}wght@{weight}&text={name}")
}
}
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
pub enum Platform {
#[default]
Unknown,
Windows,
Mac,
Linux,
}
impl Platform {
pub fn as_keyboard_platform_layout(&self) -> KeyboardPlatformLayout {
match self {
Platform::Mac => KeyboardPlatformLayout::Mac,
Platform::Windows | Platform::Linux => KeyboardPlatformLayout::Standard,
Platform::Unknown => {
warn!("The platform has not been set, remember to send `GlobalsMessage::SetPlatform` during editor initialization.");
KeyboardPlatformLayout::Standard
}
}
}
}
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
pub enum KeyboardPlatformLayout {
/// Standard keyboard mapping used by Windows and Linux
#[default]
Standard,
/// Keyboard mapping used by Macs where Command is sometimes used in favor of Control
Mac,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub enum PanelType {
#[default]
Document,
Welcome,
Layers,
Properties,
DataPanel,
}
impl From<String> for PanelType {
fn from(value: String) -> Self {
match value.as_str() {
"Document" => PanelType::Document,
"Welcome" => PanelType::Welcome,
"Layers" => PanelType::Layers,
"Properties" => PanelType::Properties,
"Data" => PanelType::DataPanel,
_ => panic!("Unknown panel type: {value}"),
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/portfolio_message.rs | editor/src/messages/portfolio/portfolio_message.rs | use super::document::utility_types::document_metadata::LayerNodeIdentifier;
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::portfolio::utility_types::FontCatalog;
use crate::messages::prelude::*;
use graphene_std::Color;
use graphene_std::raster::Image;
use graphene_std::text::Font;
use std::path::PathBuf;
#[impl_message(Message, Portfolio)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum PortfolioMessage {
// Sub-messages
#[child]
Document(DocumentMessage),
// Messages
Init,
DocumentPassMessage {
document_id: DocumentId,
message: DocumentMessage,
},
AutoSaveActiveDocument,
AutoSaveAllDocuments,
AutoSaveDocument {
document_id: DocumentId,
},
CloseActiveDocumentWithConfirmation,
CloseAllDocuments,
CloseAllDocumentsWithConfirmation,
CloseDocument {
document_id: DocumentId,
},
CloseDocumentWithConfirmation {
document_id: DocumentId,
},
Copy {
clipboard: Clipboard,
},
Cut {
clipboard: Clipboard,
},
DeleteDocument {
document_id: DocumentId,
},
DestroyAllDocuments,
EditorPreferences,
FontCatalogLoaded {
catalog: FontCatalog,
},
LoadFontData {
font: Font,
},
FontLoaded {
font_family: String,
font_style: String,
data: Vec<u8>,
},
Import,
LoadDocumentResources {
document_id: DocumentId,
},
NewDocumentWithName {
name: String,
},
NextDocument,
OpenDocument,
OpenDocumentFile {
document_name: Option<String>,
document_path: Option<PathBuf>,
document_serialized_content: String,
},
OpenDocumentFileWithId {
document_id: DocumentId,
document_name: Option<String>,
document_path: Option<PathBuf>,
document_is_auto_saved: bool,
document_is_saved: bool,
document_serialized_content: String,
to_front: bool,
select_after_open: bool,
},
ToggleResetNodesToDefinitionsOnOpen,
PasteIntoFolder {
clipboard: Clipboard,
parent: LayerNodeIdentifier,
insert_index: usize,
},
PasteSerializedData {
data: String,
},
PasteSerializedVector {
data: String,
},
CenterPastedLayers {
layers: Vec<LayerNodeIdentifier>,
},
PasteImage {
name: Option<String>,
image: Image<Color>,
mouse: Option<(f64, f64)>,
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
},
PasteSvg {
name: Option<String>,
svg: String,
mouse: Option<(f64, f64)>,
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
},
PrevDocument,
RequestWelcomeScreenButtonsLayout,
RequestStatusBarInfoLayout,
SetActivePanel {
panel: PanelType,
},
SelectDocument {
document_id: DocumentId,
},
SubmitDocumentExport {
name: String,
file_type: FileType,
scale_factor: f64,
bounds: ExportBounds,
transparent_background: bool,
},
SubmitActiveGraphRender,
SubmitGraphRender {
document_id: DocumentId,
ignore_hash: bool,
},
ToggleDataPanelOpen,
TogglePropertiesPanelOpen,
ToggleLayersPanelOpen,
ToggleRulers,
UpdateDocumentWidgets,
UpdateOpenDocumentsList,
UpdateVelloPreference,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/mod.rs | editor/src/messages/portfolio/mod.rs | mod portfolio_message;
mod portfolio_message_handler;
pub mod document;
pub mod document_migration;
pub mod utility_types;
#[doc(inline)]
pub use portfolio_message::{PortfolioMessage, PortfolioMessageDiscriminant};
#[doc(inline)]
pub use portfolio_message_handler::{PortfolioMessageContext, PortfolioMessageHandler};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/portfolio_message_handler.rs | editor/src/messages/portfolio/portfolio_message_handler.rs | use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::document::utility_types::network_interface;
use super::utility_types::{PanelType, PersistentData};
use crate::application::generate_uuid;
use crate::consts::{DEFAULT_DOCUMENT_NAME, DEFAULT_STROKE_WIDTH, FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
use crate::messages::clipboard::utility_types::ClipboardContent;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentDetails, OpenDocument};
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::DocumentMessageContext;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions;
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::network_interface::OutputConnector;
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
use crate::messages::portfolio::document_migration::*;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::utility_types::{HintData, ToolType};
use crate::messages::viewport::ToPhysical;
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
use derivative::*;
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::renderer::Quad;
use graphene_std::subpath::BezierHandles;
use graphene_std::text::Font;
use graphene_std::vector::misc::HandleId;
use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType};
use std::vec;
#[derive(ExtractField)]
pub struct PortfolioMessageContext<'a> {
pub ipp: &'a InputPreprocessorMessageHandler,
pub preferences: &'a PreferencesMessageHandler,
pub animation: &'a AnimationMessageHandler,
pub current_tool: &'a ToolType,
pub reset_node_definitions_on_open: bool,
pub timing_information: TimingInformation,
pub viewport: &'a ViewportMessageHandler,
}
#[derive(Debug, Derivative, ExtractField)]
#[derivative(Default)]
pub struct PortfolioMessageHandler {
pub documents: HashMap<DocumentId, DocumentMessageHandler>,
document_ids: VecDeque<DocumentId>,
active_panel: PanelType,
pub(crate) active_document_id: Option<DocumentId>,
copy_buffer: [Vec<CopyBufferEntry>; INTERNAL_CLIPBOARD_COUNT as usize],
pub persistent_data: PersistentData,
pub executor: NodeGraphExecutor,
pub selection_mode: SelectionMode,
pub reset_node_definitions_on_open: bool,
pub data_panel_open: bool,
#[derivative(Default(value = "true"))]
pub layers_panel_open: bool,
#[derivative(Default(value = "true"))]
pub properties_panel_open: bool,
}
#[message_handler_data]
impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for PortfolioMessageHandler {
fn process_message(&mut self, message: PortfolioMessage, responses: &mut VecDeque<Message>, context: PortfolioMessageContext) {
let PortfolioMessageContext {
ipp,
preferences,
animation,
current_tool,
reset_node_definitions_on_open,
timing_information,
viewport,
} = context;
match message {
// Sub-messages
PortfolioMessage::Document(message) => {
if let Some(document_id) = self.active_document_id
&& let Some(document) = self.documents.get_mut(&document_id)
{
let document_inputs = DocumentMessageContext {
document_id,
ipp,
persistent_data: &self.persistent_data,
executor: &mut self.executor,
current_tool,
preferences,
viewport,
data_panel_open: self.data_panel_open,
layers_panel_open: self.layers_panel_open,
properties_panel_open: self.properties_panel_open,
};
document.process_message(message, responses, document_inputs)
}
}
// Messages
PortfolioMessage::Init => {
// Tell frontend to load persistent preferences
responses.add(FrontendMessage::TriggerLoadPreferences);
// Tell frontend to load the current document
responses.add(FrontendMessage::TriggerLoadFirstAutoSaveDocument);
// Display the menu bar at the top of the window
responses.add(MenuBarMessage::SendLayout);
// Send the information for tooltips and categories for each node/input.
responses.add(FrontendMessage::SendUIMetadata {
node_descriptions: document_node_definitions::collect_node_descriptions(),
node_types: document_node_definitions::collect_node_types(),
});
// Send shortcuts for widgets created in the frontend which need shortcut tooltips
responses.add(FrontendMessage::SendShortcutF11 {
shortcut: action_shortcut_manual!(Key::F11),
});
responses.add(FrontendMessage::SendShortcutAltClick {
shortcut: action_shortcut_manual!(Key::Alt, Key::MouseLeft),
});
responses.add(FrontendMessage::SendShortcutShiftClick {
shortcut: action_shortcut_manual!(Key::Shift, Key::MouseLeft),
});
// Before loading any documents, initially prepare the welcome screen buttons layout
responses.add(PortfolioMessage::RequestWelcomeScreenButtonsLayout);
// Request status bar info layout
responses.add(PortfolioMessage::RequestStatusBarInfoLayout);
// Tell frontend to finish loading persistent documents
responses.add(FrontendMessage::TriggerLoadRestAutoSaveDocuments);
responses.add(FrontendMessage::TriggerOpenLaunchDocuments);
}
PortfolioMessage::DocumentPassMessage { document_id, message } => {
if let Some(document) = self.documents.get_mut(&document_id) {
let document_inputs = DocumentMessageContext {
document_id,
ipp,
persistent_data: &self.persistent_data,
executor: &mut self.executor,
current_tool,
preferences,
viewport,
data_panel_open: self.data_panel_open,
layers_panel_open: self.layers_panel_open,
properties_panel_open: self.properties_panel_open,
};
document.process_message(message, responses, document_inputs)
}
}
PortfolioMessage::AutoSaveActiveDocument => {
if let Some(document_id) = self.active_document_id
&& let Some(document) = self.active_document_mut()
{
document.set_auto_save_state(true);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
}
PortfolioMessage::AutoSaveAllDocuments => {
for (document_id, document) in self.documents.iter_mut() {
if !document.is_auto_saved() {
document.set_auto_save_state(true);
responses.add(PortfolioMessage::AutoSaveDocument { document_id: *document_id });
}
}
}
PortfolioMessage::AutoSaveDocument { document_id } => {
let document = self.documents.get(&document_id).unwrap();
responses.add(FrontendMessage::TriggerPersistenceWriteDocument {
document_id,
document: document.serialize_document(),
details: DocumentDetails {
name: document.name.clone(),
path: document.path.clone(),
is_saved: document.is_saved(),
is_auto_saved: document.is_auto_saved(),
},
})
}
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::CloseDocumentWithConfirmation { document_id });
}
}
PortfolioMessage::CloseAllDocuments => {
if self.active_document_id.is_some() {
responses.add(EventMessage::ToolAbort);
responses.add(ToolMessage::DeactivateTools);
// Clear relevant UI layouts if there are no documents
responses.add(PropertiesPanelMessage::Clear);
responses.add(DocumentMessage::ClearLayersPanel);
responses.add(DataPanelMessage::ClearLayout);
HintData::clear_layout(responses);
}
for document_id in &self.document_ids {
responses.add(FrontendMessage::TriggerPersistenceRemoveDocument { document_id: *document_id });
}
responses.add(PortfolioMessage::DestroyAllDocuments);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
PortfolioMessage::CloseAllDocumentsWithConfirmation => {
if self.unsaved_document_names().is_empty() {
responses.add(PortfolioMessage::CloseAllDocuments)
} else {
responses.add(DialogMessage::CloseAllDocumentsWithConfirmation)
}
}
PortfolioMessage::CloseDocument { document_id } => {
// Is this the last document?
if self.documents.len() == 1 && self.document_ids[0] == document_id {
// Clear UI layouts that assume the existence of a document
responses.add(PropertiesPanelMessage::Clear);
responses.add(DocumentMessage::ClearLayersPanel);
responses.add(DataPanelMessage::ClearLayout);
HintData::clear_layout(responses);
}
// Actually delete the document (delay to delete document is required to let the document and properties panel messages above get processed)
responses.add(PortfolioMessage::DeleteDocument { document_id });
responses.add(FrontendMessage::TriggerPersistenceRemoveDocument { document_id });
// Send the new list of document tab names
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
PortfolioMessage::CloseDocumentWithConfirmation { document_id } => {
let target_document = self.documents.get(&document_id).unwrap();
if target_document.is_saved() {
responses.add(EventMessage::ToolAbort);
responses.add(PortfolioMessage::CloseDocument { document_id });
} else {
let dialog = simple_dialogs::CloseDocumentDialog {
document_name: target_document.name.clone(),
document_id,
};
dialog.send_dialog_to_frontend(responses);
// Select the document being closed
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
PortfolioMessage::Copy { clipboard } => {
if context.current_tool == &ToolType::Path {
responses.add(PathToolMessage::Copy { clipboard });
return;
}
// We can't use `self.active_document()` because it counts as an immutable borrow of the entirety of `self`
let Some(active_document) = self.active_document_id.and_then(|id| self.documents.get_mut(&id)) else {
return;
};
if active_document.graph_view_overlay_open() {
responses.add(NodeGraphMessage::Copy);
return;
}
let mut copy_val = |buffer: &mut Vec<CopyBufferEntry>| {
let mut ordered_last_elements = active_document.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
ordered_last_elements.sort_by_key(|layer| {
let Some(parent) = layer.parent(active_document.metadata()) else { return usize::MAX };
DocumentMessageHandler::get_calculated_insert_index(active_document.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
});
for layer in ordered_last_elements.into_iter() {
let layer_node_id = layer.to_node();
let mut copy_ids = HashMap::new();
copy_ids.insert(layer_node_id, NodeId(0));
active_document
.network_interface
.upstream_flow_back_from_nodes(vec![layer_node_id], &[], network_interface::FlowType::LayerChildrenUpstreamFlow)
.enumerate()
.for_each(|(index, node_id)| {
copy_ids.insert(node_id, NodeId((index + 1) as u64));
});
buffer.push(CopyBufferEntry {
nodes: active_document.network_interface.copy_nodes(©_ids, &[]).collect(),
selected: active_document.network_interface.selected_nodes().selected_layers_contains(layer, active_document.metadata()),
visible: active_document.network_interface.selected_nodes().layer_visible(layer, &active_document.network_interface),
locked: active_document.network_interface.selected_nodes().layer_locked(layer, &active_document.network_interface),
collapsed: false,
});
}
};
if clipboard == Clipboard::Device {
let mut buffer = Vec::new();
copy_val(&mut buffer);
let Ok(data) = serde_json::to_string(&buffer) else {
log::error!("Failed to serialize nodes for clipboard");
return;
};
responses.add(ClipboardMessage::Write {
content: ClipboardContent::Layer(data),
});
} else {
let copy_buffer = &mut self.copy_buffer;
copy_buffer[clipboard as usize].clear();
copy_val(&mut copy_buffer[clipboard as usize]);
}
}
PortfolioMessage::Cut { clipboard } => {
if context.current_tool == &ToolType::Path {
responses.add(PathToolMessage::Cut { clipboard });
return;
}
if let Some(active_document) = self.active_document()
&& active_document.graph_view_overlay_open()
{
responses.add(NodeGraphMessage::Cut);
return;
}
responses.add(PortfolioMessage::Copy { clipboard });
responses.add(DocumentMessage::DeleteSelectedLayers);
}
PortfolioMessage::DeleteDocument { document_id } => {
let document_index = self.document_index(document_id);
self.documents.remove(&document_id);
self.document_ids.remove(document_index);
if self.document_ids.is_empty() {
self.active_document_id = None;
responses.add(MenuBarMessage::SendLayout);
} else if self.active_document_id.is_some() {
let document_id = if document_index == self.document_ids.len() {
// If we closed the last document take the one previous (same as last)
*self.document_ids.back().unwrap()
} else {
// Move to the next tab
self.document_ids[document_index]
};
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
PortfolioMessage::DestroyAllDocuments => {
// Empty the list of internal document data
self.documents.clear();
self.document_ids.clear();
self.active_document_id = None;
responses.add(MenuBarMessage::SendLayout);
}
PortfolioMessage::FontCatalogLoaded { catalog } => {
self.persistent_data.font_catalog = catalog;
if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::LoadDocumentResources { document_id });
}
// Load the default font
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.into(), graphene_std::consts::DEFAULT_FONT_STYLE.into());
responses.add(PortfolioMessage::LoadFontData { font });
}
PortfolioMessage::LoadFontData { font } => {
if let Some(style) = self.persistent_data.font_catalog.find_font_style_in_catalog(&font) {
let font = Font::new(font.font_family, style.to_named_style());
if !self.persistent_data.font_cache.loaded_font(&font) {
responses.add(FrontendMessage::TriggerFontDataLoad { font, url: style.url });
}
}
}
PortfolioMessage::FontLoaded { font_family, font_style, data } => {
let font = Font::new(font_family, font_style);
self.persistent_data.font_cache.insert(font, data);
self.executor.update_font_cache(self.persistent_data.font_cache.clone());
for document_id in self.document_ids.iter() {
let node_to_inspect = self.node_to_inspect();
let Some(document) = self.documents.get_mut(document_id) else {
log::error!("Tried to render non-existent document");
continue;
};
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(viewport.center_in_viewport_space().into(), &document.document_ptz);
let pointer_position = document_to_viewport.inverse().transform_point2(ipp.mouse.position);
let scale = viewport.scale();
// Use exact physical dimensions from browser (via ResizeObserver's devicePixelContentBoxSize)
let physical_resolution = viewport.size().to_physical().into_dvec2().round().as_uvec2();
if let Ok(message) = self.executor.submit_node_graph_evaluation(
self.documents.get_mut(document_id).expect("Tried to render non-existent document"),
*document_id,
physical_resolution,
scale,
timing_information,
node_to_inspect,
true,
pointer_position,
) {
responses.add_front(message);
}
}
if self.active_document_mut().is_some() {
responses.add(NodeGraphMessage::RunDocumentGraph);
}
if current_tool == &ToolType::Text {
responses.add(TextToolMessage::RefreshEditingFontData);
}
}
PortfolioMessage::EditorPreferences => self.executor.update_editor_preferences(preferences.editor_preferences()),
PortfolioMessage::Import => {
// This portfolio message wraps the frontend message so it can be listed as an action, which isn't possible for frontend messages
responses.add(FrontendMessage::TriggerImport);
}
PortfolioMessage::LoadDocumentResources { document_id } => {
let catalog = &self.persistent_data.font_catalog;
if catalog.0.is_empty() {
log::error!("Tried to load document resources before font catalog was loaded");
}
if let Some(document) = self.documents.get_mut(&document_id) {
document.load_layer_resources(responses, catalog);
}
}
PortfolioMessage::NewDocumentWithName { name } => {
let mut new_document = DocumentMessageHandler::default();
new_document.name = name;
responses.add(DocumentMessage::PTZUpdate);
let document_id = DocumentId(generate_uuid());
if self.active_document().is_some() {
responses.add(EventMessage::ToolAbort);
responses.add(NavigationMessage::CanvasPan { delta: (0., 0.).into() });
}
self.load_document(new_document, document_id, self.layers_panel_open, responses, false);
responses.add(PortfolioMessage::SelectDocument { document_id });
}
PortfolioMessage::NextDocument => {
if let Some(active_document_id) = self.active_document_id {
let current_index = self.document_index(active_document_id);
let next_index = (current_index + 1) % self.document_ids.len();
let next_id = self.document_ids[next_index];
responses.add(PortfolioMessage::SelectDocument { document_id: next_id });
}
}
PortfolioMessage::OpenDocument => {
// This portfolio message wraps the frontend message so it can be listed as an action, which isn't possible for frontend messages
responses.add(FrontendMessage::TriggerOpenDocument);
}
PortfolioMessage::OpenDocumentFile {
document_name,
document_path,
document_serialized_content,
} => {
responses.add(PortfolioMessage::OpenDocumentFileWithId {
document_id: DocumentId(generate_uuid()),
document_name,
document_path,
document_is_auto_saved: false,
document_is_saved: true,
document_serialized_content,
to_front: false,
select_after_open: true,
});
}
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
responses.add(MenuBarMessage::SendLayout);
}
PortfolioMessage::OpenDocumentFileWithId {
document_id,
document_name,
document_path,
document_is_auto_saved,
document_is_saved,
document_serialized_content,
to_front,
select_after_open,
} => {
// Upgrade the document being opened to use fresh copies of all nodes
let reset_node_definitions_on_open = reset_node_definitions_on_open || document_migration_reset_node_definition(&document_serialized_content);
// Upgrade the document being opened with string replacements on the original JSON
let document_serialized_content = document_migration_string_preprocessing(document_serialized_content);
// Deserialize the document
let document = DocumentMessageHandler::deserialize_document(&document_serialized_content);
// Display an error to the user if the document could not be opened
let mut document = match document {
Ok(document) => document,
Err(e) => {
if !document_is_auto_saved {
responses.add(DialogMessage::DisplayDialogError {
title: "Failed to open document".to_string(),
description: e.to_string(),
});
}
return;
}
};
// Upgrade the document's nodes to be compatible with the latest version
document_migration_upgrades(&mut document, reset_node_definitions_on_open);
// Ensure each node has the metadata for its inputs
for (node_id, node, path) in document.network_interface.document_network().clone().recursive_nodes() {
document.network_interface.validate_input_metadata(node_id, node, &path);
document.network_interface.validate_display_name_metadata(node_id, &path);
document.network_interface.validate_output_names(node_id, node, &path);
}
// Ensure layers are positioned as stacks if they are upstream siblings of another layer
document.network_interface.load_structure();
let all_layers = LayerNodeIdentifier::ROOT_PARENT.descendants(document.network_interface.document_metadata()).collect::<Vec<_>>();
for layer in all_layers {
let Some((downstream_node, input_index)) = document
.network_interface
.outward_wires(&[])
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(layer.to_node(), 0)))
.and_then(|outward_wires| outward_wires.first())
.and_then(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())))
else {
continue;
};
// If the downstream node is a layer and the input is the first input and the current layer is not in a stack
if input_index == 0 && document.network_interface.is_layer(&downstream_node, &[]) && !document.network_interface.is_stack(&layer.to_node(), &[]) {
// Ensure the layer is horizontally aligned with the downstream layer to prevent changing the layout of old files
let (Some(layer_position), Some(downstream_position)) =
(document.network_interface.position(&layer.to_node(), &[]), document.network_interface.position(&downstream_node, &[]))
else {
log::error!("Could not get position for layer {:?} or downstream node {} when opening file", layer.to_node(), downstream_node);
continue;
};
if layer_position.x == downstream_position.x {
document.network_interface.set_stack_position_calculated_offset(&layer.to_node(), &downstream_node, &[]);
}
}
}
// Set the save state of the document based on what's given to us by the caller to this message
document.set_auto_save_state(document_is_auto_saved);
document.set_save_state(document_is_saved);
let document_name_from_path = document_path.as_ref().and_then(|path| {
if path.extension().is_some_and(|e| e == FILE_EXTENSION) {
path.file_stem().map(|n| n.to_string_lossy().to_string())
} else {
None
}
});
match (document_name, document_path, document_name_from_path) {
(Some(name), _, None) => {
document.name = name;
}
(_, Some(path), Some(name)) => {
document.name = name;
document.path = Some(path);
}
(_, _, Some(name)) => {
document.name = name;
}
_ => {
document.name = DEFAULT_DOCUMENT_NAME.to_string();
}
}
// Load the document into the portfolio so it opens in the editor
self.load_document(document, document_id, self.layers_panel_open, responses, to_front);
if select_after_open {
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
PortfolioMessage::PasteIntoFolder { clipboard, parent, insert_index } => {
let mut all_new_ids = Vec::new();
let paste = |entry: &CopyBufferEntry, responses: &mut VecDeque<_>, all_new_ids: &mut Vec<NodeId>| {
if self.active_document().is_some() {
trace!("Pasting into folder {parent:?} as index: {insert_index}");
let nodes = entry.clone().nodes;
let new_ids: HashMap<_, _> = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
all_new_ids.extend(new_ids.values().cloned());
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
}
};
responses.add(DocumentMessage::DeselectAllLayers);
for entry in self.copy_buffer[clipboard as usize].iter().rev() {
paste(entry, responses, &mut all_new_ids)
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
}
PortfolioMessage::PasteSerializedData { data } => {
if let Some(document) = self.active_document() {
let mut all_new_ids = Vec::new();
if let Ok(data) = serde_json::from_str::<Vec<CopyBufferEntry>>(&data) {
let parent = document.new_layer_parent(false);
let mut layers = Vec::new();
let mut added_nodes = false;
for entry in data.into_iter().rev() {
if !added_nodes {
responses.add(DocumentMessage::DeselectAllLayers);
responses.add(DocumentMessage::AddTransaction);
added_nodes = true;
}
document.load_layer_resources(responses, &self.persistent_data.font_catalog);
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
all_new_ids.extend(new_ids.values().cloned());
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
layers.push(layer);
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
responses.add(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterPastedLayers { layers }.into()],
});
}
}
}
// Custom paste implementation for Path tool
PortfolioMessage::PasteSerializedVector { data } => {
// If using Path tool then send the operation to Path tool
if *current_tool == ToolType::Path {
responses.add(PathToolMessage::Paste { data });
return;
}
// If not using Path tool, create new layers and add paths into those
if let Some(document) = self.active_document() {
let Ok(data) = serde_json::from_str::<Vec<(LayerNodeIdentifier, Vector, DAffine2)>>(&data) else {
return;
};
let mut layers = Vec::new();
for (_, new_vector, transform) in data {
let Some(node_type) = resolve_document_node_type("Path") else {
error!("Path node does not exist");
continue;
};
let nodes = vec![(NodeId(0), node_type.default_node_template())];
let parent = document.new_layer_parent(false);
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
layers.push(layer);
// Adding the transform back into the layer
responses.add(GraphOperationMessage::TransformSet {
layer,
transform,
transform_in: TransformIn::Local,
skip_rerender: false,
});
// Add default fill and stroke to the layer
let fill_color = Color::WHITE;
let stroke_color = Color::BLACK;
let fill = graphene_std::vector::style::Fill::solid(fill_color.to_gamma_srgb());
responses.add(GraphOperationMessage::FillSet { layer, fill });
let stroke = graphene_std::vector::style::Stroke::new(Some(stroke_color.to_gamma_srgb()), DEFAULT_STROKE_WIDTH);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
// Create new point ids and add those into the existing Vector path
let mut points_map = HashMap::new();
for (point, position) in new_vector.point_domain.iter() {
let new_point_id = PointId::generate();
points_map.insert(point, new_point_id);
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Create new segment ids and add the segments into the existing Vector path
let mut segments_map = HashMap::new();
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
let new_segment_id = SegmentId::generate();
segments_map.insert(segment_id, new_segment_id);
let handles = match bezier.handles {
BezierHandles::Linear => [None, None],
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
};
let points = [points_map[&start], points_map[&end]];
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
// Set G1 continuity
for handles in new_vector.colinear_manipulators {
let to_new_handle = |handle: HandleId| -> HandleId {
HandleId {
ty: handle.ty,
segment: segments_map[&handle.segment],
}
};
let new_handles = [to_new_handle(handles[0]), to_new_handle(handles[1])];
let modification_type = VectorModificationType::SetG1Continuous { handles: new_handles, enabled: true };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterPastedLayers { layers }.into()],
}));
}
}
PortfolioMessage::CenterPastedLayers { layers } => {
if let Some(document) = self.active_document_mut() {
let viewport_bounds_quad_pixels = Quad::from_box([DVec2::ZERO, viewport.size().into_dvec2()]); // In viewport pixel coordinates
let viewport_center_pixels = viewport_bounds_quad_pixels.center(); // In viewport pixel coordinates
let doc_to_viewport_transform = document.metadata().document_to_viewport;
let viewport_to_doc_transform = doc_to_viewport_transform.inverse();
let viewport_quad_doc_space = viewport_to_doc_transform * viewport_bounds_quad_pixels;
let mut top_level_items_to_center: Vec<LayerNodeIdentifier> = Vec::new();
let mut artboards_in_selection: Vec<LayerNodeIdentifier> = Vec::new();
for &layer_id in &layers {
if document.network_interface.is_artboard(&layer_id.to_node(), &document.node_graph_handler.network) {
artboards_in_selection.push(layer_id);
}
}
for &layer_id in &layers {
let is_child_of_selected_artboard = artboards_in_selection.iter().any(|&artboard_id| {
if layer_id == artboard_id {
return false;
}
layer_id.ancestors(document.metadata()).any(|ancestor| ancestor == artboard_id)
});
if !is_child_of_selected_artboard {
top_level_items_to_center.push(layer_id);
}
}
if top_level_items_to_center.is_empty() {
return;
}
let mut combined_min_doc = DVec2::MAX;
let mut combined_max_doc = DVec2::MIN;
let mut has_any_bounds = false;
for &item_id in &top_level_items_to_center {
if let Some(bounds_doc) = document.metadata().bounding_box_document(item_id) {
combined_min_doc = combined_min_doc.min(bounds_doc[0]);
combined_max_doc = combined_max_doc.max(bounds_doc[1]);
has_any_bounds = true;
}
}
if !has_any_bounds {
return;
}
let combined_bounds_doc_quad = Quad::from_box([combined_min_doc, combined_max_doc]);
if combined_bounds_doc_quad.intersects(viewport_quad_doc_space) {
return;
}
let combined_center_doc = combined_bounds_doc_quad.center();
let combined_center_viewport_pixels = doc_to_viewport_transform.transform_point2(combined_center_doc);
let translation_viewport_pixels_rounded = (viewport_center_pixels - combined_center_viewport_pixels).round();
let final_translation_offset_doc = viewport_to_doc_transform.transform_vector2(translation_viewport_pixels_rounded);
if final_translation_offset_doc.abs_diff_eq(glam::DVec2::ZERO, 1e-9) {
return;
}
responses.add(DocumentMessage::AddTransaction);
for &item_id in &top_level_items_to_center {
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document_migration.rs | editor/src/messages/portfolio/document_migration.rs | // TODO: Eventually remove this document upgrade code
// This file contains lots of hacky code for upgrading old documents to the new format
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use glam::{DVec2, IVec2};
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
use graphene_std::ProtoNodeIdentifier;
use graphene_std::subpath::Subpath;
use graphene_std::table::Table;
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::uuid::NodeId;
use graphene_std::vector::Vector;
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
use std::collections::HashMap;
use std::f64::consts::PI;
const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
("graphene_core::vector::vector_nodes::SamplePointsNode", "graphene_core::vector::SamplePolylineNode"),
("graphene_core::vector::vector_nodes::SubpathSegmentLengthsNode", "graphene_core::vector::SubpathSegmentLengthsNode"),
("\"manual_composition\":null", "\"manual_composition\":{\"Generic\":\"T\"}"),
(
"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>",
"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>",
),
("graphene_core::transform::Footprint", "graphene_core::transform::Footprint"),
];
pub struct NodeReplacement<'a> {
node: ProtoNodeIdentifier,
aliases: &'a [&'a str],
}
const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
// ================================
// blending
// ================================
NodeReplacement {
node: graphene_std::blending_nodes::blending::IDENTIFIER,
aliases: &["graphene_core::raster::BlendingNode", "graphene_core::blending_nodes::BlendingNode"],
},
NodeReplacement {
node: graphene_std::blending_nodes::blend_mode::IDENTIFIER,
aliases: &["graphene_core::raster::BlendModeNode", "graphene_core::blending_nodes::BlendModeNode"],
},
NodeReplacement {
node: graphene_std::blending_nodes::opacity::IDENTIFIER,
aliases: &["graphene_core::raster::OpacityNode", "graphene_core::blending_nodes::OpacityNode"],
},
// ================================
// brush
// ================================
NodeReplacement {
node: graphene_std::brush::brush::blit::IDENTIFIER,
aliases: &["graphene_brush::BlitNode", "graphene_std::brush::BlitNode", "graphene_brush::brush::BlitNode"],
},
NodeReplacement {
node: graphene_std::brush::brush::brush::IDENTIFIER,
aliases: &["graphene_brush::BrushNode", "graphene_std::brush::BrushNode", "graphene_brush::brush::BrushNode"],
},
NodeReplacement {
node: graphene_std::brush::brush::brush_stamp_generator::IDENTIFIER,
aliases: &[
"graphene_brush::BrushStampGeneratorNode",
"graphene_std::brush::BrushStampGeneratorNode",
"graphene_brush::brush::BrushStampGeneratorNode",
],
},
// ================================
// gcore
// ================================
NodeReplacement {
node: graphene_std::animation::animation_time::IDENTIFIER,
aliases: &["graphene_core::animation::AnimationTimeNode"],
},
NodeReplacement {
node: graphene_std::debug::clone::IDENTIFIER,
aliases: &["graphene_core::ops::CloneNode"],
},
NodeReplacement {
node: graphene_std::extract_xy::extract_xy::IDENTIFIER,
aliases: &["graphene_core::ops::ExtractXyNode"],
},
NodeReplacement {
node: graphene_std::ops::identity::IDENTIFIER,
aliases: &[
"graphene_core::transform::CullNode",
"graphene_core::transform::BoundlessFootprintNode",
"graphene_core::transform::FreezeRealTimeNode",
"graphene_core::transform_nodes::BoundlessFootprintNode",
"graphene_core::transform_nodes::FreezeRealTimeNode",
],
},
NodeReplacement {
node: graphene_std::memo::monitor::IDENTIFIER,
aliases: &["graphene_core::memo::MonitorNode"],
},
NodeReplacement {
node: graphene_std::memo::memo::IDENTIFIER,
aliases: &["graphene_core::memo::MemoNode", "graphene_core::memo::ImpureMemoNode"],
},
NodeReplacement {
node: graphene_std::animation::real_time::IDENTIFIER,
aliases: &["graphene_core::animation::RealTimeNode"],
},
NodeReplacement {
node: graphene_std::logic::serialize::IDENTIFIER,
aliases: &["graphene_core::logic::SerializeNode"],
},
NodeReplacement {
node: graphene_std::debug::size_of::IDENTIFIER,
aliases: &["graphene_core::ops::SizeOfNode"],
},
NodeReplacement {
node: graphene_std::debug::some::IDENTIFIER,
aliases: &["graphene_core::ops::SomeNode"],
},
NodeReplacement {
node: graphene_std::logic::string_concatenate::IDENTIFIER,
aliases: &["graphene_core::logic::StringConcatenateNode"],
},
NodeReplacement {
node: graphene_std::logic::string_length::IDENTIFIER,
aliases: &["graphene_core::logic::StringLengthNode"],
},
NodeReplacement {
node: graphene_std::logic::string_replace::IDENTIFIER,
aliases: &["graphene_core::logic::StringReplaceNode"],
},
NodeReplacement {
node: graphene_std::logic::string_slice::IDENTIFIER,
aliases: &["graphene_core::logic::StringSliceNode"],
},
NodeReplacement {
node: graphene_std::logic::string_split::IDENTIFIER,
aliases: &["graphene_core::logic::StringSplitNode"],
},
NodeReplacement {
node: graphene_std::logic::switch::IDENTIFIER,
aliases: &["graphene_core::logic::SwitchNode"],
},
NodeReplacement {
node: graphene_std::logic::to_string::IDENTIFIER,
aliases: &["graphene_core::logic::ToStringNode"],
},
NodeReplacement {
node: graphene_std::debug::unwrap_option::IDENTIFIER,
aliases: &["graphene_core::ops::UnwrapNode", "graphene_core::debug::UnwrapNode"],
},
// ================================
// graphic
// ================================
NodeReplacement {
node: graphene_std::artboard::create_artboard::IDENTIFIER,
aliases: &[
"graphene_core::artboard::CreateArtboardNode",
"graphene_core::ConstructArtboardNode",
"graphene_core::graphic_element::ToArtboardNode",
"graphene_core::artboard::ToArtboardNode",
],
},
NodeReplacement {
node: graphene_std::graphic::extend::IDENTIFIER,
aliases: &["graphene_core::graphic::graphic::ExtendNode", "graphene_core::graphic::ExtendNode"],
},
NodeReplacement {
node: graphene_std::graphic::flatten_graphic::IDENTIFIER,
aliases: &[
"graphene_core::graphic::FlattenGraphicNode",
"graphene_core::graphic_element::FlattenGroupNode",
"graphene_core::graphic_types::FlattenGroupNode",
],
},
NodeReplacement {
node: graphene_std::graphic::flatten_vector::IDENTIFIER,
aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"],
},
NodeReplacement {
node: graphene_std::graphic::index_elements::IDENTIFIER,
aliases: &[
"graphene_core::graphic_element::IndexNode",
"graphene_core::graphic::IndexNode",
"graphene_core::graphic::IndexElementsNode",
],
},
NodeReplacement {
node: graphene_std::graphic::legacy_layer_extend::IDENTIFIER,
aliases: &[
"graphene_core::graphic_element::LayerNode",
"graphene_core::graphic_types::LayerNode",
// Converted from "Append Artboard"
"graphene_core::AddArtboardNode",
"graphene_core::graphic_element::AppendArtboardNode",
"graphene_core::graphic_types::AppendArtboardNode",
"graphene_core::artboard::AppendArtboardNode",
"graphene_core::graphic::LegacyLayerExtendNode",
],
},
NodeReplacement {
node: graphene_std::graphic_nodes::source_node_id::IDENTIFIER,
aliases: &["graphene_core::graphic::graphic::SourceNodeIdNode", "graphene_core::graphic::SourceNodeIdNode"],
},
NodeReplacement {
node: graphene_std::graphic::to_graphic::IDENTIFIER,
aliases: &[
"graphene_core::ToGraphicGroupNode",
"graphene_core::graphic_element::ToGroupNode",
"graphene_core::graphic_types::ToGroupNode",
"graphene_core::graphic::ToGraphicNode",
],
},
NodeReplacement {
node: graphene_std::graphic::wrap_graphic::IDENTIFIER,
aliases: &[
// Converted from "To Element"
"graphene_core::ToGraphicElementNode",
"graphene_core::graphic_element::ToElementNode",
"graphene_core::graphic_types::ToElementNode",
"graphene_core::graphic::WrapGraphicNode",
],
},
// ================================
// math
// ================================
NodeReplacement {
node: graphene_std::math_nodes::absolute_value::IDENTIFIER,
aliases: &["graphene_math_nodes::AbsoluteValueNode", "graphene_core::ops::AbsoluteValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::add::IDENTIFIER,
aliases: &["graphene_math_nodes::AddNode", "graphene_core::ops::AddNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::bool_value::IDENTIFIER,
aliases: &["graphene_math_nodes::BoolValueNode", "graphene_core::ops::BoolValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::ceiling::IDENTIFIER,
aliases: &["graphene_math_nodes::CeilingNode", "graphene_core::ops::CeilingNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::clamp::IDENTIFIER,
aliases: &["graphene_math_nodes::ClampNode", "graphene_core::ops::ClampNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::color_value::IDENTIFIER,
aliases: &["graphene_math_nodes::ColorValueNode", "graphene_core::ops::ColorValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::cosine::IDENTIFIER,
aliases: &["graphene_math_nodes::CosineNode", "graphene_core::ops::CosineNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::cosine_inverse::IDENTIFIER,
aliases: &["graphene_math_nodes::CosineInverseNode", "graphene_core::ops::CosineInverseNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::divide::IDENTIFIER,
aliases: &["graphene_math_nodes::DivideNode", "graphene_core::ops::DivideNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::dot_product::IDENTIFIER,
aliases: &["graphene_math_nodes::DotProductNode", "graphene_core::ops::DotProductNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::equals::IDENTIFIER,
aliases: &["graphene_math_nodes::EqualsNode", "graphene_core::ops::EqualsNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::exponent::IDENTIFIER,
aliases: &["graphene_math_nodes::ExponentNode", "graphene_core::ops::ExponentNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::floor::IDENTIFIER,
aliases: &["graphene_math_nodes::FloorNode", "graphene_core::ops::FloorNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_table_value::IDENTIFIER,
aliases: &["graphene_math_nodes::GradientTableValueNode", "graphene_core::ops::GradientTableValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_value::IDENTIFIER,
aliases: &["graphene_math_nodes::GradientValueNode", "graphene_core::ops::GradientValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::greater_than::IDENTIFIER,
aliases: &["graphene_math_nodes::GreaterThanNode", "graphene_core::ops::GreaterThanNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::greatest_common_divisor::IDENTIFIER,
aliases: &[
"graphene_math_nodes::GreatestCommonDivisor",
"graphene_core::ops::GreatestCommonDivisor",
"graphene_math_nodes::GreatestCommonDivisorNode",
],
},
NodeReplacement {
node: graphene_std::math_nodes::least_common_multiple::IDENTIFIER,
aliases: &[
"graphene_math_nodes::LeastCommonMultiple",
"graphene_core::ops::LeastCommonMultiple",
"graphene_math_nodes::LeastCommonMultipleNode",
],
},
NodeReplacement {
node: graphene_std::math_nodes::length::IDENTIFIER,
aliases: &["graphene_math_nodes::LengthNode", "graphene_core::ops::LenghtNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::less_than::IDENTIFIER,
aliases: &["graphene_math_nodes::LessThanNode", "graphene_core::ops::LessThanNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::logarithm::IDENTIFIER,
aliases: &["graphene_math_nodes::LogarithmNode", "graphene_core::ops::LogarithmNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::logical_and::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalAndNode",
"graphene_core::ops::LogicNotNode",
"graphene_core::logic::LogicNotNode",
"graphene_math_nodes::LogicalAndNode",
],
},
NodeReplacement {
node: graphene_std::math_nodes::logical_not::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalNotNode",
"graphene_core::ops::LogicOrNode",
"graphene_core::logic::LogicOrNode",
"graphene_math_nodes::LogicalNotNode",
],
},
NodeReplacement {
node: graphene_std::math_nodes::logical_or::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalOrNode",
"graphene_core::ops::LogicAndNode",
"graphene_core::logic::LogicAndNode",
"graphene_math_nodes::LogicalOrNode",
],
},
NodeReplacement {
node: graphene_std::math_nodes::math::IDENTIFIER,
aliases: &["graphene_math_nodes::MathNode", "graphene_core::ops::MathNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::max::IDENTIFIER,
aliases: &["graphene_math_nodes::MaxNode", "graphene_core::ops::MaxNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::min::IDENTIFIER,
aliases: &["graphene_math_nodes::MinNode", "graphene_core::ops::MinNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::modulo::IDENTIFIER,
aliases: &["graphene_math_nodes::ModuloNode", "graphene_core::ops::ModuloNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::multiply::IDENTIFIER,
aliases: &["graphene_math_nodes::MultiplyNode", "graphene_core::ops::MultiplyNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::normalize::IDENTIFIER,
aliases: &["graphene_math_nodes::NormalizeNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::not_equals::IDENTIFIER,
aliases: &["graphene_math_nodes::NotEqualsNode", "graphene_core::ops::NotEqualsNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::number_value::IDENTIFIER,
aliases: &["graphene_math_nodes::NumberValueNode", "graphene_core::ops::NumberValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::percentage_value::IDENTIFIER,
aliases: &["graphene_math_nodes::PercentageValueNode", "graphene_core::ops::PercentageValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::random::IDENTIFIER,
aliases: &["graphene_math_nodes::RandomNode", "graphene_core::ops::RandomNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::remap::IDENTIFIER,
aliases: &["graphene_math_nodes::RemapNode", "graphene_core::ops::RemapNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::root::IDENTIFIER,
aliases: &["graphene_math_nodes::RootNode", "graphene_core::ops::RootNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::round::IDENTIFIER,
aliases: &["graphene_math_nodes::RoundNode", "graphene_core::ops::RoundNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::sample_gradient::IDENTIFIER,
aliases: &["graphene_math_nodes::SampleGradientNode", "graphene_core::ops::SampleGradientNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::sine::IDENTIFIER,
aliases: &["graphene_math_nodes::SineNode", "graphene_core::ops::SineNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::sine_inverse::IDENTIFIER,
aliases: &["graphene_math_nodes::SineInverseNode", "graphene_core::ops::SineInverseNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::string_value::IDENTIFIER,
aliases: &["graphene_math_nodes::StringValueNode", "graphene_core::ops::StringValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::subtract::IDENTIFIER,
aliases: &["graphene_math_nodes::SubtractNode", "graphene_core::ops::SubtractNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::tangent::IDENTIFIER,
aliases: &["graphene_math_nodes::TangentNode", "graphene_core::ops::TangentNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::tangent_inverse::IDENTIFIER,
aliases: &["graphene_math_nodes::TangentInverseNode", "graphene_core::ops::TangentInverseNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::to_f_64::IDENTIFIER,
aliases: &["graphene_math_nodes::ToF64Node", "graphene_core::ops::ToF64Node"],
},
NodeReplacement {
node: graphene_std::math_nodes::to_u_32::IDENTIFIER,
aliases: &["graphene_math_nodes::ToU32Node", "graphene_core::ops::ToU32Node", "math_nodes::ToU32Node"],
},
NodeReplacement {
node: graphene_std::math_nodes::to_u_64::IDENTIFIER,
aliases: &["graphene_math_nodes::ToU64Node", "graphene_core::ops::ToU64Node"],
},
NodeReplacement {
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
aliases: &[
"graphene_math_nodes::Vec2ValueNode",
"graphene_core::ops::ConstructVector2",
"graphene_core::ops::Vector2ValueNode",
"graphene_core::ops::CoordinateValueNode",
"graphene_math_nodes::CoordinateValueNode",
],
},
// ================================
// path-bool
// ================================
NodeReplacement {
node: graphene_std::path_bool::boolean_operation::IDENTIFIER,
aliases: &["graphene_path_bool::BooleanOperationNode", "graphene_std::vector::BooleanOperationNode"],
},
// ================================
// raster
// ================================
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::black_and_white::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::BlackAndWhiteNode",
"graphene_core::raster::adjustments::BlackAndWhiteNode",
"graphene_core::raster::BlackAndWhiteNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::blend::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::BlendNode",
"raster_nodes::adjustments::BlendNode",
"graphene_core::raster::adjustments::BlendNode",
"graphene_core::raster::BlendNode",
"graphene_raster_nodes::blending_nodes::BlendNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::BrightnessContrastNode",
"graphene_core::raster::adjustments::BrightnessContrastNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::brightness_contrast_classic::IDENTIFIER,
aliases: &["graphene_raster_nodes::adjustments::BrightnessContrastClassicNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::channel_mixer::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ChannelMixerNode",
"graphene_core::raster::adjustments::ChannelMixerNode",
"graphene_core::raster::ChannelMixerNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
"raster_nodes::adjustments::ColorOverlayNode",
"graphene_core::raster::adjustments::ColorOverlayNode",
"raster_nodes::generate_curves::ColorOverlayNode",
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::combine_channels::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::CombineChannelsNode", "graphene_std::raster::CombineChannelsNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
aliases: &["graphene_raster_nodes::dehaze::DehazeNode", "graphene_std::dehaze::DehazeNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::empty_image::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::EmptyImageNode", "graphene_std::raster::EmptyImageNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::exposure::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ExposureNode",
"graphene_core::raster::adjustments::ExposureNode",
"graphene_core::raster::ExposureNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::extract_channel::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ExtractChannelNode",
"graphene_core::raster::adjustments::ExtractChannelNode",
"graphene_core::raster::ExtractChannelNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::generate_curves::generate_curves::IDENTIFIER,
aliases: &["graphene_raster_nodes::generate_curves::GenerateCurvesNode", "graphene_core::raster::adjustments::GenerateCurvesNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::gradient_map::gradient_map::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::gradient_map::GradientMapNode",
"graphene_raster_nodes::adjustments::GradientMapNode",
"raster_nodes::gradient_map::GradientMapNode",
"raster_nodes::adjustments::GradientMapNode",
"graphene_core::raster::adjustments::GradientMapNode",
"graphene_core::raster::GradientMapNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::hue_saturation::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::HueSaturationNode",
"graphene_core::raster::adjustments::HueSaturationNode",
"graphene_core::raster::HueSaturationNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::image_color_palette::ImageColorPaletteNode",
"graphene_std::image_color_palette::ImageColorPaletteNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::image_value::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::std_nodes::ImageValueNode",
"graphene_std::raster::ImageValueNode",
"graphene_std::raster::ImageNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::invert::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::InvertNode",
"graphene_core::raster::adjustments::InvertNode",
"graphene_core::raster::InvertNode",
"graphene_core::raster::InvertRGBNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::levels::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::LevelsNode",
"graphene_core::raster::adjustments::LevelsNode",
"graphene_core::raster::LevelsNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::luminance::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::LuminanceNode",
"graphene_core::raster::adjustments::LuminanceNode",
"graphene_core::raster::LuminanceNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::make_opaque::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::MakeOpaqueNode",
"graphene_core::raster::adjustments::MakeOpaqueNode",
"graphene_core::raster::ExtractOpaqueNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::MandelbrotNode", "graphene_std::raster::MandelbrotNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::MaskNode", "graphene_std::raster::MaskNode", "graphene_std::raster::MaskImageNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::posterize::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::PosterizeNode",
"graphene_core::raster::adjustments::PosterizeNode",
"graphene_core::raster::PosterizeNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::NoisePatternNode", "graphene_std::raster::NoisePatternNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::sample_image::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::std_nodes::SampleImageNode",
"graphene_std::raster::SampleImageNode",
"graphene_std::raster::SampleNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::selective_color::IDENTIFIER,
aliases: &["graphene_raster_nodes::adjustments::SelectiveColorNode", "graphene_core::raster::adjustments::SelectiveColorNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ThresholdNode",
"graphene_core::raster::adjustments::ThresholdNode",
"graphene_core::raster::ThresholdNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::vibrance::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::VibranceNode",
"graphene_core::raster::adjustments::VibranceNode",
"graphene_core::raster::VibranceNode",
],
},
// ================================
// text
// ================================
NodeReplacement {
node: graphene_std::text::text::IDENTIFIER,
aliases: &["graphene_core::text::text::TextNode", "graphene_core::text::TextGeneratorNode", "graphene_core::text::TextNode"],
},
// ================================
// transform
// ================================
NodeReplacement {
node: graphene_std::transform_nodes::decompose_rotation::IDENTIFIER,
aliases: &[
"graphene_core::transform_nodes::RotationScaleNode",
"graphene_core::transform::RotationScaleNode",
"graphene_core::transform_nodes::DecomposeRotationNode",
],
},
NodeReplacement {
node: graphene_std::transform_nodes::decompose_scale::IDENTIFIER,
aliases: &["graphene_core::transform_nodes::DecomposeScaleNode", "graphene_core::transform::DecomposeScaleNode"],
},
NodeReplacement {
node: graphene_std::transform_nodes::decompose_translation::IDENTIFIER,
aliases: &["graphene_core::transform_nodes::DecomposeTranslationNode", "graphene_core::transform::DecomposeTranslationNode"],
},
NodeReplacement {
node: graphene_std::transform_nodes::extract_transform::IDENTIFIER,
aliases: &[
"graphene_core::transform_nodes::ExtractTransformNode",
"graphene_core::transform::ExtractTransformNode",
"graphene_core::vector::ExtractTransformNode",
],
},
NodeReplacement {
node: graphene_std::transform_nodes::invert_transform::IDENTIFIER,
aliases: &["graphene_core::transform_nodes::InvertTransformNode", "graphene_core::transform::InvertTransformNode"],
},
NodeReplacement {
node: graphene_std::transform_nodes::replace_transform::IDENTIFIER,
aliases: &[
"graphene_core::transform_nodes::ReplaceTransformNode",
"graphene_core::transform::SetTransformNode",
"graphene_core::transform::ReplaceTransformNode",
],
},
NodeReplacement {
node: graphene_std::transform_nodes::transform::IDENTIFIER,
aliases: &["graphene_core::transform_nodes::TransformNode", "graphene_core::transform::TransformNode"],
},
// ================================
// vector
// ================================
NodeReplacement {
node: graphene_std::vector::apply_transform::IDENTIFIER,
aliases: &["graphene_core::vector::ApplyTransformNode", "graphene_core::vector::vector_modification::ApplyTransformNode"],
},
NodeReplacement {
node: graphene_std::vector::area::IDENTIFIER,
aliases: &["graphene_core::vector::AreaNode"],
},
NodeReplacement {
node: graphene_std::vector::assign_colors::IDENTIFIER,
aliases: &["graphene_core::vector::AssignColorsNode"],
},
NodeReplacement {
node: graphene_std::vector::auto_tangents::IDENTIFIER,
aliases: &[
"graphene_core::vector::vector_nodes::AutoTangentsNode",
"graphene_core::vector::AutoTangentsNode",
"graphene_core::vector::GenerateHandlesNode",
"graphene_core::vector::RemoveHandlesNode",
],
},
NodeReplacement {
node: graphene_std::vector::bevel::IDENTIFIER,
aliases: &["graphene_core::vector::BevelNode"],
},
NodeReplacement {
node: graphene_std::vector::bounding_box::IDENTIFIER,
aliases: &["graphene_core::vector::BoundingBoxNode"],
},
NodeReplacement {
node: graphene_std::vector::box_warp::IDENTIFIER,
aliases: &["graphene_core::vector::BoxWarpNode"],
},
NodeReplacement {
node: graphene_std::vector::centroid::IDENTIFIER,
aliases: &["graphene_core::vector::CentroidNode"],
},
NodeReplacement {
node: graphene_std::vector::circular_repeat::IDENTIFIER,
aliases: &["graphene_core::vector::CircularRepeatNode"],
},
NodeReplacement {
node: graphene_std::vector::close_path::IDENTIFIER,
aliases: &["graphene_core::vector::ClosePathNode"],
},
NodeReplacement {
node: graphene_std::vector::copy_to_points::IDENTIFIER,
aliases: &["graphene_core::vector::CopyToPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::count_elements::IDENTIFIER,
aliases: &["graphene_core::vector::CountElementsNode"],
},
NodeReplacement {
node: graphene_std::vector::cut_path::IDENTIFIER,
aliases: &["graphene_core::vector::vector_nodes::SplitPathNode", "graphene_core::vector::SplitPathNode"],
},
NodeReplacement {
node: graphene_std::vector::cut_segments::IDENTIFIER,
aliases: &[
"graphene_core::vector::vector_nodes::SplitSegmentsNode",
"graphene_core::vector::SplitSegmentsNode",
"graphene_core::vector::CutSegmentsNode",
],
},
NodeReplacement {
node: graphene_std::vector::dimensions::IDENTIFIER,
aliases: &["graphene_core::vector::DimensionsNode"],
},
NodeReplacement {
node: graphene_std::vector_nodes::fill::IDENTIFIER,
aliases: &["graphene_core::vector::vector_nodes::FillNode", "graphene_core::vector::FillNode"],
},
NodeReplacement {
node: graphene_std::vector::flatten_path::IDENTIFIER,
aliases: &[
"graphene_core::vector::vector_nodes::FlattenPathNode",
"graphene_core::vector::FlattenVectorElementsNode",
"graphene_core::vector::FlattenPathNode",
],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::arc::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::ArcNode"],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::circle::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::CircleNode"],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::ellipse::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::EllipseNode"],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::grid::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::GridNode"],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::line::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::LineNode"],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::rectangle::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::RectangleNode"],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::RegularPolygonNode"],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::spiral::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::SpiralNode"],
},
NodeReplacement {
node: graphene_std::vector::generator_nodes::star::IDENTIFIER,
aliases: &["graphene_core::vector::generator_nodes::StarNode"],
},
NodeReplacement {
node: graphene_std::vector::instance_index::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceIndexNode"],
},
NodeReplacement {
node: graphene_std::vector::instance_map::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceMapNode"],
},
NodeReplacement {
node: graphene_std::vector::instance_on_points::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceOnPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::instance_position::IDENTIFIER,
aliases: &["graphene_core::vector::InstancePositionNode"],
},
NodeReplacement {
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/document_message_handler.rs | editor/src/messages/portfolio/document/document_message_handler.rs | use super::node_graph::document_node_definitions;
use super::node_graph::utility_types::Transform;
use super::utility_types::error::EditorError;
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::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::consts::{ASYMPTOTIC_EFFECT, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, SCALE_EFFECT, SCROLLBAR_SPACING, VIEWPORT_ROTATE_SNAP_INTERVAL};
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext, DataPanelMessageHandler};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext;
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay, overlay_options};
use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot};
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate};
use crate::messages::portfolio::document::utility_types::nodes::RawBuffer;
use crate::messages::portfolio::utility_types::{FontCatalog, PanelType, PersistentData};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
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 glam::{DAffine2, DVec2, IVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graphene_std::math::quad::Quad;
use graphene_std::path_bool::{boolean_intersect, path_bool_lib};
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Raster;
use graphene_std::subpath::Subpath;
use graphene_std::table::Table;
use graphene_std::text::Font;
use graphene_std::vector::PointId;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::{dvec2_to_point, point_to_dvec2};
use graphene_std::vector::style::RenderMode;
use kurbo::{Affine, CubicBez, Line, ParamCurve, PathSeg, QuadBez};
use std::path::PathBuf;
use std::time::Duration;
#[derive(ExtractField)]
pub struct DocumentMessageContext<'a> {
pub document_id: DocumentId,
pub ipp: &'a InputPreprocessorMessageHandler,
pub persistent_data: &'a PersistentData,
pub executor: &'a mut NodeGraphExecutor,
pub current_tool: &'a ToolType,
pub preferences: &'a PreferencesMessageHandler,
pub data_panel_open: bool,
pub layers_panel_open: bool,
pub properties_panel_open: bool,
pub viewport: &'a ViewportMessageHandler,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ExtractField)]
#[serde(default)]
pub struct DocumentMessageHandler {
// ======================
// Child message handlers
// ======================
//
#[serde(skip)]
pub navigation_handler: NavigationMessageHandler,
#[serde(skip)]
pub node_graph_handler: NodeGraphMessageHandler,
#[serde(skip)]
pub overlays_message_handler: OverlaysMessageHandler,
#[serde(skip)]
pub properties_panel_message_handler: PropertiesPanelMessageHandler,
#[serde(skip)]
pub data_panel_message_handler: DataPanelMessageHandler,
// ============================================
// Fields that are saved in the document format
// ============================================
//
// Contains the NodeNetwork and acts an an interface to manipulate the NodeNetwork with custom setters in order to keep NetworkMetadata in sync
pub network_interface: NodeNetworkInterface,
/// List of the [`LayerNodeIdentifier`]s that are currently collapsed by the user in the Layers panel.
/// Collapsed means that the expansion arrow isn't set to show the children of these layers.
pub collapsed: CollapsedLayers,
/// The full Git commit hash of the Graphite repository that was used to build the editor.
/// We save this to provide a hint about which version of the editor was used to create the document.
pub commit_hash: String,
/// The current pan, tilt, and zoom state of the viewport's view of the document canvas.
pub document_ptz: PTZ,
/// The current mode that the user has set for rendering the document within the viewport.
/// This is usually "Normal" but can be set to "Outline" or "Pixels" to see the canvas differently.
#[serde(alias = "view_mode")]
pub render_mode: RenderMode,
/// Sets whether or not all the viewport overlays should be drawn on top of the artwork.
/// This includes tool interaction visualizations (like the transform cage and path anchors/handles), the grid, and more.
pub overlays_visibility_settings: OverlaysVisibilitySettings,
/// Sets whether or not the rulers should be drawn along the top and left edges of the viewport area.
pub rulers_visible: bool,
/// The current user choices for snapping behavior, including whether snapping is enabled at all.
pub snapping_state: SnappingState,
/// Sets whether or not the node graph is drawn (as an overlay) on top of the viewport area, or otherwise if it's hidden.
pub graph_view_overlay_open: bool,
/// The current opacity of the faded node graph background that covers up the artwork.
pub graph_fade_artwork_percentage: f64,
// =============================================
// Fields omitted from the saved document format
// =============================================
//
/// The name of the document, which is displayed in the tab and title bar of the editor.
#[serde(skip)]
pub name: String,
/// The path of the to the document file.
#[serde(skip)]
pub(crate) path: Option<PathBuf>,
/// Path to network currently viewed in the node graph overlay. This will eventually be stored in each panel, so that multiple panels can refer to different networks
#[serde(skip)]
breadcrumb_network_path: Vec<NodeId>,
/// Path to network that is currently selected. Updated based on the most recently clicked panel.
#[serde(skip)]
selection_network_path: Vec<NodeId>,
/// Stack of document network snapshots for previous history states.
#[serde(skip)]
document_undo_history: VecDeque<NodeNetworkInterface>,
/// Stack of document network snapshots for future history states.
#[serde(skip)]
document_redo_history: VecDeque<NodeNetworkInterface>,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
/// Hash of the document snapshot that was most recently auto-saved to the IndexedDB storage that will reopen when the editor is reloaded.
#[serde(skip)]
auto_saved_hash: Option<u64>,
/// The ID of the layer at the start of a range selection in the Layers panel.
/// If the user clicks or Ctrl-clicks one layer, it becomes the start of the range selection and then Shift-clicking another layer selects all layers between the start and end.
#[serde(skip)]
layer_range_selection_reference: Option<LayerNodeIdentifier>,
/// Whether or not the editor has executed the network to render the document yet. If this is opened as an inactive tab, it won't be loaded initially because the active tab is prioritized.
#[serde(skip)]
pub is_loaded: bool,
}
impl Default for DocumentMessageHandler {
fn default() -> Self {
Self {
// ======================
// Child message handlers
// ======================
navigation_handler: NavigationMessageHandler::default(),
node_graph_handler: NodeGraphMessageHandler::default(),
overlays_message_handler: OverlaysMessageHandler::default(),
properties_panel_message_handler: PropertiesPanelMessageHandler::default(),
data_panel_message_handler: DataPanelMessageHandler::default(),
// ============================================
// Fields that are saved in the document format
// ============================================
network_interface: default_document_network_interface(),
collapsed: CollapsedLayers::default(),
commit_hash: GRAPHITE_GIT_COMMIT_HASH.to_string(),
document_ptz: PTZ::default(),
render_mode: RenderMode::default(),
overlays_visibility_settings: OverlaysVisibilitySettings::default(),
rulers_visible: true,
graph_view_overlay_open: false,
snapping_state: SnappingState::default(),
graph_fade_artwork_percentage: 80.,
// =============================================
// Fields omitted from the saved document format
// =============================================
name: DEFAULT_DOCUMENT_NAME.to_string(),
path: None,
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
document_undo_history: VecDeque::new(),
document_redo_history: VecDeque::new(),
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
is_loaded: false,
}
}
}
#[message_handler_data]
impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMessageHandler {
fn process_message(&mut self, message: DocumentMessage, responses: &mut VecDeque<Message>, context: DocumentMessageContext) {
let DocumentMessageContext {
document_id,
ipp,
persistent_data,
executor,
viewport,
current_tool,
preferences,
data_panel_open,
layers_panel_open,
properties_panel_open,
} = context;
match message {
// Sub-messages
DocumentMessage::Navigation(message) => {
let context = NavigationMessageContext {
network_interface: &mut self.network_interface,
breadcrumb_network_path: &self.breadcrumb_network_path,
ipp,
document_ptz: &mut self.document_ptz,
graph_view_overlay_open: self.graph_view_overlay_open,
preferences,
viewport,
};
self.navigation_handler.process_message(message, responses, context);
}
DocumentMessage::Overlays(message) => {
let visibility_settings = self.overlays_visibility_settings;
// Send the overlays message to the overlays message handler
self.overlays_message_handler
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
}
DocumentMessage::PropertiesPanel(message) => {
let context = PropertiesPanelMessageContext {
network_interface: &mut self.network_interface,
selection_network_path: &self.selection_network_path,
document_name: self.name.as_str(),
executor,
persistent_data,
properties_panel_open,
};
self.properties_panel_message_handler.process_message(message, responses, context);
}
DocumentMessage::DataPanel(message) => {
self.data_panel_message_handler.process_message(
message,
responses,
DataPanelMessageContext {
network_interface: &mut self.network_interface,
data_panel_open,
},
);
}
DocumentMessage::NodeGraph(message) => {
self.node_graph_handler.process_message(
message,
responses,
NodeGraphMessageContext {
network_interface: &mut self.network_interface,
selection_network_path: &self.selection_network_path,
breadcrumb_network_path: &self.breadcrumb_network_path,
document_id,
collapsed: &mut self.collapsed,
ipp,
graph_view_overlay_open: self.graph_view_overlay_open,
graph_fade_artwork_percentage: self.graph_fade_artwork_percentage,
navigation_handler: &self.navigation_handler,
preferences,
layers_panel_open,
viewport,
},
);
}
DocumentMessage::GraphOperation(message) => {
let context = GraphOperationMessageContext {
network_interface: &mut self.network_interface,
collapsed: &mut self.collapsed,
node_graph: &mut self.node_graph_handler,
};
let mut graph_operation_message_handler = GraphOperationMessageHandler {};
graph_operation_message_handler.process_message(message, responses, context);
}
DocumentMessage::AlignSelectedLayers { axis, aggregate } => {
let axis = match axis {
AlignAxis::X => DVec2::X,
AlignAxis::Y => DVec2::Y,
};
let Some(combined_box) = self.network_interface.selected_layers_artwork_bounding_box_viewport() else {
return;
};
let aggregated = match aggregate {
AlignAggregate::Min => combined_box[0],
AlignAggregate::Max => combined_box[1],
AlignAggregate::Center => (combined_box[0] + combined_box[1]) / 2.,
};
let mut added_transaction = false;
for layer in self.network_interface.selected_nodes().selected_unlocked_layers(&self.network_interface) {
let Some(bbox) = self.metadata().bounding_box_viewport(layer) else {
continue;
};
let center = match aggregate {
AlignAggregate::Min => bbox[0],
AlignAggregate::Max => bbox[1],
_ => (bbox[0] + bbox[1]) / 2.,
};
let translation = (aggregated - center) * axis;
if !added_transaction {
responses.add(DocumentMessage::AddTransaction);
added_transaction = true;
}
responses.add(GraphOperationMessage::TransformChange {
layer,
transform: DAffine2::from_translation(translation),
transform_in: TransformIn::Viewport,
skip_rerender: false,
});
}
}
DocumentMessage::RemoveArtboards => {
responses.add(GraphOperationMessage::RemoveArtboards);
}
DocumentMessage::ClearLayersPanel => {
// Send an empty layer list
let data_buffer: RawBuffer = Self::default().serialize_root();
responses.add(FrontendMessage::UpdateDocumentLayerStructure { data_buffer });
// Clear the control bar
responses.add(LayoutMessage::SendLayout {
layout: Layout::default(),
layout_target: LayoutTarget::LayersPanelControlLeftBar,
});
responses.add(LayoutMessage::SendLayout {
layout: Layout::default(),
layout_target: LayoutTarget::LayersPanelControlRightBar,
});
// Clear the bottom bar
responses.add(LayoutMessage::SendLayout {
layout: Layout::default(),
layout_target: LayoutTarget::LayersPanelBottomBar,
});
}
DocumentMessage::CreateEmptyFolder => {
let selected_nodes = self.network_interface.selected_nodes();
let id = NodeId::new();
let parent = self
.network_interface
.deepest_common_ancestor(&selected_nodes, &self.selection_network_path, true)
.unwrap_or(LayerNodeIdentifier::ROOT_PARENT);
let insert_index = DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &self.network_interface.selected_nodes(), parent);
responses.add(DocumentMessage::AddTransaction);
responses.add(GraphOperationMessage::NewCustomLayer {
id,
nodes: Vec::new(),
parent,
insert_index,
});
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
}
DocumentMessage::DeleteNode { node_id } => {
responses.add(DocumentMessage::StartTransaction);
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: vec![node_id],
delete_children: true,
});
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::SendGraph);
responses.add(DocumentMessage::EndTransaction);
}
DocumentMessage::DeleteSelectedLayers => {
responses.add(NodeGraphMessage::DeleteSelectedNodes { delete_children: true });
}
DocumentMessage::DeselectAllLayers => {
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
self.layer_range_selection_reference = None;
}
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, responses),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
let data_buffer: RawBuffer = self.serialize_root();
self.update_layers_panel_control_bar_widgets(layers_panel_open, responses);
self.update_layers_panel_bottom_bar_widgets(layers_panel_open, responses);
responses.add(FrontendMessage::UpdateDocumentLayerStructure { data_buffer });
}
}
DocumentMessage::DrawArtboardOverlays { context: overlay_context } => {
if !overlay_context.visibility_settings.artboard_name() {
return;
}
for layer in self.metadata().all_layers() {
if !self.network_interface.is_artboard(&layer.to_node(), &[]) {
continue;
}
let Some(bounds) = self.metadata().bounding_box_document(layer) else { continue };
let min = bounds[0].min(bounds[1]);
let max = bounds[0].max(bounds[1]);
let name = self.network_interface.display_name(&layer.to_node(), &[]);
// Calculate position of the text
let corner_pos = if !self.document_ptz.flip {
// Use the top-left corner
min
} else {
// Use the top-right corner, which appears to be the top-left due to being flipped
DVec2::new(max.x, min.y)
};
// When the canvas is flipped, mirror the text so it appears correctly
let scale = if !self.document_ptz.flip { DVec2::ONE } else { DVec2::new(-1., 1.) };
// Create a transform that puts the text at the true top-left regardless of flip
let transform = self.metadata().document_to_viewport
* DAffine2::from_translation(corner_pos)
* DAffine2::from_scale(DVec2::splat(self.document_ptz.zoom().recip()))
* DAffine2::from_translation(-DVec2::Y * 4.)
* DAffine2::from_scale(scale);
overlay_context.text(&name, COLOR_OVERLAY_GRAY, None, transform, 0., [Pivot::Start, Pivot::End]);
}
}
DocumentMessage::DuplicateSelectedLayers => {
responses.add(DocumentMessage::AddTransaction);
let mut new_dragging = Vec::new();
let mut layers = self.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
layers.sort_by_key(|layer| {
let Some(parent) = layer.parent(self.metadata()) else { return usize::MAX };
DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
});
for layer in layers.into_iter().rev() {
let Some(parent) = layer.parent(self.metadata()) else { continue };
// Copy the layer
let mut copy_ids = HashMap::new();
let node_id = layer.to_node();
copy_ids.insert(node_id, NodeId(0));
self.network_interface
.upstream_flow_back_from_nodes(vec![layer.to_node()], &[], FlowType::LayerChildrenUpstreamFlow)
.enumerate()
.for_each(|(index, node_id)| {
copy_ids.insert(node_id, NodeId((index + 1) as u64));
});
let nodes = self.network_interface.copy_nodes(©_ids, &[]).collect::<Vec<(NodeId, NodeTemplate)>>();
let insert_index = DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &SelectedNodes(vec![layer.to_node()]), parent);
let new_ids: HashMap<_, _> = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let layer_id = *new_ids.get(&NodeId(0)).expect("Node Id 0 should be a layer");
let layer = LayerNodeIdentifier::new_unchecked(layer_id);
new_dragging.push(layer);
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids });
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
}
let nodes = new_dragging.iter().map(|layer| layer.to_node()).collect();
responses.add(NodeGraphMessage::SelectedNodesSet { nodes });
responses.add(NodeGraphMessage::RunDocumentGraph);
}
DocumentMessage::EnterNestedNetwork { node_id } => {
self.breadcrumb_network_path.push(node_id);
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendGraph);
responses.add(DocumentMessage::ZoomCanvasToFitAll);
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
}
DocumentMessage::Escape => {
// Abort dragging nodes
if self.node_graph_handler.drag_start.is_some() {
responses.add(DocumentMessage::AbortTransaction);
self.node_graph_handler.drag_start = None;
}
// Abort box selection
else if self.node_graph_handler.box_selection_start.is_some() {
self.node_graph_handler.box_selection_start = None;
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: self.node_graph_handler.selection_before_pointer_down.clone(),
});
responses.add(FrontendMessage::UpdateBox { box_selection: None });
}
// Abort wire in progress of being connected
else if self.node_graph_handler.wire_in_progress_from_connector.is_some() {
self.node_graph_handler.wire_in_progress_from_connector = None;
self.node_graph_handler.wire_in_progress_to_connector = None;
self.node_graph_handler.wire_in_progress_type = FrontendGraphDataType::General;
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None });
responses.add(DocumentMessage::AbortTransaction);
}
// Close the context menu if it's open
else if self
.node_graph_handler
.context_menu
.as_ref()
.is_some_and(|context_menu| matches!(context_menu.context_menu_data, super::node_graph::utility_types::ContextMenuData::CreateNode { compatible_type: None }))
{
self.node_graph_handler.context_menu = None;
responses.add(FrontendMessage::UpdateContextMenuInformation { context_menu_information: None });
}
// Exit one level up if inside a nested network
else if !self.breadcrumb_network_path.is_empty() {
responses.add(DocumentMessage::ExitNestedNetwork { steps_back: 1 });
}
// Close the graph view overlay if it's open
else {
responses.add(DocumentMessage::GraphViewOverlay { open: false });
}
}
DocumentMessage::ExitNestedNetwork { steps_back } => {
for _ in 0..steps_back {
self.breadcrumb_network_path.pop();
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
}
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendGraph);
responses.add(DocumentMessage::PTZUpdate);
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
}
DocumentMessage::FlipSelectedLayers { flip_axis } => {
let scale = match flip_axis {
FlipAxis::X => DVec2::new(-1., 1.),
FlipAxis::Y => DVec2::new(1., -1.),
};
if let Some([min, max]) = self.network_interface.selected_unlocked_layers_bounding_box_viewport() {
let center = (max + min) / 2.;
let bbox_trans = DAffine2::from_translation(-center);
let mut added_transaction = false;
for layer in self.network_interface.selected_nodes().selected_unlocked_layers(&self.network_interface) {
if !added_transaction {
responses.add(DocumentMessage::AddTransaction);
added_transaction = true;
}
responses.add(GraphOperationMessage::TransformChange {
layer,
transform: DAffine2::from_scale(scale),
transform_in: TransformIn::Scope { scope: bbox_trans },
skip_rerender: false,
});
}
}
}
DocumentMessage::RotateSelectedLayers { degrees } => {
// Get the bounding box of selected layers in viewport space
if let Some([min, max]) = self.network_interface.selected_unlocked_layers_bounding_box_viewport() {
// Calculate the center of the bounding box to use as rotation pivot
let center = (max + min) / 2.;
// Transform that moves pivot point to origin
let bbox_trans = DAffine2::from_translation(-center);
let mut added_transaction = false;
for layer in self.network_interface.selected_nodes().selected_unlocked_layers(&self.network_interface) {
if !added_transaction {
responses.add(DocumentMessage::AddTransaction);
added_transaction = true;
}
responses.add(GraphOperationMessage::TransformChange {
layer,
transform: DAffine2::from_angle(degrees.to_radians()),
transform_in: TransformIn::Scope { scope: bbox_trans },
skip_rerender: false,
});
}
}
}
DocumentMessage::GraphViewOverlay { open } => {
let opened = !self.graph_view_overlay_open && open;
self.graph_view_overlay_open = open;
responses.add(FrontendMessage::UpdateGraphViewOverlay { open });
responses.add(FrontendMessage::UpdateGraphFadeArtwork {
percentage: self.graph_fade_artwork_percentage,
});
// Update the tilt menu bar buttons to be disabled when the graph is open
responses.add(MenuBarMessage::SendLayout);
responses.add(DocumentMessage::RenderRulers);
responses.add(DocumentMessage::RenderScrollbars);
if opened {
responses.add(NodeGraphMessage::UnloadWires);
}
if open {
responses.add(ToolMessage::DeactivateTools);
responses.add(OverlaysMessage::Draw); // Clear the overlays
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
responses.add(NodeGraphMessage::UpdateGraphBarRight);
responses.add(NodeGraphMessage::SendGraph);
responses.add(NodeGraphMessage::UpdateHints);
responses.add(NodeGraphMessage::UpdateEdges);
} else {
responses.add(ToolMessage::ActivateTool { tool_type: *current_tool });
responses.add(OverlaysMessage::Draw); // Redraw overlays when graph is closed
}
}
DocumentMessage::GraphViewOverlayToggle => {
responses.add(DocumentMessage::GraphViewOverlay { open: !self.graph_view_overlay_open });
}
DocumentMessage::GridOptions { options } => {
self.snapping_state.grid = options;
self.snapping_state.grid_snapping = true;
responses.add(OverlaysMessage::Draw);
responses.add(PortfolioMessage::UpdateDocumentWidgets);
}
DocumentMessage::GridOverlays { context: mut overlay_context } => {
if self.snapping_state.grid_snapping {
grid_overlay(self, &mut overlay_context)
}
}
DocumentMessage::GridVisibility { visible } => {
self.snapping_state.grid_snapping = visible;
responses.add(OverlaysMessage::Draw);
}
DocumentMessage::GroupSelectedLayers { group_folder_type } => {
responses.add(DocumentMessage::AddTransaction);
let mut parent_per_selected_nodes: HashMap<LayerNodeIdentifier, Vec<NodeId>> = HashMap::new();
let artboards = LayerNodeIdentifier::ROOT_PARENT
.children(self.metadata())
.filter(|x| self.network_interface.is_artboard(&x.to_node(), &self.selection_network_path))
.collect::<Vec<_>>();
let selected_nodes = self.network_interface.selected_nodes();
// Non-artboard (infinite canvas) workflow
if artboards.is_empty() {
let Some(parent) = self.network_interface.deepest_common_ancestor(&selected_nodes, &self.selection_network_path, false) else {
return;
};
let Some(selected_nodes) = &self.network_interface.selected_nodes_in_nested_network(&self.selection_network_path) else {
return;
};
let insert_index = DocumentMessageHandler::get_calculated_insert_index(self.metadata(), selected_nodes, parent);
DocumentMessageHandler::group_layers(responses, insert_index, parent, group_folder_type, &mut self.network_interface);
}
// Artboard workflow
else {
for artboard in artboards {
let selected_descendants = artboard.descendants(self.metadata()).filter(|x| selected_nodes.selected_layers_contains(*x, self.metadata()));
for selected_descendant in selected_descendants {
parent_per_selected_nodes.entry(artboard).or_default().push(selected_descendant.to_node());
}
}
let mut new_folders: Vec<NodeId> = Vec::new();
for children in parent_per_selected_nodes.into_values() {
let child_selected_nodes = SelectedNodes(children);
let Some(parent) = self.network_interface.deepest_common_ancestor(&child_selected_nodes, &self.selection_network_path, false) else {
continue;
};
let insert_index = DocumentMessageHandler::get_calculated_insert_index(self.metadata(), &child_selected_nodes, parent);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: child_selected_nodes.0 });
new_folders.push(DocumentMessageHandler::group_layers(responses, insert_index, parent, group_folder_type, &mut self.network_interface));
}
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: new_folders });
}
}
DocumentMessage::MoveSelectedLayersTo { parent, insert_index } => {
if !self.selection_network_path.is_empty() {
log::error!("Moving selected layers is only supported for the Document Network");
return;
}
// Disallow trying to insert into self.
if self
.network_interface
.selected_nodes()
.selected_layers(self.metadata())
.any(|layer| parent.ancestors(self.metadata()).any(|ancestor| ancestor == layer))
{
return;
}
// Artboards can only have `ROOT_PARENT` as the parent.
let any_artboards = self
.network_interface
.selected_nodes()
.selected_layers(self.metadata())
.any(|layer| self.network_interface.is_artboard(&layer.to_node(), &self.selection_network_path));
if any_artboards && parent != LayerNodeIdentifier::ROOT_PARENT {
return;
}
// Non-artboards cannot be put at the top level if artboards also exist there
let selected_any_non_artboards = self
.network_interface
.selected_nodes()
.selected_layers(self.metadata())
.any(|layer| !self.network_interface.is_artboard(&layer.to_node(), &self.selection_network_path));
let top_level_artboards = LayerNodeIdentifier::ROOT_PARENT
.children(self.metadata())
.any(|layer| self.network_interface.is_artboard(&layer.to_node(), &self.selection_network_path));
if selected_any_non_artboards && parent == LayerNodeIdentifier::ROOT_PARENT && top_level_artboards {
return;
}
let layers_to_move = self.network_interface.shallowest_unique_layers_sorted(&self.selection_network_path);
// Offset the index for layers to move that are below another layer to move. For example when moving 1 and 2 between 3 and 4, 2 should be inserted at the same index as 1 since 1 is moved first.
let layers_to_move_with_insert_offset = layers_to_move
.iter()
.map(|layer| {
if layer.parent(self.metadata()) != Some(parent) {
return (*layer, 0);
}
let upstream_selected_siblings = layer
.downstream_siblings(self.network_interface.document_metadata())
.filter(|sibling| {
sibling != layer
&& layers_to_move.iter().any(|layer| {
layer == sibling
&& layer
.parent(self.metadata())
.is_some_and(|parent| parent.children(self.metadata()).position(|child| child == *layer) < Some(insert_index))
})
})
.count();
(*layer, upstream_selected_siblings)
})
.collect::<Vec<_>>();
responses.add(DocumentMessage::AddTransaction);
for (layer_index, (layer_to_move, insert_offset)) in layers_to_move_with_insert_offset.into_iter().enumerate() {
responses.add(NodeGraphMessage::MoveLayerToStack {
layer: layer_to_move,
parent,
insert_index: insert_index + layer_index - insert_offset,
});
if layer_to_move.parent(self.metadata()) != Some(parent) {
// TODO: Fix this so it works when dragging a layer into a group parent which has a Transform node, which used to work before #2689 caused this regression by removing the empty vector table row.
// TODO: See #2688 for this issue.
let layer_local_transform = self.network_interface.document_metadata().transform_to_viewport(layer_to_move);
let undo_transform = self.network_interface.document_metadata().transform_to_viewport(parent).inverse();
let transform = undo_transform * layer_local_transform;
responses.add(GraphOperationMessage::TransformSet {
layer: layer_to_move,
transform,
transform_in: TransformIn::Local,
skip_rerender: false,
});
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/mod.rs | editor/src/messages/portfolio/document/mod.rs | mod document_message;
mod document_message_handler;
pub mod data_panel;
pub mod graph_operation;
pub mod navigation;
pub mod node_graph;
pub mod overlays;
pub mod properties_panel;
pub mod utility_types;
#[doc(inline)]
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
#[doc(inline)]
pub use document_message_handler::{DocumentMessageContext, DocumentMessageHandler};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/document_message.rs | editor/src/messages/portfolio/document/document_message.rs | use std::path::PathBuf;
use super::utility_types::misc::{GroupFolderType, SnappingState};
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::portfolio::document::data_panel::DataPanelMessage;
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, OverlaysType};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
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_std::Color;
use graphene_std::raster::BlendMode;
use graphene_std::raster::Image;
use graphene_std::transform::Footprint;
use graphene_std::vector::click_target::ClickTarget;
use graphene_std::vector::style::RenderMode;
#[impl_message(Message, PortfolioMessage, Document)]
#[derive(derivative::Derivative, Clone, serde::Serialize, serde::Deserialize)]
#[derivative(Debug, PartialEq)]
pub enum DocumentMessage {
Noop,
// Sub-messages
#[child]
GraphOperation(GraphOperationMessage),
#[child]
Navigation(NavigationMessage),
#[child]
NodeGraph(NodeGraphMessage),
#[child]
Overlays(OverlaysMessage),
#[child]
PropertiesPanel(PropertiesPanelMessage),
#[child]
DataPanel(DataPanelMessage),
// Messages
AlignSelectedLayers {
axis: AlignAxis,
aggregate: AlignAggregate,
},
RemoveArtboards,
ClearLayersPanel,
CreateEmptyFolder,
DeleteNode {
node_id: NodeId,
},
DeleteSelectedLayers,
DeselectAllLayers,
DocumentHistoryBackward,
DocumentHistoryForward,
DocumentStructureChanged,
DrawArtboardOverlays {
context: OverlayContext,
},
DuplicateSelectedLayers,
EnterNestedNetwork {
node_id: NodeId,
},
Escape,
ExitNestedNetwork {
steps_back: usize,
},
FlipSelectedLayers {
flip_axis: FlipAxis,
},
RotateSelectedLayers {
degrees: f64,
},
GraphViewOverlay {
open: bool,
},
GraphViewOverlayToggle,
GridOptions {
options: GridSnapping,
},
GridOverlays {
context: OverlayContext,
},
GridVisibility {
visible: bool,
},
GroupSelectedLayers {
group_folder_type: GroupFolderType,
},
MoveSelectedLayersTo {
parent: LayerNodeIdentifier,
insert_index: usize,
},
MoveSelectedLayersToGroup {
parent: LayerNodeIdentifier,
},
NudgeSelectedLayers {
delta_x: f64,
delta_y: f64,
resize: Key,
resize_opposite_corner: Key,
},
PasteImage {
name: Option<String>,
image: Image<Color>,
mouse: Option<(f64, f64)>,
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
},
PasteSvg {
name: Option<String>,
svg: String,
mouse: Option<(f64, f64)>,
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
},
Redo,
RenameDocument {
new_name: String,
},
RenderRulers,
RenderScrollbars,
SaveDocument,
SaveDocumentAs,
SavedDocument {
path: Option<PathBuf>,
},
MarkAsSaved,
SelectParentLayer,
SelectAllLayers,
SelectedLayersLower,
SelectedLayersLowerToBack,
SelectedLayersRaise,
SelectedLayersRaiseToFront,
SelectedLayersReverse,
SelectedLayersReorder {
relative_index_offset: isize,
},
ClipLayer {
id: NodeId,
},
SelectLayer {
id: NodeId,
ctrl: bool,
shift: bool,
},
SetActivePanel {
active_panel: PanelType,
},
SetBlendModeForSelectedLayers {
blend_mode: BlendMode,
},
SetGraphFadeArtwork {
percentage: f64,
},
SetNodePinned {
node_id: NodeId,
pinned: bool,
},
SetOpacityForSelectedLayers {
opacity: f64,
},
SetFillForSelectedLayers {
fill: f64,
},
SetOverlaysVisibility {
visible: bool,
overlays_type: Option<OverlaysType>,
},
SetRangeSelectionLayer {
new_layer: Option<LayerNodeIdentifier>,
},
SetSnapping {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
closure: Option<for<'a> fn(&'a mut SnappingState) -> &'a mut bool>,
snapping_state: bool,
},
SetToNodeOrLayer {
node_id: NodeId,
is_layer: bool,
},
SetRenderMode {
render_mode: RenderMode,
},
AddTransaction,
StartTransaction,
EndTransaction,
CommitTransaction,
CancelTransaction,
AbortTransaction,
RepeatedAbortTransaction {
undo_count: usize,
},
ToggleLayerExpansion {
id: NodeId,
recursive: bool,
},
ToggleSelectedVisibility,
ToggleSelectedLocked,
ToggleGridVisibility,
ToggleOverlaysVisibility,
ToggleSnapping,
UpdateUpstreamTransforms {
upstream_footprints: HashMap<NodeId, Footprint>,
local_transforms: HashMap<NodeId, DAffine2>,
first_element_source_id: HashMap<NodeId, Option<NodeId>>,
},
UpdateClickTargets {
click_targets: HashMap<NodeId, Vec<ClickTarget>>,
},
UpdateClipTargets {
clip_targets: HashSet<NodeId>,
},
Undo,
UngroupSelectedLayers,
UngroupLayer {
layer: LayerNodeIdentifier,
},
PTZUpdate,
SelectionStepBack,
SelectionStepForward,
WrapContentInArtboard {
place_artboard_at_origin: bool,
},
ZoomCanvasTo100Percent,
ZoomCanvasTo200Percent,
ZoomCanvasToFitAll,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/misc.rs | editor/src/messages/portfolio/document/utility_types/misc.rs | use crate::consts::COLOR_OVERLAY_GRAY;
use glam::DVec2;
use graphene_std::raster::Color;
use std::fmt;
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct DocumentId(pub u64);
#[derive(PartialEq, Eq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize, Hash)]
pub enum FlipAxis {
X,
Y,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize, Hash, specta::Type)]
pub enum AlignAxis {
X,
Y,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize, Hash, specta::Type)]
pub enum AlignAggregate {
Min,
Max,
Center,
}
// #[derive(Default, PartialEq, Eq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
// pub enum DocumentMode {
// #[default]
// DesignMode,
// SelectMode,
// GuideMode,
// }
// impl fmt::Display for DocumentMode {
// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// match self {
// DocumentMode::DesignMode => write!(f, "Design Mode"),
// DocumentMode::SelectMode => write!(f, "Select Mode"),
// DocumentMode::GuideMode => write!(f, "Guide Mode"),
// }
// }
// }
// impl DocumentMode {
// pub fn icon_name(&self) -> String {
// match self {
// DocumentMode::DesignMode => "ViewportDesignMode".to_string(),
// DocumentMode::SelectMode => "ViewportSelectMode".to_string(),
// DocumentMode::GuideMode => "ViewportGuideMode".to_string(),
// }
// }
// }
/// SnappingState determines the current individual snapping states
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct SnappingState {
pub snapping_enabled: bool,
pub grid_snapping: bool,
pub artboards: bool,
pub tolerance: f64,
pub bounding_box: BoundingBoxSnapping,
pub path: PathSnapping,
pub grid: GridSnapping,
}
impl Default for SnappingState {
fn default() -> Self {
Self {
snapping_enabled: true,
grid_snapping: false,
artboards: true,
tolerance: 8.,
bounding_box: BoundingBoxSnapping::default(),
path: PathSnapping::default(),
grid: GridSnapping::default(),
}
}
}
impl SnappingState {
pub const fn target_enabled(&self, target: SnapTarget) -> bool {
if !self.snapping_enabled {
return false;
}
match target {
SnapTarget::BoundingBox(target) => match target {
BoundingBoxSnapTarget::CornerPoint => self.bounding_box.corner_point,
BoundingBoxSnapTarget::EdgeMidpoint => self.bounding_box.edge_midpoint,
BoundingBoxSnapTarget::CenterPoint => self.bounding_box.center_point,
},
SnapTarget::Path(target) => match target {
PathSnapTarget::AnchorPointWithColinearHandles | PathSnapTarget::AnchorPointWithFreeHandles => self.path.anchor_point,
PathSnapTarget::LineMidpoint => self.path.line_midpoint,
PathSnapTarget::AlongPath => self.path.along_path,
PathSnapTarget::NormalToPath => self.path.normal_to_path,
PathSnapTarget::TangentToPath => self.path.tangent_to_path,
PathSnapTarget::IntersectionPoint => self.path.path_intersection_point,
PathSnapTarget::PerpendicularToEndpoint => self.path.perpendicular_from_endpoint,
},
SnapTarget::Artboard(_) => self.artboards,
SnapTarget::Grid(_) => self.grid_snapping,
SnapTarget::Alignment(AlignmentSnapTarget::AlignWithAnchorPoint) => self.path.align_with_anchor_point,
SnapTarget::Alignment(_) => self.bounding_box.align_with_edges,
SnapTarget::DistributeEvenly(_) => self.bounding_box.distribute_evenly,
_ => false,
}
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct BoundingBoxSnapping {
pub center_point: bool,
pub corner_point: bool,
pub edge_midpoint: bool,
pub align_with_edges: bool,
pub distribute_evenly: bool,
}
impl Default for BoundingBoxSnapping {
fn default() -> Self {
Self {
center_point: true,
corner_point: true,
edge_midpoint: true,
align_with_edges: true,
distribute_evenly: true,
}
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct PathSnapping {
pub anchor_point: bool,
pub line_midpoint: bool,
pub along_path: bool,
pub normal_to_path: bool,
pub tangent_to_path: bool,
pub path_intersection_point: bool,
pub align_with_anchor_point: bool, // TODO: Rename
pub perpendicular_from_endpoint: bool,
}
impl Default for PathSnapping {
fn default() -> Self {
Self {
anchor_point: true,
line_midpoint: true,
along_path: true,
normal_to_path: true,
tangent_to_path: true,
path_intersection_point: true,
align_with_anchor_point: true,
perpendicular_from_endpoint: true,
}
}
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize, PartialEq)]
pub enum GridType {
#[serde(alias = "Rectangle")]
Rectangular {
spacing: DVec2,
},
Isometric {
y_axis_spacing: f64,
angle_a: f64,
angle_b: f64,
},
}
impl Default for GridType {
fn default() -> Self {
Self::Rectangular { spacing: DVec2::ONE }
}
}
impl GridType {
pub fn rectangular_spacing(&mut self) -> Option<&mut DVec2> {
match self {
Self::Rectangular { spacing } => Some(spacing),
_ => None,
}
}
pub fn isometric_y_spacing(&mut self) -> Option<&mut f64> {
match self {
Self::Isometric { y_axis_spacing, .. } => Some(y_axis_spacing),
_ => None,
}
}
pub fn angle_a(&mut self) -> Option<&mut f64> {
match self {
Self::Isometric { angle_a, .. } => Some(angle_a),
_ => None,
}
}
pub fn angle_b(&mut self) -> Option<&mut f64> {
match self {
Self::Isometric { angle_b, .. } => Some(angle_b),
_ => None,
}
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(default)]
pub struct GridSnapping {
pub origin: DVec2,
pub grid_type: GridType,
pub rectangular_spacing: DVec2,
pub isometric_y_spacing: f64,
pub isometric_angle_a: f64,
pub isometric_angle_b: f64,
pub grid_color: Color,
pub dot_display: bool,
}
impl Default for GridSnapping {
fn default() -> Self {
Self {
origin: DVec2::ZERO,
grid_type: Default::default(),
rectangular_spacing: DVec2::ONE,
isometric_y_spacing: 1.,
isometric_angle_a: 30.,
isometric_angle_b: 30.,
grid_color: Color::from_rgb_str(COLOR_OVERLAY_GRAY.strip_prefix('#').unwrap()).unwrap(),
dot_display: false,
}
}
}
impl GridSnapping {
// Double grid size until it takes up at least 10px.
pub fn compute_rectangle_spacing(mut size: DVec2, navigation: &PTZ) -> Option<DVec2> {
let mut iterations = 0;
size = size.abs();
while (size * navigation.zoom()).cmplt(DVec2::splat(10.)).any() {
if iterations > 100 {
return None;
}
size *= 2.;
iterations += 1;
}
Some(size)
}
// Double grid size until it takes up at least 10px.
pub fn compute_isometric_multiplier(length: f64, divisor: f64, navigation: &PTZ) -> Option<f64> {
let length = length.abs();
let mut iterations = 0;
let mut multiplier = 1.;
while (length / divisor.abs().max(1.)) * multiplier * navigation.zoom() < 10. {
if iterations > 100 {
return None;
}
multiplier *= 2.;
iterations += 1;
}
Some(multiplier)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoundingBoxSnapSource {
CornerPoint,
CenterPoint,
EdgeMidpoint,
}
impl fmt::Display for BoundingBoxSnapSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BoundingBoxSnapSource::CornerPoint => write!(f, "Bounding Box: Corner Point"),
BoundingBoxSnapSource::CenterPoint => write!(f, "Bounding Box: Center Point"),
BoundingBoxSnapSource::EdgeMidpoint => write!(f, "Bounding Box: Edge Midpoint"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArtboardSnapSource {
CornerPoint,
CenterPoint,
}
impl fmt::Display for ArtboardSnapSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ArtboardSnapSource::CornerPoint => write!(f, "Artboard: Corner Point"),
ArtboardSnapSource::CenterPoint => write!(f, "Artboard: Center Point"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathSnapSource {
AnchorPointWithColinearHandles,
AnchorPointWithFreeHandles,
HandlePoint,
LineMidpoint,
IntersectionPoint,
}
impl fmt::Display for PathSnapSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PathSnapSource::AnchorPointWithColinearHandles | PathSnapSource::AnchorPointWithFreeHandles => write!(f, "Path: Anchor Point"),
PathSnapSource::HandlePoint => write!(f, "Path: Handle Point"),
PathSnapSource::LineMidpoint => write!(f, "Path: Line Midpoint"),
PathSnapSource::IntersectionPoint => write!(f, "Path: Intersection Point"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlignmentSnapSource {
BoundingBoxCornerPoint,
BoundingBoxCenterPoint,
BoundingBoxEdgeMidpoint,
ArtboardCornerPoint,
ArtboardCenterPoint,
}
impl fmt::Display for AlignmentSnapSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AlignmentSnapSource::BoundingBoxCornerPoint => write!(f, "{}", BoundingBoxSnapSource::CornerPoint),
AlignmentSnapSource::BoundingBoxCenterPoint => write!(f, "{}", BoundingBoxSnapSource::CenterPoint),
AlignmentSnapSource::BoundingBoxEdgeMidpoint => write!(f, "{}", BoundingBoxSnapSource::EdgeMidpoint),
AlignmentSnapSource::ArtboardCornerPoint => write!(f, "{}", ArtboardSnapSource::CornerPoint),
AlignmentSnapSource::ArtboardCenterPoint => write!(f, "{}", ArtboardSnapSource::CenterPoint),
}
}
}
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum SnapSource {
#[default]
None,
BoundingBox(BoundingBoxSnapSource),
Artboard(ArtboardSnapSource),
Path(PathSnapSource),
Alignment(AlignmentSnapSource),
}
impl SnapSource {
pub fn is_some(&self) -> bool {
self != &Self::None
}
pub fn bounding_box(&self) -> bool {
matches!(self, Self::BoundingBox(_) | Self::Artboard(_))
}
pub fn align(&self) -> bool {
matches!(self, Self::Alignment(_))
}
pub fn center(&self) -> bool {
matches!(
self,
Self::Alignment(AlignmentSnapSource::ArtboardCenterPoint | AlignmentSnapSource::BoundingBoxCenterPoint)
| Self::Artboard(ArtboardSnapSource::CenterPoint)
| Self::BoundingBox(BoundingBoxSnapSource::CenterPoint)
)
}
}
impl fmt::Display for SnapSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SnapSource::None => write!(f, "None"),
SnapSource::BoundingBox(bounding_box_snap_source) => write!(f, "{bounding_box_snap_source}"),
SnapSource::Artboard(artboard_snap_source) => write!(f, "{artboard_snap_source}"),
SnapSource::Path(path_snap_source) => write!(f, "{path_snap_source}"),
SnapSource::Alignment(alignment_snap_source) => write!(f, "{alignment_snap_source}"),
}
}
}
type GetSnapState = for<'a> fn(&'a mut SnappingState) -> &'a mut bool;
pub const SNAP_FUNCTIONS_FOR_BOUNDING_BOXES: [(&str, GetSnapState, &str); 5] = [
(
"Align with Edges",
(|snapping_state| &mut snapping_state.bounding_box.align_with_edges) as GetSnapState,
"Snaps to horizontal/vertical alignment with the edges of any layer's bounding box.",
),
(
"Corner Points",
(|snapping_state| &mut snapping_state.bounding_box.corner_point) as GetSnapState,
"Snaps to the four corners of any layer's bounding box.",
),
(
"Center Points",
(|snapping_state| &mut snapping_state.bounding_box.center_point) as GetSnapState,
"Snaps to the center point of any layer's bounding box.",
),
(
"Edge Midpoints",
(|snapping_state| &mut snapping_state.bounding_box.edge_midpoint) as GetSnapState,
"Snaps to any of the four points at the middle of the edges of any layer's bounding box.",
),
(
"Distribute Evenly",
(|snapping_state| &mut snapping_state.bounding_box.distribute_evenly) as GetSnapState,
"Snaps to a consistent distance offset established by the bounding boxes of nearby layers.",
),
];
pub const SNAP_FUNCTIONS_FOR_PATHS: [(&str, GetSnapState, &str); 7] = [
(
"Align with Anchor Points",
(|snapping_state: &mut SnappingState| &mut snapping_state.path.align_with_anchor_point) as GetSnapState,
"Snaps to horizontal/vertical alignment with the anchor points of any vector path.",
),
(
"Anchor Points",
(|snapping_state: &mut SnappingState| &mut snapping_state.path.anchor_point) as GetSnapState,
"Snaps to the anchor point of any vector path.",
),
(
// TODO: Extend to the midpoints of curved segments and rename to "Segment Midpoint"
"Line Midpoints",
(|snapping_state: &mut SnappingState| &mut snapping_state.path.line_midpoint) as GetSnapState,
"Snaps to the point at the middle of any straight line segment of a vector path.",
),
(
"Path Intersection Points",
(|snapping_state: &mut SnappingState| &mut snapping_state.path.path_intersection_point) as GetSnapState,
"Snaps to any points where vector paths intersect.",
),
(
"Along Paths",
(|snapping_state: &mut SnappingState| &mut snapping_state.path.along_path) as GetSnapState,
"Snaps along the length of any vector path.",
),
(
// TODO: This works correctly for line segments, but not curved segments.
// TODO: Therefore, we should make this use the normal in relation to the incoming curve, not the straight line between the incoming curve's start point and the path.
"Normal to Paths",
(|snapping_state: &mut SnappingState| &mut snapping_state.path.normal_to_path) as GetSnapState,
// TODO: Fix the bug/limitation that requires 'Intersections of Paths' to be enabled
"Snaps a line to a point perpendicular to a vector path.\n(Due to a bug, 'Intersections of Paths' must be enabled.)",
),
(
// TODO: This works correctly for line segments, but not curved segments.
// TODO: Therefore, we should make this use the tangent in relation to the incoming curve, not the straight line between the incoming curve's start point and the path.
"Tangent to Paths",
(|snapping_state: &mut SnappingState| &mut snapping_state.path.tangent_to_path) as GetSnapState,
// TODO: Fix the bug/limitation that requires 'Intersections of Paths' to be enabled
"Snaps a line to a point tangent to a vector path.\n(Due to a bug, 'Intersections of Paths' must be enabled.)",
),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum BoundingBoxSnapTarget {
CornerPoint,
CenterPoint,
EdgeMidpoint,
}
impl fmt::Display for BoundingBoxSnapTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BoundingBoxSnapTarget::CornerPoint => write!(f, "Bounding Box: Corner Point"),
BoundingBoxSnapTarget::CenterPoint => write!(f, "Bounding Box: Center Point"),
BoundingBoxSnapTarget::EdgeMidpoint => write!(f, "Bounding Box: Edge Midpoint"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PathSnapTarget {
AnchorPointWithColinearHandles,
AnchorPointWithFreeHandles,
LineMidpoint,
AlongPath,
NormalToPath,
TangentToPath,
IntersectionPoint,
PerpendicularToEndpoint,
}
impl fmt::Display for PathSnapTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PathSnapTarget::AnchorPointWithColinearHandles | PathSnapTarget::AnchorPointWithFreeHandles => write!(f, "Path: Anchor Point"),
PathSnapTarget::LineMidpoint => write!(f, "Path: Line Midpoint"),
PathSnapTarget::AlongPath => write!(f, "Path: Along Path"),
PathSnapTarget::NormalToPath => write!(f, "Path: Normal to Path"),
PathSnapTarget::TangentToPath => write!(f, "Path: Tangent to Path"),
PathSnapTarget::IntersectionPoint => write!(f, "Path: Intersection Point"),
PathSnapTarget::PerpendicularToEndpoint => write!(f, "Path: Perp. to Endpoint"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArtboardSnapTarget {
CornerPoint,
CenterPoint,
AlongEdge,
}
impl fmt::Display for ArtboardSnapTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ArtboardSnapTarget::CornerPoint => write!(f, "Artboard: Corner Point"),
ArtboardSnapTarget::CenterPoint => write!(f, "Artboard: Center Point"),
ArtboardSnapTarget::AlongEdge => write!(f, "Artboard: Along Edge"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GridSnapTarget {
Line,
LineNormal,
Intersection,
}
impl fmt::Display for GridSnapTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GridSnapTarget::Line => write!(f, "Grid: Along Line"),
GridSnapTarget::LineNormal => write!(f, "Grid: Normal to Line"),
GridSnapTarget::Intersection => write!(f, "Grid: Intersection Point"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlignmentSnapTarget {
BoundingBoxCornerPoint,
BoundingBoxCenterPoint,
ArtboardCornerPoint,
ArtboardCenterPoint,
AlignWithAnchorPoint,
IntersectionPoint,
PerpendicularToEndpoint,
}
impl fmt::Display for AlignmentSnapTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AlignmentSnapTarget::BoundingBoxCornerPoint => write!(f, "{}", BoundingBoxSnapTarget::CornerPoint),
AlignmentSnapTarget::BoundingBoxCenterPoint => write!(f, "{}", BoundingBoxSnapTarget::CenterPoint),
AlignmentSnapTarget::ArtboardCornerPoint => write!(f, "{}", ArtboardSnapTarget::CornerPoint),
AlignmentSnapTarget::ArtboardCenterPoint => write!(f, "{}", ArtboardSnapTarget::CenterPoint),
AlignmentSnapTarget::AlignWithAnchorPoint => write!(f, "{}", PathSnapTarget::AnchorPointWithColinearHandles),
AlignmentSnapTarget::IntersectionPoint => write!(f, "{}", PathSnapTarget::IntersectionPoint),
AlignmentSnapTarget::PerpendicularToEndpoint => write!(f, "{}", PathSnapTarget::PerpendicularToEndpoint),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DistributionSnapTarget {
X,
Y,
Right,
Left,
Up,
Down,
XY,
}
impl fmt::Display for DistributionSnapTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DistributionSnapTarget::X => write!(f, "Distribute: X"),
DistributionSnapTarget::Y => write!(f, "Distribute: Y"),
DistributionSnapTarget::Right => write!(f, "Distribute: Right"),
DistributionSnapTarget::Left => write!(f, "Distribute: Left"),
DistributionSnapTarget::Up => write!(f, "Distribute: Up"),
DistributionSnapTarget::Down => write!(f, "Distribute: Down"),
DistributionSnapTarget::XY => write!(f, "Distribute: XY"),
}
}
}
impl DistributionSnapTarget {
pub const fn is_x(&self) -> bool {
matches!(self, Self::Left | Self::Right | Self::X)
}
pub const fn is_y(&self) -> bool {
matches!(self, Self::Up | Self::Down | Self::Y)
}
}
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum SnapTarget {
#[default]
None,
BoundingBox(BoundingBoxSnapTarget),
Path(PathSnapTarget),
Artboard(ArtboardSnapTarget),
Grid(GridSnapTarget),
Alignment(AlignmentSnapTarget),
DistributeEvenly(DistributionSnapTarget),
}
impl SnapTarget {
pub fn is_some(&self) -> bool {
self != &Self::None
}
pub fn bounding_box(&self) -> bool {
matches!(self, Self::BoundingBox(_) | Self::Artboard(_))
}
}
impl fmt::Display for SnapTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SnapTarget::None => write!(f, "None"),
SnapTarget::BoundingBox(bounding_box_snap_target) => write!(f, "{bounding_box_snap_target}"),
SnapTarget::Path(path_snap_target) => write!(f, "{path_snap_target}"),
SnapTarget::Artboard(artboard_snap_target) => write!(f, "{artboard_snap_target}"),
SnapTarget::Grid(grid_snap_target) => write!(f, "{grid_snap_target}"),
SnapTarget::Alignment(alignment_snap_target) => write!(f, "{alignment_snap_target}"),
SnapTarget::DistributeEvenly(distribution_snap_target) => write!(f, "{distribution_snap_target}"),
}
}
}
// TODO: implement icons for SnappingOptions eventually
pub enum SnappingOptions {
BoundingBoxes,
Paths,
}
impl fmt::Display for SnappingOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SnappingOptions::BoundingBoxes => write!(f, "Bounding Boxes"),
SnappingOptions::Paths => write!(f, "Paths"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct PTZ {
/// Offset distance.
pub pan: DVec2,
/// Angle in radians.
tilt: f64,
/// Scale factor.
zoom: f64,
/// Flipped status.
pub flip: bool,
}
impl Default for PTZ {
fn default() -> Self {
Self {
pan: DVec2::ZERO,
tilt: 0.,
zoom: 1.,
flip: false,
}
}
}
impl PTZ {
/// Get the tilt angle between -180Β° and 180Β° in radians.
pub fn tilt(&self) -> f64 {
(((self.tilt + std::f64::consts::PI) % std::f64::consts::TAU) + std::f64::consts::TAU) % std::f64::consts::TAU - std::f64::consts::PI
}
pub fn unmodified_tilt(&self) -> f64 {
self.tilt
}
/// Set a new tilt angle in radians.
pub fn set_tilt(&mut self, tilt: f64) {
self.tilt = tilt;
}
/// Get the scale factor.
pub fn zoom(&self) -> f64 {
self.zoom
}
/// Set a new scale factor.
pub fn set_zoom(&mut self, zoom: f64) {
self.zoom = zoom.clamp(crate::consts::VIEWPORT_ZOOM_SCALE_MIN, crate::consts::VIEWPORT_ZOOM_SCALE_MAX)
}
}
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum GroupFolderType {
Layer,
BooleanOperation(graphene_std::path_bool::BooleanOperation),
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/clipboards.rs | editor/src/messages/portfolio/document/utility_types/clipboards.rs | use super::network_interface::NodeTemplate;
use graph_craft::document::NodeId;
#[repr(u8)]
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, Debug, specta::Type)]
pub enum Clipboard {
Internal,
Device,
_InternalClipboardCount, // Keep this as the last entry of **internal** clipboards since it is used for counting the number of enum variants
}
pub const INTERNAL_CLIPBOARD_COUNT: u8 = Clipboard::_InternalClipboardCount as u8;
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct CopyBufferEntry {
pub nodes: Vec<(NodeId, NodeTemplate)>,
pub selected: bool,
pub visible: bool,
pub locked: bool,
pub collapsed: bool,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/network_interface.rs | editor/src/messages/portfolio/document/utility_types/network_interface.rs | mod deserialization;
mod memo_network;
mod resolved_types;
use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelations};
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::{DocumentNodeDefinition, resolve_document_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{Direction, FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
use crate::messages::portfolio::document::overlays::utility_functions::text_width;
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
use deserialization::deserialize_node_persistent_metadata;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::Type;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graphene_std::ContextDependencies;
use graphene_std::math::quad::Quad;
use graphene_std::subpath::Subpath;
use graphene_std::transform::Footprint;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::{PointId, Vector, VectorModificationType};
use kurbo::BezPath;
use memo_network::MemoNetwork;
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hash;
use std::ops::Deref;
/// All network modifications should be done through this API, so the fields cannot be public. However, all fields within this struct can be public since it it not possible to have a public mutable reference.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct NodeNetworkInterface {
/// The node graph that generates this document's artwork. It recursively stores its sub-graphs, so this root graph is the whole snapshot of the document content.
/// A public mutable reference should never be created. It should only be mutated through custom setters which perform the necessary side effects to keep network_metadata in sync
network: MemoNetwork,
/// Stores all editor information for a NodeNetwork. Should automatically kept in sync by the setter methods when changes to the document network are made.
network_metadata: NodeNetworkMetadata,
// TODO: Wrap in TransientMetadata Option
/// Stores the document network's structural topology. Should automatically kept in sync by the setter methods when changes to the document network are made.
#[serde(skip)]
document_metadata: DocumentMetadata,
/// All input/output types based on the compiled network.
#[serde(skip)]
pub resolved_types: ResolvedDocumentNodeTypes,
#[serde(skip)]
transaction_status: TransactionStatus,
}
impl Clone for NodeNetworkInterface {
fn clone(&self) -> Self {
Self {
network: self.network.clone(),
network_metadata: self.network_metadata.clone(),
document_metadata: Default::default(),
resolved_types: Default::default(),
transaction_status: TransactionStatus::Finished,
}
}
}
impl PartialEq for NodeNetworkInterface {
fn eq(&self, other: &Self) -> bool {
self.network == other.network && self.network_metadata == other.network_metadata
}
}
impl NodeNetworkInterface {
/// Add DocumentNodePath input to the PathModifyNode protonode
pub fn migrate_path_modify_node(&mut self) {
fix_network(self.document_network_mut());
fn fix_network(network: &mut NodeNetwork) {
for node in network.nodes.values_mut() {
if let Some(network) = node.implementation.get_network_mut() {
fix_network(network);
}
if let DocumentNodeImplementation::ProtoNode(protonode) = &node.implementation
&& protonode.name.contains("PathModifyNode")
&& node.inputs.len() < 3
{
node.inputs.push(NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath));
}
}
}
}
}
// Public immutable getters for the network interface
impl NodeNetworkInterface {
/// Gets the network of the root document
pub fn document_network(&self) -> &NodeNetwork {
self.network.network()
}
pub fn document_network_mut(&mut self) -> &mut NodeNetwork {
self.network.network_mut()
}
/// Gets the nested network based on network_path
pub fn nested_network(&self, network_path: &[NodeId]) -> Option<&NodeNetwork> {
let Some(network) = self.document_network().nested_network(network_path) else {
log::error!("Could not get nested network with path {network_path:?} in NodeNetworkInterface::network");
return None;
};
Some(network)
}
pub fn network_hash(&self) -> u64 {
self.network.current_hash()
}
/// Get the specified document node in the nested network based on node_id and network_path
pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
let network = self.nested_network(network_path)?;
let Some(node_metadata) = network.nodes.get(node_id) else {
log::error!("Could not get document node with id {node_id} in network {network_path:?}");
return None;
};
Some(node_metadata)
}
pub fn node_metadata(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeMetadata> {
let network_metadata = self.network_metadata(network_path)?;
let Some(node_metadata) = network_metadata.persistent_metadata.node_metadata.get(node_id) else {
log::error!("Could not get node metadata for node {node_id} in network {network_path:?}");
return None;
};
Some(node_metadata)
}
pub fn document_network_metadata(&self) -> &NodeNetworkMetadata {
&self.network_metadata
}
/// The network metadata should always exist for the current network
pub fn network_metadata(&self, network_path: &[NodeId]) -> Option<&NodeNetworkMetadata> {
let Some(network_metadata) = self.network_metadata.nested_metadata(network_path) else {
log::error!("Could not get nested network_metadata with path {network_path:?}");
return None;
};
Some(network_metadata)
}
pub fn document_metadata(&self) -> &DocumentMetadata {
&self.document_metadata
}
pub fn transaction_status(&self) -> TransactionStatus {
self.transaction_status
}
pub fn selected_nodes(&self) -> SelectedNodes {
self.selected_nodes_in_nested_network(&[]).unwrap_or_default()
}
/// Get the selected nodes for the network at the network_path
pub fn selected_nodes_in_nested_network(&self, network_path: &[NodeId]) -> Option<SelectedNodes> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in selected_nodes");
return None;
};
Some(
network_metadata
.persistent_metadata
.selection_undo_history
.back()
.cloned()
.unwrap_or_default()
.filtered_selected_nodes(|node_id| network_metadata.persistent_metadata.node_metadata.contains_key(node_id)),
)
}
/// Get the network which the encapsulating node of the currently viewed network is part of. Will always be None in the document network.
pub fn encapsulating_network_metadata(&self, network_path: &[NodeId]) -> Option<&NodeNetworkMetadata> {
let mut encapsulating_path = network_path.to_vec();
encapsulating_path.pop()?;
let Some(parent_metadata) = self.network_metadata(&encapsulating_path) else {
log::error!("Could not get parent network in encapsulating_node_metadata");
return None;
};
Some(parent_metadata)
}
/// Get the node which encapsulates the currently viewed network. Will always be None in the document network.
pub fn encapsulating_node(&self, network_path: &[NodeId]) -> Option<&DocumentNode> {
let mut encapsulating_path = network_path.to_vec();
let encapsulating_node_id = encapsulating_path.pop()?;
let Some(encapsulating_node) = self.document_node(&encapsulating_node_id, &encapsulating_path) else {
log::error!("Could not get encapsulating node in encapsulating_node");
return None;
};
Some(encapsulating_node)
}
/// Get the node metadata for the node which encapsulates the currently viewed network. Will always be None in the document network.
pub fn encapsulating_node_metadata(&self, network_path: &[NodeId]) -> Option<&DocumentNodeMetadata> {
let mut encapsulating_path = network_path.to_vec();
let encapsulating_node_id = encapsulating_path.pop()?;
let Some(parent_metadata) = self.network_metadata(&encapsulating_path) else {
log::error!("Could not get parent network in encapsulating_node_metadata");
return None;
};
let Some(encapsulating_node_metadata) = parent_metadata.persistent_metadata.node_metadata.get(&encapsulating_node_id) else {
log::error!("Could not get encapsulating node metadata in encapsulating_node_metadata");
return None;
};
Some(encapsulating_node_metadata)
}
/// Returns the first downstream layer(inclusive) from a node. If the node is a layer, it will return itself.
pub fn downstream_layer_for_chain_node(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<NodeId> {
let mut id = *node_id;
while !self.is_layer(&id, network_path) {
id = self.outward_wires(network_path)?.get(&OutputConnector::node(id, 0))?.first()?.node_id()?;
}
Some(id)
}
/// Returns all downstream layers (inclusive) from a node. If the node is a layer, it will return itself.
pub fn downstream_layers(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
let mut stack = vec![*node_id];
let mut layers = Vec::new();
while let Some(current_node) = stack.pop() {
if self.is_layer(¤t_node, network_path) {
layers.push(current_node);
} else {
let Some(outward_wires) = self.outward_wires(network_path).and_then(|outward_wires| outward_wires.get(&OutputConnector::node(current_node, 0))) else {
log::error!("Could not get outward wires in downstream_layer");
return Vec::new();
};
stack.extend(outward_wires.iter().filter_map(|input_connector| input_connector.node_id()));
}
}
layers
}
pub fn chain_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
if self.number_of_displayed_inputs(node_id, network_path) > 1 {
let mut last_chain_node_distance = 0u32;
// Iterate upstream from the layer, and get the number of nodes distance to the last node with Position::Chain
for (index, node_id) in self
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalPrimaryOutputFlow)
.skip(1)
.enumerate()
.collect::<Vec<_>>()
{
// Check if the node is positioned as a chain
if self.is_chain(&node_id, network_path) {
last_chain_node_distance = (index as u32) + 1;
} else {
return last_chain_node_distance * 7 + 1;
}
}
last_chain_node_distance * 7 + 1
} else {
// Layer with no inputs has no chain
0
}
}
/// Check if the specified node id is connected to the output
pub fn connected_to_output(&self, target_node_id: &NodeId, network_path: &[NodeId]) -> bool {
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get network in connected_to_output");
return false;
};
// If the node is the output then return true
if network
.exports
.iter()
.any(|export| if let NodeInput::Node { node_id, .. } = export { node_id == target_node_id } else { false })
{
return true;
}
// Get the outputs
let mut stack = network
.exports
.iter()
.filter_map(|output| if let NodeInput::Node { node_id, .. } = output { network.nodes.get(node_id) } else { None })
.collect::<Vec<_>>();
let mut already_visited = HashSet::new();
already_visited.extend(
network
.exports
.iter()
.filter_map(|output| if let NodeInput::Node { node_id, .. } = output { Some(node_id) } else { None }),
);
while let Some(node) = stack.pop() {
for input in &node.inputs {
if let &NodeInput::Node { node_id: ref_id, .. } = input {
// Skip if already viewed
if already_visited.contains(&ref_id) {
continue;
}
// If the target node is used as input then return true
if ref_id == *target_node_id {
return true;
}
// Add the referenced node to the stack
let Some(ref_node) = network.nodes.get(&ref_id) else {
continue;
};
already_visited.insert(ref_id);
stack.push(ref_node);
}
}
}
false
}
pub fn number_of_imports(&self, network_path: &[NodeId]) -> usize {
// TODO: Use network.import_types.len()
if let Some(encapsulating_node) = self.encapsulating_node(network_path) {
encapsulating_node.inputs.len()
} else {
0
}
}
pub fn number_of_exports(&self, network_path: &[NodeId]) -> usize {
if let Some(network) = self.nested_network(network_path) { network.exports.len() } else { 0 }
}
fn number_of_displayed_inputs(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
let Some(node) = self.document_node(node_id, network_path) else {
log::error!("Could not get node {node_id} in number_of_displayed_inputs");
return 0;
};
node.inputs.iter().filter(|input| input.is_exposed()).count()
}
pub fn number_of_inputs(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
let Some(node) = self.document_node(node_id, network_path) else {
log::error!("Could not get node {node_id} in number_of_inputs");
return 0;
};
node.inputs.len()
}
pub fn number_of_outputs(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
let Some(implementation) = self.implementation(node_id, network_path) else {
log::error!("Could not get node {node_id} in number_of_outputs");
return 0;
};
match &implementation {
DocumentNodeImplementation::ProtoNode(_) => 1,
DocumentNodeImplementation::Network(nested_network) => nested_network.exports.len(),
DocumentNodeImplementation::Extract => 1,
}
}
/// Creates a copy for each node by disconnecting nodes which are not connected to other copied nodes.
/// Returns an iterator of all persistent metadata for a node and their ids
pub fn copy_nodes<'a>(&'a mut self, new_ids: &'a HashMap<NodeId, NodeId>, network_path: &'a [NodeId]) -> impl Iterator<Item = (NodeId, NodeTemplate)> + 'a {
let mut new_nodes = new_ids
.iter()
.filter_map(|(node_id, &new)| {
self.create_node_template(node_id, network_path).and_then(|mut node_template| {
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in copy_nodes");
return None;
};
// TODO: Get downstream connections from all outputs
let mut downstream_connections = outward_wires.get(&OutputConnector::node(*node_id, 0)).map_or([].iter(), |outputs| outputs.iter());
let has_selected_node_downstream = downstream_connections.any(|input_connector| input_connector.node_id().is_some_and(|upstream_id| new_ids.keys().any(|key| *key == upstream_id)));
// If the copied node does not have a downstream connection to another copied node, then set the position to absolute
if !has_selected_node_downstream {
let Some(position) = self.position(node_id, network_path) else {
log::error!("Could not get position in create_node_template");
return None;
};
match &mut node_template.persistent_node_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => layer_metadata.position = LayerPosition::Absolute(position),
NodeTypePersistentMetadata::Node(node_metadata) => node_metadata.position = NodePosition::Absolute(position),
};
}
// If a chain node does not have a selected downstream layer, then set the position to absolute
let downstream_layer = self.downstream_layer_for_chain_node(node_id, network_path);
if downstream_layer.is_none_or(|downstream_layer| new_ids.keys().all(|key| *key != downstream_layer)) {
let Some(position) = self.position(node_id, network_path) else {
log::error!("Could not get position in create_node_template");
return None;
};
node_template.persistent_node_metadata.node_type_metadata = NodeTypePersistentMetadata::Node(NodePersistentMetadata {
position: NodePosition::Absolute(position),
});
}
// Shift all absolute nodes 2 to the right and 2 down
// TODO: Remove 2x2 offset and replace with layout system to find space for new node
match &mut node_template.persistent_node_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => {
if let LayerPosition::Absolute(position) = &mut layer_metadata.position {
*position += IVec2::new(2, 2)
}
}
NodeTypePersistentMetadata::Node(node_metadata) => {
if let NodePosition::Absolute(position) = &mut node_metadata.position {
*position += IVec2::new(2, 2)
}
}
}
Some((new, *node_id, node_template))
})
})
.collect::<Vec<_>>();
for old_id in new_nodes.iter().map(|(_, old_id, _)| *old_id).collect::<Vec<_>>() {
// Try set all selected nodes upstream of a layer to be chain nodes
if self.is_layer(&old_id, network_path) {
for valid_upstream_chain_node in self.valid_upstream_chain_nodes(&InputConnector::node(old_id, 1), network_path) {
if let Some(node_template) = new_nodes.iter_mut().find_map(|(_, old_id, template)| (*old_id == valid_upstream_chain_node).then_some(template)) {
match &mut node_template.persistent_node_metadata.node_type_metadata {
NodeTypePersistentMetadata::Node(node_metadata) => node_metadata.position = NodePosition::Chain,
NodeTypePersistentMetadata::Layer(_) => log::error!("Node cannot be a layer"),
};
}
}
}
}
new_nodes.into_iter().map(move |(new, node_id, node)| (new, self.map_ids(node, &node_id, new_ids, network_path)))
}
/// Create a node template from an existing node.
pub fn create_node_template(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<NodeTemplate> {
let Some(node) = self.document_node(node_id, network_path) else {
log::error!("Could not get node {node_id} in create_node_template");
return None;
};
let Some(node_metadata) = self.node_metadata(node_id, network_path).cloned() else {
log::error!("Could not get node_metadata in create_node_template");
return None;
};
Some(NodeTemplate {
persistent_node_metadata: node_metadata.persistent_metadata,
document_node: node.clone(),
})
}
/// Converts all node id inputs to a new id based on a HashMap.
///
/// If the node is not in the hashmap then a default input is found based on the compiled network, using the node_id passed as a parameter
pub fn map_ids(&mut self, mut node_template: NodeTemplate, node_id: &NodeId, new_ids: &HashMap<NodeId, NodeId>, network_path: &[NodeId]) -> NodeTemplate {
for (input_index, input) in node_template.document_node.inputs.iter_mut().enumerate() {
if let &mut NodeInput::Node { node_id: id, output_index } = input {
if let Some(&new_id) = new_ids.get(&id) {
*input = NodeInput::Node { node_id: new_id, output_index };
} else {
// Disconnect node input if it is not connected to another node in new_ids
let tagged_value = self.tagged_value_from_input(&InputConnector::node(*node_id, input_index), network_path);
*input = NodeInput::value(tagged_value, true);
}
} else if let &mut NodeInput::Import { .. } = input {
// Always disconnect network node input
let tagged_value = self.tagged_value_from_input(&InputConnector::node(*node_id, input_index), network_path);
*input = NodeInput::value(tagged_value, true);
}
}
node_template
}
/// Try and get the [`DocumentNodeDefinition`] for a node
pub fn get_node_definition(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeDefinition> {
let metadata = self.node_metadata(node_id, network_path)?;
resolve_document_node_type(metadata.persistent_metadata.reference.as_ref()?)
}
pub fn input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<&NodeInput> {
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get network in input_from_connector");
return None;
};
match input_connector {
InputConnector::Node { node_id, input_index } => {
let Some(node) = network.nodes.get(node_id) else {
log::error!("Could not get node {node_id} in input_from_connector");
return None;
};
node.inputs.get(*input_index)
}
InputConnector::Export(export_index) => network.exports.get(*export_index),
}
}
pub fn position(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
let top_left_position = self
.node_click_targets(node_id, network_path)
.and_then(|click_targets| click_targets.node_click_target.bounding_box())
.map(|mut bounding_box| {
if !self.is_layer(node_id, network_path) {
bounding_box[0] -= DVec2::new(0., 12.);
}
(bounding_box[0] / 24.).as_ivec2()
});
top_left_position.map(|position| {
if self.is_layer(node_id, network_path) {
position + IVec2::new(self.chain_width(node_id, network_path) as i32, 0)
} else {
position
}
})
}
pub fn frontend_imports(&mut self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
match network_path.split_last() {
Some((node_id, encapsulating_network_path)) => {
let Some(node) = self.document_node(node_id, encapsulating_network_path) else {
log::error!("Could not get node {node_id} in network {encapsulating_network_path:?}");
return Vec::new();
};
let mut frontend_imports = (0..node.inputs.len())
.map(|import_index| self.frontend_output_from_connector(&OutputConnector::Import(import_index), network_path))
.collect::<Vec<_>>();
if frontend_imports.is_empty() {
frontend_imports.push(None);
}
frontend_imports
}
// In the document network display no imports
None => Vec::new(),
}
}
pub fn frontend_exports(&mut self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphInput>> {
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
let mut frontend_exports = ((0..network.exports.len()).map(|export_index| self.frontend_input_from_connector(&InputConnector::Export(export_index), network_path))).collect::<Vec<_>>();
if frontend_exports.is_empty() {
frontend_exports.push(None);
}
frontend_exports
}
pub fn import_export_position(&mut self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path).cloned() else {
log::error!("Could not get all nodes bounding box in load_export_ports");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get current network in load_export_ports");
return None;
};
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_export_ports");
return None;
};
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
let target_viewport_top_left = DVec2::new(IMPORTS_TO_LEFT_EDGE_PIXEL_GAP as f64, IMPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
let node_graph_pixel_offset_top_left = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_left);
// A 5x5 grid offset from the top left corner
let node_graph_grid_space_offset_top_left = node_graph_to_viewport.inverse().transform_point2(DVec2::ZERO) + DVec2::new(5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the import is the highest/furthest left of the two offsets
let top_left_inner_bound = DVec2::new(
node_graph_pixel_offset_top_left.x.min(node_graph_grid_space_offset_top_left.x),
node_graph_pixel_offset_top_left.y.min(node_graph_grid_space_offset_top_left.y),
);
let offset_from_top_left = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(-4. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(-4. * GRID_SIZE as f64, 0.)
};
let bounding_box_top_left = DVec2::new((all_nodes_bounding_box[0].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.) + offset_from_top_left;
let import_top_left = DVec2::new(top_left_inner_bound.x.min(bounding_box_top_left.x), top_left_inner_bound.y.min(bounding_box_top_left.y));
let rounded_import_top_left = DVec2::new((import_top_left.x / 24.).round() * 24., (import_top_left.y / 24.).round() * 24.);
let viewport_width = network_metadata.persistent_metadata.navigation_metadata.node_graph_width;
let target_viewport_top_right = DVec2::new(viewport_width - EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP as f64, EXPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
// An offset from the right edge in viewport pixels
let node_graph_pixel_offset_top_right = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_right);
// A 5x5 grid offset from the right corner
let node_graph_grid_space_offset_top_right = node_graph_to_viewport.inverse().transform_point2(DVec2::new(viewport_width, 0.)) + DVec2::new(-5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the export is the highest/furthest right of the two offsets.
// When zoomed out this keeps it a constant grid space away from the edge, but when zoomed in it prevents the exports from getting too far in
let top_right_inner_bound = DVec2::new(
node_graph_pixel_offset_top_right.x.max(node_graph_grid_space_offset_top_right.x),
node_graph_pixel_offset_top_right.y.min(node_graph_grid_space_offset_top_right.y),
);
let offset_from_top_right = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(2. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(4. * GRID_SIZE as f64, 0.)
};
let mut bounding_box_top_right = DVec2::new((all_nodes_bounding_box[1].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.);
bounding_box_top_right += offset_from_top_right;
let export_top_right = DVec2::new(top_right_inner_bound.x.max(bounding_box_top_right.x), top_right_inner_bound.y.min(bounding_box_top_right.y));
let rounded_export_top_right = DVec2::new((export_top_right.x / 24.).round() * 24., (export_top_right.y / 24.).round() * 24.);
Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2()))
}
/// Returns None if there is an error, it is a hidden primary export, or a hidden input
pub fn frontend_input_from_connector(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<FrontendGraphInput> {
// Return None if it is a hidden input
if self.input_from_connector(input_connector, network_path).is_some_and(|input| !input.is_exposed()) {
return None;
}
let input_type = self.input_type(input_connector, network_path);
let data_type = input_type.displayed_type();
let resolved_type = input_type.resolved_type_node_string();
let connected_to = self
.upstream_output_connector(input_connector, network_path)
.map(|output_connector| match output_connector {
OutputConnector::Node { node_id, output_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to output #{output_index} of \"{name}\", ID: {node_id}.")
}
OutputConnector::Import(import_index) => format!("Connected to import #{import_index}."),
})
.unwrap_or("Connected to nothing.".to_string());
let (name, description) = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path),
InputConnector::Export(export_index) => {
// Get export name from parent node metadata input, which must match the number of exports.
// Empty string means to use type, or "Export + index" if type is empty determined
let export_name = if network_path.is_empty() {
"Canvas".to_string()
} else {
self.encapsulating_node_metadata(network_path)
.and_then(|encapsulating_metadata| encapsulating_metadata.persistent_metadata.output_names.get(*export_index).cloned())
.unwrap_or_default()
};
let export_name = if !export_name.is_empty() {
export_name
} else if let Some(export_type_name) = input_type.compiled_nested_type().map(|nested| nested.to_string()) {
export_type_name
} else {
format!("Export #{}", export_index)
};
(export_name, String::new())
}
};
Some(FrontendGraphInput {
data_type,
resolved_type,
name,
description,
valid_types: self.potential_valid_input_types(input_connector, network_path).iter().map(|ty| ty.to_string()).collect(),
connected_to,
})
}
/// Returns None if there is an error, it is the document network, a hidden primary output or import
pub fn frontend_output_from_connector(&mut self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<FrontendGraphOutput> {
let output_type = self.output_type(output_connector, network_path);
let (name, description) = match output_connector {
OutputConnector::Node { node_id, output_index } => {
// Do not display the primary output port for a node if it is a network node with a hidden primary export
if *output_index == 0 && self.hidden_primary_output(node_id, network_path) {
return None;
};
// Get the output name from the interior network export name
let node_metadata = self.node_metadata(node_id, network_path)?;
let output_name = node_metadata.persistent_metadata.output_names.get(*output_index).cloned().unwrap_or_default();
let output_name = if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() };
(output_name, String::new())
}
OutputConnector::Import(import_index) => {
// Get the import name from the encapsulating node input metadata
let Some((encapsulating_node_id, encapsulating_path)) = network_path.split_last() else {
// Return None if it is an import in the document network
return None;
};
// Return None if the primary input is hidden and this is the primary import
if *import_index == 0 && self.hidden_primary_import(network_path) {
return None;
};
let (import_name, description) = self.displayed_input_name_and_description(encapsulating_node_id, *import_index, encapsulating_path);
let import_name = if !import_name.is_empty() {
import_name
} else if let Some(import_type_name) = output_type.compiled_nested_type().map(|nested| nested.to_string()) {
import_type_name
} else {
format!("Import #{}", import_index)
};
(import_name, description)
}
};
let data_type = output_type.displayed_type();
let resolved_type = output_type.resolved_type_node_string();
let mut connected_to = self
.outward_wires(network_path)
.and_then(|outward_wires| outward_wires.get(output_connector))
.cloned()
.unwrap_or_default()
.iter()
.map(|input| match input {
&InputConnector::Node { node_id, input_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to input #{input_index} of \"{name}\", ID: {node_id}.")
}
InputConnector::Export(export_index) => format!("Connected to export #{export_index}."),
})
.collect::<Vec<_>>();
if connected_to.is_empty() {
connected_to.push("Connected to nothing.".to_string());
}
Some(FrontendGraphOutput {
data_type,
resolved_type,
name,
description,
connected_to,
})
}
pub fn height_from_click_target(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
let mut node_height: Option<u32> = self
.node_click_targets(node_id, network_path)
.and_then(|click_targets: &DocumentNodeClickTargets| click_targets.node_click_target.bounding_box())
.map(|bounding_box| ((bounding_box[1].y - bounding_box[0].y) / 24.) as u32);
if !self.is_layer(node_id, network_path) {
node_height = node_height.map(|height| height + 1);
}
node_height
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/error.rs | editor/src/messages/portfolio/document/utility_types/error.rs | use graphene_std::raster::color::Color;
use thiserror::Error;
/// The error type used by the Graphite editor.
#[derive(Clone, Debug, Error)]
pub enum EditorError {
#[error("Failed to execute operation:\n{0}")]
InvalidOperation(String),
#[error("Tried to construct an invalid color:\n{0:?}")]
Color(String),
#[error("The requested tool does not exist")]
UnknownTool,
#[error("The operation caused a document error:\n{0:?}")]
Document(String),
#[error(
"This document was created in an older version of the editor.\n\
\n\
Full backwards compatibility is not guaranteed in the current alpha release.\n\
\n\
If this document is critical, ask for support in Graphite's Discord community."
)]
DocumentDeserialization(String),
#[error("{0}")]
Misc(String),
}
macro_rules! derive_from {
($type:ty, $kind:ident) => {
impl From<$type> for EditorError {
fn from(error: $type) -> Self {
EditorError::$kind(format!("{error:?}"))
}
}
};
}
derive_from!(&str, Misc);
derive_from!(String, Misc);
derive_from!(Color, Color);
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/transformation.rs | editor/src/messages/portfolio/document/utility_types/transformation.rs | use super::network_interface::NodeNetworkInterface;
use crate::consts::{ROTATE_INCREMENT, SCALE_INCREMENT};
use crate::messages::portfolio::document::graph_operation::transform_utils;
use crate::messages::portfolio::document::graph_operation::utility_types::{ModifyInputsContext, TransformIn};
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::transform_layer::transform_layer_message_handler::TransformationState;
use crate::messages::tool::utility_types::ToolType;
use glam::{DAffine2, DMat2, DVec2};
use graphene_std::renderer::Quad;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId};
use graphene_std::vector::{HandleExt, PointId, VectorModificationType};
use std::collections::{HashMap, VecDeque};
#[derive(Debug, PartialEq, Clone, Copy)]
struct AnchorPoint {
initial: DVec2,
current: DVec2,
}
#[derive(Debug, PartialEq, Clone, Copy)]
struct HandlePoint {
initial: DVec2,
relative: DVec2,
anchor: PointId,
mirror: Option<(HandleId, DVec2)>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct InitialPoints {
anchors: HashMap<PointId, AnchorPoint>,
handles: HashMap<HandleId, HandlePoint>,
}
#[derive(Debug, PartialEq, Clone)]
pub enum OriginalTransforms {
Layer(HashMap<LayerNodeIdentifier, DAffine2>),
Path(HashMap<LayerNodeIdentifier, InitialPoints>),
}
impl Default for OriginalTransforms {
fn default() -> Self {
OriginalTransforms::Path(HashMap::new())
}
}
impl OriginalTransforms {
pub fn clear(&mut self) {
match self {
OriginalTransforms::Layer(layer_map) => layer_map.clear(),
OriginalTransforms::Path(path_map) => path_map.clear(),
}
}
/// Gets the transform from the most downstream transform node
fn get_layer_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<DAffine2> {
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain("Transform", layer, network_interface)?;
let document_node = network_interface.document_network().nodes.get(&transform_node_id)?;
Some(transform_utils::get_current_transform(&document_node.inputs))
}
pub fn update<'a>(&mut self, selected: &'a [LayerNodeIdentifier], network_interface: &NodeNetworkInterface, shape_editor: Option<&'a ShapeState>) {
match self {
OriginalTransforms::Layer(layer_map) => {
layer_map.retain(|layer, _| selected.contains(layer));
for &layer in selected {
if layer == LayerNodeIdentifier::ROOT_PARENT {
continue;
}
layer_map.entry(layer).or_insert_with(|| Self::get_layer_transform(layer, network_interface).unwrap_or_default());
}
}
OriginalTransforms::Path(path_map) => {
let Some(shape_editor) = shape_editor else {
warn!("No shape editor structure found, which only happens in select tool, which cannot reach this point as we check for ToolType");
return;
};
for &layer in selected {
if path_map.contains_key(&layer) {
continue;
}
let Some(vector) = network_interface.compute_modified_vector(layer) else {
continue;
};
let Some(selected_points) = shape_editor.selected_points_in_layer(layer) else {
continue;
};
let Some(selected_segments) = shape_editor.selected_segments_in_layer(layer) else {
continue;
};
let mut selected_points = selected_points.clone();
for (segment_id, _, start, end) in vector.segment_bezier_iter() {
if selected_segments.contains(&segment_id) {
selected_points.insert(ManipulatorPointId::Anchor(start));
selected_points.insert(ManipulatorPointId::Anchor(end));
}
}
// Anchors also move their handles
let anchor_ids = selected_points.iter().filter_map(|point| point.as_anchor());
let anchors = anchor_ids.filter_map(|id| vector.point_domain.position_from_id(id).map(|pos| (id, AnchorPoint { initial: pos, current: pos })));
let anchors = anchors.collect();
let selected_handles = selected_points.iter().filter_map(|point| point.as_handle());
let anchor_ids = selected_points.iter().filter_map(|point| point.as_anchor());
let connected_handles = anchor_ids.flat_map(|point| vector.all_connected(point));
let all_handles = selected_handles.chain(connected_handles);
let handles = all_handles
.filter_map(|id| {
let anchor = id.to_manipulator_point().get_anchor(&vector)?;
let initial = id.to_manipulator_point().get_position(&vector)?;
let relative = vector.point_domain.position_from_id(anchor)?;
let other_handle = vector
.other_colinear_handle(id)
.filter(|other| !selected_points.contains(&other.to_manipulator_point()) && !selected_points.contains(&ManipulatorPointId::Anchor(anchor)));
let mirror = other_handle.and_then(|id| Some((id, id.to_manipulator_point().get_position(&vector)?)));
Some((id, HandlePoint { initial, relative, anchor, mirror }))
})
.collect();
path_map.insert(layer, InitialPoints { anchors, handles });
}
}
}
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq, Copy)]
pub enum Axis {
#[default]
Both,
X,
Y,
}
impl Axis {
pub fn contrainted_to_axis(self, target: Axis, local: bool) -> (Self, bool) {
if self != target {
return (target, false);
}
if local { (Axis::Both, false) } else { (self, true) }
}
}
#[derive(Default, Debug, Clone, PartialEq, Copy)]
pub struct Translation {
pub dragged_distance: DVec2,
pub typed_distance: Option<f64>,
pub constraint: Axis,
}
impl Translation {
pub fn to_dvec(self, state: &TransformationState, document: &DocumentMessageHandler) -> DVec2 {
let document_to_viewport = document.metadata().document_to_viewport;
let displacement = if let Some(value) = self.typed_distance {
match self.constraint {
Axis::X => DVec2::X * value,
Axis::Y => DVec2::Y * value,
Axis::Both => self.dragged_distance,
}
} else {
match self.constraint {
Axis::Both => self.dragged_distance,
Axis::X => DVec2::X * self.dragged_distance.dot(state.constraint_axis(self.constraint).unwrap_or_default()),
Axis::Y => DVec2::Y * self.dragged_distance.dot(state.constraint_axis(self.constraint).unwrap_or_default()),
}
};
let displacement_viewport = displacement * document_to_viewport.matrix2.y_axis.length(); // Values are local to the viewport but scaled so values are relative to the current scale.
let displacement_document = document_to_viewport.inverse().transform_vector2(displacement_viewport);
let displacement_document = if state.is_rounded_to_intervals { displacement_document.round() } else { displacement_document }; // It rounds in document space?
document_to_viewport.transform_vector2(displacement_document)
}
#[must_use]
pub fn increment_amount(self, delta: DVec2) -> Self {
Self {
dragged_distance: self.dragged_distance + delta,
typed_distance: None,
constraint: self.constraint,
}
}
pub fn set_amount(self, change: DVec2) -> Self {
Self {
dragged_distance: change,
typed_distance: None,
constraint: self.constraint,
}
}
pub fn negate(self) -> Self {
let dragged_distance = -self.dragged_distance;
Self { dragged_distance, ..self }
}
pub fn with_constraint(self, target: Axis, local: bool) -> (Self, bool) {
let (constraint, local) = self.constraint.contrainted_to_axis(target, local);
(Self { constraint, ..self }, local)
}
}
#[derive(Default, Debug, Clone, PartialEq, Copy)]
pub struct Rotation {
pub dragged_angle: f64,
pub typed_angle: Option<f64>,
}
impl Rotation {
pub fn to_f64(self, increment_mode: bool) -> f64 {
if let Some(value) = self.typed_angle {
value.to_radians()
} else if increment_mode {
let increment_resolution = ROTATE_INCREMENT.to_radians();
(self.dragged_angle / increment_resolution).round() * increment_resolution
} else {
self.dragged_angle
}
}
#[must_use]
pub fn increment_amount(self, delta: f64) -> Self {
Self {
dragged_angle: self.dragged_angle + delta,
typed_angle: None,
}
}
pub fn set_amount(self, angle: f64) -> Self {
Self {
dragged_angle: angle,
typed_angle: None,
}
}
pub fn negate(self) -> Self {
let dragged_angle = -self.dragged_angle;
Self { dragged_angle, ..self }
}
}
#[derive(Debug, Clone, PartialEq, Copy)]
pub struct Scale {
pub dragged_factor: f64,
pub typed_factor: Option<f64>,
pub constraint: Axis,
}
impl Default for Scale {
fn default() -> Self {
Self {
dragged_factor: 1.,
typed_factor: None,
constraint: Axis::default(),
}
}
}
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 }
}
pub fn to_dvec(self, increment_mode: bool) -> DVec2 {
let factor = self.to_f64(increment_mode);
match self.constraint {
Axis::Both => DVec2::splat(factor),
Axis::X => DVec2::new(factor, 1.),
Axis::Y => DVec2::new(1., factor),
}
}
pub fn negate(self) -> Self {
let dragged_factor = -self.dragged_factor;
Self { dragged_factor, ..self }
}
#[must_use]
pub fn increment_amount(self, delta: f64) -> Self {
Self {
dragged_factor: (self.dragged_factor + delta),
typed_factor: None,
constraint: self.constraint,
}
}
pub fn set_amount(self, change: f64) -> Self {
Self {
dragged_factor: 1. + change,
typed_factor: None,
constraint: self.constraint,
}
}
pub fn with_constraint(self, target: Axis, local: bool) -> (Self, bool) {
let (constraint, local) = self.constraint.contrainted_to_axis(target, local);
(Self { constraint, ..self }, local)
}
}
#[derive(Default, Debug, Clone, PartialEq, Copy)]
pub enum TransformOperation {
#[default]
None,
Grabbing(Translation),
Rotating(Rotation),
Scaling(Scale),
}
#[derive(Debug, Clone, PartialEq, Copy, serde::Serialize, serde::Deserialize)]
pub enum TransformType {
Grab,
Rotate,
Scale,
}
impl TransformType {
pub fn equivalent_to(&self, operation: TransformOperation) -> bool {
matches!(
(operation, self),
(TransformOperation::Scaling(_), TransformType::Scale) | (TransformOperation::Grabbing(_), TransformType::Grab) | (TransformOperation::Rotating(_), TransformType::Rotate)
)
}
}
impl TransformOperation {
#[allow(clippy::too_many_arguments)]
pub fn apply_transform_operation(&self, selected: &mut Selected, state: &TransformationState, document: &DocumentMessageHandler) {
if self != &TransformOperation::None {
let mut transformation = match self {
TransformOperation::Grabbing(translation) => DAffine2::from_translation(translation.to_dvec(state, document)),
TransformOperation::Rotating(rotation) => DAffine2::from_angle(rotation.to_f64(state.is_rounded_to_intervals)),
TransformOperation::Scaling(scale) => DAffine2::from_scale(scale.to_dvec(state.is_rounded_to_intervals)),
TransformOperation::None => unreachable!(),
};
let normalized_transform = state.local_to_viewport_transform();
transformation = normalized_transform * transformation * normalized_transform.inverse();
selected.update_transforms(transformation, Some(state.pivot_viewport(document)), Some(*self));
self.hints(selected.responses, state.is_transforming_in_local_space);
}
}
pub fn axis_constraint(&self) -> Axis {
match self {
TransformOperation::Grabbing(grabbing) => grabbing.constraint,
TransformOperation::Scaling(scaling) => scaling.constraint,
_ => Axis::Both,
}
}
pub fn can_begin_typing(&self) -> bool {
self.is_constraint_to_axis() || !matches!(self, TransformOperation::Grabbing(_))
}
#[allow(clippy::too_many_arguments)]
pub fn constrain_axis(&mut self, axis: Axis, selected: &mut Selected, state: &TransformationState, document: &DocumentMessageHandler) -> bool {
let resulting_local;
(*self, resulting_local) = match self {
TransformOperation::Grabbing(translation) => {
let (translation, resulting_local) = translation.with_constraint(axis, state.is_transforming_in_local_space);
(TransformOperation::Grabbing(translation), resulting_local)
}
TransformOperation::Scaling(scale) => {
let (scale, resulting_local) = scale.with_constraint(axis, state.is_transforming_in_local_space);
(TransformOperation::Scaling(scale), resulting_local)
}
_ => (*self, false),
};
self.apply_transform_operation(selected, state, document);
resulting_local
}
#[allow(clippy::too_many_arguments)]
pub fn grs_typed(&mut self, typed: Option<f64>, selected: &mut Selected, state: &TransformationState, document: &DocumentMessageHandler) {
match self {
TransformOperation::None => (),
TransformOperation::Grabbing(translation) => translation.typed_distance = typed,
TransformOperation::Rotating(rotation) => rotation.typed_angle = typed,
TransformOperation::Scaling(scale) => scale.typed_factor = typed,
};
self.apply_transform_operation(selected, state, document);
}
pub fn hints(&self, responses: &mut VecDeque<Message>, local: bool) {
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
let mut input_hints = Vec::new();
let clear_constraint = "Clear Constraint";
match self.axis_constraint() {
Axis::Both => {
input_hints.push(HintInfo::keys([Key::KeyX], "X-Axis Constraint"));
input_hints.push(HintInfo::keys([Key::KeyY], "Y-Axis Constraint"));
}
Axis::X => {
let x_label = if local { clear_constraint } else { "Local X-Axis Constraint" };
input_hints.push(HintInfo::keys([Key::KeyX], x_label));
input_hints.push(HintInfo::keys([Key::KeyY], "Y-Axis Constraint"));
if !local {
input_hints.push(HintInfo::keys([Key::KeyX, Key::KeyX], clear_constraint));
}
}
Axis::Y => {
let y_label = if local { clear_constraint } else { "Local Y-Axis Constraint" };
input_hints.push(HintInfo::keys([Key::KeyX], "X-Axis Constraint"));
input_hints.push(HintInfo::keys([Key::KeyY], y_label));
if !local {
input_hints.push(HintInfo::keys([Key::KeyY, Key::KeyY], clear_constraint));
}
}
}
let grs_hint_group = match self {
TransformOperation::None => unreachable!(),
TransformOperation::Scaling(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyG], [Key::KeyR]], "Grab/Rotate Selected")]),
TransformOperation::Grabbing(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyR], [Key::KeyS]], "Rotate/Scale Selected")]),
TransformOperation::Rotating(_) => HintGroup(vec![HintInfo::multi_keys([[Key::KeyG], [Key::KeyS]], "Grab/Scale Selected")]),
};
let confirm_and_cancel_group = HintGroup(vec![
HintInfo::mouse(MouseMotion::Lmb, ""),
HintInfo::keys([Key::Enter], "Confirm").prepend_slash(),
HintInfo::mouse(MouseMotion::Rmb, ""),
HintInfo::keys([Key::Escape], "Cancel").prepend_slash(),
]);
let mut hint_groups = vec![confirm_and_cancel_group, grs_hint_group];
if !self.is_typing() {
let modifiers = vec![
HintInfo::keys([Key::Shift], "Slow"),
HintInfo::keys([Key::Control], if matches!(self, TransformOperation::Rotating(_)) { "15Β° Increments" } else { "Increments" }),
];
hint_groups.push(HintGroup(modifiers));
}
if !matches!(self, TransformOperation::Rotating(_)) {
hint_groups.push(HintGroup(input_hints));
}
let mut typing_hints = vec![HintInfo::keys([Key::Minus], "Negate Direction")];
if self.can_begin_typing() {
typing_hints.push(HintInfo::keys([Key::FakeKeyNumbers], "Enter Number"));
if self.is_typing() {
typing_hints.push(HintInfo::keys([Key::Backspace], "Delete Digit"));
}
}
hint_groups.push(HintGroup(typing_hints));
HintData(hint_groups).send_layout(responses);
}
pub fn is_constraint_to_axis(&self) -> bool {
self.axis_constraint() != Axis::Both
}
pub fn is_typing(&self) -> bool {
match self {
TransformOperation::None => false,
TransformOperation::Grabbing(translation) => translation.typed_distance.is_some(),
TransformOperation::Rotating(rotation) => rotation.typed_angle.is_some(),
TransformOperation::Scaling(scale) => scale.typed_factor.is_some(),
}
}
#[allow(clippy::too_many_arguments)]
pub fn negate(&mut self, selected: &mut Selected, state: &TransformationState, document: &DocumentMessageHandler) {
if *self != TransformOperation::None {
*self = match self {
TransformOperation::Scaling(scale) => TransformOperation::Scaling(scale.negate()),
TransformOperation::Rotating(rotation) => TransformOperation::Rotating(rotation.negate()),
TransformOperation::Grabbing(translation) => TransformOperation::Grabbing(translation.negate()),
_ => *self,
};
self.apply_transform_operation(selected, state, document);
}
}
}
pub struct Selected<'a> {
pub selected: &'a [LayerNodeIdentifier],
pub responses: &'a mut VecDeque<Message>,
pub network_interface: &'a NodeNetworkInterface,
pub original_transforms: &'a mut OriginalTransforms,
pub pivot: &'a mut DVec2,
pub shape_editor: Option<&'a ShapeState>,
pub tool_type: &'a ToolType,
// Only for the Pen tool
pub pen_handle: Option<&'a mut DVec2>,
}
impl<'a> Selected<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
original_transforms: &'a mut OriginalTransforms,
pivot: &'a mut DVec2,
selected: &'a [LayerNodeIdentifier],
responses: &'a mut VecDeque<Message>,
network_interface: &'a NodeNetworkInterface,
shape_editor: Option<&'a ShapeState>,
tool_type: &'a ToolType,
pen_handle: Option<&'a mut DVec2>,
) -> Self {
// If user is using the Select tool or Shape tool then use the original layer transforms
if (*tool_type == ToolType::Select || *tool_type == ToolType::Shape) && (*original_transforms == OriginalTransforms::Path(HashMap::new())) {
*original_transforms = OriginalTransforms::Layer(HashMap::new());
}
original_transforms.update(selected, network_interface, shape_editor);
Self {
selected,
responses,
network_interface,
original_transforms,
pivot,
shape_editor,
tool_type,
pen_handle,
}
}
pub fn center_of_aabb(&mut self) -> DVec2 {
let [min, max] = self
.selected
.iter()
.filter_map(|&layer| self.network_interface.document_metadata().bounding_box_viewport(layer))
.reduce(Quad::combine_bounds)
.unwrap_or_default();
(min + max) / 2.
}
pub fn bounding_box(&mut self) -> Quad {
let metadata = self.network_interface.document_metadata();
let mut transform = self
.network_interface
.selected_nodes()
.selected_visible_and_unlocked_layers(self.network_interface)
.find(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
.map(|layer| metadata.transform_to_viewport(layer))
.unwrap_or(DAffine2::IDENTITY);
if transform.matrix2.determinant().abs() <= f64::EPSILON {
transform.matrix2 += DMat2::IDENTITY * 1e-4; // TODO: Is this the cleanest way to handle this?
}
let bounds = self
.selected
.iter()
.filter_map(|&layer| metadata.bounding_box_with_transform(layer, transform.inverse() * metadata.transform_to_viewport(layer)))
.reduce(Quad::combine_bounds)
.unwrap_or_default();
transform * Quad::from_box(bounds)
}
fn transform_layer(document_metadata: &DocumentMetadata, layer: LayerNodeIdentifier, original_transform: Option<&DAffine2>, transformation: DAffine2, responses: &mut VecDeque<Message>) {
let Some(&original_transform) = original_transform else { return };
let to = document_metadata.downstream_transform_to_viewport(layer);
let new = to.inverse() * transformation * to * original_transform;
responses.add(GraphOperationMessage::TransformSet {
layer,
transform: new,
transform_in: TransformIn::Local,
skip_rerender: false,
});
}
fn transform_path(
document_metadata: &DocumentMetadata,
layer: LayerNodeIdentifier,
initial_points: &mut InitialPoints,
transformation: DAffine2,
responses: &mut VecDeque<Message>,
transform_operation: Option<TransformOperation>,
) {
let viewspace = document_metadata.transform_to_viewport(layer);
let layerspace_rotation = viewspace.inverse() * transformation;
for (&point, anchor) in initial_points.anchors.iter_mut() {
let new_pos_viewport = layerspace_rotation.transform_point2(viewspace.transform_point2(anchor.initial));
let delta = new_pos_viewport - anchor.current;
anchor.current += delta;
let modification_type = VectorModificationType::ApplyPointDelta { point, delta };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
if transform_operation.is_some_and(|transform_operation| matches!(transform_operation, TransformOperation::Scaling(_))) && (initial_points.anchors.len() == 2) {
return;
}
for (&id, handle) in initial_points.handles.iter() {
let new_pos_viewport = layerspace_rotation.transform_point2(viewspace.transform_point2(handle.initial));
let relative = initial_points.anchors.get(&handle.anchor).map_or(handle.relative, |anchor| anchor.current);
let modification_type = id.set_relative_position(new_pos_viewport - relative);
responses.add(GraphOperationMessage::Vector { layer, modification_type });
if let Some((id, initial)) = handle.mirror {
// When the handle is scaled to zero, don't update the mirror handle
if (new_pos_viewport - relative).length_squared() > f64::EPSILON {
let direction = viewspace.transform_vector2(new_pos_viewport - relative).try_normalize();
let length = viewspace.transform_vector2(initial - relative).length();
let new_relative = direction.map_or(initial - relative, |direction| viewspace.inverse().transform_vector2(-direction * length));
let modification_type = id.set_relative_position(new_relative);
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
}
}
}
pub fn apply_transform_pen(&mut self, transformation: DAffine2) {
if let Some(pen_handle) = &self.pen_handle {
let final_position = transformation.transform_point2(**pen_handle);
self.responses.add(PenToolMessage::FinalPosition { final_position });
}
}
pub fn apply_transformation(&mut self, transformation: DAffine2, transform_operation: Option<TransformOperation>) {
if self.selected.is_empty() {
return;
}
// TODO: Cache the result of `shallowest_unique_layers` to avoid this heavy computation every frame of movement, see https://github.com/GraphiteEditor/Graphite/pull/481
for layer in self.network_interface.shallowest_unique_layers(&[]) {
match &mut self.original_transforms {
OriginalTransforms::Layer(layer_transforms) => Self::transform_layer(self.network_interface.document_metadata(), layer, layer_transforms.get(&layer), transformation, self.responses),
OriginalTransforms::Path(path_transforms) => {
if let Some(initial_points) = path_transforms.get_mut(&layer) {
Self::transform_path(self.network_interface.document_metadata(), layer, initial_points, transformation, self.responses, transform_operation)
}
}
}
}
}
pub fn update_transforms(&mut self, delta: DAffine2, pivot: Option<DVec2>, transform_operation: Option<TransformOperation>) {
let pivot = DAffine2::from_translation(pivot.unwrap_or(*self.pivot));
let transformation = pivot * delta * pivot.inverse();
match self.tool_type {
ToolType::Pen => self.apply_transform_pen(transformation),
_ => self.apply_transformation(transformation, transform_operation),
}
}
pub fn revert_operation(&mut self) {
for layer in self.selected.iter().copied() {
let original_transform = &self.original_transforms;
match original_transform {
OriginalTransforms::Layer(hash) => {
let Some(matrix) = hash.get(&layer) else { continue };
self.responses.add(GraphOperationMessage::TransformSet {
layer,
transform: *matrix,
transform_in: TransformIn::Local,
skip_rerender: false,
});
}
OriginalTransforms::Path(path) => {
for (&layer, points) in path {
for (&point, &anchor) in &points.anchors {
let delta = anchor.initial - anchor.current;
let modification_type = VectorModificationType::ApplyPointDelta { point, delta };
self.responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
for (&point, &handle) in &points.handles {
let modification_type = point.set_relative_position(handle.initial - handle.relative);
self.responses.add(GraphOperationMessage::Vector { layer, modification_type });
if let Some((id, initial)) = handle.mirror {
let modification_type = id.set_relative_position(initial - handle.relative);
self.responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
}
}
}
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Typing {
pub digits: Vec<u8>,
pub string: String,
pub contains_decimal: bool,
pub negative: bool,
}
const DECIMAL_POINT: u8 = 10;
impl Typing {
pub fn type_number(&mut self, number: u8) -> Option<f64> {
self.digits.push(number);
self.string.push((b'0' + number) as char);
self.evaluate()
}
pub fn type_backspace(&mut self) -> Option<f64> {
if self.digits.is_empty() {
return None;
}
match self.digits.pop() {
Some(DECIMAL_POINT) => self.contains_decimal = false,
Some(_) => (),
None => self.negative = false,
}
self.string.pop();
self.evaluate()
}
pub fn type_decimal_point(&mut self) -> Option<f64> {
if !self.contains_decimal {
self.contains_decimal = true;
self.digits.push(DECIMAL_POINT);
self.string.push('.');
}
self.evaluate()
}
pub fn type_negate(&mut self) -> Option<f64> {
self.negative = !self.negative;
if self.negative {
self.string.insert(0, '-');
} else {
self.string.remove(0);
}
self.evaluate()
}
pub fn evaluate(&self) -> Option<f64> {
if self.digits.is_empty() {
return None;
}
let mut result = 0_f64;
let mut running_decimal_place = 0_i32;
for digit in &self.digits {
if *digit == DECIMAL_POINT {
if running_decimal_place == 0 {
running_decimal_place = 1;
}
} else if running_decimal_place == 0 {
result *= 10.;
result += *digit as f64;
} else {
result += *digit as f64 * 0.1_f64.powi(running_decimal_place);
running_decimal_place += 1;
}
}
if self.negative {
result = -result;
}
Some(result)
}
pub fn clear(&mut self) {
self.digits.clear();
self.string.clear();
self.contains_decimal = false;
self.negative = false;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/mod.rs | editor/src/messages/portfolio/document/utility_types/mod.rs | pub mod clipboards;
pub mod document_metadata;
pub mod error;
pub mod misc;
pub mod network_interface;
pub mod nodes;
pub mod transformation;
pub mod wires;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/nodes.rs | editor/src/messages/portfolio/document/utility_types/nodes.rs | use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use super::network_interface::NodeNetworkInterface;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::DVec2;
use graph_craft::document::{NodeId, NodeNetwork};
use serde::ser::SerializeStruct;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, specta::Type)]
pub struct RawBuffer(Vec<u8>);
impl From<&[u64]> for RawBuffer {
fn from(iter: &[u64]) -> Self {
let v_from_raw: Vec<u8> = iter.iter().flat_map(|x| x.to_ne_bytes()).collect();
Self(v_from_raw)
}
}
#[derive(Debug, Clone, serde::Deserialize, PartialEq, Eq, specta::Type)]
pub struct JsRawBuffer(Vec<u8>);
impl From<RawBuffer> for JsRawBuffer {
fn from(buffer: RawBuffer) -> Self {
Self(buffer.0)
}
}
impl serde::Serialize for JsRawBuffer {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut buffer = serializer.serialize_struct("Buffer", 2)?;
buffer.serialize_field("pointer", &(self.0.as_ptr() as usize))?;
buffer.serialize_field("length", &(self.0.len()))?;
buffer.end()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, specta::Type)]
pub struct LayerPanelEntry {
pub id: NodeId,
pub reference: String,
pub alias: String,
#[serde(rename = "inSelectedNetwork")]
pub in_selected_network: bool,
#[serde(rename = "childrenAllowed")]
pub children_allowed: bool,
#[serde(rename = "childrenPresent")]
pub children_present: bool,
pub expanded: bool,
pub depth: usize,
pub visible: bool,
#[serde(rename = "parentsVisible")]
pub parents_visible: bool,
pub unlocked: bool,
#[serde(rename = "parentsUnlocked")]
pub parents_unlocked: bool,
#[serde(rename = "parentId")]
pub parent_id: Option<NodeId>,
pub selected: bool,
#[serde(rename = "ancestorOfSelected")]
pub ancestor_of_selected: bool,
#[serde(rename = "descendantOfSelected")]
pub descendant_of_selected: bool,
pub clipped: bool,
pub clippable: bool,
}
/// IMPORTANT: the same node may appear multiple times.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq, specta::Type)]
pub struct SelectedNodes(pub Vec<NodeId>);
impl SelectedNodes {
pub fn layer_visible(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
layer.ancestors(network_interface.document_metadata()).all(|layer| {
if layer != LayerNodeIdentifier::ROOT_PARENT {
network_interface.is_visible(&layer.to_node(), &[])
} else {
true
}
})
}
pub fn selected_visible_layers<'a>(&'a self, network_interface: &'a NodeNetworkInterface) -> impl Iterator<Item = LayerNodeIdentifier> + 'a {
self.selected_layers(network_interface.document_metadata())
.filter(move |&layer| self.layer_visible(layer, network_interface))
}
pub fn layer_locked(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
layer.ancestors(network_interface.document_metadata()).any(|layer| {
if layer != LayerNodeIdentifier::ROOT_PARENT {
network_interface.is_locked(&layer.to_node(), &[])
} else {
false
}
})
}
pub fn selected_unlocked_layers<'a>(&'a self, network_interface: &'a NodeNetworkInterface) -> impl Iterator<Item = LayerNodeIdentifier> + 'a {
self.selected_layers(network_interface.document_metadata())
.filter(move |&layer| !self.layer_locked(layer, network_interface))
}
pub fn selected_visible_and_unlocked_layers<'a>(&'a self, network_interface: &'a NodeNetworkInterface) -> impl Iterator<Item = LayerNodeIdentifier> + 'a {
self.selected_layers(network_interface.document_metadata())
.filter(move |&layer| self.layer_visible(layer, network_interface) && !self.layer_locked(layer, network_interface))
}
pub fn selected_visible_and_unlocked_layers_mean_average_origin<'a>(&'a self, network_interface: &'a NodeNetworkInterface) -> DVec2 {
let (sum, count) = self
.selected_visible_and_unlocked_layers(network_interface)
.map(|layer| graph_modification_utils::get_viewport_origin(layer, network_interface))
.fold((glam::DVec2::ZERO, 0), |(sum, count), item| (sum + item, count + 1));
if count == 0 { DVec2::ZERO } else { sum / count as f64 }
}
pub fn selected_visible_and_unlocked_median_points<'a>(&'a self, network_interface: &'a NodeNetworkInterface) -> DVec2 {
let (sum, count) = self
.selected_visible_and_unlocked_layers(network_interface)
.map(|layer| graph_modification_utils::get_viewport_center(layer, network_interface))
.fold((glam::DVec2::ZERO, 0), |(sum, count), item| (sum + item, count + 1));
if count == 0 { DVec2::ZERO } else { sum / count as f64 }
}
pub fn selected_layers<'a>(&'a self, metadata: &'a DocumentMetadata) -> impl Iterator<Item = LayerNodeIdentifier> + 'a {
metadata.all_layers().filter(|layer| self.0.contains(&layer.to_node()))
}
pub fn selected_layers_except_artboards<'a>(&'a self, network_interface: &'a NodeNetworkInterface) -> impl Iterator<Item = LayerNodeIdentifier> + 'a {
self.selected_layers(network_interface.document_metadata())
.filter(move |&layer| !network_interface.is_artboard(&layer.to_node(), &[]))
}
pub fn selected_layers_contains(&self, layer: LayerNodeIdentifier, metadata: &DocumentMetadata) -> bool {
self.selected_layers(metadata).any(|selected| selected == layer)
}
/// IMPORTANT: the same node may appear multiple times.
pub fn selected_nodes(&self) -> impl Iterator<Item = &NodeId> + '_ {
self.0.iter()
}
pub fn selected_nodes_ref(&self) -> &Vec<NodeId> {
&self.0
}
pub fn network_has_selected_nodes(&self, network: &NodeNetwork) -> bool {
self.0.iter().any(|node_id| network.nodes.contains_key(node_id))
}
pub fn has_selected_nodes(&self) -> bool {
!self.0.is_empty()
}
pub fn retain_selected_nodes(&mut self, f: impl FnMut(&NodeId) -> bool) {
self.0.retain(f);
}
pub fn set_selected_nodes(&mut self, new: Vec<NodeId>) {
self.0 = new;
}
pub fn add_selected_nodes(&mut self, new: Vec<NodeId>) {
self.0.extend(new);
}
pub fn clear_selected_nodes(&mut self) {
self.0 = Vec::new();
}
pub fn replace_with(&mut self, new: Vec<NodeId>) -> Vec<NodeId> {
std::mem::replace(&mut self.0, new)
}
pub fn filtered_selected_nodes(&self, filter: impl Fn(&NodeId) -> bool) -> SelectedNodes {
SelectedNodes(self.0.iter().copied().filter(filter).collect())
}
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq, specta::Type)]
pub struct CollapsedLayers(pub Vec<LayerNodeIdentifier>);
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/document_metadata.rs | editor/src/messages/portfolio/document/utility_types/document_metadata.rs | 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 crate::messages::portfolio::document::utility_types::network_interface::FlowType;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeId;
use graphene_std::math::quad::Quad;
use graphene_std::subpath;
use graphene_std::transform::Footprint;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::{PointId, Vector};
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU64;
// ================
// DocumentMetadata
// ================
// TODO: To avoid storing a stateful snapshot of some other system's state (which is easily to accidentally get out of sync),
// TODO: it might be better to have a system that can query the state of the node network on demand.
#[derive(Debug, Clone, Default)]
pub struct DocumentMetadata {
pub upstream_footprints: HashMap<NodeId, Footprint>,
pub local_transforms: HashMap<NodeId, DAffine2>,
pub first_element_source_ids: HashMap<NodeId, Option<NodeId>>,
pub structure: HashMap<LayerNodeIdentifier, NodeRelations>,
pub click_targets: HashMap<LayerNodeIdentifier, Vec<ClickTarget>>,
pub clip_targets: HashSet<NodeId>,
pub vector_modify: HashMap<NodeId, Vector>,
/// Transform from document space to viewport space.
pub document_to_viewport: DAffine2,
}
// =================================
// DocumentMetadata: Layer iterators
// =================================
impl DocumentMetadata {
pub fn all_layers(&self) -> DescendantsIter<'_> {
LayerNodeIdentifier::ROOT_PARENT.descendants(self)
}
pub fn layer_exists(&self, layer: LayerNodeIdentifier) -> bool {
self.structure.contains_key(&layer)
}
pub fn click_targets(&self, layer: LayerNodeIdentifier) -> Option<&Vec<ClickTarget>> {
self.click_targets.get(&layer)
}
/// Access the [`NodeRelations`] of a layer.
fn get_relations(&self, node_identifier: LayerNodeIdentifier) -> Option<&NodeRelations> {
self.structure.get(&node_identifier)
}
/// Mutably access the [`NodeRelations`] of a layer.
fn get_structure_mut(&mut self, node_identifier: LayerNodeIdentifier) -> &mut NodeRelations {
self.structure.entry(node_identifier).or_default()
}
}
// ============================
// DocumentMetadata: Transforms
// ============================
impl DocumentMetadata {
/// Access the cached transformation to document space from layer space
pub fn transform_to_document(&self, layer: LayerNodeIdentifier) -> DAffine2 {
self.document_to_viewport.inverse() * self.transform_to_viewport(layer)
}
pub fn transform_to_viewport(&self, layer: LayerNodeIdentifier) -> DAffine2 {
// We're not allowed to convert the root parent to a node id
if layer == LayerNodeIdentifier::ROOT_PARENT {
return self.document_to_viewport;
}
let footprint = self.upstream_footprints.get(&layer.to_node()).map(|footprint| footprint.transform).unwrap_or(self.document_to_viewport);
let local_transform = self.local_transforms.get(&layer.to_node()).copied().unwrap_or_default();
footprint * local_transform
}
pub fn transform_to_viewport_if_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 {
// We're not allowed to convert the root parent to a node id
if layer == LayerNodeIdentifier::ROOT_PARENT {
return self.document_to_viewport;
}
let footprint = self.upstream_footprints.get(&layer.to_node()).map(|footprint| footprint.transform).unwrap_or(self.document_to_viewport);
let mut use_local = true;
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer("Path")
&& let Some(&source) = self.first_element_source_ids.get(&layer.to_node())
&& !network_interface
.upstream_flow_back_from_nodes(vec![path_node], &[], FlowType::HorizontalFlow)
.any(|upstream| Some(upstream) == source)
{
use_local = false;
info!("Local transform is invalid β using the identity for the local transform instead")
}
let local_transform = use_local.then(|| self.local_transforms.get(&layer.to_node()).copied()).flatten().unwrap_or_default();
footprint * local_transform
}
pub fn transform_to_document_if_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 {
self.document_to_viewport.inverse() * self.transform_to_viewport_if_feeds(layer, network_interface)
}
pub fn transform_to_viewport_with_first_transform_node_if_group(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 {
let footprint = self.upstream_footprints.get(&layer.to_node()).map(|footprint| footprint.transform).unwrap_or(self.document_to_viewport);
let local_transform = self.local_transforms.get(&layer.to_node()).copied();
let transform = local_transform.unwrap_or_else(|| {
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain("Transform", layer, network_interface);
let transform_node = transform_node_id.and_then(|id| network_interface.document_node(&id, &[]));
transform_node.map(|node| transform_utils::get_current_transform(node.inputs.as_slice())).unwrap_or_default()
});
footprint * transform
}
pub fn upstream_transform(&self, node_id: NodeId) -> DAffine2 {
self.local_transforms.get(&node_id).copied().unwrap_or(DAffine2::IDENTITY)
}
pub fn downstream_transform_to_document(&self, layer: LayerNodeIdentifier) -> DAffine2 {
self.document_to_viewport.inverse() * self.downstream_transform_to_viewport(layer)
}
pub fn downstream_transform_to_viewport(&self, layer: LayerNodeIdentifier) -> DAffine2 {
if layer == LayerNodeIdentifier::ROOT_PARENT {
return self.transform_to_viewport(layer);
}
self.upstream_footprints
.get(&layer.to_node())
.copied()
.map(|footprint| footprint.transform)
.unwrap_or_else(|| self.transform_to_viewport(layer))
}
}
// ===============================
// DocumentMetadata: Click targets
// ===============================
impl DocumentMetadata {
/// Get the bounding box of the click target of the specified layer in the specified transform space
pub fn bounding_box_with_transform(&self, layer: LayerNodeIdentifier, transform: DAffine2) -> Option<[DVec2; 2]> {
self.click_targets(layer)?
.iter()
.filter_map(|click_target| click_target.bounding_box_with_transform(transform))
.reduce(Quad::combine_bounds)
}
/// Get the loose bounding box of the click target of the specified layer in the specified transform space
pub fn loose_bounding_box_with_transform(&self, layer: LayerNodeIdentifier, transform: DAffine2) -> Option<[DVec2; 2]> {
self.click_targets(layer)?
.iter()
.filter_map(|click_target| match click_target.target_type() {
ClickTargetType::Subpath(subpath) => subpath.loose_bounding_box_with_transform(transform),
ClickTargetType::FreePoint(_) => click_target.bounding_box_with_transform(transform),
})
.reduce(Quad::combine_bounds)
}
/// Calculate the corners of the bounding box but with a nonzero size.
///
/// If the layer bounds are `0` in either axis then they are changed to be `1`.
pub fn nonzero_bounding_box(&self, layer: LayerNodeIdentifier) -> [DVec2; 2] {
let [mut bounds_min, mut bounds_max] = self.bounding_box_with_transform(layer, DAffine2::IDENTITY).unwrap_or_default();
let bounds_size = bounds_max - bounds_min;
let bounds_midpoint = bounds_min.midpoint(bounds_max);
const BOX_NUDGE: f64 = 5e-9;
if bounds_size.x < 1e-10 {
bounds_max.x = bounds_midpoint.x + BOX_NUDGE;
bounds_min.x = bounds_midpoint.x - BOX_NUDGE;
}
if bounds_size.y < 1e-10 {
bounds_max.y = bounds_midpoint.y + BOX_NUDGE;
bounds_min.y = bounds_midpoint.y - BOX_NUDGE;
}
[bounds_min, bounds_max]
}
/// Get the bounding box of the click target of the specified layer in document space
pub fn bounding_box_document(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
self.bounding_box_with_transform(layer, self.transform_to_document(layer))
}
/// Get the bounding box of the click target of the specified layer in viewport space
pub fn bounding_box_viewport(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
self.bounding_box_with_transform(layer, self.transform_to_viewport(layer))
}
/// Calculates the document bounds in viewport space
pub fn document_bounds_viewport_space(&self) -> Option<[DVec2; 2]> {
self.all_layers().filter_map(|layer| self.bounding_box_viewport(layer)).reduce(Quad::combine_bounds)
}
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &subpath::Subpath<PointId>> {
static EMPTY: Vec<ClickTarget> = Vec::new();
let click_targets = self.click_targets.get(&layer).unwrap_or(&EMPTY);
click_targets.iter().filter_map(|target| match target.target_type() {
ClickTargetType::Subpath(subpath) => Some(subpath),
_ => None,
})
}
pub fn layer_with_free_points_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &ClickTargetType> {
static EMPTY: Vec<ClickTarget> = Vec::new();
let click_targets = self.click_targets.get(&layer).unwrap_or(&EMPTY);
click_targets.iter().map(|target| target.target_type())
}
pub fn is_clip(&self, node: NodeId) -> bool {
self.clip_targets.contains(&node)
}
}
// ===================
// LayerNodeIdentifier
// ===================
/// ID of a layer node
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct LayerNodeIdentifier(NonZeroU64);
impl core::fmt::Debug for LayerNodeIdentifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let node_id = if *self != LayerNodeIdentifier::ROOT_PARENT { self.to_node() } else { NodeId(0) };
f.debug_tuple("LayerNodeIdentifier").field(&node_id).finish()
}
}
impl Default for LayerNodeIdentifier {
fn default() -> Self {
Self::ROOT_PARENT
}
}
impl LayerNodeIdentifier {
/// A conceptual layer used to represent the parent of layers that feed into the export
pub const ROOT_PARENT: Self = LayerNodeIdentifier::new_unchecked(NodeId(0));
/// Construct a [`LayerNodeIdentifier`] without checking if it is a layer node
pub const fn new_unchecked(node_id: NodeId) -> Self {
// # Safety: will always be >=1
Self(unsafe { NonZeroU64::new_unchecked(node_id.0 + 1) })
}
/// Construct a [`LayerNodeIdentifier`], debug asserting that it is a layer node. This should only be used in the document network since the structure is not loaded in nested networks.
#[track_caller]
pub fn new(node_id: NodeId, network_interface: &NodeNetworkInterface) -> Self {
debug_assert!(network_interface.is_layer(&node_id, &[]), "Layer identifier constructed from non-layer node {node_id}",);
Self::new_unchecked(node_id)
}
/// Access the node id of this layer
pub fn to_node(self) -> NodeId {
let id = NodeId(u64::from(self.0) - 1);
debug_assert!(id != NodeId(0), "LayerNodeIdentifier::ROOT_PARENT cannot be converted to NodeId");
id
}
/// Access the parent layer if possible
pub fn parent(self, metadata: &DocumentMetadata) -> Option<LayerNodeIdentifier> {
metadata.get_relations(self).and_then(|relations| relations.parent)
}
/// Access the previous sibling of this layer (up the Layers panel)
pub fn previous_sibling(self, metadata: &DocumentMetadata) -> Option<LayerNodeIdentifier> {
metadata.get_relations(self).and_then(|relations| relations.previous_sibling)
}
/// Access the next sibling of this layer (down the Layers panel)
pub fn next_sibling(self, metadata: &DocumentMetadata) -> Option<LayerNodeIdentifier> {
metadata.get_relations(self).and_then(|relations| relations.next_sibling)
}
/// Access the first child of this layer (top most in Layers panel)
pub fn first_child(self, metadata: &DocumentMetadata) -> Option<LayerNodeIdentifier> {
metadata.get_relations(self).and_then(|relations| relations.first_child)
}
/// Access the last child of this layer (bottom most in Layers panel)
pub fn last_child(self, metadata: &DocumentMetadata) -> Option<LayerNodeIdentifier> {
metadata.get_relations(self).and_then(|relations| relations.last_child)
}
/// Does the layer have children? If so, then it is a folder.
pub fn has_children(self, metadata: &DocumentMetadata) -> bool {
self.first_child(metadata).is_some()
}
/// Is the layer a child of the given layer?
pub fn is_child_of(self, metadata: &DocumentMetadata, parent: &LayerNodeIdentifier) -> bool {
parent.children(metadata).any(|child| child == self)
}
/// Is the layer an ancestor of the given layer?
pub fn is_ancestor_of(self, metadata: &DocumentMetadata, child: &LayerNodeIdentifier) -> bool {
child.ancestors(metadata).any(|ancestor| ancestor == self)
}
/// Is the layer the last child of its stack? Used for clipping
pub fn can_be_clipped(self, metadata: &DocumentMetadata) -> bool {
self.parent(metadata)
.is_some_and(|layer| layer.last_child(metadata).expect("Parent accessed via child should have children") != self)
}
/// Iterator over all direct children (excluding self and recursive children)
pub fn children(self, metadata: &DocumentMetadata) -> AxisIter<'_> {
AxisIter {
layer_node: self.first_child(metadata),
next_node: Self::next_sibling,
metadata,
}
}
pub fn downstream_siblings(self, metadata: &DocumentMetadata) -> AxisIter<'_> {
AxisIter {
layer_node: Some(self),
next_node: Self::previous_sibling,
metadata,
}
}
/// All ancestors of this layer, including self, going to the document root
pub fn ancestors(self, metadata: &DocumentMetadata) -> AxisIter<'_> {
AxisIter {
layer_node: Some(self),
next_node: Self::parent,
metadata,
}
}
/// Iterator through all the last children, starting from self
pub fn last_children(self, metadata: &DocumentMetadata) -> AxisIter<'_> {
AxisIter {
layer_node: Some(self),
next_node: Self::last_child,
metadata,
}
}
/// Iterator through all descendants, including recursive children (not including self)
pub fn descendants(self, metadata: &DocumentMetadata) -> DescendantsIter<'_> {
DescendantsIter {
front: self.first_child(metadata),
back: self.last_child(metadata).and_then(|child| child.last_children(metadata).last()),
metadata,
}
}
/// Add a child towards the top of the Layers panel
pub fn push_front_child(self, metadata: &mut DocumentMetadata, new: LayerNodeIdentifier) {
assert!(!metadata.structure.contains_key(&new), "Cannot add already existing layer");
let parent = metadata.get_structure_mut(self);
let old_first_child = parent.first_child.replace(new);
parent.last_child.get_or_insert(new);
if let Some(old_first_child) = old_first_child {
metadata.get_structure_mut(old_first_child).previous_sibling = Some(new);
}
metadata.get_structure_mut(new).next_sibling = old_first_child;
metadata.get_structure_mut(new).parent = Some(self);
}
/// Add a child towards the bottom of the Layers panel
pub fn push_child(self, metadata: &mut DocumentMetadata, new: LayerNodeIdentifier) {
assert!(!metadata.structure.contains_key(&new), "Cannot add already existing layer");
let parent = metadata.get_structure_mut(self);
let old_last_child = parent.last_child.replace(new);
parent.first_child.get_or_insert(new);
if let Some(old_last_child) = old_last_child {
metadata.get_structure_mut(old_last_child).next_sibling = Some(new);
}
metadata.get_structure_mut(new).previous_sibling = old_last_child;
metadata.get_structure_mut(new).parent = Some(self);
}
/// Add sibling above in the Layers panel
pub fn add_before(self, metadata: &mut DocumentMetadata, new: LayerNodeIdentifier) {
assert!(!metadata.structure.contains_key(&new), "Cannot add already existing layer");
metadata.get_structure_mut(new).next_sibling = Some(self);
metadata.get_structure_mut(new).parent = self.parent(metadata);
let old_previous_sibling = metadata.get_structure_mut(self).previous_sibling.replace(new);
if let Some(old_previous_sibling) = old_previous_sibling {
metadata.get_structure_mut(old_previous_sibling).next_sibling = Some(new);
metadata.get_structure_mut(new).previous_sibling = Some(old_previous_sibling);
} else if let Some(structure) = self
.parent(metadata)
.map(|parent| metadata.get_structure_mut(parent))
.filter(|structure| structure.first_child == Some(self))
{
structure.first_child = Some(new);
}
}
/// Add sibling below in the Layers panel
pub fn add_after(self, metadata: &mut DocumentMetadata, new: LayerNodeIdentifier) {
assert!(!metadata.structure.contains_key(&new), "Cannot add already existing layer");
metadata.get_structure_mut(new).previous_sibling = Some(self);
metadata.get_structure_mut(new).parent = self.parent(metadata);
let old_next_sibling = metadata.get_structure_mut(self).next_sibling.replace(new);
if let Some(old_next_sibling) = old_next_sibling {
metadata.get_structure_mut(old_next_sibling).previous_sibling = Some(new);
metadata.get_structure_mut(new).next_sibling = Some(old_next_sibling);
} else if let Some(structure) = self
.parent(metadata)
.map(|parent| metadata.get_structure_mut(parent))
.filter(|structure| structure.last_child == Some(self))
{
structure.last_child = Some(new);
}
}
/// Delete layer and all children
pub fn delete(self, metadata: &mut DocumentMetadata) {
let previous_sibling = self.previous_sibling(metadata);
let next_sibling = self.next_sibling(metadata);
if let Some(previous_sibling) = previous_sibling.map(|node| metadata.get_structure_mut(node)) {
previous_sibling.next_sibling = next_sibling;
}
if let Some(next_sibling) = next_sibling.map(|node| metadata.get_structure_mut(node)) {
next_sibling.previous_sibling = previous_sibling;
}
let mut parent = self.parent(metadata).map(|parent| metadata.get_structure_mut(parent));
if let Some(structure) = parent.as_mut().filter(|structure| structure.first_child == Some(self)) {
structure.first_child = next_sibling;
}
if let Some(structure) = parent.as_mut().filter(|structure| structure.last_child == Some(self)) {
structure.last_child = previous_sibling;
}
let mut delete = vec![self];
delete.extend(self.descendants(metadata));
for node in delete {
metadata.structure.remove(&node);
}
}
pub fn exists(&self, metadata: &DocumentMetadata) -> bool {
metadata.get_relations(*self).is_some()
}
pub fn starts_with(&self, other: Self, metadata: &DocumentMetadata) -> bool {
self.ancestors(metadata).any(|parent| parent == other)
}
}
// ========
// AxisIter
// ========
/// Iterator over specified axis.
#[derive(Clone)]
pub struct AxisIter<'a> {
pub layer_node: Option<LayerNodeIdentifier>,
pub next_node: fn(LayerNodeIdentifier, &DocumentMetadata) -> Option<LayerNodeIdentifier>,
pub metadata: &'a DocumentMetadata,
}
impl Iterator for AxisIter<'_> {
type Item = LayerNodeIdentifier;
fn next(&mut self) -> Option<Self::Item> {
let layer_node = self.layer_node.take();
self.layer_node = layer_node.and_then(|node| (self.next_node)(node, self.metadata));
layer_node
}
}
// ===============
// DescendantsIter
// ===============
#[derive(Clone)]
pub struct DescendantsIter<'a> {
front: Option<LayerNodeIdentifier>,
back: Option<LayerNodeIdentifier>,
metadata: &'a DocumentMetadata,
}
impl Iterator for DescendantsIter<'_> {
type Item = LayerNodeIdentifier;
fn next(&mut self) -> Option<Self::Item> {
if self.front == self.back {
self.back = None;
self.front.take()
} else {
let layer_node = self.front.take();
if let Some(layer_node) = layer_node {
self.front = layer_node
.first_child(self.metadata)
.or_else(|| layer_node.ancestors(self.metadata).find_map(|ancestor| ancestor.next_sibling(self.metadata)));
}
layer_node
}
}
}
impl DoubleEndedIterator for DescendantsIter<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.front == self.back {
self.front = None;
self.back.take()
} else {
let layer_node = self.back.take();
if let Some(layer_node) = layer_node {
self.back = layer_node
.previous_sibling(self.metadata)
.and_then(|sibling| sibling.last_children(self.metadata).last())
.or_else(|| layer_node.parent(self.metadata));
}
layer_node
}
}
}
// =============
// NodeRelations
// =============
#[derive(Debug, Clone, Copy, Default)]
pub struct NodeRelations {
pub parent: Option<LayerNodeIdentifier>,
previous_sibling: Option<LayerNodeIdentifier>,
next_sibling: Option<LayerNodeIdentifier>,
first_child: Option<LayerNodeIdentifier>,
last_child: Option<LayerNodeIdentifier>,
}
// ================
// Helper functions
// ================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tree() {
let mut metadata = DocumentMetadata::default();
let root = LayerNodeIdentifier::ROOT_PARENT;
let metadata = &mut metadata;
root.push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(3)));
assert_eq!(root.children(metadata).collect::<Vec<_>>(), vec![LayerNodeIdentifier::new_unchecked(NodeId(3))]);
root.push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(6)));
assert_eq!(root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(), vec![NodeId(3), NodeId(6)]);
assert_eq!(root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(), vec![NodeId(3), NodeId(6)]);
LayerNodeIdentifier::new_unchecked(NodeId(3)).add_after(metadata, LayerNodeIdentifier::new_unchecked(NodeId(4)));
LayerNodeIdentifier::new_unchecked(NodeId(3)).add_before(metadata, LayerNodeIdentifier::new_unchecked(NodeId(2)));
LayerNodeIdentifier::new_unchecked(NodeId(6)).add_before(metadata, LayerNodeIdentifier::new_unchecked(NodeId(5)));
LayerNodeIdentifier::new_unchecked(NodeId(6)).add_after(metadata, LayerNodeIdentifier::new_unchecked(NodeId(9)));
LayerNodeIdentifier::new_unchecked(NodeId(6)).push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(8)));
LayerNodeIdentifier::new_unchecked(NodeId(6)).push_front_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(7)));
root.push_front_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(1)));
assert_eq!(
root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
vec![NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(6), NodeId(9)]
);
assert_eq!(
root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
vec![NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(6), NodeId(7), NodeId(8), NodeId(9)]
);
assert_eq!(
root.descendants(metadata).map(LayerNodeIdentifier::to_node).rev().collect::<Vec<_>>(),
vec![NodeId(9), NodeId(8), NodeId(7), NodeId(6), NodeId(5), NodeId(4), NodeId(3), NodeId(2), NodeId(1)]
);
assert!(root.children(metadata).all(|child| child.parent(metadata) == Some(root)));
LayerNodeIdentifier::new_unchecked(NodeId(6)).delete(metadata);
LayerNodeIdentifier::new_unchecked(NodeId(1)).delete(metadata);
LayerNodeIdentifier::new_unchecked(NodeId(9)).push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(10)));
assert_eq!(
root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
vec![NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(9)]
);
assert_eq!(
root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
vec![NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(9), NodeId(10)]
);
assert_eq!(
root.descendants(metadata).map(LayerNodeIdentifier::to_node).rev().collect::<Vec<_>>(),
vec![NodeId(10), NodeId(9), NodeId(5), NodeId(4), NodeId(3), NodeId(2)]
);
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/wires.rs | editor/src/messages/portfolio/document/utility_types/wires.rs | use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use glam::{DVec2, IVec2};
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape};
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct WirePath {
#[serde(rename = "pathString")]
pub path_string: String,
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
pub thick: bool,
pub dashed: bool,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct WirePathUpdate {
pub id: NodeId,
#[serde(rename = "inputIndex")]
pub input_index: usize,
// If none, then remove the wire from the map
#[serde(rename = "wirePathUpdate")]
pub wire_path_update: Option<WirePath>,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum GraphWireStyle {
#[default]
Direct = 0,
GridAligned = 1,
}
impl std::fmt::Display for GraphWireStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GraphWireStyle::GridAligned => write!(f, "Grid-Aligned"),
GraphWireStyle::Direct => write!(f, "Direct"),
}
}
}
impl GraphWireStyle {
pub fn tooltip_description(&self) -> &'static str {
match self {
GraphWireStyle::GridAligned => "Wires follow the grid, running in straight lines between nodes.",
GraphWireStyle::Direct => "Wires bend to run at an angle directly between nodes.",
}
}
pub fn is_direct(&self) -> bool {
*self == GraphWireStyle::Direct
}
}
pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
let grid_spacing = 24.;
match graph_wire_style {
GraphWireStyle::Direct => {
let horizontal_gap = (output_position.x - input_position.x).abs();
let vertical_gap = (output_position.y - input_position.y).abs();
let curve_length = grid_spacing;
let curve_falloff_rate = curve_length * std::f64::consts::TAU;
let horizontal_curve_amount = -(2_f64.powf((-10. * horizontal_gap) / curve_falloff_rate)) + 1.;
let vertical_curve_amount = -(2_f64.powf((-10. * vertical_gap) / curve_falloff_rate)) + 1.;
let horizontal_curve = horizontal_curve_amount * curve_length;
let vertical_curve = vertical_curve_amount * curve_length;
let locations = [
output_position,
DVec2::new(
if vertical_out { output_position.x } else { output_position.x + horizontal_curve },
if vertical_out { output_position.y - vertical_curve } else { output_position.y },
),
DVec2::new(
if vertical_in { input_position.x } else { input_position.x - horizontal_curve },
if vertical_in { input_position.y + vertical_curve } else { input_position.y },
),
DVec2::new(input_position.x, input_position.y),
];
let smoothing = 0.5;
let delta01 = DVec2::new((locations[1].x - locations[0].x) * smoothing, (locations[1].y - locations[0].y) * smoothing);
let delta23 = DVec2::new((locations[3].x - locations[2].x) * smoothing, (locations[3].y - locations[2].y) * smoothing);
let mut wire = BezPath::new();
wire.move_to(dvec2_to_point(locations[0]));
wire.line_to(dvec2_to_point(locations[1]));
wire.curve_to(dvec2_to_point(locations[1] + delta01), dvec2_to_point(locations[2] - delta23), dvec2_to_point(locations[2]));
wire.line_to(dvec2_to_point(locations[3]));
wire
}
GraphWireStyle::GridAligned => {
let locations = straight_wire_path(output_position, input_position, vertical_out, vertical_in);
straight_wire_to_bezpath(locations)
}
}
}
fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec<IVec2> {
let grid_spacing = 24;
let line_width = 2;
let in_x = input_position.x as i32;
let in_y = input_position.y as i32;
let out_x = output_position.x as i32;
let out_y = output_position.y as i32;
let mid_x = (in_x + out_x) / 2 + (((in_x + out_x) / 2) % grid_spacing);
let mid_y = (in_y + out_y) / 2 + (((in_y + out_y) / 2) % grid_spacing);
let mid_y_alternate = (in_y + in_y) / 2 - (((in_y + in_y) / 2) % grid_spacing);
let x1 = out_x;
let x2 = out_x + grid_spacing;
let x3 = in_x - 2 * grid_spacing;
let x4 = in_x;
let x5 = in_x - 2 * grid_spacing + line_width;
let x6 = out_x + grid_spacing + line_width;
let x7 = out_x + 2 * grid_spacing + line_width;
let x8 = in_x + line_width;
let x9 = out_x + 2 * grid_spacing;
let x10 = mid_x + line_width;
let x11 = out_x - grid_spacing;
let x12 = out_x - 4 * grid_spacing;
let x13 = mid_x;
let x14 = in_x + grid_spacing;
let x15 = in_x - 4 * grid_spacing;
let x16 = in_x + 8 * grid_spacing;
let x17 = mid_x - 2 * line_width;
let x18 = out_x + grid_spacing - 2 * line_width;
let x19 = out_x - 2 * line_width;
let x20 = mid_x - line_width;
let y1 = out_y;
let y2 = out_y - grid_spacing;
let y3 = in_y;
let y4 = out_y - grid_spacing + 5 * line_width + 1;
let y5 = in_y - 2 * grid_spacing;
let y6 = out_y + 4 * line_width;
let y7 = out_y + 5 * line_width;
let y8 = out_y - 2 * grid_spacing + 5 * line_width + 1;
let y9 = out_y + 6 * line_width;
let y10 = in_y + 2 * grid_spacing;
let y111 = in_y + grid_spacing + 6 * line_width + 1;
let y12 = in_y + grid_spacing - 5 * line_width + 1;
let y13 = in_y - grid_spacing;
let y14 = in_y + grid_spacing;
let y15 = mid_y;
let y16 = mid_y_alternate;
let wire1 = vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x5, y4), IVec2::new(x5, y3), IVec2::new(x4, y3)];
let wire2 = vec![IVec2::new(x1, y1), IVec2::new(x1, y16), IVec2::new(x3, y16), IVec2::new(x3, y3), IVec2::new(x4, y3)];
let wire3 = vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x12, y4),
IVec2::new(x12, y10),
IVec2::new(x3, y10),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
let wire4 = vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x13, y4),
IVec2::new(x13, y10),
IVec2::new(x3, y10),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) {
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)];
}
// `outConnector` point and `inConnector` point lying on the same horizontal grid line and `outConnector` point lies to the right of `inConnector` point
if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) {
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)];
};
// Handle straight lines
if out_y == in_y || (out_x == in_x && vertical_out) {
return vec![IVec2::new(x1, y1), IVec2::new(x4, y3)];
};
// Handle standard right-angle paths
// Start vertical, then horizontal
// `outConnector` point lies to the left of `inConnector` point
if vertical_out && in_x > out_x {
// `outConnector` point lies above `inConnector` point
if out_y < in_y {
// `outConnector` point lies on the vertical grid line 4 units to the left of `inConnector` point point
if -4 * grid_spacing <= out_x - in_x && out_x - in_x < -3 * grid_spacing {
return wire1;
};
// `outConnector` point lying on vertical grid lines 3 and 2 units to the left of `inConnector` point
if -3 * grid_spacing <= out_x - in_x && out_x - in_x <= -grid_spacing {
if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing {
return vec![IVec2::new(x1, y1), IVec2::new(x1, y2), IVec2::new(x2, y2), IVec2::new(x2, y3), IVec2::new(x4, y3)];
};
if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 {
return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x6, y4), IVec2::new(x6, y3), IVec2::new(x4, y3)];
};
return vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x7, y4),
IVec2::new(x7, y5),
IVec2::new(x3, y5),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
}
// `outConnector` point lying on vertical grid line 1 units to the left of `inConnector` point
if -grid_spacing < out_x - in_x && out_x - in_x <= 0 {
// `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point
if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing {
return vec![IVec2::new(x1, y6), IVec2::new(x2, y6), IVec2::new(x8, y3)];
};
// `outConnector` point lying on the same horizontal grid line as `inConnector` point
if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 {
return vec![IVec2::new(x1, y7), IVec2::new(x4, y3)];
};
return vec![
IVec2::new(x1, y1),
IVec2::new(x1, y2),
IVec2::new(x9, y2),
IVec2::new(x9, y5),
IVec2::new(x3, y5),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
}
return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x10, y4), IVec2::new(x10, y3), IVec2::new(x4, y3)];
}
// `outConnector` point lies below `inConnector` point
// `outConnector` point lying on vertical grid line 1 unit to the left of `inConnector` point
if -grid_spacing <= out_x - in_x && out_x - in_x <= 0 {
// `outConnector` point lying on the horizontal grid lines 1 and 2 units below the `inConnector` point
if 0 <= out_y - in_y && out_y - in_y <= 2 * grid_spacing {
return vec![IVec2::new(x1, y6), IVec2::new(x11, y6), IVec2::new(x11, y3), IVec2::new(x4, y3)];
};
return wire2;
}
return vec![IVec2::new(x1, y1), IVec2::new(x1, y3), IVec2::new(x4, y3)];
}
// `outConnector` point lies to the right of `inConnector` point
if vertical_out && in_x <= out_x {
// `outConnector` point lying on any horizontal grid line above `inConnector` point
if out_y < in_y {
// `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point
if -2 * grid_spacing < out_y - in_y && out_y - in_y <= -grid_spacing {
return wire1;
};
// `outConnector` point lying on the same horizontal grid line as `inConnector` point
if -grid_spacing < out_y - in_y && out_y - in_y <= 0 {
return vec![IVec2::new(x1, y1), IVec2::new(x1, y8), IVec2::new(x5, y8), IVec2::new(x5, y3), IVec2::new(x4, y3)];
};
// `outConnector` point lying on vertical grid lines 1 and 2 units to the right of `inConnector` point
if grid_spacing <= out_x - in_x && out_x - in_x <= 3 * grid_spacing {
return vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x9, y4),
IVec2::new(x9, y5),
IVec2::new(x3, y5),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
}
return vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x10, y4),
IVec2::new(x10, y5),
IVec2::new(x5, y5),
IVec2::new(x5, y3),
IVec2::new(x4, y3),
];
}
// `outConnector` point lies below `inConnector` point
if out_y - in_y <= grid_spacing {
// `outConnector` point lies on the horizontal grid line 1 unit below the `inConnector` Point
if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing {
return vec![IVec2::new(x1, y9), IVec2::new(x3, y9), IVec2::new(x3, y3), IVec2::new(x4, y3)];
};
if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing {
return wire3;
};
return wire4;
}
// `outConnector` point lies on the horizontal grid line 2 units below `outConnector` point
if grid_spacing <= out_y - in_y && out_y - in_y <= 2 * grid_spacing {
if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing {
return vec![IVec2::new(x1, y7), IVec2::new(x5, y7), IVec2::new(x5, y3), IVec2::new(x4, y3)];
};
if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing {
return wire3;
};
return wire4;
}
// 0 to 4 units below the `outConnector` Point
if out_y - in_y <= 4 * grid_spacing {
return wire1;
};
return wire2;
}
// Start horizontal, then vertical
if vertical_in {
// when `outConnector` lies below `inConnector`
if out_y > in_y {
// `out_x` lies to the left of `in_x`
if out_x < in_x {
return vec![IVec2::new(x1, y1), IVec2::new(x4, y1), IVec2::new(x4, y3)];
};
// `out_x` lies to the right of `in_x`
if out_y - in_y <= grid_spacing {
// `outConnector` point directly below `inConnector` point
if 0 <= out_x - in_x && out_x - in_x <= grid_spacing {
return vec![IVec2::new(x1, y1), IVec2::new(x14, y1), IVec2::new(x14, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)];
};
// `outConnector` point lies below `inConnector` point and strictly to the right of `inConnector` point
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y111), IVec2::new(x4, y111), IVec2::new(x4, y3)];
}
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)];
}
// `out_y` lies on or above the `in_y` point
if -6 * grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing {
// edge case: `outConnector` point lying on vertical grid lines ranging from 4 units to left to 5 units to right of `inConnector` point
if -grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing {
return vec![
IVec2::new(x1, y1),
IVec2::new(x2, y1),
IVec2::new(x2, y2),
IVec2::new(x15, y2),
IVec2::new(x15, y12),
IVec2::new(x4, y12),
IVec2::new(x4, y3),
];
}
return vec![IVec2::new(x1, y1), IVec2::new(x16, y1), IVec2::new(x16, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
}
// left of edge case: `outConnector` point lying on vertical grid lines more than 4 units to left of `inConnector` point
if 4 * grid_spacing < in_x - out_x {
return vec![IVec2::new(x1, y1), IVec2::new(x17, y1), IVec2::new(x17, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
};
// right of edge case: `outConnector` point lying on the vertical grid lines more than 5 units to right of `inConnector` point
if 6 * grid_spacing > in_x - out_x {
return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
};
}
// Both horizontal - use horizontal middle point
// When `inConnector` point is one of the two closest diagonally opposite points
if 0 <= in_x - out_x && in_x - out_x <= grid_spacing && in_y - out_y >= -grid_spacing && in_y - out_y <= grid_spacing {
return vec![IVec2::new(x19, y1), IVec2::new(x19, y3), IVec2::new(x4, y3)];
}
// When `inConnector` point lies on the horizontal line 1 unit above and below the `outConnector` point
if -grid_spacing <= out_y - in_y && out_y - in_y <= grid_spacing && out_x > in_x {
// Horizontal line above `out_y`
if in_y < out_y {
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y13), IVec2::new(x3, y13), IVec2::new(x3, y3), IVec2::new(x4, y3)];
};
// Horizontal line below `out_y`
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y14), IVec2::new(x3, y14), IVec2::new(x3, y3), IVec2::new(x4, y3)];
}
// `outConnector` point to the right of `inConnector` point
if out_x > in_x - grid_spacing {
return vec![
IVec2::new(x1, y1),
IVec2::new(x18, y1),
IVec2::new(x18, y15),
IVec2::new(x5, y15),
IVec2::new(x5, y3),
IVec2::new(x4, y3),
];
};
// When `inConnector` point lies on the vertical grid line two units to the right of `outConnector` point
if grid_spacing <= in_x - out_x && in_x - out_x <= 2 * grid_spacing {
return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y3), IVec2::new(x4, y3)];
};
vec![IVec2::new(x1, y1), IVec2::new(x20, y1), IVec2::new(x20, y3), IVec2::new(x4, y3)]
}
fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
if locations.is_empty() {
return BezPath::new();
}
let to_point = |location: IVec2| Point::new(location.x as f64, location.y as f64);
if locations.len() == 2 {
let p1 = to_point(locations[0]);
let p2 = to_point(locations[1]);
Line::new(p1, p2).to_path(DEFAULT_ACCURACY);
}
let corner_radius = 10;
// Create path with rounded corners
let mut path = BezPath::new();
path.move_to(to_point(locations[0]));
for i in 1..(locations.len() - 1) {
let prev = locations[i - 1];
let curr = locations[i];
let next = locations[i + 1];
let corner_start = IVec2::new(
curr.x
+ if curr.x == prev.x {
0
} else if prev.x > curr.x {
corner_radius
} else {
-corner_radius
},
curr.y
+ if curr.y == prev.y {
0
} else if prev.y > curr.y {
corner_radius
} else {
-corner_radius
},
);
let corner_start_mid = IVec2::new(
curr.x
+ if curr.x == prev.x {
0
} else if prev.x > curr.x {
corner_radius / 2
} else {
-corner_radius / 2
},
curr.y
+ if curr.y == prev.y {
0
} else {
match prev.y > curr.y {
true => corner_radius / 2,
false => -corner_radius / 2,
}
},
);
let corner_end = IVec2::new(
curr.x
+ if curr.x == next.x {
0
} else if next.x > curr.x {
corner_radius
} else {
-corner_radius
},
curr.y
+ if curr.y == next.y {
0
} else if next.y > curr.y {
corner_radius
} else {
-corner_radius
},
);
let corner_end_mid = IVec2::new(
curr.x
+ if curr.x == next.x {
0
} else if next.x > curr.x {
corner_radius / 2
} else {
-corner_radius / 2
},
curr.y
+ if curr.y == next.y {
0
} else if next.y > curr.y {
10 / 2
} else {
-corner_radius / 2
},
);
path.line_to(to_point(corner_start));
path.curve_to(to_point(corner_start_mid), to_point(corner_end_mid), to_point(corner_end));
}
path.line_to(to_point(*locations.last().unwrap()));
path
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/network_interface/memo_network.rs | editor/src/messages/portfolio/document/utility_types/network_interface/memo_network.rs | use graph_craft::document::NodeNetwork;
use std::cell::Cell;
use std::hash::{Hash, Hasher};
#[derive(Debug, Default, Clone, PartialEq)]
pub struct MemoNetwork {
network: NodeNetwork,
hash_code: Cell<Option<u64>>,
}
impl<'de> serde::Deserialize<'de> for MemoNetwork {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Self::new(NodeNetwork::deserialize(deserializer)?))
}
}
impl serde::Serialize for MemoNetwork {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.network.serialize(serializer)
}
}
impl Hash for MemoNetwork {
fn hash<H: Hasher>(&self, state: &mut H) {
self.current_hash().hash(state);
}
}
impl MemoNetwork {
pub fn network(&self) -> &NodeNetwork {
&self.network
}
pub fn network_mut(&mut self) -> &mut NodeNetwork {
self.hash_code.set(None);
&mut self.network
}
pub fn new(network: NodeNetwork) -> Self {
Self { network, hash_code: None.into() }
}
pub fn current_hash(&self) -> u64 {
let mut hash_code = self.hash_code.get();
if hash_code.is_none() {
hash_code = Some(self.network.current_hash());
self.hash_code.set(hash_code);
}
hash_code.unwrap()
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/network_interface/deserialization.rs | editor/src/messages/portfolio/document/utility_types/network_interface/deserialization.rs | use crate::messages::portfolio::document::utility_types::network_interface::{DocumentNodePersistentMetadata, InputMetadata, InputPersistentMetadata, NodeNetworkMetadata, NodeTypePersistentMetadata};
use serde_json::Value;
use std::collections::HashMap;
/// Persistent metadata for each node in the network, which must be included when creating, serializing, and deserializing saving a node.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DocumentNodePersistentMetadataInputNames {
pub reference: Option<String>,
#[serde(default)]
pub display_name: String,
pub input_names: Vec<String>,
pub output_names: Vec<String>,
pub has_primary_output: bool,
#[serde(default)]
pub locked: bool,
#[serde(default)]
pub pinned: bool,
pub node_type_metadata: NodeTypePersistentMetadata,
pub network_metadata: Option<NodeNetworkMetadata>,
}
impl From<DocumentNodePersistentMetadataInputNames> for DocumentNodePersistentMetadata {
fn from(old: DocumentNodePersistentMetadataInputNames) -> Self {
DocumentNodePersistentMetadata {
input_metadata: Vec::new(),
reference: old.reference,
display_name: old.display_name,
output_names: old.output_names,
locked: old.locked,
pinned: old.pinned,
node_type_metadata: old.node_type_metadata,
network_metadata: old.network_metadata,
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DocumentNodePersistentMetadataPropertiesRow {
pub reference: Option<String>,
#[serde(default)]
pub display_name: String,
pub input_properties: Vec<PropertiesRow>,
pub output_names: Vec<String>,
pub has_primary_output: bool,
#[serde(default)]
pub locked: bool,
#[serde(default)]
pub pinned: bool,
pub node_type_metadata: NodeTypePersistentMetadata,
pub network_metadata: Option<NodeNetworkMetadata>,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PropertiesRow {
pub input_data: HashMap<String, Value>,
pub widget_override: Option<String>,
#[serde(skip)]
pub input_name: String,
#[serde(skip)]
pub input_description: String,
}
impl From<DocumentNodePersistentMetadataPropertiesRow> for DocumentNodePersistentMetadata {
fn from(old: DocumentNodePersistentMetadataPropertiesRow) -> Self {
let mut input_metadata = Vec::new();
for properties_row in old.input_properties {
input_metadata.push(InputMetadata {
persistent_metadata: InputPersistentMetadata {
input_data: properties_row.input_data,
widget_override: properties_row.widget_override,
input_name: properties_row.input_name,
input_description: properties_row.input_description,
},
..Default::default()
})
}
DocumentNodePersistentMetadata {
reference: old.reference,
display_name: old.display_name,
input_metadata: Vec::new(),
output_names: old.output_names,
locked: old.locked,
pinned: old.pinned,
node_type_metadata: old.node_type_metadata,
network_metadata: old.network_metadata,
}
}
}
/// Persistent metadata for each node in the network, which must be included when creating, serializing, and deserializing saving a node.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DocumentNodePersistentMetadataHasPrimaryOutput {
pub reference: Option<String>,
#[serde(default)]
pub display_name: String,
pub input_metadata: Vec<InputMetadata>,
pub output_names: Vec<String>,
pub has_primary_output: bool,
#[serde(default)]
pub locked: bool,
#[serde(default)]
pub pinned: bool,
pub node_type_metadata: NodeTypePersistentMetadata,
pub network_metadata: Option<NodeNetworkMetadata>,
}
impl From<DocumentNodePersistentMetadataHasPrimaryOutput> for DocumentNodePersistentMetadata {
fn from(old: DocumentNodePersistentMetadataHasPrimaryOutput) -> Self {
DocumentNodePersistentMetadata {
reference: old.reference,
display_name: old.display_name,
input_metadata: old.input_metadata,
output_names: old.output_names,
locked: old.locked,
pinned: old.pinned,
node_type_metadata: old.node_type_metadata,
network_metadata: old.network_metadata,
}
}
}
pub fn deserialize_node_persistent_metadata<'de, D>(deserializer: D) -> Result<DocumentNodePersistentMetadata, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
let value = Value::deserialize(deserializer)?;
if let Ok(document) = serde_json::from_value::<DocumentNodePersistentMetadataHasPrimaryOutput>(value.clone()) {
return Ok(document.into());
};
if let Ok(document) = serde_json::from_value::<DocumentNodePersistentMetadata>(value.clone()) {
return Ok(document);
};
if let Ok(document) = serde_json::from_value::<DocumentNodePersistentMetadataPropertiesRow>(value.clone()) {
return Ok(document.into());
};
match serde_json::from_value::<DocumentNodePersistentMetadataInputNames>(value.clone()) {
Ok(document) => Ok(document.into()),
Err(e) => Err(serde::de::Error::custom(e)),
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs | editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs | use std::collections::{HashMap, HashSet};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
use graph_craft::proto::{GraphErrorType, GraphErrors};
use graph_craft::{Type, concrete};
use graphene_std::uuid::NodeId;
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::node_registry::NODE_REGISTRY;
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
// This file contains utility methods for interfacing with the resolved types returned from the compiler
#[derive(Debug, Default)]
pub struct ResolvedDocumentNodeTypes {
pub types: HashMap<Vec<NodeId>, NodeTypes>,
pub node_graph_errors: GraphErrors,
}
impl ResolvedDocumentNodeTypes {
pub fn update(&mut self, delta: ResolvedDocumentNodeTypesDelta, errors: GraphErrors) {
for (path, node_type) in delta.add {
self.types.insert(path.to_vec(), node_type);
}
for path in delta.remove {
self.types.remove(&path.to_vec());
}
self.node_graph_errors = errors;
}
}
/// Represents the result of a type query for an input or output connector.
#[derive(Debug, Clone, PartialEq)]
pub enum TypeSource {
/// A type that has been compiled based on all upstream types.
Compiled(Type),
/// The type of value inputs.
TaggedValue(Type),
/// When the input/output is not compiled. The Type is from the document node definition, or () if it doesn't exist.
Unknown,
/// When there is a node graph error for the inputs to a node. The Type is from the document node definition, or () if it doesn't exist.
Invalid,
/// When there is an error in the algorithm for determining the input/output type (indicates a bug in the editor).
Error(&'static str),
}
impl TypeSource {
/// The reduced set of frontend types for displaying color.
pub fn displayed_type(&self) -> FrontendGraphDataType {
if matches!(self, TypeSource::Invalid) {
return FrontendGraphDataType::Invalid;
};
match self.compiled_nested_type() {
Some(nested_type) => match TaggedValue::from_type_or_none(nested_type) {
TaggedValue::U32(_)
| TaggedValue::U64(_)
| TaggedValue::F32(_)
| TaggedValue::F64(_)
| TaggedValue::DVec2(_)
| TaggedValue::F64Array4(_)
| TaggedValue::VecF64(_)
| TaggedValue::VecDVec2(_)
| TaggedValue::DAffine2(_) => FrontendGraphDataType::Number,
TaggedValue::Artboard(_) => FrontendGraphDataType::Artboard,
TaggedValue::Graphic(_) => FrontendGraphDataType::Graphic,
TaggedValue::Raster(_) => FrontendGraphDataType::Raster,
TaggedValue::Vector(_) => FrontendGraphDataType::Vector,
TaggedValue::Color(_) => FrontendGraphDataType::Color,
TaggedValue::Gradient(_) | TaggedValue::GradientStops(_) | TaggedValue::GradientTable(_) => FrontendGraphDataType::Gradient,
TaggedValue::String(_) => FrontendGraphDataType::Typography,
_ => FrontendGraphDataType::General,
},
None => FrontendGraphDataType::General,
}
}
pub fn compiled_nested_type(&self) -> Option<&Type> {
match self {
TypeSource::Compiled(compiled_type) => Some(compiled_type.nested_type()),
TypeSource::TaggedValue(value_type) => Some(value_type.nested_type()),
_ => None,
}
}
/// Used when searching for nodes in the add Node popup.
pub fn add_node_string(self) -> Option<String> {
self.compiled_nested_type().map(|ty| format!("type:{ty}"))
}
/// The type to display in the tooltip label.
pub fn resolved_type_tooltip_string(&self) -> String {
match self {
TypeSource::Compiled(compiled_type) => format!("Data Type: {:?}", compiled_type.nested_type().to_string()),
TypeSource::TaggedValue(value_type) => format!("Data Type: {:?}", value_type.nested_type().to_string()),
TypeSource::Unknown => "Unknown Data Type".to_string(),
TypeSource::Invalid => "Invalid Type Combination".to_string(),
TypeSource::Error(_) => "Error Getting Data Type".to_string(),
}
}
/// The type to display in the node row.
pub fn resolved_type_node_string(&self) -> String {
match self {
TypeSource::Compiled(compiled_type) => compiled_type.nested_type().to_string(),
TypeSource::TaggedValue(value_type) => value_type.nested_type().to_string(),
TypeSource::Unknown => "Unknown".to_string(),
TypeSource::Invalid => "Invalid".to_string(),
TypeSource::Error(_) => "Error".to_string(),
}
}
}
impl NodeNetworkInterface {
fn input_has_error(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
match input_connector {
InputConnector::Node { node_id, input_index } => {
let Some(implementation) = self.implementation(node_id, network_path) else {
log::error!("Could not get implementation in input_has_error");
return false;
};
let node_path = [network_path, &[*node_id]].concat();
match implementation {
DocumentNodeImplementation::Network(_) => {
let Some(map) = self.outward_wires(&node_path) else { return false };
let Some(outward_wires) = map.get(&OutputConnector::Import(*input_index)) else { return false };
outward_wires.clone().iter().any(|connector| match connector {
InputConnector::Node { node_id, input_index } => self.input_has_error(&InputConnector::node(*node_id, *input_index), &node_path),
InputConnector::Export(_) => false,
})
}
DocumentNodeImplementation::ProtoNode(_) => self.resolved_types.node_graph_errors.iter().any(|error| {
error.node_path == node_path
&& match &error.error {
GraphErrorType::InvalidImplementations { error_inputs, .. } => error_inputs.iter().any(|solution| solution.iter().any(|(index, _)| index == input_index)),
_ => true,
}
}),
DocumentNodeImplementation::Extract => false,
}
}
InputConnector::Export(_) => false,
}
}
pub fn input_type_not_invalid(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> TypeSource {
let Some(input) = self.input_from_connector(input_connector, network_path) else {
return TypeSource::Error("Could not get input from connector");
};
match input {
NodeInput::Node { node_id, output_index } => {
let output_connector = OutputConnector::node(*node_id, *output_index);
self.output_type(&output_connector, network_path)
}
NodeInput::Value { tagged_value, .. } => TypeSource::TaggedValue(tagged_value.ty()),
NodeInput::Import { import_index, .. } => {
// Get the input type of the encapsulating node input
let Some((encapsulating_node, encapsulating_path)) = network_path.split_last() else {
return TypeSource::Error("Could not get type of import in document network since it has no imports");
};
self.input_type(&InputConnector::node(*encapsulating_node, *import_index), encapsulating_path)
}
NodeInput::Scope(_) => TypeSource::Compiled(concrete!(())),
NodeInput::Reflection(document_node_metadata) => TypeSource::Compiled(document_node_metadata.ty()),
NodeInput::Inline(_) => TypeSource::Compiled(concrete!(InlineRust)),
}
}
/// Get the [`TypeSource`] for any InputConnector.
/// If the input is not compiled, then an Unknown or default from the definition is returned.
pub fn input_type(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> TypeSource {
// First check if there is an error with this node or any protonodes it is connected to
if self.input_has_error(input_connector, network_path) {
return TypeSource::Invalid;
}
self.input_type_not_invalid(input_connector, network_path)
}
// Gets the default tagged value for an input. If its not compiled, then it tries to get a valid type. If there are no valid types, then it picks a random implementation
pub fn tagged_value_from_input(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> TaggedValue {
let guaranteed_type = match self.input_type(input_connector, network_path) {
TypeSource::Compiled(compiled) => compiled,
TypeSource::TaggedValue(value) => value,
TypeSource::Unknown | TypeSource::Invalid => {
// Pick a random type from the complete valid types
// TODO: Add a NodeInput::Indeterminate which can be resolved at compile time to be any type that prevents an error. This may require bidirectional typing.
self.complete_valid_input_types(input_connector, network_path)
.into_iter()
.min_by_key(|ty| ty.nested_type().to_string())
// Pick a random type from the potential valid types
.or_else(|| {
self.potential_valid_input_types(input_connector, network_path)
.into_iter()
.min_by_key(|ty| ty.nested_type().to_string())
}).unwrap_or(concrete!(()))
}
TypeSource::Error(e) => {
log::error!("Error getting tagged_value_from_input for {input_connector:?} {e}");
concrete!(())
}
};
TaggedValue::from_type_or_none(&guaranteed_type)
}
/// A list of all valid input types for this specific node.
pub fn potential_valid_input_types(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
let InputConnector::Node { node_id, input_index } = input_connector else {
// An export can have any type connected to it
return vec![graph_craft::generic!(T)];
};
let Some(implementation) = self.implementation(node_id, network_path) else {
log::error!("Could not get node implementation in potential_valid_input_types");
return Vec::new();
};
match implementation {
DocumentNodeImplementation::Network(_) => {
let nested_path = [network_path, &[*node_id]].concat();
let Some(outward_wires) = self.outward_wires(&nested_path) else {
log::error!("Could not get outward wires in potential_valid_input_types");
return Vec::new();
};
let Some(inputs_from_import) = outward_wires.get(&OutputConnector::Import(*input_index)) else {
log::error!("Could not get inputs from import in potential_valid_input_types");
return Vec::new();
};
let intersection: HashSet<Type> = inputs_from_import
.clone()
.iter()
.map(|input_connector| self.potential_valid_input_types(input_connector, &nested_path).into_iter().collect::<HashSet<_>>())
.fold(None, |acc: Option<HashSet<Type>>, set| match acc {
Some(acc_set) => Some(acc_set.intersection(&set).cloned().collect()),
None => Some(set),
})
.unwrap_or_default();
intersection.into_iter().collect::<Vec<_>>()
}
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
let Some(implementations) = NODE_REGISTRY.get(proto_node_identifier) else {
log::error!("Protonode {proto_node_identifier:?} not found in registry in potential_valid_input_types");
return Vec::new();
};
let number_of_inputs = self.number_of_inputs(node_id, network_path);
implementations
.iter()
.filter_map(|(node_io, _)| {
// Check if this NodeIOTypes implementation is valid for the other inputs
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
// TODO: Fix type checking for different call arguments
// For example a node input of (Footprint) -> Vector would not be compatible with a node that is called with () and returns Vector
node_io.inputs.get(iterator_index).map(|ty| ty.nested_type()) == input_type.compiled_nested_type()
});
// If so, then return the input at the chosen index
if valid_implementation { node_io.inputs.get(*input_index).cloned() } else { None }
})
.collect::<Vec<_>>()
}
DocumentNodeImplementation::Extract => {
log::error!("Input types for extract node not supported");
Vec::new()
}
}
}
/// Performs a downstream traversal to ensure input type will work in the full context of the graph.
pub fn complete_valid_input_types(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
match input_connector {
InputConnector::Node { node_id, input_index } => {
let Some(implementation) = self.implementation(node_id, network_path) else {
log::error!("Could not get node implementation for {:?} {} in complete_valid_input_types", network_path, *node_id);
return Vec::new();
};
match implementation {
DocumentNodeImplementation::Network(_) => self.valid_output_types(&OutputConnector::Import(input_connector.input_index()), &[network_path, &[*node_id]].concat()),
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
let Some(implementations) = NODE_REGISTRY.get(proto_node_identifier) else {
log::error!("Protonode {proto_node_identifier:?} not found in registry in complete_valid_input_types");
return Vec::new();
};
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
implementations
.iter()
.filter_map(|(node_io, _)| {
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
return None;
}
let valid_inputs = (0..node_io.inputs.len()).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
match input_type.compiled_nested_type() {
Some(input_type) => node_io.inputs.get(iterator_index).is_some_and(|node_io_input_type| node_io_input_type.nested_type() == input_type),
None => true,
}
});
if valid_inputs { node_io.inputs.get(*input_index).cloned() } else { None }
})
.collect::<Vec<_>>()
}
DocumentNodeImplementation::Extract => Vec::new(),
}
}
InputConnector::Export(export_index) => {
match network_path.split_last() {
Some((encapsulating_node, encapsulating_path)) => self.valid_output_types(&OutputConnector::node(*encapsulating_node, *export_index), encapsulating_path),
None => {
// Valid types for the export are all types that can be fed into the render node
let render_node = graphene_std::render_node::render::IDENTIFIER;
let Some(implementations) = NODE_REGISTRY.get(&render_node) else {
log::error!("Protonode {render_node:?} not found in registry");
return Vec::new();
};
implementations.keys().map(|types| types.inputs[1].clone()).collect()
}
}
}
}
}
pub fn output_type(&mut self, output_connector: &OutputConnector, network_path: &[NodeId]) -> TypeSource {
match output_connector {
OutputConnector::Node { node_id, output_index } => {
// First try iterating upstream to the first protonode and try get its compiled type
let Some(implementation) = self.implementation(node_id, network_path) else {
return TypeSource::Error("Could not get implementation");
};
match implementation {
DocumentNodeImplementation::Network(_) => self.input_type(&InputConnector::Export(*output_index), &[network_path, &[*node_id]].concat()),
DocumentNodeImplementation::ProtoNode(_) => match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
None => TypeSource::Unknown,
},
DocumentNodeImplementation::Extract => TypeSource::Compiled(concrete!(())),
}
}
OutputConnector::Import(import_index) => {
let Some((encapsulating_node, encapsulating_path)) = network_path.split_last() else {
return TypeSource::Error("Cannot get import type in document network since it has no imports");
};
let mut input_type = self.input_type(&InputConnector::node(*encapsulating_node, *import_index), encapsulating_path);
if matches!(input_type, TypeSource::Invalid) {
input_type = TypeSource::Unknown
}
input_type
}
}
}
/// The valid output types are all types that are valid for each downstream connection.
fn valid_output_types(&mut self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Vec<Type> {
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in valid_output_types");
return Vec::new();
};
let Some(inputs_from_import) = outward_wires.get(output_connector) else {
log::error!("Could not get inputs from import in valid_output_types");
return Vec::new();
};
let intersection = inputs_from_import
.clone()
.iter()
.map(|input_connector| self.potential_valid_input_types(input_connector, network_path).into_iter().collect::<HashSet<_>>())
.fold(None, |acc: Option<HashSet<Type>>, set| match acc {
Some(acc_set) => Some(acc_set.intersection(&set).cloned().collect()),
None => Some(set),
})
.unwrap_or_default();
intersection.into_iter().collect::<Vec<_>>()
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs | editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs | use super::transform_utils;
use super::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
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 crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::Color;
use graphene_std::renderer::Quad;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::table::Table;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Fill, Gradient, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
#[derive(ExtractField)]
pub struct GraphOperationMessageContext<'a> {
pub network_interface: &'a mut NodeNetworkInterface,
pub collapsed: &'a mut CollapsedLayers,
pub node_graph: &'a mut NodeGraphMessageHandler,
}
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize, ExtractField)]
pub struct GraphOperationMessageHandler {}
// GraphOperationMessageHandler always modified the document network. This is so changes to the layers panel will only affect the document network.
// For changes to the selected network, use NodeGraphMessageHandler. No NodeGraphMessage's should be added here, since they will affect the selected nested network.
#[message_handler_data]
impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for GraphOperationMessageHandler {
fn process_message(&mut self, message: GraphOperationMessage, responses: &mut VecDeque<Message>, context: GraphOperationMessageContext) {
let network_interface = context.network_interface;
match message {
GraphOperationMessage::FillSet { layer, fill } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.fill_set(fill);
}
}
GraphOperationMessage::BlendingFillSet { layer, fill } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.blending_fill_set(fill);
}
}
GraphOperationMessage::OpacitySet { layer, opacity } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.opacity_set(opacity);
}
}
GraphOperationMessage::BlendModeSet { layer, blend_mode } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.blend_mode_set(blend_mode);
}
}
GraphOperationMessage::ClipModeToggle { layer } => {
let clip_mode = get_clip_mode(layer, network_interface);
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.clip_mode_toggle(clip_mode);
}
}
GraphOperationMessage::StrokeSet { layer, stroke } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.stroke_set(stroke);
}
}
GraphOperationMessage::TransformChange {
layer,
transform,
transform_in,
skip_rerender,
} => {
let parent_transform = network_interface.document_metadata().downstream_transform_to_viewport(layer);
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.transform_change_with_parent(transform, transform_in, parent_transform, skip_rerender);
}
}
GraphOperationMessage::TransformSet {
layer,
transform,
transform_in,
skip_rerender,
} => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.transform_set(transform, transform_in, skip_rerender);
}
}
GraphOperationMessage::Vector { layer, modification_type } => {
if layer == LayerNodeIdentifier::ROOT_PARENT {
log::error!("Cannot run Vector on ROOT_PARENT");
return;
}
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.vector_modify(modification_type);
}
}
GraphOperationMessage::Brush { layer, strokes } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.brush_modify(strokes);
}
}
GraphOperationMessage::SetUpstreamToChain { layer } => {
let Some(OutputConnector::Node { node_id: first_chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::node(layer.to_node(), 1), &[]) else {
return;
};
network_interface.force_set_upstream_to_chain(&first_chain_node, &[]);
}
GraphOperationMessage::NewArtboard { id, artboard } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let artboard_location = artboard.location;
let artboard_layer = modify_inputs.create_artboard(id, artboard);
network_interface.move_layer_to_stack(artboard_layer, LayerNodeIdentifier::ROOT_PARENT, 0, &[]);
// If there is a non artboard feeding into the primary input of the artboard, move it to the secondary input
let Some(artboard) = network_interface.document_network().nodes.get(&id) else {
log::error!("Artboard not created");
return;
};
let document_metadata = network_interface.document_metadata();
let primary_input = artboard.inputs.first().expect("Artboard should have a primary input").clone();
if let NodeInput::Node { node_id, .. } = &primary_input {
if network_interface.is_artboard(node_id, &[]) {
// Nothing to do here: we have a stack full of artboards!
} else if network_interface.is_layer(node_id, &[]) {
// We have a stack of non-layer artboards.
for (insert_index, layer) in LayerNodeIdentifier::ROOT_PARENT.children(document_metadata).filter(|&layer| layer != artboard_layer).enumerate() {
// Parent the layer to our new artboard (retaining ordering)
responses.add(NodeGraphMessage::MoveLayerToStack {
layer,
parent: artboard_layer,
insert_index,
});
// Apply a translation to prevent the content from shifting
responses.add(GraphOperationMessage::TransformChange {
layer,
transform: DAffine2::from_translation(-artboard_location.as_dvec2()),
transform_in: TransformIn::Local,
skip_rerender: true,
});
}
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::value(TaggedValue::Artboard(Table::new()), true);
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
} else {
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
network_interface.disconnect_input(&InputConnector::node(artboard_layer.to_node(), 0), &[]);
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 1), primary_input, &[]);
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::value(TaggedValue::Artboard(Table::new()), true);
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
}
}
responses.add_front(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewBitmapLayer {
id,
image_frame,
parent,
insert_index,
} => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
modify_inputs.insert_image_data(image_frame, layer);
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewBooleanOperationLayer { id, operation, parent, insert_index } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
modify_inputs.insert_boolean_data(operation, layer);
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id: id,
alias: "Boolean Operation".to_string(),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewCustomLayer { id, nodes, parent, insert_index } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
if !nodes.is_empty() {
// Add the nodes to the network
let new_ids: HashMap<_, _> = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
// Since all the new nodes are already connected, just connect the input of the layer to first new node
let first_new_node_id = new_ids[&NodeId(0)];
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids });
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(layer.to_node(), 1),
input: NodeInput::node(first_new_node_id, 0),
});
}
// Move the layer and all nodes to the correct position in the network
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewVectorLayer { id, subpaths, parent, insert_index } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
modify_inputs.insert_vector(subpaths, layer, true, true, true);
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewTextLayer {
id,
text,
font,
typesetting,
parent,
insert_index,
} => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
modify_inputs.insert_text(text, font, typesetting, layer);
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(GraphOperationMessage::StrokeSet { layer, stroke: Stroke::default() });
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::ResizeArtboard { layer, location, dimensions } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.resize_artboard(location, dimensions);
}
}
GraphOperationMessage::RemoveArtboards => {
if network_interface.all_artboards().is_empty() {
return;
}
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: network_interface.all_artboards().iter().map(|layer_node| layer_node.to_node()).collect(),
delete_children: false,
});
let mut artboard_data: HashMap<NodeId, ArtboardInfo> = HashMap::new();
// Go through all artboards and create merge nodes
for artboard in network_interface.all_artboards() {
let node_id = NodeId::new();
let Some(document_node) = network_interface.document_network().nodes.get(&artboard.to_node()) else {
log::error!("Artboard not created");
responses.add(DocumentMessage::AbortTransaction);
return;
};
artboard_data.insert(
artboard.to_node(),
ArtboardInfo {
input_node: NodeInput::node(document_node.inputs[1].as_node().unwrap_or_default(), 0),
output_nodes: network_interface
.outward_wires(&[])
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(artboard.to_node(), 0)))
.cloned()
.unwrap_or_default(),
merge_node: node_id,
},
);
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
modify_inputs.create_layer(node_id);
responses.add(NodeGraphMessage::SetDisplayName {
node_id,
alias: network_interface.display_name(&artboard.to_node(), &[]),
skip_adding_history_step: true,
});
// Shift node positions in the graph
let (x, y) = network_interface.position(&artboard.to_node(), &[]).unwrap_or_default().into();
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
}
// Go through all artboards and connect them to the merge nodes
for artboard in &artboard_data {
// Modify downstream connections
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(artboard.1.merge_node, 1),
input: NodeInput::node(artboard.1.input_node.as_node().unwrap_or_default(), 0),
});
// 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 = 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 });
}
// Apply a transformation to the newly created layers to match the original artboard position
let offset = network_interface
.document_metadata()
.bounding_box_document(LayerNodeIdentifier::new_unchecked(*artboard.0))
.map(|p| p[0])
.unwrap_or_default();
responses.add(GraphOperationMessage::TransformChange {
layer: LayerNodeIdentifier::new_unchecked(artboard.1.merge_node),
transform: DAffine2::from_translation(offset),
transform_in: TransformIn::Local,
skip_rerender: false,
});
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::SendGraph);
}
GraphOperationMessage::NewSvg {
id,
svg,
transform,
parent,
insert_index,
} => {
let tree = match usvg::Tree::from_str(&svg, &usvg::Options::default()) {
Ok(t) => t,
Err(e) => {
responses.add(DialogMessage::DisplayDialogError {
title: "SVG parsing failed".to_string(),
description: e.to_string(),
});
return;
}
};
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let size = tree.size();
let offset_to_center = DVec2::new(size.width() as f64, size.height() as f64) / -2.;
let transform = transform * DAffine2::from_translation(offset_to_center);
import_usvg_node(&mut modify_inputs, &usvg::Node::Group(Box::new(tree.root().clone())), transform, id, parent, insert_index);
}
}
}
fn actions(&self) -> ActionList {
actions!(GraphOperationMessage;)
}
}
#[derive(Debug, Clone)]
struct ArtboardInfo {
input_node: NodeInput,
output_nodes: Vec<InputConnector>,
merge_node: NodeId,
}
fn usvg_color(c: usvg::Color, a: f32) -> Color {
Color::from_rgbaf32_unchecked(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
}
fn usvg_transform(c: usvg::Transform) -> DAffine2 {
DAffine2::from_cols_array(&[c.sx as f64, c.ky as f64, c.kx as f64, c.sy as f64, c.tx as f64, c.ty as f64])
}
fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, transform: DAffine2, id: NodeId, parent: LayerNodeIdentifier, insert_index: usize) {
let layer = modify_inputs.create_layer(id);
modify_inputs.network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
modify_inputs.layer_node = Some(layer);
if let Some(upstream_layer) = layer.next_sibling(modify_inputs.network_interface.document_metadata()) {
modify_inputs.network_interface.shift_node(&upstream_layer.to_node(), IVec2::new(0, 3), &[]);
}
match node {
usvg::Node::Group(group) => {
for child in group.children() {
import_usvg_node(modify_inputs, child, transform, NodeId::new(), layer, 0);
}
modify_inputs.layer_node = Some(layer);
}
usvg::Node::Path(path) => {
let subpaths = convert_usvg_path(path);
let bounds = subpaths.iter().filter_map(|subpath| subpath.bounding_box()).reduce(Quad::combine_bounds).unwrap_or_default();
modify_inputs.insert_vector(subpaths, layer, true, path.fill().is_some(), path.stroke().is_some());
if let Some(transform_node_id) = modify_inputs.existing_node_id("Transform", true) {
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, transform * usvg_transform(node.abs_transform()));
}
if let Some(fill) = path.fill() {
let bounds_transform = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
apply_usvg_fill(fill, modify_inputs, transform * usvg_transform(node.abs_transform()), bounds_transform);
}
if let Some(stroke) = path.stroke() {
apply_usvg_stroke(stroke, modify_inputs, transform * usvg_transform(node.abs_transform()));
}
}
usvg::Node::Image(_image) => {
warn!("Skip image")
}
usvg::Node::Text(text) => {
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_std::consts::DEFAULT_FONT_STYLE.to_string());
modify_inputs.insert_text(text.chunks().iter().map(|chunk| chunk.text()).collect(), font, TypesettingConfig::default(), layer);
modify_inputs.fill_set(Fill::Solid(Color::BLACK));
}
}
}
fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsContext, transform: DAffine2) {
if let usvg::Paint::Color(color) = &stroke.paint() {
modify_inputs.stroke_set(Stroke {
color: Some(usvg_color(*color, stroke.opacity().get())),
weight: stroke.width().get() as f64,
dash_lengths: stroke.dasharray().as_ref().map(|lengths| lengths.iter().map(|&length| length as f64).collect()).unwrap_or_default(),
dash_offset: stroke.dashoffset() as f64,
cap: match stroke.linecap() {
usvg::LineCap::Butt => StrokeCap::Butt,
usvg::LineCap::Round => StrokeCap::Round,
usvg::LineCap::Square => StrokeCap::Square,
},
join: match stroke.linejoin() {
usvg::LineJoin::Miter => StrokeJoin::Miter,
usvg::LineJoin::MiterClip => StrokeJoin::Miter,
usvg::LineJoin::Round => StrokeJoin::Round,
usvg::LineJoin::Bevel => StrokeJoin::Bevel,
},
join_miter_limit: stroke.miterlimit().get() as f64,
align: StrokeAlign::Center,
paint_order: PaintOrder::StrokeAbove,
transform,
non_scaling: false,
})
}
}
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, transform: DAffine2, bounds_transform: DAffine2) {
modify_inputs.fill_set(match &fill.paint() {
usvg::Paint::Color(color) => Fill::solid(usvg_color(*color, fill.opacity().get())),
usvg::Paint::LinearGradient(linear) => {
let local = [DVec2::new(linear.x1() as f64, linear.y1() as f64), DVec2::new(linear.x2() as f64, linear.y2() as f64)];
// TODO: fix this
// let to_doc_transform = if linear.base.units() == usvg::Units::UserSpaceOnUse {
// transform
// } else {
// transformed_bound_transform
// };
let to_doc_transform = transform;
let to_doc = to_doc_transform * usvg_transform(linear.transform());
let document = [to_doc.transform_point2(local[0]), to_doc.transform_point2(local[1])];
let layer = [transform.inverse().transform_point2(document[0]), transform.inverse().transform_point2(document[1])];
let [start, end] = [bounds_transform.inverse().transform_point2(layer[0]), bounds_transform.inverse().transform_point2(layer[1])];
let stops = linear.stops().iter().map(|stop| (stop.offset().get() as f64, usvg_color(stop.color(), stop.opacity().get()))).collect();
let stops = GradientStops::new(stops);
Fill::Gradient(Gradient {
start,
end,
gradient_type: GradientType::Linear,
stops,
})
}
usvg::Paint::RadialGradient(radial) => {
let local = [DVec2::new(radial.cx() as f64, radial.cy() as f64), DVec2::new(radial.fx() as f64, radial.fy() as f64)];
// TODO: fix this
// let to_doc_transform = if radial.base.units == usvg::Units::UserSpaceOnUse {
// transform
// } else {
// transformed_bound_transform
// };
let to_doc_transform = transform;
let to_doc = to_doc_transform * usvg_transform(radial.transform());
let document = [to_doc.transform_point2(local[0]), to_doc.transform_point2(local[1])];
let layer = [transform.inverse().transform_point2(document[0]), transform.inverse().transform_point2(document[1])];
let [start, end] = [bounds_transform.inverse().transform_point2(layer[0]), bounds_transform.inverse().transform_point2(layer[1])];
let stops = radial.stops().iter().map(|stop| (stop.offset().get() as f64, usvg_color(stop.color(), stop.opacity().get()))).collect();
let stops = GradientStops::new(stops);
Fill::Gradient(Gradient {
start,
end,
gradient_type: GradientType::Radial,
stops,
})
}
usvg::Paint::Pattern(_) => {
warn!("Skip pattern");
return;
}
});
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/graph_operation/utility_types.rs | editor/src/messages/portfolio/document/graph_operation/utility_types.rs | use super::transform_utils;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
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 glam::{DAffine2, IVec2};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::Artboard;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::subpath::Subpath;
use graphene_std::table::Table;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::Vector;
use graphene_std::vector::style::{Fill, Stroke};
use graphene_std::vector::{PointId, VectorModificationType};
use graphene_std::{Graphic, NodeInputDecleration};
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum TransformIn {
Local,
Scope { scope: DAffine2 },
Viewport,
}
// This struct is helpful to prevent passing the same arguments to multiple functions
// Should only be used by GraphOperationMessage, since it only affects the document network.
pub struct ModifyInputsContext<'a> {
pub network_interface: &'a mut NodeNetworkInterface,
pub responses: &'a mut VecDeque<Message>,
// Cannot be LayerNodeIdentifier::ROOT_PARENT
pub layer_node: Option<LayerNodeIdentifier>,
}
impl<'a> ModifyInputsContext<'a> {
/// Get the node network from the document
pub fn new(network_interface: &'a mut NodeNetworkInterface, responses: &'a mut VecDeque<Message>) -> Self {
Self {
network_interface,
responses,
layer_node: None,
}
}
pub fn new_with_layer(layer: LayerNodeIdentifier, network_interface: &'a mut NodeNetworkInterface, responses: &'a mut VecDeque<Message>) -> Option<Self> {
if layer == LayerNodeIdentifier::ROOT_PARENT {
log::error!("LayerNodeIdentifier::ROOT_PARENT should not be used in ModifyInputsContext::new_with_layer");
return None;
}
let mut document = Self::new(network_interface, responses);
document.layer_node = Some(layer);
Some(document)
}
/// Starts at any folder, or the output, and skips layer nodes based on insert_index. Non layer nodes are always skipped. Returns the post node InputConnector and pre node OutputConnector
/// Non layer nodes directly upstream of a layer are treated as part of that layer. See insert_index == 2 in the diagram
/// -----> Post node
/// | if insert_index == 0, return (Post node, Some(Layer1))
/// -> Layer1
/// β if insert_index == 1, return (Layer1, Some(Layer2))
/// -> Layer2
/// β
/// -> NonLayerNode
/// β if insert_index == 2, return (NonLayerNode, Some(Layer3))
/// -> Layer3
/// if insert_index == 3, return (Layer3, None)
pub fn get_post_node_with_index(network_interface: &NodeNetworkInterface, parent: LayerNodeIdentifier, insert_index: usize) -> InputConnector {
let mut post_node_input_connector = if parent == LayerNodeIdentifier::ROOT_PARENT {
InputConnector::Export(0)
} else {
InputConnector::node(parent.to_node(), 1)
};
// Skip layers based on skip_layer_nodes, which inserts the new layer at a certain index of the layer stack.
let mut current_index = 0;
// Set the post node to the layer node at insert_index
loop {
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 });
if let Some(next_node_in_stack_id) = next_node_in_stack_id {
// Only increment index for layer nodes
if network_interface.is_layer(next_node_in_stack_id, &[]) {
current_index += 1;
}
// Input as a sibling to the Layer node above
post_node_input_connector = InputConnector::node(*next_node_in_stack_id, 0);
} else {
log::error!("Error getting post node: insert_index out of bounds");
break;
};
}
let layer_input_connector = post_node_input_connector;
// Sink post_node down to the end of the non layer chain that feeds into post_node, such that pre_node is the layer node at insert_index + 1, or None if insert_index is the last layer
loop {
let pre_node_output_connector = network_interface.upstream_output_connector(&post_node_input_connector, &[]);
match pre_node_output_connector {
Some(OutputConnector::Node { node_id: pre_node_id, .. }) if !network_interface.is_layer(&pre_node_id, &[]) => {
// Update post_node_input_connector for the next iteration
post_node_input_connector = InputConnector::node(pre_node_id, 0);
// Insert directly under layer if moving to the end of a layer stack that ends with a non layer node that does not have an exposed primary input
let primary_is_exposed = network_interface.input_from_connector(&post_node_input_connector, &[]).is_some_and(|input| input.is_exposed());
if !primary_is_exposed {
return layer_input_connector;
}
}
_ => break, // Break if pre_node_output_connector is None or if pre_node_id is a layer
}
}
post_node_input_connector
}
/// Creates a new layer and adds it to the document network. network_interface.move_layer_to_stack should be called after
pub fn create_layer(&mut self, new_id: NodeId) -> LayerNodeIdentifier {
let new_merge_node = resolve_document_node_type("Merge").expect("Merge node").default_node_template();
self.network_interface.insert_node(new_id, new_merge_node, &[]);
LayerNodeIdentifier::new(new_id, self.network_interface)
}
/// Creates an artboard as the primary export for the document network
pub fn create_artboard(&mut self, new_id: NodeId, artboard: Artboard) -> LayerNodeIdentifier {
let artboard_node_template = resolve_document_node_type("Artboard").expect("Node").node_template_input_override([
Some(NodeInput::value(TaggedValue::Artboard(Default::default()), true)),
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
Some(NodeInput::value(TaggedValue::DVec2(artboard.location.into()), false)),
Some(NodeInput::value(TaggedValue::DVec2(artboard.dimensions.into()), false)),
Some(NodeInput::value(TaggedValue::Color(Table::new_from_element(artboard.background)), false)),
Some(NodeInput::value(TaggedValue::Bool(artboard.clip), false)),
]);
self.network_interface.insert_node(new_id, artboard_node_template, &[]);
LayerNodeIdentifier::new(new_id, self.network_interface)
}
pub fn insert_boolean_data(&mut self, operation: graphene_std::path_bool::BooleanOperation, layer: LayerNodeIdentifier) {
let boolean = resolve_document_node_type("Boolean Operation").expect("Boolean node does not exist").node_template_input_override([
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
]);
let boolean_id = NodeId::new();
self.network_interface.insert_node(boolean_id, boolean, &[]);
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[]);
}
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
let vector = Table::new_from_element(Vector::from_subpaths(subpaths, true));
let shape = resolve_document_node_type("Path")
.expect("Path node does not exist")
.node_template_input_override([Some(NodeInput::value(TaggedValue::Vector(vector), false))]);
let shape_id = NodeId::new();
self.network_interface.insert_node(shape_id, shape, &[]);
self.network_interface.move_node_to_chain_start(&shape_id, layer, &[]);
if include_transform {
let transform = resolve_document_node_type("Transform").expect("Transform node does not exist").default_node_template();
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
}
if include_fill {
let fill = resolve_document_node_type("Fill").expect("Fill node does not exist").default_node_template();
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[]);
}
if include_stroke {
let stroke = resolve_document_node_type("Stroke").expect("Stroke node does not exist").default_node_template();
let stroke_id = NodeId::new();
self.network_interface.insert_node(stroke_id, stroke, &[]);
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[]);
}
}
pub fn insert_text(&mut self, text: String, font: Font, typesetting: TypesettingConfig, layer: LayerNodeIdentifier) {
let stroke = resolve_document_node_type("Stroke").expect("Stroke node does not exist").default_node_template();
let fill = resolve_document_node_type("Fill").expect("Fill node does not exist").default_node_template();
let transform = resolve_document_node_type("Transform").expect("Transform node does not exist").default_node_template();
let text = resolve_document_node_type("Text").expect("Text node does not exist").node_template_input_override([
Some(NodeInput::scope("editor-api")),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Font(font), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.character_spacing), false)),
Some(NodeInput::value(TaggedValue::OptionalF64(typesetting.max_width), false)),
Some(NodeInput::value(TaggedValue::OptionalF64(typesetting.max_height), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
]);
let text_id = NodeId::new();
self.network_interface.insert_node(text_id, text, &[]);
self.network_interface.move_node_to_chain_start(&text_id, layer, &[]);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[]);
let stroke_id = NodeId::new();
self.network_interface.insert_node(stroke_id, stroke, &[]);
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[]);
}
pub fn insert_image_data(&mut self, image_frame: Table<Raster<CPU>>, layer: LayerNodeIdentifier) {
let transform = resolve_document_node_type("Transform").expect("Transform node does not exist").default_node_template();
let image = resolve_document_node_type("Image Value")
.expect("ImageValue node does not exist")
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Raster(image_frame), false))]);
let image_id = NodeId::new();
self.network_interface.insert_node(image_id, image, &[]);
self.network_interface.move_node_to_chain_start(&image_id, layer, &[]);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
}
fn get_output_layer(&self) -> Option<LayerNodeIdentifier> {
self.layer_node.or_else(|| {
let export_node = self.network_interface.document_network().exports.first().and_then(|export| export.as_node())?;
if self.network_interface.is_layer(&export_node, &[]) {
Some(LayerNodeIdentifier::new(export_node, self.network_interface))
} else {
None
}
})
}
/// Gets the node id of a node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
/// The returned node is based on the selection dots in the layer. The right most dot will always insert/access the path that flows directly into the layer.
/// Each dot after that represents an existing path node. If there is an existing upstream node, then it will always be returned first.
pub fn existing_node_id(&mut self, reference_name: &'static str, create_if_nonexistent: bool) -> Option<NodeId> {
// Start from the layer node or export
let output_layer = self.get_output_layer()?;
let existing_node_id = Self::locate_node_in_layer_chain(reference_name, output_layer, self.network_interface);
// Create a new node if the node does not exist and update its inputs
if create_if_nonexistent {
return existing_node_id.or_else(|| self.create_node(reference_name));
}
existing_node_id
}
/// Gets the node id of a node with a specific reference (name) that is upstream (leftward) from the layer node, but before reaching another upstream layer stack.
/// For example, if given a parent layer, this would find a requested "Transform" or "Boolean Operation" node in its chain, between the parent layer and its layer stack child contents.
/// It would also travel up an entire layer that's not fed by a stack until reaching the generator node, such as a "Rectangle" or "Path" layer.
pub fn locate_node_in_layer_chain(reference_name: &str, left_of_layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let upstream = network_interface.upstream_flow_back_from_nodes(vec![left_of_layer.to_node()], &[], network_interface::FlowType::HorizontalFlow);
// Look at all of the upstream nodes
for upstream_node in upstream {
// Check if this is the node we have been searching for.
if network_interface
.reference(&upstream_node, &[])
.is_some_and(|node_reference| *node_reference == Some(reference_name.to_string()))
{
if !network_interface.is_visible(&upstream_node, &[]) {
continue;
}
return Some(upstream_node);
}
// Take until another layer node is found (but not the first layer node)
let is_traversal_start = |node_id: NodeId| left_of_layer.to_node() == node_id || network_interface.document_network().exports.iter().any(|export| export.as_node() == Some(node_id));
if !is_traversal_start(upstream_node) && (network_interface.is_layer(&upstream_node, &[])) {
return None;
}
}
None
}
/// Create a new node inside the layer
pub fn create_node(&mut self, reference: &str) -> Option<NodeId> {
let output_layer = self.get_output_layer()?;
let Some(node_definition) = resolve_document_node_type(reference) else {
log::error!("Node type {reference} does not exist in ModifyInputsContext::existing_node_id");
return None;
};
// If inserting a 'Path' node, insert a 'Flatten Path' node if the type is `Graphic`.
// TODO: Allow the 'Path' node to operate on table data by utilizing the reference (index or ID?) for each row.
if node_definition.identifier == "Path" {
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]);
if layer_input_type.compiled_nested_type() == Some(&concrete!(Table<Graphic>)) {
let Some(flatten_path_definition) = resolve_document_node_type("Flatten Path") else {
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
return None;
};
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, flatten_path_definition.default_node_template(), &[]);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[]);
}
}
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, node_definition.default_node_template(), &[]);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[]);
Some(node_id)
}
pub fn fill_set(&mut self, fill: Fill) {
let fill_index = 1;
let backup_color_index = 2;
let backup_gradient_index = 3;
let Some(fill_node_id) = self.existing_node_id("Fill", true) else { return };
match &fill {
Fill::None => {
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Table::new()), false), true);
}
Fill::Solid(color) => {
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(Table::new_from_element(*color)), false), true);
}
Fill::Gradient(gradient) => {
let input_connector = InputConnector::node(fill_node_id, backup_gradient_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(gradient.clone()), false), true);
}
}
let input_connector = InputConnector::node(fill_node_id, fill_index);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Fill(fill), false), false);
}
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
let input_connector = InputConnector::node(blend_node_id, 1);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::BlendMode(blend_mode), false), false);
}
pub fn opacity_set(&mut self, opacity: f64) {
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
let input_connector = InputConnector::node(blend_node_id, 2);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(opacity * 100.), false), false);
}
pub fn blending_fill_set(&mut self, fill: f64) {
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
let input_connector = InputConnector::node(blend_node_id, 3);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(fill * 100.), false), false);
}
pub fn clip_mode_toggle(&mut self, clip_mode: Option<bool>) {
let clip = !clip_mode.unwrap_or(false);
let Some(clip_node_id) = self.existing_node_id("Blending", true) else { return };
let input_connector = InputConnector::node(clip_node_id, 4);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
}
pub fn stroke_set(&mut self, stroke: Stroke) {
let Some(stroke_node_id) = self.existing_node_id("Stroke", true) else { return };
let stroke_color = if let Some(color) = stroke.color { Table::new_from_element(color) } else { Table::new() };
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::ColorInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(stroke_color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeCap(stroke.cap), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<Vec<f64>>::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::VecF64(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
}
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
/// A new Transform node is created if one does not exist, unless it would be given the identity transform.
pub fn transform_change_with_parent(&mut self, transform: DAffine2, transform_in: TransformIn, parent_transform: DAffine2, skip_rerender: bool) {
// Get the existing upstream Transform node and its transform, if present, otherwise use the identity transform
let (layer_transform, transform_node_id) = self
.existing_node_id("Transform", false)
.and_then(|transform_node_id| {
let document_node = self.network_interface.document_network().nodes.get(&transform_node_id)?;
Some((transform_utils::get_current_transform(&document_node.inputs), transform_node_id))
})
.unzip();
let layer_transform = layer_transform.unwrap_or_default();
// Get a transform appropriate for the requested space
let to_transform = match transform_in {
TransformIn::Local => DAffine2::IDENTITY,
TransformIn::Scope { scope } => scope * parent_transform,
TransformIn::Viewport => parent_transform,
};
// Set the transform value to the Transform node
let final_transform = to_transform.inverse() * transform * to_transform * layer_transform;
self.transform_set_direct(final_transform, skip_rerender, transform_node_id);
}
/// Set the transform value to the upstream Transform node, replacing the existing value.
/// A new Transform node is created if one does not exist, unless it would be given the identity transform.
pub fn transform_set(&mut self, transform: DAffine2, transform_in: TransformIn, skip_rerender: bool) {
// Get the existing upstream Transform node, if present
let transform_node_id = self.existing_node_id("Transform", false);
// Get a transform appropriate for the requested space
let to_transform = match transform_in {
TransformIn::Local => DAffine2::IDENTITY,
TransformIn::Scope { scope } => scope,
TransformIn::Viewport => self.network_interface.document_metadata().downstream_transform_to_viewport(self.layer_node.unwrap()).inverse(),
};
// Set the transform value to the Transform node
let final_transform = to_transform * transform;
self.transform_set_direct(final_transform, skip_rerender, transform_node_id);
}
/// Write the given transform value to the upstream Transform node, if one is supplied. If one doesn't exist, it will be created unless the given transform is the identity.
pub fn transform_set_direct(&mut self, transform: DAffine2, skip_rerender: bool, transform_node_id: Option<NodeId>) {
// If the Transform node didn't exist yet, create it now
let Some(transform_node_id) = transform_node_id.or_else(|| {
// Check if the transform is the identity transform (within an epsilon) and if so, don't create a new Transform node
if transform.abs_diff_eq(DAffine2::IDENTITY, 1e-6) {
// We don't want to pollute the graph with an unnecessary Transform node, so we avoid creating and setting it by returning None
return None;
}
// Create the Transform node
self.existing_node_id("Transform", true)
}) else {
return;
};
// Update the transform value of the Transform node
transform_utils::update_transform(self.network_interface, &transform_node_id, transform);
// Refresh the render and editor UI
self.responses.add(PropertiesPanelMessage::Refresh);
if !skip_rerender {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
pub fn vector_modify(&mut self, modification_type: VectorModificationType) {
let Some(path_node_id) = self.existing_node_id("Path", true) else { return };
self.network_interface.vector_modify(&path_node_id, modification_type);
self.responses.add(PropertiesPanelMessage::Refresh);
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
pub fn brush_modify(&mut self, strokes: Vec<BrushStroke>) {
let Some(brush_node_id) = self.existing_node_id("Brush", true) else { return };
self.set_input_with_refresh(InputConnector::node(brush_node_id, 1), NodeInput::value(TaggedValue::BrushStrokes(strokes), false), false);
}
pub fn resize_artboard(&mut self, location: IVec2, dimensions: IVec2) {
let Some(artboard_node_id) = self.existing_node_id("Artboard", true) else {
return;
};
let mut dimensions = dimensions;
let mut location = location;
if dimensions.x < 0 {
dimensions.x *= -1;
location.x -= dimensions.x;
}
if dimensions.y < 0 {
dimensions.y *= -1;
location.y -= dimensions.y;
}
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 2), NodeInput::value(TaggedValue::DVec2(location.into()), false), false);
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 3), NodeInput::value(TaggedValue::DVec2(dimensions.into()), false), false);
}
/// Set the input, refresh the properties panel, and run the document graph if skip_rerender is false
pub fn set_input_with_refresh(&mut self, input_connector: InputConnector, input: NodeInput, skip_rerender: bool) {
self.network_interface.set_input(&input_connector, input, &[]);
self.responses.add(PropertiesPanelMessage::Refresh);
if !skip_rerender {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs | editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs | 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 glam::{DAffine2, IVec2};
use graph_craft::document::NodeId;
use graphene_std::Artboard;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::subpath::Subpath;
use graphene_std::table::Table;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::PointId;
use graphene_std::vector::VectorModificationType;
use graphene_std::vector::style::{Fill, Stroke};
#[impl_message(Message, DocumentMessage, GraphOperation)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum GraphOperationMessage {
FillSet {
layer: LayerNodeIdentifier,
fill: Fill,
},
BlendingFillSet {
layer: LayerNodeIdentifier,
fill: f64,
},
OpacitySet {
layer: LayerNodeIdentifier,
opacity: f64,
},
BlendModeSet {
layer: LayerNodeIdentifier,
blend_mode: BlendMode,
},
ClipModeToggle {
layer: LayerNodeIdentifier,
},
StrokeSet {
layer: LayerNodeIdentifier,
stroke: Stroke,
},
TransformChange {
layer: LayerNodeIdentifier,
transform: DAffine2,
transform_in: TransformIn,
skip_rerender: bool,
},
TransformSet {
layer: LayerNodeIdentifier,
transform: DAffine2,
transform_in: TransformIn,
skip_rerender: bool,
},
Vector {
layer: LayerNodeIdentifier,
modification_type: VectorModificationType,
},
Brush {
layer: LayerNodeIdentifier,
strokes: Vec<BrushStroke>,
},
SetUpstreamToChain {
layer: LayerNodeIdentifier,
},
NewArtboard {
id: NodeId,
artboard: Artboard,
},
NewBitmapLayer {
id: NodeId,
image_frame: Table<Raster<CPU>>,
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewBooleanOperationLayer {
id: NodeId,
operation: graphene_std::path_bool::BooleanOperation,
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewCustomLayer {
id: NodeId,
nodes: Vec<(NodeId, NodeTemplate)>,
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewVectorLayer {
id: NodeId,
subpaths: Vec<Subpath<PointId>>,
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewTextLayer {
id: NodeId,
text: String,
font: Font,
typesetting: TypesettingConfig,
parent: LayerNodeIdentifier,
insert_index: usize,
},
ResizeArtboard {
layer: LayerNodeIdentifier,
location: IVec2,
dimensions: IVec2,
},
RemoveArtboards,
NewSvg {
id: NodeId,
svg: String,
transform: DAffine2,
parent: LayerNodeIdentifier,
insert_index: usize,
},
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/graph_operation/mod.rs | editor/src/messages/portfolio/document/graph_operation/mod.rs | mod graph_operation_message;
pub mod graph_operation_message_handler;
pub mod transform_utils;
pub mod utility_types;
#[doc(inline)]
pub use graph_operation_message::*;
#[doc(inline)]
pub use graph_operation_message_handler::*;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/graph_operation/transform_utils.rs | editor/src/messages/portfolio/document/graph_operation/transform_utils.rs | use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use glam::{DAffine2, DVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::subpath::Subpath;
use graphene_std::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) {
let x_axis = transform.matrix2.x_axis;
let y_axis = transform.matrix2.y_axis;
// Assuming there is no vertical shear
let angle = x_axis.y.atan2(x_axis.x);
let (sin, cos) = angle.sin_cos();
let scale_x = if cos.abs() > 1e-10 { x_axis.x / cos } else { x_axis.y / sin };
let mut shear_x = (sin * y_axis.y + cos * y_axis.x) / (sin * sin * scale_x + cos * cos * scale_x);
if !shear_x.is_finite() {
shear_x = 0.;
}
let scale_y = if cos.abs() > 1e-10 {
(y_axis.y - scale_x * sin * shear_x) / cos
} else {
(scale_x * cos * shear_x - y_axis.x) / sin
};
let translation = transform.translation;
let scale = DVec2::new(scale_x, scale_y);
let shear = DVec2::new(shear_x, 0.);
(scale, angle, translation, shear)
}
/// Update the inputs of the transform node to match a new transform
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
let (scale, rotation, translation, shear) = compute_scale_angle_translation_shear(transform);
let rotation = rotation.to_degrees();
let shear = DVec2::new(shear.x.atan().to_degrees(), shear.y.atan().to_degrees());
network_interface.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::DVec2(translation), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::F64(rotation), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::DVec2(scale), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::DVec2(shear), false), &[]);
}
// TODO: This should be extracted from the graph at the location of the transform node.
pub struct LayerBounds {
pub bounds: [DVec2; 2],
pub bounds_transform: DAffine2,
pub layer_transform: DAffine2,
}
impl LayerBounds {
/// Extract the layer bounds and their transform for a layer.
pub fn new(
metadata: &crate::messages::portfolio::document::utility_types::document_metadata::DocumentMetadata,
layer: crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier,
) -> Self {
Self {
bounds: metadata.nonzero_bounding_box(layer),
bounds_transform: DAffine2::IDENTITY,
layer_transform: metadata.transform_to_document(layer),
}
}
pub fn layerspace_pivot(&self, normalized_pivot: DVec2) -> DVec2 {
self.bounds[0] + (self.bounds[1] - self.bounds[0]) * normalized_pivot
}
pub fn local_pivot(&self, normalized_pivot: DVec2) -> DVec2 {
self.bounds_transform.transform_point2(self.layerspace_pivot(normalized_pivot))
}
}
/// Get the current affine transform from the transform node's inputs
pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
let translation = if let Some(&TaggedValue::DVec2(translation)) = inputs[1].as_value() {
translation
} else {
DVec2::ZERO
};
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
let shear = if let Some(&TaggedValue::DVec2(shear)) = inputs[4].as_value() { shear } else { DVec2::ZERO };
let rotation = rotation.to_radians();
let shear = DVec2::new(shear.x.to_radians().tan(), shear.y.to_radians().tan());
DAffine2::from_scale_angle_translation(scale, rotation, translation) * DAffine2::from_cols_array(&[1., shear.y, shear.x, 1., 0., 0.])
}
/// 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) }
}
/// Expand a bounds to avoid div zero errors
fn clamp_bounds(bounds_min: DVec2, mut bounds_max: DVec2) -> [DVec2; 2] {
let bounds_size = bounds_max - bounds_min;
if bounds_size.x < 1e-10 {
bounds_max.x = bounds_min.x + 1.;
}
if bounds_size.y < 1e-10 {
bounds_max.y = bounds_min.y + 1.;
}
[bounds_min, bounds_max]
}
/// Returns corners of all subpaths
fn subpath_bounds(subpaths: &[Subpath<PointId>]) -> [DVec2; 2] {
subpaths
.iter()
.filter_map(|subpath| subpath.bounding_box())
.reduce(|b1, b2| [b1[0].min(b2[0]), b1[1].max(b2[1])])
.unwrap_or_default()
}
/// Returns corners of all subpaths (but expanded to avoid division-by-zero errors)
pub fn nonzero_subpath_bounds(subpaths: &[Subpath<PointId>]) -> [DVec2; 2] {
let [bounds_min, bounds_max] = subpath_bounds(subpaths);
clamp_bounds(bounds_min, bounds_max)
}
#[cfg(test)]
mod tests {
use super::*;
/// 
///
/// Source:
/// ```tex
/// \begin{bmatrix}
/// S_{x}\cos(\theta)-S_{y}\sin(\theta)H_{y} & S_{x}\cos(\theta)H_{x}-S_{y}\sin(\theta) & T_{x}\\
/// S_{x}\sin(\theta)+S_{y}\cos(\theta)H_{y} & S_{x}\sin(\theta)H_{x}+S_{y}\cos(\theta) & T_{y}\\
/// 0 & 0 & 1
/// \end{bmatrix}
/// ```
#[test]
fn derive_transform() {
for shear_x in -10..=10 {
let shear_x = (shear_x as f64) / 2.;
for angle in (0..=360).step_by(15) {
let angle = (angle as f64).to_radians();
for scale_x in 1..10 {
let scale_x = (scale_x as f64) / 5.;
for scale_y in 1..10 {
let scale_y = (scale_y as f64) / 5.;
let shear = DVec2::new(shear_x, 0.);
let scale = DVec2::new(scale_x, scale_y);
let translate = DVec2::new(5666., 644.);
let original_transform = DAffine2::from_cols(
DVec2::new(scale.x * angle.cos() - scale.y * angle.sin() * shear.y, scale.x * angle.sin() + scale.y * angle.cos() * shear.y),
DVec2::new(scale.x * angle.cos() * shear.x - scale.y * angle.sin(), scale.x * angle.sin() * shear.x + scale.y * angle.cos()),
translate,
);
let (new_scale, new_angle, new_translation, new_shear) = compute_scale_angle_translation_shear(original_transform);
let new_transform = DAffine2::from_scale_angle_translation(new_scale, new_angle, new_translation) * DAffine2::from_cols_array(&[1., new_shear.y, new_shear.x, 1., 0., 0.]);
assert!(
new_transform.abs_diff_eq(original_transform, 1e-10),
"original_transform {original_transform} new_transform {new_transform} / scale {scale} new_scale {new_scale} / angle {angle} new_angle {new_angle} / shear {shear} / new_shear {new_shear}",
);
}
}
}
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/data_panel/mod.rs | editor/src/messages/portfolio/document/data_panel/mod.rs | mod data_panel_message;
mod data_panel_message_handler;
#[doc(inline)]
pub use data_panel_message::*;
#[doc(inline)]
pub use data_panel_message_handler::*;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs | editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs | use super::VectorTableTab;
use crate::messages::layout::utility_types::layout_widget::{Layout, LayoutGroup, LayoutTarget};
use crate::messages::portfolio::document::data_panel::DataPanelMessage;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::{Affine2, Vec2};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::Context;
use graphene_std::gradient::GradientStops;
use graphene_std::memo::IORecord;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::table::Table;
use graphene_std::vector::Vector;
use graphene_std::vector::style::{Fill, FillChoice};
use graphene_std::{Artboard, Graphic};
use std::any::Any;
use std::sync::Arc;
#[derive(ExtractField)]
pub struct DataPanelMessageContext<'a> {
pub network_interface: &'a mut NodeNetworkInterface,
pub data_panel_open: bool,
}
/// The data panel allows for graph data to be previewed.
#[derive(Default, Debug, Clone, ExtractField)]
pub struct DataPanelMessageHandler {
introspected_node: Option<NodeId>,
introspected_data: Option<Arc<dyn Any + Send + Sync>>,
element_path: Vec<usize>,
active_vector_table_tab: VectorTableTab,
}
#[message_handler_data]
impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanelMessageHandler {
fn process_message(&mut self, message: DataPanelMessage, responses: &mut VecDeque<Message>, context: DataPanelMessageContext) {
match message {
DataPanelMessage::UpdateLayout { mut inspect_result } => {
self.introspected_node = Some(inspect_result.inspect_node);
self.introspected_data = inspect_result.take_data();
self.update_layout(responses, context);
}
DataPanelMessage::ClearLayout => {
self.introspected_node = None;
self.introspected_data = None;
self.element_path.clear();
self.active_vector_table_tab = VectorTableTab::default();
self.update_layout(responses, context);
}
DataPanelMessage::PushToElementPath { index } => {
self.element_path.push(index);
self.update_layout(responses, context);
}
DataPanelMessage::TruncateElementPath { len } => {
self.element_path.truncate(len);
self.update_layout(responses, context);
}
DataPanelMessage::ViewVectorTableTab { tab } => {
self.active_vector_table_tab = tab;
self.update_layout(responses, context);
}
}
}
fn actions(&self) -> ActionList {
actions!(DataPanelMessage;)
}
}
impl DataPanelMessageHandler {
fn update_layout(&mut self, responses: &mut VecDeque<Message>, context: DataPanelMessageContext<'_>) {
let DataPanelMessageContext { network_interface, .. } = context;
let mut layout_data = LayoutData {
current_depth: 0,
desired_path: &mut self.element_path,
breadcrumbs: Vec::new(),
vector_table_tab: self.active_vector_table_tab,
};
// Main data visualization
let mut layout = Layout(
self.introspected_data
.as_ref()
.map(|instrospected_data| generate_layout(instrospected_data, &mut layout_data).unwrap_or_else(|| label("Visualization of this data type is not yet supported")))
.unwrap_or_default(),
);
let mut widgets = Vec::new();
// Selected layer/node name
if let Some(node_id) = self.introspected_node {
let is_layer = network_interface.is_layer(&node_id, &[]);
widgets.extend([
if is_layer {
IconLabel::new("Layer").tooltip_description("Name of the selected layer.").widget_instance()
} else {
IconLabel::new("Node").tooltip_description("Name of the selected node.").widget_instance()
},
Separator::new(SeparatorStyle::Related).widget_instance(),
TextInput::new(network_interface.display_name(&node_id, &[]))
.tooltip_description(if is_layer { "Name of the selected layer." } else { "Name of the selected node." })
.on_update(move |text_input| {
NodeGraphMessage::SetDisplayName {
node_id,
alias: text_input.value.clone(),
skip_adding_history_step: false,
}
.into()
})
.max_width(200)
.widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
]);
}
// Element path breadcrumbs
if !layout_data.breadcrumbs.is_empty() {
let breadcrumb = BreadcrumbTrailButtons::new(layout_data.breadcrumbs)
.on_update(|&len| DataPanelMessage::TruncateElementPath { len: len as usize }.into())
.widget_instance();
widgets.push(breadcrumb);
}
if !widgets.is_empty() {
layout.0.insert(0, LayoutGroup::Row { widgets });
}
responses.add(LayoutMessage::SendLayout {
layout,
layout_target: LayoutTarget::DataPanel,
});
}
}
struct LayoutData<'a> {
current_depth: usize,
desired_path: &'a mut Vec<usize>,
breadcrumbs: Vec<String>,
vector_table_tab: VectorTableTab,
}
macro_rules! generate_layout_downcast {
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
if false { None }
$(
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<Context, $ty>>() {
Some(io.output.layout_with_breadcrumb($data))
}
)*
else { None }
}
}
// TODO: We simply try all these types sequentially. Find a better strategy.
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
generate_layout_downcast!(introspected_data, data, [
Table<Artboard>,
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
Table<Color>,
Table<GradientStops>,
Vec<String>,
f64,
u32,
u64,
bool,
String,
Option<f64>,
DVec2,
DAffine2,
])
}
fn column_headings(value: &[&str]) -> Vec<WidgetInstance> {
value.iter().map(|text| TextLabel::new(*text).widget_instance()).collect()
}
fn label(x: impl Into<String>) -> Vec<LayoutGroup> {
let error = vec![TextLabel::new(x).widget_instance()];
vec![LayoutGroup::Row { widgets: error }]
}
trait TableRowLayout {
fn type_name() -> &'static str;
fn identifier(&self) -> String;
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
data.breadcrumbs.push(self.identifier());
self.element_page(data)
}
fn element_widget(&self, index: usize) -> WidgetInstance {
TextButton::new(self.identifier())
.on_update(move |_| DataPanelMessage::PushToElementPath { index }.into())
.narrow(true)
.widget_instance()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![]
}
}
impl<T: TableRowLayout> TableRowLayout for Vec<T> {
fn type_name() -> &'static str {
"Vec"
}
fn identifier(&self) -> String {
format!("Vec<{}> ({} element{})", T::type_name(), self.len(), if self.len() == 1 { "" } else { "s" })
}
fn element_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
if let Some(index) = data.desired_path.get(data.current_depth).copied() {
if let Some(row) = self.get(index) {
data.current_depth += 1;
let result = row.layout_with_breadcrumb(data);
data.current_depth -= 1;
return result;
} else {
warn!("Desired path truncated");
data.desired_path.truncate(data.current_depth);
}
}
let mut rows = self
.iter()
.enumerate()
.map(|(index, row)| vec![TextLabel::new(format!("{index}")).narrow(true).widget_instance(), row.element_widget(index)])
.collect::<Vec<_>>();
rows.insert(0, column_headings(&["", "element"]));
vec![LayoutGroup::Table { rows, unstyled: false }]
}
}
impl<T: TableRowLayout> TableRowLayout for Table<T> {
fn type_name() -> &'static str {
"Table"
}
fn identifier(&self) -> String {
format!("Table<{}> ({} element{})", T::type_name(), self.len(), if self.len() == 1 { "" } else { "s" })
}
fn element_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
if let Some(index) = data.desired_path.get(data.current_depth).copied() {
if let Some(row) = self.get(index) {
data.current_depth += 1;
let result = row.element.layout_with_breadcrumb(data);
data.current_depth -= 1;
return result;
} else {
warn!("Desired path truncated");
data.desired_path.truncate(data.current_depth);
}
}
let mut rows = self
.iter()
.enumerate()
.map(|(index, row)| {
vec![
TextLabel::new(format!("{index}")).narrow(true).widget_instance(),
row.element.element_widget(index),
TextLabel::new(format_transform_matrix(row.transform)).narrow(true).widget_instance(),
TextLabel::new(format!("{}", row.alpha_blending)).narrow(true).widget_instance(),
TextLabel::new(row.source_node_id.map_or_else(|| "-".to_string(), |id| format!("{}", id.0)))
.narrow(true)
.widget_instance(),
]
})
.collect::<Vec<_>>();
rows.insert(0, column_headings(&["", "element", "transform", "alpha_blending", "source_node_id"]));
vec![LayoutGroup::Table { rows, unstyled: false }]
}
}
impl TableRowLayout for Artboard {
fn type_name() -> &'static str {
"Artboard"
}
fn identifier(&self) -> String {
self.label.clone()
}
fn element_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.content.element_page(data)
}
}
impl TableRowLayout for Graphic {
fn type_name() -> &'static str {
"Graphic"
}
fn identifier(&self) -> String {
match self {
Self::Graphic(table) => table.identifier(),
Self::Vector(table) => table.identifier(),
Self::RasterCPU(table) => table.identifier(),
Self::RasterGPU(table) => table.identifier(),
Self::Color(table) => table.identifier(),
Self::Gradient(table) => table.identifier(),
}
}
// Don't put a breadcrumb for Graphic
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.element_page(data)
}
fn element_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
match self {
Self::Graphic(table) => table.layout_with_breadcrumb(data),
Self::Vector(table) => table.layout_with_breadcrumb(data),
Self::RasterCPU(table) => table.layout_with_breadcrumb(data),
Self::RasterGPU(table) => table.layout_with_breadcrumb(data),
Self::Color(table) => table.layout_with_breadcrumb(data),
Self::Gradient(table) => table.layout_with_breadcrumb(data),
}
}
}
impl TableRowLayout for Vector {
fn type_name() -> &'static str {
"Vector"
}
fn identifier(&self) -> String {
format!(
"Vector ({} point{}, {} segment{})",
self.point_domain.ids().len(),
if self.point_domain.ids().len() == 1 { "" } else { "s" },
self.segment_domain.ids().len(),
if self.segment_domain.ids().len() == 1 { "" } else { "s" }
)
}
fn element_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
let table_tab_entries = [VectorTableTab::Properties, VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Regions]
.into_iter()
.map(|tab| {
RadioEntryData::new(format!("{tab:?}"))
.label(format!("{tab:?}"))
.on_update(move |_| DataPanelMessage::ViewVectorTableTab { tab }.into())
})
.collect();
let table_tabs = vec![RadioInput::new(table_tab_entries).selected_index(Some(data.vector_table_tab as u32)).widget_instance()];
let mut table_rows = Vec::new();
match data.vector_table_tab {
VectorTableTab::Properties => {
table_rows.push(column_headings(&["property", "value"]));
match self.style.fill.clone() {
Fill::None => table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoice::None).disabled(true).menu_direction(Some(MenuDirection::Top)).narrow(true).widget_instance(),
]),
Fill::Solid(color) => table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoice::Solid(color))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]),
Fill::Gradient(gradient) => {
table_rows.push(vec![
TextLabel::new("Fill").narrow(true).widget_instance(),
ColorInput::new(FillChoice::Gradient(gradient.stops))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient Type").narrow(true).widget_instance(),
TextLabel::new(gradient.gradient_type.to_string()).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient Start").narrow(true).widget_instance(),
TextLabel::new(format_dvec2(gradient.start)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Fill Gradient End").narrow(true).widget_instance(),
TextLabel::new(format_dvec2(gradient.end)).narrow(true).widget_instance(),
]);
}
}
if let Some(stroke) = self.style.stroke.clone() {
let color = if let Some(color) = stroke.color { FillChoice::Solid(color) } else { FillChoice::None };
table_rows.push(vec![
TextLabel::new("Stroke").narrow(true).widget_instance(),
ColorInput::new(color).disabled(true).menu_direction(Some(MenuDirection::Top)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Weight").narrow(true).widget_instance(),
TextLabel::new(format!("{} px", stroke.weight)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Dash Lengths").narrow(true).widget_instance(),
TextLabel::new(if stroke.dash_lengths.is_empty() {
"-".to_string()
} else {
format!("[{}]", stroke.dash_lengths.iter().map(|x| format!("{x} px")).collect::<Vec<_>>().join(", "))
})
.narrow(true)
.widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Dash Offset").narrow(true).widget_instance(),
TextLabel::new(format!("{}", stroke.dash_offset)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Cap").narrow(true).widget_instance(),
TextLabel::new(stroke.cap.to_string()).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Join").narrow(true).widget_instance(),
TextLabel::new(stroke.join.to_string()).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Join Miter Limit").narrow(true).widget_instance(),
TextLabel::new(format!("{}", stroke.join_miter_limit)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Align").narrow(true).widget_instance(),
TextLabel::new(stroke.align.to_string()).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Transform").narrow(true).widget_instance(),
TextLabel::new(format_transform_matrix(&stroke.transform)).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Non-Scaling").narrow(true).widget_instance(),
TextLabel::new((if stroke.non_scaling { "Yes" } else { "No" }).to_string()).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Stroke Paint Order").narrow(true).widget_instance(),
TextLabel::new(stroke.paint_order.to_string()).narrow(true).widget_instance(),
]);
}
let colinear = self.colinear_manipulators.iter().map(|[a, b]| format!("[{a} / {b}]")).collect::<Vec<_>>().join(", ");
let colinear = if colinear.is_empty() { "-".to_string() } else { colinear };
table_rows.push(vec![
TextLabel::new("Colinear Handle IDs").narrow(true).widget_instance(),
TextLabel::new(colinear).narrow(true).widget_instance(),
]);
table_rows.push(vec![
TextLabel::new("Upstream Nested Layers").narrow(true).widget_instance(),
TextLabel::new(if self.upstream_data.is_some() {
"Yes (this preserves references to its upstream nested layers for editing by tools)"
} else {
"No (this doesn't preserve references to its upstream nested layers for editing by tools)"
})
.narrow(true)
.widget_instance(),
]);
}
VectorTableTab::Points => {
table_rows.push(column_headings(&["", "position"]));
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("{position}")).narrow(true).widget_instance(),
]
}));
}
VectorTableTab::Segments => {
table_rows.push(column_headings(&["", "start_index", "end_index", "handles"]));
table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("{start}")).narrow(true).widget_instance(),
TextLabel::new(format!("{end}")).narrow(true).widget_instance(),
TextLabel::new(format!("{handles:?}")).narrow(true).widget_instance(),
]
}));
}
VectorTableTab::Regions => {
table_rows.push(column_headings(&["", "segment_range", "fill"]));
table_rows.extend(self.region_domain.iter().map(|(id, segment_range, fill)| {
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("{segment_range:?}")).narrow(true).widget_instance(),
TextLabel::new(format!("{}", fill.inner())).narrow(true).widget_instance(),
]
}));
}
}
vec![LayoutGroup::Row { widgets: table_tabs }, LayoutGroup::Table { rows: table_rows, unstyled: false }]
}
}
impl TableRowLayout for Raster<CPU> {
fn type_name() -> &'static str {
"Raster"
}
fn identifier(&self) -> String {
format!("Raster ({}x{})", self.width, self.height)
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let raster = self.data();
if raster.width == 0 || raster.height == 0 {
let widgets = vec![TextLabel::new("Image has no area").widget_instance()];
return vec![LayoutGroup::Row { widgets }];
}
let base64_string = raster.base64_string.clone().unwrap_or_else(|| {
use base64::Engine;
let output = raster.to_png();
let preamble = "data:image/png;base64,";
let mut base64_string = String::with_capacity(preamble.len() + output.len() * 4);
base64_string.push_str(preamble);
base64::engine::general_purpose::STANDARD.encode_string(output, &mut base64_string);
base64_string
});
let widgets = vec![ImageLabel::new(base64_string).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for Raster<GPU> {
fn type_name() -> &'static str {
"Raster"
}
fn identifier(&self) -> String {
format!("Raster ({}x{})", self.data().width(), self.data().height())
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new("Raster is a texture on the GPU and cannot currently be displayed here").widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for Color {
fn type_name() -> &'static str {
"Color"
}
fn identifier(&self) -> String {
format!("Color (#{})", self.to_gamma_srgb().to_rgba_hex_srgb())
}
fn element_widget(&self, _index: usize) -> WidgetInstance {
ColorInput::new(FillChoice::Solid(*self))
.disabled(true)
.menu_direction(Some(MenuDirection::Top))
.narrow(true)
.widget_instance()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![self.element_widget(0)];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for GradientStops {
fn type_name() -> &'static str {
"Gradient"
}
fn identifier(&self) -> String {
format!("Gradient ({} stops)", self.0.len())
}
fn element_widget(&self, _index: usize) -> WidgetInstance {
ColorInput::new(FillChoice::Gradient(self.clone()))
.menu_direction(Some(MenuDirection::Top))
.disabled(true)
.narrow(true)
.widget_instance()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![self.element_widget(0)];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for f64 {
fn type_name() -> &'static str {
"Number (f64)"
}
fn identifier(&self) -> String {
"Number (f64)".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new(self.to_string()).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for u32 {
fn type_name() -> &'static str {
"Number (u32)"
}
fn identifier(&self) -> String {
"Number (u32)".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new(self.to_string()).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for u64 {
fn type_name() -> &'static str {
"Number (u64)"
}
fn identifier(&self) -> String {
"Number (u64)".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new(self.to_string()).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for bool {
fn type_name() -> &'static str {
"Bool"
}
fn identifier(&self) -> String {
"Bool".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new(self.to_string()).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for String {
fn type_name() -> &'static str {
"String"
}
fn identifier(&self) -> String {
// Show the first line, and if there are more, indicate that with an ellipsis
let first_line = self.lines().next().unwrap_or("");
if self.lines().count() > 1 {
format!("\"{} β¦\"", first_line)
} else {
format!("\"{}\"", first_line)
}
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextAreaInput::new(self.to_string()).disabled(true).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for Option<f64> {
fn type_name() -> &'static str {
"Option<f64>"
}
fn identifier(&self) -> String {
"Option<f64>".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new(format!("{self:?}")).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for DVec2 {
fn type_name() -> &'static str {
"Vec2"
}
fn identifier(&self) -> String {
"Vec2".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new(format!("({}, {})", self.x, self.y)).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for Vec2 {
fn type_name() -> &'static str {
"Vec2"
}
fn identifier(&self) -> String {
"Vec2".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new(format!("({}, {})", self.x, self.y)).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for DAffine2 {
fn type_name() -> &'static str {
"Transform"
}
fn identifier(&self) -> String {
"Transform".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let widgets = vec![TextLabel::new(format_transform_matrix(self)).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
impl TableRowLayout for Affine2 {
fn type_name() -> &'static str {
"Transform"
}
fn identifier(&self) -> String {
"Transform".to_string()
}
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
let matrix = DAffine2::from_cols_array(&self.to_cols_array().map(|x| x as f64));
let widgets = vec![TextLabel::new(format_transform_matrix(&matrix)).widget_instance()];
vec![LayoutGroup::Row { widgets }]
}
}
fn format_transform_matrix(transform: &DAffine2) -> String {
let (scale, angle, translation) = transform.to_scale_angle_translation();
let rotation = if angle == -0. { 0. } else { angle.to_degrees() };
let round = |x: f64| (x * 1e3).round() / 1e3;
format!(
"Location: ({} px, {} px) β Rotation: {rotation:2}Β° β Scale: ({}x, {}x)",
round(translation.x),
round(translation.y),
round(scale.x),
round(scale.y)
)
}
fn format_dvec2(value: DVec2) -> String {
let round = |x: f64| (x * 1e3).round() / 1e3;
format!("({} px, {} px)", round(value.x), round(value.y))
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs | editor/src/messages/portfolio/document/data_panel/data_panel_message.rs | use crate::messages::prelude::*;
use crate::node_graph_executor::InspectResult;
/// The Data panel UI allows the user to visualize the output data of the selected node.
#[impl_message(Message, DocumentMessage, DataPanel)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum DataPanelMessage {
UpdateLayout {
#[serde(skip)]
inspect_result: InspectResult,
},
ClearLayout,
PushToElementPath {
index: usize,
},
TruncateElementPath {
len: usize,
},
ViewVectorTableTab {
tab: VectorTableTab,
},
}
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
pub enum VectorTableTab {
#[default]
Properties,
Points,
Segments,
Regions,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/overlays/utility_types_native.rs | editor/src/messages/portfolio/document/overlays/utility_types_native.rs | use crate::consts::{
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_YELLOW, COLOR_OVERLAY_YELLOW_DULL,
COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE,
PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::overlays::utility_functions::{GLOBAL_FONT_CACHE, GLOBAL_TEXT_CONTEXT};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::Message;
use crate::messages::prelude::ViewportMessageHandler;
use core::borrow::Borrow;
use core::f64::consts::{FRAC_PI_2, PI, TAU};
use glam::{DAffine2, DVec2};
use graphene_std::Color;
use graphene_std::math::quad::Quad;
use graphene_std::subpath::{self, Subpath};
use graphene_std::table::Table;
use graphene_std::text::{Font, TextAlign, TypesettingConfig};
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::point_to_dvec2;
use graphene_std::vector::{PointId, SegmentId, Vector};
use kurbo::{self, BezPath, ParamCurve};
use kurbo::{Affine, PathSeg};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard};
use vello::Scene;
use vello::peniko;
pub type OverlayProvider = fn(OverlayContext) -> Message;
pub fn empty_provider() -> OverlayProvider {
|_| Message::NoOp
}
/// Types of overlays used by DocumentMessage to enable/disable the selected set of viewport overlays.
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum OverlaysType {
ArtboardName,
CompassRose,
QuickMeasurement,
TransformMeasurement,
TransformCage,
HoverOutline,
SelectionOutline,
Pivot,
Origin,
Path,
Anchors,
Handles,
}
#[derive(PartialEq, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(default)]
pub struct OverlaysVisibilitySettings {
pub all: bool,
pub artboard_name: bool,
pub compass_rose: bool,
pub quick_measurement: bool,
pub transform_measurement: bool,
pub transform_cage: bool,
pub hover_outline: bool,
pub selection_outline: bool,
pub pivot: bool,
pub origin: bool,
pub path: bool,
pub anchors: bool,
pub handles: bool,
}
impl Default for OverlaysVisibilitySettings {
fn default() -> Self {
Self {
all: true,
artboard_name: true,
compass_rose: true,
quick_measurement: true,
transform_measurement: true,
transform_cage: true,
hover_outline: true,
selection_outline: true,
pivot: true,
origin: true,
path: true,
anchors: true,
handles: true,
}
}
}
impl OverlaysVisibilitySettings {
pub fn all(&self) -> bool {
self.all
}
pub fn artboard_name(&self) -> bool {
self.all && self.artboard_name
}
pub fn compass_rose(&self) -> bool {
self.all && self.compass_rose
}
pub fn quick_measurement(&self) -> bool {
self.all && self.quick_measurement
}
pub fn transform_measurement(&self) -> bool {
self.all && self.transform_measurement
}
pub fn transform_cage(&self) -> bool {
self.all && self.transform_cage
}
pub fn hover_outline(&self) -> bool {
self.all && self.hover_outline
}
pub fn selection_outline(&self) -> bool {
self.all && self.selection_outline
}
pub fn pivot(&self) -> bool {
self.all && self.pivot
}
pub fn origin(&self) -> bool {
self.all && self.origin
}
pub fn path(&self) -> bool {
self.all && self.path
}
pub fn anchors(&self) -> bool {
self.all && self.anchors
}
pub fn handles(&self) -> bool {
self.all && self.anchors && self.handles
}
}
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
pub struct OverlayContext {
// Serde functionality isn't used but is required by the message system macros
#[serde(skip)]
#[specta(skip)]
internal: Arc<Mutex<OverlayContextInternal>>,
pub viewport: ViewportMessageHandler,
pub visibility_settings: OverlaysVisibilitySettings,
}
impl Clone for OverlayContext {
fn clone(&self) -> Self {
let internal = self.internal.lock().expect("Failed to lock internal overlay context");
let visibility_settings = internal.visibility_settings;
drop(internal); // Explicitly release the lock before cloning the Arc<Mutex<_>>
Self {
internal: self.internal.clone(),
viewport: self.viewport,
visibility_settings,
}
}
}
// Manual implementations since Scene doesn't implement PartialEq or Debug
impl PartialEq for OverlayContext {
fn eq(&self, other: &Self) -> bool {
self.viewport == other.viewport && self.visibility_settings == other.visibility_settings
}
}
impl std::fmt::Debug for OverlayContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OverlayContext")
.field("scene", &"Scene { ... }")
.field("viewport", &self.viewport)
.field("visibility_settings", &self.visibility_settings)
.finish()
}
}
// Default implementation for Scene
impl Default for OverlayContext {
fn default() -> Self {
Self {
internal: Mutex::new(OverlayContextInternal::default()).into(),
viewport: ViewportMessageHandler::default(),
visibility_settings: OverlaysVisibilitySettings::default(),
}
}
}
// Message hashing isn't used but is required by the message system macros
impl core::hash::Hash for OverlayContext {
fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}
impl OverlayContext {
#[allow(dead_code)]
pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self {
Self {
internal: Arc::new(Mutex::new(OverlayContextInternal::new(viewport, visibility_settings))),
viewport,
visibility_settings,
}
}
pub fn take_scene(self) -> Scene {
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
std::mem::take(&mut internal.scene)
}
fn internal(&'_ self) -> MutexGuard<'_, OverlayContextInternal> {
self.internal.lock().expect("Failed to lock internal overlay context")
}
pub fn quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>) {
self.internal().quad(quad, stroke_color, color_fill);
}
pub fn draw_triangle(&mut self, base: DVec2, direction: DVec2, size: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
self.internal().draw_triangle(base, direction, size, color_fill, color_stroke);
}
pub fn dashed_quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.internal().dashed_quad(quad, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset);
}
pub fn polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>) {
self.internal().polygon(polygon, stroke_color, color_fill);
}
pub fn dashed_polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.internal().dashed_polygon(polygon, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset);
}
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
self.internal().line(start, end, color, thickness);
}
#[allow(clippy::too_many_arguments)]
pub fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.internal().dashed_line(start, end, color, thickness, dash_width, dash_gap_width, dash_offset);
}
pub fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
self.internal().hover_manipulator_handle(position, selected);
}
pub fn hover_manipulator_anchor(&mut self, position: DVec2, selected: bool) {
self.internal().hover_manipulator_anchor(position, selected);
}
pub fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
self.internal().manipulator_handle(position, selected, color);
}
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
self.internal().manipulator_anchor(position, selected, color);
}
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
self.internal().resize_handle(position, rotation);
}
pub fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) {
self.internal().skew_handles(edge_start, edge_end);
}
pub fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
self.internal().square(position, size, color_fill, color_stroke);
}
pub fn pixel(&mut self, position: DVec2, color: Option<&str>) {
self.internal().pixel(position, color);
}
pub fn circle(&mut self, position: DVec2, radius: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
self.internal().circle(position, radius, color_fill, color_stroke);
}
#[allow(clippy::too_many_arguments)]
pub fn dashed_ellipse(
&mut self,
center: DVec2,
radius_x: f64,
radius_y: f64,
rotation: Option<f64>,
start_angle: Option<f64>,
end_angle: Option<f64>,
counterclockwise: Option<bool>,
color_fill: Option<&str>,
color_stroke: Option<&str>,
dash_width: Option<f64>,
dash_gap_width: Option<f64>,
dash_offset: Option<f64>,
) {
self.internal().dashed_ellipse(
center,
radius_x,
radius_y,
rotation,
start_angle,
end_angle,
counterclockwise,
color_fill,
color_stroke,
dash_width,
dash_gap_width,
dash_offset,
);
}
pub fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
self.internal().draw_arc(center, radius, start_from, end_at);
}
pub fn draw_arc_gizmo_angle(&mut self, pivot: DVec2, bold_radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
self.internal().draw_arc_gizmo_angle(pivot, bold_radius, arc_radius, offset_angle, angle);
}
pub fn draw_angle(&mut self, pivot: DVec2, radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
self.internal().draw_angle(pivot, radius, arc_radius, offset_angle, angle);
}
pub fn draw_scale(&mut self, start: DVec2, scale: f64, radius: f64, text: &str) {
self.internal().draw_scale(start, scale, radius, text);
}
pub fn compass_rose(&mut self, compass_center: DVec2, angle: f64, show_compass_with_hover_ring: Option<bool>) {
self.internal().compass_rose(compass_center, angle, show_compass_with_hover_ring);
}
pub fn pivot(&mut self, position: DVec2, angle: f64) {
self.internal().pivot(position, angle);
}
pub fn dowel_pin(&mut self, position: DVec2, angle: f64, color: Option<&str>) {
self.internal().dowel_pin(position, angle, color);
}
#[allow(clippy::too_many_arguments)]
pub fn arc_sweep_angle(&mut self, offset_angle: f64, angle: f64, end_point_position: DVec2, bold_radius: f64, pivot: DVec2, text: &str, transform: DAffine2) {
self.internal().arc_sweep_angle(offset_angle, angle, end_point_position, bold_radius, pivot, text, transform);
}
/// Used by the Pen and Path tools to outline the path of the shape.
pub fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) {
self.internal().outline_vector(vector, transform);
}
/// Used by the Pen tool in order to show how the bezier curve would look like.
pub fn outline_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.internal().outline_bezier(bezier, transform);
}
/// Used by the path tool segment mode in order to show the selected segments.
pub fn outline_select_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.internal().outline_select_bezier(bezier, transform);
}
pub fn outline_overlay_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.internal().outline_overlay_bezier(bezier, transform);
}
/// Used by the Select tool to outline a path or a free point when selected or hovered.
pub fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
self.internal().outline(target_types, transform, color);
}
/// Fills the area inside the path. Assumes `color` is in gamma space.
/// Used by the Pen tool to show the path being closed.
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
self.internal().fill_path(subpaths, transform, color);
}
/// Fills the area inside the path with a pattern. Assumes `color` is in gamma space.
/// Used by the fill tool to show the area to be filled.
pub fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &Color) {
self.internal().fill_path_pattern(subpaths, transform, color);
}
pub fn text(&self, text: &str, font_color: &str, background_color: Option<&str>, transform: DAffine2, padding: f64, pivot: [Pivot; 2]) {
let mut internal = self.internal();
internal.text(text, font_color, background_color, transform, padding, pivot);
}
pub fn translation_box(&mut self, translation: DVec2, quad: Quad, typed_string: Option<String>) {
self.internal().translation_box(translation, quad, typed_string);
}
}
pub enum Pivot {
Start,
Middle,
End,
}
pub enum DrawHandles {
All,
SelectedAnchors(HashMap<LayerNodeIdentifier, Vec<SegmentId>>),
FrontierHandles(HashMap<LayerNodeIdentifier, HashMap<SegmentId, Vec<PointId>>>),
None,
}
pub(super) struct OverlayContextInternal {
scene: Scene,
viewport: ViewportMessageHandler,
visibility_settings: OverlaysVisibilitySettings,
}
impl Default for OverlayContextInternal {
fn default() -> Self {
Self::new(ViewportMessageHandler::default(), OverlaysVisibilitySettings::default())
}
}
impl OverlayContextInternal {
pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self {
Self {
scene: Scene::new(),
viewport,
visibility_settings,
}
}
fn parse_color(color: &str) -> peniko::Color {
let hex = color.trim_start_matches('#');
let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);
let a = if hex.len() >= 8 { u8::from_str_radix(&hex[6..8], 16).unwrap_or(255) } else { 255 };
peniko::Color::from_rgba8(r, g, b, a)
}
fn quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>) {
self.dashed_polygon(&quad.0, stroke_color, color_fill, None, None, None);
}
fn draw_triangle(&mut self, base: DVec2, direction: DVec2, size: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let normal = direction.perp();
let top = base + direction * size;
let edge1 = base + normal * size / 2.;
let edge2 = base - normal * size / 2.;
let transform = self.get_transform();
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(top.x, top.y));
path.line_to(kurbo::Point::new(edge1.x, edge1.y));
path.line_to(kurbo::Point::new(edge2.x, edge2.y));
path.close_path();
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &path);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color_stroke), None, &path);
}
fn dashed_quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.dashed_polygon(&quad.0, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset);
}
fn polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>) {
self.dashed_polygon(polygon, stroke_color, color_fill, None, None, None);
}
fn dashed_polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
if polygon.len() < 2 {
return;
}
let transform = self.get_transform();
let mut path = BezPath::new();
if let Some(first) = polygon.last() {
path.move_to(kurbo::Point::new(first.x.round() - 0.5, first.y.round() - 0.5));
}
for point in polygon {
path.line_to(kurbo::Point::new(point.x.round() - 0.5, point.y.round() - 0.5));
}
path.close_path();
if let Some(color_fill) = color_fill {
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &path);
}
let stroke_color = stroke_color.unwrap_or(COLOR_OVERLAY_BLUE);
let mut stroke = kurbo::Stroke::new(1.);
if let Some(dash_width) = dash_width {
let dash_gap = dash_gap_width.unwrap_or(1.);
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap]);
}
self.scene.stroke(&stroke, transform, Self::parse_color(stroke_color), None, &path);
}
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
self.dashed_line(start, end, color, thickness, None, None, None)
}
#[allow(clippy::too_many_arguments)]
fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
let transform = self.get_transform();
let start = start.round() - DVec2::splat(0.5);
let end = end.round() - DVec2::splat(0.5);
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(start.x, start.y));
path.line_to(kurbo::Point::new(end.x, end.y));
let mut stroke = kurbo::Stroke::new(thickness.unwrap_or(1.));
if let Some(dash_width) = dash_width {
let dash_gap = dash_gap_width.unwrap_or(1.);
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap]);
}
self.scene.stroke(&stroke, transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &path);
}
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let transform = self.get_transform();
let position = position.round() - DVec2::splat(0.5);
let circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
self.scene
.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
}
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
let transform = self.get_transform();
let position = position.round() - DVec2::splat(0.5);
let circle = kurbo::Circle::new((position.x, position.y), (MANIPULATOR_GROUP_MARKER_SIZE + 2.) / 2.);
let fill = COLOR_OVERLAY_BLUE_50;
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(COLOR_OVERLAY_BLUE_50), None, &circle);
let inner_circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
let color_fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &circle);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &inner_circle);
}
fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let color_stroke = color.unwrap_or(COLOR_OVERLAY_BLUE);
let color_fill = if selected { color_stroke } else { COLOR_OVERLAY_WHITE };
self.square(position, None, Some(color_fill), Some(color_stroke));
}
fn hover_manipulator_anchor(&mut self, position: DVec2, selected: bool) {
self.square(position, Some(MANIPULATOR_GROUP_MARKER_SIZE + 2.), Some(COLOR_OVERLAY_BLUE_50), Some(COLOR_OVERLAY_BLUE_50));
let color_fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.square(position, None, Some(color_fill), Some(COLOR_OVERLAY_BLUE));
}
fn resize_handle(&mut self, position: DVec2, rotation: f64) {
let quad = DAffine2::from_angle_translation(rotation, position) * Quad::from_box([DVec2::splat(-RESIZE_HANDLE_SIZE / 2.), DVec2::splat(RESIZE_HANDLE_SIZE / 2.)]);
self.quad(quad, None, Some(COLOR_OVERLAY_WHITE));
}
fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) {
let edge_dir = (edge_end - edge_start).normalize();
let mid = edge_end.midpoint(edge_start);
for edge in [edge_dir, -edge_dir] {
self.draw_triangle(mid + edge * (3. + SKEW_TRIANGLE_OFFSET), edge, SKEW_TRIANGLE_SIZE, None, None);
}
}
fn get_transform(&self) -> kurbo::Affine {
kurbo::Affine::scale(self.viewport.scale())
}
fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
let size = size.unwrap_or(MANIPULATOR_GROUP_MARKER_SIZE);
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let position = position.round() - DVec2::splat(0.5);
let corner = position - DVec2::splat(size) / 2.;
let transform = self.get_transform();
let rect = kurbo::Rect::new(corner.x, corner.y, corner.x + size, corner.y + size);
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &rect);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color_stroke), None, &rect);
}
fn pixel(&mut self, position: DVec2, color: Option<&str>) {
let size = 1.;
let color_fill = color.unwrap_or(COLOR_OVERLAY_WHITE);
let position = position.round() - DVec2::splat(0.5);
let corner = position - DVec2::splat(size) / 2.;
let transform = self.get_transform();
let rect = kurbo::Rect::new(corner.x, corner.y, corner.x + size, corner.y + size);
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &rect);
}
fn circle(&mut self, position: DVec2, radius: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let position = position.round();
let transform = self.get_transform();
let circle = kurbo::Circle::new((position.x, position.y), radius);
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &circle);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color_stroke), None, &circle);
}
#[allow(clippy::too_many_arguments)]
fn dashed_ellipse(
&mut self,
_center: DVec2,
_radius_x: f64,
_radius_y: f64,
_rotation: Option<f64>,
_start_angle: Option<f64>,
_end_angle: Option<f64>,
_counterclockwise: Option<bool>,
_color_fill: Option<&str>,
_color_stroke: Option<&str>,
_dash_width: Option<f64>,
_dash_gap_width: Option<f64>,
_dash_offset: Option<f64>,
) {
}
fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
let segments = ((end_at - start_from).abs() / (std::f64::consts::PI / 4.)).ceil() as usize;
let step = (end_at - start_from) / segments as f64;
let half_step = step / 2.;
let factor = 4. / 3. * half_step.sin() / (1. + half_step.cos());
let mut path = BezPath::new();
for i in 0..segments {
let start_angle = start_from + step * i as f64;
let end_angle = start_angle + step;
let start_vec = DVec2::from_angle(start_angle);
let end_vec = DVec2::from_angle(end_angle);
let start = center + radius * start_vec;
let end = center + radius * end_vec;
let handle_start = start + start_vec.perp() * radius * factor;
let handle_end = end - end_vec.perp() * radius * factor;
if i == 0 {
path.move_to(kurbo::Point::new(start.x, start.y));
}
path.curve_to(
kurbo::Point::new(handle_start.x, handle_start.y),
kurbo::Point::new(handle_end.x, handle_end.y),
kurbo::Point::new(end.x, end.y),
);
}
self.scene.stroke(&kurbo::Stroke::new(1.), self.get_transform(), Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
}
fn draw_arc_gizmo_angle(&mut self, pivot: DVec2, bold_radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
let end_point1 = pivot + bold_radius * DVec2::from_angle(angle + offset_angle);
self.line(pivot, end_point1, None, None);
self.draw_arc(pivot, arc_radius, offset_angle, (angle) % TAU + offset_angle);
}
fn draw_angle(&mut self, pivot: DVec2, radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
let end_point1 = pivot + radius * DVec2::from_angle(angle + offset_angle);
let end_point2 = pivot + radius * DVec2::from_angle(offset_angle);
self.line(pivot, end_point1, None, None);
self.dashed_line(pivot, end_point2, None, None, Some(2.), Some(2.), Some(0.5));
self.draw_arc(pivot, arc_radius, offset_angle, (angle) % TAU + offset_angle);
}
fn draw_scale(&mut self, start: DVec2, scale: f64, radius: f64, text: &str) {
let sign = scale.signum();
let mut fill_color = Color::from_rgb_str(COLOR_OVERLAY_WHITE.strip_prefix('#').unwrap()).unwrap().with_alpha(0.05).to_rgba_hex_srgb();
fill_color.insert(0, '#');
let fill_color = Some(fill_color.as_str());
self.line(start + DVec2::X * radius * sign, start + DVec2::X * radius * scale.abs(), None, None);
self.circle(start, radius, fill_color, None);
self.circle(start, radius * scale.abs(), fill_color, None);
self.text(
text,
COLOR_OVERLAY_BLUE,
None,
DAffine2::from_translation(start + sign * DVec2::X * radius * (1. + scale.abs()) / 2.),
2.,
[Pivot::Middle, Pivot::End],
)
}
fn compass_rose(&mut self, compass_center: DVec2, angle: f64, show_compass_with_hover_ring: Option<bool>) {
let hover_ring_outer_radius: f64 = COMPASS_ROSE_HOVER_RING_DIAMETER / 2.;
let main_ring_outer_radius: f64 = COMPASS_ROSE_MAIN_RING_DIAMETER / 2.;
let main_ring_inner_radius: f64 = COMPASS_ROSE_RING_INNER_DIAMETER / 2.;
let arrow_radius: f64 = COMPASS_ROSE_ARROW_SIZE / 2.;
let hover_ring_stroke_width: f64 = hover_ring_outer_radius - main_ring_inner_radius;
let hover_ring_centerline_radius: f64 = (hover_ring_outer_radius + main_ring_inner_radius) / 2.;
let main_ring_stroke_width: f64 = main_ring_outer_radius - main_ring_inner_radius;
let main_ring_centerline_radius: f64 = (main_ring_outer_radius + main_ring_inner_radius) / 2.;
let Some(show_hover_ring) = show_compass_with_hover_ring else { return };
let transform = self.get_transform();
let center = compass_center.round() - DVec2::splat(0.5);
// Hover ring
if show_hover_ring {
let mut fill_color = Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap()).unwrap().with_alpha(0.5).to_rgba_hex_srgb();
fill_color.insert(0, '#');
let circle = kurbo::Circle::new((center.x, center.y), hover_ring_centerline_radius);
self.scene
.stroke(&kurbo::Stroke::new(hover_ring_stroke_width), transform, Self::parse_color(&fill_color), None, &circle);
}
// Arrows
for i in 0..4 {
let direction = DVec2::from_angle(i as f64 * FRAC_PI_2 + angle);
let color = if i % 2 == 0 { COLOR_OVERLAY_RED } else { COLOR_OVERLAY_GREEN };
let tip = center + direction * hover_ring_outer_radius;
let base = center + direction * (main_ring_inner_radius + main_ring_outer_radius) / 2.;
let r = (arrow_radius.powi(2) + main_ring_inner_radius.powi(2)).sqrt();
let (cos, sin) = (main_ring_inner_radius / r, arrow_radius / r);
let side1 = center + r * DVec2::new(cos * direction.x - sin * direction.y, sin * direction.x + direction.y * cos);
let side2 = center + r * DVec2::new(cos * direction.x + sin * direction.y, -sin * direction.x + direction.y * cos);
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(tip.x, tip.y));
path.line_to(kurbo::Point::new(side1.x, side1.y));
path.line_to(kurbo::Point::new(base.x, base.y));
path.line_to(kurbo::Point::new(side2.x, side2.y));
path.close_path();
let color_parsed = Self::parse_color(color);
self.scene.fill(peniko::Fill::NonZero, transform, color_parsed, None, &path);
self.scene.stroke(&kurbo::Stroke::new(0.01), transform, color_parsed, None, &path);
}
// Main ring
let circle = kurbo::Circle::new((center.x, center.y), main_ring_centerline_radius);
self.scene
.stroke(&kurbo::Stroke::new(main_ring_stroke_width), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &circle);
}
fn pivot(&mut self, position: DVec2, angle: f64) {
let uv = DVec2::from_angle(angle);
let (x, y) = (position.round() - DVec2::splat(0.5)).into();
let transform = self.get_transform();
// Circle
let circle = kurbo::Circle::new((x, y), PIVOT_DIAMETER / 2.);
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(COLOR_OVERLAY_YELLOW), None, &circle);
// Crosshair
let crosshair_radius: f64 = (PIVOT_CROSSHAIR_LENGTH - PIVOT_CROSSHAIR_THICKNESS) / 2.;
let mut stroke = kurbo::Stroke::new(PIVOT_CROSSHAIR_THICKNESS);
stroke = stroke.with_caps(kurbo::Cap::Round);
// Horizontal line
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(x + crosshair_radius * uv.x, y + crosshair_radius * uv.y));
path.line_to(kurbo::Point::new(x - crosshair_radius * uv.x, y - crosshair_radius * uv.y));
self.scene.stroke(&stroke, transform, Self::parse_color(COLOR_OVERLAY_YELLOW), None, &path);
// Vertical line
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(x - crosshair_radius * uv.y, y + crosshair_radius * uv.x));
path.line_to(kurbo::Point::new(x + crosshair_radius * uv.y, y - crosshair_radius * uv.x));
self.scene.stroke(&stroke, transform, Self::parse_color(COLOR_OVERLAY_YELLOW), None, &path);
}
fn dowel_pin(&mut self, position: DVec2, angle: f64, color: Option<&str>) {
let (x, y) = (position.round() - DVec2::splat(0.5)).into();
let color = color.unwrap_or(COLOR_OVERLAY_YELLOW_DULL);
let transform = self.get_transform();
let circle = kurbo::Circle::new((x, y), DOWEL_PIN_RADIUS);
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &circle);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color), None, &circle);
let mut path = BezPath::new();
let start1 = FRAC_PI_2 + angle;
let start1_x = x + DOWEL_PIN_RADIUS * start1.cos();
let start1_y = y + DOWEL_PIN_RADIUS * start1.sin();
path.move_to(kurbo::Point::new(x, y));
path.line_to(kurbo::Point::new(start1_x, start1_y));
let arc1 = kurbo::Arc::new((x, y), (DOWEL_PIN_RADIUS, DOWEL_PIN_RADIUS), start1, FRAC_PI_2, 0.0);
arc1.to_cubic_beziers(0.1, |p1, p2, p| {
path.curve_to(p1, p2, p);
});
path.close_path();
let start2 = PI + FRAC_PI_2 + angle;
let start2_x = x + DOWEL_PIN_RADIUS * start2.cos();
let start2_y = y + DOWEL_PIN_RADIUS * start2.sin();
path.move_to(kurbo::Point::new(x, y));
path.line_to(kurbo::Point::new(start2_x, start2_y));
let arc2 = kurbo::Arc::new((x, y), (DOWEL_PIN_RADIUS, DOWEL_PIN_RADIUS), start2, FRAC_PI_2, 0.0);
arc2.to_cubic_beziers(0.1, |p1, p2, p| {
path.curve_to(p1, p2, p);
});
path.close_path();
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color), None, &path);
}
#[allow(clippy::too_many_arguments)]
fn arc_sweep_angle(&mut self, offset_angle: f64, angle: f64, end_point_position: DVec2, bold_radius: f64, pivot: DVec2, text: &str, transform: DAffine2) {
self.manipulator_handle(end_point_position, true, None);
self.draw_arc_gizmo_angle(pivot, bold_radius, ARC_SWEEP_GIZMO_RADIUS, offset_angle, angle.to_radians());
self.text(text, COLOR_OVERLAY_BLUE, None, transform, 16., [Pivot::Middle, Pivot::Middle]);
}
/// Used by the Pen and Path tools to outline the path of the shape.
fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) {
let vello_transform = self.get_transform();
let mut path = BezPath::new();
let mut last_point = None;
for (_, bezier, start_id, end_id) in vector.segment_iter() {
let move_to = last_point != Some(start_id);
last_point = Some(end_id);
self.bezier_to_path(bezier, transform, move_to, &mut path);
}
self.scene.stroke(&kurbo::Stroke::new(1.), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
}
/// Used by the Pen tool in order to show how the bezier curve would look like.
fn outline_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
let vello_transform = self.get_transform();
let mut path = BezPath::new();
self.bezier_to_path(bezier, transform, true, &mut path);
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/overlays/utility_types_web.rs | editor/src/messages/portfolio/document/overlays/utility_types_web.rs | use super::utility_functions::overlay_canvas_context;
use crate::consts::{
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_YELLOW, COLOR_OVERLAY_YELLOW_DULL,
COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE,
PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SEGMENT_SELECTED_THICKNESS, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::Message;
use crate::messages::viewport::ViewportMessageHandler;
use core::borrow::Borrow;
use core::f64::consts::{FRAC_PI_2, PI, TAU};
use glam::{DAffine2, DVec2};
use graphene_std::Color;
use graphene_std::math::quad::Quad;
use graphene_std::subpath::Subpath;
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::{dvec2_to_point, point_to_dvec2};
use graphene_std::vector::{PointId, SegmentId, Vector};
use kurbo::{self, Affine, CubicBez, ParamCurve, PathSeg};
use std::collections::HashMap;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{OffscreenCanvas, OffscreenCanvasRenderingContext2d};
pub type OverlayProvider = fn(OverlayContext) -> Message;
pub fn empty_provider() -> OverlayProvider {
|_| Message::NoOp
}
/// Types of overlays used by DocumentMessage to enable/disable the selected set of viewport overlays.
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum OverlaysType {
ArtboardName,
CompassRose,
QuickMeasurement,
TransformMeasurement,
TransformCage,
HoverOutline,
SelectionOutline,
Pivot,
Origin,
Path,
Anchors,
Handles,
}
#[derive(PartialEq, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(default)]
pub struct OverlaysVisibilitySettings {
pub all: bool,
pub artboard_name: bool,
pub compass_rose: bool,
pub quick_measurement: bool,
pub transform_measurement: bool,
pub transform_cage: bool,
pub hover_outline: bool,
pub selection_outline: bool,
pub pivot: bool,
pub origin: bool,
pub path: bool,
pub anchors: bool,
pub handles: bool,
}
impl Default for OverlaysVisibilitySettings {
fn default() -> Self {
Self {
all: true,
artboard_name: true,
compass_rose: true,
quick_measurement: true,
transform_measurement: true,
transform_cage: true,
hover_outline: true,
selection_outline: true,
pivot: true,
origin: true,
path: true,
anchors: true,
handles: true,
}
}
}
impl OverlaysVisibilitySettings {
pub fn all(&self) -> bool {
self.all
}
pub fn artboard_name(&self) -> bool {
self.all && self.artboard_name
}
pub fn compass_rose(&self) -> bool {
self.all && self.compass_rose
}
pub fn quick_measurement(&self) -> bool {
self.all && self.quick_measurement
}
pub fn transform_measurement(&self) -> bool {
self.all && self.transform_measurement
}
pub fn transform_cage(&self) -> bool {
self.all && self.transform_cage
}
pub fn hover_outline(&self) -> bool {
self.all && self.hover_outline
}
pub fn selection_outline(&self) -> bool {
self.all && self.selection_outline
}
pub fn pivot(&self) -> bool {
self.all && self.pivot
}
pub fn origin(&self) -> bool {
self.all && self.origin
}
pub fn path(&self) -> bool {
self.all && self.path
}
pub fn anchors(&self) -> bool {
self.all && self.anchors
}
pub fn handles(&self) -> bool {
self.all && self.anchors && self.handles
}
}
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct OverlayContext {
// Serde functionality isn't used but is required by the message system macros
#[serde(skip, default = "overlay_canvas_context")]
#[specta(skip)]
pub render_context: web_sys::CanvasRenderingContext2d,
pub viewport: ViewportMessageHandler,
pub visibility_settings: OverlaysVisibilitySettings,
}
// Message hashing isn't used but is required by the message system macros
impl core::hash::Hash for OverlayContext {
fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}
impl OverlayContext {
pub fn quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>) {
self.dashed_polygon(&quad.0, stroke_color, color_fill, None, None, None);
}
pub fn draw_triangle(&mut self, base: DVec2, direction: DVec2, size: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let normal = direction.perp();
let top = base + direction * size;
let edge1 = base + normal * size / 2.;
let edge2 = base - normal * size / 2.;
self.start_dpi_aware_transform();
self.render_context.begin_path();
self.render_context.move_to(top.x, top.y);
self.render_context.line_to(edge1.x, edge1.y);
self.render_context.line_to(edge2.x, edge2.y);
self.render_context.close_path();
self.render_context.set_fill_style_str(color_fill);
self.render_context.set_stroke_style_str(color_stroke);
self.render_context.fill();
self.render_context.stroke();
self.end_dpi_aware_transform();
}
pub fn dashed_quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.dashed_polygon(&quad.0, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset);
}
pub fn polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>) {
self.dashed_polygon(polygon, stroke_color, color_fill, None, None, None);
}
pub fn dashed_polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
if polygon.len() < 2 {
return;
}
self.start_dpi_aware_transform();
// Set the dash pattern
if let Some(dash_width) = dash_width {
let dash_gap_width = dash_gap_width.unwrap_or(1.);
let array = js_sys::Array::new();
array.push(&JsValue::from(dash_width));
array.push(&JsValue::from(dash_gap_width));
if let Some(dash_offset) = dash_offset {
if dash_offset != 0. {
self.render_context.set_line_dash_offset(dash_offset);
}
}
self.render_context
.set_line_dash(&JsValue::from(array))
.map_err(|error| log::warn!("Error drawing dashed line: {:?}", error))
.ok();
}
self.render_context.begin_path();
self.render_context.move_to(polygon.last().unwrap().x.round() - 0.5, polygon.last().unwrap().y.round() - 0.5);
for point in polygon {
self.render_context.line_to(point.x.round() - 0.5, point.y.round() - 0.5);
}
if let Some(color_fill) = color_fill {
self.render_context.set_fill_style_str(color_fill);
self.render_context.fill();
}
let stroke_color = stroke_color.unwrap_or(COLOR_OVERLAY_BLUE);
self.render_context.set_stroke_style_str(stroke_color);
self.render_context.stroke();
// Reset the dash pattern back to solid
if dash_width.is_some() {
self.render_context
.set_line_dash(&JsValue::from(js_sys::Array::new()))
.map_err(|error| log::warn!("Error drawing dashed line: {:?}", error))
.ok();
}
if dash_offset.is_some() && dash_offset != Some(0.) {
self.render_context.set_line_dash_offset(0.);
}
self.end_dpi_aware_transform();
}
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
self.dashed_line(start, end, color, thickness, None, None, None)
}
#[allow(clippy::too_many_arguments)]
pub fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.start_dpi_aware_transform();
// Set the dash pattern
if let Some(dash_width) = dash_width {
let dash_gap_width = dash_gap_width.unwrap_or(1.);
let array = js_sys::Array::new();
array.push(&JsValue::from(dash_width));
array.push(&JsValue::from(dash_gap_width));
if let Some(dash_offset) = dash_offset {
if dash_offset != 0. {
self.render_context.set_line_dash_offset(dash_offset);
}
}
self.render_context
.set_line_dash(&JsValue::from(array))
.map_err(|error| log::warn!("Error drawing dashed line: {:?}", error))
.ok();
}
let start = start.round() - DVec2::splat(0.5);
let end = end.round() - DVec2::splat(0.5);
self.render_context.begin_path();
self.render_context.move_to(start.x, start.y);
self.render_context.line_to(end.x, end.y);
self.render_context.set_line_width(thickness.unwrap_or(1.));
self.render_context.set_stroke_style_str(color.unwrap_or(COLOR_OVERLAY_BLUE));
self.render_context.stroke();
self.render_context.set_line_width(1.);
// Reset the dash pattern back to solid
if dash_width.is_some() {
self.render_context
.set_line_dash(&JsValue::from(js_sys::Array::new()))
.map_err(|error| log::warn!("Error drawing dashed line: {:?}", error))
.ok();
}
if dash_offset.is_some() && dash_offset != Some(0.) {
self.render_context.set_line_dash_offset(0.);
}
self.end_dpi_aware_transform();
}
#[allow(clippy::too_many_arguments)]
pub fn dashed_ellipse(
&mut self,
center: DVec2,
radius_x: f64,
radius_y: f64,
rotation: Option<f64>,
start_angle: Option<f64>,
end_angle: Option<f64>,
counterclockwise: Option<bool>,
color_fill: Option<&str>,
color_stroke: Option<&str>,
dash_width: Option<f64>,
dash_gap_width: Option<f64>,
dash_offset: Option<f64>,
) {
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let center = center.round();
self.start_dpi_aware_transform();
if let Some(dash_width) = dash_width {
let dash_gap_width = dash_gap_width.unwrap_or(1.);
let array = js_sys::Array::new();
array.push(&JsValue::from(dash_width));
array.push(&JsValue::from(dash_gap_width));
if let Some(dash_offset) = dash_offset {
if dash_offset != 0. {
self.render_context.set_line_dash_offset(dash_offset);
}
}
self.render_context
.set_line_dash(&JsValue::from(array))
.map_err(|error| log::warn!("Error drawing dashed line: {:?}", error))
.ok();
}
self.render_context.begin_path();
self.render_context
.ellipse_with_anticlockwise(
center.x,
center.y,
radius_x,
radius_y,
rotation.unwrap_or_default(),
start_angle.unwrap_or_default(),
end_angle.unwrap_or(TAU),
counterclockwise.unwrap_or_default(),
)
.expect("Failed to draw ellipse");
self.render_context.set_stroke_style_str(color_stroke);
if let Some(fill_color) = color_fill {
self.render_context.set_fill_style_str(fill_color);
self.render_context.fill();
}
self.render_context.stroke();
// Reset the dash pattern back to solid
if dash_width.is_some() {
self.render_context
.set_line_dash(&JsValue::from(js_sys::Array::new()))
.map_err(|error| log::warn!("Error drawing dashed line: {:?}", error))
.ok();
}
if dash_offset.is_some() && dash_offset != Some(0.) {
self.render_context.set_line_dash_offset(0.);
}
self.end_dpi_aware_transform();
}
pub fn dashed_circle(
&mut self,
position: DVec2,
radius: f64,
color_fill: Option<&str>,
color_stroke: Option<&str>,
dash_width: Option<f64>,
dash_gap_width: Option<f64>,
dash_offset: Option<f64>,
transform: Option<DAffine2>,
) {
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let position = position.round();
self.start_dpi_aware_transform();
if let Some(transform) = transform {
let [a, b, c, d, e, f] = transform.to_cols_array();
self.render_context.transform(a, b, c, d, e, f).expect("Failed to transform circle");
}
if let Some(dash_width) = dash_width {
let dash_gap_width = dash_gap_width.unwrap_or(1.);
let array = js_sys::Array::new();
array.push(&JsValue::from(dash_width));
array.push(&JsValue::from(dash_gap_width));
if let Some(dash_offset) = dash_offset {
if dash_offset != 0. {
self.render_context.set_line_dash_offset(dash_offset);
}
}
self.render_context
.set_line_dash(&JsValue::from(array))
.map_err(|error| log::warn!("Error drawing dashed line: {:?}", error))
.ok();
}
self.render_context.begin_path();
self.render_context.arc(position.x, position.y, radius, 0., TAU).expect("Failed to draw the circle");
self.render_context.set_stroke_style_str(color_stroke);
if let Some(fill_color) = color_fill {
self.render_context.set_fill_style_str(fill_color);
self.render_context.fill();
}
self.render_context.stroke();
// Reset the dash pattern back to solid
if dash_width.is_some() {
self.render_context
.set_line_dash(&JsValue::from(js_sys::Array::new()))
.map_err(|error| log::warn!("Error drawing dashed line: {:?}", error))
.ok();
}
if dash_offset.is_some() && dash_offset != Some(0.) {
self.render_context.set_line_dash_offset(0.);
}
self.end_dpi_aware_transform();
}
pub fn circle(&mut self, position: DVec2, radius: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
self.dashed_circle(position, radius, color_fill, color_stroke, None, None, None, None);
}
pub fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
self.start_dpi_aware_transform();
let position = position.round() - DVec2::splat(0.5);
self.render_context.begin_path();
self.render_context
.arc(position.x, position.y, MANIPULATOR_GROUP_MARKER_SIZE / 2., 0., TAU)
.expect("Failed to draw the circle");
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.render_context.set_fill_style_str(fill);
self.render_context.set_stroke_style_str(color.unwrap_or(COLOR_OVERLAY_BLUE));
self.render_context.fill();
self.render_context.stroke();
self.end_dpi_aware_transform();
}
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let color_stroke = color.unwrap_or(COLOR_OVERLAY_BLUE);
let color_fill = if selected { color_stroke } else { COLOR_OVERLAY_WHITE };
self.square(position, None, Some(color_fill), Some(color_stroke));
}
pub fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
self.start_dpi_aware_transform();
let position = position.round() - DVec2::splat(0.5);
self.render_context.begin_path();
self.render_context
.arc(position.x, position.y, (MANIPULATOR_GROUP_MARKER_SIZE + 2.) / 2., 0., TAU)
.expect("Failed to draw the circle");
self.render_context.set_fill_style_str(COLOR_OVERLAY_BLUE_50);
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE_50);
self.render_context.fill();
self.render_context.stroke();
self.render_context.begin_path();
self.render_context
.arc(position.x, position.y, MANIPULATOR_GROUP_MARKER_SIZE / 2., 0., TAU)
.expect("Failed to draw the circle");
let color_fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.render_context.set_fill_style_str(color_fill);
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
self.render_context.fill();
self.render_context.stroke();
self.end_dpi_aware_transform();
}
pub fn hover_manipulator_anchor(&mut self, position: DVec2, selected: bool) {
self.square(position, Some(MANIPULATOR_GROUP_MARKER_SIZE + 2.), Some(COLOR_OVERLAY_BLUE_50), Some(COLOR_OVERLAY_BLUE_50));
let color_fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.square(position, None, Some(color_fill), Some(COLOR_OVERLAY_BLUE));
}
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
let quad = DAffine2::from_angle_translation(rotation, position) * Quad::from_box([DVec2::splat(-RESIZE_HANDLE_SIZE / 2.), DVec2::splat(RESIZE_HANDLE_SIZE / 2.)]);
self.quad(quad, None, Some(COLOR_OVERLAY_WHITE));
}
pub fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) {
let edge_dir = (edge_end - edge_start).normalize();
let mid = edge_end.midpoint(edge_start);
for edge in [edge_dir, -edge_dir] {
self.draw_triangle(mid + edge * (3. + SKEW_TRIANGLE_OFFSET), edge, SKEW_TRIANGLE_SIZE, None, None);
}
}
/// Transforms the canvas context to adjust for DPI scaling
///
/// Overwrites all existing tranforms. This operation can be reversed with [`Self::reset_transform`].
fn start_dpi_aware_transform(&self) {
let [a, b, c, d, e, f] = DAffine2::from_scale(DVec2::splat(self.viewport.scale())).to_cols_array();
self.render_context
.set_transform(a, b, c, d, e, f)
.expect("transform should be able to be set to be able to account for DPI");
}
/// Un-transforms the Canvas context to adjust for DPI scaling
///
/// Warning: this function doesn't only reset the DPI scaling adjustment, it resets the entire transform.
fn end_dpi_aware_transform(&self) {
self.render_context.reset_transform().expect("transform should be able to be reset to be able to account for DPI");
}
pub fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
let size = size.unwrap_or(MANIPULATOR_GROUP_MARKER_SIZE);
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let position = position.round() - DVec2::splat(0.5);
let corner = position - DVec2::splat(size) / 2.;
self.start_dpi_aware_transform();
self.render_context.begin_path();
self.render_context.rect(corner.x, corner.y, size, size);
self.render_context.set_fill_style_str(color_fill);
self.render_context.set_stroke_style_str(color_stroke);
self.render_context.set_line_width(1.);
self.render_context.fill();
self.render_context.stroke();
self.end_dpi_aware_transform();
}
pub fn pixel(&mut self, position: DVec2, color: Option<&str>) {
let size = 1.;
let color_fill = color.unwrap_or(COLOR_OVERLAY_WHITE);
let position = position.round() - DVec2::splat(0.5);
let corner = position - DVec2::splat(size) / 2.;
self.start_dpi_aware_transform();
self.render_context.begin_path();
self.render_context.rect(corner.x, corner.y, size, size);
self.render_context.set_fill_style_str(color_fill);
self.render_context.fill();
self.end_dpi_aware_transform();
}
pub fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
let segments = ((end_at - start_from).abs() / (std::f64::consts::PI / 4.)).ceil() as usize;
let step = (end_at - start_from) / segments as f64;
let half_step = step / 2.;
let factor = 4. / 3. * half_step.sin() / (1. + half_step.cos());
self.render_context.begin_path();
for i in 0..segments {
let start_angle = start_from + step * i as f64;
let end_angle = start_angle + step;
let start_vec = DVec2::from_angle(start_angle);
let end_vec = DVec2::from_angle(end_angle);
let start = center + radius * start_vec;
let end = center + radius * end_vec;
let handle_start = start + start_vec.perp() * radius * factor;
let handle_end = end - end_vec.perp() * radius * factor;
let bezier = PathSeg::Cubic(CubicBez::new(dvec2_to_point(start), dvec2_to_point(handle_start), dvec2_to_point(handle_end), dvec2_to_point(end)));
self.bezier_command(bezier, DAffine2::IDENTITY, i == 0);
}
self.render_context.stroke();
}
pub fn draw_arc_gizmo_angle(&mut self, pivot: DVec2, bold_radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
let end_point1 = pivot + bold_radius * DVec2::from_angle(angle + offset_angle);
self.line(pivot, end_point1, None, None);
self.draw_arc(pivot, arc_radius, offset_angle, (angle) % TAU + offset_angle);
}
pub fn draw_angle(&mut self, pivot: DVec2, radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
let end_point1 = pivot + radius * DVec2::from_angle(angle + offset_angle);
let end_point2 = pivot + radius * DVec2::from_angle(offset_angle);
self.line(pivot, end_point1, None, None);
self.dashed_line(pivot, end_point2, None, None, Some(2.), Some(2.), Some(0.5));
self.draw_arc(pivot, arc_radius, offset_angle, (angle) % TAU + offset_angle);
}
pub fn draw_scale(&mut self, start: DVec2, scale: f64, radius: f64, text: &str) {
let sign = scale.signum();
let mut fill_color = Color::from_rgb_str(COLOR_OVERLAY_WHITE.strip_prefix('#').unwrap()).unwrap().with_alpha(0.05).to_rgba_hex_srgb();
fill_color.insert(0, '#');
let fill_color = Some(fill_color.as_str());
self.line(start + DVec2::X * radius * sign, start + DVec2::X * (radius * scale), None, None);
self.circle(start, radius, fill_color, None);
self.circle(start, radius * scale.abs(), fill_color, None);
self.text(
text,
COLOR_OVERLAY_BLUE,
None,
DAffine2::from_translation(start + sign * DVec2::X * radius * (1. + scale.abs()) / 2.),
2.,
[Pivot::Middle, Pivot::End],
)
}
pub fn compass_rose(&mut self, compass_center: DVec2, angle: f64, show_compass_with_hover_ring: Option<bool>) {
const HOVER_RING_OUTER_RADIUS: f64 = COMPASS_ROSE_HOVER_RING_DIAMETER / 2.;
const MAIN_RING_OUTER_RADIUS: f64 = COMPASS_ROSE_MAIN_RING_DIAMETER / 2.;
const MAIN_RING_INNER_RADIUS: f64 = COMPASS_ROSE_RING_INNER_DIAMETER / 2.;
const ARROW_RADIUS: f64 = COMPASS_ROSE_ARROW_SIZE / 2.;
const HOVER_RING_STROKE_WIDTH: f64 = HOVER_RING_OUTER_RADIUS - MAIN_RING_INNER_RADIUS;
const HOVER_RING_CENTERLINE_RADIUS: f64 = (HOVER_RING_OUTER_RADIUS + MAIN_RING_INNER_RADIUS) / 2.;
const MAIN_RING_STROKE_WIDTH: f64 = MAIN_RING_OUTER_RADIUS - MAIN_RING_INNER_RADIUS;
const MAIN_RING_CENTERLINE_RADIUS: f64 = (MAIN_RING_OUTER_RADIUS + MAIN_RING_INNER_RADIUS) / 2.;
let Some(show_hover_ring) = show_compass_with_hover_ring else { return };
self.start_dpi_aware_transform();
let center = compass_center.round() - DVec2::splat(0.5);
// Save the old line width to restore it later
let old_line_width = self.render_context.line_width();
// Hover ring
if show_hover_ring {
let mut fill_color = Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap()).unwrap().with_alpha(0.5).to_rgba_hex_srgb();
fill_color.insert(0, '#');
self.render_context.set_line_width(HOVER_RING_STROKE_WIDTH);
self.render_context.begin_path();
self.render_context.arc(center.x, center.y, HOVER_RING_CENTERLINE_RADIUS, 0., TAU).expect("Failed to draw hover ring");
self.render_context.set_stroke_style_str(&fill_color);
self.render_context.stroke();
}
// Arrows
self.render_context.set_line_width(0.01);
for i in 0..4 {
let direction = DVec2::from_angle(i as f64 * FRAC_PI_2 + angle);
let color = if i % 2 == 0 { COLOR_OVERLAY_RED } else { COLOR_OVERLAY_GREEN };
let tip = center + direction * HOVER_RING_OUTER_RADIUS;
let base = center + direction * (MAIN_RING_INNER_RADIUS + MAIN_RING_OUTER_RADIUS) / 2.;
let r = (ARROW_RADIUS.powi(2) + MAIN_RING_INNER_RADIUS.powi(2)).sqrt();
let (cos, sin) = (MAIN_RING_INNER_RADIUS / r, ARROW_RADIUS / r);
let side1 = center + r * DVec2::new(cos * direction.x - sin * direction.y, sin * direction.x + direction.y * cos);
let side2 = center + r * DVec2::new(cos * direction.x + sin * direction.y, -sin * direction.x + direction.y * cos);
self.render_context.begin_path();
self.render_context.move_to(tip.x, tip.y);
self.render_context.line_to(side1.x, side1.y);
self.render_context.line_to(base.x, base.y);
self.render_context.line_to(side2.x, side2.y);
self.render_context.close_path();
self.render_context.set_fill_style_str(color);
self.render_context.fill();
self.render_context.set_stroke_style_str(color);
self.render_context.stroke();
}
// Main ring
self.render_context.set_line_width(MAIN_RING_STROKE_WIDTH);
self.render_context.begin_path();
self.render_context.arc(center.x, center.y, MAIN_RING_CENTERLINE_RADIUS, 0., TAU).expect("Failed to draw main ring");
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
self.render_context.stroke();
// Restore the old line width
self.render_context.set_line_width(old_line_width);
}
pub fn pivot(&mut self, position: DVec2, angle: f64) {
let uv = DVec2::from_angle(angle);
let (x, y) = (position.round() - DVec2::splat(0.5)).into();
self.start_dpi_aware_transform();
// Circle
self.render_context.begin_path();
self.render_context.arc(x, y, PIVOT_DIAMETER / 2., 0., TAU).expect("Failed to draw the circle");
self.render_context.set_fill_style_str(COLOR_OVERLAY_YELLOW);
self.render_context.fill();
// Crosshair
// Round line caps add half the stroke width to the length on each end, so we subtract that here before halving to get the radius
const CROSSHAIR_RADIUS: f64 = (PIVOT_CROSSHAIR_LENGTH - PIVOT_CROSSHAIR_THICKNESS) / 2.;
self.render_context.set_stroke_style_str(COLOR_OVERLAY_YELLOW);
self.render_context.set_line_cap("round");
self.render_context.begin_path();
self.render_context.move_to(x + CROSSHAIR_RADIUS * uv.x, y + CROSSHAIR_RADIUS * uv.y);
self.render_context.line_to(x - CROSSHAIR_RADIUS * uv.x, y - CROSSHAIR_RADIUS * uv.y);
self.render_context.stroke();
self.render_context.begin_path();
self.render_context.move_to(x - CROSSHAIR_RADIUS * uv.y, y + CROSSHAIR_RADIUS * uv.x);
self.render_context.line_to(x + CROSSHAIR_RADIUS * uv.y, y - CROSSHAIR_RADIUS * uv.x);
self.render_context.stroke();
self.render_context.set_line_cap("butt");
self.end_dpi_aware_transform();
}
pub fn dowel_pin(&mut self, position: DVec2, angle: f64, color: Option<&str>) {
let (x, y) = (position.round() - DVec2::splat(0.5)).into();
let color = color.unwrap_or(COLOR_OVERLAY_YELLOW_DULL);
self.start_dpi_aware_transform();
// Draw the background circle with a white fill and blue outline
self.render_context.begin_path();
self.render_context.arc(x, y, DOWEL_PIN_RADIUS, 0., TAU).expect("Failed to draw the circle");
self.render_context.set_fill_style_str(COLOR_OVERLAY_WHITE);
self.render_context.fill();
self.render_context.set_stroke_style_str(color);
self.render_context.stroke();
// Draw the two blue filled sectors
self.render_context.begin_path();
// Top-left sector
self.render_context.move_to(x, y);
self.render_context.arc(x, y, DOWEL_PIN_RADIUS, FRAC_PI_2 + angle, PI + angle).expect("Failed to draw arc");
self.render_context.close_path();
// Bottom-right sector
self.render_context.move_to(x, y);
self.render_context.arc(x, y, DOWEL_PIN_RADIUS, PI + FRAC_PI_2 + angle, TAU + angle).expect("Failed to draw arc");
self.render_context.close_path();
self.render_context.set_fill_style_str(color);
self.render_context.fill();
self.end_dpi_aware_transform();
}
pub fn arc_sweep_angle(&mut self, offset_angle: f64, angle: f64, end_point_position: DVec2, bold_radius: f64, pivot: DVec2, text: &str, transform: DAffine2) {
self.manipulator_handle(end_point_position, true, None);
self.draw_arc_gizmo_angle(pivot, bold_radius, ARC_SWEEP_GIZMO_RADIUS, offset_angle, angle.to_radians());
self.text(&text, COLOR_OVERLAY_BLUE, None, transform, 16., [Pivot::Middle, Pivot::Middle]);
}
/// Used by the Pen and Path tools to outline the path of the shape.
pub fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) {
self.start_dpi_aware_transform();
self.render_context.begin_path();
let mut last_point = None;
for (_, bezier, start_id, end_id) in vector.segment_iter() {
let move_to = last_point != Some(start_id);
last_point = Some(end_id);
self.bezier_command(bezier, transform, move_to);
}
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
self.render_context.stroke();
self.end_dpi_aware_transform();
}
/// Used by the Pen tool in order to show how the bezier curve would look like.
pub fn outline_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.start_dpi_aware_transform();
self.render_context.begin_path();
self.bezier_command(bezier, transform, true);
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
self.render_context.stroke();
self.end_dpi_aware_transform();
}
/// Used by the path tool segment mode in order to show the selected segments.
pub fn outline_select_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.start_dpi_aware_transform();
self.render_context.begin_path();
self.bezier_command(bezier, transform, true);
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
self.render_context.set_line_width(SEGMENT_SELECTED_THICKNESS);
self.render_context.stroke();
self.render_context.set_line_width(1.);
self.end_dpi_aware_transform();
}
pub fn outline_overlay_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.start_dpi_aware_transform();
self.render_context.begin_path();
self.bezier_command(bezier, transform, true);
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE_50);
self.render_context.set_line_width(SEGMENT_SELECTED_THICKNESS);
self.render_context.stroke();
self.render_context.set_line_width(1.);
self.end_dpi_aware_transform();
}
fn bezier_command(&self, bezier: PathSeg, transform: DAffine2, move_to: bool) {
self.start_dpi_aware_transform();
let bezier = Affine::new(transform.to_cols_array()) * bezier;
if move_to {
self.render_context.move_to(bezier.start().x, bezier.start().y);
}
match bezier.as_path_el() {
kurbo::PathEl::LineTo(point) => self.render_context.line_to(point.x, point.y),
kurbo::PathEl::QuadTo(point, point1) => self.render_context.quadratic_curve_to(point.x, point.y, point1.x, point1.y),
kurbo::PathEl::CurveTo(point, point1, point2) => self.render_context.bezier_curve_to(point.x, point.y, point1.x, point1.y, point2.x, point2.y),
_ => unreachable!(),
}
self.end_dpi_aware_transform();
}
fn push_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
self.start_dpi_aware_transform();
self.render_context.begin_path();
for subpath in subpaths {
let subpath = subpath.borrow();
let mut curves = subpath.iter().peekable();
let Some(&first) = curves.peek() else {
continue;
};
let start_point = transform.transform_point2(point_to_dvec2(first.start()));
self.render_context.move_to(start_point.x, start_point.y);
for curve in curves {
match curve {
PathSeg::Line(line) => {
let a = transform.transform_point2(point_to_dvec2(line.p1));
let a = a.round() - DVec2::splat(0.5);
self.render_context.line_to(a.x, a.y);
}
PathSeg::Quad(quad_bez) => {
let a = transform.transform_point2(point_to_dvec2(quad_bez.p1));
let b = transform.transform_point2(point_to_dvec2(quad_bez.p2));
let a = a.round() - DVec2::splat(0.5);
let b = b.round() - DVec2::splat(0.5);
self.render_context.quadratic_curve_to(a.x, a.y, b.x, b.y);
}
PathSeg::Cubic(cubic_bez) => {
let a = transform.transform_point2(point_to_dvec2(cubic_bez.p1));
let b = transform.transform_point2(point_to_dvec2(cubic_bez.p2));
let c = transform.transform_point2(point_to_dvec2(cubic_bez.p3));
let a = a.round() - DVec2::splat(0.5);
let b = b.round() - DVec2::splat(0.5);
let c = c.round() - DVec2::splat(0.5);
self.render_context.bezier_curve_to(a.x, a.y, b.x, b.y, c.x, c.y);
}
}
}
if subpath.closed() {
self.render_context.close_path();
}
}
self.end_dpi_aware_transform();
}
/// Used by the Select tool to outline a path or a free point when selected or hovered.
pub fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
let mut subpaths: Vec<Subpath<PointId>> = vec![];
target_types.for_each(|target_type| match target_type.borrow() {
ClickTargetType::FreePoint(point) => {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Subpath(subpath) => subpaths.push(subpath.clone()),
});
if !subpaths.is_empty() {
self.push_path(subpaths.iter(), transform);
let color = color.unwrap_or(COLOR_OVERLAY_BLUE);
self.render_context.set_stroke_style_str(color);
self.render_context.set_line_width(1.);
self.render_context.stroke();
}
}
/// Fills the area inside the path. Assumes `color` is in gamma space.
/// Used by the Pen tool to show the path being closed.
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
self.push_path(subpaths, transform);
self.render_context.set_fill_style_str(color);
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/overlays/grid_overlays.rs | editor/src/messages/portfolio/document/overlays/grid_overlays.rs | 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_std::raster::color::Color;
use graphene_std::renderer::Quad;
use graphene_std::vector::style::FillChoice;
fn grid_overlay_rectangular(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, spacing: DVec2) {
let origin = document.snapping_state.grid.origin;
let grid_color = "#".to_string() + &document.snapping_state.grid.grid_color.to_rgba_hex_srgb();
let Some(spacing) = GridSnapping::compute_rectangle_spacing(spacing, &document.document_ptz) else {
return;
};
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(overlay_context.viewport.center_in_viewport_space().into(), &document.document_ptz);
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.viewport.size().into()]);
for primary in 0..2 {
let secondary = 1 - primary;
let min = bounds.0.iter().map(|&corner| corner[secondary]).min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
let max = bounds.0.iter().map(|&corner| corner[secondary]).max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
let primary_start = bounds.0.iter().map(|&corner| corner[primary]).min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
let primary_end = bounds.0.iter().map(|&corner| corner[primary]).max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
let spacing = spacing[secondary];
for line_index in 0..=((max - min) / spacing).ceil() as i32 {
let secondary_pos = (((min - origin[secondary]) / spacing).ceil() + line_index as f64) * spacing + origin[secondary];
let start = if primary == 0 {
DVec2::new(primary_start, secondary_pos)
} else {
DVec2::new(secondary_pos, primary_start)
};
let end = if primary == 0 {
DVec2::new(primary_end, secondary_pos)
} else {
DVec2::new(secondary_pos, primary_end)
};
overlay_context.line(document_to_viewport.transform_point2(start), document_to_viewport.transform_point2(end), Some(&grid_color), None);
}
}
}
// In the best case, where the x distance/total dots is an integer, this will reduce draw requests from the current m(horizontal dots)*n(vertical dots) to m(horizontal lines) * 1(line changes).
// In the worst case, where the x distance/total dots is an integer+0.5, then each pixel will require a new line, and requests will be m(horizontal lines)*n(line changes = horizontal dots).
// The draw dashed line method will also be not grid aligned for tilted grids.
// TODO: Potentially create an image and render the image onto the canvas a single time.
// TODO: Implement this with a dashed line (`set_line_dash`), with integer spacing which is continuously adjusted to correct the accumulated error.
fn grid_overlay_rectangular_dot(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, spacing: DVec2) {
let origin = document.snapping_state.grid.origin;
let grid_color = "#".to_string() + &document.snapping_state.grid.grid_color.to_rgba_hex_srgb();
let Some(spacing) = GridSnapping::compute_rectangle_spacing(spacing, &document.document_ptz) else {
return;
};
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(overlay_context.viewport.center_in_viewport_space().into(), &document.document_ptz);
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.viewport.size().into()]);
let min = bounds.0.iter().map(|corner| corner.y).min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
let max = bounds.0.iter().map(|corner| corner.y).max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
let mut primary_start = bounds.0.iter().map(|corner| corner.x).min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
let mut primary_end = bounds.0.iter().map(|corner| corner.x).max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
primary_start = (primary_start / spacing.x).floor() * spacing.x + origin.x % spacing.x;
primary_end = (primary_end / spacing.x).floor() * spacing.x + origin.x % spacing.x;
// Round to avoid floating point errors
let total_dots = ((primary_end - primary_start) / spacing.x).round();
for line_index in 0..=((max - min) / spacing.y).ceil() as i32 {
let secondary_pos = (((min - origin.y) / spacing.y).ceil() + line_index as f64) * spacing.y + origin.y;
let start = DVec2::new(primary_start, secondary_pos);
let end = DVec2::new(primary_end, secondary_pos);
let x_per_dot = (end.x - start.x) / total_dots;
for dot_index in 0..=total_dots as usize {
let exact_x = x_per_dot * dot_index as f64;
overlay_context.pixel(document_to_viewport.transform_point2(DVec2::new(start.x + exact_x, start.y)).round(), Some(&grid_color))
}
}
}
fn grid_overlay_isometric(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, y_axis_spacing: f64, angle_a: f64, angle_b: f64) {
let grid_color = "#".to_string() + &document.snapping_state.grid.grid_color.to_rgba_hex_srgb();
let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap();
let origin = document.snapping_state.grid.origin;
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(overlay_context.viewport.center_in_viewport_space().into(), &document.document_ptz);
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.viewport.size().into()]);
let tan_a = angle_a.to_radians().tan();
let tan_b = angle_b.to_radians().tan();
let spacing = DVec2::new(y_axis_spacing / (tan_a + tan_b), y_axis_spacing);
let Some(spacing_multiplier) = GridSnapping::compute_isometric_multiplier(y_axis_spacing, tan_a + tan_b, &document.document_ptz) else {
return;
};
let isometric_spacing = spacing * spacing_multiplier;
let min_x = bounds.0.iter().map(|&corner| corner.x).min_by(cmp).unwrap_or_default();
let max_x = bounds.0.iter().map(|&corner| corner.x).max_by(cmp).unwrap_or_default();
let min_y = bounds.0.iter().map(|&corner| corner.y).min_by(cmp).unwrap_or_default();
let max_y = bounds.0.iter().map(|&corner| corner.y).max_by(cmp).unwrap_or_default();
let spacing = isometric_spacing.x;
for line_index in 0..=((max_x - min_x) / spacing).ceil() as i32 {
let x_pos = (((min_x - origin.x) / spacing).ceil() + line_index as f64) * spacing + origin.x;
let start = DVec2::new(x_pos, min_y);
let end = DVec2::new(x_pos, max_y);
overlay_context.line(document_to_viewport.transform_point2(start), document_to_viewport.transform_point2(end), Some(&grid_color), None);
}
for (tan, multiply) in [(tan_a, -1.), (tan_b, 1.)] {
let project = |corner: &DVec2| corner.y + multiply * tan * (corner.x - origin.x);
let inverse_project = |corner: &DVec2| corner.y - tan * multiply * (corner.x - origin.x);
let min_y = bounds.0.into_iter().min_by(|a, b| inverse_project(a).partial_cmp(&inverse_project(b)).unwrap()).unwrap_or_default();
let max_y = bounds.0.into_iter().max_by(|a, b| inverse_project(a).partial_cmp(&inverse_project(b)).unwrap()).unwrap_or_default();
let spacing = isometric_spacing.y;
let lines = ((inverse_project(&max_y) - inverse_project(&min_y)) / spacing).ceil() as i32;
for line_index in 0..=lines {
let y_pos = (((inverse_project(&min_y) - origin.y) / spacing).ceil() + line_index as f64) * spacing + origin.y;
let start = DVec2::new(min_x, project(&DVec2::new(min_x, y_pos)));
let end = DVec2::new(max_x, project(&DVec2::new(max_x, y_pos)));
overlay_context.line(document_to_viewport.transform_point2(start), document_to_viewport.transform_point2(end), Some(&grid_color), None);
}
}
}
fn grid_overlay_isometric_dot(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, y_axis_spacing: f64, angle_a: f64, angle_b: f64) {
let grid_color = "#".to_string() + &document.snapping_state.grid.grid_color.to_rgba_hex_srgb();
let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap();
let origin = document.snapping_state.grid.origin;
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(overlay_context.viewport.center_in_viewport_space().into(), &document.document_ptz);
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.viewport.size().into()]);
let tan_a = angle_a.to_radians().tan();
let tan_b = angle_b.to_radians().tan();
let spacing = DVec2::new(y_axis_spacing / (tan_a + tan_b), y_axis_spacing);
let Some(spacing_multiplier) = GridSnapping::compute_isometric_multiplier(y_axis_spacing, tan_a + tan_b, &document.document_ptz) else {
return;
};
let isometric_spacing = spacing * spacing_multiplier;
let min_x = bounds.0.iter().map(|&corner| corner.x).min_by(cmp).unwrap_or_default();
let max_x = bounds.0.iter().map(|&corner| corner.x).max_by(cmp).unwrap_or_default();
let spacing_x = isometric_spacing.x;
let tan = tan_a;
let multiply = -1.;
let project = |corner: &DVec2| corner.y + multiply * tan * (corner.x - origin.x);
let inverse_project = |corner: &DVec2| corner.y - tan * multiply * (corner.x - origin.x);
let min_y = bounds.0.into_iter().min_by(|a, b| inverse_project(a).partial_cmp(&inverse_project(b)).unwrap()).unwrap_or_default();
let max_y = bounds.0.into_iter().max_by(|a, b| inverse_project(a).partial_cmp(&inverse_project(b)).unwrap()).unwrap_or_default();
let spacing_y = isometric_spacing.y;
let lines = ((inverse_project(&max_y) - inverse_project(&min_y)) / spacing_y).ceil() as i32;
let cos_a = angle_a.to_radians().cos();
// If cos_a is 0 then there will be no intersections and thus no dots should be drawn
if cos_a.abs() <= 0.00001 {
return;
}
let x_offset = (((min_x - origin.x) / spacing_x).ceil()) * spacing_x + origin.x - min_x;
for line_index in 0..=lines {
let y_pos = (((inverse_project(&min_y) - origin.y) / spacing_y).ceil() + line_index as f64) * spacing_y + origin.y;
let start = DVec2::new(min_x + x_offset, project(&DVec2::new(min_x + x_offset, y_pos)));
let end = DVec2::new(max_x + x_offset, project(&DVec2::new(max_x + x_offset, y_pos)));
overlay_context.dashed_line(
document_to_viewport.transform_point2(start),
document_to_viewport.transform_point2(end),
Some(&grid_color),
None,
Some(1.),
Some((spacing_x / cos_a) * document_to_viewport.matrix2.x_axis.length() - 1.),
None,
);
}
}
pub fn grid_overlay(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext) {
match document.snapping_state.grid.grid_type {
GridType::Rectangular { spacing } => {
if document.snapping_state.grid.dot_display {
grid_overlay_rectangular_dot(document, overlay_context, spacing)
} else {
grid_overlay_rectangular(document, overlay_context, spacing)
}
}
GridType::Isometric { y_axis_spacing, angle_a, angle_b } => {
if document.snapping_state.grid.dot_display {
grid_overlay_isometric_dot(document, overlay_context, y_axis_spacing, angle_a, angle_b)
} else {
grid_overlay_isometric(document, overlay_context, y_axis_spacing, angle_a, angle_b)
}
}
}
}
pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
let mut widgets = Vec::new();
fn update_val<I, F: Fn(&mut GridSnapping, &I)>(grid: &GridSnapping, update: F) -> impl Fn(&I) -> Message + use<I, F> {
let grid = grid.clone();
move |input: &I| {
let mut grid = grid.clone();
update(&mut grid, input);
DocumentMessage::GridOptions { options: grid }.into()
}
}
let update_origin = |grid, update: fn(&mut GridSnapping) -> Option<&mut f64>| {
update_val::<NumberInput, _>(grid, move |grid, val| {
if let Some(val) = val.value
&& let Some(update) = update(grid)
{
*update = val;
}
})
};
let update_color = |grid, update: fn(&mut GridSnapping) -> Option<&mut Color>| {
update_val::<ColorInput, _>(grid, move |grid, color| {
if let (Some(color), Some(update_color)) = (color.value.as_solid(), update(grid)) {
*update_color = color.to_linear_srgb();
}
})
};
let update_display = |grid, update: fn(&mut GridSnapping) -> Option<&mut bool>| {
update_val::<CheckboxInput, _>(grid, move |grid, checkbox| {
if let Some(update) = update(grid) {
*update = checkbox.checked;
}
})
};
widgets.push(LayoutGroup::Row {
widgets: vec![TextLabel::new("Grid").bold(true).widget_instance()],
});
widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Type").table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(vec![
RadioEntryData::new("rectangular").label("Rectangular").on_update(update_val(grid, |grid, _| {
if let GridType::Isometric { y_axis_spacing, angle_a, angle_b } = grid.grid_type {
grid.isometric_y_spacing = y_axis_spacing;
grid.isometric_angle_a = angle_a;
grid.isometric_angle_b = angle_b;
}
grid.grid_type = GridType::Rectangular { spacing: grid.rectangular_spacing };
})),
RadioEntryData::new("isometric").label("Isometric").on_update(update_val(grid, |grid, _| {
if let GridType::Rectangular { spacing } = grid.grid_type {
grid.rectangular_spacing = spacing;
}
grid.grid_type = GridType::Isometric {
y_axis_spacing: grid.isometric_y_spacing,
angle_a: grid.isometric_angle_a,
angle_b: grid.isometric_angle_b,
};
})),
])
.min_width(200)
.selected_index(Some(match grid.grid_type {
GridType::Rectangular { .. } => 0,
GridType::Isometric { .. } => 1,
}))
.widget_instance(),
],
});
let mut color_widgets = vec![
TextLabel::new("Display").table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
];
color_widgets.extend([
CheckboxInput::new(grid.dot_display)
.icon("GridDotted")
.tooltip_label("Display as Dotted Grid")
.on_update(update_display(grid, |grid| Some(&mut grid.dot_display)))
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
]);
color_widgets.push(
ColorInput::new(FillChoice::Solid(grid.grid_color.to_gamma_srgb()))
.tooltip_label("Grid Display Color")
.allow_none(false)
.on_update(update_color(grid, |grid| Some(&mut grid.grid_color)))
.widget_instance(),
);
widgets.push(LayoutGroup::Row { widgets: color_widgets });
widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Origin").table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(grid.origin.x))
.label("X")
.unit(" px")
.min_width(98)
.on_update(update_origin(grid, |grid| Some(&mut grid.origin.x)))
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(grid.origin.y))
.label("Y")
.unit(" px")
.min_width(98)
.on_update(update_origin(grid, |grid| Some(&mut grid.origin.y)))
.widget_instance(),
],
});
match grid.grid_type {
GridType::Rectangular { spacing } => widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Spacing").table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(spacing.x))
.label("X")
.unit(" px")
.min(0.)
.min_width(98)
.on_update(update_origin(grid, |grid| grid.grid_type.rectangular_spacing().map(|spacing| &mut spacing.x)))
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(spacing.y))
.label("Y")
.unit(" px")
.min(0.)
.min_width(98)
.on_update(update_origin(grid, |grid| grid.grid_type.rectangular_spacing().map(|spacing| &mut spacing.y)))
.widget_instance(),
],
}),
GridType::Isometric { y_axis_spacing, angle_a, angle_b } => {
widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Y Spacing").table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(y_axis_spacing))
.unit(" px")
.min(0.)
.min_width(200)
.on_update(update_origin(grid, |grid| grid.grid_type.isometric_y_spacing()))
.widget_instance(),
],
});
widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Angles").table_align(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(angle_a))
.unit("Β°")
.min_width(98)
.on_update(update_origin(grid, |grid| grid.grid_type.angle_a()))
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(angle_b))
.unit("Β°")
.min_width(98)
.on_update(update_origin(grid, |grid| grid.grid_type.angle_b()))
.widget_instance(),
],
});
}
}
widgets
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/editor/src/messages/portfolio/document/overlays/mod.rs | editor/src/messages/portfolio/document/overlays/mod.rs | pub mod grid_overlays;
mod overlays_message;
mod overlays_message_handler;
pub mod utility_functions;
// Native (nonβwasm)
#[cfg(not(target_family = "wasm"))]
pub mod utility_types_native;
#[cfg(not(target_family = "wasm"))]
pub use utility_types_native as utility_types;
// WebAssembly
#[cfg(target_family = "wasm")]
pub mod utility_types_web;
#[cfg(target_family = "wasm")]
pub use utility_types_web as utility_types;
#[doc(inline)]
pub use overlays_message::{OverlaysMessage, OverlaysMessageDiscriminant};
#[doc(inline)]
pub use overlays_message_handler::{OverlaysMessageContext, OverlaysMessageHandler};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.