mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fd2f4075f | ||
|
|
9bb2bace2f | ||
|
|
af8ef1ce2c | ||
|
|
e3bd661f54 | ||
|
|
6e018d17d2 | ||
|
|
b5e603b784 | ||
|
|
7477cd2fab | ||
|
|
d9f045aaec | ||
|
|
c099b7e76b | ||
|
|
a024a8102f | ||
|
|
8f087a395b | ||
|
|
b345ca3fd2 | ||
|
|
baf2403d7e | ||
|
|
377ba8f00c |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
|
||||
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/ca7dd793caba8999ec33fde99bb721a69c3d221f.tar.gz
|
||||
77e8a6b68d67a8d5fcfd6268a6b7938ac9322d877378c6563e933a57df6da821
|
||||
+22
-2
@@ -61,7 +61,9 @@ in
|
||||
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
|
||||
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
|
||||
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-bundle-dev; };
|
||||
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) {
|
||||
graphite-bundle = graphite-bundle-dev;
|
||||
};
|
||||
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
|
||||
|
||||
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
|
||||
@@ -70,8 +72,26 @@ in
|
||||
|
||||
devShells = withArgs (
|
||||
{ lib, ... }:
|
||||
let
|
||||
shell = lib.makeOverridable (lib.call ./dev.nix);
|
||||
in
|
||||
{
|
||||
default = lib.call ./dev.nix;
|
||||
default = shell {
|
||||
desktop = true;
|
||||
};
|
||||
full = shell {
|
||||
desktop = true;
|
||||
x11 = true;
|
||||
playwright = true;
|
||||
};
|
||||
minimal = shell { };
|
||||
x11 = shell {
|
||||
desktop = true;
|
||||
x11 = true;
|
||||
};
|
||||
playwright = shell {
|
||||
playwright = true;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
+80
-52
@@ -3,62 +3,90 @@
|
||||
deps,
|
||||
self,
|
||||
system,
|
||||
lib,
|
||||
...
|
||||
}:
|
||||
|
||||
{
|
||||
desktop ? false,
|
||||
x11 ? false,
|
||||
playwright ? false,
|
||||
}:
|
||||
|
||||
let
|
||||
libs = [
|
||||
pkgs.wayland
|
||||
pkgs.vulkan-loader
|
||||
pkgs.libGL
|
||||
pkgs.openssl
|
||||
pkgs.libraw
|
||||
features = [
|
||||
{
|
||||
packages = [
|
||||
pkgs.pkg-config
|
||||
|
||||
# X11 Support
|
||||
pkgs.libxkbcommon
|
||||
pkgs.libXcursor
|
||||
pkgs.libxcb
|
||||
pkgs.libX11
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.cargo-about
|
||||
|
||||
pkgs.rustc
|
||||
pkgs.cargo
|
||||
pkgs.rust-analyzer
|
||||
pkgs.clippy
|
||||
pkgs.rustfmt
|
||||
|
||||
pkgs.git
|
||||
|
||||
pkgs.cargo-nextest
|
||||
pkgs.cargo-expand
|
||||
|
||||
# Linker
|
||||
pkgs.mold
|
||||
|
||||
# Profiling tools
|
||||
pkgs.gnuplot
|
||||
pkgs.samply
|
||||
pkgs.cargo-flamegraph
|
||||
|
||||
# Plotting tools
|
||||
pkgs.graphviz
|
||||
];
|
||||
}
|
||||
deps.rustGPU
|
||||
(lib.optionalAttrs desktop (
|
||||
{
|
||||
libs = [
|
||||
pkgs.wayland
|
||||
pkgs.vulkan-loader
|
||||
pkgs.libGL
|
||||
pkgs.libxkbcommon
|
||||
self.packages.${system}.graphite-cef
|
||||
];
|
||||
env = {
|
||||
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
||||
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
};
|
||||
}
|
||||
))
|
||||
(lib.optionalAttrs x11 {
|
||||
libs = [
|
||||
pkgs.libXcursor
|
||||
pkgs.libxcb
|
||||
pkgs.libX11
|
||||
];
|
||||
})
|
||||
(lib.optionalAttrs playwright (
|
||||
assert pkgs.playwright-driver.version == (lib.importJSON ../tools/web-editor-driver/playwright/package-lock.json).packages."node_modules/playwright-core".version;
|
||||
{
|
||||
env = {
|
||||
PLAYWRIGHT_BROWSERS_PATH = pkgs.playwright-driver.browsers-chromium;
|
||||
PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS = "true";
|
||||
};
|
||||
}
|
||||
))
|
||||
];
|
||||
|
||||
libs = lib.concatMap (feature: feature.libs or [ ]) features;
|
||||
in
|
||||
pkgs.mkShell (
|
||||
{
|
||||
packages = libs ++ [
|
||||
pkgs.pkg-config
|
||||
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.cargo-about
|
||||
|
||||
pkgs.rustc
|
||||
pkgs.cargo
|
||||
pkgs.rust-analyzer
|
||||
pkgs.clippy
|
||||
pkgs.rustfmt
|
||||
|
||||
pkgs.git
|
||||
|
||||
pkgs.cargo-nextest
|
||||
pkgs.cargo-expand
|
||||
|
||||
# Linker
|
||||
pkgs.mold
|
||||
|
||||
# Profiling tools
|
||||
pkgs.gnuplot
|
||||
pkgs.samply
|
||||
pkgs.cargo-flamegraph
|
||||
|
||||
# Plotting tools
|
||||
pkgs.graphviz
|
||||
];
|
||||
|
||||
CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
|
||||
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
|
||||
}
|
||||
// deps.rustGPU.env
|
||||
)
|
||||
pkgs.mkShell {
|
||||
packages = libs ++ lib.concatMap (feature: feature.packages or [ ]) features;
|
||||
env = lib.mergeAttrsList (map (feature: feature.env or { }) features) // {
|
||||
LD_LIBRARY_PATH = lib.makeLibraryPath libs;
|
||||
};
|
||||
}
|
||||
@@ -30,12 +30,13 @@ pkgs.cef-binary.overrideAttrs {
|
||||
postInstall = ''
|
||||
rm -r $out/* $out/.* || true
|
||||
strip ./Release/*.so*
|
||||
mv ./Release/* $out/
|
||||
mkdir $out/lib
|
||||
mv ./Release/* $out/lib/
|
||||
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
|
||||
mv ./Resources/* $out/
|
||||
mv ./include $out/
|
||||
mv ./Resources/* $out/lib/
|
||||
mv ./include $out/lib/
|
||||
|
||||
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
|
||||
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/lib/CREDITS.html.xz
|
||||
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
@@ -43,6 +44,6 @@ pkgs.cef-binary.overrideAttrs {
|
||||
name = builtins.baseNameOf url;
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/archive.json
|
||||
}' > $out/lib/archive.json
|
||||
'';
|
||||
}
|
||||
@@ -20,6 +20,7 @@ let
|
||||
pkgs.libGL
|
||||
pkgs.openssl
|
||||
pkgs.libraw
|
||||
self.packages.${system}.graphite-cef
|
||||
# X11 Support
|
||||
pkgs.libxkbcommon
|
||||
pkgs.libXcursor
|
||||
@@ -50,7 +51,7 @@ let
|
||||
pkgs.pkg-config
|
||||
pkgs.lld
|
||||
];
|
||||
env.CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
env.CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
||||
buildPhase =
|
||||
let
|
||||
profile = if dev then "dev" else "release";
|
||||
@@ -99,7 +100,7 @@ deps.crane.lib.buildPackage (
|
||||
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
|
||||
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
|
||||
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
|
||||
CEF_PATH = self.packages.${system}.graphite-cef;
|
||||
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
|
||||
};
|
||||
|
||||
postPatch = ''
|
||||
@@ -148,7 +149,7 @@ deps.crane.lib.buildPackage (
|
||||
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
|
||||
|
||||
patchelf \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
|
||||
--set-rpath "${pkgs.lib.makeLibraryPath libs}" \
|
||||
--add-needed libGL.so \
|
||||
--add-needed libEGL.so \
|
||||
$out/bin/graphite
|
||||
|
||||
@@ -134,6 +134,10 @@ pub(crate) mod menu {
|
||||
// Return None for shortcuts that include mouse motion because we can't show them in native menu
|
||||
return None;
|
||||
};
|
||||
// Native menu shortcuts allow only one non-modifier key, so a shortcut with more (like a double tap) would otherwise trigger on a single press of its last key
|
||||
if key.is_some() && !matches!(labeled_key.key(), Key::Shift | Key::Control | Key::Alt | Key::Meta | Key::Command | Key::Accel) {
|
||||
return None;
|
||||
}
|
||||
match labeled_key.key() {
|
||||
Key::Shift => modifiers |= Modifiers::SHIFT,
|
||||
Key::Control => modifiers |= Modifiers::CONTROL,
|
||||
|
||||
@@ -37,6 +37,10 @@ pub const VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR: f64 = 0.95;
|
||||
|
||||
pub const DRAG_BEYOND_VIEWPORT_MAX_OVEREXTENSION_PIXELS: f64 = 50.;
|
||||
pub const DRAG_BEYOND_VIEWPORT_SPEED_FACTOR: f64 = 20.;
|
||||
/// How long a dragged wire must stay beyond the node graph's edge before auto-panning begins, so passing over to another panel doesn't pan.
|
||||
pub const WIRE_DRAG_AUTO_PAN_DELAY_MILLISECONDS: u64 = 400;
|
||||
/// How long a dragged wire must rest over a node before the node reveals its hidden inputs the wire could connect to.
|
||||
pub const WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS: u64 = 250;
|
||||
|
||||
// SNAPPING POINT
|
||||
pub const SNAP_POINT_TOLERANCE: f64 = 5.;
|
||||
@@ -187,6 +191,8 @@ pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
||||
|
||||
// INPUT
|
||||
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
|
||||
/// Maximum duration of the whole double-tap gesture, measured from the first tap's key-down to the second tap's key-up.
|
||||
pub const DOUBLE_TAP_MILLISECONDS: u64 = 1000;
|
||||
|
||||
// UI
|
||||
pub const UI_SCALE_DEFAULT: f64 = 1.;
|
||||
|
||||
@@ -2,6 +2,7 @@ use crate::messages::debug::utility_types::MessageLoggingVerbosity;
|
||||
use crate::messages::defer::DeferMessageContext;
|
||||
use crate::messages::dialog::DialogMessageContext;
|
||||
use crate::messages::layout::layout_message_handler::LayoutMessageContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -64,6 +65,9 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::RunDocumentGraph,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateLayerPanel,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitActiveGraphRender),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
|
||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
|
||||
@@ -258,6 +262,7 @@ impl Dispatcher {
|
||||
ipp: &self.message_handlers.input_preprocessor_message_handler,
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
||||
tool_edit_target: &self.message_handlers.tool_message_handler.edit_target,
|
||||
reset_node_definitions_on_open: self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open,
|
||||
timing_information: self.message_handlers.animation_message_handler.timing_information(),
|
||||
animation: &self.message_handlers.animation_message_handler,
|
||||
@@ -284,26 +289,45 @@ impl Dispatcher {
|
||||
.active_document_id
|
||||
.and_then(|document_id| self.message_handlers.portfolio_message_handler.documents.get_mut(&document_id))
|
||||
{
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let metadata = &document.network_interface.document_network_metadata().persistent_metadata;
|
||||
let selected_nodes = document.network_interface.selected_nodes_in_nested_network(document.selection_network_path()).unwrap_or_default();
|
||||
let network_interface = &document.network_interface;
|
||||
let layer_metadata = document.metadata();
|
||||
let metadata = &network_interface.document_network_metadata().persistent_metadata;
|
||||
|
||||
// Layers only exist in the document network, so a selection inside a subgraph has none
|
||||
let in_document_network = document.selection_network_path().is_empty();
|
||||
|
||||
menu_bar_message_handler.has_active_document = true;
|
||||
menu_bar_message_handler.canvas_tilted = document.document_ptz.tilt() != 0.;
|
||||
menu_bar_message_handler.canvas_flipped = document.document_ptz.flip;
|
||||
menu_bar_message_handler.rulers_visible = document.rulers_visible;
|
||||
menu_bar_message_handler.node_graph_open = document.is_graph_overlay_open();
|
||||
menu_bar_message_handler.has_artboards = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(layer_metadata)
|
||||
.any(|layer| network_interface.is_artboard(&layer.to_node(), &[]));
|
||||
menu_bar_message_handler.has_selected_nodes = selected_nodes.selected_nodes().next().is_some();
|
||||
menu_bar_message_handler.has_selected_layers = selected_nodes.selected_visible_layers(&document.network_interface).next().is_some();
|
||||
menu_bar_message_handler.has_selected_layers = in_document_network && selected_nodes.selected_layers(layer_metadata).next().is_some();
|
||||
menu_bar_message_handler.has_selected_visible_layers = in_document_network && selected_nodes.selected_visible_layers(network_interface).next().is_some();
|
||||
menu_bar_message_handler.has_selected_visible_and_unlocked_layers =
|
||||
in_document_network && selected_nodes.selected_visible_and_unlocked_layers(network_interface).next().is_some();
|
||||
menu_bar_message_handler.has_selected_groups = in_document_network
|
||||
&& selected_nodes
|
||||
.selected_layers(layer_metadata)
|
||||
.any(|layer| layer.has_children(layer_metadata) && !network_interface.is_artboard(&layer.to_node(), &[]));
|
||||
menu_bar_message_handler.has_selection_history = (!metadata.selection_undo_history.is_empty(), !metadata.selection_redo_history.is_empty());
|
||||
menu_bar_message_handler.make_path_editable_is_allowed = make_path_editable_is_allowed(&mut document.network_interface).is_some();
|
||||
menu_bar_message_handler.make_path_editable_is_allowed = in_document_network && make_path_editable_is_allowed(&mut document.network_interface).is_some();
|
||||
} else {
|
||||
menu_bar_message_handler.has_active_document = false;
|
||||
menu_bar_message_handler.canvas_tilted = false;
|
||||
menu_bar_message_handler.canvas_flipped = false;
|
||||
menu_bar_message_handler.rulers_visible = false;
|
||||
menu_bar_message_handler.node_graph_open = false;
|
||||
menu_bar_message_handler.has_artboards = false;
|
||||
menu_bar_message_handler.has_selected_nodes = false;
|
||||
menu_bar_message_handler.has_selected_layers = false;
|
||||
menu_bar_message_handler.has_selected_visible_layers = false;
|
||||
menu_bar_message_handler.has_selected_visible_and_unlocked_layers = false;
|
||||
menu_bar_message_handler.has_selected_groups = false;
|
||||
menu_bar_message_handler.has_selection_history = (false, false);
|
||||
menu_bar_message_handler.make_path_editable_is_allowed = false;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw, ClipboardItem, ClipboardLayer, ClipboardResource, ResourceData};
|
||||
use crate::messages::portfolio::document::SelectionParts;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -79,23 +80,18 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}
|
||||
|
||||
ClipboardMessage::CopyLayers => {
|
||||
if current_tool == &ToolType::Path {
|
||||
let Some(active_document) = portfolio.active_document() else { return };
|
||||
|
||||
// The Path tool copies the points it's editing in the viewport
|
||||
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
|
||||
responses.add(PathToolMessage::Copy);
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(active_document) = portfolio.active_document_id.and_then(|id| portfolio.documents.get_mut(&id)) else {
|
||||
return;
|
||||
};
|
||||
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
|
||||
let mut items = Vec::new();
|
||||
|
||||
if active_document.graph_view_overlay_open() {
|
||||
responses.add(NodeGraphMessage::Copy);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
|
||||
let mut ordered_last_elements = active_document.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
|
||||
let mut ordered_last_elements = layers;
|
||||
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)
|
||||
@@ -123,38 +119,69 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
.collect::<Vec<_>>();
|
||||
tree_path.reverse();
|
||||
|
||||
buffer.push(ClipboardLayer {
|
||||
items.push(ClipboardItem::Layer(ClipboardLayer {
|
||||
nodes: active_document.network_interface.copy_nodes(©_ids, &[]).collect(),
|
||||
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: active_document.collapsed.0.contains(&tree_path),
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
responses.add(ClipboardMessage::WriteItems {
|
||||
items: buffer.into_iter().map(ClipboardItem::Layer).collect(),
|
||||
});
|
||||
let copies = chain_nodes
|
||||
.iter()
|
||||
.filter_map(|node_id| active_document.network_interface.copy_chain_node(node_id, &[]))
|
||||
.collect::<Vec<_>>();
|
||||
if !copies.is_empty() {
|
||||
items.push(ClipboardItem::ChainNodes(copies));
|
||||
}
|
||||
|
||||
// Other nodes are kept under their own IDs, so a paste can tell when it's over the same nodes
|
||||
if !other_nodes.is_empty() {
|
||||
let copy_ids = active_document.with_layer_content(&other_nodes).into_iter().map(|node_id| (node_id, node_id)).collect();
|
||||
let nodes = active_document.network_interface.copy_nodes(©_ids, active_document.selection_network_path()).collect();
|
||||
items.push(ClipboardItem::Nodes(nodes));
|
||||
}
|
||||
|
||||
responses.add(ClipboardMessage::WriteItems { items });
|
||||
}
|
||||
ClipboardMessage::CutLayers => {
|
||||
if current_tool == &ToolType::Path {
|
||||
let Some(active_document) = portfolio.active_document() else { return };
|
||||
|
||||
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
|
||||
responses.add(PathToolMessage::Cut);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(active_document) = portfolio.active_document()
|
||||
&& active_document.graph_view_overlay_open()
|
||||
{
|
||||
responses.add(NodeGraphMessage::Cut);
|
||||
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
|
||||
responses.add(ClipboardMessage::CopyLayers);
|
||||
|
||||
// Layers and other nodes go along with what only they use, while chain nodes go alone so pasting them can wire back to what fed them
|
||||
let deleted_with_children = layers.iter().map(|layer| layer.to_node()).chain(other_nodes).collect::<Vec<_>>();
|
||||
if deleted_with_children.is_empty() && chain_nodes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(ClipboardMessage::CopyLayers);
|
||||
responses.add(DocumentMessage::DeleteSelectedLayers);
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
if !deleted_with_children.is_empty() {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: deleted_with_children,
|
||||
delete_children: true,
|
||||
});
|
||||
}
|
||||
if !chain_nodes.is_empty() {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: chain_nodes,
|
||||
delete_children: false,
|
||||
});
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
ClipboardMessage::WriteItems { items } => {
|
||||
let has_content = items.iter().any(|item| match item {
|
||||
ClipboardItem::Layer(entry) => !entry.nodes.is_empty(),
|
||||
ClipboardItem::Nodes(nodes) => !nodes.is_empty(),
|
||||
ClipboardItem::ChainNodes(copies) => !copies.is_empty(),
|
||||
ClipboardItem::Vector(vector) => !vector.is_empty(),
|
||||
ClipboardItem::Resource(_) => true,
|
||||
});
|
||||
@@ -167,6 +194,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
match item {
|
||||
ClipboardItem::Layer(entry) => entry.nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
|
||||
ClipboardItem::Nodes(nodes) => nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
|
||||
ClipboardItem::ChainNodes(copies) => copies.iter().for_each(|copy| network_interface::collect_template_resources(©.template, &mut resource_ids)),
|
||||
ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {}
|
||||
}
|
||||
}
|
||||
@@ -227,6 +255,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
|
||||
let mut layers = Vec::new();
|
||||
let mut node_groups = Vec::new();
|
||||
let mut chain_node_groups = Vec::new();
|
||||
let mut vectors = Vec::new();
|
||||
let mut resources = Vec::new();
|
||||
for item in items {
|
||||
@@ -244,6 +273,12 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}
|
||||
node_groups.push(nodes);
|
||||
}
|
||||
ClipboardItem::ChainNodes(mut copies) => {
|
||||
for copy in &mut copies {
|
||||
copy.template.normalize_stored_types();
|
||||
}
|
||||
chain_node_groups.push(copies);
|
||||
}
|
||||
ClipboardItem::Vector(vector) => vectors.push(vector),
|
||||
ClipboardItem::Resource(resource) => resources.push(resource),
|
||||
}
|
||||
@@ -279,7 +314,10 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
responses.add(ClipboardMessage::PasteLayers { entries: layers });
|
||||
}
|
||||
for nodes in node_groups {
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
responses.add(DocumentMessage::PasteNodes { nodes });
|
||||
}
|
||||
for copies in chain_node_groups {
|
||||
responses.add(DocumentMessage::PasteChainNodes { copies });
|
||||
}
|
||||
for paths in vectors {
|
||||
responses.add(ClipboardMessage::PasteVectors { paths });
|
||||
@@ -302,7 +340,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
.collect::<Vec<_>>();
|
||||
parent_tree_path.reverse();
|
||||
|
||||
let mut all_new_ids = Vec::new();
|
||||
let mut layers = Vec::new();
|
||||
|
||||
let mut added_nodes = false;
|
||||
@@ -321,8 +358,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
added_nodes = true;
|
||||
}
|
||||
|
||||
all_new_ids.extend(new_ids.values().copied());
|
||||
|
||||
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
|
||||
|
||||
@@ -351,22 +386,24 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: layers.iter().map(|layer| layer.to_node()).collect(),
|
||||
});
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
ClipboardMessage::PasteVectors { paths } => {
|
||||
// If using Path tool then send the operation to Path tool
|
||||
// The Path tool pastes points into the path it's editing in the viewport
|
||||
// TODO: Consider if this is actually the correct place to put this logic
|
||||
// TODO: Consider making paste in general go through the current tool, so that the tool can decide what to do
|
||||
if *current_tool == ToolType::Path {
|
||||
if *current_tool == ToolType::Path && portfolio.active_document().is_some_and(|document| !document.graph_view_overlay_open()) {
|
||||
responses.add(PathToolMessage::Paste { paths });
|
||||
return;
|
||||
}
|
||||
|
||||
// If not using Path tool, create new layers and add paths into those
|
||||
// Otherwise, create new layers and add paths into those
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
let mut layers = Vec::new();
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use glam::DAffine2;
|
||||
@@ -27,6 +27,8 @@ pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2);
|
||||
pub enum ClipboardItem {
|
||||
Layer(ClipboardLayer),
|
||||
Nodes(Vec<(NodeId, NodeTemplate)>),
|
||||
/// Nodes copied from layers' chains, ordered by their layer's place in the Layers panel, then from the layer outward.
|
||||
ChainNodes(Vec<ChainNodeCopy>),
|
||||
Vector(Vec<ClipboardVectorEntry>),
|
||||
Resource(ClipboardResource),
|
||||
}
|
||||
|
||||
@@ -107,7 +107,11 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
self.gradient_cyclic = ramp.gradient_cyclic;
|
||||
self.gradient_hue_direction = ramp.gradient_hue_direction;
|
||||
self.gradient_interpolation = ramp.gradient_interpolation;
|
||||
let gradient = Gradient::from(ramp);
|
||||
let mut gradient = Gradient::from(ramp);
|
||||
// An empty gradient renders solid black, so it's edited as black to black, which looks the same but has stops to edit
|
||||
if gradient.is_empty() {
|
||||
gradient = Gradient::from(vec![Color::BLACK, Color::BLACK]);
|
||||
}
|
||||
let first_color = gradient.color(0).unwrap_or(Color::BLACK);
|
||||
self.gradient = Some(gradient);
|
||||
self.adopt_color(first_color);
|
||||
|
||||
+2
-18
@@ -1,6 +1,6 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
@@ -26,23 +26,7 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
|
||||
if self.infinite {
|
||||
// Infinite canvas: add a locked white background layer
|
||||
let node_id = NodeId::new();
|
||||
responses.add(GraphOperationMessage::NewColorFillLayer {
|
||||
node_id,
|
||||
color: Color::WHITE,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index: 0,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Background".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
locked: true,
|
||||
});
|
||||
graph_modification_utils::new_background_layer(0, responses);
|
||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
|
||||
@@ -68,6 +68,8 @@ pub enum FrontendMessage {
|
||||
SendUIMetadata {
|
||||
#[serde(rename = "nodeDescriptions")]
|
||||
node_descriptions: Vec<(String, String)>,
|
||||
#[serde(rename = "nodeIcons")]
|
||||
node_icons: Vec<(String, IconName)>,
|
||||
#[serde(rename = "nodeTypes")]
|
||||
node_types: Vec<FrontendNodeType>,
|
||||
},
|
||||
|
||||
@@ -16,6 +16,8 @@ pub enum InputMapperMessage {
|
||||
KeyUpNoRepeat(Key),
|
||||
#[child]
|
||||
DoubleClick(MouseButton),
|
||||
#[child]
|
||||
DoubleTap(Key),
|
||||
|
||||
// Messages
|
||||
PointerMove,
|
||||
|
||||
@@ -40,6 +40,7 @@ impl InputMapperMessageHandler {
|
||||
.chain(self.mapping.key_up_no_repeat.iter())
|
||||
.chain(self.mapping.key_down_no_repeat.iter())
|
||||
.chain(self.mapping.double_click.iter())
|
||||
.chain(self.mapping.double_tap.iter())
|
||||
.chain(std::iter::once(&self.mapping.wheel_scroll))
|
||||
.chain(std::iter::once(&self.mapping.pointer_move));
|
||||
let all_mapping_entries = all_key_mapping_entries.flat_map(|entry| entry.0.iter());
|
||||
@@ -69,6 +70,7 @@ impl InputMapperMessageHandler {
|
||||
use InputMapperMessage as IMM;
|
||||
match entry.input {
|
||||
IMM::KeyDown(key) | IMM::KeyUp(key) | IMM::KeyDownNoRepeat(key) | IMM::KeyUpNoRepeat(key) => keys.push(key),
|
||||
IMM::DoubleTap(key) => keys.extend([key, key]),
|
||||
_ => (),
|
||||
}
|
||||
|
||||
|
||||
@@ -337,7 +337,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Tab); action_dispatch=ToolMessage::ToggleSelectVsPath),
|
||||
//
|
||||
// DocumentMessage
|
||||
entry!(KeyDown(Space); modifiers=[Control], action_dispatch=DocumentMessage::GraphViewOverlayToggle),
|
||||
entry!(DoubleTap(Space); action_dispatch=DocumentMessage::GraphViewOverlayToggle),
|
||||
entry!(KeyDownNoRepeat(Escape); action_dispatch=DocumentMessage::Escape),
|
||||
entry!(KeyDown(Delete); action_dispatch=DocumentMessage::DeleteSelectedLayers),
|
||||
entry!(KeyDown(Backspace); action_dispatch=DocumentMessage::DeleteSelectedLayers),
|
||||
@@ -354,8 +354,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(KeyA); modifiers=[Alt], action_dispatch=DocumentMessage::DeselectAllLayers),
|
||||
entry!(KeyDown(KeyS); modifiers=[Accel], action_dispatch=DocumentMessage::SaveDocument),
|
||||
entry!(KeyDown(KeyS); modifiers=[Accel, Shift], action_dispatch=DocumentMessage::SaveDocumentAs),
|
||||
entry!(KeyDown(KeyD); modifiers=[Accel], canonical, action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyJ); modifiers=[Accel], action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyD); modifiers=[Accel], action_dispatch=DocumentMessage::DuplicateSelectedLayers),
|
||||
entry!(KeyDown(KeyB); modifiers=[Accel, Alt], action_dispatch=DocumentMessage::BlendSelectedLayers),
|
||||
entry!(KeyDown(KeyM); modifiers=[Accel, Alt], action_dispatch=DocumentMessage::MorphSelectedLayers), // Might get eaten by the GeForce Experience overlay for some Windows users
|
||||
entry!(KeyDown(KeyG); modifiers=[Accel], action_dispatch=DocumentMessage::GroupSelectedLayers { group_folder_type: GroupFolderType::Layer }),
|
||||
@@ -416,23 +415,32 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
// NavigationMessage
|
||||
entry!(KeyDown(MouseMiddle); modifiers=[Alt], action_dispatch=NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: false }),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Alt, Space], action_dispatch=NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: false }),
|
||||
entry!(KeyDown(MouseMiddle); modifiers=[Control], action_dispatch=NavigationMessage::BeginCanvasZoom),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Control, Space], action_dispatch=NavigationMessage::BeginCanvasZoom),
|
||||
entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::BeginCanvasPan),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Space], action_dispatch=NavigationMessage::BeginCanvasPan),
|
||||
entry!(KeyDown(MouseMiddle); modifiers=[Control, Alt], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: true }),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Control, Alt, Space], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: true }),
|
||||
entry!(KeyDown(MouseMiddle); modifiers=[Control], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Control, Space], action_dispatch=NavigationMessage::BeginCanvasZoom { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::BeginCanvasPan { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Space], action_dispatch=NavigationMessage::BeginCanvasPan { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(NumpadAdd); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
||||
// `FakeKeyPlus` is a nonfunctional key mapping that must be accompanied by its real `Equal` key counterpart. This is used only to set the canonical key label so it shows "+" instead of "=" in the UI.
|
||||
entry!(KeyDown(FakeKeyPlus); modifiers=[Accel], canonical, action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
||||
entry!(KeyDown(Equal); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
||||
entry!(KeyDown(Minus); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomDecrease { center_on_mouse: false }),
|
||||
entry!(WheelScroll; modifiers=[Control], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||
entry!(WheelScroll; modifiers=[Command], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||
entry!(WheelScroll; modifiers=[Shift], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true }),
|
||||
entry!(WheelScroll; disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false }),
|
||||
entry!(WheelScroll; modifiers=[Control, Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Command, Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Control], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; modifiers=[Command], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; modifiers=[Shift, Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true, artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Alt], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false, artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Shift], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true, artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false, artwork_behind_graph: false }),
|
||||
// On Mac, the OS already converts Shift+scroll into horizontal scrolling so we have to reverse the behavior from normal to produce the same outcome
|
||||
entry!(WheelScroll; modifiers=[Control], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac }),
|
||||
entry!(WheelScroll; modifiers=[Shift], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac }),
|
||||
entry!(WheelScroll; disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||
entry!(WheelScroll; modifiers=[Control, Alt], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac, artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Shift, Alt], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac, artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Alt], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: true }),
|
||||
entry!(WheelScroll; modifiers=[Control], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac, artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; modifiers=[Shift], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac, artwork_behind_graph: false }),
|
||||
entry!(WheelScroll; disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph: false }),
|
||||
entry!(KeyDown(PageUp); modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(1., 0.) }),
|
||||
entry!(KeyDown(PageDown); modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(-1., 0.) }),
|
||||
entry!(KeyDown(PageUp); action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(0., 1.) }),
|
||||
@@ -463,7 +471,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Space); modifiers=[Shift], action_dispatch=AnimationMessage::ToggleLivePreview),
|
||||
entry!(KeyDown(Home); modifiers=[Shift], action_dispatch=AnimationMessage::RestartAnimation),
|
||||
];
|
||||
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
|
||||
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut double_tap, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
|
||||
|
||||
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
|
||||
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
|
||||
@@ -476,6 +484,10 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
for sublist in &mut double_click {
|
||||
sort(sublist)
|
||||
}
|
||||
// Sort the sublists of `double_tap`
|
||||
for sublist in &mut double_tap {
|
||||
sort(sublist)
|
||||
}
|
||||
// Sort `wheel_scroll`
|
||||
sort(&mut wheel_scroll);
|
||||
// Sort `pointer_move`
|
||||
@@ -489,6 +501,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
key_up_no_repeat,
|
||||
key_down_no_repeat,
|
||||
double_click,
|
||||
double_tap,
|
||||
wheel_scroll,
|
||||
pointer_move,
|
||||
pointer_shake,
|
||||
|
||||
@@ -119,6 +119,7 @@ macro_rules! mapping {
|
||||
let mut key_up_no_repeat = KeyMappingEntries::key_array();
|
||||
let mut key_down_no_repeat = KeyMappingEntries::key_array();
|
||||
let mut double_click = KeyMappingEntries::mouse_buttons_arrays();
|
||||
let mut double_tap = KeyMappingEntries::key_array();
|
||||
let mut wheel_scroll = KeyMappingEntries::new();
|
||||
let mut pointer_move = KeyMappingEntries::new();
|
||||
let mut pointer_shake = KeyMappingEntries::new();
|
||||
@@ -138,6 +139,7 @@ macro_rules! mapping {
|
||||
InputMapperMessage::KeyDownNoRepeat(key) => &mut key_down_no_repeat[key as usize],
|
||||
InputMapperMessage::KeyUpNoRepeat(key) => &mut key_up_no_repeat[key as usize],
|
||||
InputMapperMessage::DoubleClick(key) => &mut double_click[key as usize],
|
||||
InputMapperMessage::DoubleTap(key) => &mut double_tap[key as usize],
|
||||
InputMapperMessage::WheelScroll => &mut wheel_scroll,
|
||||
InputMapperMessage::PointerMove => &mut pointer_move,
|
||||
InputMapperMessage::PointerShake => &mut pointer_shake,
|
||||
@@ -148,7 +150,7 @@ macro_rules! mapping {
|
||||
}
|
||||
)*
|
||||
|
||||
(key_up, key_down, key_up_no_repeat, key_down_no_repeat, double_click, wheel_scroll, pointer_move, pointer_shake)
|
||||
(key_up, key_down, key_up_no_repeat, key_down_no_repeat, double_click, double_tap, wheel_scroll, pointer_move, pointer_shake)
|
||||
}};
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ pub struct Mapping {
|
||||
pub key_up_no_repeat: [KeyMappingEntries; NUMBER_OF_KEYS],
|
||||
pub key_down_no_repeat: [KeyMappingEntries; NUMBER_OF_KEYS],
|
||||
pub double_click: [KeyMappingEntries; NUMBER_OF_MOUSE_BUTTONS],
|
||||
pub double_tap: [KeyMappingEntries; NUMBER_OF_KEYS],
|
||||
pub wheel_scroll: KeyMappingEntries,
|
||||
pub pointer_move: KeyMappingEntries,
|
||||
pub pointer_shake: KeyMappingEntries,
|
||||
@@ -36,6 +37,7 @@ impl Mapping {
|
||||
InputMapperMessage::KeyDownNoRepeat(key) => &self.key_down_no_repeat[*key as usize],
|
||||
InputMapperMessage::KeyUpNoRepeat(key) => &self.key_up_no_repeat[*key as usize],
|
||||
InputMapperMessage::DoubleClick(key) => &self.double_click[*key as usize],
|
||||
InputMapperMessage::DoubleTap(key) => &self.double_tap[*key as usize],
|
||||
InputMapperMessage::WheelScroll => &self.wheel_scroll,
|
||||
InputMapperMessage::PointerMove => &self.pointer_move,
|
||||
InputMapperMessage::PointerShake => &self.pointer_shake,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::application::Editor;
|
||||
use crate::consts::DOUBLE_TAP_MILLISECONDS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{MouseButton, MouseKeys, PointerState};
|
||||
@@ -17,6 +18,18 @@ pub struct InputPreprocessorMessageHandler {
|
||||
pub keyboard: KeyStates,
|
||||
pub mouse: PointerState,
|
||||
pointer_down_time: f64,
|
||||
/// Double-tap detection state, timed as one gesture from the first tap's key-down.
|
||||
double_tap_state: DoubleTapState,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
enum DoubleTapState {
|
||||
#[default]
|
||||
Idle,
|
||||
/// The first press of the key, timed from its key-down.
|
||||
FirstTap { key: Key, start_time: u64 },
|
||||
/// The second press of the key is down, still timed from the first tap's key-down.
|
||||
SecondTap { key: Key, start_time: u64 },
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -26,6 +39,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
|
||||
match message {
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
@@ -45,7 +59,22 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.keyboard.set(key as usize);
|
||||
|
||||
if !key_repeat {
|
||||
// A press that arrives with a mouse button or modifier held can neither open nor close a double tap,
|
||||
// and it breaks a first tap already waiting
|
||||
let interrupted = !self.mouse.mouse_keys.is_empty() || !modifier_keys.is_empty();
|
||||
|
||||
self.double_tap_state = match (interrupted, self.double_tap_state) {
|
||||
(true, _) => DoubleTapState::Idle,
|
||||
(false, DoubleTapState::FirstTap { key: first_key, start_time }) if first_key == key && self.time.saturating_sub(start_time) < DOUBLE_TAP_MILLISECONDS => {
|
||||
DoubleTapState::SecondTap { key, start_time }
|
||||
}
|
||||
// A late second press starts a new first tap instead of carrying a pair that can't succeed,
|
||||
// so a slow tap followed by a quick double tap still works
|
||||
(false, _) => DoubleTapState::FirstTap { key, start_time: self.time },
|
||||
};
|
||||
|
||||
responses.add(InputMapperMessage::KeyDownNoRepeat(key));
|
||||
}
|
||||
responses.add(InputMapperMessage::KeyDown(key));
|
||||
@@ -56,9 +85,22 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
if !key_repeat {
|
||||
responses.add(InputMapperMessage::KeyUpNoRepeat(key));
|
||||
}
|
||||
if let DoubleTapState::SecondTap { key: tapped_key, start_time } = self.double_tap_state
|
||||
&& tapped_key == key
|
||||
&& self.mouse.mouse_keys.is_empty()
|
||||
{
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
|
||||
// `self.time` only advances on animation-frame ticks, so while the editor is stalled both taps can
|
||||
// share a stale timestamp. That makes a double tap easier to trigger, not harder, so no correction is applied.
|
||||
if self.time.saturating_sub(start_time) < DOUBLE_TAP_MILLISECONDS {
|
||||
responses.add(InputMapperMessage::DoubleTap(key));
|
||||
}
|
||||
}
|
||||
responses.add(InputMapperMessage::KeyUp(key));
|
||||
}
|
||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
@@ -78,6 +120,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
self.translate_mouse_event(pointer_state, false, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
@@ -99,6 +142,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
self.frame_time.advance_timestamp(Duration::from_millis(timestamp));
|
||||
}
|
||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
@@ -193,8 +237,10 @@ impl InputPreprocessorMessageHandler {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::DoubleTapState;
|
||||
use crate::consts::DOUBLE_TAP_MILLISECONDS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys};
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[test]
|
||||
@@ -299,4 +345,310 @@ mod test {
|
||||
assert!(responses.contains(&InputMapperMessage::KeyDown(Key::Control).into()));
|
||||
assert!(responses.contains(&InputMapperMessage::KeyDown(Key::Control).into()));
|
||||
}
|
||||
|
||||
fn key_down(input_preprocessor: &mut InputPreprocessorMessageHandler, key: Key, responses: &mut VecDeque<Message>) {
|
||||
process_input(
|
||||
input_preprocessor,
|
||||
InputPreprocessorMessage::KeyDown {
|
||||
key,
|
||||
key_repeat: false,
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
responses,
|
||||
);
|
||||
}
|
||||
|
||||
fn key_up(input_preprocessor: &mut InputPreprocessorMessageHandler, key: Key, responses: &mut VecDeque<Message>) {
|
||||
process_input(
|
||||
input_preprocessor,
|
||||
InputPreprocessorMessage::KeyUp {
|
||||
key,
|
||||
key_repeat: false,
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
responses,
|
||||
);
|
||||
}
|
||||
|
||||
fn tap(input_preprocessor: &mut InputPreprocessorMessageHandler, key: Key, time: u64, responses: &mut VecDeque<Message>) {
|
||||
input_preprocessor.time = time;
|
||||
key_down(input_preprocessor, key, responses);
|
||||
key_up(input_preprocessor, key, responses);
|
||||
}
|
||||
|
||||
fn process_input(input_preprocessor: &mut InputPreprocessorMessageHandler, message: InputPreprocessorMessage, responses: &mut VecDeque<Message>) {
|
||||
input_preprocessor.process_message(
|
||||
message,
|
||||
responses,
|
||||
InputPreprocessorMessageContext {
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_within_threshold() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
// The stored time stays at the first tap's key-down, since the whole gesture is timed from there
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::SecondTap { key: Key::Space, start_time: 0 });
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::Idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_outside_threshold() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// A second press that already arrives too late starts a new first tap instead of completing the pair
|
||||
input_preprocessor.time = DOUBLE_TAP_MILLISECONDS + 1;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
assert_eq!(
|
||||
input_preprocessor.double_tap_state,
|
||||
DoubleTapState::FirstTap {
|
||||
key: Key::Space,
|
||||
start_time: DOUBLE_TAP_MILLISECONDS + 1
|
||||
}
|
||||
);
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_exceeding_total_duration_fails() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// The second press alone is short, but the whole gesture from the first key-down to the second key-up exceeds the limit
|
||||
input_preprocessor.time = DOUBLE_TAP_MILLISECONDS;
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_slow_tap_then_quick_double_tap_still_works() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// Too slow to pair with the first tap, so this becomes a new first tap of its own
|
||||
tap(&mut input_preprocessor, Key::Space, DOUBLE_TAP_MILLISECONDS + 1, &mut responses);
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
responses.clear();
|
||||
|
||||
// A quick pair after that still registers
|
||||
tap(&mut input_preprocessor, Key::Space, DOUBLE_TAP_MILLISECONDS + 51, &mut responses);
|
||||
assert!(responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_interrupted_by_pointer_down() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::PointerDown {
|
||||
editor_mouse_state: EditorPointerState::default(),
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
responses.clear();
|
||||
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_not_interrupted_by_mouse_movement() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::PointerMove {
|
||||
editor_mouse_state: EditorPointerState::default(),
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
responses.clear();
|
||||
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_blocked_by_mouse_button_held() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
input_preprocessor.mouse.mouse_keys = MouseKeys::LEFT;
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 50;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::Idle);
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_modified_first_press_never_arms() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
// Press Shift+Space first, as for live preview, then a plain Space within the threshold
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::KeyDown {
|
||||
key: Key::Space,
|
||||
key_repeat: false,
|
||||
modifier_keys: ModifierKeys::SHIFT,
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
assert_eq!(
|
||||
input_preprocessor.double_tap_state,
|
||||
DoubleTapState::Idle,
|
||||
"A modified first press should leave no double-tap state at all"
|
||||
);
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 50, &mut responses);
|
||||
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_reset_by_a_different_key() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// A different key between the taps makes the next Space press start a fresh pair
|
||||
tap(&mut input_preprocessor, Key::KeyA, 50, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
input_preprocessor.time = 100;
|
||||
key_down(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
assert_eq!(
|
||||
input_preprocessor.double_tap_state,
|
||||
DoubleTapState::FirstTap { key: Key::Space, start_time: 100 },
|
||||
"The intervening key should have reset the detector"
|
||||
);
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_blocked_by_a_modifier_key() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// Shift+Space is its own shortcut, so a modifier held on the second tap suppresses the double tap
|
||||
input_preprocessor.time = 50;
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::KeyDown {
|
||||
key: Key::Space,
|
||||
key_repeat: false,
|
||||
modifier_keys: ModifierKeys::SHIFT,
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::Idle);
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_double_tap_ignores_key_repeat() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
tap(&mut input_preprocessor, Key::Space, 0, &mut responses);
|
||||
responses.clear();
|
||||
|
||||
// A held key's auto-repeat must not read as a second tap
|
||||
input_preprocessor.time = 50;
|
||||
process_input(
|
||||
&mut input_preprocessor,
|
||||
InputPreprocessorMessage::KeyDown {
|
||||
key: Key::Space,
|
||||
key_repeat: true,
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
},
|
||||
&mut responses,
|
||||
);
|
||||
|
||||
assert_eq!(input_preprocessor.double_tap_state, DoubleTapState::FirstTap { key: Key::Space, start_time: 0 });
|
||||
|
||||
responses.clear();
|
||||
key_up(&mut input_preprocessor, Key::Space, &mut responses);
|
||||
assert!(!responses.contains(&InputMapperMessage::DoubleTap(Key::Space).into()));
|
||||
}
|
||||
}
|
||||
@@ -438,31 +438,7 @@ impl LayoutMessageHandler {
|
||||
Widget::ParameterExposeButton(parameter_expose_button) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (parameter_expose_button.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Some(value_path) = value.as_array() else {
|
||||
error!("ParameterExposeButton update was not of type: array");
|
||||
return;
|
||||
};
|
||||
|
||||
// Process the bare button click, since no menu is involved if we're given an empty array.
|
||||
if value_path.is_empty() {
|
||||
(parameter_expose_button.on_update.callback)(parameter_expose_button)
|
||||
}
|
||||
// Process the menu list entry click, since we have a path to the value of the contained menu entry.
|
||||
else {
|
||||
let mut current_submenu = ¶meter_expose_button.menu_list_children;
|
||||
let mut final_entry: Option<&MenuListEntry> = None;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
(final_entry.unwrap().on_commit.callback)(&())
|
||||
}
|
||||
}
|
||||
WidgetValueAction::Update => (parameter_expose_button.on_update.callback)(parameter_expose_button),
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
|
||||
@@ -2,7 +2,9 @@ use super::widgets::button_widgets::*;
|
||||
use super::widgets::input_widgets::*;
|
||||
use super::widgets::label_widgets::*;
|
||||
use crate::application::generate_uuid;
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
@@ -58,12 +60,12 @@ define_layout_target!(
|
||||
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,
|
||||
/// Visibility and lock toggles for the selection at the bottom left of the Layers panel.
|
||||
LayersPanelBottomLeftBar,
|
||||
/// Controls for adding, grouping, and deleting layers at the bottom right of the Layers panel.
|
||||
LayersPanelBottomRightBar,
|
||||
/// 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.
|
||||
@@ -388,12 +390,25 @@ pub struct WidgetTable {
|
||||
pub unstyled: bool,
|
||||
}
|
||||
|
||||
/// A wire drawn between Properties panel sections, styled like the graph's wire carrying the same data.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SectionWire {
|
||||
#[serde(rename = "dataType")]
|
||||
pub data_type: FrontendGraphDataType,
|
||||
/// Whether the wire carries a list, drawn as two parallel lines.
|
||||
#[serde(rename = "isList")]
|
||||
pub is_list: bool,
|
||||
}
|
||||
|
||||
/// A collapsible Properties panel section for a single node: a header with its name and pin, delete, and visibility controls, above its input parameter widgets.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct WidgetSection {
|
||||
/// The node's name shown in the section header: its given alias with the implementation name in parentheses, or just the implementation name.
|
||||
pub name: String,
|
||||
/// The node definition's icon, shown before the name in the section header (none when it has no icon).
|
||||
pub icon: Option<IconName>,
|
||||
/// The node definition's description, shown as the header's tooltip (empty when it has none).
|
||||
pub description: String,
|
||||
/// Whether the node is visible rather than hidden (shown as the eye icon).
|
||||
@@ -402,6 +417,12 @@ pub struct WidgetSection {
|
||||
pub pinned: bool,
|
||||
/// Whether this section can be dragged to reorder it within its layer's chain of nodes (true for a layer chain's nodes, but not its terminal layer node).
|
||||
pub draggable: bool,
|
||||
/// For a selected layer's own section, the wire drawn up into its chain input from its chain's sections below (none when it has no chain).
|
||||
#[serde(rename = "chainWire")]
|
||||
pub chain_wire: Option<SectionWire>,
|
||||
/// For a section in a selected layer's chain, the wire drawn up to the section above, which its node's output feeds.
|
||||
#[serde(rename = "outputWire")]
|
||||
pub output_wire: Option<SectionWire>,
|
||||
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
|
||||
pub expanded: bool,
|
||||
/// The ID of the node whose properties this section displays.
|
||||
@@ -441,13 +462,17 @@ impl LayoutGroup {
|
||||
Self::Table(WidgetTable { rows, unstyled })
|
||||
}
|
||||
|
||||
pub fn section(name: impl Into<String>, description: impl Into<String>, visible: bool, pinned: bool, expanded: bool, id: u64, layout: Layout) -> Self {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn section(name: impl Into<String>, icon: Option<IconName>, description: impl Into<String>, visible: bool, pinned: bool, expanded: bool, id: u64, layout: Layout) -> Self {
|
||||
Self::Section(WidgetSection {
|
||||
name: name.into(),
|
||||
icon,
|
||||
description: description.into(),
|
||||
visible,
|
||||
pinned,
|
||||
draggable: false,
|
||||
chain_wire: None,
|
||||
output_wire: None,
|
||||
expanded,
|
||||
id,
|
||||
layout,
|
||||
@@ -544,20 +569,26 @@ impl Diffable for LayoutGroup {
|
||||
(
|
||||
Self::Section(WidgetSection {
|
||||
name: current_name,
|
||||
icon: current_icon,
|
||||
description: current_description,
|
||||
visible: current_visible,
|
||||
pinned: current_pinned,
|
||||
draggable: current_draggable,
|
||||
chain_wire: current_chain_wire,
|
||||
output_wire: current_output_wire,
|
||||
expanded: current_expanded,
|
||||
id: current_id,
|
||||
layout: current_layout,
|
||||
}),
|
||||
Self::Section(WidgetSection {
|
||||
name: new_name,
|
||||
icon: new_icon,
|
||||
description: new_description,
|
||||
visible: new_visible,
|
||||
pinned: new_pinned,
|
||||
draggable: new_draggable,
|
||||
chain_wire: new_chain_wire,
|
||||
output_wire: new_output_wire,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -567,19 +598,25 @@ impl Diffable for LayoutGroup {
|
||||
// TODO: Diff insersion and deletion of items
|
||||
if current_layout.0.len() != new_layout.0.len()
|
||||
|| *current_name != new_name
|
||||
|| *current_icon != new_icon
|
||||
|| *current_description != new_description
|
||||
|| *current_visible != new_visible
|
||||
|| *current_pinned != new_pinned
|
||||
|| *current_draggable != new_draggable
|
||||
|| *current_chain_wire != new_chain_wire
|
||||
|| *current_output_wire != new_output_wire
|
||||
|| *current_expanded != new_expanded
|
||||
|| *current_id != new_id
|
||||
{
|
||||
// Update self to reflect new changes
|
||||
current_name.clone_from(&new_name);
|
||||
current_icon.clone_from(&new_icon);
|
||||
current_description.clone_from(&new_description);
|
||||
*current_visible = new_visible;
|
||||
*current_pinned = new_pinned;
|
||||
*current_draggable = new_draggable;
|
||||
*current_chain_wire = new_chain_wire;
|
||||
*current_output_wire = new_output_wire;
|
||||
*current_expanded = new_expanded;
|
||||
*current_id = new_id;
|
||||
current_layout.clone_from(&new_layout);
|
||||
@@ -587,10 +624,13 @@ impl Diffable for LayoutGroup {
|
||||
// Push an update layout group to the diff
|
||||
let new_value = Self::Section(WidgetSection {
|
||||
name: new_name,
|
||||
icon: new_icon,
|
||||
description: new_description,
|
||||
visible: new_visible,
|
||||
pinned: new_pinned,
|
||||
draggable: new_draggable,
|
||||
chain_wire: new_chain_wire,
|
||||
output_wire: new_output_wire,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -954,10 +994,6 @@ impl DiffUpdate {
|
||||
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping);
|
||||
text_button.menu_list_children_hash = hash_menu_list_entry_sections(&text_button.menu_list_children);
|
||||
}
|
||||
Widget::ParameterExposeButton(parameter_expose_button) => {
|
||||
apply_action_shortcut_to_menu_lists(&mut parameter_expose_button.menu_list_children, action_input_mapping);
|
||||
parameter_expose_button.menu_list_children_hash = hash_menu_list_entry_sections(¶meter_expose_button.menu_list_children);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ 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 graph_craft::document::NodeId;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
@@ -33,6 +34,10 @@ pub struct IconButton {
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
|
||||
// Drag and drop
|
||||
#[serde(rename = "dragDropKinds")]
|
||||
pub drag_drop_kinds: DragDropKinds,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
@@ -45,6 +50,19 @@ pub struct IconButton {
|
||||
pub on_drag_drop: WidgetCallback<IconButton>,
|
||||
}
|
||||
|
||||
/// What can be dragged in the Layers panel and dropped onto an icon button to perform its `on_drag_drop` action.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DragDropKinds {
|
||||
/// Nothing, so the button isn't a drop target.
|
||||
#[default]
|
||||
None,
|
||||
/// Layers.
|
||||
Layers,
|
||||
/// Layers, or the nodes in a layer's chain.
|
||||
LayersAndChainNodes,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
@@ -95,13 +113,15 @@ pub struct ParameterExposeButton {
|
||||
pub exposed: bool,
|
||||
#[serde(rename = "dataType")]
|
||||
pub data_type: FrontendGraphDataType,
|
||||
|
||||
// Children
|
||||
#[serde(rename = "menuListChildren")]
|
||||
pub menu_list_children: MenuListEntrySections,
|
||||
#[serde(rename = "menuListChildrenHash")]
|
||||
#[widget_builder(skip)]
|
||||
pub menu_list_children_hash: u64,
|
||||
/// The node whose input this connector represents, so it can be dragged to and from as a wire endpoint.
|
||||
#[serde(rename = "nodeId")]
|
||||
pub node_id: NodeId,
|
||||
/// A `u32` so it reaches the frontend as a number rather than a bigint.
|
||||
#[serde(rename = "inputIndex")]
|
||||
pub input_index: u32,
|
||||
/// Whether the wire currently being dragged in the graph can be dropped onto this connector.
|
||||
#[serde(rename = "wireDropTarget")]
|
||||
pub wire_drop_target: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
|
||||
@@ -12,8 +12,12 @@ pub struct MenuBarMessageHandler {
|
||||
pub canvas_flipped: bool,
|
||||
pub rulers_visible: bool,
|
||||
pub node_graph_open: bool,
|
||||
pub has_artboards: bool,
|
||||
pub has_selected_nodes: bool,
|
||||
pub has_selected_layers: bool,
|
||||
pub has_selected_visible_layers: bool,
|
||||
pub has_selected_visible_and_unlocked_layers: bool,
|
||||
pub has_selected_groups: bool,
|
||||
pub has_selection_history: (bool, bool),
|
||||
pub message_logging_verbosity: MessageLoggingVerbosity,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
@@ -44,8 +48,12 @@ 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_artboards = self.has_artboards;
|
||||
let has_selected_nodes = self.has_selected_nodes;
|
||||
let has_selected_layers = self.has_selected_layers;
|
||||
let has_selected_visible_layers = self.has_selected_visible_layers;
|
||||
let has_selected_visible_and_unlocked_layers = self.has_selected_visible_and_unlocked_layers;
|
||||
let has_selected_groups = self.has_selected_groups;
|
||||
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;
|
||||
@@ -201,13 +209,13 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("Cut")
|
||||
.tooltip_shortcut(action_shortcut!(ClipboardMessageDiscriminant::Cut))
|
||||
.on_commit(|_| ClipboardMessage::Cut.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
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),
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
MenuListEntry::new("Paste")
|
||||
.label("Paste")
|
||||
.icon("Paste")
|
||||
@@ -234,7 +242,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.label("Convert to Infinite Canvas")
|
||||
.icon("Artboard")
|
||||
.on_commit(|_| DocumentMessage::RemoveArtboards.into())
|
||||
.disabled(no_active_document),
|
||||
.disabled(no_active_document || !has_artboards),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
@@ -267,7 +275,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("FolderOpen")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::UngroupSelectedLayers))
|
||||
.on_commit(|_| DocumentMessage::UngroupSelectedLayers.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_groups),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Hide/Show")
|
||||
@@ -275,7 +283,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("EyeHide")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_commit(|_| DocumentMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
MenuListEntry::new("Lock/Unlock")
|
||||
.label("Lock/Unlock")
|
||||
.icon("PadlockLocked")
|
||||
@@ -289,19 +297,19 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("TransformationGrab")
|
||||
.tooltip_shortcut(action_shortcut!(TransformLayerMessageDiscriminant::BeginGrab))
|
||||
.on_commit(|_| TransformLayerMessage::BeginGrab.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_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),
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_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),
|
||||
.disabled(no_active_document || node_graph_open || !has_selected_visible_and_unlocked_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Arrange")
|
||||
@@ -346,7 +354,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Align")
|
||||
.label("Align")
|
||||
.icon("AlignVerticalCenter")
|
||||
.disabled(no_active_document || !has_selected_layers)
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers)
|
||||
.children(vec![
|
||||
vec![
|
||||
MenuListEntry::new("Align Left")
|
||||
@@ -359,7 +367,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Align Horizontal Center")
|
||||
.label("Align Horizontal Center")
|
||||
.icon("AlignHorizontalCenter")
|
||||
@@ -370,7 +378,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Align Right")
|
||||
.label("Align Right")
|
||||
.icon("AlignRight")
|
||||
@@ -381,7 +389,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Align Top")
|
||||
@@ -394,7 +402,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Align Vertical Center")
|
||||
.label("Align Vertical Center")
|
||||
.icon("AlignVerticalCenter")
|
||||
@@ -405,7 +413,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Align Bottom")
|
||||
.label("Align Bottom")
|
||||
.icon("AlignBottom")
|
||||
@@ -416,40 +424,40 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
],
|
||||
]),
|
||||
MenuListEntry::new("Flip")
|
||||
.label("Flip")
|
||||
.icon("FlipVertical")
|
||||
.disabled(no_active_document || !has_selected_layers)
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_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),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_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),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
]]),
|
||||
MenuListEntry::new("Turn")
|
||||
.label("Turn")
|
||||
.icon("TurnPositive90")
|
||||
.disabled(no_active_document || !has_selected_layers)
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_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),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
MenuListEntry::new("Turn 90°")
|
||||
.label("Turn 90°")
|
||||
.icon("TurnPositive90")
|
||||
.on_commit(|_| DocumentMessage::RotateSelectedLayers { degrees: 90. }.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || !has_selected_visible_and_unlocked_layers),
|
||||
]]),
|
||||
MenuListEntry::new("Boolean")
|
||||
.label("Boolean")
|
||||
@@ -513,7 +521,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
vec![
|
||||
MenuListEntry::new("Make Path Editable")
|
||||
.label("Make Path Editable")
|
||||
.icon("NodeShape")
|
||||
.icon("Path")
|
||||
.on_commit(|_| NodeGraphMessage::AddPathNode.into())
|
||||
.disabled(!make_path_editable_is_allowed),
|
||||
MenuListEntry::new("Expand Fill/Stroke")
|
||||
@@ -546,7 +554,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("SelectParent")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::SelectParentLayer))
|
||||
.on_commit(|_| DocumentMessage::SelectParentLayer.into())
|
||||
.disabled(no_active_document || !has_selected_nodes),
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Previous Selection")
|
||||
@@ -600,7 +608,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("FrameSelected")
|
||||
.tooltip_shortcut(action_shortcut!(NavigationMessageDiscriminant::FitViewportToSelection))
|
||||
.on_commit(|_| NavigationMessage::FitViewportToSelection.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
.disabled(no_active_document || if node_graph_open { !has_selected_nodes } else { !has_selected_visible_layers }),
|
||||
MenuListEntry::new("Zoom to Fit")
|
||||
.label("Zoom to Fit")
|
||||
.icon("FrameAll")
|
||||
@@ -735,7 +743,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon(if message_logging_verbosity_off {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
"DataSourceValue".to_string()
|
||||
"SmallDot".to_string()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
@@ -749,7 +757,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon(if message_logging_verbosity_names {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
"DataSourceValue".to_string()
|
||||
"SmallDot".to_string()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
@@ -763,7 +771,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon(if message_logging_verbosity_contents {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
"DataSourceValue".to_string()
|
||||
"SmallDot".to_string()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
|
||||
@@ -39,6 +39,7 @@ use std::sync::Arc;
|
||||
#[derive(ExtractField)]
|
||||
pub struct DataPanelMessageContext<'a> {
|
||||
pub network_interface: &'a mut NodeNetworkInterface,
|
||||
pub selection_network_path: &'a [NodeId],
|
||||
pub data_panel_open: bool,
|
||||
}
|
||||
|
||||
@@ -99,12 +100,17 @@ impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanel
|
||||
|
||||
impl DataPanelMessageHandler {
|
||||
fn update_layout(&mut self, responses: &mut VecDeque<Message>, context: DataPanelMessageContext<'_>) {
|
||||
let DataPanelMessageContext { network_interface, .. } = context;
|
||||
let DataPanelMessageContext {
|
||||
network_interface,
|
||||
selection_network_path,
|
||||
..
|
||||
} = context;
|
||||
|
||||
let mut layout_data = LayoutData {
|
||||
current_depth: 0,
|
||||
desired_path: &mut self.element_path,
|
||||
network_interface: &*network_interface,
|
||||
selection_network_path,
|
||||
node_lookup_network_path: Vec::new(),
|
||||
gradient_settings: GradientSettings::default(),
|
||||
breadcrumbs: Vec::new(),
|
||||
@@ -175,6 +181,8 @@ struct LayoutData<'a> {
|
||||
current_depth: usize,
|
||||
desired_path: &'a mut Vec<PathStep>,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
/// The network open in the graph, which is where selecting a node takes effect.
|
||||
selection_network_path: &'a [NodeId],
|
||||
/// The `network_path` to use when resolving a `NodeId` against the network interface.
|
||||
/// Defaults to root (`&[]`); `List<NodeId>` rendering temporarily sets it to the path's prefix so nested
|
||||
/// layers (e.g. inside a Ctrl+M-merged custom subgraph) resolve correctly.
|
||||
@@ -1085,108 +1093,83 @@ impl TableItemLayout for NodeId {
|
||||
fn identifier(&self) -> String {
|
||||
format!("Node {self}")
|
||||
}
|
||||
// Override so the breadcrumb uses the same resolved display name as the value button, instead of the bare-ID fallback `identifier()` returns.
|
||||
// Override so the breadcrumb uses the node's resolved display name instead of the bare-ID fallback `identifier()` returns
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
data.breadcrumbs.push(node_id_display_label(*self, data.network_interface, &data.node_lookup_network_path));
|
||||
self.value_page(data)
|
||||
}
|
||||
// The value's label resolves the node's display name via the network interface so the button reads as the name shown
|
||||
// in the Node Graph / Layers panels. The lookup uses `data.node_lookup_network_path` (set by the enclosing
|
||||
// `List<NodeId>` if rendering a path) so the resolution succeeds at any nesting depth. The button's icon
|
||||
// signals layer-vs-node kind. Falls back to "Node {id}" with no icon if the lookup misses.
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let label = node_id_display_label(*self, data.network_interface, &data.node_lookup_network_path);
|
||||
let mut button = TextButton::new(label)
|
||||
.on_update(move |_| DataPanelMessage::PushToElementPath { step: target.clone() }.into())
|
||||
.narrow(true);
|
||||
if data.network_interface.node_metadata(self, &data.node_lookup_network_path).is_some() {
|
||||
let icon = if data.network_interface.is_layer(self, &data.node_lookup_network_path) { "Layer" } else { "Node" };
|
||||
button = button.icon(icon);
|
||||
}
|
||||
vec![button.widget_instance()]
|
||||
}
|
||||
// The value page shows the node's kind, name (editable), lock/visibility toggles, and a "Select Layer/Node" action button.
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
// Shown inline as the node's icon, name, a button to select it, and visibility and lock toggles. The lookups use
|
||||
// `data.node_lookup_network_path` (set by the enclosing `List<NodeId>` if rendering a path) so they resolve at any nesting depth.
|
||||
fn value_widgets(&self, _target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let node_id = *self;
|
||||
let network_interface = data.network_interface;
|
||||
let network_path = data.node_lookup_network_path.clone();
|
||||
let known = data.network_interface.node_metadata(&node_id, &network_path).is_some();
|
||||
let is_layer = known && data.network_interface.is_layer(&node_id, &network_path);
|
||||
let name = if known {
|
||||
data.network_interface.display_name(&node_id, &network_path)
|
||||
} else {
|
||||
"(node not found)".to_string()
|
||||
};
|
||||
let kind_widget = if known {
|
||||
IconLabel::new(if is_layer { "Layer" } else { "Node" }).widget_instance()
|
||||
} else {
|
||||
TextLabel::new("-").widget_instance()
|
||||
};
|
||||
let name_widget = if known {
|
||||
let path_for_rename = network_path.clone();
|
||||
TextInput::new(name)
|
||||
.tooltip_description(if is_layer { "Name of this layer." } else { "Name of this node." })
|
||||
.on_update(move |text_input| {
|
||||
NodeGraphMessage::SetDisplayName {
|
||||
|
||||
// An ID that no longer maps to a real node has nothing to show but itself
|
||||
if network_interface.node_metadata(&node_id, &network_path).is_none() {
|
||||
return vec![TextLabel::new(node_id_display_label(node_id, network_interface, &network_path)).widget_instance()];
|
||||
}
|
||||
|
||||
let is_layer = network_interface.is_layer(&node_id, &network_path);
|
||||
let is_locked = network_interface.is_locked(&node_id, &network_path);
|
||||
let is_visible = network_interface.is_visible(&node_id, &network_path);
|
||||
let icon = network_interface.node_icon(&node_id, &network_path);
|
||||
let name = network_interface.display_name(&node_id, &network_path);
|
||||
let in_open_network = network_path == data.selection_network_path;
|
||||
let already_selected = network_interface.selected_nodes_in_nested_network(&network_path).is_some_and(|selected| selected.0 == [node_id]);
|
||||
|
||||
let path_for_visibility = network_path.clone();
|
||||
let path_for_lock = network_path;
|
||||
|
||||
vec![
|
||||
IconLabel::new(icon).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(name).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
IconButton::new("SelectAll", 24)
|
||||
.disabled(!in_open_network || already_selected)
|
||||
.tooltip_label(if is_layer { "Select Layer" } else { "Select Node" })
|
||||
.tooltip_description(match (in_open_network, already_selected, is_layer) {
|
||||
(false, _, true) => "This layer is not in the part of the graph currently open.",
|
||||
(false, _, false) => "This node is not in the part of the graph currently open.",
|
||||
(true, true, true) => "This is already the selected layer.",
|
||||
(true, true, false) => "This is already the selected node.",
|
||||
(true, false, _) => "",
|
||||
})
|
||||
// Starts from the root of the newly selected node's data, since the current drill-down path means nothing there
|
||||
.on_update(move |_| Message::Batched {
|
||||
messages: Box::new([DataPanelMessage::TruncateElementPath { len: 0 }.into(), NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }.into()]),
|
||||
})
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
IconButton::new(if is_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if is_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if is_visible { "Hide" } else { "Show" })
|
||||
.on_update(move |_| {
|
||||
NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: path_for_rename.clone(),
|
||||
alias: text_input.value.clone(),
|
||||
skip_adding_history_step: false,
|
||||
network_path: path_for_visibility.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.max_width(200)
|
||||
.widget_instance()
|
||||
} else {
|
||||
TextLabel::new(name).widget_instance()
|
||||
};
|
||||
|
||||
let mut header = vec![kind_widget, Separator::new(SeparatorStyle::Related).widget_instance(), name_widget];
|
||||
|
||||
if known {
|
||||
let is_locked = data.network_interface.is_locked(&node_id, &network_path);
|
||||
let is_visible = data.network_interface.is_visible(&node_id, &network_path);
|
||||
|
||||
let path_for_lock = network_path.clone();
|
||||
let path_for_visibility = network_path.clone();
|
||||
|
||||
header.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
header.push(
|
||||
IconButton::new(if is_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if is_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.tooltip_label(if is_locked { "Unlock" } else { "Lock" })
|
||||
.on_update(move |_| {
|
||||
NodeGraphMessage::ToggleLocked {
|
||||
node_id,
|
||||
network_path: path_for_lock.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
header.push(
|
||||
IconButton::new(if is_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if is_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if is_visible { "Hide" } else { "Show" })
|
||||
.on_update(move |_| {
|
||||
NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: path_for_visibility.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
header.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
header.push(
|
||||
TextButton::new(if is_layer { "Select Layer" } else { "Select Node" })
|
||||
.tooltip_description(if is_layer { "Click to select this layer." } else { "Click to select this node." })
|
||||
.on_update(move |_| NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }.into())
|
||||
.widget_instance(),
|
||||
);
|
||||
|
||||
vec![LayoutGroup::row(header)]
|
||||
IconButton::new(if is_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if is_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.disabled(!is_layer)
|
||||
.tooltip_label(if is_locked { "Unlock" } else { "Lock" })
|
||||
.tooltip_description(if is_layer { "" } else { "Only layers can be locked." })
|
||||
.on_update(move |_| {
|
||||
NodeGraphMessage::ToggleLocked {
|
||||
node_id,
|
||||
network_path: path_for_lock.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), data))]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ 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::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, IVec2, UVec2};
|
||||
@@ -89,6 +90,9 @@ pub enum DocumentMessage {
|
||||
GridVisibility {
|
||||
visible: bool,
|
||||
},
|
||||
LayersPanelHoverOverlays {
|
||||
context: OverlayContext,
|
||||
},
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayers,
|
||||
@@ -103,6 +107,24 @@ pub enum DocumentMessage {
|
||||
ReorderPropertiesSection {
|
||||
node_id: NodeId,
|
||||
insert_index: usize,
|
||||
duplicate: bool,
|
||||
},
|
||||
MoveChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
layer: NodeId,
|
||||
insert_index: usize,
|
||||
},
|
||||
DuplicateChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
layer: NodeId,
|
||||
insert_index: usize,
|
||||
select_copies: bool,
|
||||
},
|
||||
PasteChainNodes {
|
||||
copies: Vec<ChainNodeCopy>,
|
||||
},
|
||||
PasteNodes {
|
||||
nodes: Vec<(NodeId, NodeTemplate)>,
|
||||
},
|
||||
MoveSelectedLayersToGroup {
|
||||
parent: LayerNodeIdentifier,
|
||||
@@ -162,6 +184,12 @@ pub enum DocumentMessage {
|
||||
ctrl: bool,
|
||||
shift: bool,
|
||||
},
|
||||
SelectChainNode {
|
||||
layer: NodeId,
|
||||
node_id: NodeId,
|
||||
ctrl: bool,
|
||||
shift: bool,
|
||||
},
|
||||
SetActivePanel {
|
||||
active_panel: PanelType,
|
||||
},
|
||||
@@ -171,6 +199,9 @@ pub enum DocumentMessage {
|
||||
SetGraphFadeArtwork {
|
||||
percentage: f64,
|
||||
},
|
||||
SetLayersPanelHoveredLayer {
|
||||
id: Option<NodeId>,
|
||||
},
|
||||
SetNodePinned {
|
||||
node_id: NodeId,
|
||||
pinned: bool,
|
||||
@@ -201,6 +232,10 @@ pub enum DocumentMessage {
|
||||
SetRenderMode {
|
||||
render_mode: RenderMode,
|
||||
},
|
||||
ShowNodeInGraph {
|
||||
node_id: NodeId,
|
||||
},
|
||||
ShowSelectionInGraph,
|
||||
AddTransaction,
|
||||
StartTransaction,
|
||||
EndTransaction,
|
||||
@@ -216,6 +251,7 @@ pub enum DocumentMessage {
|
||||
},
|
||||
ToggleNodePropertiesSectionExpanded {
|
||||
node_id: NodeId,
|
||||
recursive: bool,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
ToggleSelectedLocked,
|
||||
|
||||
@@ -17,18 +17,18 @@ use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext,
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::{ModifyInputsContext, TransformIn};
|
||||
use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
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, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
|
||||
use crate::messages::tool::common_functionality::utility_functions::nudge_resize_bounds;
|
||||
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
|
||||
use crate::messages::tool::tool_messages::select_tool::{SelectToolPointerKeys, draw_layer_outline};
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
@@ -61,6 +61,7 @@ pub struct DocumentMessageContext<'a> {
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub tool_edit_target: &'a EditTarget,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub data_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
@@ -70,6 +71,16 @@ pub struct DocumentMessageContext<'a> {
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
}
|
||||
|
||||
/// The selection split by how it's duplicated and copied.
|
||||
pub struct SelectionParts {
|
||||
/// The shallowest selected layers in the layer structure, which bring their content along.
|
||||
pub layers: Vec<LayerNodeIdentifier>,
|
||||
/// The selected reorderable nodes of other layers' chains, in the Layers panel's order.
|
||||
pub chain_nodes: Vec<NodeId>,
|
||||
/// Every other selected node, outside the content of the layers above.
|
||||
pub other_nodes: Vec<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize, ExtractField)]
|
||||
#[derivative(Clone, Debug)]
|
||||
#[serde(default)]
|
||||
@@ -164,6 +175,12 @@ pub struct DocumentMessageHandler {
|
||||
/// 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>,
|
||||
/// The ID of the chain node at the start of a range selection among a layer's chain node icons in the Layers panel, working like `layer_range_selection_reference`.
|
||||
#[serde(skip)]
|
||||
chain_node_range_selection_reference: Option<NodeId>,
|
||||
/// The layer under the pointer in the Layers panel, which gets a hover outline in the viewport.
|
||||
#[serde(skip)]
|
||||
layers_panel_hovered_layer: 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,
|
||||
@@ -209,6 +226,8 @@ impl Default for DocumentMessageHandler {
|
||||
saved_hash: None,
|
||||
auto_saved_hash: None,
|
||||
layer_range_selection_reference: None,
|
||||
chain_node_range_selection_reference: None,
|
||||
layers_panel_hovered_layer: None,
|
||||
is_loaded: false,
|
||||
}
|
||||
}
|
||||
@@ -223,6 +242,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
executor,
|
||||
viewport,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
preferences,
|
||||
data_panel_open,
|
||||
layers_panel_open,
|
||||
@@ -254,6 +274,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
||||
}
|
||||
DocumentMessage::PropertiesPanel(message) => {
|
||||
let wire_in_progress_output_types = self.node_graph_handler.wire_in_progress_output_types(&self.network_interface, &self.selection_network_path);
|
||||
let context = PropertiesPanelMessageContext {
|
||||
executor,
|
||||
document_id,
|
||||
@@ -264,6 +285,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
fonts,
|
||||
properties_panel_open,
|
||||
properties_panel_collapsed_sections: &self.properties_panel_collapsed_sections,
|
||||
wire_in_progress_output_types: &wire_in_progress_output_types,
|
||||
};
|
||||
self.properties_panel_message_handler.process_message(message, responses, context);
|
||||
}
|
||||
@@ -273,6 +295,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses,
|
||||
DataPanelMessageContext {
|
||||
network_interface: &mut self.network_interface,
|
||||
selection_network_path: &self.selection_network_path,
|
||||
data_panel_open,
|
||||
},
|
||||
);
|
||||
@@ -294,6 +317,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
navigation_handler: &self.navigation_handler,
|
||||
preferences,
|
||||
layers_panel_open,
|
||||
tool_edit_target,
|
||||
viewport,
|
||||
},
|
||||
);
|
||||
@@ -316,7 +340,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
AlignAxis::X => DVec2::X,
|
||||
AlignAxis::Y => DVec2::Y,
|
||||
};
|
||||
let Some(combined_box) = self.network_interface.selected_layers_artwork_bounding_box_viewport() else {
|
||||
// Locked layers stay put but still count toward the bounds the others align to
|
||||
let selected_nodes = self.network_interface.selected_nodes();
|
||||
let Some(combined_box) = selected_nodes
|
||||
.selected_visible_layers(&self.network_interface)
|
||||
.filter_map(|layer| self.metadata().bounding_box_viewport(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -327,7 +357,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
};
|
||||
|
||||
let mut added_transaction = false;
|
||||
for layer in self.network_interface.selected_nodes().selected_unlocked_layers(&self.network_interface) {
|
||||
for layer in selected_nodes.selected_visible_and_unlocked_layers(&self.network_interface) {
|
||||
let Some(bbox) = self.metadata().bounding_box_viewport(layer) else {
|
||||
continue;
|
||||
};
|
||||
@@ -364,15 +394,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
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,
|
||||
layout_target: LayoutTarget::LayersPanelBottomLeftBar,
|
||||
});
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout::default(),
|
||||
layout_target: LayoutTarget::LayersPanelBottomRightBar,
|
||||
});
|
||||
}
|
||||
DocumentMessage::CreateEmptyFolder => {
|
||||
@@ -412,6 +442,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::DeselectAllLayers => {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
|
||||
self.layer_range_selection_reference = None;
|
||||
self.chain_node_range_selection_reference = None;
|
||||
}
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
|
||||
@@ -464,11 +495,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
}
|
||||
DocumentMessage::DuplicateSelectedLayers => {
|
||||
let SelectionParts { mut layers, chain_nodes, other_nodes } = self.partition_selection();
|
||||
if layers.is_empty() && chain_nodes.is_empty() && other_nodes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
// Layers in the layer structure are copied with their content into the stack beside their originals
|
||||
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)
|
||||
@@ -488,7 +523,24 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
let nodes = new_dragging.iter().map(|layer| layer.to_node()).collect();
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes });
|
||||
|
||||
// Each chain node goes beside itself in its chain, as if duplicated one at a time
|
||||
for node_id in chain_nodes {
|
||||
responses.add(NodeGraphMessage::DuplicateChainNodes {
|
||||
node_ids: vec![node_id],
|
||||
destination: None,
|
||||
select_copies: true,
|
||||
});
|
||||
}
|
||||
|
||||
// The other nodes go into their primary flow, or loose when in none
|
||||
if !other_nodes.is_empty() {
|
||||
responses.add(NodeGraphMessage::DuplicateNodesInFlow { node_ids: other_nodes });
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::DuplicateSelectedLayersTo { parent, insert_index } => {
|
||||
if !self.selection_network_path.is_empty() {
|
||||
@@ -582,11 +634,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
// 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 });
|
||||
self.node_graph_handler.end_wire_in_progress(&mut self.network_interface, &self.selection_network_path, responses);
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
}
|
||||
// Close the context menu if it's open
|
||||
@@ -623,11 +671,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
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() {
|
||||
if let Some([min, max]) = self.network_interface.selected_visible_and_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) {
|
||||
for layer in self.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&self.network_interface) {
|
||||
if !added_transaction {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
added_transaction = true;
|
||||
@@ -643,14 +691,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
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() {
|
||||
if let Some([min, max]) = self.network_interface.selected_visible_and_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) {
|
||||
for layer in self.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&self.network_interface) {
|
||||
if !added_transaction {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
added_transaction = true;
|
||||
@@ -714,6 +762,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.snapping_state.grid_snapping = visible;
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
DocumentMessage::LayersPanelHoverOverlays { context: mut overlay_context } => {
|
||||
let Some(layer) = self.layers_panel_hovered_layer else { return };
|
||||
if !overlay_context.visibility_settings.hover_outline() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Outlined like the Select tool's hover, with groups and artboards shown by their bounding box
|
||||
if layer.has_children(self.metadata()) || self.network_interface.is_artboard(&layer.to_node(), &[]) {
|
||||
if let Some(bounds) = self.metadata().bounding_box_viewport(layer) {
|
||||
overlay_context.quad(Quad::from_box(bounds), None, None);
|
||||
}
|
||||
} else {
|
||||
draw_layer_outline(&mut overlay_context, self, layer, None);
|
||||
}
|
||||
}
|
||||
DocumentMessage::BlendSelectedLayers => {
|
||||
self.group_selected_layers(GroupFolderType::Blend, responses);
|
||||
}
|
||||
@@ -744,7 +807,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::MoveSelectedLayersTo { parent, insert_index } => {
|
||||
self.move_selected_layers_to(parent, insert_index, responses);
|
||||
}
|
||||
DocumentMessage::ReorderPropertiesSection { node_id, insert_index } => {
|
||||
DocumentMessage::ReorderPropertiesSection { node_id, insert_index, duplicate } => {
|
||||
// The Properties panel shows draggable sections in two cases, disambiguated by the current selection:
|
||||
// a single selected layer (reorder within its node chain) or no selection (reorder the pinned nodes).
|
||||
let selected_nodes = self.network_interface.selected_nodes_in_nested_network(&self.selection_network_path);
|
||||
@@ -763,20 +826,112 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
layers.sort();
|
||||
layers.dedup();
|
||||
|
||||
if layers.len() == 1 {
|
||||
// Reorder a node within the selected layer's chain by rewiring the graph
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::ReorderChainNode { node_id, insert_index });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
if let [layer] = *layers.as_slice() {
|
||||
let node_ids = vec![node_id];
|
||||
if duplicate {
|
||||
responses.add(DocumentMessage::DuplicateChainNodes {
|
||||
node_ids,
|
||||
layer,
|
||||
insert_index,
|
||||
select_copies: false,
|
||||
});
|
||||
} else {
|
||||
responses.add(DocumentMessage::MoveChainNodes { node_ids, layer, insert_index });
|
||||
}
|
||||
} else if layers.is_empty() && nodes.is_empty() {
|
||||
// Reorder a pinned node, which is purely a Properties panel display order (no graph rerender needed)
|
||||
// Reorder a pinned node, which is purely a Properties panel display order (no graph rerender needed, and nothing to duplicate into)
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::ReorderPinnedNode { node_id, insert_index });
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
}
|
||||
DocumentMessage::MoveChainNodes { node_ids, layer, insert_index } => {
|
||||
// Move nodes within their layer's chain, or into another layer's, by rewiring the graph
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::MoveChainNodes { node_ids, layer, insert_index });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::DuplicateChainNodes {
|
||||
node_ids,
|
||||
layer,
|
||||
insert_index,
|
||||
select_copies,
|
||||
} => {
|
||||
// Insert copies of nodes into a layer's chain by rewiring the graph
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
if select_copies {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() });
|
||||
}
|
||||
responses.add(NodeGraphMessage::DuplicateChainNodes {
|
||||
node_ids,
|
||||
destination: Some((layer, insert_index)),
|
||||
select_copies,
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::PasteChainNodes { copies } => {
|
||||
// Layers and their chains live in the document network, so a nested one open in the graph has no chain to paste into
|
||||
let (chain_nodes, layers) = if self.selection_network_path.is_empty() {
|
||||
let layers = self.network_interface.selected_nodes().selected_layers(self.metadata()).map(|layer| layer.to_node()).collect();
|
||||
(self.selected_reorderable_chain_nodes(), layers)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
// Selected chain nodes interleave with the copies: over the same selection that was copied, each node gets its own copy beside it (like duplicating),
|
||||
// and over a different selection of the same size, the copies pair with those nodes in order. Otherwise, all the copies go beside every selected node.
|
||||
let mut insertions = Vec::new();
|
||||
let same_selection = chain_nodes.len() == copies.len() && copies.iter().all(|copy| chain_nodes.contains(©.source));
|
||||
if same_selection {
|
||||
insertions.extend(copies.iter().map(|copy| (ChainInsertionPoint::BesideNode(copy.source), vec![copy.clone()])));
|
||||
} else if chain_nodes.len() == copies.len() {
|
||||
insertions.extend(chain_nodes.iter().zip(&copies).map(|(node_id, copy)| (ChainInsertionPoint::BesideNode(*node_id), vec![copy.clone()])));
|
||||
} else {
|
||||
insertions.extend(chain_nodes.iter().map(|node_id| (ChainInsertionPoint::BesideNode(*node_id), copies.clone())));
|
||||
}
|
||||
|
||||
// Each selected layer gets all the copies at the end of its chain
|
||||
insertions.extend(layers.into_iter().map(|layer| (ChainInsertionPoint::BesideLayer(layer), copies.clone())));
|
||||
|
||||
// With no chain to go in, such as over an empty selection, the copies are pasted loose into the graph and shown there
|
||||
if insertions.is_empty() {
|
||||
let nodes = copies.into_iter().map(|copy| (copy.source, copy.into_loose_template())).collect();
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
responses.add(DocumentMessage::ShowSelectionInGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
// The pasted copies become the selection
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() });
|
||||
for (target, copies) in insertions {
|
||||
responses.add(NodeGraphMessage::PasteIntoChain { target, copies });
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::PasteNodes { nodes } => {
|
||||
// Over the same selection they were copied from, nodes are duplicated into their flow, and otherwise they're pasted loose into the graph and shown there
|
||||
let other_nodes = self.partition_selection().other_nodes;
|
||||
let copied = nodes.iter().map(|(node_id, _)| *node_id).collect::<HashSet<_>>();
|
||||
let selected = self.with_layer_content(&other_nodes).into_iter().collect::<HashSet<_>>();
|
||||
if !copied.is_empty() && copied == selected {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() });
|
||||
responses.add(NodeGraphMessage::DuplicateNodesInFlow { node_ids: other_nodes });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
responses.add(DocumentMessage::ShowSelectionInGraph);
|
||||
}
|
||||
DocumentMessage::MoveSelectedLayersToGroup { parent } => {
|
||||
// Group all shallowest unique selected layers in order
|
||||
let all_layers_to_group_sorted = self.network_interface.shallowest_unique_layers_sorted(&self.selection_network_path);
|
||||
@@ -1165,7 +1320,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
}
|
||||
DocumentMessage::SelectAllLayers => {
|
||||
if !self.overlays_visibility_settings.selection_outline() {
|
||||
// In the graph, select every node of the network it shows
|
||||
if self.graph_view_overlay_open {
|
||||
let Some(network_metadata) = self.network_interface.network_metadata(&self.selection_network_path) else {
|
||||
return;
|
||||
};
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect();
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1255,6 +1416,38 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
}
|
||||
}
|
||||
DocumentMessage::SelectChainNode { layer, node_id, ctrl, shift } => {
|
||||
// The layer's chain as listed beside it in the Layers panel, which a Shift-click range runs along
|
||||
let chain = self.network_interface.layer_chain_nodes(layer, &[]);
|
||||
|
||||
let selected_nodes = self.network_interface.selected_nodes();
|
||||
let range_start = self
|
||||
.chain_node_range_selection_reference
|
||||
.filter(|start| shift && selected_nodes.selected_nodes().any(|selected| selected == start))
|
||||
.and_then(|start| chain.iter().position(|id| *id == start));
|
||||
let clicked = chain.iter().position(|id| *id == node_id);
|
||||
|
||||
// Shift-clicking selects the range from the still-selected last clicked node in this chain, adding it with Ctrl
|
||||
if let (Some(start), Some(end)) = (range_start, clicked) {
|
||||
let nodes = chain[start.min(end)..=start.max(end)].to_vec();
|
||||
if ctrl {
|
||||
responses.add(NodeGraphMessage::SelectedNodesAdd { nodes });
|
||||
} else {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, Ctrl-clicking toggles the node's selection while a plain click selects only it, either way starting a new range
|
||||
if !ctrl {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
} else if self.network_interface.selected_nodes().selected_nodes().any(|selected| *selected == node_id) {
|
||||
responses.add(NodeGraphMessage::SelectedNodesRemove { nodes: vec![node_id] });
|
||||
} else {
|
||||
responses.add(NodeGraphMessage::SelectedNodesAdd { nodes: vec![node_id] });
|
||||
}
|
||||
self.chain_node_range_selection_reference = Some(node_id);
|
||||
}
|
||||
DocumentMessage::SetActivePanel { active_panel } => {
|
||||
match active_panel {
|
||||
PanelType::Document => {
|
||||
@@ -1280,6 +1473,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.graph_fade_artwork_percentage = percentage;
|
||||
responses.add(FrontendMessage::UpdateGraphFadeArtwork { percentage });
|
||||
}
|
||||
DocumentMessage::SetLayersPanelHoveredLayer { id } => {
|
||||
let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked);
|
||||
if layer != self.layers_panel_hovered_layer {
|
||||
self.layers_panel_hovered_layer = layer;
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
}
|
||||
DocumentMessage::SetNodePinned { node_id, pinned } => {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SetPinned { node_id, pinned });
|
||||
@@ -1349,6 +1549,23 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.render_mode = render_mode;
|
||||
responses.add_front(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
DocumentMessage::ShowNodeInGraph { node_id } => {
|
||||
// The node is in the document network, so the graph first leaves any nested network it's showing
|
||||
if !self.breadcrumb_network_path.is_empty() {
|
||||
responses.add(DocumentMessage::ExitNestedNetwork {
|
||||
steps_back: self.breadcrumb_network_path.len(),
|
||||
});
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
responses.add(DocumentMessage::ShowSelectionInGraph);
|
||||
}
|
||||
DocumentMessage::ShowSelectionInGraph => {
|
||||
// Opens the graph on the selection, centered at 100% zoom
|
||||
responses.add(DocumentMessage::GraphViewOverlay { open: true });
|
||||
responses.add(NavigationMessage::FitViewportToSelection);
|
||||
responses.add(DocumentMessage::ZoomCanvasTo100Percent);
|
||||
}
|
||||
DocumentMessage::AddTransaction => {
|
||||
// Reverse order since they are added to the front
|
||||
responses.add_front(DocumentMessage::CommitTransaction);
|
||||
@@ -1435,12 +1652,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id } => {
|
||||
if let Some(index) = self.properties_panel_collapsed_sections.iter().position(|id| *id == node_id) {
|
||||
self.properties_panel_collapsed_sections.remove(index);
|
||||
} else {
|
||||
self.properties_panel_collapsed_sections.push(node_id);
|
||||
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id, recursive } => {
|
||||
let expand = self.properties_panel_collapsed_sections.contains(&node_id);
|
||||
|
||||
// Recursively, every section in the chain follows along, from its layer back to where another layer begins
|
||||
let network_path = &self.selection_network_path;
|
||||
let chain = recursive
|
||||
.then(|| self.network_interface.downstream_layer_for_chain_node(&node_id, network_path))
|
||||
.flatten()
|
||||
.map(|layer| std::iter::once(layer).chain(self.network_interface.layer_chain_nodes(layer, network_path)).collect::<Vec<_>>())
|
||||
// A node that only leads into a chain from the side, or into no layer at all, isn't part of one
|
||||
.filter(|chain| chain.contains(&node_id));
|
||||
let node_ids = chain.unwrap_or_else(|| vec![node_id]);
|
||||
|
||||
for node_id in node_ids {
|
||||
if expand {
|
||||
self.properties_panel_collapsed_sections.retain(|id| *id != node_id);
|
||||
} else if !self.properties_panel_collapsed_sections.contains(&node_id) {
|
||||
self.properties_panel_collapsed_sections.push(node_id);
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::ToggleSelectedLocked => responses.add(NodeGraphMessage::ToggleSelectedLocked),
|
||||
@@ -1565,20 +1797,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
log::error!("Ungrouping selected layers is only supported for the Document Network");
|
||||
return;
|
||||
}
|
||||
|
||||
// Artboards can't be ungrouped
|
||||
let folders: Vec<_> = self
|
||||
.network_interface
|
||||
.folders_sorted_by_most_nested(&self.selection_network_path)
|
||||
.into_iter()
|
||||
.filter(|&folder| folder != LayerNodeIdentifier::ROOT_PARENT && !self.network_interface.is_artboard(&folder.to_node(), &self.selection_network_path))
|
||||
.collect();
|
||||
if folders.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
let folder_paths = self.network_interface.folders_sorted_by_most_nested(&self.selection_network_path);
|
||||
for folder in folder_paths {
|
||||
if folder == LayerNodeIdentifier::ROOT_PARENT {
|
||||
log::error!("ROOT_PARENT cannot be selected when ungrouping selected layers");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Cannot ungroup artboard
|
||||
if self.network_interface.is_artboard(&folder.to_node(), &self.selection_network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
for folder in folders {
|
||||
responses.add(DocumentMessage::UngroupLayer { layer: folder });
|
||||
}
|
||||
|
||||
@@ -1639,6 +1872,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
} else {
|
||||
// The artwork behind the graph can be navigated too, so rerender it if its view changed
|
||||
let artwork_transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
if artwork_transform != self.network_interface.document_metadata().document_to_viewport {
|
||||
self.network_interface.set_document_to_viewport_transform(artwork_transform);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
let Some(network_metadata) = self.network_interface.network_metadata(&self.breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
@@ -1776,11 +2016,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
common.extend(actions!(DocumentMessageDiscriminant::SaveDocumentAs));
|
||||
|
||||
// Deleting, duplicating, and hiding apply to any selected nodes, not just layers, such as chain nodes selected in the Layers panel
|
||||
if self.network_interface.selected_nodes().has_selected_nodes() {
|
||||
common.extend(actions!(DocumentMessageDiscriminant;
|
||||
DeleteSelectedLayers,
|
||||
DuplicateSelectedLayers,
|
||||
));
|
||||
if !self.graph_view_overlay_open {
|
||||
common.extend(actions!(DocumentMessageDiscriminant::ToggleSelectedVisibility));
|
||||
}
|
||||
}
|
||||
|
||||
// Additional actions if there are any selected layers
|
||||
if self.network_interface.selected_nodes().selected_layers(self.metadata()).next().is_some() {
|
||||
let mut select = actions!(DocumentMessageDiscriminant;
|
||||
DeleteSelectedLayers,
|
||||
DuplicateSelectedLayers,
|
||||
GroupSelectedLayers,
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
@@ -1792,10 +2041,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
ToggleSelectedLocked
|
||||
);
|
||||
if !self.graph_view_overlay_open {
|
||||
select.extend(actions!(DocumentMessageDiscriminant;
|
||||
NudgeSelectedLayers,
|
||||
ToggleSelectedVisibility,
|
||||
));
|
||||
select.extend(actions!(DocumentMessageDiscriminant::NudgeSelectedLayers));
|
||||
}
|
||||
common.extend(select);
|
||||
}
|
||||
@@ -2571,6 +2817,72 @@ impl DocumentMessageHandler {
|
||||
.unwrap_or_else(|| self.network_interface.all_artboards().iter().next().copied().unwrap_or(LayerNodeIdentifier::ROOT_PARENT))
|
||||
}
|
||||
|
||||
/// The selection split the way it's duplicated and copied. Inside a nested network open in the graph, every selected node counts among the other nodes.
|
||||
pub fn partition_selection(&self) -> SelectionParts {
|
||||
let selected_nodes = self.network_interface.selected_nodes_in_nested_network(&self.selection_network_path).unwrap_or_default();
|
||||
let selected_nodes = selected_nodes.selected_nodes().copied().collect::<Vec<_>>();
|
||||
if !self.selection_network_path.is_empty() {
|
||||
return SelectionParts {
|
||||
layers: Vec::new(),
|
||||
chain_nodes: Vec::new(),
|
||||
other_nodes: selected_nodes,
|
||||
};
|
||||
}
|
||||
|
||||
let layers = self.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
|
||||
let layer_nodes = layers.iter().map(|layer| layer.to_node()).collect::<Vec<_>>();
|
||||
let mut other_nodes = selected_nodes.into_iter().filter(|node_id| !layer_nodes.contains(node_id)).collect::<Vec<_>>();
|
||||
|
||||
// Usually only layers are selected, which skips walking their content
|
||||
let mut chain_nodes = Vec::new();
|
||||
if !other_nodes.is_empty() {
|
||||
let layer_content = self
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes(layer_nodes, &[], FlowType::LayerChildrenUpstreamFlow)
|
||||
.collect::<HashSet<_>>();
|
||||
other_nodes.retain(|node_id| !layer_content.contains(node_id));
|
||||
|
||||
chain_nodes = self.selected_reorderable_chain_nodes().into_iter().filter(|node_id| other_nodes.contains(node_id)).collect();
|
||||
other_nodes.retain(|node_id| !chain_nodes.contains(node_id));
|
||||
}
|
||||
|
||||
SelectionParts { layers, chain_nodes, other_nodes }
|
||||
}
|
||||
|
||||
/// The given nodes along with the content of any layers among them, in the network open in the graph.
|
||||
pub fn with_layer_content(&self, node_ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let layers = node_ids
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|node_id| self.network_interface.is_layer(node_id, &self.selection_network_path))
|
||||
.collect();
|
||||
let content = self
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes(layers, &self.selection_network_path, FlowType::LayerChildrenUpstreamFlow);
|
||||
|
||||
node_ids.iter().copied().chain(content).collect::<HashSet<_>>().into_iter().collect()
|
||||
}
|
||||
|
||||
/// The selected nodes that can be reordered in layers' chains, ordered by their layer's place in the Layers panel, then from the layer outward.
|
||||
pub fn selected_reorderable_chain_nodes(&self) -> Vec<NodeId> {
|
||||
let selected_nodes = self.network_interface.selected_nodes().selected_nodes().copied().collect::<HashSet<_>>();
|
||||
|
||||
// Only walk the layers' chains, in O(nodes in all chains), when something other than layers is selected
|
||||
if selected_nodes.iter().all(|node_id| self.network_interface.is_layer(node_id, &[])) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut chain_nodes = Vec::new();
|
||||
for layer in self.metadata().all_layers() {
|
||||
for node_id in self.network_interface.reorderable_chain(layer.to_node(), &[]) {
|
||||
if selected_nodes.contains(&node_id) && !chain_nodes.contains(&node_id) {
|
||||
chain_nodes.push(node_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
chain_nodes
|
||||
}
|
||||
|
||||
pub fn get_calculated_insert_index(metadata: &DocumentMetadata, selected_nodes: &SelectedNodes, parent: LayerNodeIdentifier) -> usize {
|
||||
parent
|
||||
.children(metadata)
|
||||
@@ -3512,18 +3824,6 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
.collect();
|
||||
|
||||
let has_selection = self.network_interface.selected_nodes().selected_layers(self.metadata()).next().is_some();
|
||||
let selection_all_visible = self
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers(self.metadata())
|
||||
.all(|layer| self.network_interface.is_visible(&layer.to_node(), &[]));
|
||||
let selection_all_locked = self
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers(self.metadata())
|
||||
.all(|layer| self.network_interface.is_locked(&layer.to_node(), &[]));
|
||||
|
||||
let widgets = vec![
|
||||
DropdownInput::new(blend_mode_menu_entries)
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
|
||||
@@ -3577,34 +3877,10 @@ impl DocumentMessageHandler {
|
||||
.tooltip_label("Fill Opacity")
|
||||
.widget_instance(),
|
||||
];
|
||||
let layers_panel_control_bar_left = Layout(vec![LayoutGroup::row(widgets)]);
|
||||
|
||||
let widgets = vec![
|
||||
IconButton::new(if selection_all_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if selection_all_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.tooltip_label(if selection_all_locked { "Unlock Selected" } else { "Lock Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedLocked))
|
||||
.on_update(|_| NodeGraphMessage::ToggleSelectedLocked.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
IconButton::new(if selection_all_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if selection_all_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if selection_all_visible { "Hide Selected" } else { "Show Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_update(|_| DocumentMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
];
|
||||
let layers_panel_control_bar_right = Layout(vec![LayoutGroup::row(widgets)]);
|
||||
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: layers_panel_control_bar_left,
|
||||
layout: Layout(vec![LayoutGroup::row(widgets)]),
|
||||
layout_target: LayoutTarget::LayersPanelControlLeftBar,
|
||||
});
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: layers_panel_control_bar_right,
|
||||
layout_target: LayoutTarget::LayersPanelControlRightBar,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn update_layers_panel_bottom_bar_widgets(&mut self, layers_panel_open: bool, responses: &mut VecDeque<Message>) {
|
||||
@@ -3619,6 +3895,31 @@ impl DocumentMessageHandler {
|
||||
let has_multiple_selection = selected_layers.next().is_some();
|
||||
for _ in selected_layers {}
|
||||
|
||||
// Visibility applies to every selected node, layer or not, while locking applies to layers
|
||||
let selection_all_visible = selected_nodes.selected_nodes().all(|node_id| self.network_interface.is_visible(node_id, &[]));
|
||||
let selection_all_locked = selected_nodes.selected_layers(self.metadata()).all(|layer| self.network_interface.is_locked(&layer.to_node(), &[]));
|
||||
|
||||
let widgets = vec![
|
||||
IconButton::new(if selection_all_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if selection_all_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if selection_all_visible { "Hide Selected" } else { "Show Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_update(|_| DocumentMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(!selected_nodes.has_selected_nodes())
|
||||
.widget_instance(),
|
||||
IconButton::new(if selection_all_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if selection_all_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.tooltip_label(if selection_all_locked { "Unlock Selected" } else { "Lock Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::ToggleSelectedLocked))
|
||||
.on_update(|_| NodeGraphMessage::ToggleSelectedLocked.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
];
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout(vec![LayoutGroup::row(widgets)]),
|
||||
layout_target: LayoutTarget::LayersPanelBottomLeftBar,
|
||||
});
|
||||
|
||||
let widgets = vec![
|
||||
PopoverButton::new()
|
||||
.icon("Node")
|
||||
@@ -3664,6 +3965,7 @@ impl DocumentMessageHandler {
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
})
|
||||
.drag_drop_kinds(DragDropKinds::Layers)
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
IconButton::new("NewLayer", 24)
|
||||
@@ -3671,18 +3973,21 @@ impl DocumentMessageHandler {
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::CreateEmptyFolder))
|
||||
.on_update(|_| DocumentMessage::CreateEmptyFolder.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DuplicateSelectedLayers.into())
|
||||
.drag_drop_kinds(DragDropKinds::LayersAndChainNodes)
|
||||
.disabled(!has_selection && selected_nodes.has_selected_nodes())
|
||||
.widget_instance(),
|
||||
IconButton::new("Trash", 24)
|
||||
.tooltip_label("Delete Selected")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DeleteSelectedLayers))
|
||||
.on_update(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.disabled(!has_selection)
|
||||
.drag_drop_kinds(DragDropKinds::LayersAndChainNodes)
|
||||
.disabled(!selected_nodes.has_selected_nodes())
|
||||
.widget_instance(),
|
||||
];
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout: Layout(vec![LayoutGroup::row(widgets)]),
|
||||
layout_target: LayoutTarget::LayersPanelBottomBar,
|
||||
layout_target: LayoutTarget::LayersPanelBottomRightBar,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4127,6 +4432,37 @@ mod document_message_handler_tests {
|
||||
assert!(selected_nodes.selected_layers_contains(layers[2], document.metadata()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn select_all_selects_every_node_in_the_graph_but_only_layers_outside_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.handle_message(DocumentMessage::DeselectAllLayers).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
editor.handle_message(DocumentMessage::SelectAllLayers).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let all_nodes: HashSet<_> = document.network_interface.document_network().nodes.keys().copied().collect();
|
||||
let selected: HashSet<_> = document.network_interface.selected_nodes().selected_nodes().copied().collect();
|
||||
assert!(
|
||||
all_nodes.iter().any(|node_id| !document.network_interface.is_layer(node_id, &[])),
|
||||
"The rectangle should bring non-layer nodes"
|
||||
);
|
||||
assert_eq!(selected, all_nodes, "In the graph, Select All should select every node");
|
||||
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: false }).await;
|
||||
editor.handle_message(DocumentMessage::SelectAllLayers).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let selected: Vec<_> = document.network_interface.selected_nodes().selected_nodes().copied().collect();
|
||||
assert!(!selected.is_empty(), "Outside the graph, Select All should select the layer");
|
||||
assert!(
|
||||
selected.iter().all(|node_id| document.network_interface.is_layer(node_id, &[])),
|
||||
"Outside the graph, Select All should select only layers"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_layer_rearrangement() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -4389,4 +4725,33 @@ mod document_message_handler_tests {
|
||||
.count();
|
||||
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn converting_to_an_infinite_canvas_adds_a_locked_background_at_the_bottom() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
location: DVec2::ZERO,
|
||||
dimensions: DVec2::splat(200.),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
})
|
||||
.await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::RemoveArtboards).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let network_interface = &document.network_interface;
|
||||
let root_layers: Vec<_> = LayerNodeIdentifier::ROOT_PARENT.children(document.metadata()).collect();
|
||||
assert!(root_layers.iter().all(|layer| !network_interface.is_artboard(&layer.to_node(), &[])), "No artboards should remain");
|
||||
assert_eq!(root_layers.len(), 2, "The artboard should become a plain layer above the background");
|
||||
assert_eq!(root_layers[0].children(document.metadata()).count(), 1, "The artboard's content should stay in its replacement layer");
|
||||
|
||||
let background = root_layers[1].to_node();
|
||||
assert_eq!(network_interface.display_name(&background, &[]), "Background");
|
||||
assert!(network_interface.is_locked(&background, &[]), "The background should be locked");
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -7,7 +7,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{get_clip_mode, new_background_layer};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
@@ -413,6 +413,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
return;
|
||||
}
|
||||
|
||||
// Each artboard becomes one plain layer in its place, so the root stack keeps this many layers
|
||||
let root_layer_count = LayerNodeIdentifier::ROOT_PARENT.children(network_interface.document_metadata()).count();
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: network_interface.all_artboards().iter().map(|layer_node| layer_node.to_node()).collect(),
|
||||
@@ -490,6 +493,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
});
|
||||
}
|
||||
|
||||
// Like a new infinite canvas document, the artwork sits on a white background instead of transparency
|
||||
new_background_layer(root_layer_count, responses);
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
@@ -19,4 +19,4 @@ pub(crate) use document_history::{CursorMoveError, DocumentHistory};
|
||||
#[doc(inline)]
|
||||
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use document_message_handler::{DocumentMessageContext, DocumentMessageHandler};
|
||||
pub use document_message_handler::{DocumentMessageContext, DocumentMessageHandler, SelectionParts};
|
||||
@@ -6,21 +6,22 @@ use glam::DVec2;
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum NavigationMessage {
|
||||
// Messages
|
||||
BeginCanvasPan,
|
||||
BeginCanvasPan { artwork_behind_graph: bool },
|
||||
BeginCanvasTilt { was_dispatched_from_menu: bool },
|
||||
BeginCanvasZoom,
|
||||
BeginCanvasZoom { artwork_behind_graph: bool },
|
||||
CanvasPan { delta: DVec2 },
|
||||
CanvasPanAbortPrepare { x_not_y_axis: bool },
|
||||
CanvasPanAbort { x_not_y_axis: bool },
|
||||
CanvasPanByViewportFraction { delta: DVec2 },
|
||||
CanvasPanMouseWheel { use_y_as_x: bool },
|
||||
CanvasPanMouseWheel { use_y_as_x: bool, artwork_behind_graph: bool },
|
||||
CanvasTiltResetAndZoomTo100Percent,
|
||||
CanvasTiltSet { angle_radians: f64 },
|
||||
CanvasZoomDecrease { center_on_mouse: bool },
|
||||
CanvasZoomIncrease { center_on_mouse: bool },
|
||||
CanvasZoomMouseWheel,
|
||||
CanvasZoomMouseWheel { artwork_behind_graph: bool },
|
||||
CanvasZoomSet { zoom_factor: f64 },
|
||||
CanvasFlip,
|
||||
EndArtworkBehindGraph,
|
||||
EndCanvasPTZ { abort_transform: bool },
|
||||
EndCanvasPTZWithClick { commit_key: Key },
|
||||
FitViewportToBounds { bounds: [DVec2; 2], prevent_zoom_past_100: bool },
|
||||
|
||||
@@ -31,6 +31,8 @@ pub struct NavigationMessageHandler {
|
||||
mouse_position: ViewportPosition,
|
||||
finish_operation_with_click: bool,
|
||||
abortable_pan_start: Option<f64>,
|
||||
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
||||
artwork_behind_graph: bool,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -46,6 +48,17 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
viewport,
|
||||
} = context;
|
||||
|
||||
// Until the drag or wheel scroll ends, act on the artwork as if the graph were closed
|
||||
if let NavigationMessage::BeginCanvasPan { artwork_behind_graph }
|
||||
| NavigationMessage::BeginCanvasZoom { artwork_behind_graph }
|
||||
| NavigationMessage::CanvasPanMouseWheel { artwork_behind_graph, .. }
|
||||
| NavigationMessage::CanvasZoomMouseWheel { artwork_behind_graph } = &message
|
||||
{
|
||||
self.artwork_behind_graph = *artwork_behind_graph && graph_view_overlay_open;
|
||||
}
|
||||
let graph_view_overlay_open = graph_view_overlay_open && !self.artwork_behind_graph;
|
||||
let wheel_scroll_on_artwork = self.artwork_behind_graph && matches!(message, NavigationMessage::CanvasPanMouseWheel { .. } | NavigationMessage::CanvasZoomMouseWheel { .. });
|
||||
|
||||
fn get_ptz<'a>(document_ptz: &'a PTZ, network_interface: &'a NodeNetworkInterface, graph_view_overlay_open: bool, breadcrumb_network_path: &[NodeId]) -> Option<&'a PTZ> {
|
||||
if !graph_view_overlay_open {
|
||||
Some(document_ptz)
|
||||
@@ -74,7 +87,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
let old_zoom = ptz.zoom();
|
||||
|
||||
match message {
|
||||
NavigationMessage::BeginCanvasPan => {
|
||||
NavigationMessage::BeginCanvasPan { .. } => {
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Grabbing });
|
||||
|
||||
HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]).send_layout(responses);
|
||||
@@ -89,9 +102,9 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
// If the node graph is open, prevent tilt and instead start panning
|
||||
// The node graph can't be tilted, so the tilt shortcut pans the artwork behind it instead
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NavigationMessage::BeginCanvasPan);
|
||||
responses.add(NavigationMessage::BeginCanvasPan { artwork_behind_graph: true });
|
||||
} else {
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Default });
|
||||
HintData(vec![
|
||||
@@ -110,7 +123,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
self.finish_operation_with_click = was_dispatched_from_menu;
|
||||
}
|
||||
}
|
||||
NavigationMessage::BeginCanvasZoom => {
|
||||
NavigationMessage::BeginCanvasZoom { .. } => {
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
@@ -174,7 +187,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
ptz.pan += transformed_delta;
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
}
|
||||
NavigationMessage::CanvasPanMouseWheel { use_y_as_x } => {
|
||||
NavigationMessage::CanvasPanMouseWheel { use_y_as_x, .. } => {
|
||||
// On Mac, the OS already converts Shift+scroll into horizontal scrolling
|
||||
let delta = if use_y_as_x && !Editor::environment().is_mac() {
|
||||
(ipp.mouse.scroll_delta.y, 0.).into()
|
||||
@@ -231,7 +244,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: new_scale });
|
||||
}
|
||||
NavigationMessage::CanvasZoomMouseWheel => {
|
||||
NavigationMessage::CanvasZoomMouseWheel { .. } => {
|
||||
let scroll = ipp.mouse.scroll_delta.scroll_delta();
|
||||
let mut zoom_factor = 1. + scroll.abs() * preferences.viewport_zoom_wheel_rate;
|
||||
if ipp.mouse.scroll_delta.y > 0. {
|
||||
@@ -291,6 +304,9 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
}
|
||||
NavigationMessage::EndArtworkBehindGraph => {
|
||||
self.artwork_behind_graph = false;
|
||||
}
|
||||
NavigationMessage::EndCanvasPTZ { abort_transform } => {
|
||||
let Some(ptz) = get_ptz_mut(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
log::error!("Could not get mutable PTZ in EndCanvasPTZ");
|
||||
@@ -323,6 +339,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
// Reset the navigation operation now that it's done
|
||||
self.navigation_operation = NavigationOperation::None;
|
||||
self.artwork_behind_graph = false;
|
||||
|
||||
// Send the final messages to close out the operation
|
||||
responses.add(EventMessage::CanvasTransformed);
|
||||
@@ -482,6 +499,11 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
self.mouse_position = ipp.mouse.position;
|
||||
}
|
||||
}
|
||||
|
||||
// Queued behind the wheel scroll's pan or zoom, which still need the artwork as their target
|
||||
if wheel_scroll_on_artwork {
|
||||
responses.add(NavigationMessage::EndArtworkBehindGraph);
|
||||
}
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
|
||||
@@ -3,6 +3,7 @@ mod document_node_derive;
|
||||
use super::node_properties::choice::enum_choice;
|
||||
use super::node_properties::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
@@ -33,6 +34,8 @@ pub struct NodePropertiesContext<'a> {
|
||||
pub document_name: &'a str,
|
||||
/// The node IDs whose Properties panel sections the user has collapsed.
|
||||
pub properties_panel_collapsed_sections: &'a [NodeId],
|
||||
/// The types a wire being dragged from an output could carry, so compatible inputs can be marked as drop targets.
|
||||
pub wire_in_progress_output_types: &'a [Type],
|
||||
}
|
||||
|
||||
impl NodePropertiesContext<'_> {
|
||||
@@ -128,6 +131,9 @@ pub struct DocumentNodeDefinition {
|
||||
/// Definition specific data. In order for the editor to access this data, the reference will be used.
|
||||
pub category: &'static str,
|
||||
|
||||
/// Name of the icon, from the frontend's icon registry, shown for this node in the node graph.
|
||||
pub icon: Option<&'static str>,
|
||||
|
||||
/// User-facing description of the node's functionality.
|
||||
pub description: Cow<'static, str>,
|
||||
|
||||
@@ -150,6 +156,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Custom Node",
|
||||
category: "General",
|
||||
icon: Some("NodeCustomNode"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
@@ -160,6 +167,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
category: "General",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(5), 0)],
|
||||
@@ -231,6 +239,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
category: "General",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(4), 0)],
|
||||
@@ -338,6 +347,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
category: "Vector",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
@@ -512,6 +522,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
category: "Vector",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
@@ -591,6 +602,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
category: "Web Request",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
@@ -626,6 +638,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Rasterize",
|
||||
category: "Raster",
|
||||
icon: Some("NodeRasterize"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
@@ -677,6 +690,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Extract",
|
||||
category: "",
|
||||
icon: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Extract,
|
||||
inputs: vec![NodeInput::type_default(concrete!(DocumentNode), true)],
|
||||
@@ -690,6 +704,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
category: "Text: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
@@ -762,6 +777,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Path",
|
||||
category: "Vector",
|
||||
icon: Some("NodePath"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
@@ -1589,6 +1605,13 @@ pub fn collect_node_descriptions() -> Vec<(String, String)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn collect_node_icons() -> Vec<(String, IconName)> {
|
||||
DOCUMENT_NODE_TYPES
|
||||
.iter()
|
||||
.filter_map(|(identifier, definition)| Some((identifier.serialized(), definition.icon?.to_string())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl DocumentNodeDefinition {
|
||||
/// Converts the [DocumentNodeDefinition] type to a [NodeTemplate], using the provided `input_override` and falling back to the default inputs.
|
||||
/// `input_override` does not have to be the correct length.
|
||||
|
||||
+2
@@ -38,6 +38,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
let NodeMetadata {
|
||||
display_name,
|
||||
category,
|
||||
icon,
|
||||
fields,
|
||||
description,
|
||||
properties,
|
||||
@@ -104,6 +105,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
..Default::default()
|
||||
},
|
||||
category,
|
||||
icon: *icon,
|
||||
description: Cow::Borrowed(description),
|
||||
properties: *properties,
|
||||
},
|
||||
|
||||
@@ -2,9 +2,9 @@ use super::utility_types::Direction;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector, RootNode};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::IVec2;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
@@ -61,6 +61,9 @@ pub enum NodeGraphMessage {
|
||||
input_connector: InputConnector,
|
||||
},
|
||||
DisconnectRootNode,
|
||||
SetRootNodeToRestore {
|
||||
root_node_to_restore: RootNode,
|
||||
},
|
||||
EnterNestedNetwork,
|
||||
DuplicateSelectedNodes,
|
||||
ExposeInput {
|
||||
@@ -94,10 +97,23 @@ pub enum NodeGraphMessage {
|
||||
node_id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
},
|
||||
ReorderChainNode {
|
||||
node_id: NodeId,
|
||||
MoveChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
layer: NodeId,
|
||||
insert_index: usize,
|
||||
},
|
||||
DuplicateChainNodes {
|
||||
node_ids: Vec<NodeId>,
|
||||
destination: Option<(NodeId, usize)>,
|
||||
select_copies: bool,
|
||||
},
|
||||
DuplicateNodesInFlow {
|
||||
node_ids: Vec<NodeId>,
|
||||
},
|
||||
PasteIntoChain {
|
||||
target: ChainInsertionPoint,
|
||||
copies: Vec<ChainNodeCopy>,
|
||||
},
|
||||
ReorderPinnedNode {
|
||||
node_id: NodeId,
|
||||
insert_index: usize,
|
||||
@@ -121,6 +137,18 @@ pub enum NodeGraphMessage {
|
||||
PointerOutsideViewport {
|
||||
shift: Key,
|
||||
},
|
||||
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
||||
WireHoverTick,
|
||||
/// Begins dragging a wire out of an input connector shown in the Properties panel.
|
||||
StartWireFromPropertiesPanel {
|
||||
input_connector: InputConnector,
|
||||
editor_position: DVec2,
|
||||
},
|
||||
/// Reports whether the wire in progress is over the Properties panel, and which input connector there it hovers (at its editor position).
|
||||
SetWirePropertiesPanelHover {
|
||||
hovering_panel: bool,
|
||||
target: Option<(InputConnector, DVec2)>,
|
||||
},
|
||||
ShakeNode,
|
||||
UpdateNodeGraphWidth,
|
||||
RemoveImport {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::node_properties;
|
||||
use super::utility_types::{BoxSelection, ContextMenuInformation, DragStart, FrontendNode};
|
||||
use crate::consts::GRID_SIZE;
|
||||
use crate::messages::clipboard::utility_types::ClipboardItem;
|
||||
use crate::consts::{GRID_SIZE, WIRE_DRAG_AUTO_PAN_DELAY_MILLISECONDS, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
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::document_message_handler::navigation_controls;
|
||||
@@ -9,14 +8,17 @@ use crate::messages::portfolio::document::graph_operation::utility_types::Modify
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{
|
||||
DefinitionIdentifier, NodePropertiesContext, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeGraphErrorDiagnostic, WireInProgressAnchor};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, Previewing};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelEntry};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
self, FlowType, InputConnector, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, type_feeds_connector,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::edit_target::{EditTarget, ResolvedEditTarget};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||
@@ -46,6 +48,7 @@ pub struct NodeGraphMessageContext<'a> {
|
||||
pub navigation_handler: &'a NavigationMessageHandler,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub layers_panel_open: bool,
|
||||
pub tool_edit_target: &'a EditTarget,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
@@ -83,6 +86,20 @@ pub struct NodeGraphMessageHandler {
|
||||
pub wire_in_progress_to_connector: Option<DVec2>,
|
||||
/// The data type determining the color of the wire being dragged.
|
||||
pub wire_in_progress_type: FrontendGraphDataType,
|
||||
/// The connector the wire being dragged is anchored at.
|
||||
pub wire_in_progress_anchor: Option<WireInProgressAnchor>,
|
||||
/// The Properties panel input connector hovered by a wire dragged from an output, with its position in viewport coordinates.
|
||||
wire_in_progress_properties_target: Option<(InputConnector, DVec2)>,
|
||||
/// Whether the pointer dragging a wire is over the Properties panel, where graph connectors beneath it can't be hovered.
|
||||
wire_in_progress_hovering_properties_panel: bool,
|
||||
/// When the pointer dragging a wire last left the graph, in milliseconds, to delay auto-panning.
|
||||
wire_left_viewport_time: Option<u64>,
|
||||
/// The node hovered by a wire dragged from an output and when the hover began, in milliseconds.
|
||||
wire_hovered_node: Option<(NodeId, u64)>,
|
||||
/// The node expanded for the wire in progress and the indices of the inputs it temporarily exposed.
|
||||
wire_expanded_node: Option<(NodeId, Vec<usize>)>,
|
||||
/// Whether [`NodeGraphMessage::WireHoverTick`] is subscribed to animation frames.
|
||||
wire_hover_tick_subscribed: bool,
|
||||
/// State for the context menus.
|
||||
pub context_menu: Option<ContextMenuInformation>,
|
||||
/// Index of selected node to be deselected on pointer up when shift clicking an already selected node
|
||||
@@ -120,6 +137,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
navigation_handler,
|
||||
preferences,
|
||||
layers_panel_open,
|
||||
tool_edit_target,
|
||||
viewport,
|
||||
} = context;
|
||||
|
||||
@@ -251,16 +269,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
network_interface.create_wire(&output_connector, &input_connector, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::Copy => {
|
||||
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
|
||||
// Collect the selected nodes
|
||||
let new_ids = &all_selected_nodes.iter().enumerate().map(|(new, old)| (*old, NodeId(new as u64))).collect();
|
||||
let copied_nodes = network_interface.copy_nodes(new_ids, selection_network_path).collect::<Vec<_>>();
|
||||
|
||||
responses.add(ClipboardMessage::WriteItems {
|
||||
items: vec![ClipboardItem::Nodes(copied_nodes)],
|
||||
});
|
||||
}
|
||||
// Copies and cuts the same way as anywhere else
|
||||
NodeGraphMessage::Copy => responses.add(ClipboardMessage::CopyLayers),
|
||||
NodeGraphMessage::CreateNodeInLayerNoTransaction { node_type, layer } => {
|
||||
let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) else {
|
||||
return;
|
||||
@@ -322,36 +332,29 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
});
|
||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
||||
// Only auto connect to the dragged wire if the node is being added to the currently opened network
|
||||
if let Some(output_connector_position) = self.wire_in_progress_from_connector {
|
||||
let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else {
|
||||
log::error!("Could not get network metadata in CreateNodeFromContextMenu");
|
||||
return;
|
||||
};
|
||||
let output_connector_position_viewport = network_metadata
|
||||
.persistent_metadata
|
||||
.navigation_metadata
|
||||
.node_graph_to_viewport
|
||||
.transform_point2(output_connector_position);
|
||||
let Some(output_connector) = &network_interface.output_connector_from_click(output_connector_position_viewport, breadcrumb_network_path) else {
|
||||
log::error!("Could not get output from connector start");
|
||||
return;
|
||||
};
|
||||
|
||||
// Ensure connection is to correct input of new node. If it does not have an input then do not connect
|
||||
if let Some((input_index, _)) = node_template.inputs.iter().enumerate().find(|(_, input)| input.is_exposed()) {
|
||||
responses.add(NodeGraphMessage::CreateWire {
|
||||
output_connector: *output_connector,
|
||||
input_connector: InputConnector::node_at_index(node_id, input_index),
|
||||
});
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
if let Some(anchor) = self.wire_in_progress_anchor {
|
||||
match anchor {
|
||||
// Connect to the first exposed input of the new node, if it has one
|
||||
WireInProgressAnchor::Output(output_connector) => {
|
||||
if let Some((input_index, _)) = node_template.inputs.iter().enumerate().find(|(_, input)| input.is_exposed()) {
|
||||
responses.add(NodeGraphMessage::CreateWire {
|
||||
output_connector,
|
||||
input_connector: InputConnector::node_at_index(node_id, input_index),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
// Feed the anchored input from the primary output of the new node
|
||||
WireInProgressAnchor::Input { input_connector, .. } => {
|
||||
responses.add(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(node_id),
|
||||
input_connector,
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
|
||||
self.wire_in_progress_from_connector = None;
|
||||
self.wire_in_progress_to_connector = None;
|
||||
self.wire_in_progress_type = FrontendGraphDataType::General;
|
||||
}
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None });
|
||||
self.end_wire_in_progress(network_interface, selection_network_path, responses);
|
||||
responses.add(FrontendMessage::UpdateContextMenuInformation {
|
||||
context_menu_information: self.context_menu.clone(),
|
||||
});
|
||||
@@ -367,10 +370,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
input_connector,
|
||||
});
|
||||
}
|
||||
NodeGraphMessage::Cut => {
|
||||
responses.add(NodeGraphMessage::Copy);
|
||||
responses.add(NodeGraphMessage::DeleteSelectedNodes { delete_children: true });
|
||||
}
|
||||
NodeGraphMessage::Cut => responses.add(ClipboardMessage::CutLayers),
|
||||
NodeGraphMessage::DeleteNodes { node_ids, delete_children } => {
|
||||
// Detect stroke/fill proto nodes among the doomed nodes before they're gone so the tool control bars can re-sync
|
||||
let stroke = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||
@@ -411,10 +411,11 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
NodeGraphMessage::DisconnectRootNode => {
|
||||
network_interface.start_previewing_without_restore(selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::DuplicateSelectedNodes => {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
Self::duplicate_selected_nodes(network_interface, selection_network_path, responses);
|
||||
NodeGraphMessage::SetRootNodeToRestore { root_node_to_restore } => {
|
||||
network_interface.set_root_node_to_restore(root_node_to_restore, selection_network_path);
|
||||
}
|
||||
// Duplicates in the flow like everywhere else
|
||||
NodeGraphMessage::DuplicateSelectedNodes => responses.add(DocumentMessage::DuplicateSelectedLayers),
|
||||
NodeGraphMessage::EnterNestedNetwork => {
|
||||
// Do not enter the nested network if the node was dragged
|
||||
if self.node_has_moved_in_drag {
|
||||
@@ -731,8 +732,54 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
NodeGraphMessage::MoveNodeToChainStart { node_id, parent } => {
|
||||
network_interface.move_node_to_chain_start(&node_id, parent, selection_network_path, false);
|
||||
}
|
||||
NodeGraphMessage::ReorderChainNode { node_id, insert_index } => {
|
||||
network_interface.reorder_chain_node(node_id, insert_index, selection_network_path);
|
||||
NodeGraphMessage::PasteIntoChain { target, copies } => {
|
||||
let new_nodes = network_interface.paste_into_chain(target, copies, selection_network_path);
|
||||
responses.add(NodeGraphMessage::SelectedNodesAdd { nodes: new_nodes });
|
||||
}
|
||||
NodeGraphMessage::DuplicateChainNodes { node_ids, destination, select_copies } => {
|
||||
let copies = network_interface.duplicate_chain_nodes(&node_ids, destination, selection_network_path);
|
||||
if select_copies {
|
||||
responses.add(NodeGraphMessage::SelectedNodesAdd { nodes: copies });
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::DuplicateNodesInFlow { node_ids } => {
|
||||
let mut copies = Vec::new();
|
||||
let mut loose_nodes = Vec::new();
|
||||
for node_id in node_ids {
|
||||
match network_interface.duplicate_node_in_flow(&node_id, selection_network_path) {
|
||||
Some(copy) => copies.push(copy),
|
||||
None => loose_nodes.push(node_id),
|
||||
}
|
||||
}
|
||||
|
||||
// Nodes in no flow get copies offset from their originals, keeping the wires among them, and a layer brings its content along
|
||||
if !loose_nodes.is_empty() {
|
||||
let loose_layers = loose_nodes
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|node_id| network_interface.is_layer(node_id, selection_network_path))
|
||||
.collect::<Vec<_>>();
|
||||
let layer_content = network_interface.upstream_flow_back_from_nodes(loose_layers, selection_network_path, FlowType::LayerChildrenUpstreamFlow);
|
||||
let copy_ids = loose_nodes
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(layer_content)
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, node_id)| (node_id, NodeId(index as u64)))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
let nodes = network_interface.copy_nodes(©_ids, selection_network_path).collect::<Vec<_>>();
|
||||
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
|
||||
copies.extend(loose_nodes.iter().filter_map(|node_id| new_ids.get(copy_ids.get(node_id)?)));
|
||||
network_interface.insert_node_group(nodes, new_ids, selection_network_path);
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesAdd { nodes: copies });
|
||||
}
|
||||
NodeGraphMessage::MoveChainNodes { node_ids, layer, insert_index } => {
|
||||
network_interface.move_chain_nodes(&node_ids, layer, insert_index, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::ReorderPinnedNode { node_id, insert_index } => {
|
||||
network_interface.reorder_pinned_node(node_id, insert_index, selection_network_path);
|
||||
@@ -808,12 +855,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
// Abort dragging a wire
|
||||
if self.wire_in_progress_from_connector.is_some() {
|
||||
self.wire_in_progress_from_connector = None;
|
||||
self.wire_in_progress_to_connector = None;
|
||||
self.wire_in_progress_type = FrontendGraphDataType::General;
|
||||
|
||||
self.end_wire_in_progress(network_interface, selection_network_path, responses);
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -915,14 +958,11 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
// Since the user is clicking elsewhere in the graph, ensure the add nodes list is closed
|
||||
if self.context_menu.is_some() {
|
||||
self.context_menu = None;
|
||||
self.wire_in_progress_from_connector = None;
|
||||
self.wire_in_progress_to_connector = None;
|
||||
self.wire_in_progress_type = FrontendGraphDataType::General;
|
||||
self.end_wire_in_progress(network_interface, selection_network_path, responses);
|
||||
|
||||
responses.add(FrontendMessage::UpdateContextMenuInformation {
|
||||
context_menu_information: self.context_menu.clone(),
|
||||
});
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None });
|
||||
}
|
||||
|
||||
// Toggle visibility of clicked node and return
|
||||
@@ -948,21 +988,38 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.preview_on_mouse_up = Some(clicked_node);
|
||||
}
|
||||
|
||||
// Begin moving an existing wire
|
||||
if let Some(clicked_input) = &clicked_input {
|
||||
if let Some(clicked_input) = clicked_input {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
self.initial_disconnecting = true;
|
||||
self.disconnecting = Some(*clicked_input);
|
||||
|
||||
let output_connector = if *clicked_input == InputConnector::Export(0) {
|
||||
let output_connector = if clicked_input == InputConnector::Export(0) {
|
||||
network_interface.root_node(breadcrumb_network_path).map(|root_node| root_node.to_connector())
|
||||
} else {
|
||||
network_interface.upstream_output_connector(clicked_input, breadcrumb_network_path)
|
||||
network_interface.upstream_output_connector(&clicked_input, breadcrumb_network_path)
|
||||
};
|
||||
let Some(output_connector) = output_connector else { return };
|
||||
self.wire_in_progress_from_connector = network_interface.output_position(&output_connector, breadcrumb_network_path);
|
||||
|
||||
self.wire_in_progress_type = network_interface.output_type(&output_connector, breadcrumb_network_path).displayed_type();
|
||||
// Begin moving an existing wire
|
||||
if let Some(output_connector) = output_connector {
|
||||
self.initial_disconnecting = true;
|
||||
self.disconnecting = Some(clicked_input);
|
||||
|
||||
self.wire_in_progress_from_connector = network_interface.output_position(&output_connector, breadcrumb_network_path);
|
||||
self.wire_in_progress_type = network_interface.output_type(&output_connector, breadcrumb_network_path).displayed_type();
|
||||
self.wire_in_progress_anchor = Some(WireInProgressAnchor::Output(output_connector));
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
// Begin creating a new wire backward from an unconnected input
|
||||
else {
|
||||
self.initial_disconnecting = false;
|
||||
|
||||
self.wire_in_progress_from_connector = network_interface.input_position(&clicked_input, selection_network_path);
|
||||
self.wire_in_progress_type = network_interface.input_type(&clicked_input, selection_network_path).displayed_type();
|
||||
self.wire_in_progress_anchor = Some(WireInProgressAnchor::Input {
|
||||
input_connector: clicked_input,
|
||||
properties_panel_position: None,
|
||||
});
|
||||
}
|
||||
|
||||
self.update_node_graph_hints(responses);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -974,6 +1031,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.wire_in_progress_from_connector = network_interface.output_position(&clicked_output, selection_network_path);
|
||||
let output_type = network_interface.output_type(&clicked_output, breadcrumb_network_path);
|
||||
self.wire_in_progress_type = output_type.displayed_type();
|
||||
self.wire_in_progress_anchor = Some(WireInProgressAnchor::Output(clicked_output));
|
||||
log::debug!("[wire-drag] Started wire from output {clicked_output:?}, refreshing the Properties panel");
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
|
||||
self.update_node_graph_hints(responses);
|
||||
return;
|
||||
@@ -1066,9 +1126,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
return;
|
||||
};
|
||||
|
||||
// Auto-panning
|
||||
// Auto-panning, except while a wire is dragged over the Properties panel
|
||||
let messages = [NodeGraphMessage::PointerOutsideViewport { shift }.into(), NodeGraphMessage::PointerMove { shift }.into()];
|
||||
self.auto_panning.setup_by_mouse_position(ipp, viewport, &messages, responses);
|
||||
if self.wire_in_progress_hovering_properties_panel {
|
||||
self.auto_panning.stop(&messages, responses);
|
||||
} else {
|
||||
self.auto_panning.setup_by_mouse_position(ipp, viewport, &messages, responses);
|
||||
}
|
||||
|
||||
// Restart the wire's auto-panning delay whenever it comes back over the graph or onto the Properties panel
|
||||
let pointer_in_viewport = ipp.mouse.position.cmpge(DVec2::ZERO).all() && ipp.mouse.position.cmple(viewport.size().into_dvec2()).all();
|
||||
if pointer_in_viewport || self.wire_in_progress_hovering_properties_panel {
|
||||
self.wire_left_viewport_time = None;
|
||||
}
|
||||
|
||||
let viewport_location = ipp.mouse.position;
|
||||
let point = network_metadata
|
||||
@@ -1079,74 +1149,89 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
.transform_point2(viewport_location);
|
||||
|
||||
if self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none() {
|
||||
let to_connector = network_interface.input_connector_from_click(ipp.mouse.position, selection_network_path);
|
||||
if let Some(to_connector) = &to_connector {
|
||||
let Some(input_position) = network_interface.input_position(to_connector, selection_network_path) else {
|
||||
log::error!("Could not get input position for connector: {to_connector:?}");
|
||||
return;
|
||||
};
|
||||
self.wire_in_progress_to_connector = Some(input_position);
|
||||
}
|
||||
// Not hovering over a node input or node output, update with the mouse position.
|
||||
else {
|
||||
self.wire_in_progress_to_connector = Some(point);
|
||||
// Disconnect if the wire was previously connected to an input
|
||||
if let Some(disconnecting) = &self.disconnecting {
|
||||
let mut disconnect_root_node = false;
|
||||
if let Previewing::Yes { root_node_to_restore } = network_interface.previewing(selection_network_path)
|
||||
&& root_node_to_restore.is_some()
|
||||
&& *disconnecting == InputConnector::Export(0)
|
||||
{
|
||||
disconnect_root_node = true;
|
||||
}
|
||||
if disconnect_root_node {
|
||||
responses.add(NodeGraphMessage::DisconnectRootNode);
|
||||
} else {
|
||||
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
|
||||
}
|
||||
// Update the frontend that the node is disconnected
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
self.disconnecting = None;
|
||||
}
|
||||
}
|
||||
let viewport_to_node_graph = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse();
|
||||
|
||||
if let (Some(wire_in_progress_from_connector), Some(wire_in_progress_to_connector)) = (self.wire_in_progress_from_connector, self.wire_in_progress_to_connector) {
|
||||
// If performance is a concern this can be stored as a field in the wire_in_progress_from/to_connector struct, and updated when snapping to an output
|
||||
let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else {
|
||||
return;
|
||||
};
|
||||
let from_connector_viewport = network_metadata
|
||||
.persistent_metadata
|
||||
.navigation_metadata
|
||||
.node_graph_to_viewport
|
||||
.transform_point2(wire_in_progress_from_connector);
|
||||
let from_connector_is_layer = network_interface
|
||||
.output_connector_from_click(from_connector_viewport, selection_network_path)
|
||||
.is_some_and(|output_connector| {
|
||||
if let OutputConnector::Node { node_id, .. } = output_connector {
|
||||
network_interface.is_layer(&node_id, selection_network_path)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
let to_connector_is_layer = to_connector.is_some_and(|to_connector| {
|
||||
if let InputConnector::Node { node_id, input_index } = to_connector {
|
||||
input_index == 0 && network_interface.is_layer(&node_id, selection_network_path)
|
||||
} else {
|
||||
false
|
||||
// Layer stack connectors leave the wire vertically
|
||||
let is_layer_output =
|
||||
|output_connector: &OutputConnector| matches!(output_connector, OutputConnector::Node { node_id, .. } if network_interface.is_layer(node_id, selection_network_path));
|
||||
let is_layer_stack_input =
|
||||
|input_connector: &InputConnector| matches!(input_connector, InputConnector::Node { node_id, input_index: 0 } if network_interface.is_layer(node_id, selection_network_path));
|
||||
|
||||
// Only a wire dragged from an output expands the nodes it hovers
|
||||
let mut wire_hovered_node = None;
|
||||
|
||||
// Wire endpoints ordered from output to input, plus whether each one is a layer stack connector
|
||||
let wire_endpoints = match self.wire_in_progress_anchor {
|
||||
// Dragging backward from an input, so snap the loose end to an output under the pointer
|
||||
Some(WireInProgressAnchor::Input {
|
||||
input_connector,
|
||||
properties_panel_position,
|
||||
}) => {
|
||||
// An anchor in the Properties panel stays put on screen while the graph may pan beneath it
|
||||
if let Some(properties_panel_position) = properties_panel_position {
|
||||
self.wire_in_progress_from_connector = Some(viewport_to_node_graph.transform_point2(properties_panel_position));
|
||||
}
|
||||
});
|
||||
let vector_wire = build_vector_wire(
|
||||
wire_in_progress_from_connector,
|
||||
wire_in_progress_to_connector,
|
||||
from_connector_is_layer,
|
||||
to_connector_is_layer,
|
||||
GraphWireStyle::Direct,
|
||||
);
|
||||
let path_string = vector_wire.to_svg();
|
||||
|
||||
let hovered_output = (!self.wire_in_progress_hovering_properties_panel)
|
||||
.then(|| network_interface.output_connector_from_click(viewport_location, selection_network_path))
|
||||
.flatten();
|
||||
let hovered_output_position = hovered_output.and_then(|output_connector| network_interface.output_position(&output_connector, selection_network_path));
|
||||
self.wire_in_progress_to_connector = Some(hovered_output_position.unwrap_or(point));
|
||||
|
||||
let input_is_layer = properties_panel_position.is_none() && is_layer_stack_input(&input_connector);
|
||||
let output_is_layer = hovered_output.as_ref().is_some_and(is_layer_output);
|
||||
self.wire_in_progress_to_connector
|
||||
.zip(self.wire_in_progress_from_connector)
|
||||
.map(|(output_position, input_position)| (output_position, input_position, output_is_layer, input_is_layer))
|
||||
}
|
||||
// Dragging forward from an output, so snap the loose end to an input under the pointer or in the Properties panel
|
||||
Some(WireInProgressAnchor::Output(output_connector)) => {
|
||||
let hovered_input = (!self.wire_in_progress_hovering_properties_panel)
|
||||
.then(|| network_interface.input_connector_from_click(viewport_location, selection_network_path))
|
||||
.flatten();
|
||||
let hovered_input_position = hovered_input.and_then(|input_connector| network_interface.input_position(&input_connector, selection_network_path));
|
||||
let properties_target_position = self.wire_in_progress_properties_target.map(|(_, position)| viewport_to_node_graph.transform_point2(position));
|
||||
self.wire_in_progress_to_connector = Some(properties_target_position.or(hovered_input_position).unwrap_or(point));
|
||||
|
||||
// Disconnect if the wire was previously connected to an input
|
||||
if hovered_input.is_none()
|
||||
&& let Some(disconnecting) = self.disconnecting.take()
|
||||
{
|
||||
let disconnect_root_node =
|
||||
disconnecting == InputConnector::Export(0) && matches!(network_interface.previewing(selection_network_path), Previewing::Yes { root_node_to_restore: Some(_) });
|
||||
if disconnect_root_node {
|
||||
responses.add(NodeGraphMessage::DisconnectRootNode);
|
||||
} else {
|
||||
responses.add(NodeGraphMessage::DisconnectInput { input_connector: disconnecting });
|
||||
}
|
||||
|
||||
// Update the frontend that the node is disconnected
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
|
||||
// Input connectors stick out past their node's edge, so hovering one counts as hovering its node
|
||||
wire_hovered_node = (!self.wire_in_progress_hovering_properties_panel)
|
||||
.then(|| {
|
||||
let hovered_input_node = hovered_input.and_then(|input_connector| input_connector.node_id());
|
||||
hovered_input_node.or_else(|| network_interface.node_from_click(viewport_location, selection_network_path))
|
||||
})
|
||||
.flatten()
|
||||
.filter(|node_id| Some(*node_id) != output_connector.node_id());
|
||||
|
||||
let output_is_layer = is_layer_output(&output_connector);
|
||||
let input_is_layer = properties_target_position.is_none() && hovered_input.as_ref().is_some_and(is_layer_stack_input);
|
||||
self.wire_in_progress_from_connector
|
||||
.zip(self.wire_in_progress_to_connector)
|
||||
.map(|(output_position, input_position)| (output_position, input_position, output_is_layer, input_is_layer))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
if let Some((output_position, input_position, output_is_layer, input_is_layer)) = wire_endpoints {
|
||||
let vector_wire = build_vector_wire(output_position, input_position, output_is_layer, input_is_layer, GraphWireStyle::Direct);
|
||||
let wire_path = WirePath {
|
||||
path_string,
|
||||
path_string: vector_wire.to_svg(),
|
||||
data_type: self.wire_in_progress_type,
|
||||
thick: false,
|
||||
dashed: false,
|
||||
@@ -1155,6 +1240,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
};
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: Some(wire_path) });
|
||||
}
|
||||
|
||||
self.set_wire_hovered_node(wire_hovered_node.map(|node_id| (node_id, ipp.time)), network_interface, selection_network_path, responses);
|
||||
} else if let Some((drag_start, dragged)) = &mut self.drag_start {
|
||||
if drag_start.start_x != point.x || drag_start.start_y != point.y {
|
||||
*dragged = true;
|
||||
@@ -1271,44 +1358,59 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
.node_graph_to_viewport
|
||||
.inverse()
|
||||
.transform_point2(ipp.mouse.position);
|
||||
// Disconnect if the wire was previously connected to an input
|
||||
if let (Some(wire_in_progress_from_connector), Some(wire_in_progress_to_connector)) = (self.wire_in_progress_from_connector, self.wire_in_progress_to_connector) {
|
||||
// Check if dragged connector is reconnected to another input
|
||||
if let (Some(anchor), Some(wire_in_progress_to_connector)) = (self.wire_in_progress_anchor, self.wire_in_progress_to_connector) {
|
||||
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
||||
let from_connector_viewport = node_graph_to_viewport.transform_point2(wire_in_progress_from_connector);
|
||||
let to_connector_viewport = node_graph_to_viewport.transform_point2(wire_in_progress_to_connector);
|
||||
let output_connector = network_interface.output_connector_from_click(from_connector_viewport, selection_network_path);
|
||||
let input_connector = network_interface.input_connector_from_click(to_connector_viewport, selection_network_path);
|
||||
let over_graph = !self.wire_in_progress_hovering_properties_panel;
|
||||
|
||||
if let (Some(output_connector), Some(input_connector)) = (&output_connector, &input_connector) {
|
||||
responses.add(NodeGraphMessage::CreateWire {
|
||||
input_connector: *input_connector,
|
||||
output_connector: *output_connector,
|
||||
});
|
||||
// Resolve the loose end of the wire to the connector it was released on
|
||||
let (output_connector, input_connector) = match anchor {
|
||||
WireInProgressAnchor::Output(output_connector) => {
|
||||
let properties_target = self.wire_in_progress_properties_target.map(|(input_connector, _)| input_connector);
|
||||
let hovered_input = over_graph
|
||||
.then(|| network_interface.input_connector_from_click(to_connector_viewport, selection_network_path))
|
||||
.flatten();
|
||||
(Some(output_connector), properties_target.or(hovered_input))
|
||||
}
|
||||
WireInProgressAnchor::Input { input_connector, .. } => {
|
||||
let hovered_output = over_graph
|
||||
.then(|| network_interface.output_connector_from_click(to_connector_viewport, selection_network_path))
|
||||
.flatten();
|
||||
(hovered_output, Some(input_connector))
|
||||
}
|
||||
};
|
||||
|
||||
log::debug!(
|
||||
"[wire-drag] Released with anchor {anchor:?}, properties target {:?}, over graph {over_graph}, resolved {output_connector:?} -> {input_connector:?}",
|
||||
self.wire_in_progress_properties_target
|
||||
);
|
||||
|
||||
// Collapse now rather than when the wire ends, since the node creation menu can keep the wire alive
|
||||
let connected_input = output_connector.and(input_connector);
|
||||
self.collapse_wire_expanded_node(connected_input, network_interface, selection_network_path, responses);
|
||||
self.set_wire_hovered_node(None, network_interface, selection_network_path, responses);
|
||||
|
||||
if let (Some(output_connector), Some(input_connector)) = (output_connector, input_connector) {
|
||||
responses.add(NodeGraphMessage::CreateWire { output_connector, input_connector });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
} else if !self.initial_disconnecting
|
||||
&& input_connector.is_none()
|
||||
&& let Some(output_connector) = output_connector
|
||||
{
|
||||
}
|
||||
// Released over empty graph space, so offer to create a node to connect the wire to
|
||||
else if !self.initial_disconnecting && over_graph {
|
||||
// If the add node menu is already open, we don't want to open it again
|
||||
if self.context_menu.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the output types from the network interface
|
||||
let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else {
|
||||
warn!("No network_metadata");
|
||||
return;
|
||||
};
|
||||
|
||||
let appear_right_of_mouse = if ipp.mouse.position.x > viewport.size().y() - 173. { -173. } else { 0. };
|
||||
let appear_right_of_mouse = if ipp.mouse.position.x > viewport.size().x() - 173. { -173. } else { 0. };
|
||||
let appear_above_mouse = if ipp.mouse.position.y > viewport.size().y() - 34. { -34. } else { 0. };
|
||||
let node_graph_shift = DVec2::new(appear_right_of_mouse, appear_above_mouse) / network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.matrix2.x_axis.x;
|
||||
let node_graph_shift = DVec2::new(appear_right_of_mouse, appear_above_mouse) / node_graph_to_viewport.matrix2.x_axis.x;
|
||||
|
||||
let compatible_type = network_interface.output_type(&output_connector, selection_network_path).add_node_string();
|
||||
// The node catalog filters by input type, so a wire from an input isn't filtered
|
||||
let compatible_type = match anchor {
|
||||
WireInProgressAnchor::Output(output_connector) => network_interface.output_type(&output_connector, selection_network_path).add_node_string(),
|
||||
WireInProgressAnchor::Input { .. } => None,
|
||||
};
|
||||
|
||||
self.context_menu = Some(ContextMenuInformation {
|
||||
context_menu_coordinates: (point + node_graph_shift).as_ivec2().into(),
|
||||
@@ -1319,6 +1421,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(FrontendMessage::UpdateContextMenuInformation {
|
||||
context_menu_information: self.context_menu.clone(),
|
||||
});
|
||||
// Remove the drop target highlights while the wire waits on the menu
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1483,29 +1587,79 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.duplicated_in_drag = false;
|
||||
self.box_selection_start = None;
|
||||
|
||||
self.wire_in_progress_from_connector = None;
|
||||
self.wire_in_progress_to_connector = None;
|
||||
self.wire_in_progress_type = FrontendGraphDataType::General;
|
||||
self.end_wire_in_progress(network_interface, selection_network_path, responses);
|
||||
|
||||
self.reordering_export = None;
|
||||
self.reordering_import = None;
|
||||
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None });
|
||||
responses.add(FrontendMessage::UpdateBox { box_selection: None });
|
||||
responses.add(FrontendMessage::UpdateImportReorderIndex { index: None });
|
||||
responses.add(FrontendMessage::UpdateExportReorderIndex { index: None });
|
||||
self.update_node_graph_hints(responses);
|
||||
}
|
||||
NodeGraphMessage::PointerOutsideViewport { shift } => {
|
||||
if self.drag_start.is_some() || self.box_selection_start.is_some() || (self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none()) {
|
||||
let wiring_over_graph = self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none() && !self.wire_in_progress_hovering_properties_panel;
|
||||
if self.drag_start.is_some() || self.box_selection_start.is_some() {
|
||||
let _ = self.auto_panning.shift_viewport(ipp, viewport, responses);
|
||||
} else if wiring_over_graph {
|
||||
// A wire only pans once it lingers beyond the edge, so passing over to another panel doesn't pan
|
||||
let left_viewport_time = *self.wire_left_viewport_time.get_or_insert(ipp.time);
|
||||
if ipp.time.saturating_sub(left_viewport_time) >= WIRE_DRAG_AUTO_PAN_DELAY_MILLISECONDS {
|
||||
let _ = self.auto_panning.shift_viewport(ipp, viewport, responses);
|
||||
}
|
||||
} else {
|
||||
// Auto-panning
|
||||
let messages = [NodeGraphMessage::PointerOutsideViewport { shift }.into(), NodeGraphMessage::PointerMove { shift }.into()];
|
||||
self.auto_panning.stop(&messages, responses);
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::WireHoverTick => {
|
||||
self.expand_wire_hovered_node_after_delay(ipp.time, network_interface, selection_network_path, responses);
|
||||
}
|
||||
NodeGraphMessage::StartWireFromPropertiesPanel { input_connector, editor_position } => {
|
||||
if self.wire_in_progress_anchor.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else {
|
||||
log::error!("Could not get network metadata in StartWireFromPropertiesPanel");
|
||||
return;
|
||||
};
|
||||
|
||||
// Dragging out of the Properties panel dismisses any open node creation menu
|
||||
if self.context_menu.take().is_some() {
|
||||
responses.add(FrontendMessage::UpdateContextMenuInformation { context_menu_information: None });
|
||||
}
|
||||
|
||||
let viewport_position: DVec2 = (viewport.logical(editor_position) - viewport.offset()).into();
|
||||
let viewport_to_node_graph = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse();
|
||||
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
self.initial_disconnecting = false;
|
||||
self.disconnecting = None;
|
||||
|
||||
self.wire_in_progress_from_connector = Some(viewport_to_node_graph.transform_point2(viewport_position));
|
||||
self.wire_in_progress_type = network_interface.input_type(&input_connector, selection_network_path).displayed_type();
|
||||
self.wire_in_progress_anchor = Some(WireInProgressAnchor::Input {
|
||||
input_connector,
|
||||
properties_panel_position: Some(viewport_position),
|
||||
});
|
||||
self.wire_in_progress_hovering_properties_panel = true;
|
||||
|
||||
self.update_node_graph_hints(responses);
|
||||
}
|
||||
NodeGraphMessage::SetWirePropertiesPanelHover { hovering_panel, target } => {
|
||||
log::debug!("[wire-drag] Hover report: over panel {hovering_panel}, target {target:?}, anchor {:?}", self.wire_in_progress_anchor);
|
||||
let Some(anchor) = self.wire_in_progress_anchor else { return };
|
||||
|
||||
self.wire_in_progress_hovering_properties_panel = hovering_panel;
|
||||
|
||||
// Only a wire dragged from an output can be dropped onto a Properties panel input
|
||||
self.wire_in_progress_properties_target = match anchor {
|
||||
WireInProgressAnchor::Output(_) => target.map(|(input_connector, editor_position)| (input_connector, (viewport.logical(editor_position) - viewport.offset()).into())),
|
||||
WireInProgressAnchor::Input { .. } => None,
|
||||
};
|
||||
}
|
||||
NodeGraphMessage::ShakeNode => {
|
||||
let Some((drag_start, _)) = &mut self.drag_start else {
|
||||
log::error!("Drag start should be initialized when shaking a node");
|
||||
@@ -1557,6 +1711,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
|
||||
let previewing = network_interface.previewing(selection_network_path);
|
||||
for selected_node in &all_selected_nodes {
|
||||
// Handle inputs of selected node
|
||||
for input_index in 0..network_interface.number_of_inputs(selected_node, selection_network_path) {
|
||||
@@ -1600,6 +1755,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
// Handle reconnection
|
||||
// Find first non selected upstream node by primary flow
|
||||
if let Some(first_deselected_upstream_output) = first_deselected_upstream_output {
|
||||
// While previewing, the export's eventual return to this node is a connection too, so it moves upstream as well
|
||||
if let Previewing::Yes {
|
||||
root_node_to_restore: Some(root_node_to_restore),
|
||||
} = previewing && root_node_to_restore.to_connector() == OutputConnector::primary_output(*selected_node)
|
||||
&& let OutputConnector::Node { node_id, output_index } = first_deselected_upstream_output
|
||||
{
|
||||
responses.add(NodeGraphMessage::SetRootNodeToRestore {
|
||||
root_node_to_restore: RootNode { node_id, output_index },
|
||||
});
|
||||
}
|
||||
|
||||
let Some(downstream_connections_to_first_output) = outward_wires.get(&OutputConnector::primary_output(*selected_node)).cloned() else {
|
||||
log::error!("Could not get downstream_connections_to_first_output in shake node");
|
||||
return;
|
||||
@@ -2146,7 +2312,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
|
||||
NodeGraphMessage::UpdateLayerPanel => {
|
||||
Self::update_layer_panel(network_interface, selection_network_path, layers_panel_open, responses);
|
||||
Self::update_layer_panel(network_interface, selection_network_path, layers_panel_open, tool_edit_target, responses);
|
||||
}
|
||||
NodeGraphMessage::UpdateEdges => {
|
||||
// Update the import/export UI edges whenever the PTZ changes or the bounding box of all nodes changes
|
||||
@@ -2235,6 +2401,133 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
|
||||
impl NodeGraphMessageHandler {
|
||||
/// Removes the wire in progress along with any Properties panel drop target highlights, and collapses any node expanded for it.
|
||||
pub fn end_wire_in_progress(&mut self, network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque<Message>) {
|
||||
if matches!(self.wire_in_progress_anchor, Some(WireInProgressAnchor::Output(_))) {
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
|
||||
self.set_wire_hovered_node(None, network_interface, network_path, responses);
|
||||
|
||||
self.wire_in_progress_from_connector = None;
|
||||
self.wire_in_progress_to_connector = None;
|
||||
self.wire_in_progress_type = FrontendGraphDataType::General;
|
||||
self.wire_in_progress_anchor = None;
|
||||
self.wire_in_progress_properties_target = None;
|
||||
self.wire_in_progress_hovering_properties_panel = false;
|
||||
self.wire_left_viewport_time = None;
|
||||
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None });
|
||||
}
|
||||
|
||||
/// Tracks the node under a wire dragged from an output and when the hover began, collapsing the expanded node once the wire leaves it.
|
||||
fn set_wire_hovered_node(&mut self, hover: Option<(NodeId, u64)>, network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque<Message>) {
|
||||
let hovered_node = hover.map(|(node_id, _)| node_id);
|
||||
if self.wire_hovered_node.map(|(node_id, _)| node_id) == hovered_node {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.wire_expanded_node.as_ref().is_some_and(|(node_id, _)| Some(*node_id) != hovered_node) {
|
||||
self.collapse_wire_expanded_node(None, network_interface, network_path, responses);
|
||||
}
|
||||
|
||||
self.wire_hovered_node = hover;
|
||||
self.set_wire_hover_tick_subscribed(hover.is_some(), responses);
|
||||
}
|
||||
|
||||
/// Expands the hovered node once the wire has rested over it for the hover delay.
|
||||
fn expand_wire_hovered_node_after_delay(&mut self, time: u64, network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque<Message>) {
|
||||
let Some((node_id, hover_start_time)) = self.wire_hovered_node else { return };
|
||||
if time.saturating_sub(hover_start_time) < WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS {
|
||||
return;
|
||||
}
|
||||
self.set_wire_hover_tick_subscribed(false, responses);
|
||||
|
||||
let output_types = self.wire_in_progress_output_types(network_interface, network_path);
|
||||
let revealed_input_indices = (0..network_interface.number_of_inputs(&node_id, network_path))
|
||||
.filter(|&input_index| {
|
||||
let input_connector = InputConnector::node_at_index(node_id, input_index);
|
||||
let hidden_value = matches!(network_interface.input_from_connector(&input_connector, network_path), Some(NodeInput::Value { exposed: false, .. }));
|
||||
|
||||
hidden_value
|
||||
&& network_interface
|
||||
.potential_valid_input_types(&input_connector, network_path)
|
||||
.iter()
|
||||
.any(|valid_type| output_types.iter().any(|output_type| type_feeds_connector(output_type, valid_type)))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if revealed_input_indices.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for &input_index in &revealed_input_indices {
|
||||
Self::set_value_input_exposed(InputConnector::node_at_index(node_id, input_index), true, network_interface, network_path);
|
||||
}
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
self.wire_expanded_node = Some((node_id, revealed_input_indices));
|
||||
}
|
||||
|
||||
/// Hides the inputs revealed by the expanded node again, except `connected_input`.
|
||||
fn collapse_wire_expanded_node(&mut self, connected_input: Option<InputConnector>, network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque<Message>) {
|
||||
let Some((node_id, revealed_input_indices)) = self.wire_expanded_node.take() else { return };
|
||||
|
||||
for &input_index in &revealed_input_indices {
|
||||
let input_connector = InputConnector::node_at_index(node_id, input_index);
|
||||
if Some(input_connector) != connected_input {
|
||||
Self::set_value_input_exposed(input_connector, false, network_interface, network_path);
|
||||
}
|
||||
}
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
|
||||
fn set_value_input_exposed(input_connector: InputConnector, exposed: bool, network_interface: &mut NodeNetworkInterface, network_path: &[NodeId]) {
|
||||
let Some(mut input) = network_interface.input_from_connector(&input_connector, network_path).cloned() else {
|
||||
return;
|
||||
};
|
||||
let NodeInput::Value { exposed: input_exposed, .. } = &mut input else { return };
|
||||
|
||||
*input_exposed = exposed;
|
||||
network_interface.set_input(&input_connector, input, network_path);
|
||||
}
|
||||
|
||||
fn set_wire_hover_tick_subscribed(&mut self, subscribed: bool, responses: &mut VecDeque<Message>) {
|
||||
if self.wire_hover_tick_subscribed == subscribed {
|
||||
return;
|
||||
}
|
||||
self.wire_hover_tick_subscribed = subscribed;
|
||||
|
||||
let send = Box::new(NodeGraphMessage::WireHoverTick.into());
|
||||
responses.add(match subscribed {
|
||||
true => BroadcastMessage::SubscribeEvent {
|
||||
on: EventMessage::AnimationFrame,
|
||||
send,
|
||||
},
|
||||
false => BroadcastMessage::UnsubscribeEvent {
|
||||
on: EventMessage::AnimationFrame,
|
||||
send,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// The types a wire being dragged from an output could carry, used by the Properties panel to mark compatible inputs as drop targets.
|
||||
pub fn wire_in_progress_output_types(&self, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Vec<Type> {
|
||||
// The wire stays visible while the node creation menu is open, but it can no longer be dropped
|
||||
if self.context_menu.is_some() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let Some(WireInProgressAnchor::Output(output_connector)) = self.wire_in_progress_anchor else {
|
||||
return Vec::new();
|
||||
};
|
||||
let output_types = network_interface.potential_output_types(&output_connector, network_path);
|
||||
log::debug!(
|
||||
"[wire-drag] Output {output_connector:?} has type source {:?}, potential types {output_types:?}",
|
||||
network_interface.output_type(&output_connector, network_path)
|
||||
);
|
||||
output_types
|
||||
}
|
||||
|
||||
/// Similar to [`NodeGraphMessageHandler::actions`], but this provides additional actions if the node graph is open and should only be called in that circumstance.
|
||||
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
||||
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp, SendClickTargets, EndSendClickTargets);
|
||||
@@ -2313,6 +2606,23 @@ impl NodeGraphMessageHandler {
|
||||
for _ in selected_layers {}
|
||||
|
||||
let mut widgets = vec![
|
||||
IconButton::new(if selection_all_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if selection_all_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if selection_all_visible { "Hide Selected" } else { "Show Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(NodeGraphMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_update(|_| NodeGraphMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
IconButton::new(if selection_all_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if selection_all_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.tooltip_label(if selection_all_locked { "Unlock Selected" } else { "Lock Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(NodeGraphMessageDiscriminant::ToggleSelectedLocked))
|
||||
.on_update(|_| NodeGraphMessage::ToggleSelectedLocked.into())
|
||||
.disabled(!has_selection || !selection_includes_layers)
|
||||
.widget_instance(),
|
||||
//
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
//
|
||||
PopoverButton::new()
|
||||
.icon("Node")
|
||||
.tooltip_label("New Node")
|
||||
@@ -2381,23 +2691,6 @@ impl NodeGraphMessageHandler {
|
||||
.on_update(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
//
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
//
|
||||
IconButton::new(if selection_all_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
|
||||
.hover_icon(if selection_all_locked { "PadlockUnlocked" } else { "PadlockLocked" })
|
||||
.tooltip_label(if selection_all_locked { "Unlock Selected" } else { "Lock Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(NodeGraphMessageDiscriminant::ToggleSelectedLocked))
|
||||
.on_update(|_| NodeGraphMessage::ToggleSelectedLocked.into())
|
||||
.disabled(!has_selection || !selection_includes_layers)
|
||||
.widget_instance(),
|
||||
IconButton::new(if selection_all_visible { "EyeVisible" } else { "EyeHidden" }, 24)
|
||||
.hover_icon(if selection_all_visible { "EyeHide" } else { "EyeShow" })
|
||||
.tooltip_label(if selection_all_visible { "Hide Selected" } else { "Show Selected" })
|
||||
.tooltip_shortcut(action_shortcut!(NodeGraphMessageDiscriminant::ToggleSelectedVisibility))
|
||||
.on_update(|_| NodeGraphMessage::ToggleSelectedVisibility.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let mut selection = selected_nodes.selected_nodes();
|
||||
@@ -2669,11 +2962,29 @@ impl NodeGraphMessageHandler {
|
||||
.map(|node_id| node_properties::generate_node_properties(node_id, context))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// A wire leads up from the chain's sections into the layer's section, when there's a chain below it
|
||||
if node_properties.len() > 1
|
||||
&& let Some(LayoutGroup::Section(layer_section)) = node_properties.first_mut()
|
||||
{
|
||||
let chain_input_type = context.network_interface.input_type(&InputConnector::layer_secondary_input(layer), context.selection_network_path);
|
||||
layer_section.chain_wire = Some(SectionWire {
|
||||
data_type: chain_input_type.displayed_type(),
|
||||
is_list: chain_input_type.is_list(),
|
||||
});
|
||||
}
|
||||
|
||||
// Mark each chain node (but not the layer node itself, which is first) draggable so its section can be reordered.
|
||||
// A node without a primary input (e.g. a generator) is left non-draggable.
|
||||
for chain_node_section in node_properties.iter_mut().skip(1) {
|
||||
if let LayoutGroup::Section(section) = chain_node_section {
|
||||
section.draggable = context.network_interface.has_primary_input(&NodeId(section.id), context.selection_network_path);
|
||||
|
||||
// A wire leads up from each chain node to the section above, which its output feeds
|
||||
let output_type = context.network_interface.output_type(&OutputConnector::node(NodeId(section.id), 0), context.selection_network_path);
|
||||
section.output_wire = Some(SectionWire {
|
||||
data_type: output_type.displayed_type(),
|
||||
is_list: output_type.is_list(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2831,16 +3142,25 @@ impl NodeGraphMessageHandler {
|
||||
Some(NodeGraphErrorDiagnostic { position, error })
|
||||
}
|
||||
|
||||
fn update_layer_panel(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], layers_panel_open: bool, responses: &mut VecDeque<Message>) {
|
||||
fn update_layer_panel(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], layers_panel_open: bool, tool_edit_target: &EditTarget, responses: &mut VecDeque<Message>) {
|
||||
if !layers_panel_open {
|
||||
return;
|
||||
}
|
||||
|
||||
// What the active tool would edit in each layer it can edit
|
||||
let tool_targets = network_interface
|
||||
.selected_nodes()
|
||||
.selected_visible_and_unlocked_layers(network_interface)
|
||||
.filter_map(|layer| Some((layer.to_node(), tool_edit_target.resolve(layer, network_interface)?)))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
let selected_layers = network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers(network_interface.document_metadata())
|
||||
.map(|layer| layer.to_node())
|
||||
.collect::<HashSet<_>>();
|
||||
let selected_nodes = network_interface.selected_nodes().selected_nodes().copied().collect::<HashSet<_>>();
|
||||
let edited_nodes = network_interface.transaction_edited_nodes();
|
||||
|
||||
let mut descendants_of_selected = HashSet::new();
|
||||
for selected_layer in &selected_layers {
|
||||
@@ -2870,10 +3190,51 @@ impl NodeGraphMessageHandler {
|
||||
|
||||
let clippable = layer.can_be_clipped(network_interface.document_metadata()) && network_interface.layer_hosts_blending_nodes(&node_id, &[]);
|
||||
|
||||
let tool_target = tool_targets.get(&node_id);
|
||||
let description_if_outlined = |node: NodeId| tool_target.filter(|target| target.outlined_node() == Some(node)).map(|target| target.tooltip_description().to_string());
|
||||
let tool_target_insertion = match tool_target {
|
||||
Some(target @ ResolvedEditTarget::Inserted { definition, index }) => Some(LayerPanelChainInsertion {
|
||||
index: *index as u32,
|
||||
icon: resolve_document_node_type(definition).and_then(|definition| definition.icon).unwrap_or("NodeCustomNode").to_string(),
|
||||
name: definition.implementation_name_from_identifier(),
|
||||
description: target.tooltip_description().to_string(),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// Listed left to right as in the graph
|
||||
let chain_nodes = network_interface
|
||||
.layer_chain_nodes(node_id, &[])
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|chain_node_id| LayerPanelChainNode {
|
||||
id: chain_node_id,
|
||||
icon: network_interface.node_icon(&chain_node_id, &[]).to_string(),
|
||||
name: network_interface.display_name(&chain_node_id, &[]),
|
||||
selected: selected_nodes.contains(&chain_node_id),
|
||||
reorderable: network_interface.has_primary_input(&chain_node_id, &[]),
|
||||
visible: network_interface.is_visible(&chain_node_id, &[]),
|
||||
tool_target_description: description_if_outlined(chain_node_id),
|
||||
edit_in_progress: edited_nodes.contains(&chain_node_id),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Only colors the connector drawn beside a chain, so a layer without one skips resolving the type
|
||||
let chain_data_type = if chain_nodes.is_empty() && tool_target_insertion.is_none() {
|
||||
FrontendGraphDataType::default()
|
||||
} else {
|
||||
network_interface.input_type(&InputConnector::layer_secondary_input(node_id), &[]).displayed_type()
|
||||
};
|
||||
|
||||
let data = LayerPanelEntry {
|
||||
id: node_id,
|
||||
implementation_name: network_interface.implementation_name(&node_id, &[]),
|
||||
icon_name: network_interface.is_artboard(&node_id, &[]).then(|| "Artboard".to_string()),
|
||||
icon_name: network_interface.node_icon(&node_id, &[]).to_string(),
|
||||
chain_nodes,
|
||||
chain_data_type,
|
||||
tool_target_description: description_if_outlined(node_id),
|
||||
edit_in_progress: edited_nodes.contains(&node_id),
|
||||
tool_target_insertion,
|
||||
alias: network_interface.display_name(&node_id, &[]),
|
||||
in_selected_network: selection_network_path.is_empty(),
|
||||
children_allowed,
|
||||
@@ -2932,6 +3293,7 @@ impl NodeGraphMessageHandler {
|
||||
hint_data.0.extend([
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDouble, "Enter Node Subgraph")]),
|
||||
HintGroup(vec![HintInfo::keys_and_mouse([Key::Alt], MouseMotion::Lmb, "Preview Node Output")]),
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::MmbDrag, "Pan Graph"), HintInfo::keys([Key::Alt], "Pan Artwork").prepend_plus()]),
|
||||
]);
|
||||
hint_data.send_layout(responses);
|
||||
}
|
||||
@@ -2957,6 +3319,13 @@ impl Default for NodeGraphMessageHandler {
|
||||
wire_in_progress_from_connector: None,
|
||||
wire_in_progress_to_connector: None,
|
||||
wire_in_progress_type: FrontendGraphDataType::General,
|
||||
wire_in_progress_anchor: None,
|
||||
wire_in_progress_properties_target: None,
|
||||
wire_in_progress_hovering_properties_panel: false,
|
||||
wire_left_viewport_time: None,
|
||||
wire_hovered_node: None,
|
||||
wire_expanded_node: None,
|
||||
wire_hover_tick_subscribed: false,
|
||||
context_menu: None,
|
||||
deselect_on_pointer_up: None,
|
||||
auto_panning: Default::default(),
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown,
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
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, NodeNetworkInterface};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, type_feeds_connector};
|
||||
use crate::messages::portfolio::fonts::utility_types::FontCatalogStyle;
|
||||
use crate::messages::portfolio::ingest::utility_types::{IngestAction, TypeFilter};
|
||||
use crate::messages::prelude::*;
|
||||
@@ -82,85 +82,26 @@ pub fn commit_value<T>(_: &T) -> Message {
|
||||
DocumentMessage::AddTransaction.into()
|
||||
}
|
||||
|
||||
pub fn expose_widget(
|
||||
node_id: NodeId,
|
||||
index: usize,
|
||||
data_type: FrontendGraphDataType,
|
||||
resolved_type: String,
|
||||
valid_types: Vec<Type>,
|
||||
is_subnetwork: bool,
|
||||
is_wired: bool,
|
||||
exposed: bool,
|
||||
) -> WidgetInstance {
|
||||
let input_connector = InputConnector::node_at_index(node_id, index);
|
||||
|
||||
// Subnetwork inputs and wired inputs are read-only here: the type follows the subgraph or the upstream wire automatically.
|
||||
// Only unconnected protonode inputs accept a manual choice that picks among multiple type implementations.
|
||||
let entries_clickable = !is_subnetwork && !is_wired;
|
||||
|
||||
let type_entries: Vec<MenuListEntry> = if valid_types.is_empty() {
|
||||
// Fall back to a single read-only entry when no valid types are available (e.g., a type-resolution error).
|
||||
vec![MenuListEntry::new("type").label(resolved_type.clone()).disabled(true)]
|
||||
} else {
|
||||
valid_types
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, ty)| {
|
||||
let label = ty.nested_type().to_string();
|
||||
let is_active = label == resolved_type;
|
||||
let is_clickable = entries_clickable && !is_active;
|
||||
|
||||
let mut entry = MenuListEntry::new(format!("type-{i}")).label(label).disabled(!is_clickable);
|
||||
|
||||
// The active entry gets a bullet-point icon (the small filled circle) to mark it as the current selection.
|
||||
if is_active {
|
||||
entry = entry.icon("DataSourceValue");
|
||||
}
|
||||
|
||||
if is_clickable {
|
||||
entry = entry.on_commit(move |_| {
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: index,
|
||||
value: TaggedValue::from_type_or_none(&ty).into(),
|
||||
}
|
||||
.into()
|
||||
});
|
||||
}
|
||||
|
||||
entry
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
let type_submenu = vec![type_entries];
|
||||
|
||||
pub fn expose_widget(node_id: NodeId, index: usize, data_type: FrontendGraphDataType, exposed: bool, wire_drop_target: bool) -> WidgetInstance {
|
||||
ParameterExposeButton::new()
|
||||
.exposed(exposed)
|
||||
.data_type(data_type)
|
||||
.node_id(node_id)
|
||||
.input_index(index as u32)
|
||||
.wire_drop_target(wire_drop_target)
|
||||
.tooltip_description(if exposed {
|
||||
"Stop exposing this parameter as a node input in the graph."
|
||||
} else {
|
||||
"Expose this parameter as a node input in the graph."
|
||||
})
|
||||
.menu_list_children(vec![vec![
|
||||
MenuListEntry::new("value").label("Value").icon("DataSourceValue").children(type_submenu.clone()).on_commit(move |_| {
|
||||
NodeGraphMessage::ExposeInput {
|
||||
input_connector,
|
||||
set_to_exposed: false,
|
||||
start_transaction: true,
|
||||
}
|
||||
.into()
|
||||
}),
|
||||
MenuListEntry::new("graph").label("Graph").icon("DataSourceGraph").children(type_submenu).on_commit(move |_| {
|
||||
NodeGraphMessage::ExposeInput {
|
||||
input_connector,
|
||||
set_to_exposed: true,
|
||||
start_transaction: true,
|
||||
}
|
||||
.into()
|
||||
}),
|
||||
]])
|
||||
.on_update(move |_parameter| Message::Batched {
|
||||
messages: Box::new([NodeGraphMessage::ExposeInput {
|
||||
input_connector: InputConnector::node_at_index(node_id, index),
|
||||
set_to_exposed: !exposed,
|
||||
start_transaction: true,
|
||||
}
|
||||
.into()]),
|
||||
})
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
@@ -214,11 +155,8 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
parameter_widgets_info.node_id,
|
||||
parameter_widgets_info.index,
|
||||
parameter_widgets_info.input_type,
|
||||
parameter_widgets_info.resolved_type.clone(),
|
||||
parameter_widgets_info.valid_types.clone(),
|
||||
parameter_widgets_info.is_subnetwork,
|
||||
parameter_widgets_info.is_wired,
|
||||
input.is_exposed(),
|
||||
parameter_widgets_info.wire_drop_target,
|
||||
));
|
||||
}
|
||||
widgets.push(
|
||||
@@ -3161,14 +3099,6 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
// Prefer the input's currently stored value type over the protonode's default. This is what lets a user-chosen
|
||||
// type (e.g. swapping `f64` for `DVec2`) drive the widget, instead of always rendering the registry default.
|
||||
if let Some(document_node) = context.network_interface.document_node(&node_id, context.selection_network_path)
|
||||
&& let Some(NodeInput::Value { tagged_value, .. }) = document_node.inputs.get(input_index)
|
||||
{
|
||||
break 'early_return tagged_value.ty();
|
||||
}
|
||||
|
||||
if let Some(default) = default_type {
|
||||
break 'early_return default;
|
||||
}
|
||||
@@ -3219,20 +3149,19 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
implementation_name
|
||||
};
|
||||
|
||||
let description = context
|
||||
let definition = context
|
||||
.network_interface
|
||||
.reference(&node_id, context.selection_network_path)
|
||||
.as_ref()
|
||||
.and_then(|identifier| resolve_document_node_type(identifier))
|
||||
.map(|definition| definition.description.to_string())
|
||||
.filter(|string| string != "TODO")
|
||||
.unwrap_or_default();
|
||||
.and_then(|identifier| resolve_document_node_type(identifier));
|
||||
let icon = Some(context.network_interface.node_icon(&node_id, context.selection_network_path).to_string());
|
||||
let description = definition.map(|definition| definition.description.to_string()).filter(|string| string != "TODO").unwrap_or_default();
|
||||
|
||||
let visible = context.network_interface.is_visible(&node_id, context.selection_network_path);
|
||||
let pinned = context.network_interface.is_pinned(&node_id, context.selection_network_path);
|
||||
let expanded = !context.properties_panel_collapsed_sections.contains(&node_id);
|
||||
|
||||
LayoutGroup::section(name, description, visible, pinned, expanded, node_id.0, Layout(layout))
|
||||
LayoutGroup::section(name, icon, description, visible, pinned, expanded, node_id.0, Layout(layout))
|
||||
}
|
||||
|
||||
/// The layer that a chain node ultimately feeds, if any. Returns `None` in a nested network since the layer metadata structure
|
||||
@@ -3312,7 +3241,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
_ => None,
|
||||
};
|
||||
let backup_stops = match document_node.input_value(BackupGradientInput) {
|
||||
Some(TaggedValue::GradientRamp(ramp)) => ramp.clone(),
|
||||
Some(TaggedValue::GradientRamp(ramp)) if !ramp.stops.is_empty() => ramp.clone(),
|
||||
_ => GradientRamp::black_to_white(),
|
||||
};
|
||||
(backup_color, backup_stops)
|
||||
@@ -3589,12 +3518,10 @@ pub struct ParameterWidgetsInfo<'a> {
|
||||
name: String,
|
||||
description: String,
|
||||
input_type: FrontendGraphDataType,
|
||||
resolved_type: String,
|
||||
valid_types: Vec<Type>,
|
||||
is_subnetwork: bool,
|
||||
is_wired: bool,
|
||||
blank_assist: bool,
|
||||
exposable: bool,
|
||||
/// Whether a wire being dragged from an output could be connected to this parameter.
|
||||
wire_drop_target: bool,
|
||||
fonts: &'a FontsMessageHandler,
|
||||
}
|
||||
|
||||
@@ -3622,28 +3549,27 @@ impl<'a> ParameterWidgetsInfo<'a> {
|
||||
/// Reference the parameter by a runtime input index, for callers that receive the index dynamically (e.g. widget overrides).
|
||||
pub fn at_index(node_id: NodeId, index: usize, blank_assist: bool, context: &'a mut NodePropertiesContext) -> ParameterWidgetsInfo<'a> {
|
||||
let (name, description) = context.network_interface.displayed_input_name_and_description(&node_id, index, context.selection_network_path);
|
||||
let input_connector = InputConnector::node_at_index(node_id, index);
|
||||
let type_source = context.network_interface.input_type_not_invalid(&input_connector, context.selection_network_path);
|
||||
let input_type = type_source.displayed_type();
|
||||
let resolved_type = type_source.resolved_type_node_string();
|
||||
|
||||
// Start with the contextually-valid set. When that's empty for a protonode (e.g. a fresh node with no downstream
|
||||
// constraints), fall back to every input type the protonode is registered with so the user can still pick.
|
||||
let mut valid_types = context.network_interface.complete_valid_input_types(&input_connector, context.selection_network_path);
|
||||
let implementation = context.network_interface.implementation(&node_id, context.selection_network_path);
|
||||
let is_subnetwork = matches!(implementation, Some(DocumentNodeImplementation::Network(_)));
|
||||
if valid_types.is_empty()
|
||||
&& let Some(DocumentNodeImplementation::ProtoNode(protonode_id)) = implementation
|
||||
&& let Some(implementations) = interpreted_executor::node_registry::NODE_REGISTRY.get(protonode_id)
|
||||
{
|
||||
valid_types = implementations.keys().filter_map(|node_io| node_io.inputs.get(index).cloned()).collect();
|
||||
}
|
||||
// Dedupe by the displayed type name so repeated implementations sharing the same input type collapse to one entry.
|
||||
let mut seen_type_names = std::collections::HashSet::new();
|
||||
valid_types.retain(|ty| seen_type_names.insert(ty.nested_type().to_string()));
|
||||
|
||||
let input_type = context
|
||||
.network_interface
|
||||
.input_type_not_invalid(&InputConnector::node_at_index(node_id, index), context.selection_network_path)
|
||||
.displayed_type();
|
||||
let document_node = context.network_interface.document_node(&node_id, context.selection_network_path);
|
||||
let is_wired = document_node.and_then(|node| node.inputs.get(index)).is_some_and(|input| matches!(input, NodeInput::Node { .. }));
|
||||
|
||||
let wire_drop_target = !context.wire_in_progress_output_types.is_empty()
|
||||
&& context
|
||||
.network_interface
|
||||
.potential_valid_input_types(&InputConnector::node_at_index(node_id, index), context.selection_network_path)
|
||||
.iter()
|
||||
.any(|valid_type| context.wire_in_progress_output_types.iter().any(|output_type| type_feeds_connector(output_type, valid_type)));
|
||||
if !context.wire_in_progress_output_types.is_empty() {
|
||||
let valid_types = context
|
||||
.network_interface
|
||||
.potential_valid_input_types(&InputConnector::node_at_index(node_id, index), context.selection_network_path)
|
||||
.iter()
|
||||
.map(|valid_type| valid_type.nested_type().clone())
|
||||
.collect::<Vec<_>>();
|
||||
log::debug!("[wire-drag] Input {name} ({node_id}, {index}) has valid types {valid_types:?}, drop target: {wire_drop_target}");
|
||||
}
|
||||
|
||||
ParameterWidgetsInfo {
|
||||
document_id: context.document_id,
|
||||
@@ -3657,12 +3583,9 @@ impl<'a> ParameterWidgetsInfo<'a> {
|
||||
name,
|
||||
description,
|
||||
input_type,
|
||||
resolved_type,
|
||||
valid_types,
|
||||
is_subnetwork,
|
||||
is_wired,
|
||||
blank_assist,
|
||||
exposable: true,
|
||||
wire_drop_target,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::{Type, simplify_identifier_name};
|
||||
|
||||
@@ -163,6 +165,19 @@ pub enum ContextMenuData {
|
||||
},
|
||||
}
|
||||
|
||||
/// The connector a wire being dragged starts from, which stays fixed while its other end follows the pointer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum WireInProgressAnchor {
|
||||
/// Dragged from an output toward a compatible input.
|
||||
Output(OutputConnector),
|
||||
/// Dragged from an input toward a compatible output.
|
||||
Input {
|
||||
input_connector: InputConnector,
|
||||
/// Set when dragged out of the Properties panel, in viewport coordinates, since the input may not be exposed in the graph.
|
||||
properties_panel_position: Option<DVec2>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ContextMenuInformation {
|
||||
|
||||
@@ -63,6 +63,13 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
viewport: *viewport,
|
||||
},
|
||||
});
|
||||
responses.add(DocumentMessage::LayersPanelHoverOverlays {
|
||||
context: OverlayContext {
|
||||
render_context: canvas_context.clone(),
|
||||
visibility_settings: visibility_settings.clone(),
|
||||
viewport: *viewport,
|
||||
},
|
||||
});
|
||||
for provider in &self.overlay_providers {
|
||||
responses.add(provider(OverlayContext {
|
||||
render_context: canvas_context.clone(),
|
||||
@@ -80,6 +87,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
|
||||
if visibility_settings.all() {
|
||||
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
||||
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
||||
|
||||
for provider in &self.overlay_providers {
|
||||
responses.add(provider(overlay_context.clone()));
|
||||
|
||||
+4
@@ -1,3 +1,4 @@
|
||||
use graphene_std::Type;
|
||||
use graphene_std::uuid::NodeId;
|
||||
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
@@ -17,6 +18,7 @@ pub struct PropertiesPanelMessageContext<'a> {
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub properties_panel_open: bool,
|
||||
pub properties_panel_collapsed_sections: &'a [NodeId],
|
||||
pub wire_in_progress_output_types: &'a [Type],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -35,6 +37,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
fonts,
|
||||
properties_panel_open,
|
||||
properties_panel_collapsed_sections,
|
||||
wire_in_progress_output_types,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
@@ -60,6 +63,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
document_name,
|
||||
fonts,
|
||||
properties_panel_collapsed_sections,
|
||||
wire_in_progress_output_types,
|
||||
};
|
||||
let layout = Layout(NodeGraphMessageHandler::collate_properties(&mut node_properties_context));
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ mod validation;
|
||||
mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use resolved_types::type_feeds_connector;
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
pub use template::*;
|
||||
@@ -91,6 +92,15 @@ pub struct NodeNetworkInterface {
|
||||
/// a set of changes.
|
||||
#[serde(skip)]
|
||||
deltas: Vec<EditorDelta>,
|
||||
/// The document network nodes the open transaction has written to, read from `deltas`, for the Layers panel to highlight during an edit like a drag.
|
||||
#[serde(skip)]
|
||||
transaction_edited_nodes: HashSet<NodeId>,
|
||||
/// How far into `deltas` the reading for `transaction_edited_nodes` has reached.
|
||||
#[serde(skip)]
|
||||
transaction_edited_nodes_scanned: usize,
|
||||
/// Whether `transaction_edited_nodes` changed since `update_transaction_edited_nodes` last reported it.
|
||||
#[serde(skip)]
|
||||
transaction_edited_nodes_changed: bool,
|
||||
}
|
||||
|
||||
impl Clone for NodeNetworkInterface {
|
||||
@@ -102,6 +112,9 @@ impl Clone for NodeNetworkInterface {
|
||||
resolved_types: Default::default(),
|
||||
transaction_status: TransactionStatus::Finished,
|
||||
deltas: Vec::new(),
|
||||
transaction_edited_nodes: HashSet::new(),
|
||||
transaction_edited_nodes_scanned: 0,
|
||||
transaction_edited_nodes_changed: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ use super::*;
|
||||
impl NodeNetworkInterface {
|
||||
pub fn start_transaction(&mut self) {
|
||||
self.transaction_status = TransactionStatus::Started;
|
||||
self.clear_transaction_edited_nodes();
|
||||
self.transaction_edited_nodes_scanned = self.deltas.len();
|
||||
}
|
||||
|
||||
pub fn transaction_modified(&mut self) {
|
||||
@@ -15,6 +17,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub fn finish_transaction(&mut self) {
|
||||
self.transaction_status = TransactionStatus::Finished;
|
||||
self.clear_transaction_edited_nodes();
|
||||
}
|
||||
|
||||
/// Mutably get the selected nodes for the network at the network_path. Every time they are mutated, the transient metadata for the top of the stack gets unloaded.
|
||||
@@ -646,8 +649,9 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
fn load_wire(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) {
|
||||
// The export keeps its own solid wire while previewing, since previewing does not rewire it
|
||||
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, false, network_path) else {
|
||||
// While previewing, the export's wire leads to the temporarily previewed node
|
||||
let dashed = *input == InputConnector::Export(0) && matches!(self.previewing(network_path), Previewing::Yes { .. });
|
||||
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, dashed, network_path) else {
|
||||
log::error!("Could not load wire path from input");
|
||||
return;
|
||||
};
|
||||
@@ -759,14 +763,15 @@ impl NodeNetworkInterface {
|
||||
|
||||
let path_string = vector_wire.to_svg();
|
||||
let center_path_string = center_line.to_svg();
|
||||
let input_type = self.input_type(&input, network_path);
|
||||
let data_type = input_type.displayed_type();
|
||||
let is_list = input_type.is_list();
|
||||
// Styled by the root node's own output, since the export it leads to is connected to the previewed node instead
|
||||
let output_type = self.output_type(&upstream_output, network_path);
|
||||
let data_type = output_type.displayed_type();
|
||||
let is_list = output_type.is_list();
|
||||
let wire_path_update = Some(WirePath {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed: true,
|
||||
dashed: false,
|
||||
is_list,
|
||||
center_path_string,
|
||||
});
|
||||
|
||||
+577
-1
@@ -1,4 +1,6 @@
|
||||
use super::{InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, OutputConnector, Previewing, RootNode, TransactionStatus};
|
||||
use super::{
|
||||
ChainInsertionPoint, FlowType, InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeInput;
|
||||
@@ -291,6 +293,580 @@ async fn chain_membership_follows_wiring() {
|
||||
assert_invariants(&editor, "after forming and breaking a chain");
|
||||
}
|
||||
|
||||
fn fill_definition() -> DefinitionIdentifier {
|
||||
DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
|
||||
}
|
||||
|
||||
/// Builds a layer fed by the chain `near <- far <- source` (a generator fixed at the upstream end), with an outside node also wired into the near node's second input.
|
||||
async fn layer_with_chain(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
|
||||
let layer = editor.create_node_by_name_at(merge_definition(), 30, 10).await;
|
||||
let near = editor.create_node_by_name_at(fill_definition(), 23, 10).await;
|
||||
let far = editor.create_node_by_name_at(fill_definition(), 16, 10).await;
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 9, 10).await;
|
||||
let outside = editor.create_node_by_name_at(rectangle_definition(), 16, 20).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&layer, &[], true);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(near), &InputConnector::layer_secondary_input(layer), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(far), &InputConnector::primary_input(near), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(source), &InputConnector::primary_input(far), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(outside), &InputConnector::node_at_index(near, 1), &[]);
|
||||
|
||||
(layer, near, far, source, outside)
|
||||
}
|
||||
|
||||
/// The layer from `layer_with_chain` placed in an artboard, making it part of the layer structure that the Layers panel and clipboard act on.
|
||||
async fn layer_with_chain_in_artboard(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
|
||||
let artboard = NodeId::new();
|
||||
editor.handle_message(new_artboard_message(artboard)).await;
|
||||
let nodes = layer_with_chain(editor).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
let artboard_layer = LayerNodeIdentifier::new(artboard, network_interface);
|
||||
network_interface.move_layer_to_stack(LayerNodeIdentifier::new(nodes.0, network_interface), artboard_layer, 0, &[]);
|
||||
|
||||
nodes
|
||||
}
|
||||
|
||||
fn chain_of(network_interface: &NodeNetworkInterface, layer: NodeId) -> Vec<NodeId> {
|
||||
network_interface.upstream_flow_back_from_nodes(vec![layer], &[], FlowType::HorizontalFlow).skip(1).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reordering_chain_nodes_keeps_the_source_at_the_upstream_end() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
|
||||
// Gap 2 is upstream of both reorderable nodes, beside the fixed source
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.reorder_chain_nodes(&[near], 2, &[]);
|
||||
assert_eq!(chain_of(network_interface, layer), vec![far, near, source]);
|
||||
|
||||
assert_invariants(&editor, "after reordering a chain node");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_chain_nodes_inserts_copies_that_keep_their_other_wires() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, outside) = layer_with_chain(&mut editor).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.duplicate_chain_nodes(&[near], Some((layer, 2)), &[]);
|
||||
|
||||
let chain = chain_of(network_interface, layer);
|
||||
assert_eq!(chain.len(), 4, "The copy should join the chain");
|
||||
assert_eq!(
|
||||
(chain[0], chain[1], chain[3]),
|
||||
(near, far, source),
|
||||
"The originals should keep their places, with the source still at the end"
|
||||
);
|
||||
|
||||
let copy = chain[2];
|
||||
assert!(network_interface.is_chain(©, &[]), "The copy should be positioned as a chain node");
|
||||
assert_eq!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(copy, 1), &[]),
|
||||
Some(&NodeInput::node(outside, 0)),
|
||||
"The copy should keep its original's other wires"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating a chain node");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_chain_nodes_in_place_one_at_a_time_interleaves_the_copies() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
let near_copy = network_interface.duplicate_chain_nodes(&[near], None, &[]);
|
||||
let far_copy = network_interface.duplicate_chain_nodes(&[far], None, &[]);
|
||||
assert_eq!((near_copy.len(), far_copy.len()), (1, 1));
|
||||
|
||||
// Each copy lands just downstream of its own original
|
||||
assert_eq!(chain_of(network_interface, layer), vec![near_copy[0], near, far_copy[0], far, source]);
|
||||
|
||||
assert_invariants(&editor, "after duplicating chain nodes in place");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasting_a_chain_node_at_another_layers_chain_end_keeps_only_wires_that_exist() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, near, _, _, outside) = layer_with_chain(&mut editor).await;
|
||||
let other_layer = editor.create_node_by_name_at(merge_definition(), 30, 30).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&other_layer, &[], true);
|
||||
let copy = network_interface.copy_chain_node(&near, &[]).expect("The chain node should be copyable");
|
||||
|
||||
// Pasted while the outside node exists, the copy stays wired to it
|
||||
let pasted = network_interface.paste_into_chain(ChainInsertionPoint::BesideLayer(other_layer), vec![copy.clone()], &[]);
|
||||
assert_eq!(chain_of(network_interface, other_layer), pasted, "The copy should form the other layer's chain");
|
||||
assert_eq!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(pasted[0], 1), &[]),
|
||||
Some(&NodeInput::node(outside, 0))
|
||||
);
|
||||
|
||||
// Pasted where the outside node is missing, the copy takes the value it had
|
||||
network_interface.delete_nodes(vec![outside], false, &[]);
|
||||
let pasted_again = network_interface.paste_into_chain(ChainInsertionPoint::BesideLayer(other_layer), vec![copy], &[]);
|
||||
assert_eq!(
|
||||
chain_of(network_interface, other_layer),
|
||||
vec![pasted_again[0], pasted[0]],
|
||||
"Pasting at the chain's end should go beside the layer"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(pasted_again[0], 1), &[]),
|
||||
Some(NodeInput::Value { .. })
|
||||
),
|
||||
"A wire to a missing node should become its fallback value"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after pasting chain nodes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cutting_a_chain_node_and_pasting_it_back_keeps_its_wires() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, outside) = layer_with_chain_in_artboard(&mut editor).await;
|
||||
|
||||
// Cutting removes just the node, keeping the node that fed its second input
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![near] }).await;
|
||||
let clipboard = editor
|
||||
.handle_message(ClipboardMessage::CutLayers)
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||
_ => None,
|
||||
})
|
||||
.expect("Cutting a chain node should write it to the clipboard");
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(chain_of(network_interface, layer), vec![far, source], "Cutting should close the chain around the node");
|
||||
assert!(network_interface.document_node(&outside, &[]).is_some(), "Cutting should keep what fed the node's other inputs");
|
||||
|
||||
// Pasting with the layer selected puts the node back beside the layer, wired as before
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }).await;
|
||||
editor
|
||||
.handle_message(ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(clipboard),
|
||||
})
|
||||
.await;
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let chain = chain_of(network_interface, layer);
|
||||
assert_eq!(chain.len(), 3, "The pasted node should join the chain");
|
||||
assert_eq!(chain[1..], [far, source], "The pasted node should go beside the layer");
|
||||
assert_eq!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(chain[0], 1), &[]),
|
||||
Some(&NodeInput::node(outside, 0)),
|
||||
"The pasted node should be wired to what fed it before"
|
||||
);
|
||||
assert_eq!(
|
||||
network_interface.selected_nodes().selected_nodes().copied().collect::<Vec<_>>(),
|
||||
vec![chain[0]],
|
||||
"The pasted node should be selected"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after cutting and pasting a chain node");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasted_chain_nodes_go_beside_their_originals_or_pair_with_a_new_selection() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain_in_artboard(&mut editor).await;
|
||||
let copy = editor.active_document().network_interface.copy_chain_node(&near, &[]).expect("The chain node should be copyable");
|
||||
|
||||
// Over the same selection that was copied, the copy goes beside its original
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![near] }).await;
|
||||
editor.handle_message(DocumentMessage::PasteChainNodes { copies: vec![copy.clone()] }).await;
|
||||
let chain = chain_of(&editor.active_document().network_interface, layer);
|
||||
let first_copy = chain[0];
|
||||
assert_eq!(chain, vec![first_copy, near, far, source], "The copy should go beside the node it was copied from");
|
||||
|
||||
// Over a different selection of the same size, the copy pairs with that node instead
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![far] }).await;
|
||||
editor.handle_message(DocumentMessage::PasteChainNodes { copies: vec![copy] }).await;
|
||||
let chain = chain_of(&editor.active_document().network_interface, layer);
|
||||
let second_copy = chain[2];
|
||||
assert_eq!(chain, vec![first_copy, near, second_copy, far, source], "The copy should go beside the newly selected node");
|
||||
assert_eq!(
|
||||
editor.active_document().network_interface.selected_nodes().selected_nodes().copied().collect::<Vec<_>>(),
|
||||
vec![second_copy],
|
||||
"The pasted copy should become the selection"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after pasting chain nodes over a selection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moving_a_chain_node_to_another_layer_closes_the_gap_it_leaves() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
let other_layer = editor.create_node_by_name_at(merge_definition(), 30, 30).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&other_layer, &[], true);
|
||||
network_interface.move_chain_nodes(&[near], other_layer, 0, &[]);
|
||||
|
||||
assert_eq!(chain_of(network_interface, layer), vec![far, source], "The source chain should close up around the moved node");
|
||||
assert_eq!(chain_of(network_interface, other_layer), vec![near], "The moved node should form the other layer's chain");
|
||||
|
||||
assert_invariants(&editor, "after moving a chain node between layers");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_chain_node_reading_from_a_layer_joins_its_chain_only_as_an_unwired_copy() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
let other_layer = editor.create_node_by_name_at(merge_definition(), 30, 30).await;
|
||||
|
||||
// The other layer feeds the near node's second input, so its chain taking the near node with that wire would close a cycle
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&other_layer, &[], true);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(other_layer), &InputConnector::node_at_index(near, 1), &[]);
|
||||
|
||||
network_interface.move_chain_nodes(&[near], other_layer, 0, &[]);
|
||||
assert_eq!(chain_of(network_interface, layer), vec![near, far, source], "A refused move should leave the node in its own chain");
|
||||
assert!(chain_of(network_interface, other_layer).is_empty(), "A refused move should leave the other chain as it was");
|
||||
|
||||
let copies = network_interface.duplicate_chain_nodes(&[near], Some((other_layer, 0)), &[]);
|
||||
assert_eq!(chain_of(network_interface, other_layer), copies, "The copy should join the other chain");
|
||||
assert!(
|
||||
matches!(network_interface.input_from_connector(&InputConnector::node_at_index(copies[0], 1), &[]), Some(NodeInput::Value { .. })),
|
||||
"The copy's wire from the layer it joined should fall back to a value"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after chain edits that would close a cycle");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_mixed_graph_selection_stacks_the_layers_and_offsets_the_other_nodes() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let artboard = NodeId::new();
|
||||
editor.handle_message(new_artboard_message(artboard)).await;
|
||||
let (layer, near, _, _, _) = layer_with_chain(&mut editor).await;
|
||||
let loose = editor.create_node_by_name_at(rectangle_definition(), 40, 40).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
let artboard_layer = LayerNodeIdentifier::new(artboard, network_interface);
|
||||
network_interface.move_layer_to_stack(LayerNodeIdentifier::new(layer, network_interface), artboard_layer, 0, &[]);
|
||||
|
||||
// The selected chain node comes along with its layer's copy, so only the loose node gets an offset copy of its own
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer, near, loose] }).await;
|
||||
editor.handle_message(NodeGraphMessage::DuplicateSelectedNodes).await;
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let children = artboard_layer.children(network_interface.document_metadata()).map(|child| child.to_node()).collect::<Vec<_>>();
|
||||
assert_eq!(children.len(), 2, "The layer's copy should join the stack beside it");
|
||||
let layer_copy = *children.iter().find(|child| **child != layer).unwrap();
|
||||
assert_eq!(chain_of(network_interface, layer_copy).len(), 3, "The layer's copy should bring its own chain");
|
||||
|
||||
let selected = network_interface.selected_nodes().selected_nodes().copied().collect::<Vec<_>>();
|
||||
assert_eq!(selected.len(), 2, "Only the layer's copy and the loose node's copy should be selected");
|
||||
assert!(selected.contains(&layer_copy), "The layer's copy should be selected");
|
||||
let loose_copy = *selected.iter().find(|node| **node != layer_copy).unwrap();
|
||||
assert_eq!(
|
||||
network_interface.position(&loose_copy, &[]),
|
||||
network_interface.position(&loose, &[]).map(|position| position + IVec2::new(2, 2))
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating a mixed selection of layers and nodes");
|
||||
}
|
||||
|
||||
/// A generator feeding three nodes in a row through their primary inputs, outside any layer.
|
||||
async fn floating_flow(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId) {
|
||||
let generator = editor.create_node_by_name_at(rectangle_definition(), 0, 40).await;
|
||||
let first = editor.create_node_by_name_at(fill_definition(), 7, 40).await;
|
||||
let middle = editor.create_node_by_name_at(fill_definition(), 14, 40).await;
|
||||
let last = editor.create_node_by_name_at(fill_definition(), 21, 40).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.create_wire(&OutputConnector::primary_output(generator), &InputConnector::primary_input(first), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(first), &InputConnector::primary_input(middle), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(middle), &InputConnector::primary_input(last), &[]);
|
||||
|
||||
(generator, first, middle, last)
|
||||
}
|
||||
|
||||
async fn duplicate_selection(editor: &mut EditorTestUtils, nodes: Vec<NodeId>) -> Vec<NodeId> {
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
||||
editor.handle_message(DocumentMessage::DuplicateSelectedLayers).await;
|
||||
editor.active_document().network_interface.selected_nodes().selected_nodes().copied().collect()
|
||||
}
|
||||
|
||||
fn primary_input_of(network_interface: &NodeNetworkInterface, node_id: NodeId) -> Option<NodeInput> {
|
||||
network_interface.input_from_connector(&InputConnector::primary_input(node_id), &[]).cloned()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_node_inside_a_flow_puts_its_copy_right_after_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, _, middle, last) = floating_flow(&mut editor).await;
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![middle]).await;
|
||||
assert_eq!(copies.len(), 1, "The copy should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, copies[0]),
|
||||
Some(NodeInput::node(middle, 0)),
|
||||
"The copy should be fed by the original"
|
||||
);
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, last),
|
||||
Some(NodeInput::node(copies[0], 0)),
|
||||
"The copy should feed what the original fed"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating a node inside a flow");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_the_end_of_a_flow_extends_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, _, _, last) = floating_flow(&mut editor).await;
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![last]).await;
|
||||
assert_eq!(copies.len(), 1, "The copy should become the selection");
|
||||
assert_eq!(
|
||||
primary_input_of(&editor.active_document().network_interface, copies[0]),
|
||||
Some(NodeInput::node(last, 0)),
|
||||
"The copy should extend the flow from the original"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating the end of a flow");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_solo_node_or_a_generator_makes_an_offset_copy_outside_the_flow() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (generator, first, _, _) = floating_flow(&mut editor).await;
|
||||
let solo = editor.create_node_by_name_at(fill_definition(), 0, 60).await;
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![generator, solo]).await;
|
||||
assert_eq!(copies.len(), 2, "Both copies should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, first),
|
||||
Some(NodeInput::node(generator, 0)),
|
||||
"The generator should still feed the flow"
|
||||
);
|
||||
for copy in copies {
|
||||
let original = if network_interface.reference(©, &[]) == network_interface.reference(&generator, &[]) {
|
||||
generator
|
||||
} else {
|
||||
solo
|
||||
};
|
||||
assert_eq!(
|
||||
network_interface.position(©, &[]),
|
||||
network_interface.position(&original, &[]).map(|position| position + IVec2::new(2, 2)),
|
||||
"A copy outside the flow should sit offset from its original"
|
||||
);
|
||||
assert!(
|
||||
!matches!(primary_input_of(network_interface, copy), Some(NodeInput::Node { .. })),
|
||||
"A copy outside the flow should not be wired into it"
|
||||
);
|
||||
}
|
||||
|
||||
assert_invariants(&editor, "after duplicating nodes outside any flow");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_floating_layer_in_a_stack_puts_its_copy_above_it_with_its_content() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, _, _, _, _) = layer_with_chain(&mut editor).await;
|
||||
let layer_above = editor.create_node_by_name_at(merge_definition(), 30, 0).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_to_node_or_layer(&layer_above, &[], true);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(layer), &InputConnector::primary_input(layer_above), &[]);
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![layer]).await;
|
||||
assert_eq!(copies.len(), 1, "The copy should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(network_interface.is_layer(&copies[0], &[]), "The copy should be a layer");
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, copies[0]),
|
||||
Some(NodeInput::node(layer, 0)),
|
||||
"The copy should be stacked on the original"
|
||||
);
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, layer_above),
|
||||
Some(NodeInput::node(copies[0], 0)),
|
||||
"The layer above should now be stacked on the copy"
|
||||
);
|
||||
assert_eq!(chain_of(network_interface, copies[0]).len(), 3, "The copy should bring a copy of the layer's chain");
|
||||
|
||||
assert_invariants(&editor, "after duplicating a floating layer in a stack");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicating_a_solo_floating_layer_makes_an_offset_copy_with_its_content() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, _, _, _, _) = layer_with_chain(&mut editor).await;
|
||||
|
||||
let copies = duplicate_selection(&mut editor, vec![layer]).await;
|
||||
assert_eq!(copies.len(), 1, "The copy should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(network_interface.is_layer(&copies[0], &[]), "The copy should be a layer");
|
||||
assert_eq!(chain_of(network_interface, copies[0]).len(), 3, "The copy should bring a copy of the layer's chain");
|
||||
assert_eq!(
|
||||
network_interface.position(&copies[0], &[]),
|
||||
network_interface.position(&layer, &[]).map(|position| position + IVec2::new(2, 2)),
|
||||
"The copy should sit offset from the original"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after duplicating a solo floating layer");
|
||||
}
|
||||
|
||||
async fn copy_in_graph(editor: &mut EditorTestUtils, nodes: Vec<NodeId>) -> String {
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::Copy)
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||
_ => None,
|
||||
})
|
||||
.expect("Copying nodes should write them to the clipboard")
|
||||
}
|
||||
|
||||
async fn paste(editor: &mut EditorTestUtils, clipboard: String) -> Vec<NodeId> {
|
||||
editor
|
||||
.handle_message(ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(clipboard),
|
||||
})
|
||||
.await;
|
||||
editor.active_document().network_interface.selected_nodes().selected_nodes().copied().collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasting_graph_nodes_over_their_copied_selection_duplicates_them_into_the_flow() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, _, middle, last) = floating_flow(&mut editor).await;
|
||||
|
||||
let clipboard = copy_in_graph(&mut editor, vec![middle]).await;
|
||||
let pasted = paste(&mut editor, clipboard).await;
|
||||
assert_eq!(pasted.len(), 1, "The pasted copy should become the selection");
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, pasted[0]),
|
||||
Some(NodeInput::node(middle, 0)),
|
||||
"The copy should be fed by the original"
|
||||
);
|
||||
assert_eq!(
|
||||
primary_input_of(network_interface, last),
|
||||
Some(NodeInput::node(pasted[0], 0)),
|
||||
"The copy should feed what the original fed"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after pasting graph nodes over their copied selection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasting_graph_nodes_over_an_empty_selection_puts_loose_copies_in_the_graph() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, _, middle, last) = floating_flow(&mut editor).await;
|
||||
|
||||
let clipboard = copy_in_graph(&mut editor, vec![middle]).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() }).await;
|
||||
let pasted = paste(&mut editor, clipboard).await;
|
||||
assert_eq!(pasted.len(), 1, "The pasted copy should become the selection");
|
||||
|
||||
let document = editor.active_document();
|
||||
assert!(
|
||||
!matches!(primary_input_of(&document.network_interface, pasted[0]), Some(NodeInput::Node { .. })),
|
||||
"The pasted copy should be outside any flow"
|
||||
);
|
||||
assert_eq!(
|
||||
primary_input_of(&document.network_interface, last),
|
||||
Some(NodeInput::node(middle, 0)),
|
||||
"The flow should be left as it was"
|
||||
);
|
||||
assert!(document.graph_view_overlay_open(), "The graph should open to show the pasted copy");
|
||||
|
||||
assert_invariants(&editor, "after pasting graph nodes over an empty selection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasting_chain_nodes_over_an_empty_selection_puts_loose_copies_in_the_graph() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, far, source, _) = layer_with_chain_in_artboard(&mut editor).await;
|
||||
let copy = editor.active_document().network_interface.copy_chain_node(&near, &[]).expect("The chain node should be copyable");
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() }).await;
|
||||
editor.handle_message(DocumentMessage::PasteChainNodes { copies: vec![copy] }).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let pasted = document.network_interface.selected_nodes().selected_nodes().copied().collect::<Vec<_>>();
|
||||
assert_eq!(pasted.len(), 1, "The pasted copy should become the selection");
|
||||
assert!(
|
||||
!matches!(primary_input_of(&document.network_interface, pasted[0]), Some(NodeInput::Node { .. })),
|
||||
"The pasted copy should be outside any flow"
|
||||
);
|
||||
assert_eq!(chain_of(&document.network_interface, layer), vec![near, far, source], "The chain should be left as it was");
|
||||
assert!(document.graph_view_overlay_open(), "The graph should open to show the pasted copy");
|
||||
|
||||
assert_invariants(&editor, "after pasting chain nodes over an empty selection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_copied_layer_pastes_the_same_whether_copied_in_the_graph_or_not() {
|
||||
for copied_in_graph in [false, true] {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, _, _, _, _) = layer_with_chain_in_artboard(&mut editor).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: copied_in_graph }).await;
|
||||
let clipboard = copy_in_graph(&mut editor, vec![layer]).await;
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: false }).await;
|
||||
let pasted = paste(&mut editor, clipboard).await;
|
||||
assert_eq!(pasted.len(), 1, "Only the pasted layer should be selected (copied in the graph: {copied_in_graph})");
|
||||
|
||||
// The copy goes on top of the stack its original is in, bringing its chain along
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let metadata = network_interface.document_metadata();
|
||||
let parent = LayerNodeIdentifier::new(layer, network_interface).parent(metadata);
|
||||
assert!(parent.is_some(), "The original layer should be in the layer structure");
|
||||
assert_eq!(
|
||||
parent.and_then(|parent| parent.children(metadata).next()).map(|child| child.to_node()),
|
||||
Some(pasted[0]),
|
||||
"The pasted layer should go on top of the stack (copied in the graph: {copied_in_graph})"
|
||||
);
|
||||
assert_eq!(
|
||||
chain_of(network_interface, pasted[0]).len(),
|
||||
3,
|
||||
"The pasted layer should bring its chain (copied in the graph: {copied_in_graph})"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after pasting a copied layer");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn move_layer_to_stack_builds_the_layer_stack() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -309,12 +309,11 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
pub fn selected_unlocked_layers_bounding_box_viewport(&self) -> Option<[DVec2; 2]> {
|
||||
self.selected_nodes()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|node| self.is_layer(node, &[]) && !self.is_locked(node, &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_viewport(LayerNodeIdentifier::new(*layer, self)))
|
||||
pub fn selected_visible_and_unlocked_layers_bounding_box_viewport(&self) -> Option<[DVec2; 2]> {
|
||||
let selected_nodes = self.selected_nodes();
|
||||
selected_nodes
|
||||
.selected_visible_and_unlocked_layers(self)
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_viewport(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
|
||||
@@ -1242,65 +1242,323 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reorders a node within its layer's horizontal chain so it ends up at `insert_index` among the chain's nodes,
|
||||
/// where index 0 is the node closest to the layer. The connection feeding the top (most-upstream end) of the chain
|
||||
/// is preserved, as are each node's other (non-primary) inputs.
|
||||
pub fn reorder_chain_node(&mut self, node_id: NodeId, insert_index: usize, network_path: &[NodeId]) {
|
||||
let Some(layer) = self.downstream_layer_for_chain_node(&node_id, network_path) else {
|
||||
log::error!("Could not find downstream layer for chain node {node_id} in reorder_chain_node");
|
||||
/// Moves nodes within their layer's horizontal chain, keeping their relative order, so they end up together at the `insert_index`
|
||||
/// gap among the chain's reorderable nodes, where gap 0 is beside the layer. The connection feeding the top (most-upstream end)
|
||||
/// of the chain is preserved, as are each node's other (non-primary) inputs.
|
||||
pub fn reorder_chain_nodes(&mut self, node_ids: &[NodeId], insert_index: usize, network_path: &[NodeId]) {
|
||||
let Some((layer, reorderable, tail_input)) = self.reorderable_chain_nodes(node_ids, network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The nodes in the layer's chain, ordered from closest-to-layer outward, stopping at the next layer
|
||||
let chain = self
|
||||
.upstream_flow_back_from_nodes(vec![layer], network_path, FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|upstream_id| !self.is_layer(upstream_id, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// A source node (no primary input) stays pinned at the most-upstream end; only the nodes below it reorder
|
||||
let pinned_source = chain.last().copied().filter(|last| !self.has_primary_input(last, network_path));
|
||||
let reorderable = &chain[..chain.len() - pinned_source.is_some() as usize];
|
||||
|
||||
let Some(from) = reorderable.iter().position(|id| *id == node_id) else {
|
||||
log::error!("Node {node_id} is not a reorderable node in its layer's chain in reorder_chain_node");
|
||||
return;
|
||||
};
|
||||
|
||||
// The drop gap is measured against the reorderable nodes that still include the dragged node, so shift it down by one if the node is being removed from before the gap
|
||||
let to = (if insert_index > from { insert_index - 1 } else { insert_index }).min(reorderable.len() - 1);
|
||||
if to == from {
|
||||
// The drop gap is measured against the reorderable nodes that still include the moving ones, so it shifts down by each moving node before it
|
||||
let (moving, mut new_order): (Vec<NodeId>, Vec<NodeId>) = reorderable.iter().copied().partition(|id| node_ids.contains(id));
|
||||
let to = reorderable[..insert_index.min(reorderable.len())].iter().filter(|id| !node_ids.contains(id)).count();
|
||||
new_order.splice(to..to, moving);
|
||||
if new_order == reorderable {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut new_order = reorderable.to_vec();
|
||||
new_order.remove(from);
|
||||
new_order.insert(to, node_id);
|
||||
self.rewire_chain(layer, &new_order, tail_input, network_path);
|
||||
}
|
||||
|
||||
// The most-upstream reorderable node connects up to the pinned source, or else whatever fed the top of the chain
|
||||
let tail_input = if let Some(source) = pinned_source {
|
||||
NodeInput::node(source, 0)
|
||||
/// Moves nodes from their layer's horizontal chain into the given layer's chain (which may be the same one), keeping their relative order, so they end up
|
||||
/// together at the `insert_index` gap among that chain's reorderable nodes, where gap 0 is beside the layer. Both chains keep what fed their upstream ends.
|
||||
pub fn move_chain_nodes(&mut self, node_ids: &[NodeId], layer: NodeId, insert_index: usize, network_path: &[NodeId]) {
|
||||
let Some((source_layer, source_reorderable, source_tail_input)) = self.reorderable_chain_nodes(node_ids, network_path) else {
|
||||
return;
|
||||
};
|
||||
if source_layer == layer {
|
||||
self.reorder_chain_nodes(node_ids, insert_index, network_path);
|
||||
return;
|
||||
}
|
||||
let Some((target_reorderable, target_tail_input)) = self.layer_chain(layer, network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Close the gap the nodes leave in their own chain
|
||||
let (moving, remaining): (Vec<NodeId>, Vec<NodeId>) = source_reorderable.iter().copied().partition(|id| node_ids.contains(id));
|
||||
for node_id in &moving {
|
||||
self.disconnect_input(&InputConnector::primary_input(*node_id), network_path);
|
||||
}
|
||||
self.rewire_chain(source_layer, &remaining, source_tail_input.clone(), network_path);
|
||||
|
||||
// Then splice them into the other layer's chain, or restore both chains if that would close a cycle
|
||||
let mut new_order = target_reorderable.clone();
|
||||
let insert_index = insert_index.min(new_order.len());
|
||||
new_order.splice(insert_index..insert_index, moving);
|
||||
if !self.rewire_chain(layer, &new_order, target_tail_input.clone(), network_path) {
|
||||
self.rewire_chain(layer, &target_reorderable, target_tail_input, network_path);
|
||||
self.rewire_chain(source_layer, &source_reorderable, source_tail_input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Duplicates nodes in their layer's horizontal chain, inserting the copies together (in the originals' relative order) beside the originals, or into the
|
||||
/// `destination` layer's chain (which may be the same one) at the given gap among its reorderable nodes, where gap 0 is beside the layer. The copies keep the
|
||||
/// originals' other (non-primary) inputs, including their connections. Returns the IDs of the copies.
|
||||
pub fn duplicate_chain_nodes(&mut self, node_ids: &[NodeId], destination: Option<(NodeId, usize)>, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let Some((source_layer, reorderable, _)) = self.reorderable_chain_nodes(node_ids, network_path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let (layer, insert_index) = destination.unwrap_or_else(|| (source_layer, reorderable.iter().position(|id| node_ids.contains(id)).unwrap_or_default()));
|
||||
|
||||
let copies = reorderable.iter().filter(|id| node_ids.contains(id)).filter_map(|id| self.copy_chain_node(id, network_path)).collect();
|
||||
self.insert_into_chain(layer, copies, insert_index, network_path)
|
||||
}
|
||||
|
||||
/// Duplicates a node into its primary flow (wires into primary inputs, layers' chain inputs, and exports): a node feeding the flow gets its copy right after it,
|
||||
/// taking over what it fed there, and a node only fed by the flow gets its copy appended to extend the chain. A layer's copy brings a copy of its content.
|
||||
/// Returns the copy, or `None` for a node in no flow (a solo node, or a generator without a primary input), which is left to be duplicated loose.
|
||||
pub fn duplicate_node_in_flow(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
if !self.has_primary_input(node_id, network_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let flow_outputs = self
|
||||
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(*node_id)).cloned().unwrap_or_default())?
|
||||
.into_iter()
|
||||
.filter(|input| self.is_flow_input(input, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
let fed_by_flow = matches!(
|
||||
self.input_from_connector(&InputConnector::primary_input(*node_id), network_path),
|
||||
Some(NodeInput::Node { .. } | NodeInput::Import { .. })
|
||||
);
|
||||
if flow_outputs.is_empty() && !fed_by_flow {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (copy, reconnections) = if self.is_layer(node_id, network_path) {
|
||||
(self.insert_layer_copy(node_id, network_path)?, Vec::new())
|
||||
} else {
|
||||
let Some(input) = self.input_from_connector(&InputConnector::primary_input(*chain.last().unwrap()), network_path).cloned() else {
|
||||
log::error!("Could not get the upstream input of the chain in reorder_chain_node");
|
||||
return;
|
||||
// Offset from the original like a loose copy, unless joining a chain or stack positions it
|
||||
let mut node_copy = self.copy_chain_node(node_id, network_path)?;
|
||||
node_copy.template.node_type_metadata = NodeTypePersistentMetadata::node(self.position(node_id, network_path).unwrap_or_default() + IVec2::new(2, 2));
|
||||
self.insert_copy(node_copy, network_path)?
|
||||
};
|
||||
|
||||
// The copy takes over what the original fed in the flow and is fed by the original, then gets back its other wires (refusing any that would close a cycle)
|
||||
for input in &flow_outputs {
|
||||
self.set_input(input, NodeInput::node(copy, 0), network_path);
|
||||
}
|
||||
self.set_input(&InputConnector::primary_input(copy), NodeInput::node(*node_id, 0), network_path);
|
||||
for (input_connector, input) in reconnections {
|
||||
self.set_input(&input_connector, input, network_path);
|
||||
}
|
||||
|
||||
Some(copy)
|
||||
}
|
||||
|
||||
/// Whether an input carries a node's primary flow onward: a primary input, a layer's chain input, or an export.
|
||||
fn is_flow_input(&self, input: &InputConnector, network_path: &[NodeId]) -> bool {
|
||||
match input {
|
||||
InputConnector::Node { input_index: 0, .. } | InputConnector::Export(_) => true,
|
||||
InputConnector::Node { node_id, input_index: 1 } => self.is_layer(node_id, network_path),
|
||||
InputConnector::Node { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a copy of a layer along with its own copy of the layer's content, offset from the original. Returns the copy of the layer.
|
||||
fn insert_layer_copy(&mut self, layer: &NodeId, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
let mut copy_ids = HashMap::from([(*layer, NodeId(0))]);
|
||||
for (index, node_id) in self.upstream_flow_back_from_nodes(vec![*layer], network_path, FlowType::LayerChildrenUpstreamFlow).enumerate() {
|
||||
copy_ids.insert(node_id, NodeId(index as u64 + 1));
|
||||
}
|
||||
|
||||
let nodes = self.copy_nodes(©_ids, network_path).collect::<Vec<_>>();
|
||||
let new_ids = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect::<HashMap<_, _>>();
|
||||
let copy = *new_ids.get(&NodeId(0))?;
|
||||
self.insert_node_group(nodes, new_ids, network_path);
|
||||
|
||||
Some(copy)
|
||||
}
|
||||
|
||||
/// Inserts copied nodes together (in their given order) into a layer's chain at the insertion point. Returns the IDs of the new nodes.
|
||||
pub fn paste_into_chain(&mut self, target: ChainInsertionPoint, copies: Vec<ChainNodeCopy>, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let (layer, insert_index) = match target {
|
||||
ChainInsertionPoint::BesideLayer(layer) => (layer, 0),
|
||||
ChainInsertionPoint::BesideNode(node_id) => {
|
||||
let Some((layer, reorderable, _)) = self.reorderable_chain_nodes(&[node_id], network_path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
(layer, reorderable.iter().position(|id| *id == node_id).unwrap_or_default())
|
||||
}
|
||||
};
|
||||
|
||||
self.insert_into_chain(layer, copies, insert_index, network_path)
|
||||
}
|
||||
|
||||
/// Copies a node from a layer's chain so it can be inserted into a chain here or in another document.
|
||||
pub fn copy_chain_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<ChainNodeCopy> {
|
||||
// Placed where its original is until the chain it's inserted into positions it
|
||||
let mut template = self.create_node_template(node_id, network_path)?;
|
||||
template.node_type_metadata = NodeTypePersistentMetadata::node(self.position(node_id, network_path).unwrap_or_default());
|
||||
|
||||
let fallback_values = template
|
||||
.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, input)| matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }))
|
||||
.map(|(index, _)| {
|
||||
(
|
||||
index,
|
||||
NodeInput::value(self.tagged_value_from_input(&InputConnector::node_at_index(*node_id, index), network_path), true),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(ChainNodeCopy {
|
||||
source: *node_id,
|
||||
template,
|
||||
fallback_values,
|
||||
})
|
||||
}
|
||||
|
||||
/// The nodes of a layer's chain that can be reordered (all but a source node fixed at its upstream end), ordered from the layer outward.
|
||||
pub fn reorderable_chain(&self, layer: NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
self.layer_chain(layer, network_path).map(|(reorderable, _)| reorderable).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// All nodes in a layer's chain, ordered from the layer outward, stopping where the next layer begins (since flow turns from horizontal to vertical there).
|
||||
pub fn layer_chain_nodes(&self, layer: NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
self.upstream_flow_back_from_nodes(vec![layer], network_path, FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|upstream_id| !self.is_layer(upstream_id, network_path))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Inserts copied nodes together (in their given order) into a layer's chain at the `insert_index` gap among its reorderable nodes, where gap 0 is beside
|
||||
/// the layer. Each copy stays wired to whatever fed its other (non-primary) inputs where that exists here without closing a cycle, or else takes their
|
||||
/// fallback values. Returns the IDs of the new nodes, or none when they can't join the chain.
|
||||
fn insert_into_chain(&mut self, layer: NodeId, copies: Vec<ChainNodeCopy>, insert_index: usize, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let Some((reorderable, tail_input)) = self.layer_chain(layer, network_path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut new_ids = Vec::new();
|
||||
let mut reconnections = Vec::new();
|
||||
for copy in copies {
|
||||
let Some((new_id, copy_reconnections)) = self.insert_copy(copy, network_path) else { continue };
|
||||
new_ids.push(new_id);
|
||||
reconnections.extend(copy_reconnections);
|
||||
}
|
||||
|
||||
let mut new_order = reorderable.clone();
|
||||
let insert_index = insert_index.min(new_order.len());
|
||||
new_order.splice(insert_index..insert_index, new_ids.iter().copied());
|
||||
|
||||
// Copies that would close a cycle are removed, and the chain is put back as it was
|
||||
if !self.rewire_chain(layer, &new_order, tail_input.clone(), network_path) {
|
||||
self.rewire_chain(layer, &reorderable, tail_input, network_path);
|
||||
self.delete_nodes(new_ids, false, network_path);
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Reconnected only once the copies are in the chain, so a wire that would close a cycle through it is refused and leaves the fallback value
|
||||
for (input_connector, input) in reconnections {
|
||||
self.set_input(&input_connector, input, network_path);
|
||||
}
|
||||
|
||||
new_ids
|
||||
}
|
||||
|
||||
/// Inserts a copied node with its wired inputs set to their fallback values (as `insert_node` requires). Returns the new node along with the wires to
|
||||
/// restore to its other (non-primary) inputs where their sources exist here, which the caller reconnects once the node is wired in so the bookkeeping
|
||||
/// stays current and a wire that would close a cycle is refused.
|
||||
fn insert_copy(&mut self, copy: ChainNodeCopy, network_path: &[NodeId]) -> Option<(NodeId, Vec<(InputConnector, NodeInput)>)> {
|
||||
let ChainNodeCopy { mut template, fallback_values, .. } = copy;
|
||||
let new_id = NodeId::new();
|
||||
|
||||
let mut reconnections = Vec::new();
|
||||
for (index, fallback_value) in fallback_values {
|
||||
let Some(input) = template.inputs.get_mut(index) else { continue };
|
||||
let wired_input = std::mem::replace(input, fallback_value);
|
||||
if index == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A copy from another document names sources missing here, so they're looked up without logging an error
|
||||
let source_exists = match &wired_input {
|
||||
NodeInput::Node { node_id, .. } => self.nested_network(network_path).is_some_and(|network| network.nodes.contains_key(node_id)),
|
||||
NodeInput::Import { import_index, .. } => *import_index < self.number_of_imports(network_path),
|
||||
_ => false,
|
||||
};
|
||||
input
|
||||
if source_exists {
|
||||
reconnections.push((InputConnector::node_at_index(new_id, index), wired_input));
|
||||
}
|
||||
}
|
||||
if template.inputs.iter().any(|input| matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. })) {
|
||||
log::error!("A copied node is missing the fallback value for a wired input in insert_copy");
|
||||
return None;
|
||||
}
|
||||
|
||||
self.insert_node(new_id, template, network_path);
|
||||
Some((new_id, reconnections))
|
||||
}
|
||||
|
||||
/// The layer whose chain the given nodes belong to, along with what `layer_chain` gives for it. Fails unless every given node is a reorderable node of that chain.
|
||||
fn reorderable_chain_nodes(&self, node_ids: &[NodeId], network_path: &[NodeId]) -> Option<(NodeId, Vec<NodeId>, NodeInput)> {
|
||||
let first_node_id = node_ids.first()?;
|
||||
let Some(layer) = self.downstream_layer_for_chain_node(first_node_id, network_path) else {
|
||||
log::error!("Could not find downstream layer for chain node {first_node_id} in reorderable_chain_nodes");
|
||||
return None;
|
||||
};
|
||||
let (reorderable, tail_input) = self.layer_chain(layer, network_path)?;
|
||||
|
||||
if let Some(node_id) = node_ids.iter().find(|node_id| !reorderable.contains(node_id)) {
|
||||
log::error!("Node {node_id} is not a reorderable node in the same layer's chain in reorderable_chain_nodes");
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((layer, reorderable, tail_input))
|
||||
}
|
||||
|
||||
/// A layer chain's reorderable nodes (all but a source node fixed at its upstream end) ordered from the layer outward, and whatever feeds the chain's upstream end.
|
||||
fn layer_chain(&self, layer: NodeId, network_path: &[NodeId]) -> Option<(Vec<NodeId>, NodeInput)> {
|
||||
if !self.is_layer(&layer, network_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let chain = self.layer_chain_nodes(layer, network_path);
|
||||
|
||||
// A source node (no primary input) stays pinned at the most-upstream end; only the nodes below it reorder
|
||||
let pinned_source = chain.last().copied().filter(|last| !self.has_primary_input(last, network_path));
|
||||
let reorderable = chain[..chain.len() - pinned_source.is_some() as usize].to_vec();
|
||||
|
||||
// The most-upstream reorderable node connects up to the pinned source, or else whatever fed the top of the chain (or the layer, when the chain is empty)
|
||||
let tail_input = match (pinned_source, chain.last()) {
|
||||
(Some(source), _) => NodeInput::node(source, 0),
|
||||
(None, Some(last)) => self.input_from_connector(&InputConnector::primary_input(*last), network_path)?.clone(),
|
||||
(None, None) => self.input_from_connector(&InputConnector::layer_secondary_input(layer), network_path)?.clone(),
|
||||
};
|
||||
|
||||
Some((reorderable, tail_input))
|
||||
}
|
||||
|
||||
/// Rewires a layer's chain to run through `new_order` from the layer outward, with the last node fed by `tail_input`.
|
||||
/// Returns whether that took, since a connection that would close a cycle is refused.
|
||||
fn rewire_chain(&mut self, layer: NodeId, new_order: &[NodeId], tail_input: NodeInput, network_path: &[NodeId]) -> bool {
|
||||
let intended_chain = Some((new_order.to_vec(), tail_input.clone()));
|
||||
|
||||
// With no nodes left in the chain, the layer is fed directly by what fed its upstream end
|
||||
let (Some(&first), Some(&last)) = (new_order.first(), new_order.last()) else {
|
||||
self.set_input(&InputConnector::layer_secondary_input(layer), tail_input, network_path);
|
||||
return self.layer_chain(layer, network_path) == intended_chain;
|
||||
};
|
||||
|
||||
// Disconnect first so the rewiring can't transiently form a cycle (the pinned source keeps its wiring)
|
||||
for &chain_node in reorderable {
|
||||
for &chain_node in new_order {
|
||||
self.disconnect_input(&InputConnector::primary_input(chain_node), network_path);
|
||||
}
|
||||
|
||||
// Rewire in the new order: layer's secondary input -> new_order[0] -> ... -> new_order[last] -> tail input
|
||||
self.set_input(&InputConnector::layer_secondary_input(layer), NodeInput::node(new_order[0], 0), network_path);
|
||||
self.set_input(&InputConnector::layer_secondary_input(layer), NodeInput::node(first, 0), network_path);
|
||||
for pair in new_order.windows(2) {
|
||||
self.set_input(&InputConnector::primary_input(pair[0]), NodeInput::node(pair[1], 0), network_path);
|
||||
}
|
||||
self.set_input(&InputConnector::primary_input(*new_order.last().unwrap()), tail_input, network_path);
|
||||
self.set_input(&InputConnector::primary_input(last), tail_input, network_path);
|
||||
|
||||
// Re-establish chain positioning for the reordered nodes
|
||||
self.force_set_upstream_to_chain(&new_order[0], network_path);
|
||||
// Re-establish chain positioning for the rewired nodes
|
||||
self.force_set_upstream_to_chain(&first, network_path);
|
||||
|
||||
self.layer_chain(layer, network_path) == intended_chain
|
||||
}
|
||||
}
|
||||
+23
-9
@@ -945,11 +945,19 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub fn start_previewing_without_restore(&mut self, network_path: &[NodeId]) {
|
||||
// Some logic will have to be performed to prevent the graph positions from being completely changed when the export changes to some previewed node
|
||||
let Some(mut network) = self.network_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in start_previewing_without_restore");
|
||||
return;
|
||||
};
|
||||
network.set_previewing(Previewing::Yes { root_node_to_restore: None });
|
||||
self.set_previewing_state(Previewing::Yes { root_node_to_restore: None }, network_path);
|
||||
}
|
||||
|
||||
/// While previewing, changes which node output the export is reconnected to once the preview ends.
|
||||
pub fn set_root_node_to_restore(&mut self, root_node_to_restore: RootNode, network_path: &[NodeId]) {
|
||||
if let Previewing::Yes { .. } = self.previewing(network_path) {
|
||||
self.set_previewing_state(
|
||||
Previewing::Yes {
|
||||
root_node_to_restore: Some(root_node_to_restore),
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_previewing(&mut self, network_path: &[NodeId]) {
|
||||
@@ -964,11 +972,18 @@ impl NodeNetworkInterface {
|
||||
);
|
||||
}
|
||||
|
||||
self.set_previewing_state(Previewing::No, network_path);
|
||||
}
|
||||
|
||||
fn set_previewing_state(&mut self, previewing: Previewing, network_path: &[NodeId]) {
|
||||
let Some(mut network) = self.network_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in stop_previewing");
|
||||
log::error!("Could not get nested network_metadata in set_previewing_state");
|
||||
return;
|
||||
};
|
||||
network.set_previewing(Previewing::No);
|
||||
network.set_previewing(previewing);
|
||||
|
||||
// The export's wire is dashed only while previewing
|
||||
self.unload_wire(&InputConnector::Export(0), network_path);
|
||||
}
|
||||
|
||||
pub fn set_display_name(&mut self, node_id: &NodeId, display_name: String, network_path: &[NodeId]) {
|
||||
@@ -1254,7 +1269,6 @@ impl NodeNetworkInterface {
|
||||
self.disconnect_input(&InputConnector::Export(0), network_path);
|
||||
}
|
||||
}
|
||||
let Some(mut network) = self.network_mut(network_path) else { return };
|
||||
network.set_previewing(new_previewing_state);
|
||||
self.set_previewing_state(new_previewing_state, network_path);
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,11 @@ impl NodeNetworkInterface {
|
||||
self.transaction_status
|
||||
}
|
||||
|
||||
/// The document network nodes the open transaction has written to, as of the last [`Self::update_transaction_edited_nodes`].
|
||||
pub fn transaction_edited_nodes(&self) -> &HashSet<NodeId> {
|
||||
&self.transaction_edited_nodes
|
||||
}
|
||||
|
||||
pub fn selected_nodes(&self) -> SelectedNodes {
|
||||
self.selected_nodes_in_nested_network(&[]).unwrap_or_default()
|
||||
}
|
||||
@@ -510,6 +515,13 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||
}
|
||||
|
||||
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||
self.reference(node_id, network_path)
|
||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||
.unwrap_or("NodeCustomNode")
|
||||
}
|
||||
|
||||
pub fn implementation(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeImplementation> {
|
||||
self.query(network_path, "implementation", |view| view.implementation(node_id))
|
||||
}
|
||||
|
||||
+101
-25
@@ -4,6 +4,7 @@ use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
|
||||
use graphene_std::NodeIOTypes;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
@@ -11,6 +12,23 @@ 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};
|
||||
|
||||
/// Whether a `source` type can feed a `connector` type, directly or through the `input_adapter` node the compiler inserts to convert elements (such as `Color` into `Graphic`).
|
||||
pub fn type_feeds_connector(source: &Type, connector: &Type) -> bool {
|
||||
let source = source.nested_type();
|
||||
let connector = connector.nested_type();
|
||||
if source == connector {
|
||||
return true;
|
||||
}
|
||||
|
||||
let (Type::Item(element) | Type::List(element)) = connector else { return false };
|
||||
let adapter = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{}>", element.identifier_name()));
|
||||
NODE_REGISTRY.get(&adapter).is_some_and(|implementations| {
|
||||
implementations
|
||||
.keys()
|
||||
.any(|node_io| node_io.return_value.nested_type() == connector && node_io.inputs.first().is_some_and(|input| input.nested_type() == source))
|
||||
})
|
||||
}
|
||||
|
||||
// This file contains utility methods for interfacing with the resolved types returned from the compiler
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ResolvedDocumentNodeTypes {
|
||||
@@ -290,31 +308,10 @@ impl NodeNetworkInterface {
|
||||
|
||||
intersection.into_iter().collect::<Vec<_>>()
|
||||
}
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
|
||||
let Some(implementations) = NODE_REGISTRY.get(proto_node_identifier) else {
|
||||
// The compiler removes the passthrough node, so it's expected to be absent from the registry
|
||||
if proto_node_identifier != &graphene_std::ops::passthrough::IDENTIFIER {
|
||||
log::error!("Proto node `{proto_node_identifier:?}` not found in the node registry, in potential_valid_input_types");
|
||||
}
|
||||
return Vec::new();
|
||||
};
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
implementations
|
||||
.keys()
|
||||
.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_at_index(*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::ProtoNode(proto_node_identifier) => self
|
||||
.implementations_matching_inputs(proto_node_identifier, node_id, Some(*input_index), network_path)
|
||||
.filter_map(|node_io| node_io.inputs.get(*input_index).cloned())
|
||||
.collect::<Vec<_>>(),
|
||||
DocumentNodeImplementation::Extract => {
|
||||
log::error!("Input types for extract node not supported");
|
||||
Vec::new()
|
||||
@@ -322,6 +319,63 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// The types an output could produce: its compiled type, or else the return types of the registry implementations matching its node's inputs.
|
||||
pub fn potential_output_types(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Vec<Type> {
|
||||
if let Some(compiled_type) = self.output_type(output_connector, network_path).compiled_nested_type() {
|
||||
return vec![compiled_type.clone()];
|
||||
}
|
||||
|
||||
// Nodes outside the compiled graph, such as disconnected ones, have no resolved type
|
||||
let OutputConnector::Node { node_id, output_index: 0 } = output_connector else {
|
||||
log::debug!("[wire-drag] No registry fallback for {output_connector:?}");
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
log::debug!("[wire-drag] No registry fallback for non-proto node implementation {:?}", self.implementation(node_id, network_path));
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let all_implementations = NODE_REGISTRY.get(proto_node_identifier).map(|implementations| implementations.keys().cloned().collect::<Vec<_>>());
|
||||
let input_types = (0..self.number_of_inputs(node_id, network_path))
|
||||
.map(|index| self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, index), network_path))
|
||||
.collect::<Vec<_>>();
|
||||
log::debug!("[wire-drag] Registry fallback for {proto_node_identifier:?} with input types {input_types:?} among implementations {all_implementations:?}");
|
||||
|
||||
self.implementations_matching_inputs(proto_node_identifier, node_id, None, network_path)
|
||||
.map(|node_io| node_io.return_value.nested_type().clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The registry implementations of a proto node whose inputs accept the node's current input types, ignoring `disregarded_input_index`.
|
||||
fn implementations_matching_inputs<'a>(
|
||||
&'a self,
|
||||
proto_node_identifier: &ProtoNodeIdentifier,
|
||||
node_id: &'a NodeId,
|
||||
disregarded_input_index: Option<usize>,
|
||||
network_path: &'a [NodeId],
|
||||
) -> impl Iterator<Item = &'static NodeIOTypes> + 'a {
|
||||
let implementations = NODE_REGISTRY.get(proto_node_identifier);
|
||||
|
||||
// The compiler removes the passthrough node, so it's expected to be absent from the registry
|
||||
if implementations.is_none() && proto_node_identifier != &graphene_std::ops::passthrough::IDENTIFIER {
|
||||
log::error!("Proto node `{proto_node_identifier:?}` not found in the node registry");
|
||||
}
|
||||
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
implementations.into_iter().flat_map(|implementations| implementations.keys()).filter(move |node_io| {
|
||||
(0..number_of_inputs).filter(|index| Some(*index) != disregarded_input_index).all(|index| {
|
||||
let input_type = self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, 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
|
||||
match (input_type.compiled_nested_type(), node_io.inputs.get(index)) {
|
||||
(Some(source), Some(connector)) => type_feeds_connector(source, connector),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Performs a downstream traversal to ensure input type will work in the full context of the graph.
|
||||
pub fn complete_valid_input_types(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
|
||||
match input_connector {
|
||||
@@ -465,3 +519,25 @@ impl NodeNetworkInterface {
|
||||
intersection.into_iter().collect::<Vec<_>>()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::type_feeds_connector;
|
||||
use graph_craft::item;
|
||||
use graphene_std::vector::style::DashPattern;
|
||||
use graphene_std::{Color, Graphic};
|
||||
|
||||
#[test]
|
||||
fn input_adapter_conversions_feed_connectors() {
|
||||
assert!(type_feeds_connector(&item!(f64), &item!(f64)), "identical types should match directly");
|
||||
assert!(
|
||||
type_feeds_connector(&item!(Color), &item!(Graphic)),
|
||||
"a color paint should feed a graphic paint connector through its input adapter"
|
||||
);
|
||||
assert!(
|
||||
type_feeds_connector(&item!(f64), &item!(DashPattern)),
|
||||
"a number should feed a dash pattern connector through its input adapter"
|
||||
);
|
||||
assert!(!type_feeds_connector(&item!(f64), &item!(Graphic)), "a number has no conversion into a graphic");
|
||||
}
|
||||
}
|
||||
+47
-2
@@ -319,16 +319,61 @@ impl NodeNetworkInterface {
|
||||
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
|
||||
}
|
||||
|
||||
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty.
|
||||
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty
|
||||
/// after reading it for the nodes an open transaction has written to.
|
||||
pub(crate) fn take_deltas(&mut self) -> Vec<EditorDelta> {
|
||||
self.scan_transaction_edited_nodes();
|
||||
self.transaction_edited_nodes_scanned = 0;
|
||||
std::mem::take(&mut self.deltas)
|
||||
}
|
||||
|
||||
/// Drops what the writes since the last drain changed, for writes that are not edits to the document.
|
||||
/// Drops what the writes since the last drain changed, for writes that are not edits to the document,
|
||||
/// after reading it for the nodes an open transaction has written to.
|
||||
pub(crate) fn discard_deltas(&mut self) {
|
||||
self.scan_transaction_edited_nodes();
|
||||
self.transaction_edited_nodes_scanned = 0;
|
||||
self.deltas.clear();
|
||||
}
|
||||
|
||||
/// Reads the open transaction's writes since the last call, returning whether that changed which nodes it has written to.
|
||||
pub fn update_transaction_edited_nodes(&mut self) -> bool {
|
||||
self.scan_transaction_edited_nodes();
|
||||
std::mem::take(&mut self.transaction_edited_nodes_changed)
|
||||
}
|
||||
|
||||
/// Notes the document network nodes that the unread writes of an open transaction added, or set an input value of.
|
||||
fn scan_transaction_edited_nodes(&mut self) {
|
||||
if self.transaction_status != TransactionStatus::Finished {
|
||||
let new_deltas = self.deltas.get(self.transaction_edited_nodes_scanned..).unwrap_or_default();
|
||||
let edited_nodes = new_deltas
|
||||
.iter()
|
||||
.filter_map(|delta| match delta {
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, .. } | RuntimeDelta::ReplaceNode { network_path, node_id, .. }) if network_path.is_empty() => Some(*node_id),
|
||||
// Judged by what the input holds now, since splicing in a node briefly disconnects a wire to a placeholder value
|
||||
EditorDelta::Graph(RuntimeDelta::SetInput {
|
||||
network_path, node_id, input_index, ..
|
||||
}) if network_path.is_empty() => {
|
||||
let input = self.input_from_connector(&InputConnector::node_at_index(*node_id, *input_index), &[]);
|
||||
input.is_some_and(|input| input.as_value().is_some()).then_some(*node_id)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for node_id in edited_nodes {
|
||||
self.transaction_edited_nodes_changed |= self.transaction_edited_nodes.insert(node_id);
|
||||
}
|
||||
}
|
||||
self.transaction_edited_nodes_scanned = self.deltas.len();
|
||||
}
|
||||
|
||||
pub(super) fn clear_transaction_edited_nodes(&mut self) {
|
||||
if !self.transaction_edited_nodes.is_empty() {
|
||||
self.transaction_edited_nodes.clear();
|
||||
self.transaction_edited_nodes_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
|
||||
/// once its signature is edited.
|
||||
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
|
||||
|
||||
@@ -29,6 +29,46 @@ pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
path
|
||||
}
|
||||
|
||||
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ChainNodeCopy {
|
||||
/// The node that was copied.
|
||||
pub source: NodeId,
|
||||
pub template: NodeTemplate,
|
||||
/// The value of each input wired to another node, which the copy takes where that node is missing.
|
||||
pub fallback_values: Vec<(usize, NodeInput)>,
|
||||
}
|
||||
|
||||
impl ChainNodeCopy {
|
||||
/// The copied node with each of its wired inputs taking its fallback value, placed offset from its original, for pasting outside any flow.
|
||||
pub fn into_loose_template(self) -> NodeTemplate {
|
||||
let mut template = self.template;
|
||||
for (index, fallback_value) in self.fallback_values {
|
||||
if let Some(input) = template.inputs.get_mut(index) {
|
||||
*input = fallback_value;
|
||||
}
|
||||
}
|
||||
|
||||
if let NodeTypePersistentMetadata::Node(NodePersistentMetadata {
|
||||
position: NodePosition::Absolute(position),
|
||||
}) = &mut template.node_type_metadata
|
||||
{
|
||||
*position += IVec2::new(2, 2);
|
||||
}
|
||||
|
||||
template
|
||||
}
|
||||
}
|
||||
|
||||
/// Where copied nodes go when inserted into a layer's chain.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ChainInsertionPoint {
|
||||
/// Beside a node in a layer's chain, just downstream of it.
|
||||
BesideNode(NodeId),
|
||||
/// At the downstream end of a layer's chain, beside the layer.
|
||||
BesideLayer(NodeId),
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum FlowType {
|
||||
/// Iterate over all upstream nodes (inclusive) from every input (the primary and all secondary).
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use super::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
@@ -30,7 +31,22 @@ pub struct LayerPanelEntry {
|
||||
#[serde(rename = "implementationName")]
|
||||
pub implementation_name: String,
|
||||
#[serde(rename = "iconName")]
|
||||
pub icon_name: Option<IconName>,
|
||||
pub icon_name: IconName,
|
||||
/// The nodes in the chain feeding this layer, in the graph's left-to-right order.
|
||||
#[serde(rename = "chainNodes")]
|
||||
pub chain_nodes: Vec<LayerPanelChainNode>,
|
||||
/// The data type flowing from the chain into the layer, which colors the connector between them.
|
||||
#[serde(rename = "chainDataType")]
|
||||
pub chain_data_type: FrontendGraphDataType,
|
||||
/// How the active tool edits the layer node itself, if it does, for the tooltip of its outlined icon.
|
||||
#[serde(rename = "toolTargetDescription")]
|
||||
pub tool_target_description: Option<String>,
|
||||
/// Whether an edit in progress, like a drag, has written to the layer node itself, which brightens its icon's outline.
|
||||
#[serde(rename = "editInProgress")]
|
||||
pub edit_in_progress: bool,
|
||||
/// The node the active tool would add to the chain to edit this layer, shown ghosted where it would go.
|
||||
#[serde(rename = "toolTargetInsertion")]
|
||||
pub tool_target_insertion: Option<LayerPanelChainInsertion>,
|
||||
pub alias: String,
|
||||
#[serde(rename = "inSelectedNetwork")]
|
||||
pub in_selected_network: bool,
|
||||
@@ -45,6 +61,37 @@ pub struct LayerPanelEntry {
|
||||
pub clippable: bool,
|
||||
}
|
||||
|
||||
/// A node in the chain feeding a layer, shown as a button with its icon in the layer's row.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
|
||||
pub struct LayerPanelChainNode {
|
||||
pub id: NodeId,
|
||||
pub icon: IconName,
|
||||
pub name: String,
|
||||
/// Whether the node is selected, shown in every layer whose chain shares it.
|
||||
pub selected: bool,
|
||||
/// Whether the node can be dragged to reorder it, unlike a source node (with no primary input) fixed at the chain's upstream end.
|
||||
pub reorderable: bool,
|
||||
pub visible: bool,
|
||||
/// How the active tool edits this node, if it does, for the tooltip of its outlined icon.
|
||||
#[serde(rename = "toolTargetDescription")]
|
||||
pub tool_target_description: Option<String>,
|
||||
/// Whether an edit in progress, like a drag, has written to this node, which brightens its outline.
|
||||
#[serde(rename = "editInProgress")]
|
||||
pub edit_in_progress: bool,
|
||||
}
|
||||
|
||||
/// A node not yet in a layer's chain, which the active tool would add there.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
|
||||
pub struct LayerPanelChainInsertion {
|
||||
/// The position among the chain nodes, counted from the upstream end.
|
||||
pub index: u32,
|
||||
pub icon: IconName,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
/// IMPORTANT: the same node may appear multiple times.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::messages::portfolio::document_storage_io::{
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
use crate::messages::tool::utility_types::{HintData, ToolType};
|
||||
use crate::messages::viewport::ToPhysical;
|
||||
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
|
||||
@@ -37,6 +38,7 @@ pub struct PortfolioMessageContext<'a> {
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub animation: &'a AnimationMessageHandler,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub tool_edit_target: &'a EditTarget,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
pub timing_information: TimingInformation,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
@@ -71,6 +73,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
preferences,
|
||||
animation,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
reset_node_definitions_on_open,
|
||||
timing_information,
|
||||
viewport,
|
||||
@@ -89,6 +92,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
fonts: &self.fonts,
|
||||
executor: &mut self.executor,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
preferences,
|
||||
viewport,
|
||||
resource_storage,
|
||||
@@ -96,7 +100,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
layers_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace.panel_layout.focus_document,
|
||||
properties_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Properties) && !self.workspace.panel_layout.focus_document,
|
||||
};
|
||||
document.process_message(message, responses, document_inputs)
|
||||
document.process_message(message, responses, document_inputs);
|
||||
refresh_transaction_edited_nodes(document, true, responses);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::PersistentState(message) => {
|
||||
@@ -169,6 +174,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// Send the information for tooltips and categories for each node/input.
|
||||
responses.add(FrontendMessage::SendUIMetadata {
|
||||
node_descriptions: document_node_definitions::collect_node_descriptions(),
|
||||
node_icons: document_node_definitions::collect_node_icons(),
|
||||
node_types: document_node_definitions::collect_node_types(),
|
||||
});
|
||||
}
|
||||
@@ -180,6 +186,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
fonts: &self.fonts,
|
||||
executor: &mut self.executor,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
preferences,
|
||||
viewport,
|
||||
resource_storage,
|
||||
@@ -187,7 +194,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
layers_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace.panel_layout.focus_document,
|
||||
properties_panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::Properties) && !self.workspace.panel_layout.focus_document,
|
||||
};
|
||||
document.process_message(message, responses, document_inputs)
|
||||
document.process_message(message, responses, document_inputs);
|
||||
refresh_transaction_edited_nodes(document, self.active_document_id == Some(document_id), responses);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::AutoSaveActiveDocument => {
|
||||
@@ -1268,6 +1276,13 @@ impl PortfolioMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets the Layers panel brighten the nodes an edit in progress, like a drag, has written to so far.
|
||||
fn refresh_transaction_edited_nodes(document: &mut DocumentMessageHandler, is_active: bool, responses: &mut VecDeque<Message>) {
|
||||
if document.network_interface.update_transaction_edited_nodes() && is_active {
|
||||
responses.add(NodeGraphMessage::UpdateLayerPanel);
|
||||
}
|
||||
}
|
||||
|
||||
/// The name an opened file gets: the given name, else the file stem of its path, else empty so the portfolio generates one.
|
||||
fn opened_document_name(name: Option<String>, path: Option<&Path>) -> String {
|
||||
name.filter(|name| !name.trim().is_empty())
|
||||
|
||||
@@ -388,7 +388,7 @@ impl WorkspaceMessageHandler {
|
||||
fn destroy_panel_layouts(panel_type: PanelType, responses: &mut VecDeque<Message>) {
|
||||
let targets: &[LayoutTarget] = match panel_type {
|
||||
PanelType::Properties => &[LayoutTarget::PropertiesPanel],
|
||||
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelControlRightBar, LayoutTarget::LayersPanelBottomBar],
|
||||
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelBottomLeftBar, LayoutTarget::LayersPanelBottomRightBar],
|
||||
PanelType::Data => &[LayoutTarget::DataPanel],
|
||||
PanelType::Document | PanelType::Welcome => return,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
/// What a tool edits in each layer, picked out per layer by [`EditTarget::resolve`] with the same lookups the tool's edits use.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub enum EditTarget {
|
||||
/// The tool doesn't edit layers.
|
||||
#[default]
|
||||
Nothing,
|
||||
/// The downstream-most visible node with this definition in the layer's chain (or the layer node itself), or else the one `insertion` adds.
|
||||
ChainNode { definition: DefinitionIdentifier, insertion: Insertion },
|
||||
/// The first of these which applies to the layer, by their order here rather than their order in the chain.
|
||||
FirstApplicable(Vec<EditTarget>),
|
||||
}
|
||||
|
||||
/// Whether, and where, a tool adds the node it edits to a layer's chain that lacks one.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Insertion {
|
||||
Never,
|
||||
/// As the chain's most downstream node, directly feeding the layer.
|
||||
BesideLayer,
|
||||
/// Beside the layer, only in layers with vector content.
|
||||
BesideVectorLayer,
|
||||
/// Beside the layer, only in layers with vector content, but upstream of a visible Stroke node there so the stroke keeps painting on top.
|
||||
UnderStroke,
|
||||
}
|
||||
|
||||
/// The node an [`EditTarget`] picks out in a layer.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ResolvedEditTarget {
|
||||
/// A node in the layer's chain, or the layer node itself.
|
||||
Edited(NodeId),
|
||||
/// A node the tool would add, at this position among the chain nodes counted from the upstream end.
|
||||
Inserted { definition: DefinitionIdentifier, index: usize },
|
||||
}
|
||||
|
||||
impl ResolvedEditTarget {
|
||||
/// The existing node to outline, which is none when the tool would add one.
|
||||
pub fn outlined_node(&self) -> Option<NodeId> {
|
||||
match self {
|
||||
Self::Edited(node) => Some(*node),
|
||||
Self::Inserted { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tooltip description of the node in a Layers panel row.
|
||||
pub fn tooltip_description(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Edited(_) => "Edited by the active tool.",
|
||||
Self::Inserted { .. } => "Inserted here when the active tool edits this layer.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EditTarget {
|
||||
pub fn proto_node(identifier: ProtoNodeIdentifier, insertion: Insertion) -> Self {
|
||||
Self::ChainNode {
|
||||
definition: DefinitionIdentifier::ProtoNode(identifier),
|
||||
insertion,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn network_node(name: &str, insertion: Insertion) -> Self {
|
||||
Self::ChainNode {
|
||||
definition: DefinitionIdentifier::Network(name.into()),
|
||||
insertion,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Transform node, which transform edits insert beside the layer when it's missing.
|
||||
pub fn transform() -> Self {
|
||||
Self::proto_node(graphene_std::transform_nodes::transform::IDENTIFIER, Insertion::BesideLayer)
|
||||
}
|
||||
|
||||
/// The Path node, which vector edits insert beside a layer with vector content when it's missing.
|
||||
pub fn path() -> Self {
|
||||
Self::network_node("Path", Insertion::BesideVectorLayer)
|
||||
}
|
||||
|
||||
/// The Fill node, which paint edits insert under any Stroke node beside a layer with vector content when it's missing.
|
||||
pub fn fill() -> Self {
|
||||
Self::proto_node(graphene_std::vector_nodes::fill::IDENTIFIER, Insertion::UnderStroke)
|
||||
}
|
||||
|
||||
pub fn resolve(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<ResolvedEditTarget> {
|
||||
match self {
|
||||
Self::Nothing => None,
|
||||
Self::ChainNode { definition, insertion } => Self::resolve_chain_node(definition, *insertion, layer, network_interface),
|
||||
Self::FirstApplicable(targets) => targets.iter().find_map(|target| target.resolve(layer, network_interface)),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_chain_node(definition: &DefinitionIdentifier, insertion: Insertion, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<ResolvedEditTarget> {
|
||||
if let Some(node_id) = ModifyInputsContext::locate_node_in_layer_chain(definition, layer, network_interface) {
|
||||
return Some(ResolvedEditTarget::Edited(node_id));
|
||||
}
|
||||
|
||||
let has_vector_content = network_interface.document_metadata().layer_vector_data.contains_key(&layer);
|
||||
let chain = network_interface.layer_chain_nodes(layer.to_node(), &[]);
|
||||
let index = match insertion {
|
||||
Insertion::Never => return None,
|
||||
Insertion::BesideVectorLayer | Insertion::UnderStroke if !has_vector_content => return None,
|
||||
Insertion::BesideLayer | Insertion::BesideVectorLayer => chain.len(),
|
||||
Insertion::UnderStroke => {
|
||||
let stroke = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||
let beside_stroke = chain
|
||||
.first()
|
||||
.is_some_and(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&stroke) && network_interface.is_visible(node_id, &[]));
|
||||
chain.len() - usize::from(beside_stroke)
|
||||
}
|
||||
};
|
||||
|
||||
Some(ResolvedEditTarget::Inserted {
|
||||
definition: definition.clone(),
|
||||
index,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,28 @@ pub fn new_svg_layer(svg: String, transform: glam::DAffine2, center: bool, id: N
|
||||
LayerNodeIdentifier::new_unchecked(id)
|
||||
}
|
||||
|
||||
/// Create the locked, solid white "Background" layer that an infinite canvas document begins with, at the given index of the root stack.
|
||||
pub fn new_background_layer(insert_index: usize, responses: &mut VecDeque<Message>) {
|
||||
let node_id = NodeId::new();
|
||||
|
||||
responses.add(GraphOperationMessage::NewColorFillLayer {
|
||||
node_id,
|
||||
color: Color::WHITE,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
alias: "Background".to_string(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id,
|
||||
network_path: Vec::new(),
|
||||
locked: true,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn new_custom(id: NodeId, nodes: Vec<(NodeId, NodeTemplate)>, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
|
||||
responses.add(GraphOperationMessage::NewCustomLayer { id, nodes, parent, insert_index: 0 });
|
||||
responses.add(GraphOperationMessage::SetUpstreamToChain {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod auto_panning;
|
||||
pub mod color_selector;
|
||||
pub mod compass_rose;
|
||||
pub mod edit_target;
|
||||
pub mod gizmos;
|
||||
pub mod graph_modification_utils;
|
||||
pub mod layer_origin_cross;
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::application::generate_uuid;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayProvider;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
use crate::messages::tool::transform_layer::transform_layer_message_handler::TransformLayerMessageContext;
|
||||
use crate::messages::tool::utility_types::{HintData, ToolType};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
@@ -30,11 +31,12 @@ pub struct ToolMessageHandler {
|
||||
pub transform_layer_handler: TransformLayerMessageHandler,
|
||||
pub shape_editor: ShapeState,
|
||||
pub tool_is_active: bool,
|
||||
/// What the active tool would edit in the selected layers, as last shown in the Layers panel.
|
||||
pub edit_target: EditTarget,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: ToolMessageContext) {
|
||||
impl ToolMessageHandler {
|
||||
fn handle_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: ToolMessageContext) {
|
||||
let ToolMessageContext {
|
||||
document_id,
|
||||
document,
|
||||
@@ -348,6 +350,30 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the node the Layers panel outlines as edited by the active tool, which changes with the tool and its state.
|
||||
fn refresh_edit_target(&mut self, responses: &mut VecDeque<Message>) {
|
||||
// Tools are deactivated while the graph is open, so they edit nothing then
|
||||
let edit_target = if self.tool_is_active {
|
||||
self.tool_state.tool_data.active_tool().edit_target()
|
||||
} else {
|
||||
EditTarget::Nothing
|
||||
};
|
||||
|
||||
if edit_target != self.edit_target {
|
||||
self.edit_target = edit_target;
|
||||
responses.add(NodeGraphMessage::UpdateLayerPanel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: ToolMessageContext) {
|
||||
// Any message may switch the tool or change its state, so the refresh follows every one, even those handled with an early return
|
||||
self.handle_message(message, responses, context);
|
||||
self.refresh_edit_target(responses);
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
let mut list = actions!(ToolMessageDiscriminant;
|
||||
ActivateToolSelect,
|
||||
|
||||
@@ -49,6 +49,13 @@ impl ToolMetadata for ArtboardTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for ArtboardTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
// An artboard layer is itself the Artboard node, which the chain lookup starts from
|
||||
EditTarget::network_node("Artboard", Insertion::Never)
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for ArtboardTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
|
||||
@@ -105,6 +105,13 @@ impl ToolMetadata for BrushTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for BrushTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
// The outlined node is extended only when its stroke style matches, and otherwise the tool starts a new group
|
||||
EditTarget::proto_node(brush_strokes::IDENTIFIER, Insertion::Never)
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for BrushTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let widgets = vec![
|
||||
|
||||
@@ -39,6 +39,12 @@ impl ToolMetadata for EyedropperTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for EyedropperTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
EditTarget::Nothing
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for EyedropperTool {
|
||||
fn layout(&self) -> Layout {
|
||||
Layout::default()
|
||||
|
||||
@@ -45,6 +45,13 @@ impl ToolMetadata for FillTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for FillTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
// Exact for a selected layer painted whole, which a click reaches through the selection, while geometry is filled on whichever layer is clicked
|
||||
EditTarget::FirstApplicable(vec![EditTarget::proto_node(graphene_std::math_nodes::color_value::IDENTIFIER, Insertion::Never), EditTarget::fill()])
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for FillTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let widgets = vec![
|
||||
|
||||
@@ -86,6 +86,12 @@ impl ToolMetadata for FreehandTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for FreehandTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
EditTarget::path()
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for FreehandTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = self.options.drawing.fill.create_widgets(
|
||||
|
||||
@@ -78,6 +78,12 @@ impl ToolMetadata for GradientTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for GradientTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
EditTarget::FirstApplicable(vec![EditTarget::proto_node(graphene_std::math_nodes::gradient_value::IDENTIFIER, Insertion::Never), EditTarget::fill()])
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for GradientTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
|
||||
@@ -17,7 +17,8 @@ pub mod tool_prelude {
|
||||
pub use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||
pub use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
pub use crate::messages::prelude::*;
|
||||
pub use crate::messages::tool::utility_types::{EventToMessageMap, Fsm, ToolActionMessageContext, ToolMetadata, ToolTransition, ToolType};
|
||||
pub use crate::messages::tool::common_functionality::edit_target::{EditTarget, Insertion};
|
||||
pub use crate::messages::tool::utility_types::{EventToMessageMap, Fsm, ToolActionMessageContext, ToolEditTarget, ToolMetadata, ToolTransition, ToolType};
|
||||
pub use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||
pub use glam::{DAffine2, DVec2};
|
||||
}
|
||||
@@ -33,6 +33,12 @@ impl ToolMetadata for NavigateTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for NavigateTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
EditTarget::Nothing
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for NavigateTool {
|
||||
fn layout(&self) -> Layout {
|
||||
Layout::default()
|
||||
@@ -118,7 +124,7 @@ impl Fsm for NavigateToolFsmState {
|
||||
}
|
||||
NavigateToolMessage::PointerMove { snap } => {
|
||||
if self == NavigateToolFsmState::ZoomOrClickZooming {
|
||||
responses.add_front(NavigationMessage::BeginCanvasZoom);
|
||||
responses.add_front(NavigationMessage::BeginCanvasZoom { artwork_behind_graph: false });
|
||||
NavigateToolFsmState::Zooming
|
||||
} else {
|
||||
responses.add_front(NavigationMessage::PointerMove { snap });
|
||||
|
||||
@@ -199,6 +199,12 @@ impl ToolMetadata for PathTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for PathTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
EditTarget::path()
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for PathTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let coordinates = self.tool_data.selection_status.as_one().as_ref().map(|point| point.coordinates);
|
||||
@@ -325,7 +331,7 @@ impl LayoutHolder for PathTool {
|
||||
|
||||
// Works only if a single layer is selected and its type is Vector
|
||||
let path_node_button = TextButton::new("Make Path Editable")
|
||||
.icon("NodeShape")
|
||||
.icon("Path")
|
||||
.tooltip_label("Make Path Editable")
|
||||
.tooltip_description(
|
||||
"Enables the Pen and Path tools to directly edit layer geometry resulting from nondestructive operations. This inserts a 'Path' node as the last operation of the selected layer.",
|
||||
|
||||
@@ -148,6 +148,12 @@ impl ToolMetadata for PenTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for PenTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
EditTarget::path()
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for PenTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = self.options.drawing.fill.create_widgets(
|
||||
|
||||
@@ -159,6 +159,12 @@ impl ToolMetadata for SelectTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for SelectTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
EditTarget::transform()
|
||||
}
|
||||
}
|
||||
|
||||
impl SelectTool {
|
||||
fn deep_selection_widget(&self) -> WidgetInstance {
|
||||
let layer_selection_behavior_entries = [NestedSelectionBehavior::Shallowest, NestedSelectionBehavior::Deepest]
|
||||
@@ -703,7 +709,7 @@ impl SelectToolData {
|
||||
|
||||
/// Draws the hover/selection outline for a layer. When a Path node is upstream, mirrors the Path tool's view
|
||||
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer); otherwise uses the layer's recorded outlines.
|
||||
fn draw_layer_outline(overlay_context: &mut OverlayContext, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, color: Option<&str>) {
|
||||
pub fn draw_layer_outline(overlay_context: &mut OverlayContext, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, color: Option<&str>) {
|
||||
if let Some(targets) = document.network_interface.path_aware_outline_targets(layer) {
|
||||
let layer_to_viewport = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
|
||||
overlay_context.outline(targets.iter(), layer_to_viewport, color);
|
||||
|
||||
@@ -703,6 +703,31 @@ impl ToolMetadata for ShapeTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for ShapeTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
let gizmo_shapes = || {
|
||||
[
|
||||
graphene_std::vector_nodes::star::IDENTIFIER,
|
||||
graphene_std::vector_nodes::regular_polygon::IDENTIFIER,
|
||||
graphene_std::vector_nodes::arc::IDENTIFIER,
|
||||
graphene_std::vector_nodes::circle::IDENTIFIER,
|
||||
graphene_std::vector::generator_nodes::grid::IDENTIFIER,
|
||||
graphene_std::vector_nodes::spiral::IDENTIFIER,
|
||||
]
|
||||
.map(|identifier| EditTarget::proto_node(identifier, Insertion::Never))
|
||||
};
|
||||
let endpoint_shapes = || [graphene_std::vector_nodes::line::IDENTIFIER, graphene_std::vector_nodes::arrow::IDENTIFIER].map(|identifier| EditTarget::proto_node(identifier, Insertion::Never));
|
||||
|
||||
match self.fsm_state {
|
||||
ShapeToolFsmState::ModifyingGizmo => EditTarget::FirstApplicable(gizmo_shapes().into()),
|
||||
ShapeToolFsmState::DraggingLineEndpoints => EditTarget::FirstApplicable(endpoint_shapes().into()),
|
||||
ShapeToolFsmState::ResizingBounds | ShapeToolFsmState::RotatingBounds | ShapeToolFsmState::SkewingBounds { .. } => EditTarget::transform(),
|
||||
// A shape node with a gizmo or endpoints takes the shape-specific edits, while any other layer only has its transform cage
|
||||
ShapeToolFsmState::Ready(_) | ShapeToolFsmState::Drawing(_) => EditTarget::FirstApplicable(gizmo_shapes().into_iter().chain(endpoint_shapes()).chain([EditTarget::transform()]).collect()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolTransition for ShapeTool {
|
||||
fn event_to_message_map(&self) -> EventToMessageMap {
|
||||
EventToMessageMap {
|
||||
|
||||
@@ -93,6 +93,12 @@ impl ToolMetadata for SplineTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for SplineTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
EditTarget::path()
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for SplineTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = self.options.drawing.fill.create_widgets(
|
||||
|
||||
@@ -104,6 +104,17 @@ impl ToolMetadata for TextTool {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolEditTarget for TextTool {
|
||||
fn edit_target(&self) -> EditTarget {
|
||||
match self.fsm_state {
|
||||
TextToolFsmState::Ready | TextToolFsmState::Editing | TextToolFsmState::Placing | TextToolFsmState::ResizingBounds => {
|
||||
EditTarget::proto_node(graphene_std::text::text::IDENTIFIER, Insertion::Never)
|
||||
}
|
||||
TextToolFsmState::Dragging => EditTarget::transform(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &DocumentMessageHandler) -> Vec<WidgetInstance> {
|
||||
let text_node_id = can_edit_selected(document).and_then(|layer| graph_modification_utils::get_text_id(layer, &document.network_interface));
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayProvider;
|
||||
use crate::messages::preferences::PreferencesMessageHandler;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::ShapeType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -31,8 +32,8 @@ pub struct ToolActionMessageContext<'a> {
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
pub trait ToolCommon: for<'a, 'b> MessageHandler<ToolMessage, &'b mut ToolActionMessageContext<'a>> + ToolRefreshOptions + ToolTransition + ToolMetadata {}
|
||||
impl<T> ToolCommon for T where T: for<'a, 'b> MessageHandler<ToolMessage, &'b mut ToolActionMessageContext<'a>> + ToolRefreshOptions + ToolTransition + ToolMetadata {}
|
||||
pub trait ToolCommon: for<'a, 'b> MessageHandler<ToolMessage, &'b mut ToolActionMessageContext<'a>> + ToolRefreshOptions + ToolTransition + ToolMetadata + ToolEditTarget {}
|
||||
impl<T> ToolCommon for T where T: for<'a, 'b> MessageHandler<ToolMessage, &'b mut ToolActionMessageContext<'a>> + ToolRefreshOptions + ToolTransition + ToolMetadata + ToolEditTarget {}
|
||||
|
||||
type Tool = dyn ToolCommon + Send + Sync;
|
||||
|
||||
@@ -220,6 +221,12 @@ pub trait ToolMetadata {
|
||||
fn tool_type(&self) -> ToolType;
|
||||
}
|
||||
|
||||
/// Required of every tool, so the Layers panel can outline the node the tool edits in each selected layer.
|
||||
pub trait ToolEditTarget {
|
||||
/// What the tool edits in its current state, which may change between its modes and interactions.
|
||||
fn edit_target(&self) -> EditTarget;
|
||||
}
|
||||
|
||||
pub struct ToolData {
|
||||
pub active_tool_type: ToolType,
|
||||
pub active_shape_type: Option<ToolType>,
|
||||
|
||||
@@ -41,8 +41,6 @@
|
||||
export let virtualScrolling = false;
|
||||
// Whether the highlight moves to each new active entry given while the menu is open
|
||||
export let highlightFollowsActiveEntry = false;
|
||||
// Use `Popover` to draw a tail pointing at the spawner. Defaults to `Dropdown` (no tail), which the menu bar uses. Recursive submenus always use `Dropdown`.
|
||||
export let type: "Dropdown" | "Popover" = "Dropdown";
|
||||
|
||||
// Keep the child references outside of the entries array so as to avoid infinite recursion.
|
||||
let childReferences: MenuList[][] = [];
|
||||
@@ -483,7 +481,7 @@
|
||||
{open}
|
||||
on:open={({ detail }) => (open = detail)}
|
||||
on:naturalWidth
|
||||
{type}
|
||||
type="Dropdown"
|
||||
windowEdgeMargin={0}
|
||||
escapeCloses={false}
|
||||
{direction}
|
||||
|
||||
@@ -649,8 +649,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
&.top.start-aligned > .floating-menu-container,
|
||||
&.bottom.start-aligned > .floating-menu-container {
|
||||
&.top.start-aligned .floating-menu-container,
|
||||
&.bottom.start-aligned .floating-menu-container {
|
||||
justify-content: left;
|
||||
}
|
||||
|
||||
@@ -747,22 +747,22 @@
|
||||
}
|
||||
}
|
||||
|
||||
&.top > .floating-menu-container {
|
||||
&.top .floating-menu-container {
|
||||
justify-content: center;
|
||||
margin-bottom: var(--floating-menu-content-offset);
|
||||
}
|
||||
|
||||
&.bottom > .floating-menu-container {
|
||||
&.bottom .floating-menu-container {
|
||||
justify-content: center;
|
||||
margin-top: var(--floating-menu-content-offset);
|
||||
}
|
||||
|
||||
&.left > .floating-menu-container {
|
||||
&.left .floating-menu-container {
|
||||
align-items: center;
|
||||
margin-right: var(--floating-menu-content-offset);
|
||||
}
|
||||
|
||||
&.right > .floating-menu-container {
|
||||
&.right .floating-menu-container {
|
||||
align-items: center;
|
||||
margin-left: var(--floating-menu-content-offset);
|
||||
}
|
||||
|
||||
@@ -4,16 +4,15 @@
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import Separator from "/src/components/widgets/labels/Separator.svelte";
|
||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
|
||||
import type { NodeGraphStore } from "/src/stores/node-graph";
|
||||
import { layersPanelControlBarLeftLayout, layersPanelControlBarRightLayout, layersPanelBottomBarLayout } from "/src/stores/portfolio";
|
||||
import { layersPanelControlBarLeftLayout, layersPanelBottomBarLeftLayout, layersPanelBottomBarRightLayout } from "/src/stores/portfolio";
|
||||
import type { PortfolioStore } from "/src/stores/portfolio";
|
||||
import type { TooltipStore } from "/src/stores/tooltip";
|
||||
import { pasteFile } from "/src/utility-functions/files";
|
||||
import { operatingSystem } from "/src/utility-functions/platform";
|
||||
import type { EditorWrapper, LayerPanelEntry, LayerStructureEntry } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { EditorWrapper, LayerPanelChainNode, LayerPanelEntry, LayerStructureEntry } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
type LayerListingInfo = {
|
||||
folderIndex: number;
|
||||
@@ -48,6 +47,15 @@
|
||||
startY: number;
|
||||
};
|
||||
|
||||
type ChainDragState = {
|
||||
active: boolean;
|
||||
// The layer whose chain the nodes are being dragged from
|
||||
layerId: bigint;
|
||||
nodeIds: bigint[];
|
||||
startX: number;
|
||||
startY: number;
|
||||
};
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
const nodeGraph = getContext<NodeGraphStore>("nodeGraph");
|
||||
const tooltip = getContext<TooltipStore>("tooltip");
|
||||
@@ -66,6 +74,19 @@
|
||||
let dragInPanel = false;
|
||||
let dragDropTarget: HTMLElement | undefined = undefined;
|
||||
|
||||
// Interactive dragging of chain nodes within a layer's chain or into another layer's
|
||||
let chainDragState: ChainDragState | undefined = undefined;
|
||||
let chainDragActive = false;
|
||||
// The layer row (by its index in the list) under the cursor, the gap among its reorderable chain nodes counted from the left, and where its marker sits within the row
|
||||
let chainDropRowIndex: number | undefined = undefined;
|
||||
let chainInsertIndex: number | undefined = undefined;
|
||||
let chainInsertMarkerLeft: number | undefined = undefined;
|
||||
let chainDragDropTarget: HTMLElement | undefined = undefined;
|
||||
|
||||
// Viewport hover outline, tracked by row index since rows get reused when the layers change beneath a still pointer
|
||||
let hoveredRowIndex: number | undefined = undefined;
|
||||
let hoveredLayerSent: bigint | undefined = undefined;
|
||||
|
||||
// Interactive clipping
|
||||
let layerToClipUponClick: LayerListingInfo | undefined = undefined;
|
||||
let layerToClipAltKeyPressed = false;
|
||||
@@ -74,6 +95,7 @@
|
||||
let activeDragToggleGroup: string | undefined = undefined;
|
||||
|
||||
$: rebuildLayerHierarchy($portfolio.layerStructure, $portfolio.layerCache);
|
||||
$: sendHoveredLayer(layers, hoveredRowIndex);
|
||||
|
||||
onMount(() => {
|
||||
createDragToggleManager(dragToggleListener);
|
||||
@@ -101,8 +123,19 @@
|
||||
removeEventListener("pointermove", clippingHover);
|
||||
removeEventListener("keydown", clippingKeyPress);
|
||||
removeEventListener("keyup", clippingKeyPress);
|
||||
|
||||
// Closing the panel removes the hovered row without a `pointerleave`
|
||||
if (hoveredLayerSent !== undefined) editor.setLayersPanelHoveredLayer(undefined);
|
||||
});
|
||||
|
||||
function sendHoveredLayer(listings: LayerListingInfo[], rowIndex: number | undefined) {
|
||||
const id = rowIndex === undefined ? undefined : listings.at(rowIndex)?.entry.id;
|
||||
if (id === hoveredLayerSent) return;
|
||||
|
||||
hoveredLayerSent = id;
|
||||
editor.setLayersPanelHoveredLayer(id);
|
||||
}
|
||||
|
||||
function dragToggleListener(group: string | undefined) {
|
||||
activeDragToggleGroup = group;
|
||||
}
|
||||
@@ -233,6 +266,29 @@
|
||||
editor.selectLayer(listing.entry.id, accel, shift);
|
||||
}
|
||||
|
||||
function chainNodeClick(e: MouseEvent | undefined, listing: LayerListingInfo, nodeId: bigint) {
|
||||
e?.stopPropagation();
|
||||
|
||||
// The click that follows releasing a drag shouldn't select anything
|
||||
if (justFinishedDrag) return;
|
||||
|
||||
// Same modifier key handling as selecting layers
|
||||
const [accel, oppositeAccel] = operatingSystem() === "Mac" ? [e?.metaKey, e?.ctrlKey] : [e?.ctrlKey, e?.metaKey];
|
||||
if (oppositeAccel || e?.altKey) return;
|
||||
|
||||
editor.selectChainNode(listing.entry.id, nodeId, Boolean(accel), Boolean(e?.shiftKey));
|
||||
}
|
||||
|
||||
// Double-clicking a chain node's icon, or the layer's own icon at the row's end, opens the graph centered on that node
|
||||
function chainIconsDoubleClick(e: MouseEvent, listing: LayerListingInfo) {
|
||||
const target = e.target instanceof Element ? e.target : undefined;
|
||||
const chainNodeButton = target?.closest("[data-chain-node]");
|
||||
const chainNode = chainNodeButton ? listing.entry.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
|
||||
|
||||
if (chainNode) editor.showNodeInGraph(chainNode.id);
|
||||
else if (target?.closest("[data-layer-icon]")) editor.showNodeInGraph(listing.entry.id);
|
||||
}
|
||||
|
||||
async function deselectAllLayers() {
|
||||
if (justFinishedDrag) {
|
||||
justFinishedDrag = false;
|
||||
@@ -329,6 +385,14 @@
|
||||
// Only left click drags
|
||||
if (e.button !== 0 || !draggable) return;
|
||||
|
||||
// Pressing one of the chain's node buttons drags that node within the chain, rather than dragging the whole layer
|
||||
const chainNodeButton = (e.target instanceof Element && e.target.closest("[data-chain-node]")) || undefined;
|
||||
if (chainNodeButton) {
|
||||
const chainNode = listing.entry.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))];
|
||||
if (chainNode) chainNodePointerDown(e, listing, chainNode);
|
||||
return;
|
||||
}
|
||||
|
||||
internalDragState = {
|
||||
active: false,
|
||||
layerId: listing.entry.id,
|
||||
@@ -338,7 +402,130 @@
|
||||
};
|
||||
}
|
||||
|
||||
function chainNodePointerDown(e: PointerEvent, listing: LayerListingInfo, chainNode: LayerPanelChainNode) {
|
||||
// A source node stays fixed at the chain's upstream end
|
||||
if (!chainNode.reorderable) return;
|
||||
|
||||
// Dragging a selected node brings along the chain's other selected nodes, which all end up together at the drop
|
||||
const nodeIds = chainNode.selected ? listing.entry.chainNodes.filter((node) => node.reorderable && node.selected).map((node) => node.id) : [chainNode.id];
|
||||
|
||||
chainDragState = { active: false, layerId: listing.entry.id, nodeIds, startX: e.clientX, startY: e.clientY };
|
||||
}
|
||||
|
||||
function chainDraggingPointerMove(e: PointerEvent) {
|
||||
if (!chainDragState) return;
|
||||
|
||||
if (!chainDragState.active) {
|
||||
const distance = Math.hypot(e.clientX - chainDragState.startX, e.clientY - chainDragState.startY);
|
||||
const DRAG_THRESHOLD = 5;
|
||||
if (distance <= DRAG_THRESHOLD) return;
|
||||
|
||||
chainDragState.active = true;
|
||||
chainDragActive = true;
|
||||
dragInPanel = true;
|
||||
layerToClipUponClick = undefined;
|
||||
}
|
||||
|
||||
chainDropRowIndex = undefined;
|
||||
chainInsertIndex = undefined;
|
||||
chainInsertMarkerLeft = undefined;
|
||||
|
||||
// Over a bottom bar button accepting chain nodes, the drop goes to it instead, and elsewhere in the bottom bar it goes nowhere
|
||||
const target = e.target instanceof Element ? e.target : undefined;
|
||||
const droppable = target?.closest("[data-drag-droppable~=chain-nodes]");
|
||||
chainDragDropTarget = droppable instanceof HTMLElement ? droppable : undefined;
|
||||
if (chainDragDropTarget || target?.closest("[data-layer-bottom-bar]")) return;
|
||||
|
||||
// Otherwise the nodes drop into the chain of whichever layer is under the cursor
|
||||
const row = target?.closest("[data-layer]");
|
||||
if (row) calculateChainInsertIndex(row, e.clientX);
|
||||
}
|
||||
|
||||
// The row's reorderable chain node buttons, in their left-to-right order
|
||||
function reorderableChainNodeButtons(row: Element): Element[] {
|
||||
return Array.from(row.querySelectorAll("[data-chain-node-reorderable]"));
|
||||
}
|
||||
|
||||
function calculateChainInsertIndex(row: Element, clientX: number) {
|
||||
const rects = reorderableChainNodeButtons(row).map((button) => button.getBoundingClientRect());
|
||||
|
||||
// The insertion index is the number of reorderable nodes whose horizontal midpoint sits left of the cursor
|
||||
const firstRightOfCursor = rects.findIndex((rect) => clientX < (rect.left + rect.right) / 2);
|
||||
const index = firstRightOfCursor === -1 ? rects.length : firstRightOfCursor;
|
||||
|
||||
// The marker sits on the boundary between the neighboring nodes, or at the outer edge of the node at either end.
|
||||
// With nothing reorderable, the only gap is beside the layer, after a fixed source node or else just before the layer's icon.
|
||||
let markerX: number | undefined;
|
||||
if (rects.length === 0) {
|
||||
const chainNodeButtons = row.querySelectorAll("[data-chain-node]");
|
||||
const fixedSource = chainNodeButtons[chainNodeButtons.length - 1];
|
||||
markerX = fixedSource ? fixedSource.getBoundingClientRect().right : row.querySelector("[data-layer-chain]")?.getBoundingClientRect().left;
|
||||
} else if (index === 0) {
|
||||
markerX = rects[0].left;
|
||||
} else if (index === rects.length) {
|
||||
markerX = rects[rects.length - 1].right;
|
||||
} else {
|
||||
markerX = (rects[index - 1].right + rects[index].left) / 2;
|
||||
}
|
||||
if (markerX === undefined) return;
|
||||
|
||||
chainDropRowIndex = Number(row.getAttribute("data-index"));
|
||||
chainInsertIndex = index;
|
||||
chainInsertMarkerLeft = markerX - row.getBoundingClientRect().left;
|
||||
}
|
||||
|
||||
// Swallow the click fired by releasing a drag, without leaving the flag set to block a later click if none comes
|
||||
function swallowReleaseClick() {
|
||||
justFinishedDrag = true;
|
||||
setTimeout(() => (justFinishedDrag = false), 0);
|
||||
}
|
||||
|
||||
function chainDraggingPointerUp(e: PointerEvent) {
|
||||
if (chainDragState?.active) swallowReleaseClick();
|
||||
|
||||
const row = chainDropRowIndex !== undefined ? list?.div()?.querySelector(`[data-layer][data-index="${chainDropRowIndex}"]`) : undefined;
|
||||
const targetLayerId = chainDropRowIndex !== undefined ? layers[chainDropRowIndex]?.entry.id : undefined;
|
||||
if (chainDragState?.active && chainDragDropTarget) {
|
||||
// The button's action applies to the selection, so it becomes exactly the dragged nodes
|
||||
editor.selectNodes(BigUint64Array.from(chainDragState.nodeIds));
|
||||
chainDragDropTarget.dispatchEvent(new CustomEvent("dragdrop"));
|
||||
} else if (chainDragState?.active && row && targetLayerId !== undefined && chainInsertIndex !== undefined) {
|
||||
const reorderableIds = reorderableChainNodeButtons(row).map((button) => button.getAttribute("data-chain-node-reorderable"));
|
||||
|
||||
// Within the same layer, nodes already together beside the gap would stay put
|
||||
const positions = chainDragState.nodeIds.map((id) => reorderableIds.indexOf(String(id))).sort((a, b) => a - b);
|
||||
const [first, last] = [positions[0], positions[positions.length - 1]];
|
||||
const sameLayer = targetLayerId === chainDragState.layerId;
|
||||
const alreadyInPlace = sameLayer && first !== -1 && last - first + 1 === positions.length && chainInsertIndex >= first && chainInsertIndex <= last + 1;
|
||||
|
||||
// The backend counts gaps outward from the layer, the reverse of the left-to-right order shown here
|
||||
const nodeIds = BigUint64Array.from(chainDragState.nodeIds);
|
||||
const insertIndex = reorderableIds.length - chainInsertIndex;
|
||||
|
||||
// Holding Alt drops copies at the gap instead of moving the originals
|
||||
if (e.altKey) editor.duplicateChainNodes(nodeIds, targetLayerId, insertIndex);
|
||||
else if (!alreadyInPlace) editor.moveChainNodes(nodeIds, targetLayerId, insertIndex);
|
||||
}
|
||||
|
||||
abortChainDrag();
|
||||
}
|
||||
|
||||
function abortChainDrag() {
|
||||
chainDragState = undefined;
|
||||
chainDragActive = false;
|
||||
chainDropRowIndex = undefined;
|
||||
chainInsertIndex = undefined;
|
||||
chainInsertMarkerLeft = undefined;
|
||||
chainDragDropTarget = undefined;
|
||||
dragInPanel = false;
|
||||
}
|
||||
|
||||
function draggingPointerMove(e: PointerEvent) {
|
||||
if (chainDragState) {
|
||||
chainDraggingPointerMove(e);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!internalDragState || !list) return;
|
||||
|
||||
// Calculate distance moved
|
||||
@@ -362,7 +549,7 @@
|
||||
if (internalDragState.active) {
|
||||
// Check if the cursor is over any element flagged as a drag drop target
|
||||
// (e.g. a bottom-bar action button whose backend widget has an `on_drag_drop` callback set)
|
||||
const droppable = (e.target instanceof Element && e.target.closest("[data-drag-droppable]")) || undefined;
|
||||
const droppable = (e.target instanceof Element && e.target.closest("[data-drag-droppable~=layers]")) || undefined;
|
||||
dragDropTarget = droppable instanceof HTMLElement ? droppable : undefined;
|
||||
|
||||
// Hide the move-in-tree insert indicator whenever the cursor enters the bottom bar
|
||||
@@ -383,6 +570,11 @@
|
||||
}
|
||||
|
||||
function draggingPointerUp(e: PointerEvent) {
|
||||
if (chainDragState) {
|
||||
chainDraggingPointerUp(e);
|
||||
return;
|
||||
}
|
||||
|
||||
if (internalDragState?.active && dragDropTarget) {
|
||||
// Ensure the dragged layer is part of the selection, matching the move-in-tree behavior
|
||||
if (!$nodeGraph.selected.includes(internalDragState.layerId)) selectLayer(internalDragState.listing, false, false);
|
||||
@@ -390,7 +582,7 @@
|
||||
// Hand off to the button's backend `on_drag_drop` callback via the custom event
|
||||
dragDropTarget.dispatchEvent(new CustomEvent("dragdrop"));
|
||||
|
||||
justFinishedDrag = true;
|
||||
swallowReleaseClick();
|
||||
} else if (internalDragState?.active && draggingData) {
|
||||
const { select, insertParentId, insertIndex } = draggingData;
|
||||
|
||||
@@ -428,6 +620,10 @@
|
||||
justFinishedDrag = true;
|
||||
abortDrag();
|
||||
}
|
||||
if (e.button === 2 && chainDragState?.active) {
|
||||
justFinishedDrag = true;
|
||||
abortChainDrag();
|
||||
}
|
||||
}
|
||||
|
||||
function draggingKeyDown(e: KeyboardEvent) {
|
||||
@@ -435,6 +631,10 @@
|
||||
justFinishedDrag = true;
|
||||
abortDrag();
|
||||
}
|
||||
if (e.key === "Escape" && chainDragState?.active) {
|
||||
justFinishedDrag = true;
|
||||
abortChainDrag();
|
||||
}
|
||||
}
|
||||
|
||||
function handleLayerPanelKeyDown(e: KeyboardEvent) {
|
||||
@@ -549,10 +749,6 @@
|
||||
<LayoutCol class="layers" on:dragleave={() => (dragInPanel = false)}>
|
||||
<LayoutRow class="control-bar" scrollableX={true}>
|
||||
<WidgetLayout layout={$layersPanelControlBarLeftLayout} layoutTarget="LayersPanelControlLeftBar" />
|
||||
{#if $layersPanelControlBarLeftLayout?.length > 0 && $layersPanelControlBarRightLayout?.length > 0}
|
||||
<Separator />
|
||||
{/if}
|
||||
<WidgetLayout layout={$layersPanelControlBarRightLayout} layoutTarget="LayersPanelControlRightBar" />
|
||||
</LayoutRow>
|
||||
<LayoutRow class="list-area" classes={{ "drag-ongoing": Boolean(internalDragState?.active && draggingData) }} scrollableY={true}>
|
||||
<LayoutCol
|
||||
@@ -580,7 +776,21 @@
|
||||
data-index={index}
|
||||
on:pointerdown={(e) => layerPointerDown(e, listing)}
|
||||
on:click={(e) => selectLayerWithModifiers(e, listing)}
|
||||
on:pointerenter={() => (hoveredRowIndex = index)}
|
||||
on:pointerleave={() => (hoveredRowIndex = undefined)}
|
||||
>
|
||||
<IconButton
|
||||
class="status-toggle"
|
||||
classes={{ inherited: !listing.parentsVisible }}
|
||||
action={(e) => (toggleNodeVisibilityLayerPanel(listing.entry.id), e?.stopPropagation())}
|
||||
size={24}
|
||||
icon={listing.entry.visible ? "EyeVisible" : "EyeHidden"}
|
||||
hoverIcon={listing.entry.visible ? "EyeHide" : "EyeShow"}
|
||||
tooltipLabel={listing.entry.visible ? "Hide" : "Show"}
|
||||
tooltipDescription={!listing.parentsVisible ? "A parent of this layer is hidden and that status is being inherited." : ""}
|
||||
data-drag-toggle-group="layer-visibility"
|
||||
data-drag-toggle-state={listing.entry.visible ? "visible" : "hidden"}
|
||||
/>
|
||||
{#if listing.entry.childrenAllowed || listing.childrenPresent}
|
||||
<button
|
||||
class="expand-arrow"
|
||||
@@ -612,10 +822,7 @@
|
||||
{@html $nodeGraph.thumbnails.get(listing.entry.id)}
|
||||
{/if}
|
||||
</div>
|
||||
{#if listing.entry.iconName}
|
||||
<IconLabel icon={listing.entry.iconName} class="layer-type-icon" tooltipLabel="Artboard" />
|
||||
{/if}
|
||||
<LayoutRow class="layer-name" on:dblclick={() => onEditLayerName(listing)}>
|
||||
<LayoutRow class="layer-name" classes={{ editing: listing.editingName }} on:dblclick={() => onEditLayerName(listing)}>
|
||||
<input
|
||||
data-layer-name-input
|
||||
type="text"
|
||||
@@ -665,27 +872,60 @@
|
||||
data-drag-toggle-state="unlocked"
|
||||
/>
|
||||
{/if}
|
||||
<IconButton
|
||||
class="status-toggle"
|
||||
classes={{ inherited: !listing.parentsVisible }}
|
||||
action={(e) => (toggleNodeVisibilityLayerPanel(listing.entry.id), e?.stopPropagation())}
|
||||
size={24}
|
||||
icon={listing.entry.visible ? "EyeVisible" : "EyeHidden"}
|
||||
hoverIcon={listing.entry.visible ? "EyeHide" : "EyeShow"}
|
||||
tooltipLabel={listing.entry.visible ? "Hide" : "Show"}
|
||||
tooltipDescription={!listing.parentsVisible ? "A parent of this layer is hidden and that status is being inherited." : ""}
|
||||
data-drag-toggle-group="layer-visibility"
|
||||
data-drag-toggle-state={listing.entry.visible ? "visible" : "hidden"}
|
||||
/>
|
||||
<LayoutRow class="layer-name-spacer" on:dblclick={() => onEditLayerName(listing)} />
|
||||
<LayoutRow class="layer-chain-icons" on:dblclick={(e) => chainIconsDoubleClick(e, listing)} data-layer-chain>
|
||||
{#each listing.entry.chainNodes as chainNode, chainNodeIndex}
|
||||
{#if listing.entry.toolTargetInsertion?.index === chainNodeIndex}
|
||||
{@const insertion = listing.entry.toolTargetInsertion}
|
||||
<IconLabel icon={insertion.icon} class="tool-target-insertion" tooltipLabel={insertion.name} tooltipDescription={insertion.description} />
|
||||
{/if}
|
||||
<IconButton
|
||||
icon={chainNode.icon}
|
||||
size={24}
|
||||
classes={{
|
||||
selected: chainNode.selected,
|
||||
hidden: !chainNode.visible,
|
||||
"tool-target": Boolean(chainNode.toolTargetDescription),
|
||||
"edit-in-progress": chainNode.editInProgress,
|
||||
}}
|
||||
action={(e) => chainNodeClick(e, listing, chainNode.id)}
|
||||
tooltipLabel={chainNode.name}
|
||||
tooltipDescription={chainNode.toolTargetDescription}
|
||||
data-chain-node={chainNodeIndex}
|
||||
data-chain-node-reorderable={chainNode.reorderable ? String(chainNode.id) : undefined}
|
||||
/>
|
||||
{/each}
|
||||
{#if listing.entry.toolTargetInsertion?.index === listing.entry.chainNodes.length}
|
||||
{@const insertion = listing.entry.toolTargetInsertion}
|
||||
<IconLabel icon={insertion.icon} class="tool-target-insertion" tooltipLabel={insertion.name} tooltipDescription={insertion.description} />
|
||||
{/if}
|
||||
{#if listing.entry.chainNodes.length > 0 || listing.entry.toolTargetInsertion}
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" class="chain-connector" style:fill={`var(--color-data-${listing.entry.chainDataType.toLowerCase()})`}>
|
||||
<path d="M0,6.306L0,1.694C0,0.228 1.06,-0.41 2.356,0.276L7.028,2.752C8.324,3.438 8.324,4.562 7.028,5.248L2.356,7.723C1.06,8.41 0,7.771 0,6.306z" />
|
||||
</svg>
|
||||
{/if}
|
||||
<IconLabel
|
||||
icon={listing.entry.iconName}
|
||||
class="layer-type-icon"
|
||||
classes={{ hidden: !listing.entry.visible, "tool-target": Boolean(listing.entry.toolTargetDescription), "edit-in-progress": listing.entry.editInProgress }}
|
||||
tooltipLabel={listing.entry.implementationName}
|
||||
tooltipDescription={listing.entry.toolTargetDescription}
|
||||
data-layer-icon
|
||||
/>
|
||||
</LayoutRow>
|
||||
{#if chainDropRowIndex === index && chainInsertMarkerLeft !== undefined}
|
||||
<div class="chain-insert-mark" style:left={`${chainInsertMarkerLeft}px`}></div>
|
||||
{/if}
|
||||
</LayoutRow>
|
||||
{/each}
|
||||
</LayoutCol>
|
||||
{#if draggingData && !draggingData.highlightFolder && dragInPanel}
|
||||
<div class="insert-mark" style:left={`${4 + draggingData.insertDepth * 16}px`} style:top={`${draggingData.markerHeight}px`}></div>
|
||||
<div class="insert-mark" style:left={`${4 + 24 + draggingData.insertDepth * 16}px`} style:top={`${draggingData.markerHeight}px`}></div>
|
||||
{/if}
|
||||
</LayoutRow>
|
||||
<LayoutRow class="bottom-bar" classes={{ "layer-drag-active": Boolean(internalDragState?.active) }} scrollableX={true} data-layer-bottom-bar>
|
||||
<WidgetLayout layout={$layersPanelBottomBarLayout} layoutTarget="LayersPanelBottomBar" />
|
||||
<LayoutRow class="bottom-bar" classes={{ "layer-drag-active": Boolean(internalDragState?.active), "chain-node-drag-active": chainDragActive }} scrollableX={true} data-layer-bottom-bar>
|
||||
<WidgetLayout layout={$layersPanelBottomBarLeftLayout} layoutTarget="LayersPanelBottomLeftBar" />
|
||||
<WidgetLayout layout={$layersPanelBottomBarRightLayout} layoutTarget="LayersPanelBottomRightBar" />
|
||||
</LayoutRow>
|
||||
</LayoutCol>
|
||||
|
||||
@@ -714,7 +954,7 @@
|
||||
padding-top: 4px;
|
||||
flex: 0 0 auto;
|
||||
margin: 0 4px;
|
||||
justify-content: flex-end;
|
||||
justify-content: space-between;
|
||||
border-top: 1px solid var(--color-2-mildblack);
|
||||
|
||||
.widget-span > * {
|
||||
@@ -725,17 +965,11 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
&.layer-drag-active .icon-button,
|
||||
&.layer-drag-active .popover-button {
|
||||
&.drag-droppable:hover {
|
||||
background: var(--color-e-nearwhite);
|
||||
|
||||
svg {
|
||||
fill: var(--color-2-mildblack);
|
||||
}
|
||||
}
|
||||
|
||||
&:not(.drag-droppable) {
|
||||
// While dragging, buttons are grayed out unless they accept the kind of item being dragged
|
||||
&.layer-drag-active,
|
||||
&.chain-node-drag-active {
|
||||
.icon-button,
|
||||
.popover-button {
|
||||
pointer-events: none;
|
||||
background: none;
|
||||
|
||||
@@ -744,6 +978,24 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dropped items become the selection before the button acts, so a button disabled for the current selection still accepts them
|
||||
&.layer-drag-active .icon-button[data-drag-droppable~="layers"],
|
||||
&.chain-node-drag-active .icon-button[data-drag-droppable~="chain-nodes"] {
|
||||
pointer-events: auto;
|
||||
|
||||
svg {
|
||||
fill: var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--color-e-nearwhite);
|
||||
|
||||
svg {
|
||||
fill: var(--color-2-mildblack);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Layer hierarchy
|
||||
@@ -765,7 +1017,6 @@
|
||||
border-radius: 2px;
|
||||
height: 32px;
|
||||
margin: 0 4px;
|
||||
padding-left: calc(var(--layer-indent-levels) * 16px);
|
||||
|
||||
// Dimming
|
||||
&.selected {
|
||||
@@ -838,6 +1089,12 @@
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
// Indents the rest of the row by the layer's depth in the tree, after the visibility column
|
||||
.expand-arrow,
|
||||
.expand-arrow-none {
|
||||
margin-left: calc(var(--layer-indent-levels) * 16px);
|
||||
}
|
||||
|
||||
.clipped-arrow {
|
||||
margin-left: 2px;
|
||||
margin-right: 2px;
|
||||
@@ -860,16 +1117,127 @@
|
||||
}
|
||||
}
|
||||
|
||||
.layer-type-icon {
|
||||
margin-left: 8px;
|
||||
margin-right: -4px;
|
||||
// Unrelated-width gap from the name (with its right margin), and the layer icon kept 4px from the row's end like the visibility icon at its start
|
||||
.layer-chain-icons {
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
margin-left: 4px;
|
||||
margin-right: 2px;
|
||||
|
||||
.icon-button {
|
||||
width: 20px;
|
||||
}
|
||||
|
||||
.icon-button.selected {
|
||||
background: var(--color-6-lowergray);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
// A hidden node's icon is faded and struck through by a slash across its 16px icon's diagonal
|
||||
.icon-button.hidden,
|
||||
.layer-type-icon.hidden {
|
||||
position: relative;
|
||||
|
||||
svg {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: calc(16px * sqrt(2) - 2px);
|
||||
height: 1px;
|
||||
background: var(--color-e-nearwhite);
|
||||
transform: translate(-50%, -50%) rotate(-45deg);
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
// Related-width gaps to the icons beside it
|
||||
.chain-connector {
|
||||
flex: 0 0 auto;
|
||||
align-self: center;
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
margin: 0 2px;
|
||||
}
|
||||
|
||||
// Takes the same 20px width as the chain buttons
|
||||
.layer-type-icon {
|
||||
margin: 0 2px;
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
// The node the active tool edits, or the ghost of one it would add, brightened while an edit in progress writes to it
|
||||
.tool-target,
|
||||
.tool-target-insertion,
|
||||
.edit-in-progress {
|
||||
outline: 1px solid var(--color-8-uppergray);
|
||||
outline-offset: -1px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.edit-in-progress {
|
||||
outline-color: var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
// Outside the bare 16px layer icon, rather than inside a 20px button
|
||||
.layer-type-icon.tool-target,
|
||||
.layer-type-icon.edit-in-progress {
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
// Pads the 16px icon to the 20px by 24px of the chain buttons
|
||||
.tool-target-insertion {
|
||||
padding: 4px 2px;
|
||||
|
||||
svg {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The vertical counterpart of the insertion marker between layers, centered on the gap between chain nodes
|
||||
.chain-insert-mark {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
bottom: 4px;
|
||||
width: 5px;
|
||||
transform: translateX(-50%);
|
||||
background: var(--color-e-nearwhite);
|
||||
// Above the selected chain node's raised highlight
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
// Pushes the chain icons to the row's end, and can also be double-clicked to rename the layer like the name itself
|
||||
.layer-name-spacer {
|
||||
flex: 1 1 0;
|
||||
align-self: stretch;
|
||||
}
|
||||
|
||||
// Only as wide as its text, so the lock icon follows right after it, but shrinks to an ellipsis when space runs out
|
||||
.layer-name {
|
||||
flex: 1 1 100%;
|
||||
flex: 0 1 auto;
|
||||
margin: 0 8px;
|
||||
|
||||
// While renaming, the input stretches to fill the row
|
||||
&.editing {
|
||||
flex-grow: 1;
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
& ~ .layer-name-spacer {
|
||||
flex-grow: 0;
|
||||
}
|
||||
}
|
||||
|
||||
input {
|
||||
field-sizing: content;
|
||||
color: inherit;
|
||||
background: none;
|
||||
border: none;
|
||||
@@ -881,7 +1249,6 @@
|
||||
overflow: hidden;
|
||||
border-radius: 2px;
|
||||
height: 24px;
|
||||
width: 100%;
|
||||
|
||||
&:disabled {
|
||||
user-select: none;
|
||||
@@ -914,14 +1281,8 @@
|
||||
background-image: var(--inheritance-stripes-background);
|
||||
}
|
||||
|
||||
// Invisible placeholder rendered only during a lock drag-toggle gesture, so the drag can still land on rows whose lock icon is normally omitted.
|
||||
// Overlaid with absolute positioning so it doesn't shift the layer name's width.
|
||||
// Invisible placeholder rendered only during a lock drag-toggle gesture, so the drag can still land on rows whose lock icon is normally omitted
|
||||
&.drag-toggle-placeholder {
|
||||
position: absolute;
|
||||
width: 24px;
|
||||
right: 24px;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
opacity: 0; // Not `visibility: hidden`, which would exclude it from hit-testing
|
||||
}
|
||||
|
||||
|
||||
@@ -124,14 +124,18 @@
|
||||
insertMarkerTop = toContentOffset(markerViewportY);
|
||||
}
|
||||
|
||||
function draggingPointerUp() {
|
||||
function draggingPointerUp(e: PointerEvent) {
|
||||
if (dragState?.active) {
|
||||
// Suppress the click that the browser fires after the drag release, so it doesn't toggle the dropped section
|
||||
justFinishedDrag = true;
|
||||
|
||||
// Skip drops that don't actually move the node (into its own slot), or where the dragged section vanished from the DOM mid-drag (fromIndex of -1)
|
||||
if (insertIndex !== undefined && fromIndex !== undefined && fromIndex !== -1 && insertIndex !== fromIndex && insertIndex !== fromIndex + 1) {
|
||||
editor.reorderPropertiesSection(dragState.nodeId, insertIndex);
|
||||
// Holding Alt drops a copy of a layer's chain node at the gap instead of moving the original
|
||||
const duplicate = e.altKey;
|
||||
|
||||
// Skip drops that don't actually move the node (into its own slot, unless copying it), or where the dragged section vanished from the DOM mid-drag (fromIndex of -1)
|
||||
if (insertIndex !== undefined && fromIndex !== undefined && fromIndex !== -1) {
|
||||
const intoOwnSlot = insertIndex === fromIndex || insertIndex === fromIndex + 1;
|
||||
if (duplicate || !intoOwnSlot) editor.reorderPropertiesSection(dragState.nodeId, insertIndex, duplicate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +164,7 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<LayoutCol class="properties">
|
||||
<LayoutCol class="properties" data-properties-panel>
|
||||
<LayoutCol class="sections" classes={{ dragging }} scrollableY={true} bind:this={sectionsCol} on:pointerdown={sectionPointerDown}>
|
||||
<WidgetLayout layout={$propertiesPanelLayout} layoutTarget="PropertiesPanel" />
|
||||
{#if dragging && insertMarkerTop !== undefined}
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<LayoutCol class="content-container">
|
||||
<LayoutCol class="content">
|
||||
<LayoutRow class="logotype">
|
||||
<IconLabel icon="GraphiteLogotypeSolid" />
|
||||
<IconLabel icon="GraphiteLogotype" />
|
||||
</LayoutRow>
|
||||
<LayoutRow class="actions">
|
||||
<WidgetLayout layout={$welcomeScreenButtonsLayout} layoutTarget="WelcomeScreenButtons" />
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import type { DocumentStore } from "/src/stores/document";
|
||||
import type { NodeGraphStore } from "/src/stores/node-graph";
|
||||
@@ -322,15 +323,17 @@
|
||||
{#each $nodeGraphWires.values() as map}
|
||||
{#each map.values() as { pathString, centerPathString, dataType, thick, dashed }}
|
||||
{#if thick}
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="8px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
<!-- A thin inner line splits the layer-stack wire down the middle reaching past the ends into the cleaved connector slots -->
|
||||
<path d={centerPathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={`3,${dashed ? 2 : 0}`} />
|
||||
<g class:dashed>
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="8px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
<!-- A thin inner line splits the layer-stack wire down the middle reaching past the ends into the cleaved connector slots -->
|
||||
<path d={centerPathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={`3,${dashed ? 2 : 0}`} />
|
||||
</g>
|
||||
{/if}
|
||||
{/each}
|
||||
{/each}
|
||||
@@ -689,37 +692,30 @@
|
||||
{#each $nodeGraphWires.values() as map}
|
||||
{#each map.values() as { pathString, dataType, thick, dashed, isList }}
|
||||
{#if !thick}
|
||||
{#if isList}
|
||||
<!-- A rank-1 List wire reads as two parallel lines: a triple-width data line split down the middle by a 1x background-colored overlay -->
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="4px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
<path d={pathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={`3,${dashed ? 2 : 0}`} />
|
||||
{:else}
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="2px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
{/if}
|
||||
<g class:dashed>
|
||||
{#if isList}
|
||||
<!-- A rank-1 List wire reads as two parallel lines: a triple-width data line split down the middle by a 1x background-colored overlay -->
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="4px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
<path d={pathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={`3,${dashed ? 2 : 0}`} />
|
||||
{:else}
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="2px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
{/if}
|
||||
</g>
|
||||
{/if}
|
||||
{/each}
|
||||
{/each}
|
||||
{#if $nodeGraph.wirePathInProgress}
|
||||
<path
|
||||
d={$nodeGraph.wirePathInProgress?.pathString}
|
||||
style:--data-line-width={`${$nodeGraph.wirePathInProgress.thick ? 8 : 2}px`}
|
||||
style:--data-color={`var(--color-data-${$nodeGraph.wirePathInProgress.dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${$nodeGraph.wirePathInProgress.dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${$nodeGraph.wirePathInProgress.dashed ? 2 : 0}`}
|
||||
/>
|
||||
{/if}
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
@@ -730,6 +726,7 @@
|
||||
{@const exposedInputsOutputs = zipWithUndefined(node.exposedInputs, node.exposedOutputs)}
|
||||
{@const clipPathId = String(Math.random()).substring(2)}
|
||||
{@const description = node.reference ? $nodeGraph.nodeDescriptions.get(node.reference) : undefined}
|
||||
{@const icon = (node.reference && $nodeGraph.nodeIcons.get(node.reference)) || "NodeCustomNode"}
|
||||
<div
|
||||
class="node"
|
||||
class:selected={$nodeGraph.selected.includes(node.id)}
|
||||
@@ -748,6 +745,7 @@
|
||||
>
|
||||
<!-- Primary row -->
|
||||
<div class="primary" class:in-selected-network={$nodeGraph.inSelectedNetwork} class:no-secondary-section={exposedInputsOutputs.length === 0}>
|
||||
<IconLabel {icon} />
|
||||
<!-- TODO: Allow the user to edit the name, just like in the Layers panel -->
|
||||
<TextLabel>{node.displayName}</TextLabel>
|
||||
</div>
|
||||
@@ -1049,6 +1047,11 @@
|
||||
stroke-width: var(--data-line-width);
|
||||
stroke-dasharray: var(--data-dasharray);
|
||||
}
|
||||
|
||||
// The previewed node's temporary wire stands out in the bright data color
|
||||
.dashed path {
|
||||
stroke: var(--data-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1210,7 +1213,7 @@
|
||||
}
|
||||
|
||||
&.previewed::after {
|
||||
border: 1px dashed var(--data-color);
|
||||
border: 1px dashed var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
.connectors {
|
||||
@@ -1264,7 +1267,7 @@
|
||||
|
||||
.thumbnail {
|
||||
background: var(--color-2-mildblack);
|
||||
border: 1px solid var(--data-color-dim);
|
||||
border: 1px solid var(--color-5-dullgray);
|
||||
border-radius: 2px;
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
@@ -1331,7 +1334,7 @@
|
||||
field-sizing: content;
|
||||
// Stack above the absolutely-positioned grip/lock/visibility siblings, which can otherwise overlap the input's right edge and hijack clicks there.
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
z-index: 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1379,6 +1382,13 @@
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
// Above layers drawn later whose chain area extends over this layer's right edge, so hovering still reaches them
|
||||
.solo-drag-grip,
|
||||
.lock,
|
||||
.visibility {
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input.connectors .connector {
|
||||
left: 24px;
|
||||
}
|
||||
@@ -1391,7 +1401,7 @@
|
||||
top: calc((var(--offset-top) + 0.5) * 24px);
|
||||
|
||||
&::after {
|
||||
border: 1px solid var(--data-color-dim);
|
||||
border: 1px solid var(--color-5-dullgray);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
@@ -1441,14 +1451,17 @@
|
||||
}
|
||||
|
||||
.icon-label {
|
||||
display: none; // Remove after we have unique icons for the nodes
|
||||
margin: 0 8px;
|
||||
}
|
||||
|
||||
.text-label {
|
||||
// margin-right: 4px; // Restore after reenabling icon-label
|
||||
margin: 0 8px;
|
||||
}
|
||||
|
||||
.icon-label + .text-label {
|
||||
margin-left: 0;
|
||||
margin-right: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.secondary {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from "svelte";
|
||||
import type { NodeGraphStore } from "/src/stores/node-graph";
|
||||
|
||||
const nodeGraph = getContext<NodeGraphStore>("nodeGraph");
|
||||
const nodeGraphTransform = nodeGraph.transformStore;
|
||||
|
||||
// The wire is drawn above every panel so it can reach connectors in the Properties panel, which means mapping graph space onto the window ourselves
|
||||
$: wirePath = $nodeGraph.wirePathInProgress;
|
||||
$: graphBounds = wirePath && document.querySelector("[data-node-graph]")?.getBoundingClientRect();
|
||||
$: offsetX = (graphBounds?.left || 0) + $nodeGraphTransform.x;
|
||||
$: offsetY = (graphBounds?.top || 0) + $nodeGraphTransform.y;
|
||||
</script>
|
||||
|
||||
{#if wirePath && graphBounds}
|
||||
<svg class="wire-in-progress">
|
||||
<path
|
||||
d={wirePath.pathString}
|
||||
transform={`translate(${offsetX} ${offsetY}) scale(${$nodeGraphTransform.scale})`}
|
||||
style:--data-line-width={`${wirePath.thick ? 8 : 2}px`}
|
||||
style:--data-color={`var(--color-data-${wirePath.dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${wirePath.dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${wirePath.dashed ? 2 : 0}`}
|
||||
/>
|
||||
</svg>
|
||||
{/if}
|
||||
|
||||
<style lang="scss">
|
||||
.wire-in-progress {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
overflow: visible;
|
||||
z-index: 1000;
|
||||
|
||||
path {
|
||||
fill: none;
|
||||
stroke: var(--data-color-dim);
|
||||
stroke-width: var(--data-line-width);
|
||||
stroke-dasharray: var(--data-dasharray);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -2,8 +2,11 @@
|
||||
import { getContext } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte";
|
||||
import type { TooltipStore } from "/src/stores/tooltip";
|
||||
import { operatingSystem } from "/src/utility-functions/platform";
|
||||
import type { EditorWrapper, LayoutTarget, WidgetSection as WidgetSectionData } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export let widgetData: WidgetSectionData;
|
||||
@@ -20,19 +23,54 @@
|
||||
$: reorderable = layoutTarget === "PropertiesPanel" && widgetData.draggable;
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
const tooltip = getContext<TooltipStore>("tooltip");
|
||||
|
||||
// Like the Layers panel's expand arrows, a modifier key applies the toggle to the whole chain
|
||||
function toggleExpandedWithModifiers(e: MouseEvent) {
|
||||
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
|
||||
editor.toggleNodePropertiesSectionExpanded(widgetData.id, e.altKey || accel);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- TODO: Implement collapsable sections with properties system -->
|
||||
<LayoutCol class={`widget-section ${className}`.trim()} {classes} data-properties-reorderable-section={reorderable ? "" : undefined} data-node-id={reorderable ? String(widgetData.id) : undefined}>
|
||||
<LayoutCol
|
||||
class={`widget-section ${className}`.trim()}
|
||||
classes={{
|
||||
...classes,
|
||||
"chain-wire": Boolean(widgetData.chainWire),
|
||||
"chain-wire-list": Boolean(widgetData.chainWire?.isList),
|
||||
"output-wire": Boolean(widgetData.outputWire),
|
||||
"output-wire-list": Boolean(widgetData.outputWire?.isList),
|
||||
collapsed: !expanded,
|
||||
}}
|
||||
styles={{
|
||||
"--chain-wire-color": widgetData.chainWire && `var(--color-data-${widgetData.chainWire.dataType.toLowerCase()}-dim)`,
|
||||
"--output-wire-color": widgetData.outputWire && `var(--color-data-${widgetData.outputWire.dataType.toLowerCase()}-dim)`,
|
||||
}}
|
||||
data-properties-reorderable-section={reorderable ? "" : undefined}
|
||||
data-node-id={reorderable ? String(widgetData.id) : undefined}
|
||||
>
|
||||
<button
|
||||
class="header"
|
||||
class:expanded
|
||||
data-tooltip-label={widgetData.name}
|
||||
data-tooltip-description={widgetData.description}
|
||||
data-properties-reorder-handle={reorderable ? "" : undefined}
|
||||
on:click|stopPropagation={() => editor.toggleNodePropertiesSectionExpanded(widgetData.id)}
|
||||
on:click|stopPropagation={toggleExpandedWithModifiers}
|
||||
tabindex="0"
|
||||
>
|
||||
<div class="expand-arrow"></div>
|
||||
<TextLabel tooltipLabel={widgetData.name} tooltipDescription={widgetData.description} bold={true}>{widgetData.name}</TextLabel>
|
||||
<div
|
||||
class="expand-arrow"
|
||||
data-tooltip-label={expanded ? "Collapse (All)" : "Expand (All)"}
|
||||
data-tooltip-description={expanded
|
||||
? "Hide this node's parameters. (To collapse every node in the chain, perform the shortcut shown.)"
|
||||
: "Show this node's parameters. (To expand every node in the chain, perform the shortcut shown.)"}
|
||||
data-tooltip-shortcut={$tooltip.altClickShortcut?.shortcut ? JSON.stringify($tooltip.altClickShortcut.shortcut) : undefined}
|
||||
></div>
|
||||
{#if widgetData.icon}
|
||||
<IconLabel icon={widgetData.icon} />
|
||||
{/if}
|
||||
<TextLabel bold={true}>{widgetData.name}</TextLabel>
|
||||
<IconButton
|
||||
icon={widgetData.pinned ? "PinActive" : "PinInactive"}
|
||||
tooltipDescription={widgetData.pinned ? "Unpin this node so it's no longer shown here when nothing is selected." : "Pin this node so it's shown here when nothing is selected."}
|
||||
@@ -87,6 +125,95 @@
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
// A selected layer's own section, with a wire rising from its chain's sections below into its chain input (the first row)
|
||||
&.chain-wire {
|
||||
--chain-wire-corner-radius: 4px;
|
||||
--chain-wire-width: 2px;
|
||||
--chain-input-indent: 20px;
|
||||
// The wire's centerline rises in line with the expand arrows, then turns into the indented chain input connector
|
||||
--chain-wire-x: 12px;
|
||||
--chain-wire-y: 44px;
|
||||
--chain-wire-end: calc(8px + var(--chain-input-indent));
|
||||
position: relative;
|
||||
|
||||
// Like in the graph, a list's wire is a 1px line, 2px gap, and 1px line
|
||||
&.chain-wire-list {
|
||||
--chain-wire-width: 4px;
|
||||
}
|
||||
|
||||
> .body > .widget-span.row:first-child > .parameter-expose-button:first-child {
|
||||
margin-left: var(--chain-input-indent);
|
||||
|
||||
// Shortened by the indent so the widgets after it stay aligned with other rows
|
||||
+ .text-label {
|
||||
flex-basis: calc(25% - var(--chain-input-indent));
|
||||
}
|
||||
}
|
||||
|
||||
// Without the body showing, the wire from below just meets the header
|
||||
&.collapsed::before,
|
||||
&.collapsed::after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
// Outer and inner 1px lines, which touch as one solid line unless the wire is a list
|
||||
&::before,
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
box-sizing: border-box;
|
||||
bottom: 0;
|
||||
border-left: 1px solid var(--chain-wire-color);
|
||||
border-top: 1px solid var(--chain-wire-color);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&::after {
|
||||
left: calc(var(--chain-wire-x) - var(--chain-wire-width) / 2);
|
||||
top: calc(var(--chain-wire-y) - var(--chain-wire-width) / 2);
|
||||
width: calc(var(--chain-wire-end) - var(--chain-wire-x) + var(--chain-wire-width) / 2);
|
||||
border-top-left-radius: var(--chain-wire-corner-radius);
|
||||
}
|
||||
|
||||
// Inset to stay concentric with the outer line around the corner
|
||||
&::before {
|
||||
left: calc(var(--chain-wire-x) + var(--chain-wire-width) / 2 - 1px);
|
||||
top: calc(var(--chain-wire-y) + var(--chain-wire-width) / 2 - 1px);
|
||||
width: calc(var(--chain-wire-end) - var(--chain-wire-x) - var(--chain-wire-width) / 2 + 1px);
|
||||
border-top-left-radius: max(0px, var(--chain-wire-corner-radius) - var(--chain-wire-width) + 1px);
|
||||
}
|
||||
}
|
||||
|
||||
// A selected layer's chain section, with a wire rising across the gap to the section above, in line with the layer section's wire
|
||||
&.output-wire {
|
||||
--output-wire-width: 2px;
|
||||
position: relative;
|
||||
|
||||
&.output-wire-list {
|
||||
--output-wire-width: 4px;
|
||||
}
|
||||
|
||||
// Two 1px lines, like the layer section's wire
|
||||
&::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
box-sizing: border-box;
|
||||
left: calc(12px - var(--output-wire-width) / 2);
|
||||
top: -4px;
|
||||
width: var(--output-wire-width);
|
||||
height: 4px;
|
||||
border-left: 1px solid var(--output-wire-color);
|
||||
border-right: 1px solid var(--output-wire-color);
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
// A collapsed section keeps its header's bottom margin, which the wire from the section below crosses too
|
||||
&.collapsed + .widget-section.output-wire::before {
|
||||
top: calc(-4px - 4px);
|
||||
height: calc(4px + 4px);
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: left;
|
||||
align-items: center;
|
||||
@@ -140,10 +267,18 @@
|
||||
}
|
||||
}
|
||||
|
||||
> .icon-label {
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// As wide as the name, with the buttons pushed to the end
|
||||
.text-label {
|
||||
height: 18px;
|
||||
margin-left: 8px;
|
||||
flex: 1 1 100%;
|
||||
margin-right: auto;
|
||||
flex: 0 1 auto;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -183,7 +183,7 @@
|
||||
component: ParameterExposeButton,
|
||||
getProps: (props, index) => ({
|
||||
...props,
|
||||
$$events: { selectedEntryValuePath: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, false) },
|
||||
action: () => widgetValueCommitAndUpdate(index, undefined, true),
|
||||
}),
|
||||
},
|
||||
IconButton: {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import type { IconName, IconSize } from "/src/icons";
|
||||
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { ActionShortcut, DragDropKinds } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
// Content
|
||||
export let icon: IconName;
|
||||
@@ -17,9 +17,12 @@
|
||||
export let tooltipShortcut: ActionShortcut | undefined = undefined;
|
||||
// Callbacks
|
||||
export let action: (e?: MouseEvent) => void;
|
||||
// Fired when a draggable item is dropped onto this button. Setting this also flags the button as a valid drop target
|
||||
// (the consumer of the drag interaction looks for `[data-drag-droppable]` and dispatches a `dragdrop` event on it).
|
||||
// Fired when a draggable item, of a kind given by `dragDropKinds`, is dropped onto this button. The button lists those kinds in its
|
||||
// `data-drag-droppable` attribute, where the consumer of the drag interaction looks for them before dispatching a `dragdrop` event on it.
|
||||
export let actionDragDrop: (() => void) | undefined = undefined;
|
||||
export let dragDropKinds: DragDropKinds = "None";
|
||||
|
||||
$: droppableKinds = actionDragDrop ? { None: undefined, Layers: "layers", LayersAndChainNodes: "layers chain-nodes" }[dragDropKinds] : undefined;
|
||||
|
||||
let className = "";
|
||||
export { className as class };
|
||||
@@ -36,27 +39,36 @@
|
||||
}
|
||||
onMount(() => buttonElement?.addEventListener("dragdrop", handleDragDrop));
|
||||
onDestroy(() => buttonElement?.removeEventListener("dragdrop", handleDragDrop));
|
||||
|
||||
// After a pointer click, the new state's icon replaces the hover icon until the pointer leaves and comes back
|
||||
let hoverIconSuppressed = false;
|
||||
$: showsHoverIcon = Boolean(hoverIcon) && !disabled && !hoverIconSuppressed;
|
||||
|
||||
function click(e: MouseEvent) {
|
||||
if (e.detail > 0) hoverIconSuppressed = true;
|
||||
action(e);
|
||||
}
|
||||
</script>
|
||||
|
||||
<button
|
||||
class={`icon-button size-${size} ${className} ${extraClasses}`.trim()}
|
||||
class:hover-icon={hoverIcon && !disabled}
|
||||
class:hover-icon={showsHoverIcon}
|
||||
class:disabled
|
||||
class:emphasized
|
||||
class:drag-droppable={Boolean(actionDragDrop)}
|
||||
bind:this={buttonElement}
|
||||
on:click={action}
|
||||
on:click={click}
|
||||
on:pointerleave={() => (hoverIconSuppressed = false)}
|
||||
{disabled}
|
||||
data-tooltip-label={tooltipLabel}
|
||||
data-tooltip-description={tooltipDescription}
|
||||
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
|
||||
data-drag-droppable={actionDragDrop ? "" : undefined}
|
||||
data-drag-droppable={droppableKinds}
|
||||
data-icon-button
|
||||
tabindex={emphasized ? -1 : 0}
|
||||
{...$$restProps}
|
||||
>
|
||||
<IconLabel {icon} />
|
||||
{#if hoverIcon && !disabled}
|
||||
{#if hoverIcon && showsHoverIcon}
|
||||
<IconLabel icon={hoverIcon} />
|
||||
{/if}
|
||||
</button>
|
||||
@@ -77,7 +89,7 @@
|
||||
fill: var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
// The `where` pseudo-class does not contribtue to specificity
|
||||
// The `where` pseudo-class does not contribute to specificity
|
||||
& + :where(.icon-button) {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
@@ -1,47 +1,54 @@
|
||||
<script lang="ts">
|
||||
import { createEventDispatcher } from "svelte";
|
||||
import MenuList from "/src/components/floating-menus/MenuList.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import type { FrontendGraphDataType, ActionShortcut, MenuListEntry } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const dispatch = createEventDispatcher<{ selectedEntryValuePath: string[] }>();
|
||||
|
||||
let self: MenuList;
|
||||
import { consumeConnectorClickSuppression, hoveredWireDropTarget, pressPropertiesPanelConnector } from "/src/utility-functions/wire-drag";
|
||||
import type { FrontendGraphDataType, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
// Content
|
||||
export let exposed: boolean;
|
||||
export let dataType: FrontendGraphDataType;
|
||||
// Children
|
||||
export let menuListChildren: MenuListEntry[][] = [];
|
||||
export let menuListChildrenHash: bigint = 0n;
|
||||
export let nodeId: bigint;
|
||||
export let inputIndex: number;
|
||||
export let wireDropTarget: boolean;
|
||||
// Tooltips
|
||||
export let tooltipLabel: string | undefined = undefined;
|
||||
export let tooltipDescription: string | undefined = undefined;
|
||||
export let tooltipShortcut: ActionShortcut | undefined = undefined;
|
||||
// Callbacks
|
||||
export let action: (e?: MouseEvent) => void;
|
||||
|
||||
function onClick(e: MouseEvent) {
|
||||
// Focus the target so that keyboard inputs are sent to the dropdown
|
||||
if (e.target instanceof HTMLElement) e.target.focus();
|
||||
$: wireHovering = wireDropTarget && $hoveredWireDropTarget?.nodeId === nodeId && $hoveredWireDropTarget?.inputIndex === inputIndex;
|
||||
|
||||
// Open the menu list floating menu
|
||||
if (self) self.open = true;
|
||||
function click(e: MouseEvent) {
|
||||
// A press that turned into dragging a wire out of this connector shouldn't also toggle its exposure
|
||||
if (consumeConnectorClickSuppression()) return;
|
||||
|
||||
action(e);
|
||||
}
|
||||
</script>
|
||||
|
||||
<LayoutRow class="parameter-expose-button">
|
||||
<button
|
||||
class:exposed
|
||||
class:open={self?.open}
|
||||
class:wire-drop-target={wireDropTarget}
|
||||
class:wire-hovering={wireHovering}
|
||||
style:--data-type-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-type-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
on:click={onClick}
|
||||
on:pointerdown={(e) => pressPropertiesPanelConnector(e, { nodeId, inputIndex })}
|
||||
on:click={click}
|
||||
data-wire-drop-target={wireDropTarget || undefined}
|
||||
data-node-id={String(nodeId)}
|
||||
data-input-index={inputIndex}
|
||||
data-tooltip-label={tooltipLabel}
|
||||
data-tooltip-description={tooltipDescription}
|
||||
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
|
||||
data-floating-menu-spawner
|
||||
tabindex="-1"
|
||||
>
|
||||
{#if !exposed}
|
||||
{#if exposed || wireHovering}
|
||||
<!-- Same shape as an input connector in the node graph -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8">
|
||||
<path class="interior" d="M0,6.306A1.474,1.474,0,0,0,2.356,7.724L7.028,5.248c1.3-.687,1.3-1.809,0-2.5L2.356.276A1.474,1.474,0,0,0,0,1.694Z" />
|
||||
</svg>
|
||||
{:else}
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8">
|
||||
<circle class="interior" r="3" cx="4" cy="4" />
|
||||
<path
|
||||
@@ -49,26 +56,8 @@
|
||||
d="M4,1C5.656,1 7,2.344 7,4C7,5.656 5.656,7 4,7C2.344,7 1,5.656 1,4C1,2.344 2.344,1 4,1ZM4,2C2.896,2 2,2.896 2,4C2,5.104 2.896,6 4,6C5.104,6 6,5.104 6,4C6,2.896 5.104,2 4,2z"
|
||||
/>
|
||||
</svg>
|
||||
{:else}
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8">
|
||||
<path class="interior" d="M0,6.306L0,1.694C0,0.228 1.06,-0.41 2.356,0.276L7.028,2.752C8.324,3.438 8.324,4.562 7.028,5.248L2.356,7.723C1.06,8.41 0,7.771 0,6.306z" />
|
||||
<path
|
||||
class="outline"
|
||||
d="M1.364,8C0.56,8 0,7.372 0,6.306L0,1.694C0,0.228 1.06,-0.41 2.356,0.276L7.028,2.752C8.324,3.439 8.324,4.561 7.028,5.248L2.356,7.724C2.002,7.911 1.666,8 1.364,8ZM1.364,7.2C1.542,7.2 1.756,7.137 1.981,7.017L6.653,4.541C7.031,4.341 7.2,4.125 7.2,4C7.2,3.875 7.031,3.659 6.653,3.459L1.982,0.983C1.756,0.863 1.542,0.8 1.364,0.8C0.873,0.8 0.8,1.36 0.8,1.694L0.8,6.306C0.8,6.64 0.873,7.2 1.364,7.2z"
|
||||
/>
|
||||
</svg>
|
||||
{/if}
|
||||
</button>
|
||||
<MenuList
|
||||
on:selectedEntryValuePath={({ detail }) => dispatch("selectedEntryValuePath", detail)}
|
||||
open={false}
|
||||
entries={menuListChildren}
|
||||
entriesHash={menuListChildrenHash}
|
||||
direction="Bottom"
|
||||
type="Popover"
|
||||
drawIcon={true}
|
||||
bind:this={self}
|
||||
/>
|
||||
</LayoutRow>
|
||||
|
||||
<style lang="scss">
|
||||
@@ -76,10 +65,10 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 0 0 auto;
|
||||
position: relative;
|
||||
max-height: 24px;
|
||||
|
||||
button {
|
||||
position: relative;
|
||||
flex: 0 0 auto;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
@@ -90,6 +79,18 @@
|
||||
fill: none;
|
||||
stroke: none;
|
||||
|
||||
// Enlarges the area for grabbing the connector or dropping a wire onto it, without affecting the row layout
|
||||
&::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: -4px;
|
||||
}
|
||||
|
||||
svg {
|
||||
display: block;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.outline {
|
||||
fill: none;
|
||||
}
|
||||
@@ -98,8 +99,7 @@
|
||||
fill: var(--data-type-color);
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&.open {
|
||||
&:hover:not(.exposed) {
|
||||
.outline {
|
||||
fill: var(--data-type-color);
|
||||
}
|
||||
@@ -108,13 +108,33 @@
|
||||
fill: var(--data-type-color-dim);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Anchor the floating menu's tail to the bottom-center of the small button.
|
||||
// Scoped to the direct child so nested submenu floating menus aren't affected.
|
||||
> :global(.floating-menu) {
|
||||
left: 50%;
|
||||
bottom: 0;
|
||||
&.exposed:hover {
|
||||
.interior {
|
||||
fill: var(--data-type-color-dim);
|
||||
stroke: var(--data-type-color);
|
||||
stroke-width: 1px;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
}
|
||||
|
||||
// Rings each connector that the wire being dragged could be dropped onto
|
||||
&.wire-drop-target::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: -4px;
|
||||
border: 1px solid var(--data-type-color);
|
||||
border-radius: 50%;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
// Previews the connection the dragged wire would make if dropped here
|
||||
&.wire-hovering .interior {
|
||||
fill: var(--data-type-color);
|
||||
stroke: var(--color-f-white);
|
||||
stroke-width: 1px;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import { ICONS, ICON_SVG_STRINGS } from "/src/icons";
|
||||
import { ICONS, ICON_SVG_STRINGS, ICON_16X16_NODES } from "/src/icons";
|
||||
import type { IconName } from "/src/icons";
|
||||
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
@@ -28,12 +28,13 @@
|
||||
if (iconData.size === undefined) return "";
|
||||
return `size-${iconSizeOverride || iconData.size}`;
|
||||
})(icon);
|
||||
$: nodeIconClass = icon in ICON_16X16_NODES ? "node-icon" : "";
|
||||
$: extraClasses = Object.entries(classes)
|
||||
.flatMap(([className, stateName]) => (stateName ? [className] : []))
|
||||
.join(" ");
|
||||
</script>
|
||||
|
||||
<LayoutRow class={`icon-label ${iconSizeClass} ${className} ${extraClasses}`.trim()} classes={{ disabled }} {tooltipLabel} {tooltipDescription} {tooltipShortcut}>
|
||||
<LayoutRow class={`icon-label ${iconSizeClass} ${nodeIconClass} ${className} ${extraClasses}`.trim()} classes={{ disabled }} {tooltipLabel} {tooltipDescription} {tooltipShortcut} {...$$restProps}>
|
||||
{@html ICON_SVG_STRINGS[icon] || "�"}
|
||||
</LayoutRow>
|
||||
|
||||
@@ -60,5 +61,388 @@
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
|
||||
// Node icons color each shape by class, from the palette or a two-color mix of it
|
||||
&.node-icon {
|
||||
.color-7-middlegray {
|
||||
fill: var(--color-7-middlegray);
|
||||
}
|
||||
|
||||
.color-8-uppergray {
|
||||
fill: var(--color-8-uppergray);
|
||||
}
|
||||
|
||||
.color-9-palegray {
|
||||
fill: var(--color-9-palegray);
|
||||
}
|
||||
|
||||
.color-a-softgray {
|
||||
fill: var(--color-a-softgray);
|
||||
}
|
||||
|
||||
.color-artboard {
|
||||
fill: var(--color-data-artboard);
|
||||
}
|
||||
|
||||
.color-c-brightgray {
|
||||
fill: var(--color-c-brightgray);
|
||||
}
|
||||
|
||||
.color-color {
|
||||
fill: var(--color-data-color);
|
||||
}
|
||||
|
||||
.color-color-dim {
|
||||
fill: var(--color-data-color-dim);
|
||||
}
|
||||
|
||||
.color-e-nearwhite {
|
||||
fill: var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
.color-general {
|
||||
fill: var(--color-data-general);
|
||||
}
|
||||
|
||||
.color-general-dim {
|
||||
fill: var(--color-data-general-dim);
|
||||
}
|
||||
|
||||
.color-gradient {
|
||||
fill: var(--color-data-gradient);
|
||||
}
|
||||
|
||||
.color-gradient-dim {
|
||||
fill: var(--color-data-gradient-dim);
|
||||
}
|
||||
|
||||
.color-graphic {
|
||||
fill: var(--color-data-graphic);
|
||||
}
|
||||
|
||||
.color-graphic-dim {
|
||||
fill: var(--color-data-graphic-dim);
|
||||
}
|
||||
|
||||
.color-number {
|
||||
fill: var(--color-data-number);
|
||||
}
|
||||
|
||||
.color-number-dim {
|
||||
fill: var(--color-data-number-dim);
|
||||
}
|
||||
|
||||
.color-raster {
|
||||
fill: var(--color-data-raster);
|
||||
}
|
||||
|
||||
.color-raster-dim {
|
||||
fill: var(--color-data-raster-dim);
|
||||
}
|
||||
|
||||
.color-typography {
|
||||
fill: var(--color-data-typography);
|
||||
}
|
||||
|
||||
.color-typography-dim {
|
||||
fill: var(--color-data-typography-dim);
|
||||
}
|
||||
|
||||
.color-vector {
|
||||
fill: var(--color-data-vector);
|
||||
}
|
||||
|
||||
.color-vector-dim {
|
||||
fill: var(--color-data-vector-dim);
|
||||
}
|
||||
|
||||
.color-mix-7-middlegray-8-uppergray-40 {
|
||||
fill: color-mix(in srgb, var(--color-7-middlegray), var(--color-8-uppergray) 40%);
|
||||
}
|
||||
|
||||
.color-mix-8-uppergray-9-palegray-45 {
|
||||
fill: color-mix(in srgb, var(--color-8-uppergray), var(--color-9-palegray) 45%);
|
||||
}
|
||||
|
||||
.color-mix-8-uppergray-9-palegray-65 {
|
||||
fill: color-mix(in srgb, var(--color-8-uppergray), var(--color-9-palegray) 65%);
|
||||
}
|
||||
|
||||
.color-mix-8-uppergray-9-palegray-70 {
|
||||
fill: color-mix(in srgb, var(--color-8-uppergray), var(--color-9-palegray) 70%);
|
||||
}
|
||||
|
||||
.color-mix-9-palegray-a-softgray-35 {
|
||||
fill: color-mix(in srgb, var(--color-9-palegray), var(--color-a-softgray) 35%);
|
||||
}
|
||||
|
||||
.color-mix-9-palegray-a-softgray-95 {
|
||||
fill: color-mix(in srgb, var(--color-9-palegray), var(--color-a-softgray) 95%);
|
||||
}
|
||||
|
||||
.color-mix-b-lightgray-c-brightgray-25 {
|
||||
fill: color-mix(in srgb, var(--color-b-lightgray), var(--color-c-brightgray) 25%);
|
||||
}
|
||||
|
||||
.color-mix-b-lightgray-c-brightgray-65 {
|
||||
fill: color-mix(in srgb, var(--color-b-lightgray), var(--color-c-brightgray) 65%);
|
||||
}
|
||||
|
||||
.color-mix-c-brightgray-d-mildwhite-35 {
|
||||
fill: color-mix(in srgb, var(--color-c-brightgray), var(--color-d-mildwhite) 35%);
|
||||
}
|
||||
|
||||
.color-mix-c-brightgray-d-mildwhite-55 {
|
||||
fill: color-mix(in srgb, var(--color-c-brightgray), var(--color-d-mildwhite) 55%);
|
||||
}
|
||||
|
||||
.color-mix-color-e-nearwhite-50 {
|
||||
fill: color-mix(in srgb, var(--color-data-color), var(--color-e-nearwhite) 50%);
|
||||
}
|
||||
|
||||
.color-mix-d-mildwhite-e-nearwhite-5 {
|
||||
fill: color-mix(in srgb, var(--color-d-mildwhite), var(--color-e-nearwhite) 5%);
|
||||
}
|
||||
|
||||
.color-mix-general-general-dim-60 {
|
||||
fill: color-mix(in srgb, var(--color-data-general), var(--color-data-general-dim) 60%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-7-middlegray-75 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-7-middlegray) 75%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-dim-0-black-40 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient-dim), var(--color-0-black) 40%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-dim-2-mildblack-35 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient-dim), var(--color-2-mildblack) 35%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-dim-4-dimgray-20 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient-dim), var(--color-4-dimgray) 20%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-dim-8-uppergray-35 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient-dim), var(--color-8-uppergray) 35%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-10 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 10%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-15 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 15%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-20 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 20%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-25 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 25%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-30 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 30%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-35 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 35%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-40 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 40%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-45 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 45%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-5 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 5%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-50 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 50%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-55 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 55%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-60 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 60%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-65 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 65%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-70 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 70%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-75 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 75%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-80 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 80%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-85 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 85%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-90 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 90%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-e-nearwhite-95 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-e-nearwhite) 95%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-10 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 10%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-15 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 15%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-20 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 20%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-25 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 25%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-30 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 30%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-35 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 35%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-40 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 40%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-45 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 45%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-5 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 5%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-50 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 50%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-55 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 55%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-60 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 60%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-65 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 65%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-70 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 70%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-75 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 75%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-80 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 80%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-85 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 85%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-90 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 90%);
|
||||
}
|
||||
|
||||
.color-mix-gradient-gradient-dim-95 {
|
||||
fill: color-mix(in srgb, var(--color-data-gradient), var(--color-data-gradient-dim) 95%);
|
||||
}
|
||||
|
||||
.color-mix-graphic-dim-0-black-30 {
|
||||
fill: color-mix(in srgb, var(--color-data-graphic-dim), var(--color-0-black) 30%);
|
||||
}
|
||||
|
||||
.color-mix-raster-dim-7-middlegray-50 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster-dim), var(--color-7-middlegray) 50%);
|
||||
}
|
||||
|
||||
.color-mix-raster-dim-8-uppergray-40 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster-dim), var(--color-8-uppergray) 40%);
|
||||
}
|
||||
|
||||
.color-mix-raster-dim-8-uppergray-50 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster-dim), var(--color-8-uppergray) 50%);
|
||||
}
|
||||
|
||||
.color-mix-raster-e-nearwhite-15 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-e-nearwhite) 15%);
|
||||
}
|
||||
|
||||
.color-mix-raster-e-nearwhite-35 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-e-nearwhite) 35%);
|
||||
}
|
||||
|
||||
.color-mix-raster-e-nearwhite-40 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-e-nearwhite) 40%);
|
||||
}
|
||||
|
||||
.color-mix-raster-e-nearwhite-50 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-e-nearwhite) 50%);
|
||||
}
|
||||
|
||||
.color-mix-raster-e-nearwhite-65 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-e-nearwhite) 65%);
|
||||
}
|
||||
|
||||
.color-mix-raster-e-nearwhite-85 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-e-nearwhite) 85%);
|
||||
}
|
||||
|
||||
.color-mix-raster-raster-dim-30 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-data-raster-dim) 30%);
|
||||
}
|
||||
|
||||
.color-mix-raster-raster-dim-35 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-data-raster-dim) 35%);
|
||||
}
|
||||
|
||||
.color-mix-raster-raster-dim-50 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-data-raster-dim) 50%);
|
||||
}
|
||||
|
||||
.color-mix-raster-raster-dim-65 {
|
||||
fill: color-mix(in srgb, var(--color-data-raster), var(--color-data-raster-dim) 65%);
|
||||
}
|
||||
|
||||
.color-mix-vector-dim-0-black-30 {
|
||||
fill: color-mix(in srgb, var(--color-data-vector-dim), var(--color-0-black) 30%);
|
||||
}
|
||||
|
||||
.color-mix-vector-vector-dim-50 {
|
||||
fill: color-mix(in srgb, var(--color-data-vector), var(--color-data-vector-dim) 50%);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -4,6 +4,7 @@
|
||||
import Tooltip from "/src/components/floating-menus/Tooltip.svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import WireInProgress from "/src/components/views/WireInProgress.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import PanelSubdivision from "/src/components/window/PanelSubdivision.svelte";
|
||||
import StatusBar from "/src/components/window/StatusBar.svelte";
|
||||
@@ -27,6 +28,7 @@
|
||||
<PanelSubdivision subdivision={$portfolio.panelLayout.root} depth={0} />
|
||||
</LayoutRow>
|
||||
<StatusBar />
|
||||
<WireInProgress />
|
||||
{#if $dialog.visible}
|
||||
<Dialog />
|
||||
{/if}
|
||||
|
||||
+807
-259
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
import { writable } from "svelte/store";
|
||||
import type { Writable } from "svelte/store";
|
||||
import type { IconName } from "/src/icons";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { MessageBody } from "/src/subscriptions-router";
|
||||
import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -19,6 +20,7 @@ type NodeGraphStoreState = {
|
||||
nodes: Map<bigint, FrontendNode>;
|
||||
wirePathInProgress: WirePath | undefined;
|
||||
nodeDescriptions: Map<string, string>;
|
||||
nodeIcons: Map<string, IconName>;
|
||||
nodeTypes: FrontendNodeType[];
|
||||
thumbnails: Map<bigint, string>;
|
||||
selected: bigint[];
|
||||
@@ -37,6 +39,7 @@ const initialState: NodeGraphStoreState = {
|
||||
nodes: new Map(),
|
||||
wirePathInProgress: undefined,
|
||||
nodeDescriptions: new Map(),
|
||||
nodeIcons: new Map(),
|
||||
nodeTypes: [],
|
||||
thumbnails: new Map(),
|
||||
selected: [],
|
||||
@@ -76,6 +79,7 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
subscriptions.subscribeFrontendMessage("SendUIMetadata", (data) => {
|
||||
update((state) => {
|
||||
state.nodeDescriptions = new Map(data.nodeDescriptions);
|
||||
state.nodeIcons = new Map(data.nodeIcons);
|
||||
state.nodeTypes = data.nodeTypes;
|
||||
return state;
|
||||
});
|
||||
|
||||
@@ -38,8 +38,8 @@ export const welcomeScreenButtonsLayout = makeLayoutStore("welcomeScreenButtonsL
|
||||
export const propertiesPanelLayout = makeLayoutStore("propertiesPanelLayout");
|
||||
export const dataPanelLayout = makeLayoutStore("dataPanelLayout");
|
||||
export const layersPanelControlBarLeftLayout = makeLayoutStore("layersPanelControlBarLeftLayout");
|
||||
export const layersPanelControlBarRightLayout = makeLayoutStore("layersPanelControlBarRightLayout");
|
||||
export const layersPanelBottomBarLayout = makeLayoutStore("layersPanelBottomBarLayout");
|
||||
export const layersPanelBottomBarLeftLayout = makeLayoutStore("layersPanelBottomBarLeftLayout");
|
||||
export const layersPanelBottomBarRightLayout = makeLayoutStore("layersPanelBottomBarRightLayout");
|
||||
|
||||
// Each panel layout has its own dedicated store so a layout update only re-renders that panel's consumers.
|
||||
// Putting them at module scope (not inside the component) lets them survive a Svelte remount during a
|
||||
@@ -150,14 +150,14 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
|
||||
patchLayoutStore(layersPanelControlBarLeftLayout, data);
|
||||
});
|
||||
|
||||
subscriptions.subscribeLayoutUpdate("LayersPanelControlRightBar", async (data) => {
|
||||
subscriptions.subscribeLayoutUpdate("LayersPanelBottomLeftBar", async (data) => {
|
||||
await tick();
|
||||
patchLayoutStore(layersPanelControlBarRightLayout, data);
|
||||
patchLayoutStore(layersPanelBottomBarLeftLayout, data);
|
||||
});
|
||||
|
||||
subscriptions.subscribeLayoutUpdate("LayersPanelBottomBar", async (data) => {
|
||||
subscriptions.subscribeLayoutUpdate("LayersPanelBottomRightBar", async (data) => {
|
||||
await tick();
|
||||
patchLayoutStore(layersPanelBottomBarLayout, data);
|
||||
patchLayoutStore(layersPanelBottomBarRightLayout, data);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateDocumentLayerStructure", (data) => {
|
||||
@@ -193,8 +193,8 @@ export function destroyPortfolioStore() {
|
||||
subscriptions.unsubscribeLayoutUpdate("PropertiesPanel");
|
||||
subscriptions.unsubscribeLayoutUpdate("DataPanel");
|
||||
subscriptions.unsubscribeLayoutUpdate("LayersPanelControlLeftBar");
|
||||
subscriptions.unsubscribeLayoutUpdate("LayersPanelControlRightBar");
|
||||
subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomBar");
|
||||
subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomLeftBar");
|
||||
subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomRightBar");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateDocumentLayerStructure");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateDocumentLayerDetails");
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type { PortfolioStore } from "/src/stores/portfolio";
|
||||
import { pasteFile } from "/src/utility-functions/files";
|
||||
import { makeKeyboardModifiersBitfield, textInputCleanup, getLocalizedScanCode } from "/src/utility-functions/keyboard-entry";
|
||||
import { operatingSystem } from "/src/utility-functions/platform";
|
||||
import { wireDragPointerMove, wireDragPointerUp } from "/src/utility-functions/wire-drag";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const BUTTON_LEFT = 0;
|
||||
@@ -121,13 +122,16 @@ export function onPointerMove(e: PointerEvent, editor: EditorWrapper, documentSt
|
||||
|
||||
if (isObserveOnly(e)) return;
|
||||
|
||||
// Wire dragging to and from the Properties panel must be resolved before the editor processes this movement
|
||||
const graphViewOverlayOpen = get(documentStore).graphViewOverlayOpen;
|
||||
if (wireDragPointerMove(e, editor, graphViewOverlayOpen, viewportPointerInteractionOngoing)) viewportPointerInteractionOngoing = true;
|
||||
|
||||
// Don't redirect pointer movement to the backend if there's no ongoing interaction and it's over a floating menu, or the graph overlay, on top of the canvas
|
||||
// TODO: A better approach is to pass along a boolean to the backend's input preprocessor so it can know if it's being occluded by the GUI.
|
||||
// TODO: This would allow it to properly decide to act on removing hover focus from something that was hovered in the canvas before moving over the GUI.
|
||||
// TODO: Further explanation: https://github.com/GraphiteEditor/Graphite/pull/623#discussion_r866436197
|
||||
const inFloatingMenu = e.target instanceof Element && e.target.closest("[data-floating-menu-content]");
|
||||
const inGraphOverlay = get(documentStore).graphViewOverlayOpen;
|
||||
if (!viewportPointerInteractionOngoing && (inFloatingMenu || inGraphOverlay)) return;
|
||||
if (!viewportPointerInteractionOngoing && (inFloatingMenu || graphViewOverlayOpen)) return;
|
||||
|
||||
const modifiers = makeKeyboardModifiersBitfield(e);
|
||||
if (detectShake(e)) editor.onMouseShake(e.clientX, e.clientY, e.buttons, modifiers);
|
||||
@@ -183,6 +187,8 @@ export function onPointerUp(e: PointerEvent, editor: EditorWrapper) {
|
||||
|
||||
if (isObserveOnly(e) || textToolInteractiveInputElement) return;
|
||||
|
||||
wireDragPointerUp(e, editor);
|
||||
|
||||
const modifiers = makeKeyboardModifiersBitfield(e);
|
||||
editor.onMouseUp(e.clientX, e.clientY, e.buttons, modifiers, ...pointerAttributes(e));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { writable } from "svelte/store";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
// Wire dragging between the node graph and the input connectors shown in the Properties panel.
|
||||
// The graph's pointer capture hides hover from the panel's DOM, so the connector under the pointer is found by hit-testing instead.
|
||||
|
||||
export type PropertiesPanelConnector = { nodeId: bigint; inputIndex: number };
|
||||
|
||||
const DRAG_OUT_THRESHOLD = 4;
|
||||
|
||||
// The Properties panel connector that a wire dragged from the graph is hovering, which renders as a connector awaiting the drop
|
||||
export const hoveredWireDropTarget = writable<PropertiesPanelConnector | undefined>(undefined);
|
||||
|
||||
let pressedConnector: (PropertiesPanelConnector & { element: Element; startX: number; startY: number }) | undefined = undefined;
|
||||
let draggingOutOfPropertiesPanel = false;
|
||||
let suppressNextClick = false;
|
||||
|
||||
let reportedHoveringPanel = false;
|
||||
let reportedTarget: PropertiesPanelConnector | undefined = undefined;
|
||||
|
||||
export function pressPropertiesPanelConnector(e: PointerEvent, connector: PropertiesPanelConnector) {
|
||||
if (e.button !== 0 || !(e.currentTarget instanceof Element)) return;
|
||||
|
||||
pressedConnector = { ...connector, element: e.currentTarget, startX: e.clientX, startY: e.clientY };
|
||||
suppressNextClick = false;
|
||||
}
|
||||
|
||||
// Whether the click ending a press should be ignored because the press became a wire drag
|
||||
export function consumeConnectorClickSuppression(): boolean {
|
||||
const suppress = suppressNextClick;
|
||||
suppressNextClick = false;
|
||||
return suppress;
|
||||
}
|
||||
|
||||
// Returns true when this movement begins dragging a wire out of a Properties panel connector, which makes it a pointer interaction the editor must receive
|
||||
export function wireDragPointerMove(e: PointerEvent, editor: EditorWrapper, graphViewOverlayOpen: boolean, interactionOngoing: boolean): boolean {
|
||||
let started = false;
|
||||
|
||||
// Begin dragging out of a pressed connector once the pointer has moved far enough that it's no longer a click
|
||||
if (pressedConnector && !draggingOutOfPropertiesPanel && e.buttons) {
|
||||
const distance = Math.hypot(e.clientX - pressedConnector.startX, e.clientY - pressedConnector.startY);
|
||||
if (distance > DRAG_OUT_THRESHOLD && graphViewOverlayOpen) {
|
||||
const [x, y] = elementCenter(pressedConnector.element);
|
||||
editor.startWireFromPropertiesPanel(pressedConnector.nodeId, pressedConnector.inputIndex, x, y);
|
||||
|
||||
draggingOutOfPropertiesPanel = true;
|
||||
reportedHoveringPanel = true;
|
||||
started = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!graphViewOverlayOpen || !e.buttons || !(interactionOngoing || started)) return started;
|
||||
|
||||
// Find which Properties panel connector, if any, is under the pointer
|
||||
const topmost = document.elementFromPoint(e.clientX, e.clientY);
|
||||
// The whole panel counts, including its tab bar, so crossing the tabs doesn't pan the graph
|
||||
const hoveringPanel = Boolean(topmost?.closest("[data-panel-body]")?.querySelector("[data-properties-panel]"));
|
||||
const targetElement = topmost?.closest("[data-wire-drop-target]") || undefined;
|
||||
const target = targetElement && connectorFromElement(targetElement);
|
||||
|
||||
if (hoveringPanel) {
|
||||
const dropTargets = Array.from(document.querySelectorAll("[data-wire-drop-target]")).map((element) => ({ element, bounds: element.getBoundingClientRect() }));
|
||||
// eslint-disable-next-line no-console
|
||||
console.debug("[wire-drag] Hit test", { pointer: [e.clientX, e.clientY], topmost, elementsAtPoint: document.elementsFromPoint(e.clientX, e.clientY), dropTargets });
|
||||
}
|
||||
|
||||
const targetChanged = target?.nodeId !== reportedTarget?.nodeId || target?.inputIndex !== reportedTarget?.inputIndex;
|
||||
if (hoveringPanel === reportedHoveringPanel && !targetChanged) return started;
|
||||
|
||||
reportedHoveringPanel = hoveringPanel;
|
||||
reportedTarget = target;
|
||||
hoveredWireDropTarget.set(target);
|
||||
|
||||
const [x, y] = targetElement ? elementCenter(targetElement) : [0, 0];
|
||||
// eslint-disable-next-line no-console
|
||||
console.debug("[wire-drag] Reporting hover", { hoveringPanel, target, topmost, dropTargetsInDocument: document.querySelectorAll("[data-wire-drop-target]").length });
|
||||
editor.setWirePropertiesPanelHover(hoveringPanel, target?.nodeId, target?.inputIndex ?? 0, x, y);
|
||||
|
||||
return started;
|
||||
}
|
||||
|
||||
export function wireDragPointerUp(e: PointerEvent, editor: EditorWrapper) {
|
||||
if (e.buttons) return;
|
||||
|
||||
// The editor never saw the pointer go down in the Properties panel, so it needs to be told about the release
|
||||
if (draggingOutOfPropertiesPanel) {
|
||||
editor.releaseWireFromPropertiesPanel();
|
||||
suppressNextClick = true;
|
||||
}
|
||||
|
||||
pressedConnector = undefined;
|
||||
draggingOutOfPropertiesPanel = false;
|
||||
reportedHoveringPanel = false;
|
||||
reportedTarget = undefined;
|
||||
hoveredWireDropTarget.set(undefined);
|
||||
}
|
||||
|
||||
function connectorFromElement(element: Element): PropertiesPanelConnector | undefined {
|
||||
const nodeId = element.getAttribute("data-node-id") || undefined;
|
||||
const inputIndex = element.getAttribute("data-input-index") || undefined;
|
||||
if (nodeId === undefined || inputIndex === undefined) return undefined;
|
||||
|
||||
return { nodeId: BigInt(nodeId), inputIndex: Number(inputIndex) };
|
||||
}
|
||||
|
||||
function elementCenter(element: Element): [number, number] {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
return [bounds.left + bounds.width / 2, bounds.top + bounds.height / 2];
|
||||
}
|
||||
@@ -19,7 +19,7 @@ mod editor_commands {
|
||||
use editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
|
||||
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
|
||||
use editor::messages::portfolio::document::utility_types::network_interface::{ImportOrExport, InputConnector};
|
||||
use editor::messages::portfolio::utility_types::PanelGroupId;
|
||||
use editor::messages::prelude::*;
|
||||
use editor::messages::tool::tool_messages::tool_prelude::{DroppedFile, WidgetId};
|
||||
@@ -521,6 +521,35 @@ mod editor_commands {
|
||||
DocumentMessage::SelectLayer { id: NodeId(id), ctrl, shift }.into()
|
||||
}
|
||||
|
||||
/// Outline in the viewport the layer under the pointer in the Layers panel, or nothing once the pointer leaves it.
|
||||
fn set_layers_panel_hovered_layer(id: Option<u64>) -> Message {
|
||||
DocumentMessage::SetLayersPanelHoveredLayer { id: id.map(NodeId) }.into()
|
||||
}
|
||||
|
||||
/// Select exactly the given nodes.
|
||||
fn select_nodes(ids: Vec<u64>) -> Message {
|
||||
NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: ids.into_iter().map(NodeId).collect(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Select a node in the document network and open the node graph centered on it.
|
||||
fn show_node_in_graph(node_id: u64) -> Message {
|
||||
DocumentMessage::ShowNodeInGraph { node_id: NodeId(node_id) }.into()
|
||||
}
|
||||
|
||||
/// Modify the selection based on the node clicked in the chain feeding a layer, with the same <kbd>Ctrl</kbd> and <kbd>Shift</kbd> behavior as selecting layers.
|
||||
fn select_chain_node(layer: u64, node_id: u64, ctrl: bool, shift: bool) -> Message {
|
||||
DocumentMessage::SelectChainNode {
|
||||
layer: NodeId(layer),
|
||||
node_id: NodeId(node_id),
|
||||
ctrl,
|
||||
shift,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Deselect all layers
|
||||
fn deselect_all_layers() -> Message {
|
||||
DocumentMessage::DeselectAllLayers.into()
|
||||
@@ -540,11 +569,33 @@ mod editor_commands {
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Reorder a draggable Properties panel section to the given index among its peers.
|
||||
fn reorder_properties_section(node_id: u64, insert_index: usize) -> Message {
|
||||
/// Move nodes together into a layer's chain (their own or another) at the given gap among its reorderable nodes, where gap 0 is beside the layer.
|
||||
fn move_chain_nodes(node_ids: Vec<u64>, layer: u64, insert_index: usize) -> Message {
|
||||
DocumentMessage::MoveChainNodes {
|
||||
node_ids: node_ids.into_iter().map(NodeId).collect(),
|
||||
layer: NodeId(layer),
|
||||
insert_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Insert and select copies of nodes together in a layer's chain (their own or another) at the given gap among its reorderable nodes, where gap 0 is beside the layer.
|
||||
fn duplicate_chain_nodes(node_ids: Vec<u64>, layer: u64, insert_index: usize) -> Message {
|
||||
DocumentMessage::DuplicateChainNodes {
|
||||
node_ids: node_ids.into_iter().map(NodeId).collect(),
|
||||
layer: NodeId(layer),
|
||||
insert_index,
|
||||
select_copies: true,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Reorder a draggable Properties panel section to the given index among its peers, or for a layer's chain node, insert a copy there instead.
|
||||
fn reorder_properties_section(node_id: u64, insert_index: usize, duplicate: bool) -> Message {
|
||||
DocumentMessage::ReorderPropertiesSection {
|
||||
node_id: NodeId(node_id),
|
||||
insert_index,
|
||||
duplicate,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -613,6 +664,26 @@ mod editor_commands {
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Begin dragging a wire out of a Properties panel input connector, anchored at its center
|
||||
fn start_wire_from_properties_panel(node_id: u64, input_index: usize, x: f64, y: f64) -> Message {
|
||||
NodeGraphMessage::StartWireFromPropertiesPanel {
|
||||
input_connector: InputConnector::node_at_index(NodeId(node_id), input_index),
|
||||
editor_position: (x, y).into(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Release a wire dragged out of the Properties panel, whose pointer down never reached the editor
|
||||
fn release_wire_from_properties_panel() -> Message {
|
||||
NodeGraphMessage::PointerUp.into()
|
||||
}
|
||||
|
||||
/// Report whether the wire in progress is over the Properties panel, and which input connector there it hovers (centered at `x`, `y`)
|
||||
fn set_wire_properties_panel_hover(hovering_panel: bool, target_node_id: Option<u64>, target_input_index: usize, x: f64, y: f64) -> Message {
|
||||
let target = target_node_id.map(|node_id| (InputConnector::node_at_index(NodeId(node_id), target_input_index), (x, y).into()));
|
||||
NodeGraphMessage::SetWirePropertiesPanelHover { hovering_panel, target }.into()
|
||||
}
|
||||
|
||||
/// Respond to selection read
|
||||
fn read_selection(content: Option<String>, cut: bool) -> Message {
|
||||
ClipboardMessage::ReadSelection { content, cut }.into()
|
||||
@@ -675,9 +746,9 @@ mod editor_commands {
|
||||
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
|
||||
}
|
||||
|
||||
/// Collapse or expand a node's section in the Properties panel
|
||||
fn toggle_node_properties_section_expanded(id: u64) -> Message {
|
||||
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) }.into()
|
||||
/// Collapse or expand a node's section in the Properties panel, or recursively every section in its layer's chain
|
||||
fn toggle_node_properties_section_expanded(id: u64, recursive: bool) -> Message {
|
||||
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id), recursive }.into()
|
||||
}
|
||||
|
||||
/// Delete a layer or node given its node ID
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::sync::{LazyLock, Mutex};
|
||||
pub struct NodeMetadata {
|
||||
pub display_name: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub fields: Vec<FieldMetadata>,
|
||||
pub description: &'static str,
|
||||
pub properties: Option<&'static str>,
|
||||
|
||||
@@ -42,6 +42,12 @@ unsafe impl<C: dyn_any::StaticTypeSized> dyn_any::StaticType for GradientStops<C
|
||||
type Static = GradientStops<C::Static>;
|
||||
}
|
||||
|
||||
impl<C> GradientStops<C> {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.color.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Gradient> for GradientStops<Color> {
|
||||
fn from(gradient: &Gradient) -> Self {
|
||||
Self {
|
||||
|
||||
@@ -705,6 +705,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let import_name = format_ident!("_IMPORT_STUB_{}", mod_name.to_string().to_case(Case::UpperSnake));
|
||||
|
||||
let properties = &attributes.properties_string.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None));
|
||||
let icon = &attributes.icon.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None));
|
||||
let memoize_flag = attributes.memoize;
|
||||
let inject_scope_flag = attributes.inject_scope;
|
||||
// A node returning a `Destructure` struct records its fields as output connectors
|
||||
@@ -927,6 +928,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let metadata = NodeMetadata {
|
||||
display_name: #display_name,
|
||||
category: #category,
|
||||
icon: #icon,
|
||||
description: #description,
|
||||
properties: #properties,
|
||||
context_features: vec![#(ContextFeature::#context_features,)*],
|
||||
|
||||
@@ -45,6 +45,7 @@ pub(crate) struct ParsedNodeFn {
|
||||
pub(crate) struct NodeFnAttributes {
|
||||
pub(crate) category: Option<LitStr>,
|
||||
pub(crate) display_name: Option<LitStr>,
|
||||
pub(crate) icon: Option<LitStr>,
|
||||
pub(crate) path: Option<Path>,
|
||||
pub(crate) skip_impl: bool,
|
||||
pub(crate) properties_string: Option<LitStr>,
|
||||
@@ -407,6 +408,7 @@ impl Parse for NodeFnAttributes {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let mut category = None;
|
||||
let mut display_name = None;
|
||||
let mut icon = None;
|
||||
let mut path = None;
|
||||
let mut skip_impl = false;
|
||||
let mut properties_string = None;
|
||||
@@ -451,6 +453,18 @@ impl Parse for NodeFnAttributes {
|
||||
let parsed_name: LitStr = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a string for 'name', e.g., name(\"Memoize\")"))?;
|
||||
display_name = Some(parsed_name);
|
||||
}
|
||||
// Name of the icon, from the frontend's icon registry, shown for this node in the node graph.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., icon("NodeCircle"), ...)]
|
||||
"icon" => {
|
||||
let meta = meta.require_list()?;
|
||||
if icon.is_some() {
|
||||
return Err(Error::new_spanned(meta, "Multiple 'icon' attributes are not allowed"));
|
||||
}
|
||||
let parsed_icon: LitStr = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a string for 'icon', e.g., icon(\"NodeCircle\")"))?;
|
||||
icon = Some(parsed_icon);
|
||||
}
|
||||
// Override for the fully qualified path used by Graphene to identify the node implementation.
|
||||
// If not provided, the path will be inferred from the module path and function name.
|
||||
// Use this if the node implementation has moved to a different module or crate but a migration to that new path is not desired.
|
||||
@@ -563,7 +577,7 @@ impl Parse for NodeFnAttributes {
|
||||
indoc!(
|
||||
r#"
|
||||
Unsupported attribute in `node`.
|
||||
Supported attributes are 'category', 'name', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', and 'inject_scope'.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', and 'inject_scope'.
|
||||
Example usage:
|
||||
#[node_macro::node(..., name("Test Node"), ...)]
|
||||
"#
|
||||
@@ -589,6 +603,7 @@ impl Parse for NodeFnAttributes {
|
||||
Ok(NodeFnAttributes {
|
||||
category,
|
||||
display_name,
|
||||
icon,
|
||||
path,
|
||||
skip_impl,
|
||||
properties_string,
|
||||
@@ -1278,6 +1293,7 @@ mod tests {
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Math: Arithmetic")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: Some(parse_quote!(core_types::TestNode)),
|
||||
skip_impl: true,
|
||||
properties_string: None,
|
||||
@@ -1353,6 +1369,7 @@ mod tests {
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("General")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
properties_string: None,
|
||||
@@ -1445,6 +1462,7 @@ mod tests {
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Vector: Shape")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
properties_string: None,
|
||||
@@ -1516,6 +1534,7 @@ mod tests {
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Raster: Adjustment")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
properties_string: None,
|
||||
@@ -1599,6 +1618,7 @@ mod tests {
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Math: Arithmetic")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: Some(parse_quote!(core_types::TestNode)),
|
||||
skip_impl: false,
|
||||
properties_string: None,
|
||||
@@ -1685,6 +1705,7 @@ mod tests {
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("IO")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
properties_string: None,
|
||||
@@ -1756,6 +1777,7 @@ mod tests {
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Custom")),
|
||||
display_name: Some(parse_quote!("CustomNode2")),
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
properties_string: None,
|
||||
|
||||
@@ -6,7 +6,7 @@ use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
|
||||
#[node_macro::node(category("Blending"))]
|
||||
#[node_macro::node(category("Blending"), icon("NodeBlendMode"))]
|
||||
fn blend_mode<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
@@ -25,7 +25,7 @@ fn blend_mode<T>(
|
||||
/// Modifies the opacity and/or fill of the input graphics by multiplying the existing values by these percentages.
|
||||
/// Opacity affects the transparency of the content (together with anything above which is clipped to it).
|
||||
/// Fill affects the transparency of the content itself, independent of any content clipped to it.
|
||||
#[node_macro::node(category("Blending"))]
|
||||
#[node_macro::node(category("Blending"), icon("NodeOpacity"))]
|
||||
fn opacity<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
@@ -72,7 +72,7 @@ fn opacity<T>(
|
||||
}
|
||||
|
||||
/// Sets whether the input graphics inherit the alpha of the content beneath them, "clipping" them to that content.
|
||||
#[node_macro::node(category("Blending"))]
|
||||
#[node_macro::node(category("Blending"), icon("NodeClippingMask"))]
|
||||
fn clipping_mask<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
|
||||
@@ -14,7 +14,7 @@ use pipeline::{BasicBrushPipeline, BasicBrushPipelineArgs};
|
||||
use raster_types::{GPU, Raster};
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category("Raster: Brush"))]
|
||||
#[node_macro::node(category("Raster: Brush"), icon("NodeBasicBrush"))]
|
||||
pub async fn basic_brush<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractFootprint,
|
||||
strokes: List<Graphic>,
|
||||
|
||||
@@ -12,7 +12,7 @@ pub(crate) const DEFAULT_HARDNESS: f64 = 0.;
|
||||
pub(crate) const DEFAULT_FLOW: f64 = 100.;
|
||||
pub(crate) const DEFAULT_COLOR: Color = Color::BLACK;
|
||||
|
||||
#[node_macro::node(category("Raster: Brush"))]
|
||||
#[node_macro::node(category("Raster: Brush"), icon("NodeBrushStrokes"))]
|
||||
fn brush_strokes(
|
||||
_: impl Ctx,
|
||||
strokes: List<Stroke>,
|
||||
|
||||
@@ -30,14 +30,14 @@ pub enum AnimationTimeMode {
|
||||
|
||||
/// Evaluate the value of an animation curve
|
||||
#[node_macro::node(category("Animation"))]
|
||||
fn eval_curve(ctx: impl Ctx + ExtractAnimationTime, _primary: (), curve: Item<AnimationCurve>) -> Item<f64> {
|
||||
fn evaluate_curve(ctx: impl Ctx + ExtractAnimationTime, _primary: (), curve: Item<AnimationCurve>) -> Item<f64> {
|
||||
let curve = curve.into_element();
|
||||
let time = ctx.try_animation_time().unwrap_or_default();
|
||||
Item::new_from_element(curve.evaluate(time))
|
||||
}
|
||||
|
||||
/// Produces a chosen representation of the current real time and date (in UTC) based on the system clock.
|
||||
#[node_macro::node(category("Animation"))]
|
||||
#[node_macro::node(category("Animation"), icon("NodeRealTime"))]
|
||||
fn real_time(
|
||||
ctx: impl Ctx + ExtractRealTime,
|
||||
_primary: (),
|
||||
@@ -61,7 +61,7 @@ fn real_time(
|
||||
}
|
||||
|
||||
/// Produces the time, in seconds on the timeline, since the beginning of animation playback.
|
||||
#[node_macro::node(category("Animation"))]
|
||||
#[node_macro::node(category("Animation"), icon("NodeAnimationTime"))]
|
||||
fn animation_time(
|
||||
ctx: impl Ctx + ExtractAnimationTime,
|
||||
_primary: (),
|
||||
@@ -72,7 +72,7 @@ fn animation_time(
|
||||
Item::new_from_element(ctx.try_animation_time().unwrap_or_default() * *rate.element())
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
#[node_macro::node(category("Debug"), icon("NodeQuantizeRealTime"))]
|
||||
async fn quantize_real_time<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs,
|
||||
#[implementations(
|
||||
@@ -118,7 +118,7 @@ async fn quantize_real_time<T>(
|
||||
value.eval(Some(new_context.into())).await
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
#[node_macro::node(category("Debug"), icon("NodeQuantizeAnimationTime"))]
|
||||
async fn quantize_animation_time<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs,
|
||||
#[implementations(
|
||||
@@ -163,17 +163,7 @@ async fn quantize_animation_time<T>(
|
||||
}
|
||||
|
||||
/// Produces the current position of the user's pointer within the document canvas.
|
||||
#[node_macro::node(category("Animation"))]
|
||||
#[node_macro::node(category("Animation"), icon("NodePointerPosition"))]
|
||||
fn pointer_position(ctx: impl Ctx + ExtractPointerPosition) -> Item<DVec2> {
|
||||
Item::new_from_element(ctx.try_pointer_position().unwrap_or_default())
|
||||
}
|
||||
|
||||
// TODO: These nodes require more sophisticated algorithms for giving the correct result
|
||||
// #[node_macro::node(category("Animation"))]
|
||||
// fn month(ctx: impl Ctx + ExtractRealTime) -> f64 {
|
||||
// ((ctx.try_real_time().unwrap_or_default() / DAY / 365.25 % 1.) * 12.).floor()
|
||||
// }
|
||||
// #[node_macro::node(category("Animation"))]
|
||||
// fn day(ctx: impl Ctx + ExtractRealTime) -> f64 {
|
||||
// (ctx.try_real_time().unwrap_or_default() / DAY
|
||||
// }
|
||||
@@ -6,7 +6,7 @@ use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
#[node_macro::node(category("Context"), icon("NodeReadContext"), path(graphene_core::vector))]
|
||||
fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> Item<Graphic> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
@@ -14,7 +14,7 @@ fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> Item<Graphic> {
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
#[node_macro::node(category("Context"), icon("NodeReadContext"), path(graphene_core::vector))]
|
||||
fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> Item<Vector> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
@@ -22,7 +22,7 @@ fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> Item<Vector> {
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
#[node_macro::node(category("Context"), icon("NodeReadContext"), path(graphene_core::vector))]
|
||||
fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> Item<Raster<CPU>> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
@@ -30,7 +30,7 @@ fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> Item<Raster<CPU>> {
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
#[node_macro::node(category("Context"), icon("NodeReadContext"), path(graphene_core::vector))]
|
||||
fn read_color(ctx: impl Ctx + ExtractVarArgs) -> Item<Color> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
@@ -38,7 +38,7 @@ fn read_color(ctx: impl Ctx + ExtractVarArgs) -> Item<Color> {
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
#[node_macro::node(category("Context"), icon("NodeReadContext"), path(graphene_core::vector))]
|
||||
fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> Item<Gradient> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
@@ -47,7 +47,7 @@ fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> Item<Gradient> {
|
||||
}
|
||||
|
||||
/// Reads the current number from within a **Map** node's loop.
|
||||
#[node_macro::node(category("Context"))]
|
||||
#[node_macro::node(category("Context"), icon("NodeReadContext"))]
|
||||
fn read_number(ctx: impl Ctx + ExtractVarArgs) -> Item<f64> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
@@ -65,7 +65,7 @@ fn read_number(ctx: impl Ctx + ExtractVarArgs) -> Item<f64> {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
#[node_macro::node(category("Context"), icon("NodeReadPosition"), path(core_types::vector))]
|
||||
async fn read_position(
|
||||
ctx: impl Ctx + ExtractPosition,
|
||||
_primary: (),
|
||||
@@ -84,7 +84,7 @@ async fn read_position(
|
||||
/// Produces the index of the current iteration of a loop by reading from the evaluation context, which is supplied by downstream nodes such as *Repeat*.
|
||||
///
|
||||
/// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops.
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
#[node_macro::node(category("Context"), icon("NodeReadIndex"), path(core_types::vector))]
|
||||
async fn read_index(
|
||||
ctx: impl Ctx + ExtractIndex,
|
||||
_primary: (),
|
||||
|
||||
@@ -3,7 +3,7 @@ use core_types::list::Item;
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
/// Meant for debugging purposes, not general use. Logs the input value to the console and passes it through unchanged.
|
||||
#[node_macro::node(category("Debug"), name("Log to Console"))]
|
||||
#[node_macro::node(category("Debug"), icon("NodeLogToConsole"), name("Log to Console"))]
|
||||
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, i64, DVec2, DAffine2, String)] value: Item<T>) -> Item<T> {
|
||||
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
|
||||
log::debug!("{value:#?}");
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::sync::Mutex;
|
||||
/// Helps speed up repeated renders in a computationally-heavy part of the node graph.
|
||||
///
|
||||
/// Stores the last evaluated data that flowed through this node and immediately returns that data on subsequent renders if the context has not changed.
|
||||
#[node_macro::node(category("General"), path(graphene_core::memo), skip_impl)]
|
||||
#[node_macro::node(category("General"), icon("NodeMemoize"), path(graphene_core::memo), skip_impl)]
|
||||
async fn memoize<I: CacheHash + Send + 'n, T: Clone + WasmNotSend>(input: I, content: impl Node<I, Output = T>, #[data] cache: Arc<Mutex<Option<(u64, T)>>>) -> T {
|
||||
// Caches the output of a given node called with a specific input.
|
||||
//
|
||||
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user